oxideav_vp8/decoder.rs
1//! VP8 per-frame decode driver (`decode_vp8`) and the
2//! [`oxideav_core::Decoder`] integration.
3//!
4//! This module is the top of the keyframe decode chain — the entry point
5//! that takes the raw bytes of one VP8 frame ("one packet = one frame")
6//! and produces a fully-reconstructed, loop-filtered I420
7//! [`Vp8DecodedFrame`] (and, when the `registry` feature is on, an
8//! [`oxideav_core::VideoFrame`]).
9//!
10//! ## Frame layout per RFC 6386 §4 / §9
11//!
12//! Every VP8 frame ships as:
13//!
14//! 1. The §9.1 uncompressed header — 3 bytes for an interframe, 10 bytes
15//! for a key frame (3-byte frame tag + 3-byte start code + two
16//! 16-bit little-endian width / height words). [`Vp8FrameHeader::parse`]
17//! handles the layout.
18//! 2. The "first" (control) partition — `first_partition_size` bytes
19//! immediately following the uncompressed header. The first partition
20//! carries the §19.2 frame header and the §19.3 per-macroblock
21//! *prediction* records (segment id, skip flag, intra Y / sub-block /
22//! UV modes — §11) for every macroblock in raster order.
23//! 3. (Only when `log2_nbr_of_dct_partitions > 0`)
24//! `(nbr_of_dct_partitions - 1) * 3` bytes of 3-byte little-endian
25//! DCT-partition sizes (RFC 6386 §9.5). Each entry is the byte length
26//! of the corresponding DCT partition that follows; the last partition's
27//! length is computed by subtraction from the frame total.
28//! 4. `nbr_of_dct_partitions` concatenated DCT partitions carrying the
29//! §13 residual-coefficient records (`residual_data()` per §19.3) for
30//! every macroblock. Macroblock rows are striped round-robin across the
31//! partitions: row `r` is read from partition `r % nbr_of_dct_partitions`
32//! (RFC 6386 §20.4 — `for (row, partition = 0; row < mb_rows; row++) { ...;
33//! if (++partition == ctx->token_hdr.partitions) partition = 0; }`).
34//! Each partition uses its own [`BoolDecoder`] instance (RFC 6386
35//! §4 page 9 — "All partitions are decoded using separate instances of
36//! the boolean entropy decoder").
37//!
38//! ## Scope
39//!
40//! [`decode_vp8`] is the **stateless** single-frame entry point — it
41//! decodes one key frame in isolation and returns
42//! [`DecodeError::Unsupported`] on an interframe (since interframes
43//! need a reference-frame buffer this function does not own). For
44//! multi-frame streams with P-frames, use
45//! [`crate::state::Vp8DecoderState::decode_frame`], which owns the
46//! RFC 6386 §9 three-slot reference-frame buffer and handles both
47//! key frames and interframes end-to-end.
48
49use crate::bool_decoder::BoolDecoder;
50use crate::coded_header::{CodedHeaderError, Vp8CodedHeader};
51use crate::dct_tokens::{CoeffProbs, MbCoeffError, MbEntropyCtx, merge_default_token_probs};
52use crate::dequant::{MbDequantFactors, decode_and_dequantize_mb};
53use crate::frame::{FrameError, KeyframePlanes, MbCoeffs, decode_keyframe};
54use crate::frame_header::{FrameHeaderError, Vp8FrameHeader};
55use crate::loop_filter::{FrameFilterConfig, MAX_MB_SEGMENTS, filter_frame};
56use crate::macroblock::{
57 IntraYMode, MacroblockError, MacroblockModes, parse_key_frame_macroblock_modes,
58};
59
60/// Errors surfaced by [`decode_vp8`].
61#[derive(Debug, Clone, PartialEq, Eq)]
62#[non_exhaustive]
63pub enum DecodeError {
64 /// The §9.1 uncompressed header could not be parsed.
65 FrameHeader(FrameHeaderError),
66 /// The §19.2 boolean-coded frame header could not be parsed.
67 CodedHeader(CodedHeaderError),
68 /// The §11 / §19.3 macroblock prediction layer could not be parsed.
69 Macroblock(MacroblockError),
70 /// The §13 residual-coefficient layer could not be parsed.
71 MbCoeffs {
72 /// `mb_row * mb_cols + mb_col` of the offending macroblock.
73 index: usize,
74 /// The underlying token-decode error.
75 source: MbCoeffError,
76 },
77 /// The §14.2 per-MB reconstruction step rejected its inputs.
78 Frame(FrameError),
79 /// The frame is not a key frame — interframes are not yet supported.
80 /// VP8 P-frames need §16 motion-vector decoding, §16.2 mv_ref tree
81 /// resolution, and the reference-frame compositor (none of which are
82 /// landed yet). Callers that receive this on a P-frame should treat
83 /// the stream as un-decodable past the last key frame.
84 Unsupported(&'static str),
85 /// The first partition declared in the frame tag extends past the end
86 /// of the supplied input bytes (truncated packet).
87 TruncatedFirstPartition {
88 /// Bytes available after the uncompressed header.
89 available: usize,
90 /// Bytes the frame tag's `first_partition_size` claimed.
91 declared: usize,
92 },
93 /// One of the 3-byte DCT-partition size prefixes could not be read
94 /// (truncated packet).
95 TruncatedPartitionSizes,
96 /// A declared DCT partition extends past the end of the supplied
97 /// input bytes (truncated packet).
98 TruncatedDctPartition {
99 /// 0-based partition index (`0..nbr_of_dct_partitions`).
100 index: usize,
101 /// Bytes available for the partition.
102 available: usize,
103 /// Bytes the size prefix declared.
104 declared: usize,
105 },
106 /// `width` or `height` from the §9.1 key-frame size words was zero —
107 /// a valid VP8 key frame describes at least one pixel.
108 ZeroDimension,
109 /// The §9.1 key-frame `width × height` product exceeds the caller's
110 /// configured pixel cap. Raised *before* any plane / macroblock-grid
111 /// allocation so a tiny header declaring an enormous frame is rejected
112 /// without the decoder ever attempting the allocation. `pixels` is the
113 /// declared product (`width as u64 * height as u64`), `cap` the
114 /// configured maximum.
115 FrameTooLarge {
116 /// Declared `width as u64 * height as u64`.
117 pixels: u64,
118 /// Configured `max_pixels_per_frame` cap.
119 cap: u64,
120 },
121}
122
123/// Default per-frame pixel cap the stateless [`decode_vp8`] entry point and
124/// a freshly-constructed [`Vp8DecoderState`](crate::state::Vp8DecoderState)
125/// enforce when the caller does not tighten it.
126///
127/// Set to `32_768 × 32_768 = 1_073_741_824` — deliberately generous. VP8's
128/// §9.1 size words are 14 bits each, so a legal frame never exceeds
129/// `16_383 × 16_383 ≈ 268 M` pixels and this default therefore rejects no
130/// real key frame; it exists so callers processing untrusted input can
131/// *tighten* the cap (via [`decode_vp8_with_max_pixels`] or
132/// [`Vp8DecoderState::with_max_pixels_per_frame`](crate::state::Vp8DecoderState::with_max_pixels_per_frame))
133/// and have a huge declared frame refused before allocation instead of
134/// OOM-ing. Numerically matches `oxideav_core::DecoderLimits::default()`'s
135/// `max_pixels_per_frame` so the two layers agree.
136pub const DEFAULT_MAX_PIXELS_PER_FRAME: u64 = 32_768 * 32_768;
137
138/// Check the §9.1 declared `width × height` against a pixel cap.
139///
140/// Computed in `u64` so the `16_383 × 16_383` worst case (or any wider
141/// value a future caller might pass) cannot overflow. Returns
142/// [`DecodeError::FrameTooLarge`] when the product exceeds `cap`.
143pub(crate) fn check_pixel_cap(width: u32, height: u32, cap: u64) -> Result<(), DecodeError> {
144 let pixels = width as u64 * height as u64;
145 if pixels > cap {
146 return Err(DecodeError::FrameTooLarge { pixels, cap });
147 }
148 Ok(())
149}
150
151impl core::fmt::Display for DecodeError {
152 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
153 match self {
154 DecodeError::FrameHeader(e) => write!(f, "vp8 decode: {e}"),
155 DecodeError::CodedHeader(e) => write!(f, "vp8 decode: {e}"),
156 DecodeError::Macroblock(e) => write!(f, "vp8 decode: {e}"),
157 DecodeError::MbCoeffs { index, source } => {
158 write!(f, "vp8 decode: macroblock {index}: {source}")
159 }
160 DecodeError::Frame(e) => write!(f, "vp8 decode: {e}"),
161 DecodeError::Unsupported(msg) => write!(f, "vp8 decode: {msg}"),
162 DecodeError::TruncatedFirstPartition {
163 available,
164 declared,
165 } => write!(
166 f,
167 "vp8 decode: truncated first partition ({declared} declared, {available} available)"
168 ),
169 DecodeError::TruncatedPartitionSizes => {
170 f.write_str("vp8 decode: truncated DCT-partition size prefixes")
171 }
172 DecodeError::TruncatedDctPartition {
173 index,
174 available,
175 declared,
176 } => write!(
177 f,
178 "vp8 decode: truncated DCT partition {index} ({declared} declared, {available} available)"
179 ),
180 DecodeError::ZeroDimension => {
181 f.write_str("vp8 decode: zero width or height in key-frame header")
182 }
183 DecodeError::FrameTooLarge { pixels, cap } => write!(
184 f,
185 "vp8 decode: declared frame size {pixels} px exceeds configured cap {cap} px"
186 ),
187 }
188 }
189}
190
191impl std::error::Error for DecodeError {}
192
193impl From<FrameHeaderError> for DecodeError {
194 fn from(value: FrameHeaderError) -> Self {
195 DecodeError::FrameHeader(value)
196 }
197}
198impl From<CodedHeaderError> for DecodeError {
199 fn from(value: CodedHeaderError) -> Self {
200 DecodeError::CodedHeader(value)
201 }
202}
203impl From<MacroblockError> for DecodeError {
204 fn from(value: MacroblockError) -> Self {
205 DecodeError::Macroblock(value)
206 }
207}
208impl From<FrameError> for DecodeError {
209 fn from(value: FrameError) -> Self {
210 DecodeError::Frame(value)
211 }
212}
213impl From<crate::bool_decoder::BoolDecoderError> for DecodeError {
214 fn from(value: crate::bool_decoder::BoolDecoderError) -> Self {
215 // Surface a bool-decoder mishap during interframe macroblock-header
216 // reads as a macroblock error (the §19.3 prefix is part of the
217 // macroblock layer).
218 DecodeError::Macroblock(MacroblockError::from(value))
219 }
220}
221impl From<crate::near_mv::InterMbError> for DecodeError {
222 fn from(value: crate::near_mv::InterMbError) -> Self {
223 match value {
224 crate::near_mv::InterMbError::BoolDecoder(inner) => {
225 DecodeError::Macroblock(MacroblockError::from(inner))
226 }
227 crate::near_mv::InterMbError::SplitNotSupported { .. } => DecodeError::Unsupported(
228 "vp8 interframe: SPLITMV reconstruction path tripped an internal mis-dispatch",
229 ),
230 }
231 }
232}
233
234/// Fully-decoded, loop-filtered VP8 key-frame in I420 layout.
235///
236/// `y`/`u`/`v` are the visible-cropped planes — the §9.1 width / height
237/// from the key-frame header, rounded for chroma sub-sampling
238/// (`uv_width = (width + 1) / 2`, `uv_height = (height + 1) / 2`). Decode
239/// pads internally to whole macroblocks; the §15 loop filter runs against
240/// that padded buffer, then this output is cropped to the visible area.
241#[derive(Debug, Clone, Default, PartialEq, Eq)]
242pub struct Vp8DecodedFrame {
243 /// Visible width in luma pixels (the §9.1 key-frame `width`).
244 pub width: u32,
245 /// Visible height in luma pixels (the §9.1 key-frame `height`).
246 pub height: u32,
247 /// Luma plane — `width * height` bytes, row-major (stride == width).
248 pub y: Vec<u8>,
249 /// U chroma plane — `((width+1)/2) * ((height+1)/2)` bytes.
250 pub u: Vec<u8>,
251 /// V chroma plane — same dimensions as `u`.
252 pub v: Vec<u8>,
253}
254
255impl Vp8DecodedFrame {
256 /// Set `width`.
257 #[must_use]
258 pub fn with_width(mut self, v: u32) -> Self {
259 self.width = v;
260 self
261 }
262
263 /// Set `height`.
264 #[must_use]
265 pub fn with_height(mut self, v: u32) -> Self {
266 self.height = v;
267 self
268 }
269
270 /// Set `y`.
271 #[must_use]
272 pub fn with_y(mut self, v: Vec<u8>) -> Self {
273 self.y = v;
274 self
275 }
276
277 /// Set `u`.
278 #[must_use]
279 pub fn with_u(mut self, v: Vec<u8>) -> Self {
280 self.u = v;
281 self
282 }
283
284 /// Set `v`.
285 #[must_use]
286 pub fn with_v(mut self, v: Vec<u8>) -> Self {
287 self.v = v;
288 self
289 }
290}
291
292/// Decode one VP8 frame end-to-end and emit the reconstructed I420 picture.
293///
294/// `bytes` must hold exactly one VP8 elementary-stream frame (the bytes a
295/// container demuxer hands the decoder for one sample / packet). The
296/// function is stateless — no reference-frame carry-over, no probability
297/// persistence — so it can only handle **key frames**. Interframes return
298/// [`DecodeError::Unsupported`].
299///
300/// See the module docstring for the partition-layout walk this function
301/// follows. Production-grade users should prefer [`Vp8Decoder`] (gated on
302/// the `registry` feature), which wraps this entry point in the
303/// [`oxideav_core::Decoder`] trait.
304pub fn decode_vp8(bytes: &[u8]) -> Result<Vp8DecodedFrame, DecodeError> {
305 decode_vp8_with_max_pixels(bytes, DEFAULT_MAX_PIXELS_PER_FRAME)
306}
307
308/// Controls for a one-shot key-frame decode
309/// ([`decode_vp8_with_options`]).
310///
311/// `Default` is [`decode_vp8`]: serial, [`DEFAULT_MAX_PIXELS_PER_FRAME`].
312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
313#[non_exhaustive]
314pub struct Vp8DecodeOptions {
315 /// Thread budget. `0` and `1` both mean serial (the default); with
316 /// `n > 1` token rows, reconstruction rows and the loop filter run
317 /// on up to `n` scoped threads that end with the call. The picture
318 /// is the same at every budget.
319 pub threads: usize,
320 /// Reject a declared `width × height` above this before any
321 /// allocation (see [`decode_vp8_with_max_pixels`]).
322 pub max_pixels_per_frame: u64,
323}
324
325impl Default for Vp8DecodeOptions {
326 fn default() -> Self {
327 Vp8DecodeOptions {
328 threads: 0,
329 max_pixels_per_frame: DEFAULT_MAX_PIXELS_PER_FRAME,
330 }
331 }
332}
333
334impl Vp8DecodeOptions {
335 /// The defaults: serial, [`DEFAULT_MAX_PIXELS_PER_FRAME`].
336 pub fn new() -> Self {
337 Self::default()
338 }
339
340 /// Set `threads`.
341 #[must_use]
342 pub fn with_threads(mut self, v: usize) -> Self {
343 self.threads = v;
344 self
345 }
346
347 /// Set `max_pixels_per_frame`.
348 #[must_use]
349 pub fn with_max_pixels_per_frame(mut self, v: u64) -> Self {
350 self.max_pixels_per_frame = v;
351 self
352 }
353}
354
355/// Decode one VP8 key frame under [`Vp8DecodeOptions`] — [`decode_vp8`]
356/// with a caller-granted thread budget and pixel cap. This is the entry
357/// point for a still-picture container that wants its decode to follow
358/// the caller's thread budget.
359///
360/// The picture is bit-identical to [`decode_vp8`]'s at every budget.
361/// Like `decode_vp8` it is stateless and decodes key frames only. It
362/// works a macroblock row at a time — a row's coefficients are decoded,
363/// reconstructed and dropped — where `decode_vp8` holds the dequantised
364/// coefficients of the whole frame (800 bytes per macroblock, 38 MiB
365/// for a 12-megapixel picture) until reconstruction is over; the serial
366/// speed of the two is the same.
367///
368/// ```
369/// use oxideav_vp8::{Vp8DecodeOptions, decode_vp8, decode_vp8_with_options};
370/// # use oxideav_vp8::{I420Frame, KeyframeParams, encode_keyframe};
371/// # let (w, h) = (64u32, 48u32);
372/// # let y: Vec<u8> = (0..w * h).map(|i| (i * 5 % 253) as u8).collect();
373/// # let c = vec![128u8; ((w / 2) * (h / 2)) as usize];
374/// # let vp8_keyframe_bytes =
375/// # encode_keyframe(&I420Frame::packed(w, h, &y, &c, &c), &KeyframeParams::default())?;
376/// let options = Vp8DecodeOptions::new().with_threads(4);
377/// let picture = decode_vp8_with_options(&vp8_keyframe_bytes, &options)?;
378/// assert_eq!(picture, decode_vp8(&vp8_keyframe_bytes)?);
379/// # Ok::<(), Box<dyn std::error::Error>>(())
380/// ```
381pub fn decode_vp8_with_options(
382 bytes: &[u8],
383 options: &Vp8DecodeOptions,
384) -> Result<Vp8DecodedFrame, DecodeError> {
385 let header = Vp8FrameHeader::parse(bytes)?;
386 if !header.key_frame {
387 return Err(DecodeError::Unsupported(
388 "VP8 inter-frame (§16) decoding needs the carried state of \
389 `Vp8DecoderState` — this entry point decodes key frames only",
390 ));
391 }
392 crate::state::Vp8DecoderState::new()
393 .with_max_pixels_per_frame(options.max_pixels_per_frame)
394 .with_threads(options.threads)
395 .decode_frame(bytes)
396}
397
398/// Decode one VP8 key frame, rejecting a declared `width × height` larger
399/// than `max_pixels_per_frame` before any allocation.
400///
401/// Identical to [`decode_vp8`] except the pixel cap is caller-chosen rather
402/// than [`DEFAULT_MAX_PIXELS_PER_FRAME`]. Callers processing untrusted input
403/// (e.g. a server decoding uploads) pass a tight cap so a malformed header
404/// declaring an enormous frame returns [`DecodeError::FrameTooLarge`]
405/// instead of driving a multi-hundred-megabyte plane allocation. The check
406/// fires immediately after the §9.1 size words are parsed and before the
407/// first macroblock-grid `Vec` is reserved.
408pub fn decode_vp8_with_max_pixels(
409 bytes: &[u8],
410 max_pixels_per_frame: u64,
411) -> Result<Vp8DecodedFrame, DecodeError> {
412 let header = Vp8FrameHeader::parse(bytes)?;
413 if !header.key_frame {
414 return Err(DecodeError::Unsupported(
415 "VP8 inter-frame (§16) decoding is not implemented yet — \
416 only key frames are supported in this build",
417 ));
418 }
419
420 // §9.1: width and height live on the key-frame header (Some) and are
421 // both 14 bits; reject zero up-front so the macroblock math below sees
422 // a non-degenerate frame.
423 let width = header.width.unwrap_or(0) as u32;
424 let height = header.height.unwrap_or(0) as u32;
425 if width == 0 || height == 0 {
426 return Err(DecodeError::ZeroDimension);
427 }
428
429 // DoS guard: refuse a declared frame larger than the configured cap
430 // *before* the first grid allocation (`parse_key_frame_macroblock_modes`
431 // reserves `mb_rows * mb_cols` entries a few lines below).
432 check_pixel_cap(width, height, max_pixels_per_frame)?;
433
434 // §4 / §9.1: macroblock dimensions round up to whole 16-pixel blocks.
435 let mb_cols = width.div_ceil(16) as usize;
436 let mb_rows = height.div_ceil(16) as usize;
437
438 // ---- Carve out the first (control) partition ---------------------
439 let first_part_offset = header.header_bytes_consumed;
440 let first_part_size = header.first_partition_size as usize;
441 let available_after_hdr = bytes.len().saturating_sub(first_part_offset);
442 if first_part_size > available_after_hdr {
443 return Err(DecodeError::TruncatedFirstPartition {
444 available: available_after_hdr,
445 declared: first_part_size,
446 });
447 }
448 let first_partition = &bytes[first_part_offset..first_part_offset + first_part_size];
449
450 // ---- §19.2 boolean-coded frame header + §11 macroblock layer -----
451 let (coded, mut dec) = Vp8CodedHeader::parse_with_decoder(first_partition, true)?;
452 let modes = parse_key_frame_macroblock_modes(&mut dec, &coded, mb_rows, mb_cols)?;
453 debug_assert_eq!(modes.len(), mb_rows * mb_cols);
454
455 // ---- §9.5 DCT-partition table ------------------------------------
456 // The DCT partitions begin immediately after the first partition,
457 // preceded by (nbr_of_dct_partitions - 1) 3-byte LE size words.
458 let dct_section_offset = first_part_offset + first_part_size;
459 let dct_section = &bytes[dct_section_offset..];
460 let num_partitions = coded.nbr_of_dct_partitions as usize;
461 let partitions = carve_dct_partitions(dct_section, num_partitions)?;
462
463 // ---- §14.1 per-segment dequant factors ---------------------------
464 // Resolve the four segment slots up front. With segmentation off the
465 // four entries collapse to the same factor set and the per-MB
466 // `segment_id` is `None` (treated as segment 0).
467 let dequant_factors = resolve_segment_dequant_factors(&coded);
468
469 // ---- §13 token probability table ---------------------------------
470 let coeff_probs: CoeffProbs = merge_default_token_probs(&coded.token_prob_updates);
471
472 // ---- Per-row residual decode -------------------------------------
473 let coeffs = decode_residuals(
474 &coded,
475 &modes,
476 &partitions,
477 &coeff_probs,
478 &dequant_factors,
479 mb_rows,
480 mb_cols,
481 )?;
482
483 // ---- §12 / §14.2 reconstruction ----------------------------------
484 let mut planes = decode_keyframe(mb_cols, mb_rows, &modes, &coeffs)?;
485
486 // ---- §15.1 loop-filter post-pass ---------------------------------
487 let lf_config = FrameFilterConfig::keyframe(&coded);
488 if lf_config.loop_filter_level != 0 {
489 filter_frame(&mut planes, &modes, &coeffs, &lf_config);
490 }
491
492 // ---- §9.1 crop to visible width / height -------------------------
493 Ok(crop_to_visible(&planes, width, height))
494}
495
496/// Carve the DCT-partition section into a `Vec` of byte slices.
497///
498/// Layout per RFC 6386 §9.5: the first `(num_partitions - 1) * 3` bytes
499/// are 3-byte little-endian size words, then the partitions follow
500/// concatenated. The last partition's length is implied by what is left.
501/// `num_partitions == 1` skips the size table entirely.
502pub(crate) fn carve_dct_partitions(
503 section: &[u8],
504 num_partitions: usize,
505) -> Result<Vec<&[u8]>, DecodeError> {
506 debug_assert!((1..=8).contains(&num_partitions));
507 let table_len = (num_partitions - 1) * 3;
508 if section.len() < table_len {
509 return Err(DecodeError::TruncatedPartitionSizes);
510 }
511 let (sizes_bytes, body) = section.split_at(table_len);
512
513 let mut sizes: Vec<usize> = Vec::with_capacity(num_partitions);
514 for i in 0..(num_partitions - 1) {
515 let off = i * 3;
516 let sz = (sizes_bytes[off] as usize)
517 | ((sizes_bytes[off + 1] as usize) << 8)
518 | ((sizes_bytes[off + 2] as usize) << 16);
519 sizes.push(sz);
520 }
521 // Last partition's size: the remaining bytes.
522 let consumed: usize = sizes.iter().sum();
523 if consumed > body.len() {
524 // One of the prefix sizes already overshot the available data.
525 // Surface the offending one rather than the last (computed) slot.
526 for (i, &sz) in sizes.iter().enumerate() {
527 let off: usize = sizes.iter().take(i).sum();
528 if off + sz > body.len() {
529 return Err(DecodeError::TruncatedDctPartition {
530 index: i,
531 available: body.len().saturating_sub(off),
532 declared: sz,
533 });
534 }
535 }
536 }
537 sizes.push(body.len() - consumed);
538
539 let mut out: Vec<&[u8]> = Vec::with_capacity(num_partitions);
540 let mut cursor = 0usize;
541 for (i, &sz) in sizes.iter().enumerate() {
542 let end = cursor + sz;
543 if end > body.len() {
544 return Err(DecodeError::TruncatedDctPartition {
545 index: i,
546 available: body.len().saturating_sub(cursor),
547 declared: sz,
548 });
549 }
550 out.push(&body[cursor..end]);
551 cursor = end;
552 }
553 Ok(out)
554}
555
556/// Build the four per-segment [`MbDequantFactors`] for the frame, applying
557/// the §10 `quantizer_update` segment override (delta or absolute) on top
558/// of the §9.6 frame baseline.
559///
560/// When segmentation is disabled (the common case for the simplest key
561/// frames) every slot resolves to the frame-level
562/// [`MbDequantFactors::from_quant_indices`] result, so the per-MB lookup
563/// always lands on the correct factors regardless of how the caller's
564/// `segment_id` happens to be populated.
565fn resolve_segment_dequant_factors(coded: &Vp8CodedHeader) -> [MbDequantFactors; MAX_MB_SEGMENTS] {
566 let base = MbDequantFactors::from_quant_indices(&coded.quant_indices);
567 let mut out = [base; MAX_MB_SEGMENTS];
568 if coded.segmentation_enabled
569 && let Some(seg) = coded.update_segmentation
570 {
571 for (i, slot) in out.iter_mut().enumerate() {
572 let qval = seg.quantizer_update[i].unwrap_or(0) as i32;
573 *slot = MbDequantFactors::for_segment(
574 &coded.quant_indices,
575 qval,
576 seg.segment_feature_mode_absolute,
577 );
578 }
579 }
580 out
581}
582
583/// Decode the §13 residual coefficients for every macroblock, threading the
584/// above / left non-zero predictor contexts per the §13.3 rules and routing
585/// each row's reads to the correct DCT partition per the §9.5 / §20.4
586/// round-robin row striping.
587fn decode_residuals(
588 coded: &Vp8CodedHeader,
589 modes: &[MacroblockModes],
590 partitions: &[&[u8]],
591 coeff_probs: &CoeffProbs,
592 dequant_factors: &[MbDequantFactors; MAX_MB_SEGMENTS],
593 mb_rows: usize,
594 mb_cols: usize,
595) -> Result<Vec<MbCoeffs>, DecodeError> {
596 let num_partitions = partitions.len();
597 debug_assert!(num_partitions >= 1);
598
599 // §13: every macroblock is decoded exactly once, in raster order
600 // (`mb_row` outer, `mb_col` inner), and its coefficients appended.
601 // Reserve the frame's slots and `push` per MB rather than `resize`-ing
602 // to `default()` first: each slot is overwritten before it is read, so
603 // the bulk default-zeroing (800 bytes per `MbCoeffs`) was dead work.
604 let mut coeffs: Vec<MbCoeffs> = Vec::with_capacity(mb_rows * mb_cols);
605
606 // One above-context per macroblock column, lives for the whole frame.
607 let mut above: Vec<MbEntropyCtx> = vec![MbEntropyCtx::default(); mb_cols];
608
609 // One bool-decoder per DCT partition that is actually consumed, with
610 // the cursor persisting across rows that share a partition (the §20.4
611 // round-robin rule). Partitions that no row routes to — e.g. the
612 // 1-byte padding partitions of a 16×16 / 4-partition frame, where only
613 // partition 0 is ever read — are left `None` and never initialised.
614 // Consumed partitions use the tolerant §20.2 `init_bool_decoder` form
615 // ([`BoolDecoder::init_partition`]): a DCT partition that rounds down
616 // to a 0- or 1-byte slice is spec-legal (`sz < 2` → zero-initialised
617 // value register, empty input) and must decode, matching the
618 // stateful keyframe path in `state::decode_intra_residuals`. The
619 // round-284 `decode_stream_token_descent` fuzz target's
620 // cross-entry-point differential caught this path still using the
621 // strict control-partition `init` and rejecting such frames with
622 // `InputTooShort`.
623 let mut partition_decoders: Vec<Option<BoolDecoder<'_>>> =
624 (0..num_partitions).map(|_| None).collect();
625 for mb_row in 0..mb_rows {
626 let part_idx = mb_row % num_partitions;
627 if partition_decoders[part_idx].is_none() {
628 partition_decoders[part_idx] = Some(BoolDecoder::init_partition(partitions[part_idx]));
629 }
630 }
631
632 for mb_row in 0..mb_rows {
633 // §13.3 page 65: the "left" non-zero predictor context resets at
634 // the start of every macroblock row.
635 let mut left = MbEntropyCtx::default();
636 let part_idx = mb_row % num_partitions;
637 let dec = partition_decoders[part_idx]
638 .as_mut()
639 .expect("partition decoder initialised above for every consumed partition");
640
641 for (mb_col, above_ctx) in above.iter_mut().enumerate() {
642 let raster = mb_row * mb_cols + mb_col;
643 let mb = &modes[raster];
644 let has_y2 = mb.y_mode != IntraYMode::B;
645 // §10: a macroblock with no `segment_id` defaults to segment 0
646 // (the §10 default before the map is ever updated). When
647 // segmentation is off, all four segment factors are identical
648 // anyway, so the unwrap_or here cannot mis-route.
649 let seg = mb.segment_id.unwrap_or(0) as usize;
650 let seg = seg.min(MAX_MB_SEGMENTS - 1);
651 let factors = &dequant_factors[seg];
652
653 let mb_coeffs = decode_and_dequantize_mb(
654 dec,
655 has_y2,
656 mb.mb_skip_coeff,
657 coeff_probs,
658 factors,
659 above_ctx,
660 &mut left,
661 )
662 .map_err(|source| DecodeError::MbCoeffs {
663 index: raster,
664 source,
665 })?;
666 debug_assert_eq!(coeffs.len(), raster, "coeffs pushed in raster order");
667 coeffs.push(mb_coeffs);
668 }
669 }
670
671 // `coded` is informational at this layer (the per-MB walk above is
672 // entirely self-contained), but keep the reference to make the
673 // signature unambiguous about what header state drives the loop and to
674 // future-proof for the §16 interframe extension (which will need
675 // `coded.prob_intra` etc here).
676 let _ = coded;
677
678 Ok(coeffs)
679}
680
681/// Public-in-crate alias of [`crop_to_visible`] for the multi-frame driver.
682pub(crate) fn crop_to_visible_public(
683 planes: &KeyframePlanes,
684 width: u32,
685 height: u32,
686) -> Vp8DecodedFrame {
687 crop_to_visible(planes, width, height)
688}
689
690/// Crop the §14.2 reconstructed plane buffers (sized to whole macroblocks)
691/// to the §9.1 visible width / height and return a packed I420 frame.
692fn crop_to_visible(planes: &KeyframePlanes, width: u32, height: u32) -> Vp8DecodedFrame {
693 let w = width as usize;
694 let h = height as usize;
695 let uvw = w.div_ceil(2);
696 let uvh = h.div_ceil(2);
697
698 // When the visible width equals the macroblock-padded stride there is no
699 // per-row gap to skip, so the whole leading `w * h` region of the source
700 // plane is already the packed output verbatim — one contiguous copy
701 // instead of `h` row-sliced `extend_from_slice` calls. This is the common
702 // case for macroblock-aligned dimensions (e.g. 128×128, 16-multiples). The
703 // strided path below produces the identical packed bytes when a gap exists.
704 let y = if w == planes.y_stride {
705 planes.y[..w * h].to_vec()
706 } else {
707 let mut y = Vec::with_capacity(w * h);
708 for r in 0..h {
709 let src = r * planes.y_stride;
710 y.extend_from_slice(&planes.y[src..src + w]);
711 }
712 y
713 };
714
715 let (u, v) = if uvw == planes.uv_stride {
716 (
717 planes.u[..uvw * uvh].to_vec(),
718 planes.v[..uvw * uvh].to_vec(),
719 )
720 } else {
721 let mut u = Vec::with_capacity(uvw * uvh);
722 let mut v = Vec::with_capacity(uvw * uvh);
723 for r in 0..uvh {
724 let src = r * planes.uv_stride;
725 u.extend_from_slice(&planes.u[src..src + uvw]);
726 v.extend_from_slice(&planes.v[src..src + uvw]);
727 }
728 (u, v)
729 };
730
731 Vp8DecodedFrame {
732 width,
733 height,
734 y,
735 u,
736 v,
737 }
738}
739
740// ─────────────────── oxideav_core::Decoder integration ───────────────────
741
742#[cfg(feature = "registry")]
743mod registry {
744 use std::collections::VecDeque;
745
746 use oxideav_core::frame::VideoPlane;
747 use oxideav_core::{
748 CodecCapabilities, CodecId, CodecInfo, CodecParameters, CodecRegistry, CodecTag,
749 ColorSignal, Decoder, DecoderLimits, Error, Frame, MatrixCoefficients, Packet, PixelFormat,
750 Result, RuntimeContext, VideoFrame,
751 };
752
753 use super::{DecodeError, Vp8DecodedFrame};
754
755 /// Canonical codec id under which this decoder registers. Matches the
756 /// long-standing `oxideav-vp9` / `oxideav-av1` naming convention.
757 pub const VP8_CODEC_ID: &str = "vp8";
758
759 impl From<DecodeError> for Error {
760 fn from(value: DecodeError) -> Self {
761 match value {
762 DecodeError::Unsupported(msg) => Error::unsupported(msg),
763 // A tripped pixel cap is a DoS-guard rejection, not a
764 // malformed stream — surface it as the framework's
765 // resource-exhaustion error so callers can distinguish it.
766 DecodeError::FrameTooLarge { .. } => Error::resource_exhausted(value.to_string()),
767 DecodeError::FrameHeader(_)
768 | DecodeError::CodedHeader(_)
769 | DecodeError::Macroblock(_)
770 | DecodeError::MbCoeffs { .. }
771 | DecodeError::Frame(_)
772 | DecodeError::TruncatedFirstPartition { .. }
773 | DecodeError::TruncatedPartitionSizes
774 | DecodeError::TruncatedDctPartition { .. }
775 | DecodeError::ZeroDimension => Error::invalid(value.to_string()),
776 }
777 }
778 }
779
780 impl From<Vp8DecodedFrame> for VideoFrame {
781 fn from(f: Vp8DecodedFrame) -> Self {
782 let uv_stride = (f.width as usize).div_ceil(2);
783 VideoFrame {
784 pts: None,
785 planes: vec![
786 VideoPlane {
787 stride: f.width as usize,
788 data: f.y,
789 },
790 VideoPlane {
791 stride: uv_stride,
792 data: f.u,
793 },
794 VideoPlane {
795 stride: uv_stride,
796 data: f.v,
797 },
798 ],
799 }
800 }
801 }
802
803 /// `oxideav_core::Decoder` impl driving [`Vp8DecoderState`].
804 ///
805 /// Each `send_packet` queues one compressed packet; `receive_frame`
806 /// consumes queued packets and feeds them to
807 /// [`Vp8DecoderState::decode_frame`], which threads reference frames
808 /// and entropy carry-state across calls. Both key frames and
809 /// interframes decode end-to-end; the only `DecodeError::Unsupported`
810 /// returned now is "interframe arrived before any key frame" (a
811 /// stream-mis-feed error, not a missing feature).
812 ///
813 /// ## Invisible frames
814 ///
815 /// A frame whose §9.1 `show_frame` bit is 0 is "not for display": it
816 /// is decoded (its §9.7 / §9.8 reference-slot side effects apply) but
817 /// no picture is returned for it — `receive_frame` moves on to the
818 /// next queued packet, and answers [`Error::NeedMore`] when that was
819 /// the last one. Only shown pictures reach the caller.
820 ///
821 /// ## Stream parameters
822 ///
823 /// [`Decoder::output_params`] answers the resolved description of
824 /// the pictures this decoder returns: the §9.1 visible `width` /
825 /// `height` (the cropped size of the emitted planes, not the
826 /// macroblock-aligned one), [`PixelFormat::Yuv420P`], and the §9.2
827 /// `color_space` as the colour signal's matrix. Before the first
828 /// picture it answers from the key frame already decoded, else from
829 /// the first queued key frame's headers.
830 ///
831 /// Only a key frame can change that description (§9.1 / §9.2 are
832 /// key-frame-only fields). When the first **shown** picture of a new
833 /// description is about to be returned, the decoder bumps
834 /// [`Decoder::output_params_generation`] and returns one
835 /// [`Frame::StreamParams`] event carrying the new `output_params()`
836 /// first; the picture follows on the next call. No event is
837 /// returned for the first description, for a key frame that repeats
838 /// the current one, or for an invisible key frame (the event waits
839 /// for the first shown picture of the new size). [`Decoder::reset`]
840 /// keeps the description of the last picture returned, so a seek
841 /// into a segment of a different size announces it the same way.
842 ///
843 /// The §9.1 upscale codes and the §9.2 `clamping_type` bit do not
844 /// change the emitted planes and are not part of the description;
845 /// [`Vp8Decoder::upscale`] / [`Vp8Decoder::clamping_type`] expose
846 /// them.
847 ///
848 /// The decoder runs serially; it keeps the default no-op
849 /// [`Decoder::set_execution_context`].
850 ///
851 /// [`Vp8DecoderState::decode_frame`]: crate::state::Vp8DecoderState::decode_frame
852 pub struct Vp8Decoder {
853 codec_id: CodecId,
854 pending: VecDeque<Packet>,
855 eof: bool,
856 state: crate::state::Vp8DecoderState,
857 /// Description of the picture most recently returned (`None`
858 /// until the first one).
859 shape: Option<OutputShape>,
860 /// [`Decoder::output_params_generation`] counter: bumped once per
861 /// mid-stream change of `shape`.
862 generation: u64,
863 /// The first picture of a new shape, held back behind the
864 /// [`Frame::StreamParams`] event just returned for it.
865 held: Option<VideoFrame>,
866 }
867
868 /// The part of the decoder's output that [`Decoder::output_params`]
869 /// describes.
870 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
871 struct OutputShape {
872 width: u32,
873 height: u32,
874 /// §9.2 `color_space` bit (`false` = BT.601-like YUV).
875 color_space_reserved: bool,
876 }
877
878 impl OutputShape {
879 /// §9.2 `color_space` → colour signal. Value 0 is "YUV color
880 /// space similar to the YCrCb color space defined in
881 /// [ITU-R_BT.601]": the BT.601 luma / chroma matrix (H.273
882 /// matrix code points 5 and 6 are the same matrix; 6 is used).
883 /// §9.2 states no primaries, transfer or nominal range, so those
884 /// stay unspecified; value 1 is reserved and states nothing.
885 fn color_signal(self) -> ColorSignal {
886 let mut signal = ColorSignal::unspecified();
887 if !self.color_space_reserved {
888 signal.matrix = MatrixCoefficients::BT601_525;
889 }
890 signal
891 }
892
893 fn to_params(self, codec_id: &CodecId) -> CodecParameters {
894 let mut p = CodecParameters::video(codec_id.clone());
895 p.width = Some(self.width);
896 p.height = Some(self.height);
897 p.pixel_format = Some(PixelFormat::Yuv420P);
898 p.color_signal = self.color_signal();
899 p
900 }
901
902 /// The shape the state's most recent key frame installed.
903 fn from_state(state: &crate::state::Vp8DecoderState) -> Option<Self> {
904 Some(Self {
905 width: state.visible_width()?,
906 height: state.visible_height()?,
907 color_space_reserved: state.color_space()?,
908 })
909 }
910
911 /// Read the shape straight off a key frame's §9.1 uncompressed
912 /// header and the first bit of its §9.2 / §19.2 first partition,
913 /// without decoding it. `None` for an interframe or a header
914 /// that does not parse.
915 fn peek_key_frame(bytes: &[u8]) -> Option<Self> {
916 let header = crate::frame_header::Vp8FrameHeader::parse(bytes).ok()?;
917 if !header.key_frame {
918 return None;
919 }
920 let width = u32::from(header.width?);
921 let height = u32::from(header.height?);
922 if width == 0 || height == 0 {
923 return None;
924 }
925 let first = bytes.get(header.header_bytes_consumed..)?;
926 let first = &first[..first.len().min(header.first_partition_size as usize)];
927 let mut bd = crate::bool_decoder::BoolDecoder::init(first).ok()?;
928 let color_space_reserved = bd.read_literal(1).ok()? != 0;
929 Some(Self {
930 width,
931 height,
932 color_space_reserved,
933 })
934 }
935 }
936
937 impl Vp8Decoder {
938 /// Build a fresh decoder bound to the supplied codec id. The id is
939 /// reported verbatim by [`Decoder::codec_id`]. The internal
940 /// [`Vp8DecoderState`] starts empty — the first packet fed to
941 /// `send_packet` / `receive_frame` must be a key frame.
942 ///
943 /// [`Vp8DecoderState`]: crate::state::Vp8DecoderState
944 pub fn new(codec_id: CodecId) -> Self {
945 Self::with_state(codec_id, crate::state::Vp8DecoderState::new())
946 }
947
948 /// Build a decoder that enforces `limits.max_pixels_per_frame` as
949 /// the §9.1 declared-frame-size cap. Any key frame whose declared
950 /// `width × height` exceeds the cap is refused with
951 /// [`Error::ResourceExhausted`] before the decoder allocates its
952 /// macroblock grid. Constructed by [`make_decoder`] from the
953 /// [`CodecParameters::limits`](oxideav_core::CodecParameters) the
954 /// registry threads in. The cap survives [`Decoder::reset`].
955 pub fn with_limits(codec_id: CodecId, limits: DecoderLimits) -> Self {
956 Self::with_state(
957 codec_id,
958 crate::state::Vp8DecoderState::new()
959 .with_max_pixels_per_frame(limits.max_pixels_per_frame),
960 )
961 }
962
963 fn with_state(codec_id: CodecId, state: crate::state::Vp8DecoderState) -> Self {
964 Self {
965 codec_id,
966 pending: VecDeque::new(),
967 eof: false,
968 state,
969 shape: None,
970 generation: 0,
971 held: None,
972 }
973 }
974
975 /// §9.1 `(horizontal_scale, vertical_scale)` upscale codes of the
976 /// most recently decoded key frame — a display hint that does not
977 /// change the emitted planes. `None` before any key frame.
978 pub fn upscale(
979 &self,
980 ) -> Option<(
981 crate::frame_header::ScaleCode,
982 crate::frame_header::ScaleCode,
983 )> {
984 self.state.upscale()
985 }
986
987 /// §9.2 `clamping_type` bit of the most recently decoded key
988 /// frame (`Some(true)` = the encoder guarantees in-range pixels).
989 /// `None` before any key frame.
990 pub fn clamping_type(&self) -> Option<bool> {
991 self.state.clamping_type()
992 }
993 }
994
995 impl std::fmt::Debug for Vp8Decoder {
996 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
997 f.debug_struct("Vp8Decoder")
998 .field("codec_id", &self.codec_id)
999 .field("pending", &self.pending.len())
1000 .field("eof", &self.eof)
1001 .field("shape", &self.shape)
1002 .field("generation", &self.generation)
1003 .finish()
1004 }
1005 }
1006
1007 impl Decoder for Vp8Decoder {
1008 fn codec_id(&self) -> &CodecId {
1009 &self.codec_id
1010 }
1011
1012 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
1013 self.pending.push_back(packet.clone());
1014 Ok(())
1015 }
1016
1017 /// Take the thread budget for each frame's decode from the
1018 /// framework (serial unless one is announced). The pictures do
1019 /// not depend on it.
1020 fn set_execution_context(&mut self, ctx: &oxideav_core::ExecutionContext) {
1021 self.state.set_threads(ctx.threads);
1022 }
1023
1024 fn receive_frame(&mut self) -> Result<Frame> {
1025 if let Some(vf) = self.held.take() {
1026 return Ok(Frame::Video(vf));
1027 }
1028 loop {
1029 let Some(pkt) = self.pending.pop_front() else {
1030 return if self.eof {
1031 Err(Error::Eof)
1032 } else {
1033 Err(Error::NeedMore)
1034 };
1035 };
1036 let decoded = self.state.decode_frame(&pkt.data)?;
1037 if self.state.last_frame_shown() == Some(false) {
1038 // §9.1 show_frame = 0: reference-only, not for display.
1039 continue;
1040 }
1041 let shape = OutputShape::from_state(&self.state)
1042 .expect("a decoded frame implies a decoded key frame");
1043 let mut vf: VideoFrame = decoded.into();
1044 vf.pts = pkt.pts;
1045 return match self.shape {
1046 Some(current) if current != shape => {
1047 self.shape = Some(shape);
1048 self.generation = self.generation.wrapping_add(1);
1049 self.held = Some(vf);
1050 Ok(Frame::StreamParams(Box::new(
1051 shape.to_params(&self.codec_id),
1052 )))
1053 }
1054 _ => {
1055 self.shape = Some(shape);
1056 Ok(Frame::Video(vf))
1057 }
1058 };
1059 }
1060 }
1061
1062 fn flush(&mut self) -> Result<()> {
1063 self.eof = true;
1064 Ok(())
1065 }
1066
1067 fn reset(&mut self) -> Result<()> {
1068 self.pending.clear();
1069 self.held = None;
1070 self.eof = false;
1071 let cap = self.state.max_pixels_per_frame();
1072 let threads = self.state.threads();
1073 self.state = crate::state::Vp8DecoderState::new()
1074 .with_max_pixels_per_frame(cap)
1075 .with_threads(threads);
1076 // `shape` / `generation` are kept: the next picture is
1077 // compared against the last one returned before the reset.
1078 Ok(())
1079 }
1080
1081 fn output_pixel_format(&self) -> Option<PixelFormat> {
1082 self.output_params().and_then(|p| p.pixel_format)
1083 }
1084
1085 fn output_params(&self) -> Option<CodecParameters> {
1086 // The last picture returned; before the first one, the key
1087 // frame already decoded (an invisible one returns no picture),
1088 // else the first queued key frame's headers.
1089 let shape = self
1090 .shape
1091 .or_else(|| OutputShape::from_state(&self.state))
1092 .or_else(|| {
1093 self.pending
1094 .iter()
1095 .find_map(|p| OutputShape::peek_key_frame(&p.data))
1096 })?;
1097 Some(shape.to_params(&self.codec_id))
1098 }
1099
1100 fn output_params_generation(&self) -> u64 {
1101 self.generation
1102 }
1103 }
1104
1105 /// `make_decoder` factory plugged into the registry. Required by the
1106 /// `DecoderFactory` function-pointer type.
1107 pub fn make_decoder(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
1108 // Thread the caller's DoS caps into the decoder so a tightened
1109 // `max_pixels_per_frame` is enforced on every key frame.
1110 Ok(Box::new(Vp8Decoder::with_limits(
1111 params.codec_id.clone(),
1112 params.limits,
1113 )))
1114 }
1115
1116 /// Register the VP8 codec into the supplied [`CodecRegistry`] under the
1117 /// canonical [`VP8_CODEC_ID`] codec id, with the container tags VP8
1118 /// commonly carries (Matroska / WebM `V_VP8`, MP4 / ISOBMFF `vp08`,
1119 /// IVF / RIFF `VP80` FourCC).
1120 pub fn register_codecs(reg: &mut CodecRegistry) {
1121 let caps = CodecCapabilities::video(VP8_CODEC_ID)
1122 .with_lossy(true)
1123 .with_max_size(16384, 16384);
1124 reg.register(
1125 CodecInfo::new(CodecId::new(VP8_CODEC_ID))
1126 .capabilities(caps)
1127 .decoder(make_decoder)
1128 .encoder(crate::encoder::make_encoder_from_param_options)
1129 .encoder_options::<crate::encoder::Vp8EncoderOptions>()
1130 .tags([
1131 CodecTag::fourcc(b"VP80"),
1132 CodecTag::fourcc(b"vp08"),
1133 CodecTag::matroska("V_VP8"),
1134 ]),
1135 );
1136 }
1137
1138 /// Unified entry point — installs the VP8 codec into a
1139 /// [`RuntimeContext`]. Called by `oxideav-meta` via the
1140 /// [`oxideav_core::register!`] hook in `lib.rs`.
1141 pub fn register(ctx: &mut RuntimeContext) {
1142 register_codecs(&mut ctx.codecs);
1143 }
1144
1145 /// Helper that the public reflection / fallback path inspects: returns
1146 /// the pixel format the decoder produces (always I420 in this build).
1147 pub fn output_pixel_format() -> PixelFormat {
1148 PixelFormat::Yuv420P
1149 }
1150}
1151
1152#[cfg(feature = "registry")]
1153pub use registry::{
1154 VP8_CODEC_ID, Vp8Decoder, make_decoder, output_pixel_format, register, register_codecs,
1155};
1156
1157// ───────────────────────────── tests ────────────────────────────────
1158
1159#[cfg(test)]
1160mod tests {
1161 use super::*;
1162
1163 /// Strip the 32-byte DKIF header and one 12-byte IVF frame header off
1164 /// the front of an IVF file and return the contained VP8 elementary
1165 /// frame bytes. This is **not** a container parser — it knows just
1166 /// enough about the IVF wrapper to lift a single VP8 frame out of a
1167 /// fixture so the codec test stays self-contained per the workspace
1168 /// "no cross-crate dev-deps" rule. The IVF wrapper is a 32-byte DKIF
1169 /// header (`'DKIF'` magic + version + header_len + FourCC + width +
1170 /// height + fps + scale + frame_count + reserved) followed by one or
1171 /// more 12-byte frame headers (4-byte LE frame size + 8-byte LE pts)
1172 /// each preceding the raw frame bytes — read directly off the fixture
1173 /// `input.ivf` byte layout, no external parser consulted.
1174 fn strip_single_ivf_frame(ivf: &[u8]) -> &[u8] {
1175 assert!(ivf.len() >= 32 + 12, "IVF too short for a single frame");
1176 assert_eq!(&ivf[0..4], b"DKIF", "expected DKIF magic");
1177 let frame_hdr_off = 32;
1178 let frame_size = u32::from_le_bytes([
1179 ivf[frame_hdr_off],
1180 ivf[frame_hdr_off + 1],
1181 ivf[frame_hdr_off + 2],
1182 ivf[frame_hdr_off + 3],
1183 ]) as usize;
1184 let payload_off = frame_hdr_off + 12;
1185 assert!(
1186 ivf.len() >= payload_off + frame_size,
1187 "IVF frame body truncated"
1188 );
1189 &ivf[payload_off..payload_off + frame_size]
1190 }
1191
1192 /// Build a minimal interframe (3-byte frame tag with bit 0 = 1).
1193 fn interframe_bytes() -> Vec<u8> {
1194 // tmp = 1: key_frame bit set → interframe; version=0; show=0;
1195 // first_partition_size=0.
1196 vec![0x01, 0x00, 0x00]
1197 }
1198
1199 #[test]
1200 fn non_keyframe_rejected_as_unsupported() {
1201 let res = decode_vp8(&interframe_bytes());
1202 assert!(matches!(res, Err(DecodeError::Unsupported(_))));
1203 }
1204
1205 #[test]
1206 fn too_short_frame_header_propagates_error() {
1207 let res = decode_vp8(&[]);
1208 assert!(matches!(
1209 res,
1210 Err(DecodeError::FrameHeader(
1211 crate::frame_header::FrameHeaderError::InputTooShort
1212 ))
1213 ));
1214 }
1215
1216 #[test]
1217 fn truncated_first_partition_surfaces_clean_error() {
1218 // Build a key-frame header whose first_partition_size is 1000 but
1219 // append no actual partition bytes. The function should refuse on
1220 // the slice carve, not panic.
1221 //
1222 // first_partition_size = 1000 → tmp = 1000 << 5 = 0x7d00.
1223 let fps: u32 = 1000;
1224 let tmp: u32 = fps << 5;
1225 let mut buf = vec![
1226 (tmp & 0xff) as u8,
1227 ((tmp >> 8) & 0xff) as u8,
1228 ((tmp >> 16) & 0xff) as u8,
1229 ];
1230 // Start code + width/height (16x16, scale 0).
1231 buf.extend_from_slice(&[0x9d, 0x01, 0x2a, 0x10, 0x00, 0x10, 0x00]);
1232 assert_eq!(buf.len(), 10);
1233 let res = decode_vp8(&buf);
1234 assert!(matches!(
1235 res,
1236 Err(DecodeError::TruncatedFirstPartition {
1237 available: 0,
1238 declared: 1000,
1239 })
1240 ));
1241 }
1242
1243 /// `crop_to_visible`'s contiguous fast path (taken when the visible
1244 /// width equals the macroblock-padded stride) must produce byte-for-byte
1245 /// the same packed I420 output as the strided per-row copy. Sweeps an
1246 /// aligned case (no per-row gap → contiguous path) and a cropped case
1247 /// (visible < stride → strided path) against a reference that always
1248 /// copies row-by-row, on a deterministically textured plane set.
1249 #[test]
1250 fn crop_to_visible_contiguous_matches_strided() {
1251 // Reference: the unconditional strided per-row crop.
1252 fn crop_strided(planes: &KeyframePlanes, width: u32, height: u32) -> Vp8DecodedFrame {
1253 let w = width as usize;
1254 let h = height as usize;
1255 let uvw = w.div_ceil(2);
1256 let uvh = h.div_ceil(2);
1257 let mut y = Vec::with_capacity(w * h);
1258 for r in 0..h {
1259 let src = r * planes.y_stride;
1260 y.extend_from_slice(&planes.y[src..src + w]);
1261 }
1262 let mut u = Vec::with_capacity(uvw * uvh);
1263 let mut v = Vec::with_capacity(uvw * uvh);
1264 for r in 0..uvh {
1265 let src = r * planes.uv_stride;
1266 u.extend_from_slice(&planes.u[src..src + uvw]);
1267 v.extend_from_slice(&planes.v[src..src + uvw]);
1268 }
1269 Vp8DecodedFrame {
1270 width,
1271 height,
1272 y,
1273 u,
1274 v,
1275 }
1276 }
1277
1278 // Build a 2×2-macroblock padded plane set (32×32 luma, 16×16 chroma)
1279 // filled with a position-dependent LCG texture so a stride/offset bug
1280 // produces visibly wrong bytes.
1281 let mb_cols = 2usize;
1282 let mb_rows = 2usize;
1283 let y_stride = mb_cols * 16; // 32
1284 let uv_stride = mb_cols * 8; // 16
1285 let y_rows = mb_rows * 16; // 32
1286 let uv_rows = mb_rows * 8; // 16
1287 let mut seed: u32 = 0x1234_5678;
1288 let mut next = || {
1289 seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1290 (seed >> 24) as u8
1291 };
1292 let y: Vec<u8> = (0..y_stride * y_rows).map(|_| next()).collect();
1293 let u: Vec<u8> = (0..uv_stride * uv_rows).map(|_| next()).collect();
1294 let v: Vec<u8> = (0..uv_stride * uv_rows).map(|_| next()).collect();
1295 let planes = KeyframePlanes {
1296 y,
1297 u,
1298 v,
1299 y_stride,
1300 uv_stride,
1301 mb_cols,
1302 mb_rows,
1303 };
1304
1305 // Aligned case: visible == padded → contiguous fast path.
1306 let got = crop_to_visible(&planes, 32, 32);
1307 let want = crop_strided(&planes, 32, 32);
1308 assert_eq!(got.y, want.y, "aligned luma");
1309 assert_eq!(got.u, want.u, "aligned U");
1310 assert_eq!(got.v, want.v, "aligned V");
1311
1312 // Cropped case: visible < padded on both axes → strided path. Chroma
1313 // visible width 17.div_ceil(2)=9 < uv_stride 16 keeps the chroma
1314 // strided path active too.
1315 let got = crop_to_visible(&planes, 17, 18);
1316 let want = crop_strided(&planes, 17, 18);
1317 assert_eq!(got.y, want.y, "cropped luma");
1318 assert_eq!(got.u, want.u, "cropped U");
1319 assert_eq!(got.v, want.v, "cropped V");
1320
1321 // Mixed case: luma aligned (width==stride) but chroma not. width 32 →
1322 // uvw 16 == uv_stride → both contiguous; use width 32 height 30 so the
1323 // luma row count differs but width stays aligned (luma contiguous,
1324 // height truncation handled by the `w*h` prefix length).
1325 let got = crop_to_visible(&planes, 32, 30);
1326 let want = crop_strided(&planes, 32, 30);
1327 assert_eq!(got.y, want.y, "height-truncated luma");
1328 assert_eq!(got.u, want.u, "height-truncated U");
1329 assert_eq!(got.v, want.v, "height-truncated V");
1330 }
1331
1332 #[test]
1333 fn zero_dimension_rejected() {
1334 // Valid key-frame header but with width = height = 0.
1335 let buf = [0x00, 0x00, 0x00, 0x9d, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00];
1336 let res = decode_vp8(&buf);
1337 assert!(matches!(res, Err(DecodeError::ZeroDimension)));
1338 }
1339
1340 #[test]
1341 fn check_pixel_cap_boundary() {
1342 // Exactly at the cap is allowed; one over is refused.
1343 assert!(check_pixel_cap(16, 16, 256).is_ok());
1344 assert!(matches!(
1345 check_pixel_cap(16, 17, 256),
1346 Err(DecodeError::FrameTooLarge {
1347 pixels: 272,
1348 cap: 256
1349 })
1350 ));
1351 // u32::MAX × u32::MAX must not overflow the u64 product.
1352 assert!(matches!(
1353 check_pixel_cap(u32::MAX, u32::MAX, DEFAULT_MAX_PIXELS_PER_FRAME),
1354 Err(DecodeError::FrameTooLarge { .. })
1355 ));
1356 }
1357
1358 /// A real 16×16 key frame decodes under the default cap but is refused
1359 /// (before any allocation) once the caller tightens the cap below its
1360 /// 256-pixel declared size. Guards the DoS entry point end-to-end.
1361 #[test]
1362 fn tight_pixel_cap_rejects_before_alloc() {
1363 const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
1364 let frame = strip_single_ivf_frame(IVF);
1365
1366 // Default cap: decodes to the full 16×16 picture.
1367 let ok = decode_vp8(frame).expect("default cap decodes the 16x16 key frame");
1368 assert_eq!((ok.width, ok.height), (16, 16));
1369
1370 // Exactly 256 px is still allowed (cap is inclusive).
1371 assert!(decode_vp8_with_max_pixels(frame, 256).is_ok());
1372
1373 // 255 px cap: the 256-px frame is refused with the DoS error and no
1374 // partial decode.
1375 let err = decode_vp8_with_max_pixels(frame, 255)
1376 .expect_err("a 255-px cap must reject a 256-px frame");
1377 assert!(matches!(
1378 err,
1379 DecodeError::FrameTooLarge {
1380 pixels: 256,
1381 cap: 255
1382 }
1383 ));
1384 }
1385
1386 /// The tiny-i-only-16x16 fixture is a single-keyframe VP8 elementary
1387 /// stream packaged in IVF; decoding the contained 57-byte frame should
1388 /// produce a 16x16 I420 picture.
1389 ///
1390 /// `expected.yuv` from the fixture set is the reference decoder's
1391 /// black-box output for the same input (the `ffmpeg` invocation that
1392 /// produced it is recorded in the fixture's `notes.md`). The decode is
1393 /// **bit-exact** against that reference — the whole point of VP8's
1394 /// "exact pixel values are part of the specification" guarantee (RFC
1395 /// 6386 §2). We assert the full I420 byte stream (Y then U then V)
1396 /// equals `expected.yuv` so a regression anywhere in the
1397 /// bitstream → dequant → reconstruct → loop-filter chain is caught.
1398 #[test]
1399 fn tiny_i_only_16x16_fixture_decodes_bit_exact() {
1400 const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
1401 const EXPECTED: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/expected.yuv");
1402 // Sanity: trace.txt lists the contained frame as 57 bytes.
1403 assert_eq!(
1404 strip_single_ivf_frame(IVF).len(),
1405 57,
1406 "fixture VP8 frame size changed"
1407 );
1408 // Concatenate the planes in I420 order and require a byte-exact
1409 // match against the reference (384 bytes = 256 Y + 64 U + 64 V).
1410 assert_fixture_bit_exact(IVF, EXPECTED, 16, 16);
1411 }
1412
1413 /// A second, multi-macroblock bit-exact fixture: a 64×64 intra-only
1414 /// key frame (4×4 = 16 macroblocks, one DCT partition). Exercises the
1415 /// §12 cross-macroblock neighbour propagation (above-row / left-column
1416 /// strips), the §13.3 above/left non-zero predictor threading across a
1417 /// full raster of macroblocks, and the §15.1 loop-filter geometry over
1418 /// internal macroblock edges — none of which the single-MB 16×16
1419 /// fixture touches. Bit-exact against the reference YUV.
1420 #[test]
1421 fn i_only_64x64_fixture_decodes_bit_exact() {
1422 const IVF: &[u8] = include_bytes!("../tests/fixtures/i-only-64x64/input.ivf");
1423 const EXPECTED: &[u8] = include_bytes!("../tests/fixtures/i-only-64x64/expected.yuv");
1424 // 6144 bytes = 64*64 Y + 32*32 U + 32*32 V.
1425 assert_fixture_bit_exact(IVF, EXPECTED, 64, 64);
1426 }
1427
1428 /// Decode a fixture IVF and assert its single key frame is bit-exact
1429 /// against the reference YUV. `w` / `h` are the visible dimensions.
1430 fn assert_fixture_bit_exact(ivf: &[u8], expected: &[u8], w: u32, h: u32) {
1431 let frame_bytes = strip_single_ivf_frame(ivf);
1432 let decoded = decode_vp8(frame_bytes).expect("fixture should decode");
1433 assert_eq!(decoded.width, w);
1434 assert_eq!(decoded.height, h);
1435 let mut got = Vec::with_capacity(expected.len());
1436 got.extend_from_slice(&decoded.y);
1437 got.extend_from_slice(&decoded.u);
1438 got.extend_from_slice(&decoded.v);
1439 assert_eq!(got.len(), expected.len(), "plane byte count mismatch");
1440 assert_eq!(got, expected, "decoded I420 must be bit-exact vs reference");
1441 }
1442
1443 /// A 16×16 key frame coded with **four DCT partitions** (the
1444 /// `log2_nbr_of_dct_partitions = 2` case, §9.5). Exercises the 3-byte
1445 /// little-endian partition-size table parse and the round-robin row
1446 /// striping (one MB row → partition 0). Bit-exact against the
1447 /// reference.
1448 #[test]
1449 fn partition_padding_16x16_4parts_decodes_bit_exact() {
1450 const IVF: &[u8] =
1451 include_bytes!("../tests/fixtures/partition-padding-16x16-4parts/input.ivf");
1452 const EXPECTED: &[u8] =
1453 include_bytes!("../tests/fixtures/partition-padding-16x16-4parts/expected.yuv");
1454 assert_fixture_bit_exact(IVF, EXPECTED, 16, 16);
1455 }
1456
1457 /// A 128×128 key frame (8×8 = 64 macroblocks) coded with four DCT
1458 /// partitions. With eight macroblock rows striped round-robin across
1459 /// four partitions (rows 0/4 → part 0, 1/5 → part 1, …) this is the
1460 /// fixture that actually exercises the §20.4 multi-row partition
1461 /// routing (and the per-partition bool-decoder cursor persisting across
1462 /// the rows that share a partition). Bit-exact against the reference.
1463 #[test]
1464 fn segment_4_partitions_128x128_decodes_bit_exact() {
1465 const IVF: &[u8] = include_bytes!("../tests/fixtures/segment-4-partitions/input.ivf");
1466 const EXPECTED: &[u8] =
1467 include_bytes!("../tests/fixtures/segment-4-partitions/expected.yuv");
1468 assert_fixture_bit_exact(IVF, EXPECTED, 128, 128);
1469 }
1470
1471 /// A batch of single-key-frame fixtures, each decoded bit-exact
1472 /// against its reference YUV. These cover decode behaviours the
1473 /// 16×16 / 64×64 / partition fixtures above don't reach:
1474 ///
1475 /// * `q-high` — `loop_filter_level = 38` (heavy normal deblocking)
1476 /// over a 128×128 frame, the strongest test of the §15.3 `mb_filter`
1477 /// / `subblock_filter` parameter ladder.
1478 /// * `i-only-loopfilter-high` — `loop_filter_level = 33` over 64×64.
1479 /// * `i-only-loopfilter-off` — `loop_filter_level = 0` (the §15 page-84
1480 /// whole-frame filter skip).
1481 /// * `vp8-with-loopfilter-mode-simple` — the §15.2 simple-filter path
1482 /// (`filter_type = 1`, luma-only).
1483 /// * `q-low` — `loop_filter_level = 0`, 32×32 (a non-multiple-of-16
1484 /// path is the next size up; 32 is a clean 2×2 MB grid).
1485 /// * `gradient-and-noise-128x128` — high-entropy content that exercises
1486 /// the full §13 token alphabet (cat ranges, dense blocks).
1487 #[test]
1488 fn additional_single_keyframe_fixtures_decode_bit_exact() {
1489 // (fixture name, input IVF bytes, expected YUV, visible w, visible h)
1490 type FixtureCase = (&'static str, &'static [u8], &'static [u8], u32, u32);
1491 let cases: &[FixtureCase] = &[
1492 (
1493 "q-high",
1494 include_bytes!("../tests/fixtures/q-high/input.ivf"),
1495 include_bytes!("../tests/fixtures/q-high/expected.yuv"),
1496 128,
1497 128,
1498 ),
1499 (
1500 "q-low",
1501 include_bytes!("../tests/fixtures/q-low/input.ivf"),
1502 include_bytes!("../tests/fixtures/q-low/expected.yuv"),
1503 32,
1504 32,
1505 ),
1506 (
1507 "i-only-loopfilter-off",
1508 include_bytes!("../tests/fixtures/i-only-loopfilter-off/input.ivf"),
1509 include_bytes!("../tests/fixtures/i-only-loopfilter-off/expected.yuv"),
1510 64,
1511 64,
1512 ),
1513 (
1514 "i-only-loopfilter-high",
1515 include_bytes!("../tests/fixtures/i-only-loopfilter-high/input.ivf"),
1516 include_bytes!("../tests/fixtures/i-only-loopfilter-high/expected.yuv"),
1517 64,
1518 64,
1519 ),
1520 (
1521 "gradient-and-noise-128x128",
1522 include_bytes!("../tests/fixtures/gradient-and-noise-128x128/input.ivf"),
1523 include_bytes!("../tests/fixtures/gradient-and-noise-128x128/expected.yuv"),
1524 128,
1525 128,
1526 ),
1527 (
1528 "vp8-with-loopfilter-mode-simple",
1529 include_bytes!("../tests/fixtures/vp8-with-loopfilter-mode-simple/input.ivf"),
1530 include_bytes!("../tests/fixtures/vp8-with-loopfilter-mode-simple/expected.yuv"),
1531 64,
1532 64,
1533 ),
1534 ];
1535 for (name, ivf, expected, w, h) in cases {
1536 let frame_bytes = strip_single_ivf_frame(ivf);
1537 let decoded = decode_vp8(frame_bytes)
1538 .unwrap_or_else(|e| panic!("fixture {name} should decode: {e}"));
1539 assert_eq!(decoded.width, *w, "{name} width");
1540 assert_eq!(decoded.height, *h, "{name} height");
1541 let mut got = Vec::with_capacity(expected.len());
1542 got.extend_from_slice(&decoded.y);
1543 got.extend_from_slice(&decoded.u);
1544 got.extend_from_slice(&decoded.v);
1545 assert_eq!(
1546 &got, expected,
1547 "fixture {name} must be bit-exact against the reference"
1548 );
1549 }
1550 }
1551
1552 #[test]
1553 fn carve_dct_partitions_single_partition_no_size_table() {
1554 // num_partitions = 1: the whole section is the one partition; no
1555 // 3-byte size table is read.
1556 let section = [0xAAu8; 7];
1557 let parts = carve_dct_partitions(§ion, 1).expect("single-partition");
1558 assert_eq!(parts.len(), 1);
1559 assert_eq!(parts[0], §ion[..]);
1560 }
1561
1562 #[test]
1563 fn carve_dct_partitions_two_partitions_uses_three_byte_size_prefix() {
1564 // num_partitions = 2: 3 bytes of size prefix for partition 0,
1565 // partition 1 takes the rest.
1566 //
1567 // Build: size[0] = 4 (LE 04 00 00) | partition0 (4 bytes) |
1568 // partition1 (3 bytes).
1569 let mut buf = vec![0x04, 0x00, 0x00];
1570 buf.extend_from_slice(&[0xA1, 0xA2, 0xA3, 0xA4]);
1571 buf.extend_from_slice(&[0xB1, 0xB2, 0xB3]);
1572 let parts = carve_dct_partitions(&buf, 2).expect("two-partition");
1573 assert_eq!(parts.len(), 2);
1574 assert_eq!(parts[0], &[0xA1, 0xA2, 0xA3, 0xA4][..]);
1575 assert_eq!(parts[1], &[0xB1, 0xB2, 0xB3][..]);
1576 }
1577
1578 #[test]
1579 fn carve_dct_partitions_truncated_size_table_rejected() {
1580 // num_partitions = 2 needs 3 size bytes; supply only 2.
1581 let buf = [0x04u8, 0x00];
1582 let res = carve_dct_partitions(&buf, 2);
1583 assert!(matches!(res, Err(DecodeError::TruncatedPartitionSizes)));
1584 }
1585
1586 #[test]
1587 fn carve_dct_partitions_truncated_body_rejected() {
1588 // size[0] = 10, but only 6 body bytes available.
1589 let mut buf = vec![0x0Au8, 0x00, 0x00];
1590 buf.extend_from_slice(&[0xCC; 6]);
1591 let res = carve_dct_partitions(&buf, 2);
1592 assert!(matches!(
1593 res,
1594 Err(DecodeError::TruncatedDctPartition {
1595 index: 0,
1596 available: 6,
1597 declared: 10,
1598 })
1599 ));
1600 }
1601
1602 #[cfg(feature = "registry")]
1603 mod registry_tests {
1604 use super::*;
1605 use oxideav_core::{CodecId, Decoder as _, Error, Frame, Packet, TimeBase};
1606
1607 #[test]
1608 fn vp8_decoder_returns_unsupported_for_interframe_before_keyframe() {
1609 // An interframe fed in with no prior key frame can't decode
1610 // (the §16 inter-prediction layer has no reference to predict
1611 // from); surfaces `Error::Unsupported` via the
1612 // `Vp8DecoderState` driver's empty-reference-slot check.
1613 let mut dec = Vp8Decoder::new(CodecId::new(VP8_CODEC_ID));
1614 let pkt = Packet::new(0, TimeBase::new(1, 1000), interframe_bytes());
1615 dec.send_packet(&pkt).expect("queue packet");
1616 match dec.receive_frame() {
1617 Err(Error::Unsupported(_)) => {}
1618 other => panic!("expected Unsupported, got {other:?}"),
1619 }
1620 }
1621
1622 #[test]
1623 fn vp8_decoder_needs_packet_before_frame() {
1624 let mut dec = Vp8Decoder::new(CodecId::new(VP8_CODEC_ID));
1625 match dec.receive_frame() {
1626 Err(Error::NeedMore) => {}
1627 other => panic!("expected NeedMore, got {other:?}"),
1628 }
1629 }
1630
1631 #[test]
1632 fn vp8_decoder_decodes_tiny_keyframe_through_trait_api() {
1633 const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
1634 let frame_bytes = strip_single_ivf_frame(IVF);
1635 let mut dec = Vp8Decoder::new(CodecId::new(VP8_CODEC_ID));
1636 let mut pkt = Packet::new(0, TimeBase::new(1, 1000), frame_bytes.to_vec());
1637 pkt.pts = Some(42);
1638 pkt.flags.keyframe = true;
1639 dec.send_packet(&pkt).expect("send packet");
1640 let frame = dec.receive_frame().expect("decode");
1641 let Frame::Video(v) = frame else {
1642 panic!("expected Video frame, got {frame:?}");
1643 };
1644 assert_eq!(v.planes.len(), 3, "I420 has three planes");
1645 assert_eq!(v.planes[0].stride, 16);
1646 assert_eq!(v.planes[1].stride, 8);
1647 assert_eq!(v.planes[2].stride, 8);
1648 assert_eq!(v.planes[0].data.len(), 16 * 16);
1649 assert_eq!(v.planes[1].data.len(), 8 * 8);
1650 assert_eq!(v.planes[2].data.len(), 8 * 8);
1651 assert_eq!(v.pts, Some(42));
1652 // After draining, the next call needs more input.
1653 assert!(matches!(dec.receive_frame(), Err(Error::NeedMore)));
1654 }
1655
1656 /// End-to-end multi-frame decode through the `Decoder` trait
1657 /// surface — feed the two-frame `i-frame-then-p-frame-64x64`
1658 /// fixture as two consecutive `Packet`s and assert both frames
1659 /// produce a `Frame::Video` (the bit-exact pixel-match itself is
1660 /// covered by the state-module tests).
1661 #[test]
1662 fn vp8_decoder_decodes_multi_frame_through_trait_api() {
1663 const IVF: &[u8] =
1664 include_bytes!("../tests/fixtures/i-frame-then-p-frame-64x64/input.ivf");
1665 // Walk the IVF (32-byte DKIF + per-frame 12-byte headers).
1666 let mut frames: Vec<Vec<u8>> = Vec::new();
1667 let mut cur = 32usize;
1668 while cur + 12 <= IVF.len() {
1669 let size = u32::from_le_bytes([IVF[cur], IVF[cur + 1], IVF[cur + 2], IVF[cur + 3]])
1670 as usize;
1671 let body = cur + 12;
1672 frames.push(IVF[body..body + size].to_vec());
1673 cur = body + size;
1674 }
1675 assert_eq!(frames.len(), 2, "fixture has 2 frames");
1676 let mut dec = Vp8Decoder::new(CodecId::new(VP8_CODEC_ID));
1677 for (i, bytes) in frames.iter().enumerate() {
1678 let pkt = Packet::new(i as u32, TimeBase::new(1, 1000), bytes.clone());
1679 dec.send_packet(&pkt).expect("send packet");
1680 let frame = dec.receive_frame().expect("decode through trait API");
1681 let Frame::Video(v) = frame else {
1682 panic!("expected Video frame, got {frame:?}");
1683 };
1684 assert_eq!(v.planes.len(), 3, "I420 has 3 planes");
1685 assert_eq!(v.planes[0].stride, 64);
1686 assert_eq!(v.planes[1].stride, 32);
1687 assert_eq!(v.planes[2].stride, 32);
1688 }
1689 }
1690
1691 /// `make_decoder` threads `CodecParameters::limits` into the
1692 /// decoder: a tightened `max_pixels_per_frame` refuses an oversized
1693 /// key frame with `Error::ResourceExhausted` through the trait API,
1694 /// while the default limits decode the same frame unchanged.
1695 #[test]
1696 fn make_decoder_honours_pixel_cap_from_params() {
1697 use oxideav_core::{CodecParameters, DecoderLimits};
1698 const IVF: &[u8] = include_bytes!("../tests/fixtures/tiny-i-only-16x16/input.ivf");
1699 let frame_bytes = strip_single_ivf_frame(IVF).to_vec();
1700 let id = CodecId::new(VP8_CODEC_ID);
1701
1702 // Default params: the 256-px frame decodes.
1703 let mut dec = make_decoder(&CodecParameters::video(id.clone()))
1704 .expect("factory builds a decoder");
1705 let pkt = Packet::new(0, TimeBase::new(1, 1000), frame_bytes.clone());
1706 dec.send_packet(&pkt).expect("queue");
1707 assert!(matches!(dec.receive_frame(), Ok(Frame::Video(_))));
1708
1709 // Tightened to 255 px: the 256-px frame is refused as a
1710 // resource-exhaustion (DoS-cap) error, not a decode error.
1711 let params = CodecParameters::video(id)
1712 .with_limits(DecoderLimits::default().with_max_pixels_per_frame(255));
1713 let mut dec = make_decoder(¶ms).expect("factory builds a decoder");
1714 let pkt = Packet::new(0, TimeBase::new(1, 1000), frame_bytes);
1715 dec.send_packet(&pkt).expect("queue");
1716 match dec.receive_frame() {
1717 Err(Error::ResourceExhausted(_)) => {}
1718 other => panic!("expected ResourceExhausted, got {other:?}"),
1719 }
1720 }
1721
1722 #[test]
1723 fn registers_into_codec_registry() {
1724 use oxideav_core::CodecRegistry;
1725 let mut reg = CodecRegistry::new();
1726 register_codecs(&mut reg);
1727 // The id we registered under must round-trip through
1728 // `decoder_ids()`.
1729 let id = CodecId::new(VP8_CODEC_ID);
1730 let found = reg.decoder_ids().any(|i| i == &id);
1731 assert!(found, "vp8 codec id should be enumerated");
1732 }
1733 }
1734}