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
//! VP8 per-frame decode driver (`decode_vp8`) and the
//! [`oxideav_core::Decoder`] integration.
//!
//! This module is the top of the keyframe decode chain — the entry point
//! that takes the raw bytes of one VP8 frame ("one packet = one frame")
//! and produces a fully-reconstructed, loop-filtered I420
//! [`Vp8DecodedFrame`] (and, when the `registry` feature is on, an
//! [`oxideav_core::VideoFrame`]).
//!
//! ## Frame layout per RFC 6386 §4 / §9
//!
//! Every VP8 frame ships as:
//!
//! 1. The §9.1 uncompressed header — 3 bytes for an interframe, 10 bytes
//!    for a key frame (3-byte frame tag + 3-byte start code + two
//!    16-bit little-endian width / height words). [`Vp8FrameHeader::parse`]
//!    handles the layout.
//! 2. The "first" (control) partition — `first_partition_size` bytes
//!    immediately following the uncompressed header. The first partition
//!    carries the §19.2 frame header and the §19.3 per-macroblock
//!    *prediction* records (segment id, skip flag, intra Y / sub-block /
//!    UV modes — §11) for every macroblock in raster order.
//! 3. (Only when `log2_nbr_of_dct_partitions > 0`)
//!    `(nbr_of_dct_partitions - 1) * 3` bytes of 3-byte little-endian
//!    DCT-partition sizes (RFC 6386 §9.5). Each entry is the byte length
//!    of the corresponding DCT partition that follows; the last partition's
//!    length is computed by subtraction from the frame total.
//! 4. `nbr_of_dct_partitions` concatenated DCT partitions carrying the
//!    §13 residual-coefficient records (`residual_data()` per §19.3) for
//!    every macroblock. Macroblock rows are striped round-robin across the
//!    partitions: row `r` is read from partition `r % nbr_of_dct_partitions`
//!    (RFC 6386 §20.4 — `for (row, partition = 0; row < mb_rows; row++) { ...;
//!    if (++partition == ctx->token_hdr.partitions) partition = 0; }`).
//!    Each partition uses its own [`BoolDecoder`] instance (RFC 6386
//!    §4 page 9 — "All partitions are decoded using separate instances of
//!    the boolean entropy decoder").
//!
//! ## Scope
//!
//! [`decode_vp8`] is the **stateless** single-frame entry point — it
//! decodes one key frame in isolation and returns
//! [`DecodeError::Unsupported`] on an interframe (since interframes
//! need a reference-frame buffer this function does not own). For
//! multi-frame streams with P-frames, use
//! [`crate::state::Vp8DecoderState::decode_frame`], which owns the
//! RFC 6386 §9 three-slot reference-frame buffer and handles both
//! key frames and interframes end-to-end.

use crate::bool_decoder::BoolDecoder;
use crate::coded_header::{CodedHeaderError, Vp8CodedHeader};
use crate::dct_tokens::{CoeffProbs, MbCoeffError, MbEntropyCtx, merge_default_token_probs};
use crate::dequant::{MbDequantFactors, decode_and_dequantize_mb};
use crate::frame::{FrameError, KeyframePlanes, MbCoeffs, decode_keyframe};
use crate::frame_header::{FrameHeaderError, Vp8FrameHeader};
use crate::loop_filter::{FrameFilterConfig, MAX_MB_SEGMENTS, filter_frame};
use crate::macroblock::{
    IntraYMode, MacroblockError, MacroblockModes, parse_key_frame_macroblock_modes,
};

/// Errors surfaced by [`decode_vp8`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DecodeError {
    /// The §9.1 uncompressed header could not be parsed.
    FrameHeader(FrameHeaderError),
    /// The §19.2 boolean-coded frame header could not be parsed.
    CodedHeader(CodedHeaderError),
    /// The §11 / §19.3 macroblock prediction layer could not be parsed.
    Macroblock(MacroblockError),
    /// The §13 residual-coefficient layer could not be parsed.
    MbCoeffs {
        /// `mb_row * mb_cols + mb_col` of the offending macroblock.
        index: usize,
        /// The underlying token-decode error.
        source: MbCoeffError,
    },
    /// The §14.2 per-MB reconstruction step rejected its inputs.
    Frame(FrameError),
    /// The frame is not a key frame — interframes are not yet supported.
    /// VP8 P-frames need §16 motion-vector decoding, §16.2 mv_ref tree
    /// resolution, and the reference-frame compositor (none of which are
    /// landed yet). Callers that receive this on a P-frame should treat
    /// the stream as un-decodable past the last key frame.
    Unsupported(&'static str),
    /// The first partition declared in the frame tag extends past the end
    /// of the supplied input bytes (truncated packet).
    TruncatedFirstPartition {
        /// Bytes available after the uncompressed header.
        available: usize,
        /// Bytes the frame tag's `first_partition_size` claimed.
        declared: usize,
    },
    /// One of the 3-byte DCT-partition size prefixes could not be read
    /// (truncated packet).
    TruncatedPartitionSizes,
    /// A declared DCT partition extends past the end of the supplied
    /// input bytes (truncated packet).
    TruncatedDctPartition {
        /// 0-based partition index (`0..nbr_of_dct_partitions`).
        index: usize,
        /// Bytes available for the partition.
        available: usize,
        /// Bytes the size prefix declared.
        declared: usize,
    },
    /// `width` or `height` from the §9.1 key-frame size words was zero —
    /// a valid VP8 key frame describes at least one pixel.
    ZeroDimension,
    /// The §9.1 key-frame `width × height` product exceeds the caller's
    /// configured pixel cap. Raised *before* any plane / macroblock-grid
    /// allocation so a tiny header declaring an enormous frame is rejected
    /// without the decoder ever attempting the allocation. `pixels` is the
    /// declared product (`width as u64 * height as u64`), `cap` the
    /// configured maximum.
    FrameTooLarge {
        /// Declared `width as u64 * height as u64`.
        pixels: u64,
        /// Configured `max_pixels_per_frame` cap.
        cap: u64,
    },
}

/// Default per-frame pixel cap the stateless [`decode_vp8`] entry point and
/// a freshly-constructed [`Vp8DecoderState`](crate::state::Vp8DecoderState)
/// enforce when the caller does not tighten it.
///
/// Set to `32_768 × 32_768 = 1_073_741_824` — deliberately generous. VP8's
/// §9.1 size words are 14 bits each, so a legal frame never exceeds
/// `16_383 × 16_383 ≈ 268 M` pixels and this default therefore rejects no
/// real key frame; it exists so callers processing untrusted input can
/// *tighten* the cap (via [`decode_vp8_with_max_pixels`] or
/// [`Vp8DecoderState::with_max_pixels_per_frame`](crate::state::Vp8DecoderState::with_max_pixels_per_frame))
/// and have a huge declared frame refused before allocation instead of
/// OOM-ing. Numerically matches `oxideav_core::DecoderLimits::default()`'s
/// `max_pixels_per_frame` so the two layers agree.
pub const DEFAULT_MAX_PIXELS_PER_FRAME: u64 = 32_768 * 32_768;

/// Check the §9.1 declared `width × height` against a pixel cap.
///
/// Computed in `u64` so the `16_383 × 16_383` worst case (or any wider
/// value a future caller might pass) cannot overflow. Returns
/// [`DecodeError::FrameTooLarge`] when the product exceeds `cap`.
pub(crate) fn check_pixel_cap(width: u32, height: u32, cap: u64) -> Result<(), DecodeError> {
    let pixels = width as u64 * height as u64;
    if pixels > cap {
        return Err(DecodeError::FrameTooLarge { pixels, cap });
    }
    Ok(())
}

impl core::fmt::Display for DecodeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            DecodeError::FrameHeader(e) => write!(f, "vp8 decode: {e}"),
            DecodeError::CodedHeader(e) => write!(f, "vp8 decode: {e}"),
            DecodeError::Macroblock(e) => write!(f, "vp8 decode: {e}"),
            DecodeError::MbCoeffs { index, source } => {
                write!(f, "vp8 decode: macroblock {index}: {source}")
            }
            DecodeError::Frame(e) => write!(f, "vp8 decode: {e}"),
            DecodeError::Unsupported(msg) => write!(f, "vp8 decode: {msg}"),
            DecodeError::TruncatedFirstPartition {
                available,
                declared,
            } => write!(
                f,
                "vp8 decode: truncated first partition ({declared} declared, {available} available)"
            ),
            DecodeError::TruncatedPartitionSizes => {
                f.write_str("vp8 decode: truncated DCT-partition size prefixes")
            }
            DecodeError::TruncatedDctPartition {
                index,
                available,
                declared,
            } => write!(
                f,
                "vp8 decode: truncated DCT partition {index} ({declared} declared, {available} available)"
            ),
            DecodeError::ZeroDimension => {
                f.write_str("vp8 decode: zero width or height in key-frame header")
            }
            DecodeError::FrameTooLarge { pixels, cap } => write!(
                f,
                "vp8 decode: declared frame size {pixels} px exceeds configured cap {cap} px"
            ),
        }
    }
}

