oxideav-vp8 0.2.10

Pure-Rust VP8 video codec — orphan-rebuild scaffold pending clean-room re-implementation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
//! Multi-frame VP8 decoder state (`Vp8DecoderState`) and the top-level
//! interframe driver — RFC 6386 §9 / §16.
//!
//! [`decode_vp8`](crate::decoder::decode_vp8) is stateless: it decodes one
//! key frame in isolation. The interframe machinery (§16) needs three
//! things [`decode_vp8`] cannot provide:
//!
//! 1. **A 3-slot reference-frame buffer.** §16.2 selects the prediction
//!    source between the previously-decoded `LAST` frame, the `GOLDEN`
//!    frame, and the `ALTREF` frame. Each inter macroblock fetches pixels
//!    from one of those three frames; without a multi-frame state object
//!    nothing has the previous frame to fetch from.
//! 2. **Across-frame entropy persistence.** §9.10 `refresh_entropy_probs`
//!    controls whether the in-frame token-probability / intra-mode /
//!    motion-vector updates persist into the *next* frame, or are rolled
//!    back to the entry-state at end-of-frame (the §20 `saved_entropy`
//!    pattern).
//! 3. **§9 reference-frame refresh / copy ladder.** After a frame
//!    decodes, the bits `copy_buffer_to_alternate` (L2), `copy_buffer_to_golden`
//!    (L2), `refresh_golden_frame` (L1), `refresh_alternate_frame` (L1),
//!    and `refresh_last` (L1) decide which of the three slots are
//!    replaced by the just-decoded frame (or by a copy of another slot)
//!    before the next frame's decode begins. Key frames implicitly
//!    refresh all three slots per §9.7 / §9.8.
//!
//! The [`Vp8DecoderState`] type owns those three pieces, and
//! [`Vp8DecoderState::decode_frame`] is the per-frame driver: parse the
//! §9.1 frame tag, branch on key-vs-inter, decode the macroblock layer,
//! reconstruct pixels using the appropriate reference frame, run the §15
//! loop filter, update the entropy carry-state per §9.10, and rotate the
//! reference-frame slots per §9 before returning the cropped I420 picture.
//!
//! Per-frame decode reuses the same building blocks the stateless key-frame
//! driver does ([`decode_keyframe`], [`decode_and_dequantize_mb`],
//! [`filter_frame`], the §16.3 / §16.4 inter-MB helpers
//! ([`decode_inter_mb`] / [`decode_split_mv_mb`]), the §18 motion-comp
//! kernels, …); this module is purely the cross-frame composition layer.

use crate::bool_decoder::BoolDecoder;
use crate::coded_header::Vp8CodedHeader;
use crate::dct_tokens::{CoeffProbs, MbEntropyCtx, merge_default_token_probs};
use crate::decoder::{DecodeError, Vp8DecodedFrame};
use crate::dequant::{MbDequantFactors, decode_and_dequantize_mb};
use crate::frame::{FrameError, KeyframePlanes, MbCoeffs};
use crate::frame_header::{ScaleCode, Vp8FrameHeader};
use crate::loop_filter::{FrameFilterConfig, MAX_MB_SEGMENTS};
use crate::macroblock::{
    InterFrameIntraProbs, IntraYMode, MacroblockModes, parse_inter_frame_intra_macroblock_modes,
    parse_key_frame_macroblock_modes,
};
use crate::motion_comp::{
    RefFrame, ReferencePlanes, filter_set_for_version, reconstruct_inter_mb,
    reconstruct_split_mv_mb, select_ref_frame,
};
use crate::motion_vector::{Mv, MvContexts, default_mv_contexts, resolve_mv_contexts};
use crate::near_mv::{
    InterMbError, InterMode, MbInfo, MvClampRect, ResolvedInterMode, SignBias, SplitMvResult,
    clamp_mv, decode_split_mv, find_near_mvs, mv_ref_probs, read_inter_mode,
};
use crate::reconstruct::ReconstructedMb;

mod rows;

/// One slot of the §9 / §16 three-slot reference-frame buffer.
///
/// Holds the reconstructed (post-loop-filter, padded-to-whole-macroblocks)
/// I420 planes of a previously-decoded frame, plus the macroblock-row /
/// macroblock-column counts the next inter frame needs for §20.14
/// `build_mc_border` edge replication. The visible width/height is *not*
/// stored — the reference fetch operates in macroblock-aligned coordinates,
/// the visible crop is a final-output presentation concern (handled by
/// [`Vp8DecoderState::decode_frame`] when it emits the [`Vp8DecodedFrame`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefFrameSlot {
    /// Luma plane, row-major, `y_stride * (mb_rows * 16)` bytes.
    pub y: Vec<u8>,
    /// U chroma plane, row-major, `uv_stride * (mb_rows * 8)` bytes.
    pub u: Vec<u8>,
    /// V chroma plane, same dimensions as `u`.
    pub v: Vec<u8>,
    /// Luma plane stride (= `mb_cols * 16`).
    pub y_stride: usize,
    /// Chroma plane stride (= `mb_cols * 8`).
    pub uv_stride: usize,
    /// Number of macroblock columns of the slot's frame.
    pub mb_cols: usize,
    /// Number of macroblock rows of the slot's frame.
    pub mb_rows: usize,
}

impl RefFrameSlot {
    pub(crate) fn from_keyframe_planes(planes: &KeyframePlanes) -> Self {
        RefFrameSlot {
            y: planes.y.clone(),
            u: planes.u.clone(),
            v: planes.v.clone(),
            y_stride: planes.y_stride,
            uv_stride: planes.uv_stride,
            mb_cols: planes.mb_cols,
            mb_rows: planes.mb_rows,
        }
    }

    /// Borrow the slot as the [`ReferencePlanes`] the §18 motion-comp
    /// fetch consumes.
    pub(crate) fn as_reference_planes(&self) -> ReferencePlanes<'_> {
        ReferencePlanes {
            y: &self.y,
            u: &self.u,
            v: &self.v,
            y_stride: self.y_stride,
            uv_stride: self.uv_stride,
            mb_cols: self.mb_cols,
            mb_rows: self.mb_rows,
        }
    }
}

/// Symbolic source of one rotated reference slot.
///
/// The §9 slot rotation is a pure *select-and-replace* over whole slots: every
/// new `LAST` / `GOLDEN` / `ALTREF` value is one of the four pre-rotation
/// inputs (the three entry slots or the just-decoded frame), never a
/// byte-level mutation of plane data. Resolving each destination to one of
/// these tokens first lets the materialisation step move each owned source
/// into its destination and clone a source only when it genuinely feeds more
/// than one destination — which collapses the common refresh-last path (one
/// destination consumes `Current`, the other two pass `Golden` / `AltRef`
/// through) to zero plane copies.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RotationSource {
    PreLast,
    PreGolden,
    PreAltRef,
    Current,
}

/// Rotate the three reference slots per the §9 / §20-page-147 refresh ladder,
/// consuming the entry slots and the just-decoded frame by value and
/// materialising the next slot-set with the fewest possible plane copies.
///
/// `current` is the just-decoded, post-loop-filter frame. `pre_*` are the
/// entry `self.last` / `golden` / `altref`. The five refresh controls follow
/// the §20 ordering: `copy_buffer_to_alternate` → `copy_buffer_to_golden` →
/// `refresh_golden_frame` → `refresh_alternate_frame` → `refresh_last`. Both
/// copy cases consult the *pre-rotation* slot set (§16), so the resolution
/// reads only the four input tokens and never a partially-rotated value.
///
/// Returns `(new_last, new_golden, new_altref)`. Byte-for-byte identical to a
/// clone-everything staging of the same ladder (`RotationSource` selection is
/// the only logic; materialisation reproduces the selected planes exactly),
/// proved by [`tests::rotation_matches_clone_everything_reference`].
#[allow(clippy::too_many_arguments)]
fn rotate_reference_slots(
    current: RefFrameSlot,
    pre_last: Option<RefFrameSlot>,
    pre_golden: Option<RefFrameSlot>,
    pre_altref: Option<RefFrameSlot>,
    copy_buffer_to_alternate: Option<u8>,
    copy_buffer_to_golden: Option<u8>,
    refresh_golden_frame: Option<bool>,
    refresh_alternate_frame: Option<bool>,
    refresh_last: Option<bool>,
) -> (
    Option<RefFrameSlot>,
    Option<RefFrameSlot>,
    Option<RefFrameSlot>,
) {
    use RotationSource::*;

    // --- Resolve each destination to a symbolic source (no plane data yet). ---
    // ALTREF: copy_buffer_to_alternate (1 = LAST, 2 = GOLDEN) then
    // refresh_alternate_frame overrides with the current frame.
    let mut src_altref = match copy_buffer_to_alternate {
        Some(1) => PreLast,
        Some(2) => PreGolden,
        _ => PreAltRef,
    };
    // GOLDEN: copy_buffer_to_golden (1 = LAST, 2 = ALTREF — the *pre*-rotation
    // ALTREF) then refresh_golden_frame overrides with the current frame.
    let mut src_golden = match copy_buffer_to_golden {
        Some(1) => PreLast,
        Some(2) => PreAltRef,
        _ => PreGolden,
    };
    if refresh_golden_frame == Some(true) {
        src_golden = Current;
    }
    if refresh_alternate_frame == Some(true) {
        src_altref = Current;
    }
    let src_last = if refresh_last == Some(true) {
        Current
    } else {
        PreLast
    };

    // --- Materialise. Move each owned source into the *last* destination that
    // selects it; every earlier destination that selects the same source takes
    // a clone. A source that is `None` and selected yields `None` — identical
    // to cloning a `None` entry slot. ---
    let sources = [src_last, src_golden, src_altref];
    let take_for = |which: usize,
                    pre_last: &mut Option<RefFrameSlot>,
                    pre_golden: &mut Option<RefFrameSlot>,
                    pre_altref: &mut Option<RefFrameSlot>,
                    current: &mut Option<RefFrameSlot>|
     -> Option<RefFrameSlot> {
        let tok = sources[which];
        // Is this the final destination that uses `tok`? If so we may move it
        // out; otherwise clone so later destinations still see the source.
        let is_last_use = !sources[which + 1..].contains(&tok);
        let owned = match tok {
            PreLast => pre_last,
            PreGolden => pre_golden,
            PreAltRef => pre_altref,
            Current => current,
        };
        if is_last_use {
            owned.take()
        } else {
            owned.clone()
        }
    };

    let mut pre_last = pre_last;
    let mut pre_golden = pre_golden;
    let mut pre_altref = pre_altref;
    let mut current = Some(current);

    let new_last = take_for(
        0,
        &mut pre_last,
        &mut pre_golden,
        &mut pre_altref,
        &mut current,
    );
    let new_golden = take_for(
        1,
        &mut pre_last,
        &mut pre_golden,
        &mut pre_altref,
        &mut current,
    );
    let new_altref = take_for(
        2,
        &mut pre_last,
        &mut pre_golden,
        &mut pre_altref,
        &mut current,
    );

    (new_last, new_golden, new_altref)
}

