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
/*
 * Copyright (c) Radzivon Bartoshyk 6/2026. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3.  Neither the name of the copyright holder nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use super::*;
use crate::cdf::{CdfModeContext, CdfMvContext};
use crate::ctx::memset_pow2;
use crate::decode_partition::decode_partition;
use crate::env::BlockContext;

use crate::internal::Pass;
use crate::intops::{imax, imin};
use crate::intra::{intra_bottom_left_units, intra_top_right_units};
use crate::levels::{Av2Block, BlockPartition, BlockSize, CFL_PRED, TxPartition};

use crate::msac::MsacReader;

use crate::pixel::Pixel;

use crate::tables::{BLOCK_DIMENSIONS, TXFM_DIMENSIONS};

#[allow(clippy::too_many_arguments)]
pub(crate) fn recon_b_intra_luma_phase<
    BD: BitDepth,
    const UPDATE_CDF: bool,
    M: MsacReader<UPDATE_CDF>,
>(
    rb: &mut ReconBCtx<'_, '_, '_, BD, UPDATE_CDF, M>,
    bx: i32,
    by: i32,
    _bx4: usize,
    _by4: usize,
    _intrabc: bool,
    phase: TxPhase,
) -> Result<(), ()>
where
    BD::Coef: DecodeCoeff,
{
    let recon = &mut *rb.recon;
    let msac = &mut *rb.msac;
    let cdf_m = &mut *rb.cdf_m;
    let a = &mut *rb.a;
    let l = &mut *rb.l;
    let b = rb.b;
    let fi = rb.fi;
    recon_b_intra_luma_geom_phase(
        &mut ReconBCtx {
            recon: &mut *recon,
            msac: &mut *msac,
            cdf_m: &mut *cdf_m,
            a: &mut *a,
            l: &mut *l,
            b,
            fi,
        },
        bx,
        by,
        (bx, by),
        b.bs as usize,
        phase,
    )
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn recon_b_intra_luma_geom_phase<
    BD: BitDepth,
    const UPDATE_CDF: bool,
    M: MsacReader<UPDATE_CDF>,
>(
    rb: &mut ReconBCtx<'_, '_, '_, BD, UPDATE_CDF, M>,
    bx: i32,
    by: i32,
    blk_origin: (i32, i32),
    geom_bs: usize,
    phase: TxPhase,
) -> Result<(), ()>
where
    BD::Coef: DecodeCoeff,
{
    let recon = &mut *rb.recon;
    let msac = &mut *rb.msac;
    let cdf_m = &mut *rb.cdf_m;
    let a = &mut *rb.a;
    let l = &mut *rb.l;
    let b = rb.b;
    let fi = rb.fi;
    let bs = geom_bs;
    let seg_id = b.seg_id as usize;
    let lossless = recon.frame.seg_lossless[seg_id] != 0;

    let tp = &crate::tables::TX_PART_TBL[bs];

    // pb.col_start / pb.row_start are the coding block's origin (used by
    // is_hv5 and the intra edge availability), not the 64x64 sub-block's.
    let (pb_col_start, pb_row_start) = blk_origin;

    if phase != TxPhase::ReadOnly && b.is_intra != 0 && b.intrabc == 0 && b.intra_data().pal_sz != 0
    {
        let bw = BLOCK_DIMENSIONS[bs][0] as usize * 4;
        let bh = BLOCK_DIMENSIONS[bs][1] as usize * 4;
        let stride = recon.frame.y_stride_px;
        let dst_off = 4 * (by as usize * stride + bx as usize);
        let pal: [BD::Pixel; 8] =
            std::array::from_fn(|i| BD::Pixel::from_i32(recon.scratch.pal[i] as i32));
        if BD::BPC == 8 {
            let dst8 = BD::Pixel::slice_as_ne_bytes_mut(&mut recon.dst_y);
            let pal8 = BD::Pixel::slice_as_ne_bytes(&pal);
            unsafe {
                (recon.frame.exec.pal_pred_8bpc)(
                    &mut dst8[dst_off..],
                    stride,
                    pal8,
                    &recon.scratch.pal_idx_y[..],
                    bw,
                    bh,
                );
            }
        } else {
            let dst16 = BD::Pixel::try_as_u16_slice_mut(&mut recon.dst_y)
                .expect("HBD palette prediction requires u16 storage");
            let pal16 = BD::Pixel::try_as_u16_slice(&pal)
                .expect("HBD palette prediction requires a u16 palette");
            unsafe {
                (recon.frame.exec.pal_pred_hbd)(
                    &mut dst16[dst_off..],
                    stride,
                    pal16,
                    &recon.scratch.pal_idx_y[..],
                    bw,
                    bh,
                );
            }
        }
    }

    if lossless {
        let tx = if b.tx_size_ll != 0 {
            crate::tables::MAX_TXFM_SIZE_FOR_BS[bs][3] as usize
        } else {
            0 // TX_4X4
        };
        let t_dim = &TXFM_DIMENSIONS[tx];
        let tw4 = t_dim.w as i32;
        let th4 = t_dim.h as i32;
        let h4 = imin(BLOCK_DIMENSIONS[bs][1] as i32, fi.bh - by);
        let w4 = imin(BLOCK_DIMENSIONS[bs][0] as i32, fi.bw - bx);
        let mut y = 0;
        while y < h4 {
            let mut x = 0;
            while x < w4 {
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    bx + x,
                    by + y,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
                x += tw4;
            }
            y += th4;
        }
        return Ok(());
    }

    let tx_part = b.tx_part as usize;
    let tx = tp[tx_part] as usize;

    match TxPartition::from_raw(b.tx_part) {
        TxPartition::None => {
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
        }
        TxPartition::Split => {
            let t_dim = &TXFM_DIMENSIONS[tx];
            let tw4 = t_dim.w as i32;
            let th4 = t_dim.h as i32;
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            let have_v_split = bx + tw4 < fi.bw;
            if have_v_split {
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    bx + tw4,
                    by,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
            }
            if by + th4 >= fi.bh {
                return Ok(());
            }
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                by + th4,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            if have_v_split {
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    bx + tw4,
                    by + th4,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
            }
        }
        TxPartition::H => {
            let th4 = TXFM_DIMENSIONS[tx].h as i32;
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            if by + th4 >= fi.bh {
                return Ok(());
            }
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                by + th4,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
        }
        TxPartition::V => {
            let tw4 = TXFM_DIMENSIONS[tx].w as i32;
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            if bx + tw4 >= fi.bw {
                return Ok(());
            }
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx + tw4,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
        }
        TxPartition::H4 => {
            // started if the previous one did not reach the frame's bottom edge.
            let th4 = TXFM_DIMENSIONS[tx].h as i32;
            for i in 0..4 {
                let yy = by + i * th4;
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    bx,
                    yy,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
                if yy + th4 >= fi.bh {
                    break;
                }
            }
        }
        TxPartition::V4 => {
            let tw4 = TXFM_DIMENSIONS[tx].w as i32;
            for i in 0..4 {
                let xx = bx + i * tw4;
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    xx,
                    by,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
                if xx + tw4 >= fi.bw {
                    break;
                }
            }
        }
        TxPartition::H5 => {
            let tx_big = tp[TxPartition::H as usize] as usize;
            let t_dim_small = &TXFM_DIMENSIONS[tx];
            let tw4_small = t_dim_small.w as i32;
            let th4_small = t_dim_small.h as i32;
            let th4_big = TXFM_DIMENSIONS[tx_big].h as i32;
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            let have_v_split = bx + tw4_small < fi.bw;
            if have_v_split {
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    bx + tw4_small,
                    by,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
            }
            if by + th4_small >= fi.bh {
                return Ok(());
            }
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx_big,
                bx,
                by + th4_small,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            if by + th4_small + th4_big >= fi.bh {
                return Ok(());
            }
            let yb = by + th4_small + th4_big;
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                yb,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            if have_v_split {
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    bx + tw4_small,
                    yb,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
            }
        }
        TxPartition::V5 => {
            let tx_big = tp[TxPartition::V as usize] as usize;
            let t_dim_small = &TXFM_DIMENSIONS[tx];
            let tw4_small = t_dim_small.w as i32;
            let th4_small = t_dim_small.h as i32;
            let tw4_big = TXFM_DIMENSIONS[tx_big].w as i32;
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                bx,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            let have_h_split = by + th4_small < fi.bh;
            if have_h_split {
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    bx,
                    by + th4_small,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
            }
            if bx + tw4_small >= fi.bw {
                return Ok(());
            }
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx_big,
                bx + tw4_small,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            if bx + tw4_small + tw4_big >= fi.bw {
                return Ok(());
            }
            let xb = bx + tw4_small + tw4_big;
            recon_b_luma_tx_phase(
                &mut ReconBCtx {
                    recon: &mut *recon,
                    msac: &mut *msac,
                    cdf_m: &mut *cdf_m,
                    a: &mut *a,
                    l: &mut *l,
                    b,
                    fi,
                },
                tx,
                xb,
                by,
                pb_col_start,
                pb_row_start,
                lossless,
                phase,
            )?;
            if have_h_split {
                recon_b_luma_tx_phase(
                    &mut ReconBCtx {
                        recon: &mut *recon,
                        msac: &mut *msac,
                        cdf_m: &mut *cdf_m,
                        a: &mut *a,
                        l: &mut *l,
                        b,
                        fi,
                    },
                    tx,
                    xb,
                    by + th4_small,
                    pb_col_start,
                    pb_row_start,
                    lossless,
                    phase,
                )?;
            }
        }
    }

    Ok(())
}

/// Reconstruct the chroma planes (U=1, V=2) of an intra (non-IntraBC) block
#[allow(clippy::too_many_arguments)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum TxPhase {
    Both,
    ReadOnly,
    ReconOnly,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ChromaPhase {
    Both,
    ReadOnly,
    ReconOnly,
}

#[inline(always)]
pub(crate) fn chroma_phase_intersect(
    local: ChromaPhase,
    outer: ChromaPhase,
) -> Option<ChromaPhase> {
    match outer {
        ChromaPhase::Both => Some(local),
        ChromaPhase::ReadOnly => match local {
            ChromaPhase::Both | ChromaPhase::ReadOnly => Some(ChromaPhase::ReadOnly),
            ChromaPhase::ReconOnly => None,
        },
        ChromaPhase::ReconOnly => match local {
            ChromaPhase::Both | ChromaPhase::ReconOnly => Some(ChromaPhase::ReconOnly),
            ChromaPhase::ReadOnly => None,
        },
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn recon_b_intra_chroma_phase<
    BD: BitDepth,
    const UPDATE_CDF: bool,
    M: MsacReader<UPDATE_CDF>,
>(
    rb: &mut ReconBCtx<'_, '_, '_, BD, UPDATE_CDF, M>,
    cbx: i32,
    cby: i32,
    cbs: BlockSize,
    sdp_active: bool,
    phase: ChromaPhase,
) -> Result<(), ()>
where
    BD::Coef: DecodeCoeff,
{
    let recon = &mut *rb.recon;
    let msac = &mut *rb.msac;
    let cdf_m = &mut *rb.cdf_m;
    let a = &mut *rb.a;
    let l = &mut *rb.l;
    let b = rb.b;
    let fi = rb.fi;
    let is_intrabc = b.intrabc != 0;
    let is_intra = b.is_intra != 0 && (sdp_active || !is_intrabc);

    let ss_hor = recon.frame.ss_hor;
    let ss_ver = recon.frame.ss_ver;
    let seg_id = b.seg_id as usize;
    let lossless = recon.frame.seg_lossless[seg_id] != 0;

    let cb_dim = &BLOCK_DIMENSIONS[cbs as u8 as usize];
    let cbw4 = cb_dim[0] as i32;
    let cbh4 = cb_dim[1] as i32;
    let cw4 = imin(fi.bw - cbx, cbw4);
    let ch4 = imin(fi.bh - cby, cbh4);
    let cbw4ss = ((cbw4 + ss_hor) >> ss_hor) as usize;
    let cw4ss = (cw4 + ss_hor) >> ss_hor;
    let ch4ss = (ch4 + ss_ver) >> ss_ver;
    let cbh4ss = ((cbh4 + ss_ver) >> ss_ver) as usize;

    let uvtx = if lossless {
        0usize // TX_4X4
    } else {
        let layout_idx =
            (crate::headers::PixelLayout::I444 as i32 - recon.frame.layout as i32) as usize;
        crate::tables::MAX_TXFM_SIZE_FOR_BS[cbs as u8 as usize][layout_idx] as usize
    };
    let uv_t_dim = &TXFM_DIMENSIONS[uvtx];
    let ctw4 = imin(uv_t_dim.w as i32, (fi.bw - cbx + ss_hor) >> ss_hor);
    let cth4 = imin(uv_t_dim.h as i32, (fi.bh - cby + ss_ver) >> ss_ver);
    let ctw = uv_t_dim.w as usize * 4;
    let cth = uv_t_dim.h as usize * 4;
    let txw = uv_t_dim.w as i32;
    let txh = uv_t_dim.h as i32;

    let bd = recon.bd;
    let bx4 = (cbx & 63) as usize;
    let by4 = (cby & 63) as usize;
    let cbx4 = bx4 >> ss_hor;
    let cby4 = by4 >> ss_ver;
    let ssbx = (cbx >> ss_hor) as usize;
    let ssby = (cby >> ss_ver) as usize;
    let cstride = recon.frame.uv_stride_px;
    let ystride = recon.frame.y_stride_px;
    let sbsz = fi.sb_step;
    use crate::levels::IntraPredMode;

    let orig_uv_mode = b.intra_data().uv_mode;
    let mut angle = b.intra_data().uv_angle as i32;
    let uv_mode_remapped = {
        let m_in = IntraPredMode::from_raw(orig_uv_mode.min(12));
        crate::recon::wide_angle_remap(uv_t_dim, m_in, &mut angle, 0) as u8
    };
    let uv_mode = if orig_uv_mode <= 12 {
        uv_mode_remapped
    } else {
        orig_uv_mode
    };

    let n_tu = cbw4ss * cbh4ss;
    let cf_len = n_tu * 16;
    let cf_need = cf_len * 2;
    let mut cf_uv = recon.scratch.take_chroma_cf::<BD::Coef>();
    if cf_uv.len() < cf_need {
        cf_uv.resize(cf_need, <BD::Coef as crate::pixel::Coeff>::ZERO);
    }
    let (cf_u, cf_v) = cf_uv[..cf_need].split_at_mut(cf_len);
    recon.scratch.chroma_txtp[..n_tu].fill([0u16; 2]);
    recon.scratch.chroma_eob[..n_tu].fill([-1i16; 2]);

    // Snapshot the per-4x4 luma fsc map for the lossless-chroma txtp derivation
    // sidestep the `recon` borrow inside the per-TU coef loop below.
    let luma_fsc_map: [u8; 256] = recon.scratch.luma_fsc_map;

    // IntraBC blocks with skip_txfm code no chroma coefficients: fill the ccoef
    // (For non-IntraBC intra blocks skip_txfm is always 0; the chroma-only SDP
    // tree is sdp_active so skip_txfm does not apply.)
    let chroma_skip_txfm = is_intrabc && b.skip_txfm != 0;

    let mut u_has_cf = 0i32;
    if chroma_skip_txfm {
        if phase != ChromaPhase::ReconOnly {
            for pl in 0..2 {
                let aw = imin(cw4ss, 64 - cbx4 as i32).max(0) as usize;
                let lh = imin(ch4ss, 64 - cby4 as i32).max(0) as usize;
                if aw > 0 {
                    a.ccoef[pl][cbx4..cbx4 + aw].fill(0x40);
                }
                if lh > 0 {
                    l.ccoef[pl][cby4..cby4 + lh].fill(0x40);
                }
            }
        }
    } else if phase != ChromaPhase::ReconOnly {
        for pl in 0..2 {
            let cf = if pl == 0 { &mut *cf_u } else { &mut *cf_v };
            let mut y = 0;
            while y < ch4ss {
                let mut x = 0;
                while x < cw4ss {
                    let i = (y * cbw4ss as i32 + x) as usize;
                    // IntraBC is an inter block for chroma transform selection
                    // (AVM `av2_get_tx_type`): chroma inherits the co-located luma
                    // type, per TU when chroma and luma share the block size,
                    // otherwise the coding block's origin type.
                    let mut txtp: u16 = if is_intrabc && !is_intra {
                        if b.bs == b.cbs {
                            let lbx = cbx + (x << ss_hor);
                            let lby = cby + (y << ss_ver);
                            recon.scratch.txtp_map[(lby & 15) as usize * 16 + (lbx & 15) as usize]
                        } else {
                            recon.scratch.ibc_uv_txtp_seed
                        }
                    } else {
                        0
                    };
                    let mut res_ctx: u8 = 0;
                    // TU coefficient region is txw*txh*16 coefs (= ctw*cth), placed at
                    let cf_slot = &mut cf[i * 16..];
                    let tu_n = (uv_t_dim.w as usize * 4) * (uv_t_dim.h as usize * 4);
                    cf_slot[..tu_n].fill(<BD::Coef as crate::pixel::Coeff>::ZERO);

                    let dq_tbl = recon.dq_active[seg_id][1 + pl];
                    let qm_ref: Option<&[u8]> = recon.frame.qm[uvtx][1 + pl];

                    let acoef = &a.ccoef[pl][(cbx4 + x as usize)..];
                    let lcoef = &l.ccoef[pl][(cby4 + y as usize)..];

                    let params = crate::recon::DecodeCoefParams {
                        tx: uvtx,
                        // skip/entropy ctx keys off the full chroma coding block
                        // (b.cbs), not the tx-chunk walk size, matching luma's b.bs
                        // and AVM's plane_bsize = chroma_ref_info.bsize_base.
                        bs: b.cbs as usize,
                        plane: (pl + 1) as i32,
                        intra: is_intra,
                        fsc: b.fsc != 0,
                        lossless,
                        sdp_active,
                        y_mode: 0,
                        uv_mode: uv_mode as usize,
                        seq_fsc: recon.frame.seq_fsc,
                        seq_ist: recon.frame.seq_ist,
                        seq_cctx: recon.frame.seq_cctx,
                        chroma_dctonly: false,
                        reduced_txtp_set: recon.frame.reduced_txtp_set,
                        tcq_enabled: recon.frame.tcq,
                        parity_hiding: recon.frame.parity_hiding,
                        layout: recon.frame.layout,
                        u_has_cf,
                        cbx,
                        cby,
                        luma_fsc_map: &luma_fsc_map,
                        dq_tbl,
                        bitdepth: recon.frame.bitdepth,
                        qm: qm_ref,
                        ss_hor: ss_hor != 0,
                        ss_ver: ss_ver != 0,
                    };

                    let eob = msac.decode_coefs(
                        recon.cdf_coef,
                        cdf_m,
                        acoef,
                        lcoef,
                        &params,
                        cf_slot,
                        &mut txtp,
                        &mut res_ctx,
                        &mut recon.scratch.coef_levels,
                        &mut recon.scratch.coef_nz,
                    );
                    if eob == i32::MIN {
                        recon.scratch.put_chroma_cf::<BD::Coef>(cf_uv);
                        return Err(());
                    }
                    if pl == 0 {
                        u_has_cf = (eob >= 0) as i32;
                    }
                    recon.scratch.chroma_txtp[i][pl] = txtp;
                    recon.scratch.chroma_eob[i][pl] = eob as i16;

                    let aw = imin(ctw4, 64 - (cbx4 + x as usize) as i32).max(0) as usize;
                    let lh = imin(cth4, 64 - (cby4 + y as usize) as i32).max(0) as usize;
                    if aw > 0 {
                        a.ccoef[pl][cbx4 + x as usize..cbx4 + x as usize + aw].fill(res_ctx);
                    }
                    if lh > 0 {
                        l.ccoef[pl][cby4 + y as usize..cby4 + y as usize + lh].fill(res_ctx);
                    }
                    x += txw;
                }
                y += txh;
            }
        }
    } // end coef-read phase

    // Stash decoded coefficients for the deferred recon phase, or restore them.
    if phase == ChromaPhase::ReadOnly {
        let need = cf_need;
        let cf_off = recon.scratch.chroma_tx_cf_mut::<BD::Coef>().len();
        {
            let chroma_tx_cf = recon.scratch.chroma_tx_cf_mut::<BD::Coef>();
            chroma_tx_cf.extend_from_slice(cf_u);
            chroma_tx_cf.extend_from_slice(cf_v);
        }
        let meta_off = recon.scratch.chroma_tx_txtp.len() as u32;
        let (txtp_src, eob_src) = (
            &recon.scratch.chroma_txtp[..n_tu],
            &recon.scratch.chroma_eob[..n_tu],
        );
        recon.scratch.chroma_tx_txtp.extend_from_slice(txtp_src);
        recon.scratch.chroma_tx_eob.extend_from_slice(eob_src);
        recon.scratch.chroma_tx.push(ChromaTxRecord {
            cbx: cbx as i16,
            cby: cby as i16,
            cbs: cbs as u8,
            sdp_active,
            n_tu: n_tu as u16,
            cf_off: cf_off as u32,
            cf_len: need as u32,
            u_has_cf,
            meta_off,
        });
        recon.scratch.put_chroma_cf::<BD::Coef>(cf_uv);
        return Ok(());
    } else if phase == ChromaPhase::ReconOnly {
        let rec = match recon
            .scratch
            .chroma_tx
            .get(recon.scratch.chroma_tx_rpos)
            .copied()
        {
            Some(rec) => rec,
            None => {
                recon.scratch.put_chroma_cf::<BD::Coef>(cf_uv);
                return Err(());
            }
        };
        recon.scratch.chroma_tx_rpos += 1;
        debug_assert_eq!(rec.cbx as i32, cbx);
        debug_assert_eq!(rec.cby as i32, cby);
        debug_assert_eq!(rec.cbs, cbs as u8);
        debug_assert_eq!(rec.sdp_active, sdp_active);
        debug_assert_eq!(rec.n_tu as usize, n_tu);
        let cf_off = rec.cf_off as usize;
        let rec_cf_len = rec.cf_len as usize;
        debug_assert_eq!(rec_cf_len, cf_need);
        let chroma_tx_cf = recon.scratch.chroma_tx_cf::<BD::Coef>();
        cf_u.copy_from_slice(&chroma_tx_cf[cf_off..cf_off + cf_len]);
        cf_v.copy_from_slice(&chroma_tx_cf[cf_off + cf_len..cf_off + cf_need]);
        let mo = rec.meta_off as usize;
        let scratch = &mut recon.scratch;
        scratch.chroma_txtp[..n_tu].copy_from_slice(&scratch.chroma_tx_txtp[mo..mo + n_tu]);
        scratch.chroma_eob[..n_tu].copy_from_slice(&scratch.chroma_tx_eob[mo..mo + n_tu]);
        u_has_cf = rec.u_has_cf;
    }
    let _ = u_has_cf;

    // CfL is intra-only (`if (intra) cfl()`); IntraBC used the mc copy instead.
    if is_intra && uv_mode == CFL_PRED {
        if let Err(e) = cfl_predict_8bpc(recon, b, uvtx, cbx, cby, fi) {
            recon.scratch.put_chroma_cf::<BD::Coef>(cf_uv);
            return Err(e);
        }
    }

    let col_end_ss = fi.tile_col_end >> ss_hor;
    let row_end_ss = fi.tile_row_end >> ss_ver;
    let mut y = 0;
    while y < ch4ss {
        let mut x = 0;
        while x < cw4ss {
            let i = (y * cbw4ss as i32 + x) as usize;
            let dst_off = 4 * ((ssby + y as usize) * cstride + ssbx + x as usize);

            // Intra prediction for both planes (skipped for CfL and IntraBC).
            // C gate: `if (intra && b->uv_mode != CFL_PRED)`.
            if is_intra && uv_mode != CFL_PRED {
                for pl in 0..2 {
                    let plane_x = ssbx as i32 + x;
                    let plane_y = ssby as i32 + y;
                    let col_start_ss = fi.tile_col_start >> ss_hor;
                    let row_start_ss = fi.tile_row_start >> ss_ver;
                    let right_edge4 = col_end_ss - plane_x - ctw4;
                    let bottom_edge4 = row_end_ss - plane_y - cth4;
                    let right_available = plane_x + ctw4 < col_end_ss;
                    let bottom_available = bottom_edge4 > 0 && plane_y + cth4 < row_end_ss;
                    let n_tr = intra_top_right_units(
                        false,
                        b.tx_part,
                        true,
                        &recon.scratch.is_coded,
                        1,
                        sbsz,
                        cbs,
                        ssbx as i32,
                        ssby as i32,
                        x,
                        y,
                        ctw4,
                        ss_hor,
                        ss_ver,
                        plane_y > row_start_ss,
                        right_available,
                        right_edge4,
                    );
                    let n_bl = intra_bottom_left_units(
                        false,
                        b.tx_part,
                        true,
                        &recon.scratch.is_coded,
                        1,
                        sbsz,
                        cbs,
                        ssbx as i32,
                        ssby as i32,
                        x,
                        y,
                        cth4,
                        ss_hor,
                        ss_ver,
                        bottom_available,
                        plane_x > col_start_ss,
                        bottom_edge4,
                    );

                    let mut apply_ibp = recon.frame.seq_ibp && uvtx != 0;
                    let sm_top = b.intra_data().is_sm[1].a;
                    let sm_left = b.intra_data().is_sm[1].l;
                    let is_sm_flag = if apply_ibp {
                        (sm_top * crate::levels::ANGLE_SMOOTH_TOP_EDGE_FLAG)
                            | (sm_left * crate::levels::ANGLE_SMOOTH_LEFT_EDGE_FLAG)
                    } else {
                        (sm_top | sm_left)
                            * (crate::levels::ANGLE_SMOOTH_TOP_EDGE_FLAG
                                | crate::levels::ANGLE_SMOOTH_LEFT_EDGE_FLAG)
                    };
                    apply_ibp &= uv_mode == 0; // DC_PRED
                    let have_left = cbx + (x << ss_hor) > fi.tile_col_start;
                    let have_top = cby + (y << ss_ver) > fi.tile_row_start;
                    let intra_flags = is_sm_flag
                        | if apply_ibp {
                            crate::levels::ANGLE_IBP_FLAG
                        } else {
                            0
                        }
                        | if recon.frame.seq_ibp {
                            crate::levels::ANGLE_SEQHDR_IBP_FLAG
                        } else {
                            0
                        }
                        | if recon.frame.seq_intra_edge_filter {
                            crate::levels::ANGLE_USE_EDGE_FILTER_FLAG
                        } else {
                            0
                        }
                        | if have_left {
                            crate::levels::ANGLE_HAS_LEFT_FLAG
                        } else {
                            0
                        }
                        | if have_top {
                            crate::levels::ANGLE_HAS_TOP_FLAG
                        } else {
                            0
                        };
                    let pred_mode = if uv_mode == CFL_PRED { 0 } else { uv_mode };

                    let dst_plane: &mut [BD::Pixel] =
                        if pl == 0 { recon.dst_u } else { recon.dst_v };
                    let edge_o: usize = 768;
                    let m = crate::ipred_prepare::prepare_intra_edges(
                        bd,
                        ssbx as i32 + x,
                        ssby as i32 + y,
                        col_end_ss,
                        row_end_ss,
                        n_tr,
                        n_bl,
                        dst_plane,
                        dst_off,
                        cstride,
                        None,
                        pred_mode,
                        txw,
                        txh,
                        angle | intra_flags,
                        recon.edge,
                        edge_o,
                    );
                    let pred_angle = angle | intra_flags;
                    let max_w = 4 * fi.bw - 4 * (cbx + x);
                    let max_h = 4 * fi.bh - 4 * (cby + y);
                    dispatch_ipred(
                        recon.frame.exec,
                        bd,
                        m,
                        dst_plane,
                        dst_off,
                        cstride,
                        recon.edge,
                        edge_o,
                        ctw,
                        cth,
                        pred_angle,
                        max_w,
                        max_h,
                        &recon.frame.ibp_weights,
                    );
                }
            }

            let cctx_enabled = recon.frame.seq_cctx
                && (recon.frame.layout == crate::headers::PixelLayout::I420 || uv_t_dim.min < 8);
            let cctx_type = if cctx_enabled && recon.scratch.chroma_eob[i][0] >= 1 {
                (recon.scratch.chroma_txtp[i][0] >> 8) as i32
            } else {
                0
            };
            if cctx_type != 0 {
                let sz = imin(ctw as i32, 32) as usize * imin(cth as i32, 32) as usize;
                crate::itx::cctx_bd_ctx(
                    recon.frame.exec,
                    bd,
                    &mut cf_u[i * 16..],
                    &mut cf_v[i * 16..],
                    &crate::tables::CCTX_ANGLE[(cctx_type - 1) as usize],
                    sz,
                );
                let gt = (recon.scratch.chroma_eob[i][1] > recon.scratch.chroma_eob[i][0]) as usize;
                recon.scratch.chroma_eob[i][1 - gt] = recon.scratch.chroma_eob[i][gt];
                let t0 = recon.scratch.chroma_txtp[i][0] & 0xff;
                recon.scratch.chroma_txtp[i][0] = t0;
                recon.scratch.chroma_txtp[i][1] = t0;
            }

            for pl in 0..2 {
                let eob = recon.scratch.chroma_eob[i][pl];
                if eob != -1 {
                    let cf = if pl == 0 { &mut *cf_u } else { &mut *cf_v };
                    let mut txtp = recon.scratch.chroma_txtp[i][pl] as u32;
                    // `lossless && b->intra && (sdp_active || !b->intrabc) && dpcm[1]`;
                    // the inter-DDT branch is `seq_hdr->inter_ddt && !b->intra`.
                    // The DDT branch keys off `!b->intra` — an IntraBC block has
                    // `b->intra == 1`, so it takes NEITHER branch. This chroma tx
                    // path only runs for intra/IntraBC blocks, so the DDT branch
                    // never fires; applying it for IntraBC corrupts the transform.
                    if lossless && is_intra && b.intra_data().dpcm[1] != 0 {
                        txtp +=
                            ((1 + (uv_mode == IntraPredMode::VertPred as u8) as u32) as u32) << 8;
                    } else if recon.frame.seq_inter_ddt && b.is_intra == 0 {
                        txtp += txtp & crate::tables::TX_DDT_MASK[uvtx] as u32;
                    }
                    let dst_plane: &mut [BD::Pixel] =
                        if pl == 0 { recon.dst_u } else { recon.dst_v };
                    crate::itx::inv_txfm_add_ctx(
                        recon.frame.exec,
                        bd,
                        dst_plane,
                        dst_off,
                        cstride,
                        &mut cf[i * 16..],
                        txtp,
                        eob as i32,
                        uvtx,
                        &mut recon.scratch.itx_tmp,
                    );
                }
            }

            let coded_w = imin(ctw4, 64 - (cbx4 as i32 + x)).max(0) as u32;
            if coded_w > 0 {
                let mask: u64 = (((1u128 << coded_w) - 1) as u64) << ((cbx4 as i32 + x) as u32);
                for yy in 0..cth4 {
                    let row = (cby4 as i32 + y + yy) as usize;
                    if row < 64 {
                        recon.scratch.is_coded[1][row] |= mask;
                    }
                }
            }
            x += txw;
        }
        y += txh;
    }

    let _ = (orig_uv_mode, ystride);
    recon.scratch.put_chroma_cf::<BD::Coef>(cf_uv);
    Ok(())
}

/// Handles CFL_EXPLICIT / CFL_IMPLICIT (cfl_type < 2) and CFL_MHCCP (cfl_type==2).
#[allow(clippy::too_many_arguments)]
fn cfl_predict_8bpc<BD: BitDepth>(
    recon: &mut ReconCtx<BD>,
    b: &Av2Block,
    uvtx: usize,
    cbx: i32,
    cby: i32,
    fi: &SbFrameInfo,
) -> Result<(), ()> {
    use crate::ipred::{
        CFL_HAS_LEFT, CFL_HAS_TOP, CFL_IS_TOP_SB_EDGE, CFL_MHCCP_MAX_EDGE_SAMPLES, cfl_calc_alphas,
        cfl_gen_mat, cfl_gen_y_420, cfl_mhccp_pred, cfl_pred_raw,
    };
    use crate::levels::CflMhDir;

    let bd = recon.bd;
    let ss_hor = recon.frame.ss_hor as usize;
    let ss_ver = recon.frame.ss_ver as usize;
    let ystride = recon.frame.y_stride_px;
    let cstride = recon.frame.uv_stride_px;
    let sbsz = fi.sb_step;
    let ssbx = (cbx >> ss_hor) as usize;
    let ssby = (cby >> ss_ver) as usize;
    let has_top = cby > fi.tile_row_start;
    let has_left = cbx > fi.tile_col_start;
    let is_top_sb_edge = (cby & (sbsz - 1)) == 0;
    let t_dim = &TXFM_DIMENSIONS[uvtx];
    let ctw4 = imin(t_dim.w as i32, (fi.bw - cbx + ss_hor as i32) >> ss_hor) as usize;
    let cth4 = imin(t_dim.h as i32, (fi.bh - cby + ss_ver as i32) >> ss_ver) as usize;
    let ctw = t_dim.w as usize * 4;
    let cth = t_dim.h as usize * 4;
    let filter_type = recon.frame.cfl_ds_filter_index;
    let cfl_type = b.intra_data().cfl_type as i32;
    let cfl_mh_dir_raw = b.intra_data().cfl.mh_dir();
    // Raw symbol (0/1) maps directly to the dispatch index (CENTER=0, TOP=1).
    let dir = CflMhDir::from_raw(cfl_mh_dir_raw.min(3));

    let ysrc_off = (cby as usize * ystride + cbx as usize) * 4;

    if cfl_type < 2 {
        let implicit = cfl_type == 1; // CFL_IMPLICIT
        let coff = (ssby * cstride + ssbx) * 4;
        // ytop / utop / vtop: source rows above the current block used for the CfL
        // above the SB). In single-thread / filters-off decode `prefilter_data`
        // aliases the current plane with `prefilter_data_full_frame` set, so the
        // luma SB-edge row resolves to `ysrc - ystride` (one luma row up) and is
        // downsampled with `bottom = 0` via the CFL_IS_TOP_SB_EDGE flag; the
        // in-plane fallback instead starts `1 + ss_ver` rows up with
        // `bottom = ystride`. The chroma `utop`/`vtop` offsets are `coff - cstride`
        // in both branches (single-thread alias), so only `ytop_off` differs.
        let ytop_off = if is_top_sb_edge && has_top {
            (ysrc_off as isize - ystride as isize) as usize
        } else {
            (ysrc_off as isize - ((1 + ss_ver) as isize) * ystride as isize) as usize
        };
        let utop_off = (coff as isize - cstride as isize) as usize;
        let vtop_off = utop_off;

        // AVM pads CfL to the current transform prediction size, not to the
        // containing chroma block size. Using cbs here over-pads internal TUs
        // and can reject valid AVM-produced 4:2:2/4:4:4 edge cases.
        debug_assert!(ctw4 <= t_dim.w as usize);
        debug_assert!(cth4 <= t_dim.h as usize);
        let wpad = t_dim.w as usize - ctw4;
        let hpad = t_dim.h as usize - cth4;

        let alpha = b.intra_data().cfl.alpha();
        let cfl_has_left = has_left;
        let cfl_has_top = has_top;
        let flags = (filter_type as u32)
            | if cfl_has_top { CFL_HAS_TOP as u32 } else { 0 }
            | if cfl_has_left { CFL_HAS_LEFT as u32 } else { 0 }
            | if is_top_sb_edge {
                CFL_IS_TOP_SB_EDGE
            } else {
                0
            }
            | (((alpha[0] as u32) << crate::ipred::CFL_ALPHA_U_SHIFT)
                & crate::ipred::CFL_ALPHA_U_MASK)
            | (((alpha[1] as u32) << crate::ipred::CFL_ALPHA_V_SHIFT)
                & crate::ipred::CFL_ALPHA_V_MASK);

        // In C, utop/vtop and the left references alias the same allocation as the
        // goes one step further and runs CfL into temporary chroma blocks with an
        let dst_y: &[BD::Pixel] = &*recon.dst_y;
        let (u_buf, v_buf) = (&mut *recon.dst_u, &mut *recon.dst_v);

        cfl_pred_raw(
            recon.frame.exec,
            bd,
            dst_y,
            u_buf,
            v_buf,
            ytop_off,
            utop_off,
            vtop_off,
            ysrc_off,
            coff,
            coff,
            ystride as isize,
            cstride as isize,
            wpad,
            hpad,
            ctw,
            cth,
            flags,
            implicit,
            ss_hor,
            ss_ver,
        )?;

        return Ok(());
    }

    let mut refw = (ctw4 * 4) as i32;
    let mut refh = (cth4 * 4) as i32;
    let cbx4 = ((cbx & 63) >> ss_hor) as i32;
    let cby4 = ((cby & 63) >> ss_ver) as i32;
    if has_top {
        let csbsz = sbsz >> ss_hor as i32;
        let tile_end = fi.tile_col_end >> ss_hor as i32;
        let mut w = imax(0, imin(ctw4 as i32, tile_end - ssbx as i32 - ctw4 as i32));
        let n_tr = if is_top_sb_edge {
            w
        } else {
            let end = imin((ssbx as i32 + csbsz) & !(csbsz - 1), tile_end);
            w = imin(ctw4 as i32, end - ssbx as i32 - ctw4 as i32);
            if w == 0 {
                0
            } else {
                let bits =
                    recon.scratch.is_coded[1][(cby4 - 1) as usize] >> ((cbx4 + ctw4 as i32) as u32);
                imin((0x10000u64 | !bits).trailing_zeros() as i32, w)
            }
        };
        // AVM only extends the reference to the top-right when the luma-scaled
        // TX width is > 4 (`have_top_right && width > 4`), i.e. never for 4-wide
        // chroma TXs in 4:4:4.
        if (ctw << ss_hor) > 4 {
            refw += n_tr * 4;
        }
    }
    let mut subleft = 0;
    if has_left {
        let csbsz = sbsz >> ss_ver as i32;
        let end = imax(
            0,
            imin(
                (ssby as i32 + csbsz) & !(csbsz - 1),
                fi.tile_row_end >> ss_ver as i32,
            ),
        );
        let h = imin(cth4 as i32, end - ssby as i32 - cth4 as i32);
        let n_bl = if (cbx & (sbsz - 1)) == 0 || h <= 0 {
            h
        } else {
            let mask = 1u64 << ((cbx4 - 1) as u32);
            let mut nb = 0;
            while nb < h {
                if (recon.scratch.is_coded[1][(cby4 + nb + cth4 as i32) as usize] & mask) == 0 {
                    break;
                }
                nb += 1;
            }
            nb
        };
        // Same `height > 4` gate for the bottom-left (4-tall chroma TXs in
        // 4:2:2 / 4:4:4).
        if (cth << ss_ver) > 4 {
            refh += n_bl * 4;
        }
        refw += 2;
        subleft = (dir != CflMhDir::Left) as i32;
    }
    if refw > (128 >> ss_hor) {
        refw = 128 >> ss_hor;
        subleft = 0;
    }
    refh = imin(refh, (128 >> ss_ver) - 2 * has_top as i32);

    let luma_top_stride = ((refw as usize) + 63) & !63;
    let edge_flags = if has_top { CFL_HAS_TOP } else { 0 }
        | if has_left { CFL_HAS_LEFT } else { 0 }
        | if is_top_sb_edge {
            CFL_IS_TOP_SB_EDGE as i32
        } else {
            0
        };

    let mut luma = [BD::Pixel::default(); crate::ipred::CFL_MHCCP_MAX_LUMA_SIZE];
    // SAFETY: luma plane is a disjoint allocation from chroma planes.
    let ysrc: &[BD::Pixel] = &*recon.dst_y;
    // and `prefilter_data_full_frame` is set, so `ytop_sb_edge` resolves to the
    // explicitly makes `cfl_gen_y` take the `top_sb_edge != NULL` branch (b=0),
    // which differs from the in-plane fallback (b=src_stride) at internal SB
    let ytop_sb_edge: Option<(&[BD::Pixel], usize)> = if is_top_sb_edge && has_top {
        Some((ysrc, ysrc_off - ystride))
    } else {
        None
    };
    cfl_gen_y_420(
        recon.frame.exec,
        &mut luma,
        luma_top_stride,
        ysrc,
        ysrc_off,
        ytop_sb_edge,
        ystride,
        (refw - subleft) as usize,
        refh as usize,
        ctw,
        cth,
        edge_flags | dir as i32,
        filter_type,
        ss_hor,
        ss_ver,
    );
    refh += has_top as i32;

    let mut mat = [[0i32; 3]; 3];
    let mut imat = [[0u16; CFL_MHCCP_MAX_EDGE_SAMPLES]; 2];
    if has_top || has_left {
        cfl_gen_mat(
            recon.frame.exec,
            bd,
            &mut mat,
            &mut imat,
            &luma,
            0,
            luma_top_stride,
            refw as usize,
            refh as usize,
            edge_flags,
            dir,
        );
    }

    for pl in 0..2 {
        let mut alpha = [0i32; 3];
        let chroma_off = 4 * (ssby * cstride + ssbx);
        let chroma: &mut [BD::Pixel] = if pl == 0 { recon.dst_u } else { recon.dst_v };
        if has_top || has_left {
            cfl_calc_alphas(
                recon.frame.exec,
                bd,
                &mut alpha,
                chroma,
                chroma_off,
                None, // ctop_sb_edge (frame-top only)
                cstride,
                refw as usize,
                refh as usize,
                &mut mat,
                &imat,
                edge_flags,
            );
        } else {
            alpha[2] = 0x10000;
        }
        let n_top = if has_top {
            has_top as usize + (dir == CflMhDir::Top) as usize
        } else {
            0
        };
        let src_off = n_top * luma_top_stride;
        // the `chroma` pointer to the block), so slice the destination plane at
        // the block offset rather than the plane origin.
        cfl_mhccp_pred(
            recon.frame.exec,
            bd,
            &mut chroma[chroma_off..],
            cstride,
            &luma,
            src_off,
            luma_top_stride,
            ctw,
            cth,
            &alpha,
            edge_flags,
            dir,
        );
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn recon_b_luma_tx_phase<
    BD: crate::pixel::BitDepth,
    const UPDATE_CDF: bool,
    M: MsacReader<UPDATE_CDF>,
>(
    rb: &mut ReconBCtx<'_, '_, '_, BD, UPDATE_CDF, M>,
    tx: usize,
    bx: i32,
    by: i32,
    pb_col_start: i32,
    pb_row_start: i32,
    lossless: bool,
    phase: TxPhase,
) -> Result<(), ()>
where
    BD::Coef: DecodeCoeff,
{
    let recon = &mut *rb.recon;
    let msac = &mut *rb.msac;
    let cdf_m = &mut *rb.cdf_m;
    let a = &mut *rb.a;
    let l = &mut *rb.l;
    let b = rb.b;
    let fi = rb.fi;
    use crate::levels::IntraPredMode;

    let bd = recon.bd;
    let bx4 = (bx & 63) as usize;
    let by4 = (by & 63) as usize;
    let t_dim = &TXFM_DIMENSIONS[tx];
    let tw = t_dim.w as usize * 4;
    let th = t_dim.h as usize * 4;
    let tw4 = t_dim.w as i32;
    let th4 = t_dim.h as i32;

    let is_intrabc = b.intrabc != 0;
    // The decode-coefs / stx "intra" flag: `b->intra && (sdp_active || !b->intrabc)`
    // — here sdp_active is false in the luma path, so it is false for IntraBC.
    let is_intra = !is_intrabc;

    let intra = b.intra_data();
    let orig_y_mode = intra.y_mode;
    let mut angle = intra.y_angle as i32;

    let y_mode = if is_intra {
        // SAFETY: y_mode is a valid IntraPredMode discriminant (0..=12).
        let y_mode_remapped = {
            let m_in = IntraPredMode::from_raw(orig_y_mode.min(12));
            crate::recon::wide_angle_remap(t_dim, m_in, &mut angle, intra.mrl_index as i32) as u8
        };
        if orig_y_mode <= 12 {
            y_mode_remapped
        } else {
            orig_y_mode
        }
    } else {
        orig_y_mode
    };

    let tu_n = tw * th;
    let mut txtp: u16 = 0;
    let mut res_ctx: u8 = 0;
    // No pre-clear: every inverse-transform path clears cf[..S*S] after use
    // (itx_2d dequant cores + itx.rs WHT/DC/generic), and cf starts zeroed, so
    // cf is already zero on entry here. Verified bit-exact + via prefill poison.

    // IntraBC blocks may set skip_txfm (intra/non-IntraBC blocks force it to 0).
    // When set, no coefficients are coded: eob=-1, txtp=DCT_DCT, stx=0, and the
    // coefficient contexts are updated as skipped.
    let (mut eob, stx, mut txtp) = if phase == TxPhase::ReconOnly {
        let rec = recon
            .scratch
            .luma_tx
            .get(recon.scratch.luma_tx_rpos)
            .copied()
            .ok_or(())?;
        recon.scratch.luma_tx_rpos += 1;
        debug_assert_eq!(rec.tx as usize, tx);
        debug_assert_eq!(rec.bx as i32, bx);
        debug_assert_eq!(rec.by as i32, by);
        debug_assert_eq!(rec.pb_col_start as i32, pb_col_start);
        debug_assert_eq!(rec.pb_row_start as i32, pb_row_start);
        debug_assert_eq!(rec.lossless, lossless);
        let cf_off = rec.cf_off as usize;
        let cf_len = rec.cf_len as usize;
        if cf_len != 0 {
            recon.cf[..cf_len]
                .copy_from_slice(&recon.scratch.luma_tx_cf::<BD::Coef>()[cf_off..cf_off + cf_len]);
        }
        (rec.eob as i32, rec.stx as i32, rec.txtp as u32)
    } else if b.skip_txfm != 0 {
        res_ctx = 0x40;
        (-1i32, 0i32, crate::levels::txtp::DCT_DCT as u32)
    } else {
        let dq_seg = b.seg_id as usize;
        let dq_tbl = recon.dq_active[dq_seg][0]; // plane 0 (luma)
        let qm_ref: Option<&[u8]> = recon.frame.qm[tx][0];

        let params = crate::recon::DecodeCoefParams {
            tx,
            bs: b.bs as usize,
            plane: 0,
            intra: is_intra,
            fsc: b.fsc != 0,
            lossless,
            sdp_active: false,
            y_mode: y_mode as usize,
            uv_mode: 0,
            seq_fsc: recon.frame.seq_fsc,
            seq_ist: recon.frame.seq_ist,
            seq_cctx: recon.frame.seq_cctx,
            chroma_dctonly: false,
            reduced_txtp_set: recon.frame.reduced_txtp_set,
            tcq_enabled: recon.frame.tcq,
            parity_hiding: recon.frame.parity_hiding,
            layout: recon.frame.layout,
            u_has_cf: 0,
            cbx: 0,
            cby: 0,
            luma_fsc_map: &[],
            dq_tbl,
            bitdepth: recon.frame.bitdepth,
            qm: qm_ref,
            ss_hor: recon.frame.ss_hor != 0,
            ss_ver: recon.frame.ss_ver != 0,
        };

        let eob = msac.decode_coefs(
            recon.cdf_coef,
            cdf_m,
            &a.lcoef[bx4..],
            &l.lcoef[by4..],
            &params,
            recon.cf,
            &mut txtp,
            &mut res_ctx,
            &mut recon.scratch.coef_levels,
            &mut recon.scratch.coef_nz,
        );
        if eob == i32::MIN {
            return Err(());
        }
        let stx = (txtp >> 8) as i32;
        (eob, stx, (txtp & 0xff) as u32)
    };

    // IntraBC chroma inherits the luma transform type (it is an inter block
    // for chroma tx selection), so record it per covered 4x4 like the inter
    // luma path does.
    if is_intrabc && phase != TxPhase::ReconOnly {
        let (by15, bx15) = ((by & 15) as usize, (bx & 15) as usize);
        for yy in by15..(by15 + th4 as usize).min(16) {
            for xx in bx15..(bx15 + tw4 as usize).min(16) {
                recon.scratch.txtp_map[yy * 16 + xx] = (txtp & 0xff) as u16;
            }
        }
    }

    let aw = imin(tw4, fi.bw - bx).max(0) as usize;
    let lh = imin(th4, fi.bh - by).max(0) as usize;
    if phase != TxPhase::ReconOnly {
        if aw > 0 {
            a.lcoef[bx4..bx4 + aw].fill(res_ctx);
        }
        if lh > 0 {
            l.lcoef[by4..by4 + lh].fill(res_ctx);
        }
    }

    if phase == TxPhase::ReadOnly {
        let cf_len = if eob != -1 { tu_n } else { 0 };
        let cf_off = recon.scratch.luma_tx_cf_mut::<BD::Coef>().len();
        if cf_len != 0 {
            recon
                .scratch
                .luma_tx_cf_mut::<BD::Coef>()
                .extend_from_slice(&recon.cf[..cf_len]);
            // In the normal path `inv_txfm_add` clears the consumed coefficient
            // region.  ReadOnly returns before the inverse transform, so preserve
            // the same zero-on-entry invariant for the next coefficient block.
            recon.cf[..cf_len].fill(<BD::Coef as crate::pixel::Coeff>::ZERO);
        }
        recon.scratch.luma_tx.push(LumaTxRecord {
            tx: tx as u8,
            bx: bx as i16,
            by: by as i16,
            pb_col_start: pb_col_start as i16,
            pb_row_start: pb_row_start as i16,
            eob: eob as i16,
            stx: stx as i8,
            txtp: txtp as u16,
            cf_off: cf_off as u32,
            cf_len: cf_len as u16,
            lossless,
        });
        return Ok(());
    }

    // dst origin for this tx block.
    let stride = recon.frame.y_stride_px;
    let dst_off = 4 * (by as usize * stride + bx as usize);

    // Skipped for IntraBC: the block-copy prediction was applied before the tx
    if is_intra && intra.pal_sz == 0 {
        let sbsz = fi.sb_step;
        let mrl_idx = intra.mrl_index as i32;
        let mrl_mul = intra.multi_mrl != 0 && tx != 0; // tx != TX_4X4
        let is_hv5 = (by > pb_row_start || bx > pb_col_start)
            && (b.tx_part == TxPartition::H5 as u8 || b.tx_part == TxPartition::V5 as u8);

        let col_off = bx - pb_col_start;
        let row_off = by - pb_row_start;
        let right_edge4 = fi.tile_col_end - bx - tw4;
        let bottom_edge4 = fi.tile_row_end - by - th4;
        let right_available = bx + tw4 < fi.tile_col_end;
        let bottom_available = bottom_edge4 > 0 && by + th4 < fi.tile_row_end;
        let n_tr = intra_top_right_units(
            true,
            b.tx_part,
            !is_hv5,
            &recon.scratch.is_coded,
            0,
            sbsz,
            BlockSize::from_raw(b.bs),
            pb_col_start,
            pb_row_start,
            col_off,
            row_off,
            tw4,
            0,
            0,
            by > fi.tile_row_start,
            right_available,
            right_edge4,
        );
        let n_bl = intra_bottom_left_units(
            true,
            b.tx_part,
            !is_hv5,
            &recon.scratch.is_coded,
            0,
            sbsz,
            BlockSize::from_raw(b.bs),
            pb_col_start,
            pb_row_start,
            col_off,
            row_off,
            th4,
            0,
            0,
            bottom_available,
            bx > fi.tile_col_start,
            bottom_edge4,
        );

        let mut apply_ibp = recon.frame.seq_ibp && tx != 0 && mrl_idx == 0;
        let dip = intra.dip as i32 - 1;
        let sm_top = intra.is_sm[0].a;
        let sm_left = intra.is_sm[0].l;
        let is_sm_flag = if apply_ibp {
            (sm_top * crate::levels::ANGLE_SMOOTH_TOP_EDGE_FLAG)
                | (sm_left * crate::levels::ANGLE_SMOOTH_LEFT_EDGE_FLAG)
        } else {
            (sm_top | sm_left)
                * (crate::levels::ANGLE_SMOOTH_TOP_EDGE_FLAG
                    | crate::levels::ANGLE_SMOOTH_LEFT_EDGE_FLAG)
        };
        if intra.y_angle & 1 != 0 {
            apply_ibp = false;
        }
        let have_left = bx > fi.tile_col_start;
        let have_top = by > fi.tile_row_start;
        let intra_flags = crate::levels::ANGLE_IS_LUMA
            | is_sm_flag
            | if recon.frame.seq_intra_edge_filter {
                crate::levels::ANGLE_USE_EDGE_FILTER_FLAG
            } else {
                0
            }
            | if apply_ibp {
                crate::levels::ANGLE_IBP_FLAG
            } else {
                0
            }
            | if recon.frame.seq_ibp {
                crate::levels::ANGLE_SEQHDR_IBP_FLAG
            } else {
                0
            }
            | (mrl_idx << crate::levels::ANGLE_MRL_IDX_SHIFT)
            | if mrl_mul {
                crate::levels::ANGLE_MULTI_MRL_FLAG
            } else {
                0
            }
            | if have_left {
                crate::levels::ANGLE_HAS_LEFT_FLAG
            } else {
                0
            }
            | if have_top {
                crate::levels::ANGLE_HAS_TOP_FLAG
            } else {
                0
            }
            | if dip >= 0 {
                crate::levels::ANGLE_DIP_FLAG
            } else {
                0
            };
        let angle_eff = if dip >= 0 { dip } else { angle };

        // Edge buffer origin: C uses `edge + 128 + !!mrl_idx*9`; we centre in a
        // larger slab so any layout (incl. multi-mrl second edge) fits.
        let edge_o: usize = 768 + if mrl_idx != 0 { 9 } else { 0 };

        // `prefilter_data` copy of the row above the SB; with single-thread /
        // filters-off decode that aliases the current plane's row directly above
        // the block (prefilter_data_full_frame). Passing it makes prepare_intra
        // _edges use the SB-edge row (top_stride 0) instead of stepping mrl_idx+1
        // rows up, which would cross the SB boundary for multi-reference-line
        // directional blocks. The slice is based at column 0 of row `4*by - 1`
        // (prepare adds the `x*4` column offset).
        let prefilter_top: Option<&[BD::Pixel]> = if have_top && (by & (sbsz - 1)) == 0 {
            let base = dst_off - (bx as usize) * 4 - stride;
            let plane: &[BD::Pixel] = &*recon.dst_y;
            Some(&plane[base..])
        } else {
            None
        };

        let m = crate::ipred_prepare::prepare_intra_edges(
            bd,
            bx,
            by,
            fi.tile_col_end,
            fi.tile_row_end,
            n_tr,
            n_bl,
            recon.dst_y,
            dst_off,
            stride,
            prefilter_top,
            y_mode,
            tw4,
            th4,
            angle_eff | intra_flags,
            recon.edge,
            edge_o,
        );

        let pred_angle = angle_eff | intra_flags;
        let max_w = 4 * fi.bw - 4 * bx;
        let max_h = 4 * fi.bh - 4 * by;
        dispatch_ipred(
            recon.frame.exec,
            bd,
            m,
            recon.dst_y,
            dst_off,
            stride,
            recon.edge,
            edge_o,
            tw,
            th,
            pred_angle,
            max_w,
            max_h,
            &recon.frame.ibp_weights,
        );
    }

    if eob != -1 {
        if stx != 0 {
            const MASK: i32 = (1 << IntraPredMode::HorPred as i32)
                | (1 << IntraPredMode::HorDownPred as i32)
                | (1 << IntraPredMode::VertLeftPred as i32)
                | (1 << IntraPredMode::SmoothHPred as i32);
            // C: transpose = intrabc || !intra || !((mask >> b->y_mode) & 1);
            let transpose = is_intrabc || (MASK >> (y_mode as i32)) & 1 == 0;
            let stype = (stx & 3) - 1;
            let set = (stx >> 2) & 15;
            if tw >= 8 && th >= 8 {
                let koff = (set as usize * 3 + stype as usize) * 1536;
                let idx = (imin(t_dim.lh as i32, 3) - 1) as usize;
                let scan_out = &crate::stx_tables::STX_SCAN_ORDERS_8X8[idx][transpose as usize];
                let mapping =
                    &crate::stx_tables::COEFF8X8_MAPPING[set as usize * 3 + stype as usize];
                crate::stx::stxfm8_dispatch(
                    recon.cf,
                    &crate::stx_tables::STX_8X8_KERNEL[koff..],
                    eob as usize,
                    recon.frame.bitdepth_max,
                    scan_out,
                    mapping,
                );
                eob = [63, 119, 231][idx];
            } else {
                let koff = (set as usize * 3 + stype as usize) * 128;
                let idx = imin(t_dim.lh as i32, 3) as usize;
                let scan_out = &crate::stx_tables::STX_SCAN_ORDERS_4X4[idx][transpose as usize];
                crate::stx::stxfm4_dispatch(
                    recon.cf,
                    &crate::stx_tables::STX_4X4_KERNEL[koff..],
                    eob as usize,
                    recon.frame.bitdepth_max,
                    scan_out,
                );
                eob = [15, 15, 51, 99][idx];
            }
        }

        // DPCM branch on `b->intra && !b->intrabc && b->dpcm[0]` and the inter-DDT
        // ((flip)adst -> (f)ddt) branch on `seq_hdr->inter_ddt && !b->intra`.
        // Crucially the DDT branch keys off `!b->intra`, NOT IntraBC: an IntraBC
        // block has `b->intra == 1`, so it takes NEITHER branch. This luma tx
        // walk only ever runs for intra/IntraBC blocks (`b.is_intra == 1`), so
        // the DDT branch never fires here — applying it for IntraBC corrupts the
        // residual transform type.
        if lossless && is_intra && b.intra_data().dpcm[0] != 0 {
            txtp += ((1 + (y_mode == IntraPredMode::VertPred as u8) as u32) as u32) << 8;
        } else if recon.frame.seq_inter_ddt && b.is_intra == 0 {
            txtp += txtp & crate::tables::TX_DDT_MASK[tx] as u32;
        }

        crate::itx::inv_txfm_add_ctx(
            recon.frame.exec,
            bd,
            recon.dst_y,
            dst_off,
            stride,
            recon.cf,
            txtp,
            eob,
            tx,
            &mut recon.scratch.itx_tmp,
        );
    }

    let coded_w = imin(tw4, 64 - bx4 as i32).max(0) as u32;
    if coded_w > 0 {
        let mask: u64 = (((1u128 << coded_w) - 1) as u64) << (bx4 as u32);
        for y in 0..th4 {
            let row = by4 + y as usize;
            if row < 64 {
                recon.scratch.is_coded[0][row] |= mask;
            }
        }
    }

    // LR no-skip mask (luma): set per coded luma TX block for the PC/NS-Wiener
    if eob != -1 {
        let m = &mut recon.lf_mask[recon.lf_idx];
        let mask_idx = (bx4 >> 4) as usize;
        let lr_mask: u16 = (((1u32 << tw4) - 1) << ((bx4 & 0xf) as u32)) as u16;
        for y in 0..th4 as usize {
            let row = by4 + y;
            if row < 64 && mask_idx < 4 {
                m.lr_noskip_mask[row][mask_idx] |= lr_mask;
            }
        }
    }

    let _ = orig_y_mode; // C restores b->y_mode; we never mutated b.
    Ok(())
}

/// Dispatch the resolved intra predictor `m` into `dst` (mirrors the C
#[allow(clippy::too_many_arguments)]
pub(crate) fn dispatch_ipred<BD: BitDepth>(
    exec: &crate::exec_context::ExecContext,
    bd: BD,
    m: u8,
    dst: &mut [BD::Pixel],
    dst_off: usize,
    stride: usize,
    edge: &[BD::Pixel],
    edge_o: usize,
    w: usize,
    h: usize,
    angle: i32,
    max_w: i32,
    max_h: i32,
    ibp_weights: &[[[u8; 16]; 16]; 7],
) {
    if BD::BPC == 8 {
        let dst8: &mut [u8] = BD::Pixel::slice_as_ne_bytes_mut(dst);
        let edge8: &[u8] = BD::Pixel::slice_as_ne_bytes(edge);
        unsafe {
            exec.call_ipred_8bpc(
                m,
                &mut dst8[dst_off..],
                stride,
                edge8,
                edge_o,
                w,
                h,
                angle,
                max_w,
                max_h,
                ibp_weights,
            );
        }
        return;
    }
    if let (Some(dst16), Some(edge16)) = (
        BD::Pixel::try_as_u16_slice_mut(dst),
        BD::Pixel::try_as_u16_slice(edge),
    ) {
        unsafe {
            exec.call_ipred_hbd(
                m,
                bd.bitdepth_max() as u16,
                &mut dst16[dst_off..],
                stride,
                edge16,
                edge_o,
                w,
                h,
                angle,
                max_w,
                max_h,
                ibp_weights,
            );
        }
        return;
    }

    use crate::ipred;
    use crate::levels::*;
    let d = &mut dst[dst_off..];
    match m {
        0 /* DcPred */ => ipred::ipred_dc(bd, d, stride, edge, edge_o, w, h, angle),
        _ if m == DC_128_PRED => ipred::ipred_dc_128(bd, d, stride, w, h),
        _ if m == TOP_DC_PRED => ipred::ipred_dc_top(bd, d, stride, edge, edge_o, w, h, angle),
        _ if m == LEFT_DC_PRED => ipred::ipred_dc_left(bd, d, stride, edge, edge_o, w, h, angle),
        2 /* HorPred */ => ipred::ipred_h(bd, d, stride, edge, edge_o, w, h, angle),
        1 /* VertPred */ => ipred::ipred_v(bd, d, stride, edge, edge_o, w, h, angle),
        12 /* PaethPred */ => ipred::ipred_paeth(bd, d, stride, edge, edge_o, w, h),
        9 /* SmoothPred */ => ipred::ipred_smooth(bd, d, stride, edge, edge_o, w, h),
        10 /* SmoothVPred */ => ipred::ipred_smooth_v(bd, d, stride, edge, edge_o, w, h),
        11 /* SmoothHPred */ => ipred::ipred_smooth_h(bd, d, stride, edge, edge_o, w, h),
        _ if m == Z1_PRED => ipred::ipred_z1(bd, d, stride, edge, edge_o, w, h, angle, max_w, max_h, ibp_weights),
        _ if m == Z2_PRED => ipred::ipred_z2(bd, d, stride, edge, edge_o, w, h, angle, max_w, max_h),
        _ if m == Z3_PRED => ipred::ipred_z3(bd, d, stride, edge, edge_o, w, h, angle, max_w, max_h, ibp_weights),
        _ if m == DIP_PRED => ipred::ipred_dip(bd, d, stride, edge, edge_o, w, h, angle),
        _ => ipred::ipred_dc_128(bd, d, stride, w, h),
    }
}