impl std::error::Error for DecodeError {}

impl From<FrameHeaderError> for DecodeError {
    fn from(value: FrameHeaderError) -> Self {
        DecodeError::FrameHeader(value)
    }
}
impl From<CodedHeaderError> for DecodeError {
    fn from(value: CodedHeaderError) -> Self {
        DecodeError::CodedHeader(value)
    }
}
impl From<MacroblockError> for DecodeError {
    fn from(value: MacroblockError) -> Self {
        DecodeError::Macroblock(value)
    }
}
impl From<FrameError> for DecodeError {
    fn from(value: FrameError) -> Self {
        DecodeError::Frame(value)
    }
}
impl From<crate::bool_decoder::BoolDecoderError> for DecodeError {
    fn from(value: crate::bool_decoder::BoolDecoderError) -> Self {
        // Surface a bool-decoder mishap during interframe macroblock-header
        // reads as a macroblock error (the §19.3 prefix is part of the
        // macroblock layer).
        DecodeError::Macroblock(MacroblockError::from(value))
    }
}
impl From<crate::near_mv::InterMbError> for DecodeError {
    fn from(value: crate::near_mv::InterMbError) -> Self {
        match value {
            crate::near_mv::InterMbError::BoolDecoder(inner) => {
                DecodeError::Macroblock(MacroblockError::from(inner))
            }
            crate::near_mv::InterMbError::SplitNotSupported { .. } => DecodeError::Unsupported(
                "vp8 interframe: SPLITMV reconstruction path tripped an internal mis-dispatch",
            ),
        }
    }
}

/// Fully-decoded, loop-filtered VP8 key-frame in I420 layout.
///
/// `y`/`u`/`v` are the visible-cropped planes — the §9.1 width / height
/// from the key-frame header, rounded for chroma sub-sampling
/// (`uv_width = (width + 1) / 2`, `uv_height = (height + 1) / 2`). Decode
/// pads internally to whole macroblocks; the §15 loop filter runs against
/// that padded buffer, then this output is cropped to the visible area.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Vp8DecodedFrame {
    /// Visible width in luma pixels (the §9.1 key-frame `width`).
    pub width: u32,
    /// Visible height in luma pixels (the §9.1 key-frame `height`).
    pub height: u32,
    /// Luma plane — `width * height` bytes, row-major (stride == width).
    pub y: Vec<u8>,
    /// U chroma plane — `((width+1)/2) * ((height+1)/2)` bytes.
    pub u: Vec<u8>,
    /// V chroma plane — same dimensions as `u`.
    pub v: Vec<u8>,
}

impl Vp8DecodedFrame {
    /// Set `width`.
    #[must_use]
    pub fn with_width(mut self, v: u32) -> Self {
        self.width = v;
        self
    }

    /// Set `height`.
    #[must_use]
    pub fn with_height(mut self, v: u32) -> Self {
        self.height = v;
        self
    }

    /// Set `y`.
    #[must_use]
    pub fn with_y(mut self, v: Vec<u8>) -> Self {
        self.y = v;
        self
    }

    /// Set `u`.
    #[must_use]
    pub fn with_u(mut self, v: Vec<u8>) -> Self {
        self.u = v;
        self
    }

    /// Set `v`.
    #[must_use]
    pub fn with_v(mut self, v: Vec<u8>) -> Self {
        self.v = v;
        self
    }
}

/// Decode one VP8 frame end-to-end and emit the reconstructed I420 picture.
///
/// `bytes` must hold exactly one VP8 elementary-stream frame (the bytes a
/// container demuxer hands the decoder for one sample / packet). The
/// function is stateless — no reference-frame carry-over, no probability
/// persistence — so it can only handle **key frames**. Interframes return
/// [`DecodeError::Unsupported`].
///
/// See the module docstring for the partition-layout walk this function
/// follows. Production-grade users should prefer [`Vp8Decoder`] (gated on
/// the `registry` feature), which wraps this entry point in the
/// [`oxideav_core::Decoder`] trait.
pub fn decode_vp8(bytes: &[u8]) -> Result<Vp8DecodedFrame, DecodeError> {
    decode_vp8_with_max_pixels(bytes, DEFAULT_MAX_PIXELS_PER_FRAME)
}

/// Controls for a one-shot key-frame decode
/// ([`decode_vp8_with_options`]).
///
/// `Default` is [`decode_vp8`]: serial, [`DEFAULT_MAX_PIXELS_PER_FRAME`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Vp8DecodeOptions {
    /// Thread budget. `0` and `1` both mean serial (the default); with
    /// `n > 1` token rows, reconstruction rows and the loop filter run
    /// on up to `n` scoped threads that end with the call. The picture
    /// is the same at every budget.
    pub threads: usize,
    /// Reject a declared `width × height` above this before any
    /// allocation (see [`decode_vp8_with_max_pixels`]).
    pub max_pixels_per_frame: u64,
}

impl Default for Vp8DecodeOptions {
    fn default() -> Self {
        Vp8DecodeOptions {
            threads: 0,
            max_pixels_per_frame: DEFAULT_MAX_PIXELS_PER_FRAME,
        }
    }
}

impl Vp8DecodeOptions {
    /// The defaults: serial, [`DEFAULT_MAX_PIXELS_PER_FRAME`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Set `threads`.
    #[must_use]
    pub fn with_threads(mut self, v: usize) -> Self {
        self.threads = v;
        self
    }

    /// Set `max_pixels_per_frame`.
    #[must_use]
    pub fn with_max_pixels_per_frame(mut self, v: u64) -> Self {
        self.max_pixels_per_frame = v;
        self
    }
}

/// Decode one VP8 key frame under [`Vp8DecodeOptions`] — [`decode_vp8`]
/// with a caller-granted thread budget and pixel cap. This is the entry
/// point for a still-picture container that wants its decode to follow
/// the caller's thread budget.
///
/// The picture is bit-identical to [`decode_vp8`]'s at every budget.
/// Like `decode_vp8` it is stateless and decodes key frames only. It
/// works a macroblock row at a time — a row's coefficients are decoded,
/// reconstructed and dropped — where `decode_vp8` holds the dequantised
/// coefficients of the whole frame (800 bytes per macroblock, 38 MiB
/// for a 12-megapixel picture) until reconstruction is over; the serial
/// speed of the two is the same.
///
/// ```
/// use oxideav_vp8::{Vp8DecodeOptions, decode_vp8, decode_vp8_with_options};
/// # use oxideav_vp8::{I420Frame, KeyframeParams, encode_keyframe};
/// # let (w, h) = (64u32, 48u32);
/// # let y: Vec<u8> = (0..w * h).map(|i| (i * 5 % 253) as u8).collect();
/// # let c = vec![128u8; ((w / 2) * (h / 2)) as usize];
/// # let vp8_keyframe_bytes =
/// #     encode_keyframe(&I420Frame::packed(w, h, &y, &c, &c), &KeyframeParams::default())?;
/// let options = Vp8DecodeOptions::new().with_threads(4);
/// let picture = decode_vp8_with_options(&vp8_keyframe_bytes, &options)?;
/// assert_eq!(picture, decode_vp8(&vp8_keyframe_bytes)?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn decode_vp8_with_options(
    bytes: &[u8],
    options: &Vp8DecodeOptions,
) -> Result<Vp8DecodedFrame, DecodeError> {
    let header = Vp8FrameHeader::parse(bytes)?;
    if !header.key_frame {
        return Err(DecodeError::Unsupported(
            "VP8 inter-frame (§16) decoding needs the carried state of \
             `Vp8DecoderState` — this entry point decodes key frames only",
        ));
    }
    crate::state::Vp8DecoderState::new()
        .with_max_pixels_per_frame(options.max_pixels_per_frame)
        .with_threads(options.threads)
        .decode_frame(bytes)
}