/// Benchmark/measurement shim for the shipped §9 minimal-copy slot
/// rotation [`rotate_reference_slots`]. Exposes the exact move-based
/// rotation `decode_frame` runs so a criterion harness can measure its
/// real per-frame copy cost (zero plane clones on the common refresh-last
/// path) instead of a clone-everything stand-in. Not part of the decoder
/// API — hidden from docs and only meaningful to in-tree benches.
///
/// The argument order mirrors the coded-header fields exactly:
/// `(current, pre_last, pre_golden, pre_altref, copy_buffer_to_alternate,
/// copy_buffer_to_golden, refresh_golden_frame, refresh_alternate_frame,
/// refresh_last)`. `copy_buffer_to_*` use `0` for "no copy" (mapped to
/// `None` internally), matching [`RefreshControls`](crate::RefreshControls).
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn bench_rotate_reference_slots(
    current: RefFrameSlot,
    pre_last: Option<RefFrameSlot>,
    pre_golden: Option<RefFrameSlot>,
    pre_altref: Option<RefFrameSlot>,
    copy_buffer_to_alternate: u8,
    copy_buffer_to_golden: u8,
    refresh_golden_frame: bool,
    refresh_alternate_frame: bool,
    refresh_last: bool,
) -> (
    Option<RefFrameSlot>,
    Option<RefFrameSlot>,
    Option<RefFrameSlot>,
) {
    rotate_reference_slots(
        current,
        pre_last,
        pre_golden,
        pre_altref,
        (copy_buffer_to_alternate != 0).then_some(copy_buffer_to_alternate),
        (copy_buffer_to_golden != 0).then_some(copy_buffer_to_golden),
        Some(refresh_golden_frame),
        Some(refresh_alternate_frame),
        Some(refresh_last),
    )
}

/// Persistent across-frame state of a VP8 decoder — the 3-slot
/// reference-frame buffer (`LAST`, `GOLDEN`, `ALTREF`) plus the §9.10
/// entropy / intra-mode / motion-vector carry-state and the §9.7
/// reference-frame sign bias bits.
///
/// `Vp8DecoderState::new()` starts with no decoded frame yet; the first
/// call to [`Vp8DecoderState::decode_frame`] must therefore be a key
/// frame, otherwise the decoder rejects with [`DecodeError::Unsupported`]
/// (no reference frame to predict from).
#[derive(Debug, Clone)]
pub struct Vp8DecoderState {
    /// `LAST` reference frame — the previously-decoded frame, the default
    /// inter-prediction source. Populated by every key frame and every
    /// frame with `refresh_last = true` (§9.8). `None` before any frame
    /// has been decoded.
    pub last: Option<RefFrameSlot>,
    /// `GOLDEN` reference frame. Populated by every key frame and by the
    /// §9.7 / §16 `refresh_golden_frame` / `copy_buffer_to_golden` rules.
    pub golden: Option<RefFrameSlot>,
    /// `ALTREF` reference frame. Populated by every key frame and by the
    /// §9.7 / §16 `refresh_alternate_frame` / `copy_buffer_to_alternate`
    /// rules.
    pub altref: Option<RefFrameSlot>,
    /// Carried `CoeffProbs` (§13 token probabilities). Starts at
    /// [`DEFAULT_COEFF_PROBS`] (the §13.5 baseline) and is overlaid by
    /// each frame's `token_prob_update()` block per §13.4. When a frame
    /// has `refresh_entropy_probs = false`, the post-frame value is
    /// rolled back to the pre-frame value (the §20 `saved_entropy`
    /// pattern), so the in-frame update is in effect only for the
    /// duration of that single frame.
    ///
    /// [`DEFAULT_COEFF_PROBS`]: crate::dct_tokens::DEFAULT_COEFF_PROBS
    pub coeff_probs: CoeffProbs,
    /// Carried interframe intra-mode probabilities (§16.1 `ymode_prob` /
    /// `uv_mode_prob`). Default at the start of every key frame.
    pub intra_probs: InterFrameIntraProbs,
    /// Carried §17.2 MV contexts (row + column). Default at the start of
    /// every key frame; overlaid by each interframe's `mv_prob_update()`
    /// block. Same `refresh_entropy_probs` rollback behaviour as
    /// [`coeff_probs`](Self::coeff_probs).
    pub mv_contexts: MvContexts,
    /// `sign_bias_golden` / `sign_bias_alternate` carried across frames.
    /// Zeroed on every key frame per §9.7; written by every interframe
    /// from the §19.2 header.
    pub sign_bias: SignBias,
    /// Carried §9.4 reference-frame deltas in
    /// `[CURRENT, LAST, GOLDEN, ALTREF]` order. The §9.4 deltas persist
    /// across frames unless overridden by the current header's
    /// `ref_frame_delta_update`. Zeroed on key frames.
    pub ref_lf_deltas: [i16; 4],
    /// Carried §9.4 mode deltas in
    /// `[B_PRED, ZERO_MV, OTHER_MV, SPLIT_MV]` order. Same persistence
    /// semantics as [`ref_lf_deltas`](Self::ref_lf_deltas).
    pub mode_lf_deltas: [i16; 4],
    /// Visible width carried across frames — VP8 §9.1 only re-transmits
    /// dimensions on key frames; an interframe uses the carried value.
    /// `None` before any key frame has been decoded.
    visible_width: Option<u32>,
    /// Visible height carried across frames — same semantics as
    /// [`visible_width`](Self::visible_width).
    visible_height: Option<u32>,
    /// §9.1 `show_frame` bit of the most recently decoded frame.
    /// `Some(false)` after an "invisible" frame (§9.1: "0 when current
    /// frame is not for display") — typically an altref-update frame
    /// that rotates the §9.7 reference slots without contributing a
    /// picture to the presentation sequence. `None` before any frame
    /// has been decoded successfully.
    last_frame_shown: Option<bool>,
    /// §9.1 `(horizontal_scale, vertical_scale)` upscale codes of the most
    /// recent key frame. `None` before any key frame has been decoded.
    upscale: Option<(ScaleCode, ScaleCode)>,
    /// §9.2 `color_space` bit of the most recent key frame (`false` = the
    /// BT.601-like YUV colour space, `true` = reserved). `None` before any
    /// key frame has been decoded.
    color_space: Option<bool>,
    /// §9.2 `clamping_type` bit of the most recent key frame (`false` =
    /// the decoder must clamp, `true` = the encoder guarantees in-range
    /// pixels). `None` before any key frame has been decoded.
    clamping_type: Option<bool>,
    /// DoS guard: the §9.1 declared `width × height` a key frame may
    /// carry before decode refuses it with
    /// [`DecodeError::FrameTooLarge`](crate::decoder::DecodeError::FrameTooLarge).
    /// Defaults to
    /// [`DEFAULT_MAX_PIXELS_PER_FRAME`](crate::decoder::DEFAULT_MAX_PIXELS_PER_FRAME)
    /// (generous enough to never reject a legal VP8 frame); tightened via
    /// [`with_max_pixels_per_frame`](Self::with_max_pixels_per_frame). Only
    /// key frames re-transmit dimensions, so this is checked on the
    /// key-frame path; interframes inherit the (already-capped) grid of the
    /// key frame that installed the reference slots.
    max_pixels_per_frame: u64,
    /// Thread budget for decoding one frame (`0` / `1` = serial).
    threads: usize,
}

impl Default for Vp8DecoderState {
    fn default() -> Self {
        Self::new()
    }
}

impl Vp8DecoderState {
    /// Build a fresh decoder state. Equivalent to `Default::default()` but
    /// makes the intent at the call site explicit. The first frame fed in
    /// must be a key frame.
    pub fn new() -> Self {
        Vp8DecoderState {
            last: None,
            golden: None,
            altref: None,
            coeff_probs: crate::dct_tokens::DEFAULT_COEFF_PROBS,
            intra_probs: InterFrameIntraProbs::defaults(),
            mv_contexts: default_mv_contexts(),
            sign_bias: SignBias::default(),
            ref_lf_deltas: [0; 4],
            mode_lf_deltas: [0; 4],
            visible_width: None,
            visible_height: None,
            last_frame_shown: None,
            upscale: None,
            color_space: None,
            clamping_type: None,
            max_pixels_per_frame: crate::decoder::DEFAULT_MAX_PIXELS_PER_FRAME,
            threads: 1,
        }
    }

    /// Grant a thread budget for decoding each frame. `0` and `1` both
    /// mean serial (the default); with `n > 1` up to `n` scoped threads
    /// (they end with each `decode_frame` call) share the token parsing,
    /// reconstruction and loop filtering of a frame. The decoded
    /// pictures do not depend on the budget.
    pub fn with_threads(mut self, threads: usize) -> Self {
        self.threads = threads;
        self
    }

    /// Change the thread budget of a running decoder (see
    /// [`with_threads`](Self::with_threads)).
    pub fn set_threads(&mut self, threads: usize) {
        self.threads = threads;
    }

    /// The thread budget granted to this decoder.
    pub fn threads(&self) -> usize {
        self.threads
    }

    /// Tighten the §9.1 declared-frame-size DoS cap.
    ///
    /// A key frame whose declared `width × height` exceeds
    /// `max_pixels_per_frame` is refused with
    /// [`DecodeError::FrameTooLarge`](crate::decoder::DecodeError::FrameTooLarge)
    /// before the decoder allocates its macroblock grid, so a tiny header
    /// declaring an enormous frame cannot drive a large allocation. Builder
    /// form: `Vp8DecoderState::new().with_max_pixels_per_frame(cap)`.
    pub fn with_max_pixels_per_frame(mut self, max_pixels_per_frame: u64) -> Self {
        self.max_pixels_per_frame = max_pixels_per_frame;
        self
    }

