still265 0.6.1

Pure-Rust HEVC/H.265 still-image encoder with BPG and HEIC support
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
//! CTU (Coding Tree Unit) and CU (Coding Unit) decoding
//!
//! This module handles the hierarchical quad-tree structure of HEVC:
//! - CTU: Coding Tree Unit (largest block, typically 64x64)
//! - CU: Coding Unit (result of quad-tree split, 8x8 to 64x64)
//! - PU: Prediction Unit (for motion/intra prediction)
//! - TU: Transform Unit (for residual coding)

use alloc::vec;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicU32, Ordering};

/// Set to true to enable verbose debug tracing to stderr
const DEBUG_TRACE: bool = false;

/// Debug print macro gated behind DEBUG_TRACE const
macro_rules! debug_trace {
    ($($arg:tt)*) => {
        #[cfg(feature = "std")]
        if DEBUG_TRACE {
            eprintln!($($arg)*);
        }
    };
}

use super::cabac::{CabacDecoder, ContextModel, INIT_VALUES, context};
use super::debug;
use super::intra;
use super::params::{Pps, Sps};
use super::picture::DecodedFrame;
use super::residual::{self, ScanOrder};
use super::sao::SaoMap;
use super::slice::{IntraPredMode, PartMode, PredMode, SliceHeader};
use super::transform;
use super::transform_simd::add_residual_block_scalar;
#[cfg(target_arch = "x86_64")]
use super::transform_simd::add_residual_block_v3;
use crate::internal::bpg_hevc_decode::error::HevcError;
use archmage::incant;

type Result<T> = core::result::Result<T, HevcError>;

/// Global SE counter for syntax element tracing
pub static SE_COUNTER: AtomicU32 = AtomicU32::new(0);
pub const SE_TRACE_LIMIT: u32 = 0;

/// Diagnostic CU-partition stats (env `BPG_PARTNXN_STATS=1`), used to count how
/// often a decoded stream uses 8x8 `PartNxN`. Indexed by `log2_cb_size`
/// (3..=6 => 8/16/32/64). Cheap relaxed atomics; printed at end of decode.
pub static CU_COUNT_BY_LOG2: [AtomicU32; 7] = [
    AtomicU32::new(0),
    AtomicU32::new(0),
    AtomicU32::new(0),
    AtomicU32::new(0),
    AtomicU32::new(0),
    AtomicU32::new(0),
    AtomicU32::new(0),
];
pub static NXN_8X8_COUNT: AtomicU32 = AtomicU32::new(0);

/// Log a syntax element decode for differential testing.
/// Set SE_TRACE_LIMIT > 0 to enable tracing.
#[allow(clippy::absurd_extreme_comparisons)]
fn se_trace(name: &str, val: i64, cabac: &CabacDecoder) {
    let num = SE_COUNTER.fetch_add(1, Ordering::Relaxed);
    if num < SE_TRACE_LIMIT {
        #[cfg(feature = "std")]
        {
            let (range, _, _) = cabac.get_state_extended();
            let (byte_pos, _, _) = cabac.get_position();
            eprintln!(
                "SE#{} {} val={} range={} byte={}",
                num, name, val, range, byte_pos
            );
        }
    }
    let _ = (name, val, cabac);
}

/// Chroma QP derivation (H.265 §8.6.1). The qPi→QpC mapping of Table 8-10 is
/// applied only for `ChromaArrayType == 1` (4:2:0); for 4:2:2/4:4:4 the spec
/// uses `QpC = Min(qPi, 51)` with no table. Applying the table to 4:4:4 (as the
/// code did before) reconstructs chroma at the wrong QP whenever qPi > 29 —
/// invisible at low QP (the table is identity there) but diverging from a
/// conformant decoder above it.
fn chroma_qp_mapping(qp_i: i32, chroma_array_type: u8) -> i32 {
    if chroma_array_type != 1 {
        return qp_i.min(51);
    }
    // Table 8-10: qPi to QpC mapping (4:2:0 only).
    // For qPi 0-29, QpC = qPi; for qPi 30-57, QpC follows the table.
    static CHROMA_QP_TABLE: [i32; 58] = [
        0, 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, 29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 39, 40, 41,
        42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
    ];
    CHROMA_QP_TABLE[qp_i.clamp(0, 57) as usize]
}

/// Decoding context for a slice
pub struct SliceContext<'a> {
    /// Sequence parameter set
    pub sps: &'a Sps,
    /// Picture parameter set
    pub pps: &'a Pps,
    /// Slice header
    pub header: &'a SliceHeader,
    /// Slice data (EPB-stripped RBSP). Retained so the CABAC engine can be
    /// re-seated at a substream (tile/WPP) start via the entry-point offsets.
    slice_data: &'a [u8],
    /// CABAC decoder
    pub cabac: CabacDecoder<'a>,
    /// Context models
    pub ctx: [ContextModel; context::NUM_CONTEXTS],
    /// Tile partition geometry (single-tile grid when tiles are disabled).
    /// Drives tile-scan decode order and cross-tile neighbour availability.
    pub tile_grid: super::tile::TileGrid,
    /// Current CTB X position (in CTB units)
    pub ctb_x: u32,
    /// Current CTB Y position (in CTB units)
    pub ctb_y: u32,
    /// Current luma QP value
    pub qp_y: i32,
    /// Current Cb QP value
    pub qp_cb: i32,
    /// Current Cr QP value
    pub qp_cr: i32,
    /// Is CU QP delta coded flag
    pub is_cu_qp_delta_coded: bool,
    /// CU QP delta value
    pub cu_qp_delta: i32,
    /// CU transquant bypass flag
    pub cu_transquant_bypass_flag: bool,
    /// Debug flag for current CTU
    debug_ctu: bool,
    /// Debug: track chroma prediction calls
    #[allow(dead_code)]
    chroma_pred_count: u32,
    /// CT depth map for split_cu_flag context derivation (indexed by min_cb_size grid)
    ct_depth_map: Vec<u8>,
    /// Width of ct_depth_map in min_cb_size units
    ct_depth_map_stride: u32,
    /// Intra luma mode map (indexed by min_pu_size grid, stores IntraPredMode as u8)
    /// min_pu_size = min_cb_size / 2, to support NxN PU resolution
    intra_mode_map: Vec<u8>,
    /// Width of intra_mode_map in min_pu_size units
    intra_mode_map_stride: u32,
    /// Intra chroma mode map (indexed by min_pu_size grid, stores IntraPredMode as u8)
    intra_chroma_mode_map: Vec<u8>,
    /// Current CU base position (set at decode_coding_unit start)
    cu_base_x: u32,
    cu_base_y: u32,
    /// Current CU log2 size (set at decode_coding_unit start)
    cu_log2_size: u8,
    /// QP map: stores per-CU QPY values (indexed by min_tb_size grid)
    qp_map: Vec<i8>,
    /// Width of QP map in min_tb_size units
    qp_map_stride: u32,
    /// Current QPY for the current quantization group
    current_qpy: i32,
    /// Last QPY from previous quantization group (for prediction)
    last_qpy_in_prev_qg: i32,
    /// libbpg/FFmpeg rolling QP predictor, updated when a CU ends on a QG boundary.
    qpy_pred: i32,
    /// Whether the next QG is the first QP group in the slice.
    first_qp_group: bool,
    /// Current quantization group position
    current_qg_x: i32,
    current_qg_y: i32,
    /// SAO parameters per CTB
    pub sao_map: SaoMap,
    /// Reusable residual buffer (inverse transform writes all elements, no re-zeroing needed)
    residual_buf: [i16; 1024],
    /// Reusable scaling matrix buffer
    scaling_buf: [u8; 1024],
}

impl<'a> SliceContext<'a> {
    /// Create a new slice context
    pub fn new(
        sps: &'a Sps,
        pps: &'a Pps,
        header: &'a SliceHeader,
        slice_data: &'a [u8],
    ) -> Result<Self> {
        // DEBUG: Print first few bytes of slice data
        debug_trace!(
            "DEBUG: Slice data first 16 bytes: {:02x?}",
            &slice_data[..16.min(slice_data.len())]
        );
        debug_trace!(
            "DEBUG: SPS: {}x{}, ctb_size={}, min_cb_size={}, scaling_list={}",
            sps.pic_width_in_luma_samples,
            sps.pic_height_in_luma_samples,
            sps.ctb_size(),
            1 << sps.log2_min_cb_size(),
            sps.scaling_list_enabled_flag
        );
        debug_trace!(
            "DEBUG: SPS: max_transform_hierarchy_depth_intra={}",
            sps.max_transform_hierarchy_depth_intra
        );
        debug_trace!(
            "DEBUG: SPS: log2_min_tb={}, log2_max_tb={}",
            sps.log2_min_tb_size(),
            sps.log2_max_tb_size()
        );

        let cabac = CabacDecoder::new(slice_data)?;
        let (range, offset) = cabac.get_state();
        debug_trace!(
            "DEBUG: CABAC init state: range={}, offset={}",
            range,
            offset
        );

        // Initialize context models
        let mut ctx = [ContextModel::new(154); context::NUM_CONTEXTS];
        let slice_qp = header.slice_qp_y;

        for (i, init_val) in INIT_VALUES.iter().enumerate() {
            ctx[i].init(*init_val, slice_qp);
        }

        // Calculate chroma QP values (H.265 Table 8-10 and section 8.6.1)
        // qPi_Cb = qP_Y + pps_cb_qp_offset + slice_cb_qp_offset
        // qPi_Cr = qP_Y + pps_cr_qp_offset + slice_cr_qp_offset
        let qp_i_cb = slice_qp + pps.pps_cb_qp_offset as i32 + header.slice_cb_qp_offset as i32;
        let qp_i_cr = slice_qp + pps.pps_cr_qp_offset as i32 + header.slice_cr_qp_offset as i32;

        // Derive chroma QP (H.265 §8.6.1); table only for 4:2:0, else Min(qPi,51).
        let cat = sps.chroma_array_type();
        let qp_cb = chroma_qp_mapping(qp_i_cb.clamp(0, 57), cat);
        let qp_cr = chroma_qp_mapping(qp_i_cr.clamp(0, 57), cat);

        debug_trace!(
            "DEBUG: Chroma QP: qp_y={}, qp_cb={}, qp_cr={}",
            slice_qp,
            qp_cb,
            qp_cr
        );
        debug_trace!(
            "DEBUG: sign_data_hiding_enabled_flag={}",
            pps.sign_data_hiding_enabled_flag
        );
        debug_trace!(
            "DEBUG: tiles_enabled={} entropy_coding_sync={}",
            pps.tiles_enabled_flag,
            pps.entropy_coding_sync_enabled_flag
        );
        // Initialize ct_depth_map for split_cu_flag context derivation
        // Map is in units of min_cb_size (typically 8x8)
        let min_cb_size = 1u32 << sps.log2_min_cb_size();
        let ct_depth_map_stride = sps.pic_width_in_luma_samples.div_ceil(min_cb_size);
        let ct_depth_map_height = sps.pic_height_in_luma_samples.div_ceil(min_cb_size);
        let ct_map_size = (ct_depth_map_stride * ct_depth_map_height) as usize;
        let ct_depth_map = vec![0xFF; ct_map_size];

        // Intra mode map at min_pu_size granularity (= min_cb_size / 2)
        // This supports NxN partition PU-level resolution
        let min_pu_size = (min_cb_size / 2).max(1);
        let intra_mode_map_stride = sps.pic_width_in_luma_samples.div_ceil(min_pu_size);
        let intra_mode_map_height = sps.pic_height_in_luma_samples.div_ceil(min_pu_size);
        let pu_map_size = (intra_mode_map_stride * intra_mode_map_height) as usize;
        let intra_mode_map = vec![IntraPredMode::Dc.as_u8(); pu_map_size];
        let intra_chroma_mode_map = vec![IntraPredMode::Dc.as_u8(); pu_map_size];

        // QP map at min_tb_size granularity
        let min_tb_size = 1u32 << sps.log2_min_tb_size();
        let qp_map_stride = sps.pic_width_in_luma_samples.div_ceil(min_tb_size);
        let qp_map_height = sps.pic_height_in_luma_samples.div_ceil(min_tb_size);
        let qp_map = vec![slice_qp as i8; (qp_map_stride * qp_map_height) as usize];

        let tile_grid = match (pps.tiles_enabled_flag, pps.tile_info.as_ref()) {
            (true, Some(ti)) => super::tile::TileGrid::from_tile_info(
                sps.pic_width_in_ctbs(),
                sps.pic_height_in_ctbs(),
                ti,
            ),
            _ => super::tile::TileGrid::single(sps.pic_width_in_ctbs(), sps.pic_height_in_ctbs()),
        };

        Ok(Self {
            sps,
            pps,
            header,
            slice_data,
            cabac,
            ctx,
            tile_grid,
            ctb_x: 0,
            ctb_y: 0,
            qp_y: slice_qp,
            qp_cb,
            qp_cr,
            is_cu_qp_delta_coded: false,
            cu_qp_delta: 0,
            cu_transquant_bypass_flag: false,
            debug_ctu: false,
            chroma_pred_count: 0,
            ct_depth_map,
            ct_depth_map_stride,
            intra_mode_map,
            intra_mode_map_stride,
            intra_chroma_mode_map,
            cu_base_x: 0,
            cu_base_y: 0,
            cu_log2_size: 0,
            qp_map,
            qp_map_stride,
            current_qpy: slice_qp,
            last_qpy_in_prev_qg: slice_qp,
            qpy_pred: slice_qp,
            first_qp_group: true,
            current_qg_x: -1,
            current_qg_y: -1,
            sao_map: SaoMap::new(sps.pic_width_in_ctbs(), sps.pic_height_in_ctbs()),
            residual_buf: [0i16; 1024],
            scaling_buf: [16u8; 1024],
        })
    }