/// Compound `avg` blend dispatch: NEON 8bpc fast-path (byte-identical) or the
/// generic HBD kernel.
#[inline]
pub(crate) fn mc_avg<BD: crate::pixel::BitDepth>(
    exec: &crate::exec_context::ExecContext,
    bd: BD,
    dst: &mut [BD::Pixel],
    dst_stride: usize,
    tmp1: &[i16],
    tmp2: &[i16],
    w: usize,
    h: usize,
) {
    if BD::BPC == 8 {
        let d8: &mut [u8] = BD::Pixel::slice_as_ne_bytes_mut(dst);
        crate::mc::avg_8bpc(exec, d8, dst_stride, tmp1, tmp2, w, h);
    } else {
        crate::mc::avg(exec, bd, dst, dst_stride, tmp1, tmp2, w, h);
    }
}

#[inline]
#[allow(clippy::too_many_arguments)]
pub(crate) fn mc_w_avg<BD: BitDepth>(
    exec: &crate::exec_context::ExecContext,
    bd: BD,
    dst: &mut [BD::Pixel],
    dst_stride: usize,
    tmp1: &[i16],
    tmp2: &[i16],
    w: usize,
    h: usize,
    weight: i32,
) {
    if BD::BPC == 8 {
        let d8: &mut [u8] = BD::Pixel::slice_as_ne_bytes_mut(dst);
        crate::mc::w_avg_8bpc(exec, d8, dst_stride, tmp1, tmp2, w, h, weight);
    } else {
        crate::mc::w_avg(exec, bd, dst, dst_stride, tmp1, tmp2, w, h, weight);
    }
}