    /// Decode one VP8 frame end-to-end, threading reference frames and
    /// entropy carry-state across calls.
    ///
    /// Each call accepts the raw bytes of one VP8 elementary-stream frame
    /// (`one packet = one frame`, regardless of whether the frame is a key
    /// frame or an interframe). The function:
    ///
    /// 1. Parses the §9.1 uncompressed header and the §19.2 boolean-coded
    ///    frame header.
    /// 2. Decodes the §11 / §16 / §19.3 macroblock layer.
    /// 3. Reconstructs the frame's I420 plane buffers, using the
    ///    `LAST` / `GOLDEN` / `ALTREF` reference slots as the §18 motion-comp
    ///    source on inter macroblocks.
    /// 4. Runs the §15.1 loop-filter post-pass.
    /// 5. Updates the entropy / MV / intra-mode carry-state per §9.10
    ///    `refresh_entropy_probs`.
    /// 6. Rotates the reference-frame slots per §9 (`copy_buffer_to_*` /
    ///    `refresh_*`).
    /// 7. Emits a visible-cropped [`Vp8DecodedFrame`].
    ///
    /// The decoder rejects an interframe with no prior key frame as
    /// [`DecodeError::Unsupported`] — the §16 machinery has no reference to
    /// predict from.
    pub fn decode_frame(&mut self, bytes: &[u8]) -> Result<Vp8DecodedFrame, DecodeError> {
        let header = Vp8FrameHeader::parse(bytes)?;
        let shown = header.show_frame;
        let decoded = if header.key_frame {
            self.decode_key_frame(&header, bytes)
        } else {
            self.decode_inter_frame(&header, bytes)
        }?;
        // Record the §9.1 show_frame bit only once the frame has decoded
        // successfully — a failed decode leaves the previous frame's
        // visibility (like every other piece of carried state).
        self.last_frame_shown = Some(shown);
        Ok(decoded)
    }

    /// §9.1 `show_frame` bit of the most recently decoded frame.
    ///
    /// Returns `Some(false)` when that frame was an "invisible" frame —
    /// §9.1 defines `show_frame` as "0 when current frame is not for
    /// display, 1 when current frame is for display". Encoders use
    /// invisible frames to install a prediction-only picture into the
    /// §9.7 GOLDEN / ALTREF slots (e.g. a temporally-filtered altref)
    /// without adding it to the presentation sequence, so a playback
    /// caller should drop the returned picture from display when this
    /// reads `Some(false)` (the reference-slot side effects have already
    /// been applied either way). `None` before any frame has been
    /// decoded successfully.
    pub fn last_frame_shown(&self) -> Option<bool> {
        self.last_frame_shown
    }

    /// Key-frame decode path — re-uses [`decode_vp8`](crate::decoder::decode_vp8)
    /// then installs the result into all three reference slots per §9.7 /
    /// §9.8 and resets the carried entropy state per §16.1 last paragraph /
    /// §17.2.
    fn decode_key_frame(
        &mut self,
        header: &Vp8FrameHeader,
        bytes: &[u8],
    ) -> Result<Vp8DecodedFrame, DecodeError> {
        let width = header.width.unwrap_or(0) as u32;
        let height = header.height.unwrap_or(0) as u32;
        if width == 0 || height == 0 {
            return Err(DecodeError::ZeroDimension);
        }

        // DoS guard: refuse an oversized declared frame before the first
        // macroblock-grid allocation below.
        crate::decoder::check_pixel_cap(width, height, self.max_pixels_per_frame)?;

        let mb_cols = width.div_ceil(16) as usize;
        let mb_rows = height.div_ceil(16) as usize;

        let first_part_offset = header.header_bytes_consumed;
        let first_part_size = header.first_partition_size as usize;
        let available_after_hdr = bytes.len().saturating_sub(first_part_offset);
        if first_part_size > available_after_hdr {
            return Err(DecodeError::TruncatedFirstPartition {
                available: available_after_hdr,
                declared: first_part_size,
            });
        }
        let first_partition = &bytes[first_part_offset..first_part_offset + first_part_size];

        let (coded, mut dec) = Vp8CodedHeader::parse_with_decoder(first_partition, true)?;
        let modes = parse_key_frame_macroblock_modes(&mut dec, &coded, mb_rows, mb_cols)?;
        debug_assert_eq!(modes.len(), mb_rows * mb_cols);

        let dct_section_offset = first_part_offset + first_part_size;
        let dct_section = &bytes[dct_section_offset..];
        let num_partitions = coded.nbr_of_dct_partitions as usize;
        let partitions = crate::decoder::carve_dct_partitions(dct_section, num_partitions)?;

        let dequant_factors = resolve_segment_dequant_factors(&coded);

        // §13 token probabilities: a key frame resets the carried table to
        // the §13.5 defaults before overlaying its own updates (§16.1 last
        // paragraph for intra-mode probs covers the same pattern). The
        // post-frame value is what becomes the next frame's entry state.
        let frame_coeff_probs: CoeffProbs = merge_default_token_probs(&coded.token_prob_updates);

        let lf_config = FrameFilterConfig::keyframe(&coded);
        let planes = {
            // Token decoding and reconstruction as row units (see
            // `rows.rs`) — on the thread budget, or serially row by row
            // so that one row of coefficients is alive at a time — then
            // the row-band filter.
            let (mut planes, has_coeffs) = rows::decode_rows(
                &rows::RowDecode {
                    mb_cols,
                    mb_rows,
                    modes: &modes,
                    predictions: None,
                    references: &[],
                    partitions: &partitions,
                    coeff_probs: &frame_coeff_probs,
                    dequant_factors: &dequant_factors,
                    full_pixel: false,
                    filters: filter_set_for_version(header.version).taps(),
                },
                self.threads,
            )?;
            if lf_config.loop_filter_level != 0 {
                crate::loop_filter::filter_frame_flags_threaded(
                    &mut planes,
                    &modes,
                    &has_coeffs,
                    &lf_config,
                    self.threads,
                );
            }
            planes
        };
        // §9.4 deltas carried into the next frame: on a key frame
        // `ref_delta_current` and `bpred_mode_delta` were resolved from
        // the header (or 0 when delta_enabled is off); the other slots
        // are 0 because the keyframe builder doesn't read them.
        let mut new_ref_deltas = [0i16; 4];
        let mut new_mode_deltas = [0i16; 4];
        new_ref_deltas[0] = lf_config.ref_delta_current;
        new_mode_deltas[0] = lf_config.bpred_mode_delta;
        if coded.mb_lf_adjustments.loop_filter_adj_enable {
            for (i, slot) in new_ref_deltas.iter_mut().enumerate() {
                if let Some(v) = coded.mb_lf_adjustments.ref_frame_delta_update[i] {
                    *slot = v;
                }
            }
            for (i, slot) in new_mode_deltas.iter_mut().enumerate() {
                if let Some(v) = coded.mb_lf_adjustments.mb_mode_delta_update[i] {
                    *slot = v;
                }
            }
        }
        self.ref_lf_deltas = new_ref_deltas;
        self.mode_lf_deltas = new_mode_deltas;

        // §9.7 / §9.8 / §17.2 / §16.1: a key frame implicitly refreshes
        // all three reference slots; entropy / intra-mode / MV tables
        // reset to defaults (with this frame's overlays); sign biases
        // reset to (false, false).
        // Build the visible-cropped output from `planes` first, then MOVE the
        // planes into one of the three slots; the other two take clones (a key
        // frame populates all three slots, so two copies are unavoidable, but
        // the third slot consumes the just-decoded planes without a copy).
        let output = crate::decoder::crop_to_visible_public(&planes, width, height);
        self.golden = Some(RefFrameSlot::from_keyframe_planes(&planes));
        self.altref = Some(RefFrameSlot::from_keyframe_planes(&planes));
        self.last = Some(RefFrameSlot {
            y: planes.y,
            u: planes.u,
            v: planes.v,
            y_stride: planes.y_stride,
            uv_stride: planes.uv_stride,
            mb_cols: planes.mb_cols,
            mb_rows: planes.mb_rows,
        });
        self.coeff_probs = if coded.refresh_entropy_probs {
            frame_coeff_probs
        } else {
            crate::dct_tokens::DEFAULT_COEFF_PROBS
        };
        self.intra_probs = InterFrameIntraProbs::defaults();
        self.mv_contexts = default_mv_contexts();
        self.sign_bias = SignBias::default();
        self.visible_width = Some(width);
        self.visible_height = Some(height);
        self.upscale = Some((
            header.horizontal_scale.unwrap_or(ScaleCode::None),
            header.vertical_scale.unwrap_or(ScaleCode::None),
        ));
        self.color_space = Some(coded.color_space.unwrap_or(false));
        self.clamping_type = Some(coded.clamping_type.unwrap_or(false));

        Ok(output)
    }