    /// Reset all CABAC context models to their slice-init state. Called at the
    /// start of each tile (after byte-alignment), since tiles are entropy- and
    /// context-independent per H.265 9.3.1.
    fn reset_contexts(&mut self) {
        let slice_qp = self.header.slice_qp_y;
        for (i, init_val) in INIT_VALUES.iter().enumerate() {
            self.ctx[i].init(*init_val, slice_qp);
        }
    }

    /// Reset the local QP predictor state at tile/substream starts. libbpg keeps
    /// this state in the local CABAC context, so tile-independent substreams must
    /// not carry QG prediction across tile boundaries.
    fn reset_qp_prediction(&mut self) {
        let slice_qp = self.header.slice_qp_y;
        self.current_qpy = slice_qp;
        self.last_qpy_in_prev_qg = slice_qp;
        self.qpy_pred = slice_qp;
        self.first_qp_group = true;
        self.current_qg_x = -1;
        self.current_qg_y = -1;
        self.is_cu_qp_delta_coded = false;
        self.cu_qp_delta = 0;
    }

    /// Map each substream's cumulative entry-point offset (NAL-domain, incl.
    /// emulation-prevention bytes) to a byte offset into the EPB-stripped
    /// `slice_data` (RBSP-domain). The decoder strips all EPBs in one pass, so to
    /// re-seat the CABAC engine at substream `k`'s start we must invert the
    /// encoder's EPB accounting: walk the RBSP advancing a parallel NAL cursor
    /// (which gains an extra byte wherever a `00 00 0x` triple would have had a
    /// `0x03` inserted, with the zero-run carried continuously), and record the
    /// RBSP position each time the NAL cursor reaches a substream boundary. This
    /// mirrors the encoder's `tile_entry_offsets` exactly.
    fn rbsp_substream_starts(slice_data: &[u8], cum_nal: &[u32]) -> Vec<usize> {
        let mut starts = Vec::with_capacity(cum_nal.len());
        let mut zeros = 0u32;
        let mut nal_pos = 0u32;
        let mut rbsp_pos = 0usize;
        let mut next = 0usize;
        while next < cum_nal.len() {
            // Record any boundaries that fall at the current (pre-byte) position.
            while next < cum_nal.len() && nal_pos == cum_nal[next] {
                starts.push(rbsp_pos);
                next += 1;
            }
            if rbsp_pos >= slice_data.len() {
                break;
            }
            let b = slice_data[rbsp_pos];
            // An EPB would have been inserted *before* this byte; it belongs to the
            // substream this byte starts, so count it before testing boundaries on
            // the next iteration.
            if zeros >= 2 && b <= 0x03 {
                nal_pos += 1;
                zeros = 0;
            }
            nal_pos += 1;
            rbsp_pos += 1;
            if b == 0 {
                zeros += 1;
            } else {
                zeros = 0;
            }
        }
        // Any boundaries past the end clamp to the data end (defensive).
        while next < cum_nal.len() {
            starts.push(slice_data.len());
            next += 1;
        }
        starts
    }

    /// Decode all CTUs in the slice
    pub fn decode_slice(&mut self, frame: &mut DecodedFrame) -> Result<()> {
        // Initialize CABAC tracker for debugging
        debug::init_tracker();

        let ctb_size = self.sps.ctb_size();
        let pic_width_in_ctbs = self.sps.pic_width_in_ctbs();
        let pic_height_in_ctbs = self.sps.pic_height_in_ctbs();
        let wpp = self.pps.entropy_coding_sync_enabled_flag;

        // Start from slice segment address
        let start_addr = self.header.slice_segment_address;

        let mut ctu_count = 0u32;
        let total_ctus = pic_width_in_ctbs * pic_height_in_ctbs;
        let tiles_enabled = self.pps.tiles_enabled_flag;

        // Iterate CTUs in tile-scan order. When tiles are disabled the grid is a
        // single identity-mapped tile, so this is plain raster order.
        let mut ctb_addr_ts = self.tile_grid.ctb_addr_rs_to_ts[start_addr as usize];

        // WPP: saved context models from CTB column 1 of previous row
        let mut wpp_saved_ctx: Option<[super::cabac::ContextModel; context::NUM_CONTEXTS]> = None;

        // Tile/WPP substream starts (RBSP-domain), and the next one to consume.
        // We seek the engine via entry-point offsets rather than relying on the
        // previous engine position (CABAC reads ahead, so that position is not
        // necessarily the substream boundary).
        let sub_starts = if tiles_enabled || wpp {
            Self::rbsp_substream_starts(self.slice_data, &self.header.entry_point_offsets)
        } else {
            Vec::new()
        };
        let mut entry_idx = 0usize;

        loop {
            let ctb_addr_rs = self.tile_grid.ctb_addr_ts_to_rs[ctb_addr_ts as usize];
            self.ctb_y = ctb_addr_rs / pic_width_in_ctbs;
            self.ctb_x = ctb_addr_rs % pic_width_in_ctbs;

            // WPP: at start of each new row (ctb_x==0, ctb_y>0), restore saved context
            if wpp
                && self.ctb_x == 0
                && self.ctb_y > 0
                && pic_width_in_ctbs > 1
                && let Some(saved) = wpp_saved_ctx
            {
                self.ctx = saved;
            }

            // Decode one CTU
            let x_ctb = self.ctb_x * ctb_size;
            let y_ctb = self.ctb_y * ctb_size;

            // Track CTU position for debugging
            let (byte_pos, _, _) = self.cabac.get_position();
            debug::track_ctu_start(ctu_count, byte_pos);

            // DEBUG: Print CTU state periodically
            if ctu_count.is_multiple_of(50) || ctu_count <= 3 {
                let (range, offset) = self.cabac.get_state();
                debug_trace!(
                    "DEBUG: CTU {} byte={} cabac=({},{}) x={} y={}",
                    ctu_count,
                    byte_pos,
                    range,
                    offset,
                    self.ctb_x,
                    self.ctb_y
                );
            }
            // Enable debug for CTU 1 (where first large coefficient occurs)
            self.debug_ctu = ctu_count == 1;

            self.decode_ctu(x_ctb, y_ctb, frame)?;
            ctu_count += 1;

            // WPP: save context models after CTB column 1
            if wpp && self.ctb_x == 1 && self.ctb_y < pic_height_in_ctbs - 1 {
                wpp_saved_ctx = Some(self.ctx);
            }

            // Check for end of slice segment
            let end_of_slice = self.cabac.decode_terminate()?;
            se_trace("end_of_slice", end_of_slice as i64, &self.cabac);
            if end_of_slice != 0 {
                debug_trace!(
                    "DEBUG: end_of_slice after CTU {}, decoded {}/{} CTUs",
                    ctu_count,
                    ctu_count,
                    total_ctus
                );
                break;
            }

            // Advance in tile-scan order.
            ctb_addr_ts += 1;
            if ctb_addr_ts >= total_ctus {
                break;
            }
            let next_rs = self.tile_grid.ctb_addr_ts_to_rs[ctb_addr_ts as usize];
            let next_x = next_rs % pic_width_in_ctbs;
            let next_y = next_rs / pic_width_in_ctbs;

            // Substream boundary handling. At a tile boundary, consume
            // end_of_sub_stream_one_bit, byte-align, and reset CABAC contexts to
            // slice-init (each tile is entropy-independent). At a WPP row
            // boundary (tiles off), consume end_of_sub_stream and reinit without
            // resetting contexts (the saved row context is restored at row start).
            let new_tile = tiles_enabled
                && !self
                    .tile_grid
                    .same_tile_ctb(self.ctb_x, self.ctb_y, next_x, next_y);
            if new_tile {
                // Seek the CABAC engine to the next tile's substream start (the
                // authoritative boundary from the entry-point offsets) and reset
                // contexts to slice-init (tiles are entropy-independent).
                let _eoss = self.cabac.decode_terminate()?;
                if let Some(&start) = sub_starts.get(entry_idx) {
                    self.cabac = CabacDecoder::new(&self.slice_data[start..])?;
                } else {
                    // No entry-point offset available (malformed/legacy): fall back
                    // to in-place reinit so we at least keep advancing.
                    self.cabac.reinit();
                }
                entry_idx += 1;
                self.reset_contexts();
                self.reset_qp_prediction();
                if std::env::var_os("BPG_TILE_DEBUG").is_some() {
                    let (bp, _, _) = self.cabac.get_position();
                    eprintln!(
                        "DEC_TILE: enter tile at rs=({},{}) ts={} rbsp_start={:?} cabac_byte_pos={}",
                        next_x,
                        next_y,
                        ctb_addr_ts,
                        sub_starts.get(entry_idx - 1),
                        bp
                    );
                }
            } else if wpp && next_y != self.ctb_y {
                let _eoss = self.cabac.decode_terminate()?;
                if let Some(&start) = sub_starts.get(entry_idx) {
                    self.cabac = CabacDecoder::new(&self.slice_data[start..])?;
                } else {
                    self.cabac.reinit();
                }
                entry_idx += 1;
            }
        }

        if DEBUG_TRACE {
            debug::print_tracker_summary();
        }

        #[cfg(feature = "std")]
        if std::env::var("BPG_PARTNXN_STATS").is_ok() {
            let c8 = CU_COUNT_BY_LOG2[3].load(Ordering::Relaxed);
            let c16 = CU_COUNT_BY_LOG2[4].load(Ordering::Relaxed);
            let c32 = CU_COUNT_BY_LOG2[5].load(Ordering::Relaxed);
            let c64 = CU_COUNT_BY_LOG2[6].load(Ordering::Relaxed);
            let nxn = NXN_8X8_COUNT.load(Ordering::Relaxed);
            let pct = if c8 > 0 {
                100.0 * nxn as f64 / c8 as f64
            } else {
                0.0
            };
            eprintln!(
                "PARTNXN_STATS cu8={c8} cu16={c16} cu32={c32} cu64={c64} \
                 partnxn_8x8={nxn} ({pct:.1}% of 8x8 CUs)"
            );
        }

        Ok(())
    }