/// Decode one VP8 key frame, rejecting a declared `width × height` larger
/// than `max_pixels_per_frame` before any allocation.
///
/// Identical to [`decode_vp8`] except the pixel cap is caller-chosen rather
/// than [`DEFAULT_MAX_PIXELS_PER_FRAME`]. Callers processing untrusted input
/// (e.g. a server decoding uploads) pass a tight cap so a malformed header
/// declaring an enormous frame returns [`DecodeError::FrameTooLarge`]
/// instead of driving a multi-hundred-megabyte plane allocation. The check
/// fires immediately after the §9.1 size words are parsed and before the
/// first macroblock-grid `Vec` is reserved.
pub fn decode_vp8_with_max_pixels(
    bytes: &[u8],
    max_pixels_per_frame: u64,
) -> Result<Vp8DecodedFrame, DecodeError> {
    let header = Vp8FrameHeader::parse(bytes)?;
    if !header.key_frame {
        return Err(DecodeError::Unsupported(
            "VP8 inter-frame (§16) decoding is not implemented yet — \
             only key frames are supported in this build",
        ));
    }

    // §9.1: width and height live on the key-frame header (Some) and are
    // both 14 bits; reject zero up-front so the macroblock math below sees
    // a non-degenerate frame.
    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 a declared frame larger than the configured cap
    // *before* the first grid allocation (`parse_key_frame_macroblock_modes`
    // reserves `mb_rows * mb_cols` entries a few lines below).
    check_pixel_cap(width, height, max_pixels_per_frame)?;

    // §4 / §9.1: macroblock dimensions round up to whole 16-pixel blocks.
    let mb_cols = width.div_ceil(16) as usize;
    let mb_rows = height.div_ceil(16) as usize;

    // ---- Carve out the first (control) partition ---------------------
    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];

    // ---- §19.2 boolean-coded frame header + §11 macroblock layer -----
    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);

    // ---- §9.5 DCT-partition table ------------------------------------
    // The DCT partitions begin immediately after the first partition,
    // preceded by (nbr_of_dct_partitions - 1) 3-byte LE size words.
    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 = carve_dct_partitions(dct_section, num_partitions)?;

    // ---- §14.1 per-segment dequant factors ---------------------------
    // Resolve the four segment slots up front. With segmentation off the
    // four entries collapse to the same factor set and the per-MB
    // `segment_id` is `None` (treated as segment 0).
    let dequant_factors = resolve_segment_dequant_factors(&coded);

    // ---- §13 token probability table ---------------------------------
    let coeff_probs: CoeffProbs = merge_default_token_probs(&coded.token_prob_updates);

    // ---- Per-row residual decode -------------------------------------
    let coeffs = decode_residuals(
        &coded,
        &modes,
        &partitions,
        &coeff_probs,
        &dequant_factors,
        mb_rows,
        mb_cols,
    )?;

    // ---- §12 / §14.2 reconstruction ----------------------------------
    let mut planes = decode_keyframe(mb_cols, mb_rows, &modes, &coeffs)?;

    // ---- §15.1 loop-filter post-pass ---------------------------------
    let lf_config = FrameFilterConfig::keyframe(&coded);
    if lf_config.loop_filter_level != 0 {
        filter_frame(&mut planes, &modes, &coeffs, &lf_config);
    }

    // ---- §9.1 crop to visible width / height -------------------------
    Ok(crop_to_visible(&planes, width, height))
}

/// Carve the DCT-partition section into a `Vec` of byte slices.
///
/// Layout per RFC 6386 §9.5: the first `(num_partitions - 1) * 3` bytes
/// are 3-byte little-endian size words, then the partitions follow
/// concatenated. The last partition's length is implied by what is left.
/// `num_partitions == 1` skips the size table entirely.
pub(crate) fn carve_dct_partitions(
    section: &[u8],
    num_partitions: usize,
) -> Result<Vec<&[u8]>, DecodeError> {
    debug_assert!((1..=8).contains(&num_partitions));
    let table_len = (num_partitions - 1) * 3;
    if section.len() < table_len {
        return Err(DecodeError::TruncatedPartitionSizes);
    }
    let (sizes_bytes, body) = section.split_at(table_len);

    let mut sizes: Vec<usize> = Vec::with_capacity(num_partitions);
    for i in 0..(num_partitions - 1) {
        let off = i * 3;
        let sz = (sizes_bytes[off] as usize)
            | ((sizes_bytes[off + 1] as usize) << 8)
            | ((sizes_bytes[off + 2] as usize) << 16);
        sizes.push(sz);
    }
    // Last partition's size: the remaining bytes.
    let consumed: usize = sizes.iter().sum();
    if consumed > body.len() {
        // One of the prefix sizes already overshot the available data.
        // Surface the offending one rather than the last (computed) slot.
        for (i, &sz) in sizes.iter().enumerate() {
            let off: usize = sizes.iter().take(i).sum();
            if off + sz > body.len() {
                return Err(DecodeError::TruncatedDctPartition {
                    index: i,
                    available: body.len().saturating_sub(off),
                    declared: sz,
                });
            }
        }
    }
    sizes.push(body.len() - consumed);

    let mut out: Vec<&[u8]> = Vec::with_capacity(num_partitions);
    let mut cursor = 0usize;
    for (i, &sz) in sizes.iter().enumerate() {
        let end = cursor + sz;
        if end > body.len() {
            return Err(DecodeError::TruncatedDctPartition {
                index: i,
                available: body.len().saturating_sub(cursor),
                declared: sz,
            });
        }
        out.push(&body[cursor..end]);
        cursor = end;
    }
    Ok(out)
}

/// Build the four per-segment [`MbDequantFactors`] for the frame, applying
/// the §10 `quantizer_update` segment override (delta or absolute) on top
/// of the §9.6 frame baseline.
///
/// When segmentation is disabled (the common case for the simplest key
/// frames) every slot resolves to the frame-level
/// [`MbDequantFactors::from_quant_indices`] result, so the per-MB lookup
/// always lands on the correct factors regardless of how the caller's
/// `segment_id` happens to be populated.
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
}

/// Decode the §13 residual coefficients for every macroblock, threading the
/// above / left non-zero predictor contexts per the §13.3 rules and routing
/// each row's reads to the correct DCT partition per the §9.5 / §20.4
/// round-robin row striping.
fn decode_residuals(
    coded: &Vp8CodedHeader,
    modes: &[MacroblockModes],
    partitions: &[&[u8]],
    coeff_probs: &CoeffProbs,
    dequant_factors: &[MbDequantFactors; MAX_MB_SEGMENTS],
    mb_rows: usize,
    mb_cols: usize,
) -> Result<Vec<MbCoeffs>, DecodeError> {
    let num_partitions = partitions.len();
    debug_assert!(num_partitions >= 1);

    // §13: every macroblock is decoded exactly once, in raster order
    // (`mb_row` outer, `mb_col` inner), and its coefficients appended.
    // Reserve the frame's slots and `push` per MB rather than `resize`-ing
    // to `default()` first: each slot is overwritten before it is read, so
    // the bulk default-zeroing (800 bytes per `MbCoeffs`) was dead work.
    let mut coeffs: Vec<MbCoeffs> = Vec::with_capacity(mb_rows * mb_cols);

    // One above-context per macroblock column, lives for the whole frame.
    let mut above: Vec<MbEntropyCtx> = vec![MbEntropyCtx::default(); mb_cols];

    // One bool-decoder per DCT partition that is actually consumed, with
    // the cursor persisting across rows that share a partition (the §20.4
    // round-robin rule). Partitions that no row routes to — e.g. the
    // 1-byte padding partitions of a 16×16 / 4-partition frame, where only
    // partition 0 is ever read — are left `None` and never initialised.
    // Consumed partitions use the tolerant §20.2 `init_bool_decoder` form
    // ([`BoolDecoder::init_partition`]): a DCT partition that rounds down
    // to a 0- or 1-byte slice is spec-legal (`sz < 2` → zero-initialised
    // value register, empty input) and must decode, matching the
    // stateful keyframe path in `state::decode_intra_residuals`. The
    // round-284 `decode_stream_token_descent` fuzz target's
    // cross-entry-point differential caught this path still using the
    // strict control-partition `init` and rejecting such frames with
    // `InputTooShort`.
    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() {
            partition_decoders[part_idx] = Some(BoolDecoder::init_partition(partitions[part_idx]));
        }
    }

    for mb_row in 0..mb_rows {
        // §13.3 page 65: the "left" non-zero predictor context resets at
        // the start of every macroblock row.
        let mut left = MbEntropyCtx::default();
        let part_idx = mb_row % num_partitions;
        let dec = partition_decoders[part_idx]
            .as_mut()
            .expect("partition decoder initialised above for every consumed partition");

        for (mb_col, above_ctx) in above.iter_mut().enumerate() {
            let raster = mb_row * mb_cols + mb_col;
            let mb = &modes[raster];
            let has_y2 = mb.y_mode != IntraYMode::B;
            // §10: a macroblock with no `segment_id` defaults to segment 0
            // (the §10 default before the map is ever updated). When
            // segmentation is off, all four segment factors are identical
            // anyway, so the unwrap_or here cannot mis-route.
            let seg = mb.segment_id.unwrap_or(0) as usize;
            let seg = seg.min(MAX_MB_SEGMENTS - 1);
            let factors = &dequant_factors[seg];

            let mb_coeffs = decode_and_dequantize_mb(
                dec,
                has_y2,
                mb.mb_skip_coeff,
                coeff_probs,
                factors,
                above_ctx,
                &mut left,
            )
            .map_err(|source| DecodeError::MbCoeffs {
                index: raster,
                source,
            })?;
            debug_assert_eq!(coeffs.len(), raster, "coeffs pushed in raster order");
            coeffs.push(mb_coeffs);
        }
    }

    // `coded` is informational at this layer (the per-MB walk above is
    // entirely self-contained), but keep the reference to make the
    // signature unambiguous about what header state drives the loop and to
    // future-proof for the §16 interframe extension (which will need
    // `coded.prob_intra` etc here).
    let _ = coded;

    Ok(coeffs)
}