#[inline]
#[allow(clippy::too_many_arguments)]
pub(crate) fn mc_mask<BD: BitDepth>(
    exec: &crate::exec_context::ExecContext,
    bd: BD,
    dst: &mut [BD::Pixel],
    dst_stride: usize,
    tmp1: &[i16],
    tmp2: &[i16],
    w: usize,
    h: usize,
    m: &[u8],
) {
    if BD::BPC == 8 {
        let d8: &mut [u8] = BD::Pixel::slice_as_ne_bytes_mut(dst);
        crate::mc::mask_8bpc(exec, d8, dst_stride, tmp1, tmp2, w, h, m);
    } else {
        crate::mc::mask_fn(exec, bd, dst, dst_stride, tmp1, tmp2, w, h, m);
    }
}

#[inline]
#[allow(clippy::too_many_arguments)]
pub(crate) fn mc_w_mask<BD: BitDepth>(
    exec: &crate::exec_context::ExecContext,
    bd: BD,
    dst: &mut [BD::Pixel],
    dst_stride: usize,
    tmp1: &[i16],
    tmp2: &[i16],
    w: usize,
    h: usize,
    m: &mut [u8],
    mask_stride: usize,
    sign: i32,
    ss_hor: bool,
    ss_ver: bool,
) {
    let _ = exec;
    if BD::BPC == 8 {
        let d8: &mut [u8] = BD::Pixel::slice_as_ne_bytes_mut(dst);
        crate::mc::w_mask_8bpc(
            d8,
            dst_stride,
            tmp1,
            tmp2,
            w,
            h,
            m,
            mask_stride,
            sign,
            ss_hor,
            ss_ver,
        );
    } else {
        crate::mc::w_mask(
            bd,
            dst,
            dst_stride,
            tmp1,
            tmp2,
            w,
            h,
            m,
            mask_stride,
            sign,
            ss_hor,
            ss_ver,
        );
    }
}