    /// Decode a single CTU (Coding Tree Unit)
    fn decode_ctu(&mut self, x_ctb: u32, y_ctb: u32, frame: &mut DecodedFrame) -> Result<()> {
        let log2_ctb_size = self.sps.log2_ctb_size();

        // Reset per-CTU state
        if self.pps.cu_qp_delta_enabled_flag {
            self.is_cu_qp_delta_coded = false;
            self.cu_qp_delta = 0;
        }

        // Decode SAO syntax elements (must consume from CABAC stream even if not applied)
        if self.header.slice_sao_luma_flag || self.header.slice_sao_chroma_flag {
            self.decode_sao(x_ctb, y_ctb)?;
        }

        // Decode the coding quadtree
        self.decode_coding_quadtree(x_ctb, y_ctb, log2_ctb_size, 0, frame)
    }

    /// Decode SAO (Sample Adaptive Offset) syntax elements from CABAC stream
    /// and store them in the SAO map for later filtering.
    fn decode_sao(&mut self, x_ctb_pixels: u32, y_ctb_pixels: u32) -> Result<()> {
        let ctb_size = self.sps.ctb_size();
        let x_ctb = x_ctb_pixels / ctb_size;
        let y_ctb = y_ctb_pixels / ctb_size;

        let mut sao_merge_left_flag = false;
        let mut sao_merge_up_flag = false;

        // sao_merge_left_flag
        if x_ctb > 0 {
            let pic_width_ctbs = self.sps.pic_width_in_ctbs();
            let ctb_addr_rs = y_ctb * pic_width_ctbs + x_ctb;
            let slice_addr_rs = 0u32;
            let left_in_slice = ctb_addr_rs > slice_addr_rs
                && self.tile_grid.same_tile_ctb(x_ctb - 1, y_ctb, x_ctb, y_ctb);
            if left_in_slice {
                let ctx_idx = context::SAO_MERGE_FLAG;
                sao_merge_left_flag = self.cabac.decode_bin(&mut self.ctx[ctx_idx])? != 0;
                se_trace("sao_merge_left", sao_merge_left_flag as i64, &self.cabac);
            }
        }

        // sao_merge_up_flag
        if y_ctb > 0 && !sao_merge_left_flag {
            let pic_width_ctbs = self.sps.pic_width_in_ctbs();
            let ctb_addr_rs = y_ctb * pic_width_ctbs + x_ctb;
            let slice_addr_rs = 0u32;
            let up_in_slice = ctb_addr_rs >= pic_width_ctbs + slice_addr_rs
                && self.tile_grid.same_tile_ctb(x_ctb, y_ctb - 1, x_ctb, y_ctb);
            if up_in_slice {
                let ctx_idx = context::SAO_MERGE_FLAG;
                sao_merge_up_flag = self.cabac.decode_bin(&mut self.ctx[ctx_idx])? != 0;
                se_trace("sao_merge_up", sao_merge_up_flag as i64, &self.cabac);
            }
        }

        let sao_info = if sao_merge_left_flag {
            *self.sao_map.get(x_ctb - 1, y_ctb)
        } else if sao_merge_up_flag {
            *self.sao_map.get(x_ctb, y_ctb - 1)
        } else {
            let mut info = super::sao::SaoInfo::default();
            let is_mono = self.sps.chroma_format_idc == 0;
            let n_chroma = if is_mono { 1 } else { 3 };

            #[allow(unused_assignments)]
            let mut sao_type_idx_luma = 0u8;
            let mut sao_type_idx_chroma = 0u8;
            let mut eo_class_chroma = 0u8;

            for c_idx in 0..n_chroma {
                let should_decode = (self.header.slice_sao_luma_flag && c_idx == 0)
                    || (self.header.slice_sao_chroma_flag && c_idx > 0);

                if !should_decode {
                    continue;
                }

                let sao_type_idx = if c_idx == 0 {
                    sao_type_idx_luma = self.decode_sao_type_idx()?;
                    se_trace("sao_type_idx_luma", sao_type_idx_luma as i64, &self.cabac);
                    sao_type_idx_luma
                } else if c_idx == 1 {
                    sao_type_idx_chroma = self.decode_sao_type_idx()?;
                    se_trace(
                        "sao_type_idx_chroma",
                        sao_type_idx_chroma as i64,
                        &self.cabac,
                    );
                    sao_type_idx_chroma
                } else {
                    sao_type_idx_chroma
                };

                info.sao_type_idx[c_idx] = sao_type_idx;

                if sao_type_idx != 0 {
                    let bit_depth = if c_idx == 0 {
                        self.sps.bit_depth_y() as u32
                    } else {
                        self.sps.bit_depth_c() as u32
                    };
                    let c_max = (1u32 << (bit_depth.min(10) - 5)) - 1;
                    let offset_scale = 1i32 << (bit_depth.saturating_sub(bit_depth.min(10)));

                    let mut offsets_abs = [0u32; 4];
                    for elem in &mut offsets_abs {
                        *elem = self.decode_cabac_tu_bypass(c_max)?;
                        se_trace("sao_offset_abs", *elem as i64, &self.cabac);
                    }

                    if sao_type_idx == 1 {
                        // Band offset: decode signs + band position
                        let mut signed_offsets = [0i8; 4];
                        for i in 0..4 {
                            if offsets_abs[i] != 0 {
                                let sign = self.cabac.decode_bypass()?;
                                se_trace("sao_offset_sign", sign as i64, &self.cabac);
                                let val = (offsets_abs[i] as i32 * offset_scale) as i8;
                                signed_offsets[i] = if sign != 0 { -val } else { val };
                            }
                        }
                        info.sao_offset_val[c_idx] = signed_offsets;

                        let band_pos = self.cabac.decode_bypass_bits(5)?;
                        se_trace("sao_band_position", band_pos as i64, &self.cabac);
                        info.sao_band_position[c_idx] = band_pos as u8;
                    } else {
                        // Edge offset: store absolute values (sign applied during filtering)
                        for (i, &offset) in offsets_abs.iter().enumerate() {
                            info.sao_offset_val[c_idx][i] = (offset as i32 * offset_scale) as i8;
                        }

                        if c_idx <= 1 {
                            let eo_class = self.cabac.decode_bypass_bits(2)?;
                            se_trace("sao_eo_class", eo_class as i64, &self.cabac);
                            if c_idx == 0 {
                                info.sao_eo_class[0] = eo_class as u8;
                            } else {
                                eo_class_chroma = eo_class as u8;
                                info.sao_eo_class[1] = eo_class_chroma;
                            }
                        } else {
                            info.sao_eo_class[2] = eo_class_chroma;
                        }
                    }
                }
            }
            info
        };

        *self.sao_map.get_mut(x_ctb, y_ctb) = sao_info;
        Ok(())
    }

    /// Decode sao_type_idx: context bin + optional bypass bin
    fn decode_sao_type_idx(&mut self) -> Result<u8> {
        let ctx_idx = context::SAO_TYPE_IDX;
        let bit0 = self.cabac.decode_bin(&mut self.ctx[ctx_idx])?;
        if bit0 == 0 {
            Ok(0)
        } else {
            let bit1 = self.cabac.decode_bypass()?;
            if bit1 == 0 { Ok(1) } else { Ok(2) }
        }
    }

    /// Decode truncated unary with bypass bins (for sao_offset_abs)
    fn decode_cabac_tu_bypass(&mut self, c_max: u32) -> Result<u32> {
        for i in 0..c_max {
            let bit = self.cabac.decode_bypass()?;
            if bit == 0 {
                return Ok(i);
            }
        }
        Ok(c_max)
    }

    /// Decode coding quadtree recursively
    fn decode_coding_quadtree(
        &mut self,
        x0: u32,
        y0: u32,
        log2_cb_size: u8,
        ct_depth: u8,
        frame: &mut DecodedFrame,
    ) -> Result<()> {
        let cb_size = 1u32 << log2_cb_size;
        let pic_width = self.sps.pic_width_in_luma_samples;
        let pic_height = self.sps.pic_height_in_luma_samples;
        let log2_min_cb_size = self.sps.log2_min_cb_size();

        // Determine if we need to split
        let split_flag = if x0 + cb_size <= pic_width
            && y0 + cb_size <= pic_height
            && log2_cb_size > log2_min_cb_size
        {
            // Decode split_cu_flag
            let flag = self.decode_split_cu_flag(x0, y0, ct_depth)?;
            if self.debug_ctu {
                let (r, o) = self.cabac.get_state();
                debug_trace!(
                    "  CTU37: split_cu_flag at ({},{}) depth={} log2={} → {} (r={},o={})",
                    x0,
                    y0,
                    ct_depth,
                    log2_cb_size,
                    flag,
                    r,
                    o
                );
            }
            flag
        } else if log2_cb_size > log2_min_cb_size {
            // Must split if partially outside picture
            if self.debug_ctu {
                debug_trace!(
                    "  CTU37: forced split at ({},{}) depth={} - outside picture",
                    x0,
                    y0,
                    ct_depth
                );
            }
            true
        } else {
            // At minimum size, don't split
            if self.debug_ctu {
                debug_trace!(
                    "  CTU37: no split at ({},{}) depth={} - min size",
                    x0,
                    y0,
                    ct_depth
                );
            }
            false
        };

        // Handle QP delta depth: reset at quantization group boundaries
        // Log2MinCuQpDeltaSize = Log2CtbSizeY - diff_cu_qp_delta_depth
        if self.pps.cu_qp_delta_enabled_flag
            && log2_cb_size >= self.sps.log2_ctb_size() - self.pps.diff_cu_qp_delta_depth
        {
            self.is_cu_qp_delta_coded = false;
            self.cu_qp_delta = 0;
        }

        if split_flag {
            let half = cb_size / 2;
            let x1 = x0 + half;
            let y1 = y0 + half;

            // Decode four sub-CUs
            self.decode_coding_quadtree(x0, y0, log2_cb_size - 1, ct_depth + 1, frame)?;

            if x1 < pic_width {
                self.decode_coding_quadtree(x1, y0, log2_cb_size - 1, ct_depth + 1, frame)?;
            }

            if y1 < pic_height {
                self.decode_coding_quadtree(x0, y1, log2_cb_size - 1, ct_depth + 1, frame)?;
            }

            if x1 < pic_width && y1 < pic_height {
                self.decode_coding_quadtree(x1, y1, log2_cb_size - 1, ct_depth + 1, frame)?;
            }

            let qp_block_mask =
                (1u32 << (self.sps.log2_ctb_size() - self.pps.diff_cu_qp_delta_depth)) - 1;
            if ((x0 + cb_size) & qp_block_mask) == 0 && ((y0 + cb_size) & qp_block_mask) == 0 {
                self.qpy_pred = self.current_qpy;
            }
        } else {
            // Decode the coding unit
            self.decode_coding_unit(x0, y0, log2_cb_size, ct_depth, frame)?;
        }

        Ok(())
    }