/// Public-in-crate alias of [`crop_to_visible`] for the multi-frame driver.
pub(crate) fn crop_to_visible_public(
    planes: &KeyframePlanes,
    width: u32,
    height: u32,
) -> Vp8DecodedFrame {
    crop_to_visible(planes, width, height)
}

/// Crop the §14.2 reconstructed plane buffers (sized to whole macroblocks)
/// to the §9.1 visible width / height and return a packed I420 frame.
fn crop_to_visible(planes: &KeyframePlanes, width: u32, height: u32) -> Vp8DecodedFrame {
    let w = width as usize;
    let h = height as usize;
    let uvw = w.div_ceil(2);
    let uvh = h.div_ceil(2);

    // When the visible width equals the macroblock-padded stride there is no
    // per-row gap to skip, so the whole leading `w * h` region of the source
    // plane is already the packed output verbatim — one contiguous copy
    // instead of `h` row-sliced `extend_from_slice` calls. This is the common
    // case for macroblock-aligned dimensions (e.g. 128×128, 16-multiples). The
    // strided path below produces the identical packed bytes when a gap exists.
    let y = if w == planes.y_stride {
        planes.y[..w * h].to_vec()
    } else {
        let mut y = Vec::with_capacity(w * h);
        for r in 0..h {
            let src = r * planes.y_stride;
            y.extend_from_slice(&planes.y[src..src + w]);
        }
        y
    };

    let (u, v) = if uvw == planes.uv_stride {
        (
            planes.u[..uvw * uvh].to_vec(),
            planes.v[..uvw * uvh].to_vec(),
        )
    } else {
        let mut u = Vec::with_capacity(uvw * uvh);
        let mut v = Vec::with_capacity(uvw * uvh);
        for r in 0..uvh {
            let src = r * planes.uv_stride;
            u.extend_from_slice(&planes.u[src..src + uvw]);
            v.extend_from_slice(&planes.v[src..src + uvw]);
        }
        (u, v)
    };

    Vp8DecodedFrame {
        width,
        height,
        y,
        u,
        v,
    }
}

// ─────────────────── oxideav_core::Decoder integration ───────────────────

#[cfg(feature = "registry")]
mod registry {
    use std::collections::VecDeque;

    use oxideav_core::frame::VideoPlane;
    use oxideav_core::{
        CodecCapabilities, CodecId, CodecInfo, CodecParameters, CodecRegistry, CodecTag,
        ColorSignal, Decoder, DecoderLimits, Error, Frame, MatrixCoefficients, Packet, PixelFormat,
        Result, RuntimeContext, VideoFrame,
    };

    use super::{DecodeError, Vp8DecodedFrame};

    /// Canonical codec id under which this decoder registers. Matches the
    /// long-standing `oxideav-vp9` / `oxideav-av1` naming convention.
    pub const VP8_CODEC_ID: &str = "vp8";

    impl From<DecodeError> for Error {
        fn from(value: DecodeError) -> Self {
            match value {
                DecodeError::Unsupported(msg) => Error::unsupported(msg),
                // A tripped pixel cap is a DoS-guard rejection, not a
                // malformed stream — surface it as the framework's
                // resource-exhaustion error so callers can distinguish it.
                DecodeError::FrameTooLarge { .. } => Error::resource_exhausted(value.to_string()),
                DecodeError::FrameHeader(_)
                | DecodeError::CodedHeader(_)
                | DecodeError::Macroblock(_)
                | DecodeError::MbCoeffs { .. }
                | DecodeError::Frame(_)
                | DecodeError::TruncatedFirstPartition { .. }
                | DecodeError::TruncatedPartitionSizes
                | DecodeError::TruncatedDctPartition { .. }
                | DecodeError::ZeroDimension => Error::invalid(value.to_string()),
            }
        }
    }

    impl From<Vp8DecodedFrame> for VideoFrame {
        fn from(f: Vp8DecodedFrame) -> Self {
            let uv_stride = (f.width as usize).div_ceil(2);
            VideoFrame {
                pts: None,
                planes: vec![
                    VideoPlane {
                        stride: f.width as usize,
                        data: f.y,
                    },
                    VideoPlane {
                        stride: uv_stride,
                        data: f.u,
                    },
                    VideoPlane {
                        stride: uv_stride,
                        data: f.v,
                    },
                ],
            }
        }
    }

    /// `oxideav_core::Decoder` impl driving [`Vp8DecoderState`].
    ///
    /// Each `send_packet` queues one compressed packet; `receive_frame`
    /// consumes queued packets and feeds them to
    /// [`Vp8DecoderState::decode_frame`], which threads reference frames
    /// and entropy carry-state across calls. Both key frames and
    /// interframes decode end-to-end; the only `DecodeError::Unsupported`
    /// returned now is "interframe arrived before any key frame" (a
    /// stream-mis-feed error, not a missing feature).
    ///
    /// ## Invisible frames
    ///
    /// A frame whose §9.1 `show_frame` bit is 0 is "not for display": it
    /// is decoded (its §9.7 / §9.8 reference-slot side effects apply) but
    /// no picture is returned for it — `receive_frame` moves on to the
    /// next queued packet, and answers [`Error::NeedMore`] when that was
    /// the last one. Only shown pictures reach the caller.
    ///
    /// ## Stream parameters
    ///
    /// [`Decoder::output_params`] answers the resolved description of
    /// the pictures this decoder returns: the §9.1 visible `width` /
    /// `height` (the cropped size of the emitted planes, not the
    /// macroblock-aligned one), [`PixelFormat::Yuv420P`], and the §9.2
    /// `color_space` as the colour signal's matrix. Before the first
    /// picture it answers from the key frame already decoded, else from
    /// the first queued key frame's headers.
    ///
    /// Only a key frame can change that description (§9.1 / §9.2 are
    /// key-frame-only fields). When the first **shown** picture of a new
    /// description is about to be returned, the decoder bumps
    /// [`Decoder::output_params_generation`] and returns one
    /// [`Frame::StreamParams`] event carrying the new `output_params()`
    /// first; the picture follows on the next call. No event is
    /// returned for the first description, for a key frame that repeats
    /// the current one, or for an invisible key frame (the event waits
    /// for the first shown picture of the new size). [`Decoder::reset`]
    /// keeps the description of the last picture returned, so a seek
    /// into a segment of a different size announces it the same way.
    ///
    /// The §9.1 upscale codes and the §9.2 `clamping_type` bit do not
    /// change the emitted planes and are not part of the description;
    /// [`Vp8Decoder::upscale`] / [`Vp8Decoder::clamping_type`] expose
    /// them.
    ///
    /// The decoder runs serially; it keeps the default no-op
    /// [`Decoder::set_execution_context`].
    ///
    /// [`Vp8DecoderState::decode_frame`]: crate::state::Vp8DecoderState::decode_frame
    pub struct Vp8Decoder {
        codec_id: CodecId,
        pending: VecDeque<Packet>,
        eof: bool,
        state: crate::state::Vp8DecoderState,
        /// Description of the picture most recently returned (`None`
        /// until the first one).
        shape: Option<OutputShape>,
        /// [`Decoder::output_params_generation`] counter: bumped once per
        /// mid-stream change of `shape`.
        generation: u64,
        /// The first picture of a new shape, held back behind the
        /// [`Frame::StreamParams`] event just returned for it.
        held: Option<VideoFrame>,
    }