/// Bundle of the superblock-decode state that threads unchanged through the
/// `decode_sb` partition recursion. Passing a single `&mut SbCtx` instead of
/// ~16 individual `&mut` arguments removes the per-call pointer crowding (the
/// "pointer congestion" of spilling that many references at every recursive
/// call) and keeps the call sites legible. It is deliberately NOT generic over
/// `BitDepth` -- the bit-depth-dependent `recon` stays a separate argument --
/// so the non-generic `decode_partition` can borrow from it as well.
pub(crate) struct SbCtx<'a, const UPDATE_CDF: bool, M: MsacReader<UPDATE_CDF>> {
    pub(crate) fi: &'a SbFrameInfo,
    pub(crate) bx: &'a mut i32,
    pub(crate) by: &'a mut i32,
    pub(crate) cbx: &'a mut i32,
    pub(crate) cby: &'a mut i32,
    pub(crate) intra_region: &'a mut i32,
    pub(crate) sdp_cfl_disallowed: &'a mut i32,
    pub(crate) a: &'a mut BlockContext,
    pub(crate) l: &'a mut BlockContext,
    pub(crate) msac: &'a mut M,
    pub(crate) cdf_m: &'a mut CdfModeContext,
    /// Inter MV residuals (AVM `nmvc`).
    pub(crate) cdf_mv: &'a mut CdfMvContext,
    /// IntraBC block-vector residuals (AVM `ndvc`).
    pub(crate) cdf_dmv: &'a mut CdfMvContext,
    pub(crate) part_w: &'a mut Vec<u8>,
    pub(crate) part_w_idx: &'a mut usize,
    pub(crate) part_r: &'a [u8],
    pub(crate) part_r_idx: &'a mut usize,
    /// Chroma loop-restoration read to run between the SDP luma and chroma
    /// trees of a 64x64 superblock root (entropy pass only).
    pub(crate) sdp_lr: Option<crate::decode::SdpLrRead<'a>>,
}