    /// Get ctDepth at a pixel position (returns 0xFF if not yet decoded)
    fn get_ct_depth(&self, x: u32, y: u32) -> u8 {
        let min_cb_size = 1u32 << self.sps.log2_min_cb_size();
        let map_x = x / min_cb_size;
        let map_y = y / min_cb_size;

        if map_x >= self.ct_depth_map_stride
            || map_y * self.ct_depth_map_stride + map_x >= self.ct_depth_map.len() as u32
        {
            return 0xFF; // Out of bounds
        }

        self.ct_depth_map[(map_y * self.ct_depth_map_stride + map_x) as usize]
    }

    /// Set ctDepth for a CU region
    fn set_ct_depth(&mut self, x0: u32, y0: u32, log2_cb_size: u8, ct_depth: u8) {
        let min_cb_size = 1u32 << self.sps.log2_min_cb_size();
        let cb_size = 1u32 << log2_cb_size;

        // Fill the ct_depth_map for this CU region
        let start_x = x0 / min_cb_size;
        let start_y = y0 / min_cb_size;
        let num_blocks = cb_size / min_cb_size;

        for dy in 0..num_blocks {
            for dx in 0..num_blocks {
                let map_x = start_x + dx;
                let map_y = start_y + dy;
                if map_x < self.ct_depth_map_stride {
                    let idx = (map_y * self.ct_depth_map_stride + map_x) as usize;
                    if idx < self.ct_depth_map.len() {
                        self.ct_depth_map[idx] = ct_depth;
                    }
                }
            }
        }
    }

    /// Check if a neighbor position is available (within picture bounds)
    fn is_neighbor_available(&self, x: i32, y: i32) -> bool {
        x >= 0
            && y >= 0
            && (x as u32) < self.sps.pic_width_in_luma_samples
            && (y as u32) < self.sps.pic_height_in_luma_samples
    }

    /// Whether luma pixel `(ax, ay)` lies in the same tile as `(bx, by)`. Always
    /// true when tiles are disabled.
    fn same_tile_px(&self, ax: u32, ay: u32, bx: u32, by: u32) -> bool {
        self.tile_grid
            .same_tile_px(ax, ay, bx, by, self.sps.log2_ctb_size())
    }

    /// Decode split_cu_flag using CABAC
    fn decode_split_cu_flag(&mut self, x0: u32, y0: u32, ct_depth: u8) -> Result<bool> {
        // Context selection based on neighboring CU depths (H.265 9.3.4.2.2)
        // condTermL: 1 if left neighbor has larger depth (was split more)
        // condTermA: 1 if above neighbor has larger depth
        // ctxInc = condTermL + condTermA

        // Neighbours across a tile boundary are unavailable for context
        // derivation (H.265 6.4.1 / 9.3.4.2.2).
        let available_l = self.is_neighbor_available(x0 as i32 - 1, y0 as i32)
            && self.same_tile_px(x0 - 1, y0, x0, y0);
        let available_a = self.is_neighbor_available(x0 as i32, y0 as i32 - 1)
            && self.same_tile_px(x0, y0 - 1, x0, y0);

        let mut cond_l = 0;
        let mut cond_a = 0;

        if available_l {
            let depth_l = self.get_ct_depth(x0 - 1, y0);
            if depth_l != 0xFF && depth_l > ct_depth {
                cond_l = 1;
            }
        }

        if available_a {
            let depth_a = self.get_ct_depth(x0, y0 - 1);
            if depth_a != 0xFF && depth_a > ct_depth {
                cond_a = 1;
            }
        }

        let ctx_idx = context::SPLIT_CU_FLAG + cond_l + cond_a;
        let bin = self.cabac.decode_bin(&mut self.ctx[ctx_idx])?;
        se_trace("split_cu_flag", bin as i64, &self.cabac);

        Ok(bin != 0)
    }

    /// Decode a coding unit
    fn decode_coding_unit(
        &mut self,
        x0: u32,
        y0: u32,
        log2_cb_size: u8,
        ct_depth: u8,
        frame: &mut DecodedFrame,
    ) -> Result<()> {
        let cb_size = 1u32 << log2_cb_size;
        let _ = cb_size; // Used in PartNxN

        // Track CU base position for transform unit QP derivation
        self.cu_base_x = x0;
        self.cu_base_y = y0;
        self.cu_log2_size = log2_cb_size;

        // Decode quantization parameters at CU start (H.265 8.6.1)
        self.decode_quantization_parameters(x0, y0, log2_cb_size);
        self.store_qpy(x0, y0, log2_cb_size, self.current_qpy);

        // Set ct_depth for this CU (used by split_cu_flag context derivation)
        self.set_ct_depth(x0, y0, log2_cb_size, ct_depth);

        // For I-slices, prediction mode is always INTRA
        let pred_mode = PredMode::Intra;

        // Decode transquant_bypass_flag if enabled
        self.cu_transquant_bypass_flag = if self.pps.transquant_bypass_enabled_flag {
            let ctx_idx = context::CU_TRANSQUANT_BYPASS_FLAG;
            self.cabac.decode_bin(&mut self.ctx[ctx_idx])? != 0
        } else {
            false
        };

        // Decode partition mode
        let part_mode = if log2_cb_size == self.sps.log2_min_cb_size() {
            // At minimum size, can be 2Nx2N or NxN
            let pm = self.decode_part_mode(pred_mode, log2_cb_size)?;
            // Debug: log part_mode for first CTU (and count NxN)
            if pm == PartMode::PartNxN {
                static NXN_COUNT: core::sync::atomic::AtomicU32 =
                    core::sync::atomic::AtomicU32::new(0);
                let count = NXN_COUNT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
                if count == 0 || x0 < 64 && y0 < 64 {
                    let (r, o) = self.cabac.get_state();
                    debug_trace!(
                        "DEBUG: part_mode at ({},{}) log2={}: {:?} cabac=({},{})",
                        x0,
                        y0,
                        log2_cb_size,
                        pm,
                        r,
                        o
                    );
                }
            }
            if self.debug_ctu {
                let (r, o) = self.cabac.get_state();
                debug_trace!(
                    "  CTU37: CU at ({},{}) log2={} part_mode={:?} (r={},o={})",
                    x0,
                    y0,
                    log2_cb_size,
                    pm,
                    r,
                    o
                );
            }
            pm
        } else {
            // Larger sizes are always 2Nx2N for intra
            if self.debug_ctu {
                debug_trace!(
                    "  CTU37: CU at ({},{}) log2={} part_mode=2Nx2N (implicit)",
                    x0,
                    y0,
                    log2_cb_size
                );
            }
            PartMode::Part2Nx2N
        };

        // Diagnostic: count CU sizes and 8x8 PartNxN usage (env-gated print at
        // slice end). Relaxed atomics, negligible cost.
        CU_COUNT_BY_LOG2[(log2_cb_size as usize).min(6)].fetch_add(1, Ordering::Relaxed);
        if part_mode == PartMode::PartNxN {
            NXN_8X8_COUNT.fetch_add(1, Ordering::Relaxed);
        }

        // Decode prediction info and get intra modes for scan order
        let (intra_luma_mode, intra_chroma_mode) = match part_mode {
            PartMode::Part2Nx2N => {
                // Single PU covering entire CU
                let modes = self.decode_intra_prediction(x0, y0, log2_cb_size, true, frame)?;
                if super::debug::decision_log_active() {
                    super::debug::log_pu(super::debug::PuRecord {
                        x: x0,
                        y: y0,
                        log2_size: log2_cb_size,
                        luma_mode: modes.0.as_u8(),
                        chroma_mode: modes.1.as_u8(),
                    });
                }
                if self.debug_ctu {
                    let (r, o) = self.cabac.get_state();
                    debug_trace!(
                        "  CTU37: After intra_prediction at (1144,120): mode={:?} (r={},o={}) bits={}",
                        modes,
                        r,
                        o,
                        self.cabac.get_position().2
                    );
                }
                modes
            }
            PartMode::PartNxN => {
                // Four PUs (only at minimum CU size for intra)
                // For 4:2:0, all four 4x4 luma PUs share one 4x4 chroma block
                let half = cb_size / 2;
                let log2_pu_size = log2_cb_size - 1;

                // Per H.265 spec 7.3.8.5 and libde265 slice.cc:4385-4458:
                // FIRST pass: decode ALL prev_intra_luma_pred_flag (context-coded bins)
                let prev_flags = [
                    self.decode_prev_intra_luma_pred_flag()?,
                    self.decode_prev_intra_luma_pred_flag()?,
                    self.decode_prev_intra_luma_pred_flag()?,
                    self.decode_prev_intra_luma_pred_flag()?,
                ];

                // SECOND pass: decode mpm_idx/rem (bypass bins) and store IMMEDIATELY
                // per libde265: each PU mode stored before next PU's neighbor lookup
                let luma_mode_0 = self.derive_intra_luma_mode(x0, y0, prev_flags[0])?;
                self.store_intra_mode(x0, y0, log2_pu_size, luma_mode_0);

                let luma_mode_1 = self.derive_intra_luma_mode(x0 + half, y0, prev_flags[1])?;
                self.store_intra_mode(x0 + half, y0, log2_pu_size, luma_mode_1);

                let luma_mode_2 = self.derive_intra_luma_mode(x0, y0 + half, prev_flags[2])?;
                self.store_intra_mode(x0, y0 + half, log2_pu_size, luma_mode_2);

                let luma_mode_3 =
                    self.derive_intra_luma_mode(x0 + half, y0 + half, prev_flags[3])?;
                self.store_intra_mode(x0 + half, y0 + half, log2_pu_size, luma_mode_3);

                // Chroma modes. Per H.265 7.3.8.5, intra_chroma_pred_mode is
                // signaled once per PU only when ChromaArrayType == 3 (4:4:4);
                // for 4:2:0/4:2:2 a single chroma mode covers the whole CU.
                let chroma_mode = if self.sps.chroma_array_type() == 0 {
                    IntraPredMode::Dc
                } else if self.sps.chroma_array_type() == 3 {
                    let half = cb_size / 2;
                    let cm0 = self.decode_intra_chroma_mode(luma_mode_0)?;
                    self.store_intra_chroma_mode(x0, y0, log2_pu_size, cm0);
                    let cm1 = self.decode_intra_chroma_mode(luma_mode_1)?;
                    self.store_intra_chroma_mode(x0 + half, y0, log2_pu_size, cm1);
                    let cm2 = self.decode_intra_chroma_mode(luma_mode_2)?;
                    self.store_intra_chroma_mode(x0, y0 + half, log2_pu_size, cm2);
                    let cm3 = self.decode_intra_chroma_mode(luma_mode_3)?;
                    self.store_intra_chroma_mode(x0 + half, y0 + half, log2_pu_size, cm3);
                    cm0
                } else {
                    // Single chroma mode (derived from the first luma mode if DM).
                    let cm = self.decode_intra_chroma_mode(luma_mode_0)?;
                    self.store_intra_chroma_mode(x0, y0, log2_cb_size, cm);
                    cm
                };

                // NOTE: Prediction is NOT done here. It happens in decode_transform_unit_leaf
                // and the 8x8→4x4 chroma split handler, so each TU is predicted →
                // reconstructed before the next TU reads its neighbors.

                if super::debug::decision_log_active() {
                    let cm = chroma_mode.as_u8();
                    for (px, py, lm) in [
                        (x0, y0, luma_mode_0),
                        (x0 + half, y0, luma_mode_1),
                        (x0, y0 + half, luma_mode_2),
                        (x0 + half, y0 + half, luma_mode_3),
                    ] {
                        super::debug::log_pu(super::debug::PuRecord {
                            x: px,
                            y: py,
                            log2_size: log2_pu_size,
                            luma_mode: lm.as_u8(),
                            chroma_mode: cm,
                        });
                    }
                }

                (luma_mode_0, chroma_mode)
            }
            _ => {
                // Other partition modes not used for intra
                return Err(HevcError::InvalidBitstream("invalid intra partition mode"));
            }
        };

        // Decode rqt_root_cbf (residual quad-tree coded block flag)
        // For intra, this is always coded (not signaled, assumed 1)
        // unless transquant_bypass is enabled
        if !self.cu_transquant_bypass_flag {
            // Decode transform tree
            let intra_split_flag = part_mode == PartMode::PartNxN;
            self.decode_transform_tree(
                x0,
                y0,
                log2_cb_size,
                0, // trafo_depth
                intra_luma_mode,
                intra_chroma_mode,
                intra_split_flag,
                frame,
            )?;

            if self.debug_ctu {
                let (r, o) = self.cabac.get_state();
                debug_trace!(
                    "  CTU37: After transform_tree at ({},{}) log2={} (r={},o={})",
                    x0,
                    y0,
                    log2_cb_size,
                    r,
                    o
                );
            }
        }

        let qp_block_mask =
            (1u32 << (self.sps.log2_ctb_size() - self.pps.diff_cu_qp_delta_depth)) - 1;
        if ((x0 + cb_size) & qp_block_mask) == 0 && ((y0 + cb_size) & qp_block_mask) == 0 {
            self.qpy_pred = self.current_qpy;
        }

        Ok(())
    }