    /// The part of the decoder's output that [`Decoder::output_params`]
    /// describes.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    struct OutputShape {
        width: u32,
        height: u32,
        /// §9.2 `color_space` bit (`false` = BT.601-like YUV).
        color_space_reserved: bool,
    }

    impl OutputShape {
        /// §9.2 `color_space` → colour signal. Value 0 is "YUV color
        /// space similar to the YCrCb color space defined in
        /// [ITU-R_BT.601]": the BT.601 luma / chroma matrix (H.273
        /// matrix code points 5 and 6 are the same matrix; 6 is used).
        /// §9.2 states no primaries, transfer or nominal range, so those
        /// stay unspecified; value 1 is reserved and states nothing.
        fn color_signal(self) -> ColorSignal {
            let mut signal = ColorSignal::unspecified();
            if !self.color_space_reserved {
                signal.matrix = MatrixCoefficients::BT601_525;
            }
            signal
        }

        fn to_params(self, codec_id: &CodecId) -> CodecParameters {
            let mut p = CodecParameters::video(codec_id.clone());
            p.width = Some(self.width);
            p.height = Some(self.height);
            p.pixel_format = Some(PixelFormat::Yuv420P);
            p.color_signal = self.color_signal();
            p
        }

        /// The shape the state's most recent key frame installed.
        fn from_state(state: &crate::state::Vp8DecoderState) -> Option<Self> {
            Some(Self {
                width: state.visible_width()?,
                height: state.visible_height()?,
                color_space_reserved: state.color_space()?,
            })
        }

        /// Read the shape straight off a key frame's §9.1 uncompressed
        /// header and the first bit of its §9.2 / §19.2 first partition,
        /// without decoding it. `None` for an interframe or a header
        /// that does not parse.
        fn peek_key_frame(bytes: &[u8]) -> Option<Self> {
            let header = crate::frame_header::Vp8FrameHeader::parse(bytes).ok()?;
            if !header.key_frame {
                return None;
            }
            let width = u32::from(header.width?);
            let height = u32::from(header.height?);
            if width == 0 || height == 0 {
                return None;
            }
            let first = bytes.get(header.header_bytes_consumed..)?;
            let first = &first[..first.len().min(header.first_partition_size as usize)];
            let mut bd = crate::bool_decoder::BoolDecoder::init(first).ok()?;
            let color_space_reserved = bd.read_literal(1).ok()? != 0;
            Some(Self {
                width,
                height,
                color_space_reserved,
            })
        }
    }

    impl Vp8Decoder {
        /// Build a fresh decoder bound to the supplied codec id. The id is
        /// reported verbatim by [`Decoder::codec_id`]. The internal
        /// [`Vp8DecoderState`] starts empty — the first packet fed to
        /// `send_packet` / `receive_frame` must be a key frame.
        ///
        /// [`Vp8DecoderState`]: crate::state::Vp8DecoderState
        pub fn new(codec_id: CodecId) -> Self {
            Self::with_state(codec_id, crate::state::Vp8DecoderState::new())
        }

        /// Build a decoder that enforces `limits.max_pixels_per_frame` as
        /// the §9.1 declared-frame-size cap. Any key frame whose declared
        /// `width × height` exceeds the cap is refused with
        /// [`Error::ResourceExhausted`] before the decoder allocates its
        /// macroblock grid. Constructed by [`make_decoder`] from the
        /// [`CodecParameters::limits`](oxideav_core::CodecParameters) the
        /// registry threads in. The cap survives [`Decoder::reset`].
        pub fn with_limits(codec_id: CodecId, limits: DecoderLimits) -> Self {
            Self::with_state(
                codec_id,
                crate::state::Vp8DecoderState::new()
                    .with_max_pixels_per_frame(limits.max_pixels_per_frame),
            )
        }

        fn with_state(codec_id: CodecId, state: crate::state::Vp8DecoderState) -> Self {
            Self {
                codec_id,
                pending: VecDeque::new(),
                eof: false,
                state,
                shape: None,
                generation: 0,
                held: None,
            }
        }

        /// §9.1 `(horizontal_scale, vertical_scale)` upscale codes of the
        /// most recently decoded key frame — a display hint that does not
        /// change the emitted planes. `None` before any key frame.
        pub fn upscale(
            &self,
        ) -> Option<(
            crate::frame_header::ScaleCode,
            crate::frame_header::ScaleCode,
        )> {
            self.state.upscale()
        }

        /// §9.2 `clamping_type` bit of the most recently decoded key
        /// frame (`Some(true)` = the encoder guarantees in-range pixels).
        /// `None` before any key frame.
        pub fn clamping_type(&self) -> Option<bool> {
            self.state.clamping_type()
        }
    }

    impl std::fmt::Debug for Vp8Decoder {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("Vp8Decoder")
                .field("codec_id", &self.codec_id)
                .field("pending", &self.pending.len())
                .field("eof", &self.eof)
                .field("shape", &self.shape)
                .field("generation", &self.generation)
                .finish()
        }
    }

    impl Decoder for Vp8Decoder {
        fn codec_id(&self) -> &CodecId {
            &self.codec_id
        }

        fn send_packet(&mut self, packet: &Packet) -> Result<()> {
            self.pending.push_back(packet.clone());
            Ok(())
        }

        /// Take the thread budget for each frame's decode from the
        /// framework (serial unless one is announced). The pictures do
        /// not depend on it.
        fn set_execution_context(&mut self, ctx: &oxideav_core::ExecutionContext) {
            self.state.set_threads(ctx.threads);
        }

        fn receive_frame(&mut self) -> Result<Frame> {
            if let Some(vf) = self.held.take() {
                return Ok(Frame::Video(vf));
            }
            loop {
                let Some(pkt) = self.pending.pop_front() else {
                    return if self.eof {
                        Err(Error::Eof)
                    } else {
                        Err(Error::NeedMore)
                    };
                };
                let decoded = self.state.decode_frame(&pkt.data)?;
                if self.state.last_frame_shown() == Some(false) {
                    // §9.1 show_frame = 0: reference-only, not for display.
                    continue;
                }
                let shape = OutputShape::from_state(&self.state)
                    .expect("a decoded frame implies a decoded key frame");
                let mut vf: VideoFrame = decoded.into();
                vf.pts = pkt.pts;
                return match self.shape {
                    Some(current) if current != shape => {
                        self.shape = Some(shape);
                        self.generation = self.generation.wrapping_add(1);
                        self.held = Some(vf);
                        Ok(Frame::StreamParams(Box::new(
                            shape.to_params(&self.codec_id),
                        )))
                    }
                    _ => {
                        self.shape = Some(shape);
                        Ok(Frame::Video(vf))
                    }
                };
            }
        }

        fn flush(&mut self) -> Result<()> {
            self.eof = true;
            Ok(())
        }

        fn reset(&mut self) -> Result<()> {
            self.pending.clear();
            self.held = None;
            self.eof = false;
            let cap = self.state.max_pixels_per_frame();
            let threads = self.state.threads();
            self.state = crate::state::Vp8DecoderState::new()
                .with_max_pixels_per_frame(cap)
                .with_threads(threads);
            // `shape` / `generation` are kept: the next picture is
            // compared against the last one returned before the reset.
            Ok(())
        }

        fn output_pixel_format(&self) -> Option<PixelFormat> {
            self.output_params().and_then(|p| p.pixel_format)
        }

        fn output_params(&self) -> Option<CodecParameters> {
            // The last picture returned; before the first one, the key
            // frame already decoded (an invisible one returns no picture),
            // else the first queued key frame's headers.
            let shape = self
                .shape
                .or_else(|| OutputShape::from_state(&self.state))
                .or_else(|| {
                    self.pending
                        .iter()
                        .find_map(|p| OutputShape::peek_key_frame(&p.data))
                })?;
            Some(shape.to_params(&self.codec_id))
        }

        fn output_params_generation(&self) -> u64 {
            self.generation
        }
    }

    /// `make_decoder` factory plugged into the registry. Required by the
    /// `DecoderFactory` function-pointer type.
    pub fn make_decoder(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
        // Thread the caller's DoS caps into the decoder so a tightened
        // `max_pixels_per_frame` is enforced on every key frame.
        Ok(Box::new(Vp8Decoder::with_limits(
            params.codec_id.clone(),
            params.limits,
        )))
    }

    /// Register the VP8 codec into the supplied [`CodecRegistry`] under the
    /// canonical [`VP8_CODEC_ID`] codec id, with the container tags VP8
    /// commonly carries (Matroska / WebM `V_VP8`, MP4 / ISOBMFF `vp08`,
    /// IVF / RIFF `VP80` FourCC).
    pub fn register_codecs(reg: &mut CodecRegistry) {
        let caps = CodecCapabilities::video(VP8_CODEC_ID)
            .with_lossy(true)
            .with_max_size(16384, 16384);
        reg.register(
            CodecInfo::new(CodecId::new(VP8_CODEC_ID))
                .capabilities(caps)
                .decoder(make_decoder)
                .encoder(crate::encoder::make_encoder_from_param_options)
                .encoder_options::<crate::encoder::Vp8EncoderOptions>()
                .tags([
                    CodecTag::fourcc(b"VP80"),
                    CodecTag::fourcc(b"vp08"),
                    CodecTag::matroska("V_VP8"),
                ]),
        );
    }

    /// Unified entry point — installs the VP8 codec into a
    /// [`RuntimeContext`]. Called by `oxideav-meta` via the
    /// [`oxideav_core::register!`] hook in `lib.rs`.
    pub fn register(ctx: &mut RuntimeContext) {
        register_codecs(&mut ctx.codecs);
    }

    /// Helper that the public reflection / fallback path inspects: returns
    /// the pixel format the decoder produces (always I420 in this build).
    pub fn output_pixel_format() -> PixelFormat {
        PixelFormat::Yuv420P
    }
}