pub fn decode_sb<BD: BitDepth, const UPDATE_CDF: bool, M: MsacReader<UPDATE_CDF>>(
    ctx: &mut SbCtx<'_, UPDATE_CDF, M>,
    recon: &mut ReconCtx<BD>,
    pass: u8,
    lbs: BlockSize,
    cbs: BlockSize,
    dir_ptr: &mut i32,
) -> Result<(), ()>
where
    BD::Coef: DecodeCoeff,
{
    let bs = if lbs == BlockSize::Invalid { cbs } else { lbs };
    // bs is always valid for a well-formed partition tree; a malformed stream can
    // leave both block sizes invalid, so abort gracefully rather than panic.
    if bs == BlockSize::Invalid {
        return Err(());
    }

    let b_dim = &BLOCK_DIMENSIONS[bs as u8 as usize];
    let bw4 = b_dim[0] as i32;
    let bh4 = b_dim[1] as i32;
    let hw4 = bw4 >> 1;
    let hh4 = bh4 >> 1;
    let qw4 = hw4 >> 1;
    let qh4 = hh4 >> 1;
    let have_h_split = ctx.fi.bw > *ctx.bx + hw4;
    let have_v_split = ctx.fi.bh > *ctx.by + hh4;
    let cbs_orig = cbs;

    if lbs == BlockSize::Bs64x64
        && cbs == BlockSize::Bs64x64
        && ctx.fi.sdp
        && !ctx.fi.is_inter_or_switch
    {
        let mut dir = 0i32;
        decode_sb(ctx, recon, pass, lbs, BlockSize::Invalid, &mut dir)?;
        if pass & crate::internal::Pass::Entropy as u8 != 0
            && let Some(lr) = ctx.sdp_lr.take()
        {
            crate::decode::read_sb_restoration(
                &mut *ctx.msac,
                &mut *ctx.cdf_m,
                lr.lr_mask,
                lr.bank,
                lr.frame_hdr,
                &lr.geom,
                1..3,
            );
        }
        return decode_sb(ctx, recon, pass, BlockSize::Invalid, cbs, &mut dir);
    }

    let pl = (lbs == BlockSize::Invalid) as usize;
    let pcc = &PARTITION_SUBB[bs as u8 as usize];
    let (bp, cbs) = decode_partition(
        ctx,
        pass,
        lbs,
        cbs,
        bs,
        b_dim,
        bw4,
        bh4,
        qw4,
        qh4,
        have_h_split,
        have_v_split,
        dir_ptr,
    )?;

    if bs == cbs {
        *ctx.cbx = *ctx.bx;
        *ctx.cby = *ctx.by;
    }

    let lim = &PARTITION_LIM[bp as u8 as usize];
    let mut child_dir = ((bw4 <= lim[0] as i32 || bh4 <= lim[1] as i32) as i32) << 24;

    match bp {
        BlockPartition::None => {
            let _b = decode_b(ctx, recon, pass, lbs, cbs)?;
            if pass & (Pass::Entropy as u8) != 0 {
                let bx4 = (*ctx.bx & 63) as usize;
                let by4 = (*ctx.by & 63) as usize;
                if (cbs as i8 | lbs as i8) != BlockSize::Invalid as i8 {
                    // C: case_set(b_dim[2 + i]) writes 1<<b_dim[2+i] bytes (pow2 length),
                    // for both partition[0] and partition[1].
                    memset_pow2(&mut ctx.a.partition[0], bx4, !(b_dim[0] - 1), b_dim[2]);
                    memset_pow2(&mut ctx.a.partition[1], bx4, !(b_dim[0] - 1), b_dim[2]);
                    memset_pow2(&mut ctx.l.partition[0], by4, !(b_dim[1] - 1), b_dim[3]);
                    memset_pow2(&mut ctx.l.partition[1], by4, !(b_dim[1] - 1), b_dim[3]);
                } else {
                    memset_pow2(&mut ctx.a.partition[pl], bx4, !(b_dim[0] - 1), b_dim[2]);
                    memset_pow2(&mut ctx.l.partition[pl], by4, !(b_dim[1] - 1), b_dim[3]);
                }
            }
        }
        BlockPartition::V => {
            if hw4 <= 0 {
                return Err(());
            }
            let sub4 = bs == cbs && (hw4 >> ctx.fi.ss_hor) > 0;
            if !sub4 && pl != 0 {
                return Err(());
            }
            let child_lbs = if pl != 0 {
                BlockSize::Invalid
            } else {
                BlockSize::from_raw(pcc.part[1][0])
            };
            let child_cbs_first = if sub4 {
                BlockSize::from_raw(pcc.part[1][0])
            } else {
                BlockSize::Invalid
            };
            decode_sb(ctx, recon, pass, child_lbs, child_cbs_first, &mut child_dir)?;
            if *ctx.bx + hw4 >= ctx.fi.bw { /* done */
            } else {
                *ctx.bx += hw4;
                let child_cbs_second = if sub4 {
                    BlockSize::from_raw(pcc.part[1][0])
                } else {
                    cbs
                };
                decode_sb(
                    ctx,
                    recon,
                    pass,
                    child_lbs,
                    child_cbs_second,
                    &mut child_dir,
                )?;
                *ctx.bx -= hw4;
            }
        }
        BlockPartition::H => {
            if hh4 <= 0 {
                return Err(());
            }
            let sub4 = bs == cbs && (hh4 >> ctx.fi.ss_ver) > 0;
            if !sub4 && pl != 0 {
                return Err(());
            }
            let child_lbs = if pl != 0 {
                BlockSize::Invalid
            } else {
                BlockSize::from_raw(pcc.part[0][0])
            };
            let child_cbs_first = if sub4 {
                BlockSize::from_raw(pcc.part[0][0])
            } else {
                BlockSize::Invalid
            };
            decode_sb(ctx, recon, pass, child_lbs, child_cbs_first, &mut child_dir)?;
            if *ctx.by + hh4 >= ctx.fi.bh { /* done */
            } else {
                *ctx.by += hh4;
                let child_cbs_second = if sub4 {
                    BlockSize::from_raw(pcc.part[0][0])
                } else {
                    cbs
                };
                decode_sb(
                    ctx,
                    recon,
                    pass,
                    child_lbs,
                    child_cbs_second,
                    &mut child_dir,
                )?;
                *ctx.by -= hh4;
            }
        }
        BlockPartition::Split => {
            // A square SPLIT of a 128×128/256×256 SHARED block. For interior
            // blocks all four children are on-frame; at a right/bottom boundary
            // the off-frame children are skipped (mirroring AVM, which still
            // reads do_square_split there because PARTITION_SPLIT stays eligible
            // even when an implied rect direction is chroma-invalid for the
            // subsampling).
            let sbs = BlockSize::from_raw(pcc.part[0][3]);
            // Monochrome (I400) carries no chroma block (cbs == Invalid): recurse
            // luma-only. Otherwise a SHARED square split must have cbs == lbs and
            // the children carry `sbs` as their (coupled) chroma block size.
            let child_cbs = if cbs == BlockSize::Invalid {
                BlockSize::Invalid
            } else if cbs == lbs {
                sbs
            } else {
                return Err(());
            };
            // top-left (origin is always on-frame)
            decode_sb(ctx, recon, pass, sbs, child_cbs, &mut child_dir)?;
            // top-right
            if *ctx.bx + hw4 < ctx.fi.bw {
                *ctx.bx += hw4;
                decode_sb(ctx, recon, pass, sbs, child_cbs, &mut child_dir)?;
                *ctx.bx -= hw4;
            }
            // bottom row
            if *ctx.by + hh4 < ctx.fi.bh {
                *ctx.by += hh4;
                decode_sb(ctx, recon, pass, sbs, child_cbs, &mut child_dir)?;
                if *ctx.bx + hw4 < ctx.fi.bw {
                    *ctx.bx += hw4;
                    decode_sb(ctx, recon, pass, sbs, child_cbs, &mut child_dir)?;
                    *ctx.bx -= hw4;
                }
                *ctx.by -= hh4;
            }
        }
        BlockPartition::V3 => {
            if qw4 <= 0 || hh4 <= 0 {
                return Err(());
            }
            let sub4 = bs == cbs && (qw4 >> ctx.fi.ss_hor) > 0 && (hh4 >> ctx.fi.ss_ver) > 0;
            if !sub4 && pl != 0 {
                return Err(());
            }
            let p1_0 = BlockSize::from_raw(pcc.part[1][0]);
            let p1_1 = BlockSize::from_raw(pcc.part[1][1]);
            let p1_3 = BlockSize::from_raw(pcc.part[1][3]);
            // AVM only enters the BLOCK_32X8 + PARTITION_VERT_3 multi-ref
            // chroma layout when the parent partition has a non-zero chroma
            // reference offset.  For 4:4:4 and 4:2:2 this parent still produces
            // valid independent chroma children, so treating child 1 as luma-only
            // there consumes too few chroma symbols and desynchronizes entropy.
            // In 4px units AVM's V3 offset test is:
            //   (plane_w < 16px) || (half_plane_h < 4px)
            // which is equivalent to (bw4 >> ss_hor) < 4 ||
            // (bh4 >> ss_ver) < 2.
            let avm_v3_32x8_chroma = cbs != BlockSize::Invalid
                && bs == BlockSize::Bs32x8
                && ((bw4 >> ctx.fi.ss_hor) < 4 || (bh4 >> ctx.fi.ss_ver) < 2);
            let i_3only = cbs == BlockSize::Invalid || (!sub4 && !avm_v3_32x8_chroma);
            let lbs_child = if pl != 0 { BlockSize::Invalid } else { p1_1 };
            let cbs_first = if i_3only { BlockSize::Invalid } else { p1_1 };
            decode_sb(ctx, recon, pass, lbs_child, cbs_first, &mut child_dir)?;
            if *ctx.bx + qw4 >= ctx.fi.bw { /* done */
            } else {
                *ctx.bx += qw4;
                if !i_3only {
                    *ctx.cbx = *ctx.bx;
                }
                let lbs_mid = if pl != 0 { BlockSize::Invalid } else { p1_3 };
                let cbs_mid = if avm_v3_32x8_chroma {
                    BlockSize::Invalid
                } else if sub4 {
                    p1_3
                } else {
                    BlockSize::Invalid
                };
                decode_sb(ctx, recon, pass, lbs_mid, cbs_mid, &mut child_dir)?;
                if *ctx.by + hh4 < ctx.fi.bh {
                    *ctx.by += hh4;
                    let cbs_mid2 = if i_3only {
                        BlockSize::Invalid
                    } else if avm_v3_32x8_chroma {
                        p1_0
                    } else if sub4 {
                        p1_3
                    } else {
                        p1_0
                    };
                    decode_sb(ctx, recon, pass, lbs_mid, cbs_mid2, &mut child_dir)?;
                    *ctx.by -= hh4;
                }
                if *ctx.bx + hw4 >= ctx.fi.bw {
                    *ctx.bx -= qw4;
                } else {
                    *ctx.bx += hw4;
                    let cbs_last = if i_3only { cbs } else { p1_1 };
                    decode_sb(ctx, recon, pass, lbs_child, cbs_last, &mut child_dir)?;
                    *ctx.bx -= 3 * qw4;
                }
            }
        }
        BlockPartition::H3 => {
            if qh4 <= 0 || hw4 <= 0 {
                return Err(());
            }
            let sub4 = bs == cbs && (qh4 >> ctx.fi.ss_ver) > 0 && (hw4 >> ctx.fi.ss_hor) > 0;
            if !sub4 && pl != 0 {
                return Err(());
            }
            let p0_0 = BlockSize::from_raw(pcc.part[0][0]);
            let p0_1 = BlockSize::from_raw(pcc.part[0][1]);
            let p0_3 = BlockSize::from_raw(pcc.part[0][3]);
            // Mirror AVM's BLOCK_8X32 + PARTITION_HORZ_3 multi-ref chroma
            // layout only when AVM's have_nz_chroma_ref_offset() is true.  For
            // 4:4:4 the four H3 children are still independent chroma refs; for
            // subsampled cases where the half-width/quarter-height chroma child
            // would be sub-4, child 1 is luma-only and child 2 carries the
            // combined 8x16 chroma block.  In 4px units AVM's H3 offset test is:
            //   (half_plane_w < 4px) || (plane_h < 16px)
            // equivalent to (bw4 >> ss_hor) < 2 || (bh4 >> ss_ver) < 4.
            let avm_h3_8x32_chroma = cbs != BlockSize::Invalid
                && bs == BlockSize::Bs8x32
                && ((bw4 >> ctx.fi.ss_hor) < 2 || (bh4 >> ctx.fi.ss_ver) < 4);
            let i_3only = cbs == BlockSize::Invalid || (!sub4 && !avm_h3_8x32_chroma);
            let lbs_child = if pl != 0 { BlockSize::Invalid } else { p0_1 };
            let cbs_first = if i_3only { BlockSize::Invalid } else { p0_1 };
            decode_sb(ctx, recon, pass, lbs_child, cbs_first, &mut child_dir)?;
            if *ctx.by + qh4 >= ctx.fi.bh { /* done */
            } else {
                *ctx.by += qh4;
                if !i_3only {
                    *ctx.cby = *ctx.by;
                }
                let lbs_mid = if pl != 0 { BlockSize::Invalid } else { p0_3 };
                let cbs_mid = if avm_h3_8x32_chroma {
                    BlockSize::Invalid
                } else if sub4 {
                    p0_3
                } else {
                    BlockSize::Invalid
                };
                decode_sb(ctx, recon, pass, lbs_mid, cbs_mid, &mut child_dir)?;
                if *ctx.bx + hw4 < ctx.fi.bw {
                    *ctx.bx += hw4;
                    let cbs_mid2 = if i_3only {
                        BlockSize::Invalid
                    } else if avm_h3_8x32_chroma {
                        p0_0
                    } else if sub4 {
                        p0_3
                    } else {
                        p0_0
                    };
                    decode_sb(ctx, recon, pass, lbs_mid, cbs_mid2, &mut child_dir)?;
                    *ctx.bx -= hw4;
                }
                if *ctx.by + hh4 >= ctx.fi.bh {
                    *ctx.by -= qh4;
                } else {
                    *ctx.by += hh4;
                    let cbs_last = if i_3only { cbs } else { p0_1 };
                    decode_sb(ctx, recon, pass, lbs_child, cbs_last, &mut child_dir)?;
                    *ctx.by -= 3 * qh4;
                }
            }
        }
        BlockPartition::V4A | BlockPartition::V4B => {
            let ew4 = qw4 >> 1;
            if ew4 <= 0 {
                return Err(());
            }
            let sub4 = bs == cbs && (ew4 >> ctx.fi.ss_hor) > 0;
            if !sub4 && pl != 0 {
                return Err(());
            }
            let p1_2 = BlockSize::from_raw(pcc.part[1][2]);
            let var = bp as i8 - BlockPartition::V4A as i8;
            let p1_nvar = BlockSize::from_raw(pcc.part[1][(!var & 1) as usize]);
            let p1_var = BlockSize::from_raw(pcc.part[1][var as usize]);
            let lbs_edge = if pl != 0 { BlockSize::Invalid } else { p1_2 };
            let lbs_nvar = if pl != 0 { BlockSize::Invalid } else { p1_nvar };
            let lbs_var = if pl != 0 { BlockSize::Invalid } else { p1_var };

            decode_sb(
                ctx,
                recon,
                pass,
                lbs_edge,
                if sub4 { p1_2 } else { BlockSize::Invalid },
                &mut child_dir,
            )?;
            if *ctx.bx + ew4 >= ctx.fi.bw { /* done */
            } else {
                *ctx.bx += ew4;
                decode_sb(
                    ctx,
                    recon,
                    pass,
                    lbs_nvar,
                    if sub4 { p1_nvar } else { BlockSize::Invalid },
                    &mut child_dir,
                )?;
                let w4a = qw4 << var;
                let w4b = hw4 >> var;
                if *ctx.bx + w4a >= ctx.fi.bw {
                    *ctx.bx -= ew4;
                } else {
                    *ctx.bx += w4a;
                    decode_sb(
                        ctx,
                        recon,
                        pass,
                        lbs_var,
                        if sub4 { p1_var } else { BlockSize::Invalid },
                        &mut child_dir,
                    )?;
                    if *ctx.bx + w4b >= ctx.fi.bw {
                        *ctx.bx -= ew4 + w4a;
                    } else {
                        *ctx.bx += w4b;
                        decode_sb(
                            ctx,
                            recon,
                            pass,
                            lbs_edge,
                            if sub4 { p1_2 } else { cbs },
                            &mut child_dir,
                        )?;
                        *ctx.bx -= 7 * ew4;
                    }
                }
            }
        }
        BlockPartition::H4A | BlockPartition::H4B => {
            let eh4 = qh4 >> 1;
            if eh4 <= 0 {
                return Err(());
            }
            let sub4 = bs == cbs && (eh4 >> ctx.fi.ss_ver) > 0;
            if !sub4 && pl != 0 {
                return Err(());
            }
            let p0_2 = BlockSize::from_raw(pcc.part[0][2]);
            let var = bp as i8 - BlockPartition::H4A as i8;
            let p0_nvar = BlockSize::from_raw(pcc.part[0][(!var & 1) as usize]);
            let p0_var = BlockSize::from_raw(pcc.part[0][var as usize]);
            let lbs_edge = if pl != 0 { BlockSize::Invalid } else { p0_2 };
            let lbs_nvar = if pl != 0 { BlockSize::Invalid } else { p0_nvar };
            let lbs_var = if pl != 0 { BlockSize::Invalid } else { p0_var };

            decode_sb(
                ctx,
                recon,
                pass,
                lbs_edge,
                if sub4 { p0_2 } else { BlockSize::Invalid },
                &mut child_dir,
            )?;
            if *ctx.by + eh4 >= ctx.fi.bh { /* done */
            } else {
                *ctx.by += eh4;
                decode_sb(
                    ctx,
                    recon,
                    pass,
                    lbs_nvar,
                    if sub4 { p0_nvar } else { BlockSize::Invalid },
                    &mut child_dir,
                )?;
                let h4a = qh4 << var;
                let h4b = hh4 >> var;
                if *ctx.by + h4a >= ctx.fi.bh {
                    *ctx.by -= eh4;
                } else {
                    *ctx.by += h4a;
                    decode_sb(
                        ctx,
                        recon,
                        pass,
                        lbs_var,
                        if sub4 { p0_var } else { BlockSize::Invalid },
                        &mut child_dir,
                    )?;
                    if *ctx.by + h4b >= ctx.fi.bh {
                        *ctx.by -= eh4 + h4a;
                    } else {
                        *ctx.by += h4b;
                        decode_sb(
                            ctx,
                            recon,
                            pass,
                            lbs_edge,
                            if sub4 { p0_2 } else { cbs },
                            &mut child_dir,
                        )?;
                        *ctx.by -= 7 * eh4;
                    }
                }
            }
        }
        _ => return Err(()),
    }

    *dir_ptr |= (child_dir & 0xff) << 16;

    if *ctx.intra_region != 0 && cbs_orig != BlockSize::Invalid {
        *ctx.cbx = *ctx.bx;
        *ctx.cby = *ctx.by;
        let _b = decode_b(ctx, recon, pass, BlockSize::Invalid, cbs_orig)?;
        *ctx.intra_region = 0;
    }

    Ok(())
}