    /// Decode transform tree recursively
    #[allow(clippy::too_many_arguments)]
    fn decode_transform_tree(
        &mut self,
        x0: u32,
        y0: u32,
        log2_size: u8,
        trafo_depth: u8,
        intra_luma_mode: IntraPredMode,
        intra_chroma_mode: IntraPredMode,
        intra_split_flag: bool,
        frame: &mut DecodedFrame,
    ) -> Result<()> {
        // For 4:2:0, start with root having chroma responsibility
        self.decode_transform_tree_inner(
            x0,
            y0,
            log2_size,
            trafo_depth,
            intra_luma_mode,
            intra_chroma_mode,
            intra_split_flag,
            true,
            true,
            frame,
        )
    }

    /// Inner transform tree decoding
    /// cbf_cb_parent/cbf_cr_parent: whether parent says chroma has residuals (or true at root)
    #[allow(clippy::too_many_arguments)]
    fn decode_transform_tree_inner(
        &mut self,
        x0: u32,
        y0: u32,
        log2_size: u8,
        trafo_depth: u8,
        intra_luma_mode: IntraPredMode,
        intra_chroma_mode: IntraPredMode,
        intra_split_flag: bool,
        cbf_cb_parent: bool,
        cbf_cr_parent: bool,
        frame: &mut DecodedFrame,
    ) -> Result<()> {
        // Per H.265: MaxTrafoDepth = max_transform_hierarchy_depth_intra + IntraSplitFlag
        let max_trafo_depth =
            self.sps.max_transform_hierarchy_depth_intra + if intra_split_flag { 1 } else { 0 };
        let log2_min_trafo_size = self.sps.log2_min_tb_size();
        let log2_max_trafo_size = self.sps.log2_max_tb_size();

        // Per HEVC spec 7.3.8.7, the order is:
        // 1. split_transform_flag (if applicable)
        // 2. cbf_cb (if applicable)
        // 3. cbf_cr (if applicable)

        // Debug for specific position
        let debug_tt = self.debug_ctu;

        // Step 1: Determine if we should split
        // Per H.265: decode split_transform_flag only when all conditions met AND
        // NOT (IntraSplitFlag && trafoDepth == 0)
        let split_transform = if log2_size <= log2_max_trafo_size
            && log2_size > log2_min_trafo_size
            && trafo_depth < max_trafo_depth
            && !(intra_split_flag && trafo_depth == 0)
        {
            // Decode split_transform_flag
            let ctx_idx = context::SPLIT_TRANSFORM_FLAG + (5 - log2_size as usize).min(2);
            let flag = self.cabac.decode_bin(&mut self.ctx[ctx_idx])? != 0;
            se_trace("split_transform", flag as i64, &self.cabac);
            flag
        } else if log2_size > log2_max_trafo_size || (intra_split_flag && trafo_depth == 0) {
            true // Must split: larger than max OR IntraSplitFlag at depth 0
        } else {
            if debug_tt {
                debug_trace!(
                    "    TT(1144,120): no split (log2={} min={} max={} depth={} maxdepth={})",
                    log2_size,
                    log2_min_trafo_size,
                    log2_max_trafo_size,
                    trafo_depth,
                    max_trafo_depth
                );
            }
            false
        };

        // Step 2: Decode cbf_cb and cbf_cr.
        // Per H.265 7.3.8.8: chroma cbf is decoded when
        //   (log2TrafoSize > 2 && ChromaArrayType != 0) || ChromaArrayType == 3.
        // The `|| == 3` clause means 4:4:4 decodes chroma cbf even at 4x4
        // (log2_size == 2), where it is otherwise inherited from the parent.
        let cat = self.sps.chroma_array_type();
        let decode_chroma_cbf = (log2_size > 2 && cat != 0) || cat == 3;
        // 4:2:2 carries a second chroma TB stacked below the first; its cbf is
        // decoded (right after the first) wherever the chroma residual is coded
        // at this level: a leaf (!split) or an 8x8 splitting to 4x4 (log2==3).
        let decode_second_cbf = cat == 2 && (!split_transform || log2_size == 3);
        let (cbf_cb, cbf_cb1, cbf_cr, cbf_cr1) = if decode_chroma_cbf {
            let ctx_idx = context::CBF_CBCR + trafo_depth as usize;
            let decode = |s: &mut Self| -> Result<bool> {
                let val = s.cabac.decode_bin(&mut s.ctx[ctx_idx])? != 0;
                se_trace("cbf_chroma", val as i64, &s.cabac);
                Ok(val)
            };
            // cbf_cb[0], then cbf_cb[1] (4:2:2), then cbf_cr[0], then cbf_cr[1].
            let cb = if trafo_depth == 0 || cbf_cb_parent {
                decode(self)?
            } else {
                false
            };
            let cb1 = if decode_second_cbf && (trafo_depth == 0 || cbf_cb_parent) {
                decode(self)?
            } else {
                false
            };
            let cr = if trafo_depth == 0 || cbf_cr_parent {
                decode(self)?
            } else {
                false
            };
            let cr1 = if decode_second_cbf && (trafo_depth == 0 || cbf_cr_parent) {
                decode(self)?
            } else {
                false
            };
            (cb, cb1, cr, cr1)
        } else {
            // log2_size == 2: inherit from parent (chroma decoded at parent level)
            (cbf_cb_parent, false, cbf_cr_parent, false)
        };

        if split_transform {
            let half = 1u32 << (log2_size - 1);
            let new_depth = trafo_depth + 1;
            let new_log2_size = log2_size - 1;

            self.decode_transform_tree_inner(
                x0,
                y0,
                new_log2_size,
                new_depth,
                intra_luma_mode,
                intra_chroma_mode,
                intra_split_flag,
                cbf_cb,
                cbf_cr,
                frame,
            )?;
            self.decode_transform_tree_inner(
                x0 + half,
                y0,
                new_log2_size,
                new_depth,
                intra_luma_mode,
                intra_chroma_mode,
                intra_split_flag,
                cbf_cb,
                cbf_cr,
                frame,
            )?;
            self.decode_transform_tree_inner(
                x0,
                y0 + half,
                new_log2_size,
                new_depth,
                intra_luma_mode,
                intra_chroma_mode,
                intra_split_flag,
                cbf_cb,
                cbf_cr,
                frame,
            )?;
            self.decode_transform_tree_inner(
                x0 + half,
                y0 + half,
                new_log2_size,
                new_depth,
                intra_luma_mode,
                intra_chroma_mode,
                intra_split_flag,
                cbf_cb,
                cbf_cr,
                frame,
            )?;

            // If we split from 8x8 to 4x4, the children are 4x4 luma TUs that
            // can't carry chroma, so the chroma TB(s) for the 8x8 region are
            // predicted + decoded now at the parent level. 4:2:0 has one 4x4
            // chroma TB; 4:2:2 has two stacked 4x4 TBs. 4:4:4 does NOT do this
            // (its 4x4 children carry their own chroma — handled in the leaf).
            if log2_size == 3 && cat != 0 && cat != 3 {
                self.decode_chroma_tus(
                    x0,
                    y0,
                    2,
                    intra_chroma_mode,
                    cbf_cb,
                    cbf_cb1,
                    cbf_cr,
                    cbf_cr1,
                    frame,
                )?;
            }
        } else {
            // Decode transform unit (leaf node)
            self.decode_transform_unit_leaf(
                x0,
                y0,
                log2_size,
                trafo_depth,
                intra_luma_mode,
                intra_chroma_mode,
                cbf_cb,
                cbf_cb1,
                cbf_cr,
                cbf_cr1,
                frame,
            )?;
        }

        Ok(())
    }

    /// Predict + (optionally) reconstruct the chroma transform block(s) for a
    /// luma region, dispatching on chroma format.
    ///
    /// `cx_luma`/`cy_luma` are the *luma* coordinates and `chroma_log2` the
    /// chroma TB log2 size. 4:2:0 has a single TB at (x/2, y/2); 4:2:2 has two
    /// TBs stacked vertically at (x/2, y) and (x/2, y + size) with the Table 8-3
    /// remapped mode; 4:4:4 is handled inline in the leaf (full-size, at luma
    /// coords), not here.
    #[allow(clippy::too_many_arguments)]
    fn decode_chroma_tus(
        &mut self,
        cx_luma: u32,
        cy_luma: u32,
        chroma_log2: u8,
        chroma_mode: IntraPredMode,
        cbf_cb0: bool,
        cbf_cb1: bool,
        cbf_cr0: bool,
        cbf_cr1: bool,
        frame: &mut DecodedFrame,
    ) -> Result<()> {
        let cat = self.sps.chroma_array_type();
        let size = 1u32 << chroma_log2;
        if cat == 2 {
            // 4:2:2: chroma x is halved, y is full; two square TBs stacked.
            let cx = cx_luma / 2;
            let mode = IntraPredMode::from_u8(intra::map_chroma_mode_422(chroma_mode.as_u8()))
                .unwrap_or(chroma_mode);
            self.predict_apply_chroma(cx, cy_luma, chroma_log2, 1, mode, cbf_cb0, frame)?;
            self.predict_apply_chroma(cx, cy_luma + size, chroma_log2, 1, mode, cbf_cb1, frame)?;
            self.predict_apply_chroma(cx, cy_luma, chroma_log2, 2, mode, cbf_cr0, frame)?;
            self.predict_apply_chroma(cx, cy_luma + size, chroma_log2, 2, mode, cbf_cr1, frame)?;
        } else {
            // 4:2:0: single chroma TB at (x/2, y/2).
            let (cx, cy) = (cx_luma / 2, cy_luma / 2);
            self.predict_apply_chroma(cx, cy, chroma_log2, 1, chroma_mode, cbf_cb0, frame)?;
            self.predict_apply_chroma(cx, cy, chroma_log2, 2, chroma_mode, cbf_cr0, frame)?;
        }
        Ok(())
    }