    /// Interframe decode path — decode the §11 / §16 macroblock layer,
    /// reconstruct the frame's planes using the carried reference slots,
    /// loop-filter, update carry-state, rotate slots per §9.
    fn decode_inter_frame(
        &mut self,
        header: &Vp8FrameHeader,
        bytes: &[u8],
    ) -> Result<Vp8DecodedFrame, DecodeError> {
        // The first frame of a stream is always a key frame per §4 page 8
        // / §9.1; refuse to decode an interframe without one.
        let last_slot = self.last.as_ref().ok_or(DecodeError::Unsupported(
            "VP8 interframe arrived before any key frame: no reference to predict from",
        ))?;
        let mb_cols = last_slot.mb_cols;
        let mb_rows = last_slot.mb_rows;
        // The width/height encoded in the key frame; preserved on
        // interframes (which do not re-transmit dimensions).
        // We synthesise it from `mb_cols` / `mb_rows` rounded back to
        // pixels — VP8 size words include the visible crop, which we
        // retained on the key-frame call. For now we use the macroblock
        // bounds as the visible dimensions: see the §9.1 spec gap below.
        // Visible dimensions are tracked separately on the slot.
        let visible_width = self.visible_width.unwrap_or((mb_cols * 16) as u32);
        let visible_height = self.visible_height.unwrap_or((mb_rows * 16) as u32);

        let first_part_offset = header.header_bytes_consumed;
        let first_part_size = header.first_partition_size as usize;
        let available_after_hdr = bytes.len().saturating_sub(first_part_offset);
        if first_part_size > available_after_hdr {
            return Err(DecodeError::TruncatedFirstPartition {
                available: available_after_hdr,
                declared: first_part_size,
            });
        }
        let first_partition = &bytes[first_part_offset..first_part_offset + first_part_size];

        let (coded, mut dec) = Vp8CodedHeader::parse_with_decoder(first_partition, false)?;

        // ---- §13 token probability table: overlay the frame's updates on
        //      the carried table; save the entry-state for the §9.10
        //      `refresh_entropy_probs` rollback.
        let saved_entry_coeff_probs = self.coeff_probs;
        let saved_entry_mv_contexts = self.mv_contexts;
        let saved_entry_intra_probs = self.intra_probs;

        let frame_coeff_probs: CoeffProbs =
            overlay_token_probs(&self.coeff_probs, &coded.token_prob_updates);
        let frame_intra_probs = InterFrameIntraProbs::for_frame_header(self.intra_probs, &coded);
        let frame_mv_contexts = match &coded.mv_prob_update {
            Some(updates) => resolve_mv_contexts(&self.mv_contexts, updates),
            None => self.mv_contexts,
        };

        // §9.7: sign biases for the current frame.
        let frame_sign_bias = SignBias::new(
            coded.sign_bias_golden.unwrap_or(false),
            coded.sign_bias_alternate.unwrap_or(false),
        );

        // ---- §16 / §19.3 macroblock decode (modes + residuals + per-MB
        //      reconstruction). Unlike the keyframe path the macroblock
        //      prediction header is interleaved with the residual reads
        //      across two partitions (control + DCT), so we cannot pre-walk
        //      modes; we walk MBs row-by-row, calling the right §16 helper
        //      per MB.
        let dct_section_offset = first_part_offset + first_part_size;
        let dct_section = &bytes[dct_section_offset..];
        let num_partitions = coded.nbr_of_dct_partitions as usize;
        let partitions = crate::decoder::carve_dct_partitions(dct_section, num_partitions)?;

        let dequant_factors = resolve_segment_dequant_factors(&coded);

        let (mut planes, modes_out, has_coeffs_out, ref_frames_out, inter_modes_out) = if self
            .threads
            > 1
        {
            self.decode_inter_rows_threaded(
                header,
                &coded,
                &mut dec,
                &partitions,
                &dequant_factors,
                &frame_coeff_probs,
                &frame_intra_probs,
                &frame_mv_contexts,
                frame_sign_bias,
            )?
        } else {
            // Allocate the output planes (same macroblock-aligned layout as
            // the key-frame path; we crop at the end).
            let y_stride = mb_cols * 16;
            let uv_stride = mb_cols * 8;
            let mut planes = KeyframePlanes {
                y: vec![0u8; y_stride * mb_rows * 16],
                u: vec![0u8; uv_stride * mb_rows * 8],
                v: vec![0u8; uv_stride * mb_rows * 8],
                y_stride,
                uv_stride,
                mb_cols,
                mb_rows,
            };

            // Per-row entropy context (§13.3): one above context per MB column
            // (lives across the whole frame), one left context per row.
            let mut above_entropy = vec![MbEntropyCtx::default(); mb_cols];

            // §16.3 inter-MB neighbour records — one row of `mb_cols` above
            // and one trailing `left` per row.
            let mut above_mb: Vec<MbInfo> = vec![MbInfo::border(); mb_cols];

            // Per-MB recorded mode + coeffs for the §15 loop-filter pass.
            // §16 interframe per-MB outputs. Every macroblock is decoded
            // exactly once, in raster order (`mb_row` outer, `mb_col` inner),
            // and its four side-band records are written together at the end of
            // the iteration before anything reads them back (the §15 loop filter
            // consumes them only after the whole frame is decoded). The previous
            // `vec![default(); N]` + indexed assignment paid a full-frame bulk
            // default-fill (the `MbCoeffs` lane alone is 800 bytes per MB) plus a
            // `sentinel_mode` clone for every `modes_out` slot, all immediately
            // overwritten. Reserve the slots and `push` instead: identical
            // raster-ordered contents, no reallocation, and the dead initial
            // fill (the `__bzero` / `memset` the decode profile flags) is gone.
            let mut modes_out: Vec<MacroblockModes> = Vec::with_capacity(mb_rows * mb_cols);
            // The §15 loop filter consumes the per-MB coefficients only through
            // `mb_has_coeffs` (a single boolean per MB). Compute that flag inline
            // while the freshly-decoded `mb_coeffs` is hot in cache and store only
            // the `bool` — avoids holding a whole-frame `Vec<MbCoeffs>`
            // (≈ 800 bytes / MB) alive just to feed one boolean reduction.
            let mut has_coeffs_out: Vec<bool> = Vec::with_capacity(mb_rows * mb_cols);
            let mut ref_frames_out: Vec<Option<RefFrame>> = Vec::with_capacity(mb_rows * mb_cols);
            let mut inter_modes_out: Vec<Option<InterMode>> = Vec::with_capacity(mb_rows * mb_cols);

            // DCT-partition bool decoders, lazily initialised per the §20.4
            // round-robin row-striping rule (matches the keyframe path).
            let mut partition_decoders: Vec<Option<BoolDecoder<'_>>> =
                (0..num_partitions).map(|_| None).collect();
            for mb_row in 0..mb_rows {
                let part_idx = mb_row % num_partitions;
                if partition_decoders[part_idx].is_none() {
                    // Use the §20-reference tolerant init: a tiny ALTREF-style
                    // frame can produce a DCT body with <2 bytes when every
                    // macroblock is `mb_skip = 1`. The §20 spec body sets
                    // `value = 0`, leaves `input = NULL` and reads bits
                    // succeed against `value = 0` (which yields `mb_skip = 1`
                    // for the dominant probability).
                    let bd = BoolDecoder::init_partition(partitions[part_idx]);
                    partition_decoders[part_idx] = Some(bd);
                }
            }

            // Frame-header gates for the per-MB prefix (§19.3 `macroblock_header()`).
            let segmentation_active = coded.segmentation_enabled
                && coded
                    .update_segmentation
                    .as_ref()
                    .is_some_and(|seg| seg.update_mb_segmentation_map);
            let segment_probs: [u8; 3] = if segmentation_active {
                let seg = coded
                    .update_segmentation
                    .as_ref()
                    .expect("segmentation_active implies update_segmentation is Some");
                let mut p = [255u8; 3];
                for (i, slot) in p.iter_mut().enumerate() {
                    if let Some(v) = seg.segment_prob[i] {
                        *slot = v;
                    }
                }
                p
            } else {
                [255; 3]
            };
            let skip_active = coded.mb_no_skip_coeff;
            let skip_prob = coded.prob_skip_false.unwrap_or(0);
            let prob_intra = coded.prob_intra.unwrap_or(0);
            let prob_last = coded.prob_last.unwrap_or(0);
            let prob_gf = coded.prob_gf.unwrap_or(0);

            let full_pixel = matches!(header.version, 3);
            let filters = filter_set_for_version(header.version).taps();

            for mb_row in 0..mb_rows {
                let mut left_entropy = MbEntropyCtx::default();
                let mut left_mb = MbInfo::border();
                let mut aboveleft_mb = MbInfo::border();

                for mb_col in 0..mb_cols {
                    let raster = mb_row * mb_cols + mb_col;

                    // §19.3 macroblock_header() prefix on an interframe:
                    // segment_id → mb_skip_coeff → is_inter_mb.
                    let segment_id = if segmentation_active {
                        Some(read_segment_id(&mut dec, &segment_probs)?)
                    } else {
                        None
                    };
                    let mb_skip_coeff = if skip_active {
                        dec.read_bool(skip_prob)?
                    } else {
                        false
                    };
                    let is_inter_mb = dec.read_bool(prob_intra)?;

                    let mb_info: MbInfo;
                    let mode_record: MacroblockModes;
                    let mb_coeffs: MbCoeffs;
                    let recon: ReconstructedMb;
                    // For the §15 loop-filter delta lookup we track per-MB:
                    // (a) the reference frame (None = intra) and
                    // (b) the InterMode (None = intra). These are separate
                    // from `MbInfo.ref_frame` / `MacroblockModes.y_mode`
                    // because the loop-filter ladder selects on the
                    // resolved §16.2 mode (ZEROMV / NEW / SPLIT) which the
                    // §15.1 "skip rule" `y_mode` field does not preserve.
                    let mut filter_ref_frame: Option<RefFrame> = None;
                    let mut filter_inter_mode: Option<InterMode> = None;

                    if is_inter_mb {
                        // §16.2: pick the reference frame.
                        let current_ref = select_ref_frame(&mut dec, prob_last, prob_gf)?;
                        filter_ref_frame = Some(current_ref);

                        // Resolve neighbour record for the census.
                        let above = above_mb[mb_col];
                        let above_left = aboveleft_mb;
                        let left = left_mb;

                        // §16.3 census + §16.2 inter-mode tree.
                        let near =
                            find_near_mvs(&above, &left, &above_left, current_ref, frame_sign_bias);
                        let probs = mv_ref_probs(&near.cnt);
                        let mode = read_inter_mode(&mut dec, &probs)?;
                        filter_inter_mode = Some(mode);

                        // The residual for an inter MB has Y2 unless this MB is
                        // SPLITMV (§14.2 page 76 / §19.3 residual_data()).
                        let has_y2 = !matches!(mode, InterMode::Split);

                        // Read MVs + decode residual + reconstruct.
                        let part_idx = mb_row % num_partitions;
                        let dec_dct = partition_decoders[part_idx]
                            .as_mut()
                            .expect("partition decoder initialised above");
                        let seg = segment_id.unwrap_or(0) as usize;
                        let seg = seg.min(MAX_MB_SEGMENTS - 1);
                        let factors = &dequant_factors[seg];

                        let reference_slot = self
                            .slot_for_ref(current_ref)
                            .ok_or(DecodeError::Unsupported(
                            "VP8 interframe references a frame slot that has not been populated yet",
                        ))?;
                        let reference = reference_slot.as_reference_planes();

                        // We need the bounds for clamping MVs. For NEWMV the
                        // §17 differential is read *now*, so we resolve the
                        // full vector here rather than via `decode_inter_mb`
                        // (which reads probabilities + decodes MVs internally
                        // — we've already read the probabilities; we'd
                        // double-walk if we recursed in).
                        let bounds = MvClampRect::for_mb(mb_col, mb_row, mb_cols, mb_rows);
                        let resolved = resolve_inter_mb_mv_after_mode(
                            &mut dec,
                            mode,
                            &near,
                            &above,
                            &left,
                            &above_left,
                            current_ref,
                            frame_sign_bias,
                            &bounds,
                            &frame_mv_contexts,
                        )?;

                        match resolved {
                            ResolvedInterMode::Whole { mv, .. } => {
                                // Decode + dequantize residual.
                                let above_ctx = &mut above_entropy[mb_col];
                                mb_coeffs = decode_and_dequantize_mb(
                                    dec_dct,
                                    has_y2,
                                    mb_skip_coeff,
                                    &frame_coeff_probs,
                                    factors,
                                    above_ctx,
                                    &mut left_entropy,
                                )
                                .map_err(|source| {
                                    DecodeError::MbCoeffs {
                                        index: raster,
                                        source,
                                    }
                                })?;
                                // §18 prediction + §14 residue.
                                recon = reconstruct_inter_mb(
                                    &reference,
                                    mb_col,
                                    mb_row,
                                    mv,
                                    full_pixel,
                                    filters,
                                    mb_skip_coeff,
                                    &mb_coeffs.y2,
                                    &mb_coeffs.y,
                                    &mb_coeffs.u,
                                    &mb_coeffs.v,
                                );
                                mode_record = MacroblockModes {
                                    segment_id,
                                    mb_skip_coeff,
                                    // No intra modes for an inter MB — but the
                                    // §15 loop filter only looks at y_mode to
                                    // distinguish B_PRED from the rest. We map
                                    // every whole-MB inter mode to DC_PRED for
                                    // the filter's `skip` rule.
                                    y_mode: IntraYMode::Dc,
                                    subblock_modes: None,
                                    uv_mode: crate::macroblock::IntraUvMode::Dc,
                                };
                                mb_info = MbInfo {
                                    ref_frame: Some(current_ref),
                                    mv,
                                    is_split: false,
                                    split_mvs: None,
                                };
                            }
                            ResolvedInterMode::Split { best } => {
                                // SPLITMV: read partition + per-sub-block
                                // vectors, then reconstruct.
                                let split: SplitMvResult = decode_split_mv(
                                    &mut dec,
                                    &above,
                                    &left,
                                    best,
                                    &frame_mv_contexts,
                                )?;

                                let above_ctx = &mut above_entropy[mb_col];
                                mb_coeffs = decode_and_dequantize_mb(
                                    dec_dct,
                                    false, // no Y2 for SPLITMV
                                    mb_skip_coeff,
                                    &frame_coeff_probs,
                                    factors,
                                    above_ctx,
                                    &mut left_entropy,
                                )
                                .map_err(|source| {
                                    DecodeError::MbCoeffs {
                                        index: raster,
                                        source,
                                    }
                                })?;
                                recon = reconstruct_split_mv_mb(
                                    &reference,
                                    mb_col,
                                    mb_row,
                                    &split.split_mvs,
                                    full_pixel,
                                    filters,
                                    mb_skip_coeff,
                                    &mb_coeffs.y,
                                    &mb_coeffs.u,
                                    &mb_coeffs.v,
                                );
                                mode_record = MacroblockModes {
                                    segment_id,
                                    mb_skip_coeff,
                                    // SPLITMV's §15 loop-filter rule mirrors
                                    // B_PRED ("internal edges always filtered")
                                    // — map y_mode to B for the filter
                                    // geometry skip rule.
                                    y_mode: IntraYMode::B,
                                    subblock_modes: None,
                                    uv_mode: crate::macroblock::IntraUvMode::Dc,
                                };
                                mb_info = MbInfo {
                                    ref_frame: Some(current_ref),
                                    mv: split.split_mvs[15],
                                    is_split: true,
                                    split_mvs: Some(split.split_mvs),
                                };
                            }
                        }
                    } else {
                        // §16.1 intra-on-interframe macroblock.
                        let modes = parse_inter_frame_intra_macroblock_modes(
                            &mut dec,
                            &frame_intra_probs,
                            segment_id,
                            mb_skip_coeff,
                        )?;

                        let part_idx = mb_row % num_partitions;
                        let dec_dct = partition_decoders[part_idx]
                            .as_mut()
                            .expect("partition decoder initialised above");
                        let seg = segment_id.unwrap_or(0) as usize;
                        let seg = seg.min(MAX_MB_SEGMENTS - 1);
                        let factors = &dequant_factors[seg];

                        let has_y2 = modes.y_mode != IntraYMode::B;
                        let above_ctx = &mut above_entropy[mb_col];
                        mb_coeffs = decode_and_dequantize_mb(
                            dec_dct,
                            has_y2,
                            mb_skip_coeff,
                            &frame_coeff_probs,
                            factors,
                            above_ctx,
                            &mut left_entropy,
                        )
                        .map_err(|source| DecodeError::MbCoeffs {
                            index: raster,
                            source,
                        })?;

                        // Intra reconstruction uses the in-frame neighbours
                        // (already-written `planes`), reusing the keyframe
                        // per-MB orchestrators.
                        let neighbors =
                            crate::frame::gather_neighbors_public(&planes, mb_row, mb_col);
                        recon = if modes.y_mode == IntraYMode::B {
                            crate::reconstruct::decode_keyframe_mb_bpred(
                                modes.subblock_modes.as_ref(),
                                modes.uv_mode,
                                mb_skip_coeff,
                                &neighbors,
                                &mb_coeffs.y,
                                &mb_coeffs.u,
                                &mb_coeffs.v,
                            )
                        } else {
                            crate::reconstruct::decode_keyframe_mb_non_bpred(
                                modes.y_mode,
                                modes.uv_mode,
                                mb_skip_coeff,
                                &neighbors,
                                &mb_coeffs.y2,
                                &mb_coeffs.y,
                                &mb_coeffs.u,
                                &mb_coeffs.v,
                            )
                        }
                        .map_err(|source| {
                            DecodeError::Frame(FrameError::Macroblock {
                                index: raster,
                                source,
                            })
                        })?;

                        mode_record = modes;
                        mb_info = MbInfo {
                            ref_frame: None,
                            mv: Mv::default(),
                            is_split: false,
                            split_mvs: None,
                        };
                    }

                    // Write the reconstructed MB into the frame buffers.
                    crate::frame::write_mb_public(&mut planes, mb_row, mb_col, &recon);

                    debug_assert_eq!(
                        modes_out.len(),
                        raster,
                        "per-MB outputs pushed in raster order"
                    );
                    modes_out.push(mode_record);
                    has_coeffs_out.push(crate::loop_filter::mb_has_coeffs(&mb_coeffs));
                    ref_frames_out.push(filter_ref_frame);
                    inter_modes_out.push(filter_inter_mode);

                    // Advance neighbour records.
                    aboveleft_mb = above_mb[mb_col];
                    left_mb = mb_info;
                    above_mb[mb_col] = mb_info;
                }
            }
            (
                planes,
                modes_out,
                has_coeffs_out,
                ref_frames_out,
                inter_modes_out,
            )
        };

        // ---- §15 loop filter ---------------------------------------------
        // Build the interframe filter config from the header + carried
        // §9.4 deltas; persist the resolved deltas back into the state
        // for the next frame's overlay (the §9.4 "deltas persist until
        // updated" rule).
        let lf_config =
            FrameFilterConfig::interframe(&coded, self.ref_lf_deltas, self.mode_lf_deltas);
        self.ref_lf_deltas = lf_config.ref_deltas();
        self.mode_lf_deltas = lf_config.mode_deltas();
        if lf_config.loop_filter_level != 0 {
            crate::loop_filter::filter_inter_frame_flags_threaded(
                &mut planes,
                &modes_out,
                &has_coeffs_out,
                &ref_frames_out,
                &inter_modes_out,
                &lf_config,
                self.threads,
            );
        }

        // ---- §9.10 entropy carry-state rollback / commit ------------------
        // The §20 reference pattern: if refresh_entropy_probs == false,
        // restore the entry-state (the changes were in effect only for the
        // current frame). Same for the MV contexts and intra-mode probs —
        // those updates are also gated by `refresh_entropy_probs` per §9.10
        // (the "saved_entropy" block in the §20 listing covers the entire
        // `entropy_hdr` including all three sub-tables).
        if coded.refresh_entropy_probs {
            self.coeff_probs = frame_coeff_probs;
            self.mv_contexts = frame_mv_contexts;
            self.intra_probs = frame_intra_probs;
        } else {
            self.coeff_probs = saved_entry_coeff_probs;
            self.mv_contexts = saved_entry_mv_contexts;
            self.intra_probs = saved_entry_intra_probs;
        }
        self.sign_bias = frame_sign_bias;

        // ---- §9 reference-frame slot rotation -----------------------------
        // §20 page 147 ordering: copy_arf → copy_gf → refresh_gf →
        // refresh_arf → refresh_last. The "copy" cases consult the CURRENT
        // slot-set (before refresh), so the entry slots and the just-decoded
        // frame are passed by value into the move-minimising rotation. Build
        // the visible-cropped output frame from `planes` first so the
        // just-decoded slot can MOVE `planes` instead of cloning it.
        let output = crate::decoder::crop_to_visible_public(&planes, visible_width, visible_height);
        let current_slot = RefFrameSlot {
            y: planes.y,
            u: planes.u,
            v: planes.v,
            y_stride: planes.y_stride,
            uv_stride: planes.uv_stride,
            mb_cols: planes.mb_cols,
            mb_rows: planes.mb_rows,
        };
        let (new_last, new_golden, new_altref) = rotate_reference_slots(
            current_slot,
            self.last.take(),
            self.golden.take(),
            self.altref.take(),
            coded.copy_buffer_to_alternate,
            coded.copy_buffer_to_golden,
            coded.refresh_golden_frame,
            coded.refresh_alternate_frame,
            coded.refresh_last,
        );

        self.last = new_last;
        self.golden = new_golden;
        self.altref = new_altref;

        Ok(output)
    }