#[cfg(feature = "registry")]
pub use registry::{
    VP8_CODEC_ID, Vp8Decoder, make_decoder, output_pixel_format, register, register_codecs,
};

// ───────────────────────────── tests ────────────────────────────────

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

    /// Strip the 32-byte DKIF header and one 12-byte IVF frame header off
    /// the front of an IVF file and return the contained VP8 elementary
    /// frame bytes. This is **not** a container parser — it knows just
    /// enough about the IVF wrapper to lift a single VP8 frame out of a
    /// fixture so the codec test stays self-contained per the workspace
    /// "no cross-crate dev-deps" rule. The IVF wrapper is a 32-byte DKIF
    /// header (`'DKIF'` magic + version + header_len + FourCC + width +
    /// height + fps + scale + frame_count + reserved) followed by one or
    /// more 12-byte frame headers (4-byte LE frame size + 8-byte LE pts)
    /// each preceding the raw frame bytes — read directly off the fixture
    /// `input.ivf` byte layout, no external parser consulted.
    fn strip_single_ivf_frame(ivf: &[u8]) -> &[u8] {
        assert!(ivf.len() >= 32 + 12, "IVF too short for a single frame");
        assert_eq!(&ivf[0..4], b"DKIF", "expected DKIF magic");
        let frame_hdr_off = 32;
        let frame_size = u32::from_le_bytes([
            ivf[frame_hdr_off],
            ivf[frame_hdr_off + 1],
            ivf[frame_hdr_off + 2],
            ivf[frame_hdr_off + 3],
        ]) as usize;
        let payload_off = frame_hdr_off + 12;
        assert!(
            ivf.len() >= payload_off + frame_size,
            "IVF frame body truncated"
        );
        &ivf[payload_off..payload_off + frame_size]
    }

    /// Build a minimal interframe (3-byte frame tag with bit 0 = 1).
    fn interframe_bytes() -> Vec<u8> {
        // tmp = 1: key_frame bit set → interframe; version=0; show=0;
        // first_partition_size=0.
        vec![0x01, 0x00, 0x00]
    }

    #[test]
    fn non_keyframe_rejected_as_unsupported() {
        let res = decode_vp8(&interframe_bytes());
        assert!(matches!(res, Err(DecodeError::Unsupported(_))));
    }

    #[test]
    fn too_short_frame_header_propagates_error() {
        let res = decode_vp8(&[]);
        assert!(matches!(
            res,
            Err(DecodeError::FrameHeader(
                crate::frame_header::FrameHeaderError::InputTooShort
            ))
        ));
    }

    #[test]
    fn truncated_first_partition_surfaces_clean_error() {
        // Build a key-frame header whose first_partition_size is 1000 but
        // append no actual partition bytes. The function should refuse on
        // the slice carve, not panic.
        //
        // first_partition_size = 1000 → tmp = 1000 << 5 = 0x7d00.
        let fps: u32 = 1000;
        let tmp: u32 = fps << 5;
        let mut buf = vec![
            (tmp & 0xff) as u8,
            ((tmp >> 8) & 0xff) as u8,
            ((tmp >> 16) & 0xff) as u8,
        ];
        // Start code + width/height (16x16, scale 0).
        buf.extend_from_slice(&[0x9d, 0x01, 0x2a, 0x10, 0x00, 0x10, 0x00]);
        assert_eq!(buf.len(), 10);
        let res = decode_vp8(&buf);
        assert!(matches!(
            res,
            Err(DecodeError::TruncatedFirstPartition {
                available: 0,
                declared: 1000,
            })
        ));
    }

    /// `crop_to_visible`'s contiguous fast path (taken when the visible
    /// width equals the macroblock-padded stride) must produce byte-for-byte
    /// the same packed I420 output as the strided per-row copy. Sweeps an
    /// aligned case (no per-row gap → contiguous path) and a cropped case
    /// (visible < stride → strided path) against a reference that always
    /// copies row-by-row, on a deterministically textured plane set.
    #[test]
    fn crop_to_visible_contiguous_matches_strided() {
        // Reference: the unconditional strided per-row crop.
        fn crop_strided(planes: &KeyframePlanes, width: u32, height: u32) -> Vp8DecodedFrame {
            let w = width as usize;
            let h = height as usize;
            let uvw = w.div_ceil(2);
            let uvh = h.div_ceil(2);
            let mut y = Vec::with_capacity(w * h);
            for r in 0..h {
                let src = r * planes.y_stride;
                y.extend_from_slice(&planes.y[src..src + w]);
            }
            let mut u = Vec::with_capacity(uvw * uvh);
            let mut v = Vec::with_capacity(uvw * uvh);
            for r in 0..uvh {
                let src = r * planes.uv_stride;
                u.extend_from_slice(&planes.u[src..src + uvw]);
                v.extend_from_slice(&planes.v[src..src + uvw]);
            }
            Vp8DecodedFrame {
                width,
                height,
                y,
                u,
                v,
            }
        }

        // Build a 2×2-macroblock padded plane set (32×32 luma, 16×16 chroma)
        // filled with a position-dependent LCG texture so a stride/offset bug
        // produces visibly wrong bytes.
        let mb_cols = 2usize;
        let mb_rows = 2usize;
        let y_stride = mb_cols * 16; // 32
        let uv_stride = mb_cols * 8; // 16
        let y_rows = mb_rows * 16; // 32
        let uv_rows = mb_rows * 8; // 16
        let mut seed: u32 = 0x1234_5678;
        let mut next = || {
            seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            (seed >> 24) as u8
        };
        let y: Vec<u8> = (0..y_stride * y_rows).map(|_| next()).collect();
        let u: Vec<u8> = (0..uv_stride * uv_rows).map(|_| next()).collect();
        let v: Vec<u8> = (0..uv_stride * uv_rows).map(|_| next()).collect();
        let planes = KeyframePlanes {
            y,
            u,
            v,
            y_stride,
            uv_stride,
            mb_cols,
            mb_rows,
        };

        // Aligned case: visible == padded → contiguous fast path.
        let got = crop_to_visible(&planes, 32, 32);
        let want = crop_strided(&planes, 32, 32);
        assert_eq!(got.y, want.y, "aligned luma");
        assert_eq!(got.u, want.u, "aligned U");
        assert_eq!(got.v, want.v, "aligned V");

        // Cropped case: visible < padded on both axes → strided path. Chroma
        // visible width 17.div_ceil(2)=9 < uv_stride 16 keeps the chroma
        // strided path active too.
        let got = crop_to_visible(&planes, 17, 18);
        let want = crop_strided(&planes, 17, 18);
        assert_eq!(got.y, want.y, "cropped luma");
        assert_eq!(got.u, want.u, "cropped U");
        assert_eq!(got.v, want.v, "cropped V");

        // Mixed case: luma aligned (width==stride) but chroma not. width 32 →
        // uvw 16 == uv_stride → both contiguous; use width 32 height 30 so the
        // luma row count differs but width stays aligned (luma contiguous,
        // height truncation handled by the `w*h` prefix length).
        let got = crop_to_visible(&planes, 32, 30);
        let want = crop_strided(&planes, 32, 30);
        assert_eq!(got.y, want.y, "height-truncated luma");
        assert_eq!(got.u, want.u, "height-truncated U");
        assert_eq!(got.v, want.v, "height-truncated V");
    }

    #[test]
    fn zero_dimension_rejected() {
        // Valid key-frame header but with width = height = 0.
        let buf = [0x00, 0x00, 0x00, 0x9d, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00];
        let res = decode_vp8(&buf);
        assert!(matches!(res, Err(DecodeError::ZeroDimension)));
    }

    #[test]
    fn check_pixel_cap_boundary() {
        // Exactly at the cap is allowed; one over is refused.
        assert!(check_pixel_cap(16, 16, 256).is_ok());
        assert!(matches!(
            check_pixel_cap(16, 17, 256),
            Err(DecodeError::FrameTooLarge {
                pixels: 272,
                cap: 256
            })
        ));
        // u32::MAX × u32::MAX must not overflow the u64 product.
        assert!(matches!(
            check_pixel_cap(u32::MAX, u32::MAX, DEFAULT_MAX_PIXELS_PER_FRAME),
            Err(DecodeError::FrameTooLarge { .. })
        ));
    }

    /// A real 16×16 key frame decodes under the default cap but is refused
    /// (before any allocation) once the caller tightens the cap below its
    /// 256-pixel declared size. Guards the DoS entry point end-to-end.
    #[test]
    fn tight_pixel_cap_rejects_before_alloc() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
        let frame = strip_single_ivf_frame(IVF);

        // Default cap: decodes to the full 16×16 picture.
        let ok = decode_vp8(frame).expect("default cap decodes the 16x16 key frame");
        assert_eq!((ok.width, ok.height), (16, 16));

        // Exactly 256 px is still allowed (cap is inclusive).
        assert!(decode_vp8_with_max_pixels(frame, 256).is_ok());

        // 255 px cap: the 256-px frame is refused with the DoS error and no
        // partial decode.
        let err = decode_vp8_with_max_pixels(frame, 255)
            .expect_err("a 255-px cap must reject a 256-px frame");
        assert!(matches!(
            err,
            DecodeError::FrameTooLarge {
                pixels: 256,
                cap: 255
            }
        ));
    }

    /// The tiny-i-only-16x16 fixture is a single-keyframe VP8 elementary
    /// stream packaged in IVF; decoding the contained 57-byte frame should
    /// produce a 16x16 I420 picture.
    ///
    /// `expected.yuv` from the fixture set is the reference decoder's
    /// black-box output for the same input (the `ffmpeg` invocation that
    /// produced it is recorded in the fixture's `notes.md`). The decode is
    /// **bit-exact** against that reference — the whole point of VP8's
    /// "exact pixel values are part of the specification" guarantee (RFC
    /// 6386 §2). We assert the full I420 byte stream (Y then U then V)
    /// equals `expected.yuv` so a regression anywhere in the
    /// bitstream → dequant → reconstruct → loop-filter chain is caught.
    #[test]
    fn tiny_i_only_16x16_fixture_decodes_bit_exact() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
        const EXPECTED: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/expected.yuv");
        // Sanity: trace.txt lists the contained frame as 57 bytes.
        assert_eq!(
            strip_single_ivf_frame(IVF).len(),
            57,
            "fixture VP8 frame size changed"
        );
        // Concatenate the planes in I420 order and require a byte-exact
        // match against the reference (384 bytes = 256 Y + 64 U + 64 V).
        assert_fixture_bit_exact(IVF, EXPECTED, 16, 16);
    }

    /// A second, multi-macroblock bit-exact fixture: a 64×64 intra-only
    /// key frame (4×4 = 16 macroblocks, one DCT partition). Exercises the
    /// §12 cross-macroblock neighbour propagation (above-row / left-column
    /// strips), the §13.3 above/left non-zero predictor threading across a
    /// full raster of macroblocks, and the §15.1 loop-filter geometry over
    /// internal macroblock edges — none of which the single-MB 16×16
    /// fixture touches. Bit-exact against the reference YUV.
    #[test]
    fn i_only_64x64_fixture_decodes_bit_exact() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/i-only-64x64/input.ivf");
        const EXPECTED: &[u8] = include_bytes!("../tests/fixtures/i-only-64x64/expected.yuv");
        // 6144 bytes = 64*64 Y + 32*32 U + 32*32 V.
        assert_fixture_bit_exact(IVF, EXPECTED, 64, 64);
    }

    /// Decode a fixture IVF and assert its single key frame is bit-exact
    /// against the reference YUV. `w` / `h` are the visible dimensions.
    fn assert_fixture_bit_exact(ivf: &[u8], expected: &[u8], w: u32, h: u32) {
        let frame_bytes = strip_single_ivf_frame(ivf);
        let decoded = decode_vp8(frame_bytes).expect("fixture should decode");
        assert_eq!(decoded.width, w);
        assert_eq!(decoded.height, h);
        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.len(), expected.len(), "plane byte count mismatch");
        assert_eq!(got, expected, "decoded I420 must be bit-exact vs reference");
    }

    /// A 16×16 key frame coded with **four DCT partitions** (the
    /// `log2_nbr_of_dct_partitions = 2` case, §9.5). Exercises the 3-byte
    /// little-endian partition-size table parse and the round-robin row
    /// striping (one MB row → partition 0). Bit-exact against the
    /// reference.
    #[test]
    fn partition_padding_16x16_4parts_decodes_bit_exact() {
        const IVF: &[u8] =
            include_bytes!("../tests/fixtures/partition-padding-16x16-4parts/input.ivf");
        const EXPECTED: &[u8] =
            include_bytes!("../tests/fixtures/partition-padding-16x16-4parts/expected.yuv");
        assert_fixture_bit_exact(IVF, EXPECTED, 16, 16);
    }

    /// A 128×128 key frame (8×8 = 64 macroblocks) coded with four DCT
    /// partitions. With eight macroblock rows striped round-robin across
    /// four partitions (rows 0/4 → part 0, 1/5 → part 1, …) this is the
    /// fixture that actually exercises the §20.4 multi-row partition
    /// routing (and the per-partition bool-decoder cursor persisting across
    /// the rows that share a partition). Bit-exact against the reference.
    #[test]
    fn segment_4_partitions_128x128_decodes_bit_exact() {
        const IVF: &[u8] = include_bytes!("../tests/fixtures/segment-4-partitions/input.ivf");
        const EXPECTED: &[u8] =
            include_bytes!("../tests/fixtures/segment-4-partitions/expected.yuv");
        assert_fixture_bit_exact(IVF, EXPECTED, 128, 128);
    }

    /// A batch of single-key-frame fixtures, each decoded bit-exact
    /// against its reference YUV. These cover decode behaviours the
    /// 16×16 / 64×64 / partition fixtures above don't reach:
    ///
    /// * `q-high` — `loop_filter_level = 38` (heavy normal deblocking)
    ///   over a 128×128 frame, the strongest test of the §15.3 `mb_filter`
    ///   / `subblock_filter` parameter ladder.
    /// * `i-only-loopfilter-high` — `loop_filter_level = 33` over 64×64.
    /// * `i-only-loopfilter-off` — `loop_filter_level = 0` (the §15 page-84
    ///   whole-frame filter skip).
    /// * `vp8-with-loopfilter-mode-simple` — the §15.2 simple-filter path
    ///   (`filter_type = 1`, luma-only).
    /// * `q-low` — `loop_filter_level = 0`, 32×32 (a non-multiple-of-16
    ///   path is the next size up; 32 is a clean 2×2 MB grid).
    /// * `gradient-and-noise-128x128` — high-entropy content that exercises
    ///   the full §13 token alphabet (cat ranges, dense blocks).
    #[test]
    fn additional_single_keyframe_fixtures_decode_bit_exact() {
        // (fixture name, input IVF bytes, expected YUV, visible w, visible h)
        type FixtureCase = (&'static str, &'static [u8], &'static [u8], u32, u32);
        let cases: &[FixtureCase] = &[
            (
                "q-high",
                include_bytes!("../tests/fixtures/q-high/input.ivf"),
                include_bytes!("../tests/fixtures/q-high/expected.yuv"),
                128,
                128,
            ),
            (
                "q-low",
                include_bytes!("../tests/fixtures/q-low/input.ivf"),
                include_bytes!("../tests/fixtures/q-low/expected.yuv"),
                32,
                32,
            ),
            (
                "i-only-loopfilter-off",
                include_bytes!("../tests/fixtures/i-only-loopfilter-off/input.ivf"),
                include_bytes!("../tests/fixtures/i-only-loopfilter-off/expected.yuv"),
                64,
                64,
            ),
            (
                "i-only-loopfilter-high",
                include_bytes!("../tests/fixtures/i-only-loopfilter-high/input.ivf"),
                include_bytes!("../tests/fixtures/i-only-loopfilter-high/expected.yuv"),
                64,
                64,
            ),
            (
                "gradient-and-noise-128x128",
                include_bytes!("../tests/fixtures/gradient-and-noise-128x128/input.ivf"),
                include_bytes!("../tests/fixtures/gradient-and-noise-128x128/expected.yuv"),
                128,
                128,
            ),
            (
                "vp8-with-loopfilter-mode-simple",
                include_bytes!("../tests/fixtures/vp8-with-loopfilter-mode-simple/input.ivf"),
                include_bytes!("../tests/fixtures/vp8-with-loopfilter-mode-simple/expected.yuv"),
                64,
                64,
            ),
        ];
        for (name, ivf, expected, w, h) in cases {
            let frame_bytes = strip_single_ivf_frame(ivf);
            let decoded = decode_vp8(frame_bytes)
                .unwrap_or_else(|e| panic!("fixture {name} 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,
                "fixture {name} must be bit-exact against the reference"
            );
        }
    }

    #[test]
    fn carve_dct_partitions_single_partition_no_size_table() {
        // num_partitions = 1: the whole section is the one partition; no
        // 3-byte size table is read.
        let section = [0xAAu8; 7];
        let parts = carve_dct_partitions(&section, 1).expect("single-partition");
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0], &section[..]);
    }

    #[test]
    fn carve_dct_partitions_two_partitions_uses_three_byte_size_prefix() {
        // num_partitions = 2: 3 bytes of size prefix for partition 0,
        // partition 1 takes the rest.
        //
        // Build: size[0] = 4 (LE 04 00 00) | partition0 (4 bytes) |
        //        partition1 (3 bytes).
        let mut buf = vec![0x04, 0x00, 0x00];
        buf.extend_from_slice(&[0xA1, 0xA2, 0xA3, 0xA4]);
        buf.extend_from_slice(&[0xB1, 0xB2, 0xB3]);
        let parts = carve_dct_partitions(&buf, 2).expect("two-partition");
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0], &[0xA1, 0xA2, 0xA3, 0xA4][..]);
        assert_eq!(parts[1], &[0xB1, 0xB2, 0xB3][..]);
    }

    #[test]
    fn carve_dct_partitions_truncated_size_table_rejected() {
        // num_partitions = 2 needs 3 size bytes; supply only 2.
        let buf = [0x04u8, 0x00];
        let res = carve_dct_partitions(&buf, 2);
        assert!(matches!(res, Err(DecodeError::TruncatedPartitionSizes)));
    }

    #[test]
    fn carve_dct_partitions_truncated_body_rejected() {
        // size[0] = 10, but only 6 body bytes available.
        let mut buf = vec![0x0Au8, 0x00, 0x00];
        buf.extend_from_slice(&[0xCC; 6]);
        let res = carve_dct_partitions(&buf, 2);
        assert!(matches!(
            res,
            Err(DecodeError::TruncatedDctPartition {
                index: 0,
                available: 6,
                declared: 10,
            })
        ));
    }

    #[cfg(feature = "registry")]
    mod registry_tests {
        use super::*;
        use oxideav_core::{CodecId, Decoder as _, Error, Frame, Packet, TimeBase};

        #[test]
        fn vp8_decoder_returns_unsupported_for_interframe_before_keyframe() {
            // An interframe fed in with no prior key frame can't decode
            // (the §16 inter-prediction layer has no reference to predict
            // from); surfaces `Error::Unsupported` via the
            // `Vp8DecoderState` driver's empty-reference-slot check.
            let mut dec = Vp8Decoder::new(CodecId::new(VP8_CODEC_ID));
            let pkt = Packet::new(0, TimeBase::new(1, 1000), interframe_bytes());
            dec.send_packet(&pkt).expect("queue packet");
            match dec.receive_frame() {
                Err(Error::Unsupported(_)) => {}
                other => panic!("expected Unsupported, got {other:?}"),
            }
        }

        #[test]
        fn vp8_decoder_needs_packet_before_frame() {
            let mut dec = Vp8Decoder::new(CodecId::new(VP8_CODEC_ID));
            match dec.receive_frame() {
                Err(Error::NeedMore) => {}
                other => panic!("expected NeedMore, got {other:?}"),
            }
        }

        #[test]
        fn vp8_decoder_decodes_tiny_keyframe_through_trait_api() {
            const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
            let frame_bytes = strip_single_ivf_frame(IVF);
            let mut dec = Vp8Decoder::new(CodecId::new(VP8_CODEC_ID));
            let mut pkt = Packet::new(0, TimeBase::new(1, 1000), frame_bytes.to_vec());
            pkt.pts = Some(42);
            pkt.flags.keyframe = true;
            dec.send_packet(&pkt).expect("send packet");
            let frame = dec.receive_frame().expect("decode");
            let Frame::Video(v) = frame else {
                panic!("expected Video frame, got {frame:?}");
            };
            assert_eq!(v.planes.len(), 3, "I420 has three planes");
            assert_eq!(v.planes[0].stride, 16);
            assert_eq!(v.planes[1].stride, 8);
            assert_eq!(v.planes[2].stride, 8);
            assert_eq!(v.planes[0].data.len(), 16 * 16);
            assert_eq!(v.planes[1].data.len(), 8 * 8);
            assert_eq!(v.planes[2].data.len(), 8 * 8);
            assert_eq!(v.pts, Some(42));
            // After draining, the next call needs more input.
            assert!(matches!(dec.receive_frame(), Err(Error::NeedMore)));
        }

        /// End-to-end multi-frame decode through the `Decoder` trait
        /// surface — feed the two-frame `i-frame-then-p-frame-64x64`
        /// fixture as two consecutive `Packet`s and assert both frames
        /// produce a `Frame::Video` (the bit-exact pixel-match itself is
        /// covered by the state-module tests).
        #[test]
        fn vp8_decoder_decodes_multi_frame_through_trait_api() {
            const IVF: &[u8] =
                include_bytes!("../tests/fixtures/i-frame-then-p-frame-64x64/input.ivf");
            // Walk the IVF (32-byte DKIF + per-frame 12-byte headers).
            let mut frames: Vec<Vec<u8>> = 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;
                frames.push(IVF[body..body + size].to_vec());
                cur = body + size;
            }
            assert_eq!(frames.len(), 2, "fixture has 2 frames");
            let mut dec = Vp8Decoder::new(CodecId::new(VP8_CODEC_ID));
            for (i, bytes) in frames.iter().enumerate() {
                let pkt = Packet::new(i as u32, TimeBase::new(1, 1000), bytes.clone());
                dec.send_packet(&pkt).expect("send packet");
                let frame = dec.receive_frame().expect("decode through trait API");
                let Frame::Video(v) = frame else {
                    panic!("expected Video frame, got {frame:?}");
                };
                assert_eq!(v.planes.len(), 3, "I420 has 3 planes");
                assert_eq!(v.planes[0].stride, 64);
                assert_eq!(v.planes[1].stride, 32);
                assert_eq!(v.planes[2].stride, 32);
            }
        }

        /// `make_decoder` threads `CodecParameters::limits` into the
        /// decoder: a tightened `max_pixels_per_frame` refuses an oversized
        /// key frame with `Error::ResourceExhausted` through the trait API,
        /// while the default limits decode the same frame unchanged.
        #[test]
        fn make_decoder_honours_pixel_cap_from_params() {
            use oxideav_core::{CodecParameters, DecoderLimits};
            const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
            let frame_bytes = strip_single_ivf_frame(IVF).to_vec();
            let id = CodecId::new(VP8_CODEC_ID);

            // Default params: the 256-px frame decodes.
            let mut dec = make_decoder(&CodecParameters::video(id.clone()))
                .expect("factory builds a decoder");
            let pkt = Packet::new(0, TimeBase::new(1, 1000), frame_bytes.clone());
            dec.send_packet(&pkt).expect("queue");
            assert!(matches!(dec.receive_frame(), Ok(Frame::Video(_))));

            // Tightened to 255 px: the 256-px frame is refused as a
            // resource-exhaustion (DoS-cap) error, not a decode error.
            let params = CodecParameters::video(id)
                .with_limits(DecoderLimits::default().with_max_pixels_per_frame(255));
            let mut dec = make_decoder(&params).expect("factory builds a decoder");
            let pkt = Packet::new(0, TimeBase::new(1, 1000), frame_bytes);
            dec.send_packet(&pkt).expect("queue");
            match dec.receive_frame() {
                Err(Error::ResourceExhausted(_)) => {}
                other => panic!("expected ResourceExhausted, got {other:?}"),
            }
        }

        #[test]
        fn registers_into_codec_registry() {
            use oxideav_core::CodecRegistry;
            let mut reg = CodecRegistry::new();
            register_codecs(&mut reg);
            // The id we registered under must round-trip through
            // `decoder_ids()`.
            let id = CodecId::new(VP8_CODEC_ID);
            let found = reg.decoder_ids().any(|i| i == &id);
            assert!(found, "vp8 codec id should be enumerated");
        }
    }
}