    /// Plane subsampling shifts `(x, y)` for component `c_idx` under the active
    /// chroma array type. Delegates to the shared [`super::tile::plane_shifts`]
    /// so encoder and decoder agree on the chroma-format mapping.
    fn plane_shifts(&self, c_idx: u8) -> (u8, u8) {
        super::tile::plane_shifts(c_idx, self.sps.chroma_array_type())
    }

    /// Intra-predict into `frame`, clamping reference samples to the current
    /// tile when tiles are enabled. Cross-tile reference samples are unavailable
    /// (forced via the `Some(UNINIT_SAMPLE)` reader override), so a tile decodes
    /// independently of its already-reconstructed neighbours.
    fn predict_intra_tiled(
        &self,
        frame: &mut DecodedFrame,
        x: u32,
        y: u32,
        log2_size: u8,
        mode: IntraPredMode,
        c_idx: u8,
        sis: bool,
    ) {
        if self.tile_grid.is_single() {
            intra::predict_intra(frame, x, y, log2_size, mode, c_idx, sis);
            return;
        }
        let ctb_log2 = self.sps.log2_ctb_size();
        let (sx, sy) = self.plane_shifts(c_idx);
        let (tx0, ty0, tx1, ty1) = self.tile_grid.tile_plane_bounds(x, y, ctb_log2, sx, sy);
        intra::predict_intra_with_reader(
            frame,
            x,
            y,
            log2_size,
            mode,
            c_idx,
            sis,
            move |_c, rx, ry| {
                if rx < tx0 || rx >= tx1 || ry < ty0 || ry >= ty1 {
                    Some(super::picture::UNINIT_SAMPLE)
                } else {
                    None
                }
            },
        );
    }

    /// Predict one chroma TB and, if `cbf` is set, decode+add its residual.
    fn predict_apply_chroma(
        &mut self,
        cx: u32,
        cy: u32,
        log2_size: u8,
        c_idx: u8,
        mode: IntraPredMode,
        cbf: bool,
        frame: &mut DecodedFrame,
    ) -> Result<()> {
        let sis = self.sps.strong_intra_smoothing_enabled_flag;
        self.predict_intra_tiled(frame, cx, cy, log2_size, mode, c_idx, sis);
        if cbf {
            let cat = self.sps.chroma_array_type();
            let scan = residual::get_scan_order(log2_size, mode.as_u8(), c_idx, cat);
            self.decode_and_apply_residual(cx, cy, log2_size, c_idx, scan, frame)?;
        }
        Ok(())
    }

    /// Decode transform unit at leaf node
    ///
    /// Per libde265's decode_TU(): prediction and reconstruction happen PER TU,
    /// so each TU is fully predicted + reconstructed before the next TU starts.
    /// This ensures subsequent TUs read reconstructed neighbor samples (not just
    /// prediction values) for their own intra prediction.
    #[allow(clippy::too_many_arguments)]
    fn decode_transform_unit_leaf(
        &mut self,
        x0: u32,
        y0: u32,
        log2_size: u8,
        trafo_depth: u8,
        _intra_luma_mode: IntraPredMode,
        intra_chroma_mode: IntraPredMode,
        cbf_cb: bool,
        cbf_cb1: bool,
        cbf_cr: bool,
        cbf_cr1: bool,
        frame: &mut DecodedFrame,
    ) -> Result<()> {
        let debug_tt = self.debug_ctu;

        // Decode cbf_luma - per H.265 spec 7.3.8.6:
        // cbf_luma is coded if: CuPredMode == MODE_INTRA || trafoDepth != 0 || cbf_cb || cbf_cr
        // For INTRA mode (all HEIC images), cbf_luma is ALWAYS coded
        // Context: offset 0 if trafo_depth > 0, offset 1 if trafo_depth == 0
        let ctx_offset = if trafo_depth == 0 { 1 } else { 0 };
        let ctx_idx = context::CBF_LUMA + ctx_offset;
        let cbf_luma = self.cabac.decode_bin(&mut self.ctx[ctx_idx])? != 0;
        se_trace("cbf_luma", cbf_luma as i64, &self.cabac);

        // Per H.265 7.3.8.11: decode cu_qp_delta before residuals
        // Condition: (cbf_luma || cbf_cb || cbf_cr) && cu_qp_delta_enabled_flag && !IsCuQpDeltaCoded
        if (cbf_luma || cbf_cb || cbf_cb1 || cbf_cr || cbf_cr1)
            && self.pps.cu_qp_delta_enabled_flag
            && !self.is_cu_qp_delta_coded
        {
            let cu_qp_delta_abs = self.decode_cu_qp_delta_abs()?;
            let cu_qp_delta_sign = if cu_qp_delta_abs != 0 {
                self.cabac.decode_bypass()?
            } else {
                0
            };
            self.is_cu_qp_delta_coded = true;
            self.cu_qp_delta = cu_qp_delta_abs as i32 * (1 - 2 * cu_qp_delta_sign as i32);
            se_trace("cu_qp_delta", self.cu_qp_delta as i64, &self.cabac);

            if self.first_qp_group || (self.current_qg_x == 0 && self.current_qg_y == 0) {
                self.first_qp_group = false;
            }

            // Re-derive quantization parameters with the actual delta
            let cu_x = self.cu_base_x;
            let cu_y = self.cu_base_y;
            let cu_log2 = self.cu_log2_size;
            self.decode_quantization_parameters(cu_x, cu_y, cu_log2);
            // Store QPY in the QP map for neighbor lookups
            self.store_qpy(cu_x, cu_y, cu_log2, self.current_qpy);
        }

        // Mark TU boundary and store QP for deblocking
        let tu_size = 1u32 << log2_size;
        frame.mark_tu_boundary(x0, y0, tu_size);
        frame.store_block_qp(x0, y0, tu_size, self.current_qpy as i8);

        // Look up intra mode at actual TU position (correct for NxN where sub-TUs differ)
        let actual_luma_mode = self.get_intra_mode_at(x0, y0);
        let sis = self.sps.strong_intra_smoothing_enabled_flag;
        let cat = self.sps.chroma_array_type();

        // Predict luma at TU level BEFORE residual application
        // This ensures each TU reads reconstructed neighbors from prior TUs
        self.predict_intra_tiled(frame, x0, y0, log2_size, actual_luma_mode, 0, sis);

        let scan_order = residual::get_scan_order(log2_size, actual_luma_mode.as_u8(), 0, cat);

        // Decode and apply luma residuals (adds to prediction already in frame)
        if cbf_luma {
            if debug_tt {
                let (r, o) = self.cabac.get_state();
                debug_trace!(
                    "    TT: decoding luma residual at ({},{}) log2={} (r={},o={})",
                    x0,
                    y0,
                    log2_size,
                    r,
                    o
                );
            }
            self.decode_and_apply_residual(x0, y0, log2_size, 0, scan_order, frame)?;
        }

        if cat == 3 {
            // 4:4:4: chroma transform blocks mirror luma exactly — same size,
            // same position, decoded at every leaf (including 4x4). Each TU's
            // chroma mode is looked up per-position (NxN gives one per PU).
            let chroma_mode = self.get_intra_chroma_mode_at(x0, y0);
            let chroma_scan_order =
                residual::get_scan_order(log2_size, chroma_mode.as_u8(), 1, cat);

            self.predict_intra_tiled(frame, x0, y0, log2_size, chroma_mode, 1, sis);
            if cbf_cb {
                self.decode_and_apply_residual(x0, y0, log2_size, 1, chroma_scan_order, frame)?;
            }
            self.predict_intra_tiled(frame, x0, y0, log2_size, chroma_mode, 2, sis);
            if cbf_cr {
                self.decode_and_apply_residual(x0, y0, log2_size, 2, chroma_scan_order, frame)?;
            }
        } else if cat != 0 && log2_size >= 3 {
            // 4:2:0 / 4:2:2: chroma TBs are half-width (log2_size-1). 4:2:0 has a
            // single TB; 4:2:2 has two stacked TBs (see decode_chroma_tus). (4x4
            // luma TUs carry no chroma — handled by the parent 8x8 split above.)
            self.decode_chroma_tus(
                x0,
                y0,
                log2_size - 1,
                intra_chroma_mode,
                cbf_cb,
                cbf_cb1,
                cbf_cr,
                cbf_cr1,
                frame,
            )?;
        }
        // Note: if log2_size < 3 (and not 4:4:4), chroma was predicted+decoded
        // by the parent when splitting from 8x8.

        Ok(())
    }

    /// Decode cu_qp_delta_abs per H.265 section 7.3.8.11
    /// TU prefix (up to 5 context-coded bins) + EGk bypass suffix
    fn decode_cu_qp_delta_abs(&mut self) -> Result<u32> {
        let first_bin = self
            .cabac
            .decode_bin(&mut self.ctx[context::CU_QP_DELTA_ABS])?;
        if first_bin == 0 {
            return Ok(0);
        }
        let mut prefix = 1u32;
        for _ in 0..4 {
            let bin = self
                .cabac
                .decode_bin(&mut self.ctx[context::CU_QP_DELTA_ABS + 1])?;
            if bin == 0 {
                break;
            }
            prefix += 1;
        }
        if prefix == 5 {
            // EGk(0) bypass suffix
            let suffix = self.cabac.decode_egk_bypass(0)?;
            Ok(suffix + 5)
        } else {
            Ok(prefix)
        }
    }