    /// The macroblock layer of an interframe on the thread budget: the
    /// §19.3 mode layer is parsed here, on the calling thread (it is one
    /// arithmetic-coded stream and does not depend on the residuals);
    /// token decoding and reconstruction then run as row units (see
    /// `rows.rs`). Returns what the serial walk produces: the unfiltered
    /// planes and the per-macroblock records the loop filter reads.
    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
    fn decode_inter_rows_threaded(
        &self,
        header: &Vp8FrameHeader,
        coded: &Vp8CodedHeader,
        dec: &mut BoolDecoder<'_>,
        partitions: &[&[u8]],
        dequant_factors: &[MbDequantFactors; MAX_MB_SEGMENTS],
        frame_coeff_probs: &CoeffProbs,
        frame_intra_probs: &InterFrameIntraProbs,
        frame_mv_contexts: &MvContexts,
        frame_sign_bias: SignBias,
    ) -> Result<
        (
            KeyframePlanes,
            Vec<MacroblockModes>,
            Vec<bool>,
            Vec<Option<RefFrame>>,
            Vec<Option<InterMode>>,
        ),
        DecodeError,
    > {
        let last_slot = self.last.as_ref().expect("the caller checked LAST");
        let (mb_cols, mb_rows) = (last_slot.mb_cols, last_slot.mb_rows);
        let n = mb_rows * mb_cols;

        // The populated reference slots, and each frame's index among
        // them.
        let mut references: Vec<ReferencePlanes<'_>> = Vec::with_capacity(3);
        let mut reference_index = [None; 3];
        for (slot, r) in [RefFrame::Last, RefFrame::Golden, RefFrame::AltRef]
            .into_iter()
            .enumerate()
        {
            if let Some(planes) = self.slot_for_ref(r) {
                reference_index[slot] = Some(references.len());
                references.push(planes.as_reference_planes());
            }
        }
        let index_of = |r: RefFrame| -> Result<usize, DecodeError> {
            let slot = match r {
                RefFrame::Last => 0,
                RefFrame::Golden => 1,
                RefFrame::AltRef => 2,
            };
            reference_index[slot].ok_or(DecodeError::Unsupported(
                "VP8 interframe references a frame slot that has not been populated yet",
            ))
        };

        // Frame-header gates for the per-MB prefix (§19.3
        // `macroblock_header()`), as in the serial walk.
        let segmentation = coded
            .update_segmentation
            .as_ref()
            .filter(|seg| coded.segmentation_enabled && seg.update_mb_segmentation_map);
        let segment_probs: [u8; 3] = match segmentation {
            Some(seg) => core::array::from_fn(|i| seg.segment_prob[i].unwrap_or(255)),
            None => [255; 3],
        };
        let skip_active = coded.mb_no_skip_coeff;
        let skip_prob = coded.prob_skip_false.unwrap_or(0);
        let prob_intra = coded.prob_intra.unwrap_or(0);
        let prob_last = coded.prob_last.unwrap_or(0);
        let prob_gf = coded.prob_gf.unwrap_or(0);

        let mut modes_out: Vec<MacroblockModes> = Vec::with_capacity(n);
        let mut predictions: Vec<rows::Prediction> = Vec::with_capacity(n);
        let mut ref_frames_out: Vec<Option<RefFrame>> = Vec::with_capacity(n);
        let mut inter_modes_out: Vec<Option<InterMode>> = Vec::with_capacity(n);
        let mut above_mb: Vec<MbInfo> = vec![MbInfo::border(); mb_cols];
        for mb_row in 0..mb_rows {
            let mut left_mb = MbInfo::border();
            let mut aboveleft_mb = MbInfo::border();
            for (mb_col, above_slot) in above_mb.iter_mut().enumerate() {
                // segment_id → mb_skip_coeff → is_inter_mb.
                let segment_id = if segmentation.is_some() {
                    Some(read_segment_id(dec, &segment_probs)?)
                } else {
                    None
                };
                let mb_skip_coeff = if skip_active {
                    dec.read_bool(skip_prob)?
                } else {
                    false
                };
                let is_inter_mb = dec.read_bool(prob_intra)?;
                let mb_info = if is_inter_mb {
                    let current_ref = select_ref_frame(dec, prob_last, prob_gf)?;
                    let (above, left, above_left) = (*above_slot, left_mb, aboveleft_mb);
                    let near =
                        find_near_mvs(&above, &left, &above_left, current_ref, frame_sign_bias);
                    let probs = mv_ref_probs(&near.cnt);
                    let mode = read_inter_mode(dec, &probs)?;
                    let reference = index_of(current_ref)?;
                    let bounds = MvClampRect::for_mb(mb_col, mb_row, mb_cols, mb_rows);
                    let resolved = resolve_inter_mb_mv_after_mode(
                        dec,
                        mode,
                        &near,
                        &above,
                        &left,
                        &above_left,
                        current_ref,
                        frame_sign_bias,
                        &bounds,
                        frame_mv_contexts,
                    )?;
                    ref_frames_out.push(Some(current_ref));
                    inter_modes_out.push(Some(mode));
                    match resolved {
                        ResolvedInterMode::Whole { mv, .. } => {
                            // A whole-block inter macroblock filters like
                            // `DC_PRED` (see the serial walk).
                            modes_out.push(MacroblockModes {
                                segment_id,
                                mb_skip_coeff,
                                y_mode: IntraYMode::Dc,
                                subblock_modes: None,
                                uv_mode: crate::macroblock::IntraUvMode::Dc,
                            });
                            predictions.push(rows::Prediction::Whole { reference, mv });
                            MbInfo {
                                ref_frame: Some(current_ref),
                                mv,
                                is_split: false,
                                split_mvs: None,
                            }
                        }
                        ResolvedInterMode::Split { best } => {
                            let split: SplitMvResult =
                                decode_split_mv(dec, &above, &left, best, frame_mv_contexts)?;
                            // `SPLITMV` filters like `B_PRED`.
                            modes_out.push(MacroblockModes {
                                segment_id,
                                mb_skip_coeff,
                                y_mode: IntraYMode::B,
                                subblock_modes: None,
                                uv_mode: crate::macroblock::IntraUvMode::Dc,
                            });
                            predictions.push(rows::Prediction::Split {
                                reference,
                                mvs: split.split_mvs,
                            });
                            MbInfo {
                                ref_frame: Some(current_ref),
                                mv: split.split_mvs[15],
                                is_split: true,
                                split_mvs: Some(split.split_mvs),
                            }
                        }
                    }
                } else {
                    let modes = parse_inter_frame_intra_macroblock_modes(
                        dec,
                        frame_intra_probs,
                        segment_id,
                        mb_skip_coeff,
                    )?;
                    modes_out.push(modes);
                    predictions.push(rows::Prediction::Intra);
                    ref_frames_out.push(None);
                    inter_modes_out.push(None);
                    MbInfo {
                        ref_frame: None,
                        mv: Mv::default(),
                        is_split: false,
                        split_mvs: None,
                    }
                };
                aboveleft_mb = *above_slot;
                left_mb = mb_info;
                *above_slot = mb_info;
            }
        }

        let (planes, has_coeffs) = rows::decode_rows(
            &rows::RowDecode {
                mb_cols,
                mb_rows,
                modes: &modes_out,
                predictions: Some(&predictions),
                references: &references,
                partitions,
                coeff_probs: frame_coeff_probs,
                dequant_factors,
                full_pixel: matches!(header.version, 3),
                filters: filter_set_for_version(header.version).taps(),
            },
            self.threads,
        )?;
        Ok((
            planes,
            modes_out,
            has_coeffs,
            ref_frames_out,
            inter_modes_out,
        ))
    }