    /// Decode residual coefficients and apply to frame
    fn decode_and_apply_residual(
        &mut self,
        x0: u32,
        y0: u32,
        log2_size: u8,
        c_idx: u8,
        scan_order: ScanOrder,
        frame: &mut DecodedFrame,
    ) -> Result<()> {
        // Decode coefficients via CABAC
        let (mut coeff_buf, transform_skip) = residual::decode_residual(
            &mut self.cabac,
            &mut self.ctx,
            log2_size,
            c_idx,
            scan_order,
            self.pps.sign_data_hiding_enabled_flag,
            self.cu_transquant_bypass_flag,
            self.pps.transform_skip_enabled_flag,
            x0,
            y0,
        )?;

        if coeff_buf.is_zero() {
            return Ok(());
        }

        let size = 1usize << log2_size;
        let num_coeffs = size * size;

        // Capture the coded (pre-dequant) level distribution for decision analysis.
        let coded_levels = if super::debug::decision_log_active() {
            let mut nz = 0u32;
            let mut abs_level_sum = 0u64;
            for &c in &coeff_buf.coeffs[..num_coeffs] {
                if c != 0 {
                    nz += 1;
                    abs_level_sum += (c as i64).unsigned_abs();
                }
            }
            Some((nz, abs_level_sum))
        } else {
            None
        };

        // Forensic block dump (env-gated, BPG_STILL_DUMP). Snapshot the coded
        // levels before they are dequantized in place.
        let dump_match = super::debug::dump_target()
            .is_some_and(|(dx, dy, dl, dc)| dx == x0 && dy == y0 && dl == log2_size && dc == c_idx);
        let dump_levels: Option<Vec<i16>> =
            dump_match.then(|| coeff_buf.coeffs[..num_coeffs].to_vec());

        // Dequantize coefficients in-place
        let coeffs = &mut coeff_buf.coeffs;

        let (qp, bit_depth) = match c_idx {
            0 => (self.qp_y, self.sps.bit_depth_y()),
            1 => (self.qp_cb, self.sps.bit_depth_c()),
            2 => (self.qp_cr, self.sps.bit_depth_c()),
            _ => (self.qp_y, self.sps.bit_depth_y()),
        };
        let dequant_params = transform::DequantParams {
            qp,
            bit_depth,
            log2_tr_size: log2_size,
        };

        // Use scaling list if enabled (H.265 8.6.3)
        // Per spec: use PPS scaling list if present, else SPS scaling list
        let scaling_list = if self.sps.scaling_list_enabled_flag && !transform_skip {
            self.pps
                .pps_scaling_list
                .as_ref()
                .or(self.sps.scaling_list.as_ref())
        } else {
            None
        };

        if let Some(sl) = scaling_list {
            // matrixId: intra Y=0, Cb=1, Cr=2 (all HEIC is intra)
            let matrix_id = c_idx;
            // Build scaling matrix in raster order for this TU (reuse persistent buffer)
            let scaling_matrix = &mut self.scaling_buf;
            for py in 0..size {
                for px in 0..size {
                    scaling_matrix[py * size + px] =
                        sl.get_scaling_factor(log2_size, matrix_id, px as u32, py as u32);
                }
            }
            transform::dequantize_scaled(
                &mut coeffs[..num_coeffs],
                dequant_params,
                &scaling_matrix[..num_coeffs],
            );
        } else {
            transform::dequantize(&mut coeffs[..num_coeffs], dequant_params);
        }

        let dump_dequant: Option<Vec<i16>> = dump_match.then(|| coeffs[..num_coeffs].to_vec());

        // Apply inverse transform (or skip for transform_skip mode)
        // Reuse persistent buffer — transform writes all size*size elements, no zeroing needed
        let residual = &mut self.residual_buf;
        if transform_skip {
            // Per H.265 8.6.4.1 / libde265 transform_skip_residual_fallback():
            // tsShift = 5 + Log2(nTbS)
            // bdShift = max(20 - bit_depth, 0)
            // residual = (coeff << tsShift + rnd) >> bdShift
            let ts_shift = 5 + log2_size as i32;
            let bd_shift = (20 - bit_depth as i32).max(0);
            let rnd = if bd_shift > 0 {
                1i32 << (bd_shift - 1)
            } else {
                0
            };
            for i in 0..num_coeffs {
                let c = (coeffs[i] as i32) << ts_shift;
                residual[i] = ((c + rnd) >> bd_shift) as i16;
            }
        } else {
            let is_intra_4x4_luma = log2_size == 2 && c_idx == 0;
            transform::inverse_transform(coeffs, residual, size, bit_depth, is_intra_4x4_luma);
        }

        if let Some((nz, abs_level_sum)) = coded_levels {
            let residual_energy: u64 = residual[..num_coeffs]
                .iter()
                .map(|&r| (r as i64 * r as i64) as u64)
                .sum();
            super::debug::log_tu(super::debug::TuRecord {
                x: x0,
                y: y0,
                log2_size,
                c_idx,
                nz,
                abs_level_sum,
                residual_energy,
            });
        }

        // Forensic dump: capture the prediction block (the plane still holds it
        // here, before the residual add) for the env-selected target.
        let dump_pred: Option<Vec<u16>> = dump_match.then(|| {
            let (plane, stride) = frame.plane(c_idx);
            let mut p = vec![0u16; size * size];
            for py in 0..size {
                for px in 0..size {
                    p[py * size + px] = plane[(y0 as usize + py) * stride + x0 as usize + px];
                }
            }
            p
        });

        // Add residual to prediction — single SIMD dispatch for entire block
        let max_val = (1i32 << bit_depth) - 1;
        let (plane, stride) = frame.plane_mut(c_idx);
        let last_row_end = (y0 as usize + size - 1) * stride + x0 as usize + size;
        if last_row_end <= plane.len() {
            incant!(
                add_residual_block(
                    plane,
                    stride,
                    x0 as usize,
                    y0 as usize,
                    residual,
                    size,
                    max_val
                ),
                [v3]
            );
        } else {
            for py in 0..size {
                let row_start = (y0 as usize + py) * stride + x0 as usize;
                for px in 0..size {
                    let idx = row_start + px;
                    if idx < plane.len() {
                        let pred = plane[idx] as i32;
                        let r = residual[py * size + px] as i32;
                        plane[idx] = (pred + r).clamp(0, max_val) as u16;
                    }
                }
            }
        }

        if dump_match {
            let (plane, stride) = frame.plane(c_idx);
            let mut rec = vec![0u16; size * size];
            for py in 0..size {
                for px in 0..size {
                    rec[py * size + px] = plane[(y0 as usize + py) * stride + x0 as usize + px];
                }
            }
            super::debug::dump_decode_block(
                x0,
                y0,
                log2_size,
                c_idx,
                dump_levels.as_deref().unwrap_or(&[]),
                dump_dequant.as_deref().unwrap_or(&[]),
                &residual[..num_coeffs],
                dump_pred.as_deref().unwrap_or(&[]),
                &rec,
                size,
            );
        }

        Ok(())
    }

    /// Decode partition mode
    fn decode_part_mode(&mut self, pred_mode: PredMode, log2_cb_size: u8) -> Result<PartMode> {
        if pred_mode == PredMode::Intra {
            // For intra, first bin distinguishes 2Nx2N from NxN
            let ctx_idx = context::PART_MODE;
            let bin = self.cabac.decode_bin(&mut self.ctx[ctx_idx])?;
            se_trace("part_mode", bin as i64, &self.cabac);

            if bin != 0 {
                Ok(PartMode::Part2Nx2N)
            } else {
                // NxN only allowed at minimum CU size
                if log2_cb_size == self.sps.log2_min_cb_size() {
                    Ok(PartMode::PartNxN)
                } else {
                    Err(HevcError::InvalidBitstream("NxN not allowed at this size"))
                }
            }
        } else {
            // Inter partition modes (not implemented)
            Err(HevcError::Unsupported("inter partition modes"))
        }
    }

    /// Decode intra prediction modes and apply prediction
    /// Returns (luma_mode, chroma_mode)
    fn decode_intra_prediction(
        &mut self,
        x0: u32,
        y0: u32,
        log2_size: u8,
        _apply_chroma: bool,
        frame: &mut DecodedFrame,
    ) -> Result<(IntraPredMode, IntraPredMode)> {
        let (intra_luma_mode, intra_chroma_mode) =
            self.decode_intra_prediction_modes(x0, y0, log2_size, frame)?;

        // Store intra modes in the mode map for neighbor lookups and transform tree
        self.store_intra_mode(x0, y0, log2_size, intra_luma_mode);
        self.store_intra_chroma_mode(x0, y0, log2_size, intra_chroma_mode);

        // NOTE: Prediction is NOT applied here. It happens in decode_transform_unit_leaf
        // and the 8x8→4x4 chroma split handler, so each TU is predicted →
        // reconstructed before the next TU reads its neighbors.

        Ok((intra_luma_mode, intra_chroma_mode))
    }

    /// Decode prev_intra_luma_pred_flag (context-coded bin)
    fn decode_prev_intra_luma_pred_flag(&mut self) -> Result<bool> {
        let ctx_idx = context::PREV_INTRA_LUMA_PRED_FLAG;
        let val = self.cabac.decode_bin(&mut self.ctx[ctx_idx])? != 0;
        se_trace("prev_intra_luma_pred", val as i64, &self.cabac);
        Ok(val)
    }

    /// Derive intra luma mode from prev_flag using neighbor-based MPM candidates
    ///
    /// Looks up left and above neighbors from the intra mode map, with proper
    /// CTB row boundary check for the above neighbor (H.265 8.4.2).
    fn derive_intra_luma_mode(
        &mut self,
        x0: u32,
        y0: u32,
        prev_flag: bool,
    ) -> Result<IntraPredMode> {
        let cand_a = self.get_neighbor_intra_mode_left(x0, y0);
        let cand_b = self.get_neighbor_intra_mode_above(x0, y0);
        let mpm = intra::fill_mpm_candidates(cand_a, cand_b);

        if prev_flag {
            let mpm_idx = self.decode_mpm_idx()?;
            Ok(mpm[mpm_idx as usize])
        } else {
            let rem = self.decode_rem_intra_luma_pred_mode()?;
            Ok(self.map_rem_mode_to_intra(rem, &mpm))
        }
    }

    /// Decode intra luma mode: flag + mpm/rem in one call (for Part2Nx2N)
    fn decode_intra_luma_mode(&mut self, x0: u32, y0: u32) -> Result<IntraPredMode> {
        let prev_flag = self.decode_prev_intra_luma_pred_flag()?;
        self.derive_intra_luma_mode(x0, y0, prev_flag)
    }

    /// Decode intra chroma mode
    /// Per HEVC spec Table 8-2 and libde265 map_chroma_pred_mode():
    /// - First bin (context-coded): if 0 → mode 4 (derived from luma)
    /// - If first bin is 1: read 2 fixed-length bypass bits → modes 0-3
    /// - If candidate mode collides with luma mode → Angular34
    fn decode_intra_chroma_mode(&mut self, luma_mode: IntraPredMode) -> Result<IntraPredMode> {
        let ctx_idx = context::INTRA_CHROMA_PRED_MODE;
        let first_bin = self.cabac.decode_bin(&mut self.ctx[ctx_idx])?;
        if first_bin == 0 {
            // Mode 4: derived from luma
            se_trace("intra_chroma_mode", 4, &self.cabac);
            return Ok(luma_mode);
        }

        // Read 2 fixed-length bypass bits for modes 0-3
        let mode_idx = self.cabac.decode_bypass_bits(2)? as u8;
        se_trace("intra_chroma_mode", mode_idx as i64, &self.cabac);

        let candidate = match mode_idx {
            0 => IntraPredMode::Planar,
            1 => IntraPredMode::Angular26, // Vertical
            2 => IntraPredMode::Angular10, // Horizontal
            _ => IntraPredMode::Dc,        // mode_idx == 3
        };

        // Per Table 8-2: if candidate collides with luma mode, use Angular34
        let intra_chroma_mode = if candidate == luma_mode {
            IntraPredMode::Angular34
        } else {
            candidate
        };

        Ok(intra_chroma_mode)
    }

    /// Decode intra prediction modes (luma + chroma) for Part2Nx2N
    fn decode_intra_prediction_modes(
        &mut self,
        x0: u32,
        y0: u32,
        log2_size: u8,
        _frame: &DecodedFrame,
    ) -> Result<(IntraPredMode, IntraPredMode)> {
        let intra_luma_mode = self.decode_intra_luma_mode(x0, y0)?;

        // DEBUG: Print first few intra modes
        if x0 < 16 && y0 < 16 {
            debug_trace!(
                "DEBUG: intra_mode at ({},{}) size={}: mode={:?}",
                x0,
                y0,
                1u32 << log2_size,
                intra_luma_mode
            );
        }

        let intra_chroma_mode = if self.sps.chroma_array_type() == 0 {
            IntraPredMode::Dc
        } else {
            self.decode_intra_chroma_mode(intra_luma_mode)?
        };

        Ok((intra_luma_mode, intra_chroma_mode))
    }