    /// Return the reference-frame slot indexed by `r`. `None` if that slot
    /// has not been populated yet.
    fn slot_for_ref(&self, r: RefFrame) -> Option<&RefFrameSlot> {
        match r {
            RefFrame::Last => self.last.as_ref(),
            RefFrame::Golden => self.golden.as_ref(),
            RefFrame::AltRef => self.altref.as_ref(),
        }
    }

    /// Visible width carried from the most recent key frame, if any.
    /// Interframes do not re-transmit dimensions, so we remember them
    /// per-key-frame and emit them with every subsequent decoded frame.
    pub fn visible_width(&self) -> Option<u32> {
        self.visible_width
    }
    /// Visible height carried from the most recent key frame.
    pub fn visible_height(&self) -> Option<u32> {
        self.visible_height
    }

    /// §9.1 `(horizontal_scale, vertical_scale)` upscale codes carried
    /// from the most recent key frame, if any.
    ///
    /// §9.1: "Upscaling does not affect the reconstruction buffer" — the
    /// decoded planes stay at [`visible_width`](Self::visible_width) ×
    /// [`visible_height`](Self::visible_height); the codes are a display
    /// hint the presentation layer may apply with any reasonable
    /// upsampler.
    pub fn upscale(&self) -> Option<(ScaleCode, ScaleCode)> {
        self.upscale
    }

    /// §9.2 `color_space` bit carried from the most recent key frame:
    /// `Some(false)` = "YUV color space similar to the YCrCb color space
    /// defined in [ITU-R_BT.601]", `Some(true)` = reserved. `None` before
    /// any key frame has been decoded.
    pub fn color_space(&self) -> Option<bool> {
        self.color_space
    }

    /// §9.2 `clamping_type` bit carried from the most recent key frame:
    /// `Some(false)` = the decoder is required to clamp reconstructed
    /// pixels to `0..=255`, `Some(true)` = the encoder guarantees they
    /// already are. `None` before any key frame has been decoded.
    pub fn clamping_type(&self) -> Option<bool> {
        self.clamping_type
    }

    /// The §9.1 DoS cap this state enforces on key-frame dimensions
    /// (see [`with_max_pixels_per_frame`](Self::with_max_pixels_per_frame)).
    pub fn max_pixels_per_frame(&self) -> u64 {
        self.max_pixels_per_frame
    }
}

/// Helper: parse a 2-bit segment-id literal against the §10
/// `mb_segment_tree_probs` (re-implementation of the keyframe-path
/// helper, exposed in this module so the interframe driver can call it
/// without re-routing through the keyframe-only function).
fn read_segment_id(
    dec: &mut BoolDecoder<'_>,
    probs: &[u8; 3],
) -> Result<u8, crate::bool_decoder::BoolDecoderError> {
    let b0 = dec.read_bool(probs[0])? as u8;
    if b0 == 0 {
        let b1 = dec.read_bool(probs[1])? as u8;
        Ok(b1) // 0 or 1
    } else {
        let b2 = dec.read_bool(probs[2])? as u8;
        Ok(2 + b2) // 2 or 3
    }
}

/// Resolve the four per-segment dequant factors for a frame (the
/// interframe-friendly version of `resolve_segment_dequant_factors` in
/// `decoder`; both apply the §10 segment override on the §9.6 baseline).
fn resolve_segment_dequant_factors(coded: &Vp8CodedHeader) -> [MbDequantFactors; MAX_MB_SEGMENTS] {
    let base = MbDequantFactors::from_quant_indices(&coded.quant_indices);
    let mut out = [base; MAX_MB_SEGMENTS];
    if coded.segmentation_enabled
        && let Some(seg) = coded.update_segmentation
    {
        for (i, slot) in out.iter_mut().enumerate() {
            let qval = seg.quantizer_update[i].unwrap_or(0) as i32;
            *slot = MbDequantFactors::for_segment(
                &coded.quant_indices,
                qval,
                seg.segment_feature_mode_absolute,
            );
        }
    }
    out
}

/// Overlay a frame's `token_prob_update()` block onto a carried CoeffProbs.
/// The §13.4 rule: each entry in the update block either replaces the
/// position's probability or leaves it unchanged.
fn overlay_token_probs(
    carried: &CoeffProbs,
    updates: &crate::coded_header::TokenProbUpdates,
) -> CoeffProbs {
    let mut out = *carried;
    for (plane_idx, plane) in updates.iter().enumerate() {
        for (band_idx, band) in plane.iter().enumerate() {
            for (prev_idx, ctx) in band.iter().enumerate() {
                for (pos_idx, slot) in ctx.iter().enumerate() {
                    if let Some(p) = *slot {
                        out[plane_idx][band_idx][prev_idx][pos_idx] = p;
                    }
                }
            }
        }
    }
    out
}

/// Resolve the per-MB inter-mode after the caller has already read the
/// reference-frame selection bit. Splits the mode read from the §17 MV
/// read so this driver can share state with the residual decode (the
/// `decode_inter_mb` driver internally re-runs the census + mode walk,
/// which we've already done).
#[allow(clippy::too_many_arguments)]
fn resolve_inter_mb_mv_after_mode(
    dec: &mut BoolDecoder<'_>,
    mode: InterMode,
    near: &crate::near_mv::NearMvs,
    above: &MbInfo,
    left: &MbInfo,
    above_left: &MbInfo,
    current_ref: RefFrame,
    sign_bias: SignBias,
    bounds: &MvClampRect,
    mv_contexts: &MvContexts,
) -> Result<ResolvedInterMode, InterMbError> {
    use crate::motion_vector::read_mv;
    match mode {
        InterMode::Zero => Ok(ResolvedInterMode::Whole {
            mode,
            mv: Mv::default(),
        }),
        InterMode::Nearest => Ok(ResolvedInterMode::Whole {
            mode,
            mv: clamp_mv(near.mvs[1], bounds),
        }),
        InterMode::Near => Ok(ResolvedInterMode::Whole {
            mode,
            mv: clamp_mv(near.mvs[2], bounds),
        }),
        InterMode::New => {
            // §18.1 page 114 secondary clamp on "best".
            let best = clamp_mv(near.mvs[0], bounds);
            let diff = read_mv(dec, mv_contexts)?;
            let mv = Mv {
                row: best.row.wrapping_add(diff.row),
                col: best.col.wrapping_add(diff.col),
            };
            Ok(ResolvedInterMode::Whole { mode, mv })
        }
        InterMode::Split => {
            // Drive through resolve_inter_mb_mv to share the SPLITMV best
            // computation; the caller will then call decode_split_mv.
            let best = clamp_mv(near.mvs[0], bounds);
            // We did not consume any MV bits for SPLITMV here; the caller
            // will run decode_split_mv next.
            let _ = (above, left, above_left, current_ref, sign_bias);
            Ok(ResolvedInterMode::Split { best })
        }
    }
}

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

    /// Strip the 32-byte DKIF header off an IVF file and yield successive
    /// elementary-stream frames as `&[u8]`. Each frame is preceded by a
    /// 12-byte little-endian header (`size_le32`, `pts_le64`). Stops at
    /// EOF.
    fn iter_ivf_frames(ivf: &[u8]) -> Vec<&[u8]> {
        assert_eq!(&ivf[0..4], b"DKIF", "expected DKIF magic");
        let mut out = Vec::new();
        let mut cur = 32usize;
        while cur + 12 <= ivf.len() {
            let size =
                u32::from_le_bytes([ivf[cur], ivf[cur + 1], ivf[cur + 2], ivf[cur + 3]]) as usize;
            let body = cur + 12;
            assert!(body + size <= ivf.len(), "IVF frame body truncated");
            out.push(&ivf[body..body + size]);
            cur = body + size;
        }
        out
    }

    /// Build a `RefFrameSlot` whose plane bytes uniquely identify it by `tag`
    /// so the equivalence test can assert *which* source landed in each
    /// destination, not just that some slot did.
    fn tagged_slot(tag: u8) -> RefFrameSlot {
        RefFrameSlot {
            y: vec![tag; 4],
            u: vec![tag; 2],
            v: vec![tag; 2],
            y_stride: 2,
            uv_stride: 1,
            mb_cols: 1,
            mb_rows: 1,
        }
    }

    /// The pre-round-289 clone-everything rotation ladder, verbatim, as the
    /// byte-exact oracle for [`rotate_reference_slots`].
    #[allow(clippy::too_many_arguments)]
    fn rotate_clone_everything_reference(
        current_slot: &RefFrameSlot,
        pre_last: Option<RefFrameSlot>,
        pre_golden: Option<RefFrameSlot>,
        pre_altref: Option<RefFrameSlot>,
        copy_buffer_to_alternate: Option<u8>,
        copy_buffer_to_golden: Option<u8>,
        refresh_golden_frame: Option<bool>,
        refresh_alternate_frame: Option<bool>,
        refresh_last: Option<bool>,
    ) -> (
        Option<RefFrameSlot>,
        Option<RefFrameSlot>,
        Option<RefFrameSlot>,
    ) {
        let mut new_altref = pre_altref.clone();
        match copy_buffer_to_alternate {
            Some(1) => new_altref = pre_last.clone(),
            Some(2) => new_altref = pre_golden.clone(),
            _ => {}
        }
        let mut new_golden = pre_golden.clone();
        match copy_buffer_to_golden {
            Some(1) => new_golden = pre_last.clone(),
            Some(2) => new_golden = pre_altref.clone(),
            _ => {}
        }
        if refresh_golden_frame == Some(true) {
            new_golden = Some(current_slot.clone());
        }
        if refresh_alternate_frame == Some(true) {
            new_altref = Some(current_slot.clone());
        }
        let new_last = if refresh_last == Some(true) {
            Some(current_slot.clone())
        } else {
            pre_last
        };
        (new_last, new_golden, new_altref)
    }

    #[test]
    fn rotation_matches_clone_everything_reference() {
        // Distinct tag per input so we can tell sources apart byte-for-byte.
        let current = tagged_slot(0);
        let copy_alt_opts = [None, Some(0u8), Some(1), Some(2)];
        let copy_gld_opts = [None, Some(0u8), Some(1), Some(2)];
        let bool_opts = [None, Some(false), Some(true)];
        // Sweep every entry-slot population (each of LAST/GOLDEN/ALTREF either
        // populated with its own tag or empty) × every refresh-control combo.
        for last_present in [false, true] {
            for golden_present in [false, true] {
                for altref_present in [false, true] {
                    let pre_last = last_present.then(|| tagged_slot(1));
                    let pre_golden = golden_present.then(|| tagged_slot(2));
                    let pre_altref = altref_present.then(|| tagged_slot(3));
                    for &ca in &copy_alt_opts {
                        for &cg in &copy_gld_opts {
                            for &rg in &bool_opts {
                                for &ra in &bool_opts {
                                    for &rl in &bool_opts {
                                        let want = rotate_clone_everything_reference(
                                            &current,
                                            pre_last.clone(),
                                            pre_golden.clone(),
                                            pre_altref.clone(),
                                            ca,
                                            cg,
                                            rg,
                                            ra,
                                            rl,
                                        );
                                        let got = rotate_reference_slots(
                                            current.clone(),
                                            pre_last.clone(),
                                            pre_golden.clone(),
                                            pre_altref.clone(),
                                            ca,
                                            cg,
                                            rg,
                                            ra,
                                            rl,
                                        );
                                        assert_eq!(
                                            got, want,
                                            "rotation mismatch: ca={ca:?} cg={cg:?} \
                                             rg={rg:?} ra={ra:?} rl={rl:?} \
                                             last={last_present} golden={golden_present} \
                                             altref={altref_present}"
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn fresh_state_rejects_interframe() {
        // Minimal interframe (frame tag bit 0 = 1 → not a key frame).
        let bytes = [0x01u8, 0x00, 0x00];
        let mut state = Vp8DecoderState::new();
        let res = state.decode_frame(&bytes);
        assert!(matches!(res, Err(DecodeError::Unsupported(_))));
    }

    #[test]
    fn key_frame_populates_all_three_reference_slots() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
        let frames = iter_ivf_frames(IVF);
        assert_eq!(frames.len(), 1);
        let mut state = Vp8DecoderState::new();
        let decoded = state
            .decode_frame(frames[0])
            .expect("key frame should decode");
        assert_eq!(decoded.width, 16);
        assert_eq!(decoded.height, 16);
        assert!(state.last.is_some(), "LAST populated after key frame");
        assert!(state.golden.is_some(), "GOLDEN populated after key frame");
        assert!(state.altref.is_some(), "ALTREF populated after key frame");
    }

    /// Re-decoding all the single-keyframe fixtures through the stateful
    /// driver must match the stateless `decode_vp8` output bit-exactly.
    /// (The first call to a fresh state lands on the stateless key-frame
    /// codepath, so any divergence between the two is a state-init bug.)
    #[test]
    fn stateful_key_frame_decode_matches_stateless() {
        type FixtureCase = (&'static str, &'static [u8], &'static [u8], u32, u32);
        let cases: &[FixtureCase] = &[
            (
                "tiny-i-only-16x16",
                include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf"),
                include_bytes!("../tests/fixtures/tiny-i-only-16x16/expected.yuv"),
                16,
                16,
            ),
            (
                "i-only-64x64",
                include_bytes!("../tests/fixtures/i-only-64x64/input.ivf"),
                include_bytes!("../tests/fixtures/i-only-64x64/expected.yuv"),
                64,
                64,
            ),
            (
                "partition-padding-16x16-4parts",
                include_bytes!("../tests/fixtures/partition-padding-16x16-4parts/input.ivf"),
                include_bytes!("../tests/fixtures/partition-padding-16x16-4parts/expected.yuv"),
                16,
                16,
            ),
        ];
        for (name, ivf, expected, w, h) in cases {
            let frames = iter_ivf_frames(ivf);
            assert!(!frames.is_empty(), "{name} fixture had no frames");
            let mut state = Vp8DecoderState::new();
            let decoded = state
                .decode_frame(frames[0])
                .unwrap_or_else(|e| panic!("{name} key frame should decode: {e}"));
            assert_eq!(decoded.width, *w, "{name} width");
            assert_eq!(decoded.height, *h, "{name} height");
            let mut got = Vec::with_capacity(expected.len());
            got.extend_from_slice(&decoded.y);
            got.extend_from_slice(&decoded.u);
            got.extend_from_slice(&decoded.v);
            assert_eq!(
                &got, expected,
                "{name} stateful key-frame decode must be bit-exact"
            );
        }
    }

    /// The stateful driver honours a tightened `max_pixels_per_frame`: the
    /// 64×64 (4096-px) fixture decodes under the default cap and under a cap
    /// of exactly 4096, but a cap of 4095 refuses the key frame with the DoS
    /// error and leaves the reference slots untouched (no partial state).
    #[test]
    fn stateful_pixel_cap_rejects_oversized_key_frame() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/i-only-64x64/input.ivf");
        let frames = iter_ivf_frames(IVF);
        let frame = frames[0];

        // Default cap: decodes and installs the reference slots.
        let mut ok_state = Vp8DecoderState::new();
        let d = ok_state.decode_frame(frame).expect("default cap decodes");
        assert_eq!((d.width, d.height), (64, 64));
        assert!(ok_state.last.is_some(), "LAST installed under default cap");

        // Inclusive boundary: 4096-px cap still decodes.
        let mut at_cap = Vp8DecoderState::new().with_max_pixels_per_frame(4096);
        assert!(at_cap.decode_frame(frame).is_ok());

        // One below: refused before allocation, slots stay empty.
        let mut tight = Vp8DecoderState::new().with_max_pixels_per_frame(4095);
        let err = tight
            .decode_frame(frame)
            .expect_err("a 4095-px cap must reject a 4096-px frame");
        assert!(matches!(
            err,
            DecodeError::FrameTooLarge {
                pixels: 4096,
                cap: 4095
            }
        ));
        assert!(tight.last.is_none(), "no reference slot on a refused frame");
        assert!(tight.golden.is_none());
        assert!(tight.altref.is_none());
    }

    /// The end-to-end multi-frame test: feed the
    /// `i-frame-then-p-frame-64x64` fixture (one key frame + one P frame,
    /// produced by the reference encoder) through the stateful driver and
    /// require the concatenated I420 output bytes to be byte-for-byte
    /// identical to the reference YUV. This is
    /// the multi-frame pixel-match goal of the round: it exercises the
    /// §9 reference-frame slot rotation (the §9.7 / §9.8 `refresh_last`
    /// reading the just-decoded I frame in as `LAST`), the §16
    /// intra-vs-inter macroblock dispatch, the §16.2 reference-frame
    /// selection (`prob_last` / `prob_gf`), the §16.3 near/nearest
    /// census + §16.2 inter-mode tree, the §18 motion compensation
    /// fetching from the just-decoded I frame, the §15 loop-filter
    /// post-pass, and the §9.10 entropy carry-state between the two
    /// frames.
    #[test]
    fn i_frame_then_p_frame_64x64_key_frame_decodes_bit_exact() {
        // First-frame-only sub-test: ensure the I frame round-trips through
        // the stateful driver before we look at P-frame regressions.
        const IVF: &[u8] = include_bytes!("../tests/fixtures/i-frame-then-p-frame-64x64/input.ivf");
        const EXPECTED: &[u8] =
            include_bytes!("../tests/fixtures/i-frame-then-p-frame-64x64/expected.yuv");
        let frames = iter_ivf_frames(IVF);
        let mut state = Vp8DecoderState::new();
        let decoded = state
            .decode_frame(frames[0])
            .expect("I frame should decode");
        let mut got = Vec::with_capacity(6144);
        got.extend_from_slice(&decoded.y);
        got.extend_from_slice(&decoded.u);
        got.extend_from_slice(&decoded.v);
        assert_eq!(got.len(), 6144, "frame 0 bytes");
        let expected_i = &EXPECTED[..6144];
        assert_eq!(got.as_slice(), expected_i, "I-frame must be bit-exact");
    }

    #[test]
    fn i_frame_then_p_frame_64x64_p_frame_first_diff_report() {
        // Diagnostic: report where P-frame Y plane first diverges. Skipped
        // bit-exact assertion — the full-frame test below catches the
        // overall failure.
        const IVF: &[u8] = include_bytes!("../tests/fixtures/i-frame-then-p-frame-64x64/input.ivf");
        const EXPECTED: &[u8] =
            include_bytes!("../tests/fixtures/i-frame-then-p-frame-64x64/expected.yuv");
        let frames = iter_ivf_frames(IVF);
        let mut state = Vp8DecoderState::new();
        let _ = state.decode_frame(frames[0]).expect("I frame");
        let p = state
            .decode_frame(frames[1])
            .expect("P frame should decode");
        let mut got = Vec::with_capacity(6144);
        got.extend_from_slice(&p.y);
        got.extend_from_slice(&p.u);
        got.extend_from_slice(&p.v);
        let expected_p = &EXPECTED[6144..];
        // Find first byte that differs and report row/col.
        let mut first_diff = None;
        for i in 0..got.len() {
            if got[i] != expected_p[i] {
                first_diff = Some(i);
                break;
            }
        }
        if let Some(idx) = first_diff {
            // 0..4096 is Y plane (64*64); 4096..5120 is U; 5120..6144 is V.
            let (plane, off) = if idx < 4096 {
                ("Y", idx)
            } else if idx < 5120 {
                ("U", idx - 4096)
            } else {
                ("V", idx - 5120)
            };
            let (planew, planeh) = if plane == "Y" { (64, 64) } else { (32, 32) };
            let row = off / planew;
            let col = off % planew;
            eprintln!(
                "P-frame first diff at byte {idx} (plane {plane}, row {row} of {planeh}, col {col}): got={} expected={}",
                got[idx], expected_p[idx]
            );
        } else {
            eprintln!("P-frame matched bit-exact!");
        }
    }

    /// Five-frame fixture (one key + four P frames) exercising the
    /// §9.7 `refresh_golden_frame` cycle (the encoder cycles which
    /// reference frame it refreshes mid-GOP). End-to-end bit-exact
    /// against the reference YUV.
    #[test]
    fn golden_update_cycle_decodes_bit_exact() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/golden-update-cycle/input.ivf");
        const EXPECTED: &[u8] =
            include_bytes!("../tests/fixtures/golden-update-cycle/expected.yuv");
        let frames = iter_ivf_frames(IVF);
        assert_eq!(frames.len(), 5, "fixture has 5 frames");
        let mut state = Vp8DecoderState::new();
        let mut got = Vec::with_capacity(EXPECTED.len());
        for (idx, frame_bytes) in frames.iter().enumerate() {
            let decoded = state
                .decode_frame(frame_bytes)
                .unwrap_or_else(|e| panic!("frame {idx} should decode: {e}"));
            got.extend_from_slice(&decoded.y);
            got.extend_from_slice(&decoded.u);
            got.extend_from_slice(&decoded.v);
        }
        assert_eq!(
            &got, EXPECTED,
            "5-frame golden-cycle decode must be bit-exact"
        );
    }

    /// Ten-frame fixture with the reference encoder's `auto-alt-ref` enabled — exercises
    /// the §9.7 `refresh_alternate_frame` / `copy_buffer_to_alternate`
    /// ALTREF rotation and the §16.2 `prob_gf` reference-frame selector.
    #[test]
    fn altref_arnr_on_decodes_bit_exact() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/altref-arnr-on/input.ivf");
        const EXPECTED: &[u8] = include_bytes!("../tests/fixtures/altref-arnr-on/expected.yuv");
        let frames = iter_ivf_frames(IVF);
        // The reference encoder with auto-alt-ref produces "invisible" altref frames
        // (show_frame = 0); the visible output count may differ from
        // frame_count. We decode every encoded frame and emit visible
        // ones; the reference YUV is the visible plane sequence.
        let mut state = Vp8DecoderState::new();
        let mut got = Vec::with_capacity(EXPECTED.len());
        for (idx, frame_bytes) in frames.iter().enumerate() {
            let decoded = state
                .decode_frame(frame_bytes)
                .unwrap_or_else(|e| panic!("frame {idx} should decode: {e}"));
            got.extend_from_slice(&decoded.y);
            got.extend_from_slice(&decoded.u);
            got.extend_from_slice(&decoded.v);
        }
        // 64×64 visible-only output: 6144 bytes per frame; 10 frames =
        // 61440 bytes (matches the expected.yuv size in the fixture
        // notes.md). The fixture's expected.yuv is built from `ffmpeg
        // -i out.ivf -pix_fmt yuv420p -c:v rawvideo -f rawvideo out.yuv`
        // which suppresses invisible frames automatically.
        if got.len() != EXPECTED.len() {
            // Some invisible-frame fixtures emit extra (suppressed) frames;
            // require *at least* the expected bytes and assert the visible
            // prefix matches. The "visible-only" comparison: take the first
            // `EXPECTED.len()` bytes of `got`.
            assert!(
                got.len() >= EXPECTED.len(),
                "decoder emitted fewer bytes than reference"
            );
            assert_eq!(
                &got[..EXPECTED.len()],
                EXPECTED,
                "visible prefix must be bit-exact"
            );
        } else {
            assert_eq!(&got, EXPECTED, "altref-arnr-on decode must be bit-exact");
        }
    }

    #[test]
    fn i_frame_then_p_frame_64x64_decodes_bit_exact() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/i-frame-then-p-frame-64x64/input.ivf");
        const EXPECTED: &[u8] =
            include_bytes!("../tests/fixtures/i-frame-then-p-frame-64x64/expected.yuv");
        let frames = iter_ivf_frames(IVF);
        assert_eq!(frames.len(), 2, "fixture has one I + one P frame");
        let mut state = Vp8DecoderState::new();
        let mut got = Vec::with_capacity(EXPECTED.len());
        for (idx, frame_bytes) in frames.iter().enumerate() {
            let decoded = state
                .decode_frame(frame_bytes)
                .unwrap_or_else(|e| panic!("frame {idx} should decode: {e}"));
            assert_eq!(decoded.width, 64, "frame {idx} width");
            assert_eq!(decoded.height, 64, "frame {idx} height");
            got.extend_from_slice(&decoded.y);
            got.extend_from_slice(&decoded.u);
            got.extend_from_slice(&decoded.v);
        }
        assert_eq!(got.len(), EXPECTED.len(), "byte-count mismatch");
        assert_eq!(
            &got, EXPECTED,
            "stateful multi-frame decode must be bit-exact vs reference"
        );
    }
}