    /// Get min PU size (= min_cb_size / 2, at least 1)
    fn min_pu_size(&self) -> u32 {
        ((1u32 << self.sps.log2_min_cb_size()) / 2).max(1)
    }

    /// Store intra luma mode for a region (in min_pu_size units)
    fn store_intra_mode(&mut self, x0: u32, y0: u32, log2_size: u8, mode: IntraPredMode) {
        let min_pu = self.min_pu_size();
        let stride = self.intra_mode_map_stride;
        let count = ((1u32 << log2_size) / min_pu).max(1);
        let start_x = x0 / min_pu;
        let start_y = y0 / min_pu;
        for dy in 0..count {
            for dx in 0..count {
                let idx = ((start_y + dy) * stride + (start_x + dx)) as usize;
                if idx < self.intra_mode_map.len() {
                    self.intra_mode_map[idx] = mode.as_u8();
                }
            }
        }
    }

    /// Store intra chroma mode for a region (in min_pu_size units)
    fn store_intra_chroma_mode(&mut self, x0: u32, y0: u32, log2_size: u8, mode: IntraPredMode) {
        let min_pu = self.min_pu_size();
        let stride = self.intra_mode_map_stride;
        let count = ((1u32 << log2_size) / min_pu).max(1);
        let start_x = x0 / min_pu;
        let start_y = y0 / min_pu;
        for dy in 0..count {
            for dx in 0..count {
                let idx = ((start_y + dy) * stride + (start_x + dx)) as usize;
                if idx < self.intra_chroma_mode_map.len() {
                    self.intra_chroma_mode_map[idx] = mode.as_u8();
                }
            }
        }
    }

    /// Get intra luma prediction mode at a sample position
    fn get_intra_mode_at(&self, x: u32, y: u32) -> IntraPredMode {
        let min_pu = self.min_pu_size();
        let stride = self.intra_mode_map_stride;
        let idx = ((y / min_pu) * stride + (x / min_pu)) as usize;
        if idx < self.intra_mode_map.len() {
            IntraPredMode::from_u8(self.intra_mode_map[idx]).unwrap_or(IntraPredMode::Dc)
        } else {
            IntraPredMode::Dc
        }
    }

    /// Get intra chroma prediction mode at a sample position
    #[allow(dead_code)]
    fn get_intra_chroma_mode_at(&self, x: u32, y: u32) -> IntraPredMode {
        let min_pu = self.min_pu_size();
        let stride = self.intra_mode_map_stride;
        let idx = ((y / min_pu) * stride + (x / min_pu)) as usize;
        if idx < self.intra_chroma_mode_map.len() {
            IntraPredMode::from_u8(self.intra_chroma_mode_map[idx]).unwrap_or(IntraPredMode::Dc)
        } else {
            IntraPredMode::Dc
        }
    }

    /// Get intra prediction mode of the left neighbor (x0-1, y0)
    ///
    /// Returns DC if the left neighbor is outside the picture boundary.
    fn get_neighbor_intra_mode_left(&self, x0: u32, y0: u32) -> IntraPredMode {
        if x0 == 0 {
            return IntraPredMode::Dc;
        }
        // The left neighbour is unavailable across a tile boundary (the
        // above-neighbour CTB-row guard already covers tile *row* boundaries).
        if !self.tile_grid.is_single() {
            let ctb_log2 = self.sps.log2_ctb_size();
            if !self.tile_grid.same_tile_ctb(
                (x0 - 1) >> ctb_log2,
                y0 >> ctb_log2,
                x0 >> ctb_log2,
                y0 >> ctb_log2,
            ) {
                return IntraPredMode::Dc;
            }
        }
        self.get_intra_mode_at(x0 - 1, y0)
    }

    /// Get intra prediction mode of the above neighbor (x0, y0-1)
    ///
    /// Returns DC if:
    /// - The above neighbor is outside the picture boundary (y0 == 0)
    /// - The above neighbor is in a different CTB row (H.265 8.4.2 / libde265 intrapred.cc:107-109)
    fn get_neighbor_intra_mode_above(&self, x0: u32, y0: u32) -> IntraPredMode {
        if y0 == 0 {
            return IntraPredMode::Dc;
        }
        // CTB row boundary check: if the above sample is in a different CTB row, use DC
        // This implements: y-1 < ((y >> Log2CtbSizeY) << Log2CtbSizeY)
        let ctb_size = self.sps.ctb_size();
        let ctb_y_start = (y0 / ctb_size) * ctb_size;
        if y0 - 1 < ctb_y_start {
            return IntraPredMode::Dc;
        }
        self.get_intra_mode_at(x0, y0 - 1)
    }

    /// Map rem_intra_luma_pred_mode to actual mode (excluding MPM candidates)
    fn map_rem_mode_to_intra(&self, rem: u32, mpm: &[IntraPredMode; 3]) -> IntraPredMode {
        // Sort MPM candidates
        let mut mpm_vals = [mpm[0].as_u8(), mpm[1].as_u8(), mpm[2].as_u8()];
        mpm_vals.sort_unstable();

        // Map remaining mode
        let mut mode = rem as u8;
        for &mpm_val in &mpm_vals {
            if mode >= mpm_val {
                mode += 1;
            }
        }

        IntraPredMode::from_u8(mode).unwrap_or(IntraPredMode::Dc)
    }

    /// Decode mpm_idx (0, 1, or 2)
    fn decode_mpm_idx(&mut self) -> Result<u8> {
        // Truncated unary: 0, 10, 11
        let val = if self.cabac.decode_bypass()? == 0 {
            0
        } else if self.cabac.decode_bypass()? == 0 {
            1
        } else {
            2
        };
        se_trace("mpm_idx", val as i64, &self.cabac);
        Ok(val)
    }

    /// Decode rem_intra_luma_pred_mode (5 bits)
    fn decode_rem_intra_luma_pred_mode(&mut self) -> Result<u32> {
        let mut val = 0u32;
        for _ in 0..5 {
            val = (val << 1) | self.cabac.decode_bypass()? as u32;
        }
        se_trace("rem_intra_luma", val as i64, &self.cabac);
        Ok(val)
    }

    /// Get QPY at a sample position from the QP map
    fn get_qpy_at(&self, x: u32, y: u32) -> i32 {
        let min_tb = 1u32 << self.sps.log2_min_tb_size();
        let idx = ((y / min_tb) * self.qp_map_stride + (x / min_tb)) as usize;
        if idx < self.qp_map.len() {
            self.qp_map[idx] as i32
        } else {
            self.header.slice_qp_y
        }
    }

    /// Store QPY for a CU region in the QP map
    fn store_qpy(&mut self, x0: u32, y0: u32, log2_cb_size: u8, qpy: i32) {
        let min_tb = 1u32 << self.sps.log2_min_tb_size();
        let count = ((1u32 << log2_cb_size) / min_tb).max(1);
        let start_x = x0 / min_tb;
        let start_y = y0 / min_tb;
        for dy in 0..count {
            for dx in 0..count {
                let idx = ((start_y + dy) * self.qp_map_stride + (start_x + dx)) as usize;
                if idx < self.qp_map.len() {
                    self.qp_map[idx] = qpy as i8;
                }
            }
        }
    }

    /// Decode quantization parameters (H.265 section 8.6.1)
    /// Matching libde265's decode_quantization_parameters()
    fn decode_quantization_parameters(
        &mut self,
        x_cu_base: u32,
        y_cu_base: u32,
        _log2_cb_size: u8,
    ) {
        let log2_min_cu_qp_delta_size = self.sps.log2_ctb_size() - self.pps.diff_cu_qp_delta_depth;
        let qg_mask = (1u32 << log2_min_cu_qp_delta_size) - 1;

        // Top-left pixel of current quantization group
        let x_qg = (x_cu_base & !qg_mask) as i32;
        let y_qg = (y_cu_base & !qg_mask) as i32;

        // Track QG transitions
        if x_qg != self.current_qg_x || y_qg != self.current_qg_y {
            self.last_qpy_in_prev_qg = self.current_qpy;
            self.current_qg_x = x_qg;
            self.current_qg_y = y_qg;
        }

        let ctb_size = self.sps.ctb_size();
        let ctb_mask = ctb_size - 1;
        let qp_y_pred = if self.first_qp_group || (x_qg == 0 && y_qg == 0) {
            self.header.slice_qp_y
        } else {
            self.qpy_pred
        };

        // Get neighbor QP values for averaging. Availability intentionally
        // mirrors libbpg's get_qPy_pred().
        let qp_y_a = if x_qg > 0 && (x_cu_base & ctb_mask) != 0 && ((x_qg as u32) & ctb_mask) != 0 {
            let left_x = (x_qg - 1) as u32;
            let left_y = y_qg as u32;
            let left_ctb_x = left_x / ctb_size;
            if left_ctb_x == self.ctb_x {
                self.get_qpy_at(left_x, left_y)
            } else {
                qp_y_pred
            }
        } else {
            qp_y_pred
        };

        let qp_y_b = if y_qg > 0 && (y_cu_base & ctb_mask) != 0 && ((y_qg as u32) & ctb_mask) != 0 {
            let above_x = x_qg as u32;
            let above_y = (y_qg - 1) as u32;
            let above_ctb_y = above_y / ctb_size;
            if above_ctb_y == self.ctb_y {
                self.get_qpy_at(above_x, above_y)
            } else {
                qp_y_pred
            }
        } else {
            qp_y_pred
        };

        let qp_y_pred = (qp_y_a + qp_y_b + 1) >> 1;

        // Compute final QPY
        let qp_bd_offset_y = 6 * (self.sps.bit_depth_y() as i32 - 8);
        let qpy = ((qp_y_pred + self.cu_qp_delta + 52 + 2 * qp_bd_offset_y)
            % (52 + qp_bd_offset_y))
            - qp_bd_offset_y;

        self.qp_y = qpy + qp_bd_offset_y;
        if self.qp_y < 0 {
            self.qp_y = 0;
        }

        // Compute chroma QP. Table 8-10 applies only for 4:2:0; 4:2:2/4:4:4
        // use Min(qPi, 51). Keep this in sync with the slice-init path above and
        // still265's `encoder::types::chroma_qp_from_luma`.
        let qp_bd_offset_c = 6 * (self.sps.bit_depth_c() as i32 - 8);
        let qpi_cb =
            (qpy + self.pps.pps_cb_qp_offset as i32 + self.header.slice_cb_qp_offset as i32)
                .clamp(-qp_bd_offset_c, 57);
        let qpi_cr =
            (qpy + self.pps.pps_cr_qp_offset as i32 + self.header.slice_cr_qp_offset as i32)
                .clamp(-qp_bd_offset_c, 57);
        let cat = self.sps.chroma_array_type();

        self.qp_cb = chroma_qp_mapping(qpi_cb, cat) + qp_bd_offset_c;
        self.qp_cr = chroma_qp_mapping(qpi_cr, cat) + qp_bd_offset_c;

        self.current_qpy = qpy;
    }
}