Skip to main content

oxideav_vp8/
macroblock.rs

1//! VP8 macroblock mode decoding for key frames (RFC 6386 §11) and the
2//! intra-predicted branch of interframes (RFC 6386 §16.1).
3//!
4//! On a **key frame** this module wires up the structural mode-decision
5//! layer that immediately follows the §19.2 frame header:
6//!
7//! 1. Optional `segment_id` (§10) gated by
8//!    `segmentation_enabled && update_segmentation.update_mb_segmentation_map`.
9//! 2. Optional `mb_skip_coeff` (§11.1) gated by `mb_no_skip_coeff`.
10//! 3. Luma mode (§11.2) — `kf_ymode_tree` walk against the constant
11//!    `KF_YMODE_PROB = {145, 156, 163, 128}` array.
12//! 4. If the luma mode is [`IntraYMode::B`], sixteen sub-block modes
13//!    (§11.3 / §11.5) — `bmode_tree` walks against the context-driven
14//!    `KF_BMODE_PROB[above][left]` table.
15//! 5. Chroma mode (§11.4) — `uv_mode_tree` walk against the constant
16//!    `KF_UV_MODE_PROB = {142, 114, 183}` array.
17//!
18//! On an **interframe** the per-MB layout per §16.1 is structurally
19//! analogous but the trees and probability tables differ:
20//!
21//! * The Y mode walks `ymode_tree` (root left-leaf is `DC_PRED`, not
22//!   `B_PRED`) against the dynamic `IF_YMODE_PROB` whose defaults are
23//!   `{112, 86, 140, 37}`; the frame header's
24//!   `intra_y_mode_prob_update` (§9.10) may override all four entries.
25//! * If the luma mode is [`IntraYMode::B`], the sixteen sub-block
26//!   modes walk the same `bmode_tree` but against the fixed nine-entry
27//!   `IF_BMODE_PROB = {120, 90, 79, 133, 87, 85, 80, 111, 151}` (no
28//!   above / left context).
29//! * The UV mode walks `uv_mode_tree` (same shape as on key frames)
30//!   against the dynamic `IF_UV_MODE_PROB` whose defaults are
31//!   `{162, 101, 204}`; the frame header's
32//!   `intra_uv_mode_prob_update` may override all three entries.
33//!
34//! Per §16.1 final paragraph, the dynamic `IF_YMODE_PROB` and
35//! `IF_UV_MODE_PROB` tables are **restored to their defaults whenever a
36//! key frame is detected**; the
37//! [`InterFrameIntraProbs::for_frame_header`] constructor handles that
38//! reset together with the per-frame override.
39//!
40//! This round stays **structural**: it returns the decoded
41//! [`MacroblockModes`] for every macroblock of the frame without
42//! performing any pixel prediction (§12) or DCT-coefficient decode
43//! (§13). The per-MB output is the input to the next round's
44//! intra-prediction work.
45//!
46//! # Sub-block mode context
47//!
48//! Per §11.3, the probability array used to decode each 4×4 luma
49//! sub-block's [`IntraBmode`] is indexed by the modes already coded
50//! for the sub-block immediately above and immediately to the left of
51//! the current one. Sub-blocks at the macroblock's top edge inherit
52//! their "above" predictor from the bottom row of the macroblock
53//! directly above; sub-blocks at the macroblock's left edge inherit
54//! their "left" predictor from the right column of the macroblock
55//! directly to the left.
56//!
57//! When the neighbouring macroblock used a 16×16 luma mode rather
58//! than B_PRED, §11.3 item 4 defines a constant projection from that
59//! 16×16 mode onto an [`IntraBmode`] (`DC→B_DC`, `V→B_VE`,
60//! `H→B_HE`, `TM→B_TM`). On the very top row / left column of the
61//! frame, missing predictors default to [`IntraBmode::Dc`]
62//! (§11.3 item 3).
63//!
64//! # Reference
65//!
66//! RFC 6386 §11 in full (subsections 11.1 – 11.5). The KF Y / UV /
67//! sub-block probability constants and the three coding trees are
68//! transcribed verbatim from §11.2 (`kf_ymode_tree`,
69//! `kf_ymode_prob`), §11.4 (`uv_mode_tree`, `kf_uv_mode_prob`), and
70//! §11.5 (`kf_bmode_prob[10][10][9]`). The `bmode_tree` is from
71//! §11.2's `bmode_tree` block, and `mb_segment_tree` is from §10.
72
73use crate::bool_decoder::{BoolDecoder, BoolDecoderError};
74use crate::coded_header::Vp8CodedHeader;
75use core::fmt;
76
77/// 16×16 luma intra-prediction mode (RFC 6386 §11.2). The five
78/// variants are listed in the order they take in the spec's
79/// `intra_mbmode` enum (so [`IntraYMode::Dc`] is 0, [`IntraYMode::B`]
80/// is 4); this matches the negative-leaf indices in `kf_ymode_tree`.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82pub enum IntraYMode {
83    /// DC prediction (§12 `DC_PRED`).
84    Dc,
85    /// Vertical prediction (§12 `V_PRED`).
86    V,
87    /// Horizontal prediction (§12 `H_PRED`).
88    H,
89    /// "True Motion" prediction (§12 `TM_PRED`).
90    Tm,
91    /// Each Y sub-block is independently predicted (§11.3 `B_PRED`).
92    B,
93}
94
95/// 8×8 chroma intra-prediction mode (RFC 6386 §11.4) — a subset of
96/// [`IntraYMode`] with `B` removed. The four variants correspond to
97/// `num_uv_modes = B_PRED`'s implicit enum range.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub enum IntraUvMode {
100    /// DC prediction.
101    Dc,
102    /// Vertical prediction.
103    V,
104    /// Horizontal prediction.
105    H,
106    /// "True Motion" prediction.
107    Tm,
108}
109
110/// 4×4 luma sub-block intra-prediction mode (RFC 6386 §11.2). The
111/// ten variants are listed in the order they take in the spec's
112/// `intra_bmode` enum (so [`IntraBmode::Dc`] is 0). Used both as
113/// the per-sub-block decoded mode and as the §11.3 context indexer
114/// for the neighbouring sub-block predictors.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116pub enum IntraBmode {
117    /// Predict DC using row above and column to the left.
118    Dc,
119    /// "True Motion" — propagate second differences.
120    Tm,
121    /// Predict rows using row above.
122    Ve,
123    /// Predict columns using column to the left.
124    He,
125    /// Southwest 45° diagonal prediction.
126    Ld,
127    /// Southeast 45° diagonal prediction.
128    Rd,
129    /// SSE (vertical right) diagonal prediction.
130    Vr,
131    /// SSW (vertical left) diagonal prediction.
132    Vl,
133    /// ESE (horizontal down) diagonal prediction.
134    Hd,
135    /// ENE (horizontal up) diagonal prediction.
136    Hu,
137}
138
139impl IntraUvMode {
140    /// `uv_mode_tree` leaf code (RFC 6386 §11.4): the value
141    /// `treed_read` recovers and the encoder writes via
142    /// [`UV_MODE_TREE`]. `Dc` = 0 … `Tm` = 3.
143    #[inline]
144    pub(crate) fn leaf(self) -> u8 {
145        match self {
146            IntraUvMode::Dc => 0,
147            IntraUvMode::V => 1,
148            IntraUvMode::H => 2,
149            IntraUvMode::Tm => 3,
150        }
151    }
152}
153
154impl IntraBmode {
155    /// 0..=9 — the enum's spec-defined integer code. Used as the
156    /// outer / middle index into `KF_BMODE_PROB` and as the
157    /// `bmode_tree` leaf the encoder writes.
158    #[inline]
159    pub(crate) fn idx(self) -> usize {
160        match self {
161            IntraBmode::Dc => 0,
162            IntraBmode::Tm => 1,
163            IntraBmode::Ve => 2,
164            IntraBmode::He => 3,
165            IntraBmode::Ld => 4,
166            IntraBmode::Rd => 5,
167            IntraBmode::Vr => 6,
168            IntraBmode::Vl => 7,
169            IntraBmode::Hd => 8,
170            IntraBmode::Hu => 9,
171        }
172    }
173}
174
175impl IntraYMode {
176    /// `kf_ymode_tree` leaf code (RFC 6386 §11.2): the value
177    /// `treed_read` recovers and the encoder writes via
178    /// [`KF_YMODE_TREE`]. `Dc` = 0 … `B` = 4.
179    #[inline]
180    pub(crate) fn leaf(self) -> u8 {
181        match self {
182            IntraYMode::Dc => 0,
183            IntraYMode::V => 1,
184            IntraYMode::H => 2,
185            IntraYMode::Tm => 3,
186            IntraYMode::B => 4,
187        }
188    }
189
190    /// §11.3 item 4 projection from a 16×16 luma mode onto the
191    /// sub-block mode used as the context predictor for the
192    /// neighbouring macroblock's edge sub-blocks. Note this is only
193    /// invoked for non-`B_PRED` macroblocks; [`IntraYMode::B`]
194    /// macroblocks store the actual sub-block modes themselves.
195    #[inline]
196    pub(crate) fn project_to_subblock_context(self) -> IntraBmode {
197        match self {
198            IntraYMode::Dc => IntraBmode::Dc,
199            IntraYMode::V => IntraBmode::Ve,
200            IntraYMode::H => IntraBmode::He,
201            IntraYMode::Tm => IntraBmode::Tm,
202            // §11.3 item 4 explicitly only lists the four 16×16
203            // modes; B_PRED macroblocks never reach this branch
204            // because their actual sub-block modes are recorded.
205            IntraYMode::B => IntraBmode::Dc,
206        }
207    }
208}
209
210/// Decoded mode record for one macroblock on a key frame.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct MacroblockModes {
213    /// `segment_id` (§10). `None` when the frame did not enable
214    /// `segmentation_enabled && update_mb_segmentation_map`.
215    pub segment_id: Option<u8>,
216    /// `mb_skip_coeff` (§11.1). `false` when `mb_no_skip_coeff` was
217    /// `false` for the frame (in which case no bit is read; the
218    /// value is forced to `false` per §11.1).
219    pub mb_skip_coeff: bool,
220    /// 16×16 luma mode (§11.2).
221    pub y_mode: IntraYMode,
222    /// 16 sub-block modes (§11.3 / §11.5), in raster order j=0..15.
223    /// `Some(_)` if and only if `y_mode == IntraYMode::B`.
224    pub subblock_modes: Option<[IntraBmode; 16]>,
225    /// 8×8 chroma mode (§11.4).
226    pub uv_mode: IntraUvMode,
227}
228
229/// Errors surfaced by [`parse_key_frame_macroblock_modes`].
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231#[non_exhaustive]
232pub enum MacroblockError {
233    /// The bool decoder ran out of input partway through decoding
234    /// the macroblock layer. Wraps the underlying [`BoolDecoderError`].
235    BoolDecoder(BoolDecoderError),
236    /// `parse_key_frame_macroblock_modes` was invoked on a header
237    /// that has `key_frame == false`. This entry point only handles
238    /// the §11 key-frame layout; interframes follow the §16 layout
239    /// and will be wired up in a subsequent round.
240    NotAKeyFrame,
241}
242
243impl fmt::Display for MacroblockError {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        match self {
246            MacroblockError::BoolDecoder(inner) => {
247                write!(f, "vp8 macroblock: {inner}")
248            }
249            MacroblockError::NotAKeyFrame => {
250                write!(
251                    f,
252                    "vp8 macroblock: parse_key_frame_macroblock_modes invoked on an interframe"
253                )
254            }
255        }
256    }
257}
258
259impl std::error::Error for MacroblockError {}
260
261impl From<BoolDecoderError> for MacroblockError {
262    fn from(value: BoolDecoderError) -> Self {
263        MacroblockError::BoolDecoder(value)
264    }
265}
266
267/// `kf_ymode_tree` from RFC 6386 §11.2 (and §8 listing). Eight
268/// signed entries — negative values are leaf-mode codes (negated to
269/// recover the [`IntraYMode`] index) and positive values are
270/// child-pair offsets to descend to.
271pub(crate) const KF_YMODE_TREE: [i8; 8] = [
272    // -B_PRED, 2 — root: B_PRED = "0", "1" subtree at [2..=3]
273    -4, 2, // 4, 6 — "1" subtree has two descendant subtrees
274    4, 6, // -DC_PRED, -V_PRED — "10" subtree
275    0, -1, // -H_PRED, -TM_PRED — "11" subtree
276    -2, -3,
277];
278
279/// `kf_ymode_prob` per §11.2.
280pub(crate) const KF_YMODE_PROB: [u8; 4] = [145, 156, 163, 128];
281
282/// `uv_mode_tree` from RFC 6386 §11.4. Six signed entries.
283pub(crate) const UV_MODE_TREE: [i8; 6] = [
284    // -DC_PRED, 2
285    0, 2, // -V_PRED, 4
286    -1, 4, // -H_PRED, -TM_PRED
287    -2, -3,
288];
289
290/// `kf_uv_mode_prob` per §11.4.
291pub(crate) const KF_UV_MODE_PROB: [u8; 3] = [142, 114, 183];
292
293/// `bmode_tree` from RFC 6386 §11.2. Eighteen signed entries —
294/// `2 * (num_intra_bmodes - 1) = 18`. The leaves cover all ten
295/// [`IntraBmode`] values.
296pub(crate) const BMODE_TREE: [i8; 18] = [
297    // -B_DC_PRED, 2
298    0, 2, // -B_TM_PRED, 4
299    -1, 4, // -B_VE_PRED, 6
300    -2, 6, // 8, 12 — two sub-subtrees
301    8, 12, // -B_HE_PRED, 10
302    -3, 10, // -B_RD_PRED, -B_VR_PRED
303    -5, -6, // -B_LD_PRED, 14
304    -4, 14, // -B_VL_PRED, 16
305    -7, 16, // -B_HD_PRED, -B_HU_PRED
306    -8, -9,
307];
308
309/// `mb_segment_tree` from RFC 6386 §10. Six entries — the segment
310/// id is two bits walked through a balanced tree.
311///
312/// `pub(crate)` so the encoder's §11 mode-layer writer can drive
313/// [`crate::encoder::BoolEncoder::write_treed`] against the same tree the
314/// decoder walks in [`read_segment_id`], guaranteeing the per-MB
315/// `segment_id` round-trips bit-for-bit.
316pub(crate) const MB_SEGMENT_TREE: [i8; 6] = [
317    // 2, 4
318    2, 4, // -0, -1
319    0, -1, // -2, -3
320    -2, -3,
321];
322
323/// Walk `tree` using `dec`, reading at the probability supplied by
324/// `prob_lookup(i)` where `i` is the current internal-node index
325/// halved (matching the `p[i >> 1]` indexing in §8.1's
326/// `treed_read`). Returns the leaf value (the negated final
327/// `tree` entry).
328fn treed_read<F>(
329    dec: &mut BoolDecoder<'_>,
330    tree: &[i8],
331    prob_lookup: F,
332) -> Result<u8, BoolDecoderError>
333where
334    F: Fn(usize) -> u8,
335{
336    let mut i: i8 = 0;
337    loop {
338        let prob = prob_lookup((i as usize) >> 1);
339        let bit = dec.read_bool(prob)? as usize;
340        let next = tree[i as usize + bit];
341        if next <= 0 {
342            return Ok((-next) as u8);
343        }
344        i = next;
345    }
346}
347
348/// Decode the §11.2 key-frame Y mode against the constant
349/// `KF_YMODE_PROB`. Returns the [`IntraYMode`] for the current MB.
350fn read_kf_y_mode(dec: &mut BoolDecoder<'_>) -> Result<IntraYMode, BoolDecoderError> {
351    let leaf = treed_read(dec, &KF_YMODE_TREE, |i| KF_YMODE_PROB[i])?;
352    Ok(match leaf {
353        0 => IntraYMode::Dc,
354        1 => IntraYMode::V,
355        2 => IntraYMode::H,
356        3 => IntraYMode::Tm,
357        4 => IntraYMode::B,
358        _ => unreachable!("kf_ymode_tree leaf out of range"),
359    })
360}
361
362/// Decode the §11.4 key-frame UV mode against the constant
363/// `KF_UV_MODE_PROB`. Returns the [`IntraUvMode`].
364fn read_kf_uv_mode(dec: &mut BoolDecoder<'_>) -> Result<IntraUvMode, BoolDecoderError> {
365    let leaf = treed_read(dec, &UV_MODE_TREE, |i| KF_UV_MODE_PROB[i])?;
366    Ok(match leaf {
367        0 => IntraUvMode::Dc,
368        1 => IntraUvMode::V,
369        2 => IntraUvMode::H,
370        3 => IntraUvMode::Tm,
371        _ => unreachable!("uv_mode_tree leaf out of range"),
372    })
373}
374
375/// Decode one §11.3 sub-block mode given the `above` / `left`
376/// neighbouring sub-block modes. The 3-D `KF_BMODE_PROB` table is
377/// indexed as `[above][left][i]`, where `i` is the node index of
378/// the `bmode_tree` walk.
379fn read_kf_b_mode(
380    dec: &mut BoolDecoder<'_>,
381    above: IntraBmode,
382    left: IntraBmode,
383) -> Result<IntraBmode, BoolDecoderError> {
384    let row = &KF_BMODE_PROB[above.idx()][left.idx()];
385    let leaf = treed_read(dec, &BMODE_TREE, |i| row[i])?;
386    Ok(match leaf {
387        0 => IntraBmode::Dc,
388        1 => IntraBmode::Tm,
389        2 => IntraBmode::Ve,
390        3 => IntraBmode::He,
391        4 => IntraBmode::Ld,
392        5 => IntraBmode::Rd,
393        6 => IntraBmode::Vr,
394        7 => IntraBmode::Vl,
395        8 => IntraBmode::Hd,
396        9 => IntraBmode::Hu,
397        _ => unreachable!("bmode_tree leaf out of range"),
398    })
399}
400
401/// Decode the §10 segment id (a 2-bit code walked through a
402/// 4-leaf balanced tree). `probs` is `mb_segment_tree_probs[3]`
403/// off the frame's `update_segmentation` block.
404fn read_segment_id(dec: &mut BoolDecoder<'_>, probs: &[u8; 3]) -> Result<u8, BoolDecoderError> {
405    treed_read(dec, &MB_SEGMENT_TREE, |i| probs[i])
406}
407
408/// Decode the key-frame §11 macroblock layer for a complete frame
409/// off `dec`. Returns one [`MacroblockModes`] entry per macroblock
410/// in raster order (row-major; `(mb_rows * mb_cols)` entries
411/// total).
412///
413/// `header` must be the [`Vp8CodedHeader`] returned by
414/// [`Vp8CodedHeader::parse_with_decoder`] for the same partition
415/// `dec` is reading — otherwise the bit positions would be
416/// inconsistent.
417pub fn parse_key_frame_macroblock_modes(
418    dec: &mut BoolDecoder<'_>,
419    header: &Vp8CodedHeader,
420    mb_rows: usize,
421    mb_cols: usize,
422) -> Result<Vec<MacroblockModes>, MacroblockError> {
423    // The Y mode for a key frame is in `color_space.is_some()` —
424    // the header's key/inter framing is consistent across all the
425    // Option-typed fields in §19.2. We rely on `color_space` as
426    // the canonical key-vs-inter discriminator because it is the
427    // first field §19.2 distinguishes on.
428    if header.color_space.is_none() {
429        return Err(MacroblockError::NotAKeyFrame);
430    }
431
432    let segmentation_active = header.segmentation_enabled
433        && header
434            .update_segmentation
435            .as_ref()
436            .is_some_and(|seg| seg.update_mb_segmentation_map);
437
438    // `mb_segment_tree_probs[3]` defaults to 255 (i.e. "always read
439    // a zero") when the corresponding `segment_prob_update_flag` was
440    // 0 per §9.3 item 5. We materialise the resolved probabilities
441    // up front so the per-MB loop doesn't re-resolve them.
442    let segment_probs: [u8; 3] = if segmentation_active {
443        let seg = header
444            .update_segmentation
445            .as_ref()
446            .expect("segmentation_active implies update_segmentation is Some");
447        let mut p = [255u8; 3];
448        for (i, slot) in p.iter_mut().enumerate() {
449            if let Some(v) = seg.segment_prob[i] {
450                *slot = v;
451            }
452        }
453        p
454    } else {
455        [255; 3]
456    };
457
458    let skip_active = header.mb_no_skip_coeff;
459    let skip_prob = header.prob_skip_false.unwrap_or(0);
460
461    // §11.3 item 3: "above" predictor row spans the entire frame
462    // width in 4×4-sub-block units (4 sub-blocks per macroblock
463    // column). "left" predictor column is 4 sub-blocks tall per
464    // macroblock row but only one macroblock wide. Both buffers
465    // are initialised to B_DC_PRED at the start of the frame.
466    let mut above_subblock = vec![IntraBmode::Dc; mb_cols * 4];
467
468    let mut out = Vec::with_capacity(mb_rows * mb_cols);
469    for mb_row in 0..mb_rows {
470        // §11.3 item 3 second sentence: "before decoding each row
471        // of macroblocks, the four left predictors are also set to
472        // B_DC_PRED."
473        let mut left_subblock = [IntraBmode::Dc; 4];
474
475        for mb_col in 0..mb_cols {
476            // 1. segment_id (§10).
477            let segment_id = if segmentation_active {
478                Some(read_segment_id(dec, &segment_probs)?)
479            } else {
480                None
481            };
482
483            // 2. mb_skip_coeff (§11.1).
484            let mb_skip_coeff = if skip_active {
485                dec.read_bool(skip_prob)?
486            } else {
487                false
488            };
489
490            // 3. Luma mode (§11.2).
491            let y_mode = read_kf_y_mode(dec)?;
492
493            // 4. Sixteen sub-block modes (§11.3 / §11.5) only if
494            //    the macroblock luma mode is B_PRED.
495            let subblock_modes = if y_mode == IntraYMode::B {
496                let mut modes = [IntraBmode::Dc; 16];
497                for j in 0..16 {
498                    let row = j >> 2;
499                    let col = j & 3;
500
501                    // §11.3 item 2: the sub-block immediately above
502                    // sub-block (0, col) is bottom-edge sub-block
503                    // (3, col) of the macroblock above. We've been
504                    // keeping `above_subblock` updated to track
505                    // that bottom row across the frame width.
506                    let above = if row == 0 {
507                        above_subblock[mb_col * 4 + col]
508                    } else {
509                        modes[(row - 1) * 4 + col]
510                    };
511                    // §11.3 item 2 (and 3): the sub-block to the
512                    // left of sub-block (row, 0) is right-edge
513                    // sub-block (row, 3) of the macroblock to the
514                    // left; we've been keeping `left_subblock`
515                    // updated to track that right column.
516                    let left = if col == 0 {
517                        left_subblock[row]
518                    } else {
519                        modes[row * 4 + (col - 1)]
520                    };
521
522                    modes[j] = read_kf_b_mode(dec, above, left)?;
523                }
524                Some(modes)
525            } else {
526                None
527            };
528
529            // 5. Chroma mode (§11.4).
530            let uv_mode = read_kf_uv_mode(dec)?;
531
532            // §11.3 item 3 / 4: update the cross-macroblock
533            // predictor buffers in time for the next macroblock.
534            // - The bottom four sub-block modes of the macroblock
535            //   become `above_subblock` for the macroblock directly
536            //   below us.
537            // - The right four sub-block modes of the macroblock
538            //   become `left_subblock` for the macroblock directly
539            //   to our right.
540            // For non-B_PRED macroblocks, every sub-block in the
541            // macroblock projects to the same `IntraBmode` per
542            // §11.3 item 4.
543            match &subblock_modes {
544                Some(modes) => {
545                    above_subblock[mb_col * 4..mb_col * 4 + 4].copy_from_slice(&modes[12..16]);
546                    for (row, slot) in left_subblock.iter_mut().enumerate() {
547                        *slot = modes[row * 4 + 3];
548                    }
549                }
550                None => {
551                    let projected = y_mode.project_to_subblock_context();
552                    for slot in &mut above_subblock[mb_col * 4..mb_col * 4 + 4] {
553                        *slot = projected;
554                    }
555                    left_subblock.fill(projected);
556                }
557            }
558
559            out.push(MacroblockModes {
560                segment_id,
561                mb_skip_coeff,
562                y_mode,
563                subblock_modes,
564                uv_mode,
565            });
566
567            // Suppress unused-variable warning for the loop index
568            // when no macroblock layer is decoded (e.g. the empty
569            // 0-row degenerate case in tests). Not a real risk in
570            // production; keeps clippy happy.
571            let _ = mb_row;
572        }
573    }
574
575    Ok(out)
576}
577
578/// `ymode_tree` from RFC 6386 §16.1 — the interframe variant of the
579/// 16×16 luma mode tree. Same eight signed entries as
580/// [`KF_YMODE_TREE`] but the root left-leaf is `DC_PRED` (the most
581/// common mode on interframes) rather than `B_PRED`, so the tree
582/// shape and the per-mode bitcost are different.
583pub(crate) const IF_YMODE_TREE: [i8; 8] = [
584    // -DC_PRED, 2 — root: DC_PRED = "0", "1" subtree at [2..=3]
585    0, 2, // 4, 6 — "1" subtree has two descendant subtrees
586    4, 6, // -V_PRED, -H_PRED — "10" subtree
587    -1, -2, // -TM_PRED, -B_PRED — "11" subtree
588    -3, -4,
589];
590
591/// `ymode_prob` from RFC 6386 §16.1 — the four default interframe
592/// Y-mode probabilities. May be overridden every frame by the
593/// `intra_y_mode_prob_update` field of [`Vp8CodedHeader`] and must
594/// be **restored to these defaults whenever a key frame is detected**
595/// (§16.1 final paragraph).
596pub const IF_YMODE_PROB_DEFAULTS: [u8; 4] = [112, 86, 140, 37];
597
598/// `bmode_prob` from RFC 6386 §16.1 — the fixed nine-entry sub-block
599/// mode probability table used on interframes. On interframes the
600/// sub-block mode walks the same [`BMODE_TREE`] as on key frames but
601/// against this single context-free probability vector (whereas key
602/// frames use the §11.5 `[above][left][9]` table).
603pub const IF_BMODE_PROB: [u8; 9] = [120, 90, 79, 133, 87, 85, 80, 111, 151];
604
605/// `uv_mode_prob` from RFC 6386 §16.1 — the three default interframe
606/// UV-mode probabilities. May be overridden every frame by the
607/// `intra_uv_mode_prob_update` field of [`Vp8CodedHeader`] and must
608/// be **restored to these defaults whenever a key frame is detected**
609/// (§16.1 final paragraph).
610pub const IF_UV_MODE_PROB_DEFAULTS: [u8; 3] = [162, 101, 204];
611
612/// Resolved per-frame intra-mode probabilities for an interframe.
613///
614/// The dynamic Y- and UV-mode probability tables of §16.1 carry over
615/// from one interframe to the next and are reset to
616/// [`IF_YMODE_PROB_DEFAULTS`] / [`IF_UV_MODE_PROB_DEFAULTS`] on every
617/// key frame. The frame's header may then overlay any of the four /
618/// three replacement probabilities at once via the F-gated
619/// `intra_y_mode_prob_update` / `intra_uv_mode_prob_update` fields of
620/// the §9.10 header tail (already parsed into [`Vp8CodedHeader`]).
621///
622/// This struct is what the macroblock-layer decoder reads from. The
623/// caller owns the across-frame state, computes the resolved struct
624/// per frame using [`InterFrameIntraProbs::for_frame_header`], and
625/// passes it in. The output of this round is per-MB; the across-frame
626/// continuity is the caller's responsibility.
627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
628pub struct InterFrameIntraProbs {
629    /// Resolved `ymode_prob[4]` — the four probabilities walked
630    /// against [`IF_YMODE_TREE`] (root + the two depth-1 subtrees).
631    pub y_mode_prob: [u8; 4],
632    /// Resolved `uv_mode_prob[3]` — the three probabilities walked
633    /// against [`UV_MODE_TREE`].
634    pub uv_mode_prob: [u8; 3],
635}
636
637impl InterFrameIntraProbs {
638    /// Default initial state for the very first frame of a stream
639    /// (which is always a key frame, so the dynamic tables are at
640    /// their §16.1 defaults).
641    pub const fn defaults() -> Self {
642        InterFrameIntraProbs {
643            y_mode_prob: IF_YMODE_PROB_DEFAULTS,
644            uv_mode_prob: IF_UV_MODE_PROB_DEFAULTS,
645        }
646    }
647
648    /// Resolve the per-frame intra-mode probability state given the
649    /// `previous` state at the end of the previous frame and `header`
650    /// for the current frame.
651    ///
652    /// * If `header` is a key frame (`color_space.is_some()`), the
653    ///   dynamic tables are reset to [`IF_YMODE_PROB_DEFAULTS`] /
654    ///   [`IF_UV_MODE_PROB_DEFAULTS`] per §16.1 last paragraph,
655    ///   ignoring `previous`. (Key-frame mode-decode uses the
656    ///   constant `KF_*` probability tables instead — see
657    ///   [`parse_key_frame_macroblock_modes`] — but the next
658    ///   interframe must start from the defaults regardless.)
659    /// * Otherwise the result is `previous` with each F-gated entry
660    ///   from `header.intra_y_mode_prob_update` /
661    ///   `header.intra_uv_mode_prob_update` overlaid in place. Per
662    ///   §9.10, when the F gate is `false` the corresponding `Option`
663    ///   is the whole-array `None`, in which case `previous` carries
664    ///   forward unchanged.
665    pub fn for_frame_header(previous: Self, header: &Vp8CodedHeader) -> Self {
666        if header.color_space.is_some() {
667            // Key frame: §16.1 last paragraph reset.
668            return Self::defaults();
669        }
670        let y_mode_prob = match header.intra_y_mode_prob_update {
671            Some(overrides) => overrides,
672            None => previous.y_mode_prob,
673        };
674        let uv_mode_prob = match header.intra_uv_mode_prob_update {
675            Some(overrides) => overrides,
676            None => previous.uv_mode_prob,
677        };
678        InterFrameIntraProbs {
679            y_mode_prob,
680            uv_mode_prob,
681        }
682    }
683}
684
685impl Default for InterFrameIntraProbs {
686    fn default() -> Self {
687        Self::defaults()
688    }
689}
690
691/// Decode the §16.1 interframe Y mode against `probs` (the resolved
692/// `IF_YMODE_PROB` for the current frame). Returns the
693/// [`IntraYMode`] for the current MB.
694fn read_if_y_mode(
695    dec: &mut BoolDecoder<'_>,
696    probs: &[u8; 4],
697) -> Result<IntraYMode, BoolDecoderError> {
698    let leaf = treed_read(dec, &IF_YMODE_TREE, |i| probs[i])?;
699    Ok(match leaf {
700        0 => IntraYMode::Dc,
701        1 => IntraYMode::V,
702        2 => IntraYMode::H,
703        3 => IntraYMode::Tm,
704        4 => IntraYMode::B,
705        _ => unreachable!("if_ymode_tree leaf out of range"),
706    })
707}
708
709/// Decode the §16.1 interframe UV mode against `probs` (the resolved
710/// `IF_UV_MODE_PROB` for the current frame). The tree shape is the
711/// same [`UV_MODE_TREE`] used on key frames; only the probability
712/// vector differs.
713fn read_if_uv_mode(
714    dec: &mut BoolDecoder<'_>,
715    probs: &[u8; 3],
716) -> Result<IntraUvMode, BoolDecoderError> {
717    let leaf = treed_read(dec, &UV_MODE_TREE, |i| probs[i])?;
718    Ok(match leaf {
719        0 => IntraUvMode::Dc,
720        1 => IntraUvMode::V,
721        2 => IntraUvMode::H,
722        3 => IntraUvMode::Tm,
723        _ => unreachable!("uv_mode_tree leaf out of range"),
724    })
725}
726
727/// Decode one §16.1 interframe sub-block mode against the fixed
728/// [`IF_BMODE_PROB`] vector. Unlike the key-frame variant
729/// ([`read_kf_b_mode`]), there is **no above / left context**: the
730/// same nine probabilities are used for every sub-block.
731fn read_if_b_mode(dec: &mut BoolDecoder<'_>) -> Result<IntraBmode, BoolDecoderError> {
732    let leaf = treed_read(dec, &BMODE_TREE, |i| IF_BMODE_PROB[i])?;
733    Ok(match leaf {
734        0 => IntraBmode::Dc,
735        1 => IntraBmode::Tm,
736        2 => IntraBmode::Ve,
737        3 => IntraBmode::He,
738        4 => IntraBmode::Ld,
739        5 => IntraBmode::Rd,
740        6 => IntraBmode::Vr,
741        7 => IntraBmode::Vl,
742        8 => IntraBmode::Hd,
743        9 => IntraBmode::Hu,
744        _ => unreachable!("bmode_tree leaf out of range"),
745    })
746}
747
748/// Decode the §16.1 layer for one intra-predicted macroblock on an
749/// interframe.
750///
751/// The caller has already established that the macroblock is
752/// intra-predicted (i.e. the `intra-vs-inter` bit read against
753/// `header.prob_intra` was `false` per §16). This function reads the
754/// remaining §16.1 fields:
755///
756/// 1. The 16×16 Y mode (`ymode_tree` against `probs.y_mode_prob`).
757/// 2. If the Y mode is [`IntraYMode::B`], the sixteen sub-block modes
758///    (`bmode_tree` against the fixed [`IF_BMODE_PROB`], no context).
759/// 3. The 8×8 chroma mode (`uv_mode_tree` against
760///    `probs.uv_mode_prob`).
761///
762/// The optional `segment_id` (§10) and `mb_skip_coeff` (§11.1) bits
763/// are **not** read here — on interframes they precede the
764/// intra-vs-inter discriminator and are therefore consumed before the
765/// caller reaches this entry point. To keep the returned
766/// [`MacroblockModes`] uniform with the key-frame layout, pass them
767/// in via `segment_id` and `mb_skip_coeff`; this function simply
768/// forwards them to the output record.
769pub fn parse_inter_frame_intra_macroblock_modes(
770    dec: &mut BoolDecoder<'_>,
771    probs: &InterFrameIntraProbs,
772    segment_id: Option<u8>,
773    mb_skip_coeff: bool,
774) -> Result<MacroblockModes, MacroblockError> {
775    let y_mode = read_if_y_mode(dec, &probs.y_mode_prob)?;
776
777    let subblock_modes = if y_mode == IntraYMode::B {
778        let mut modes = [IntraBmode::Dc; 16];
779        for slot in modes.iter_mut() {
780            *slot = read_if_b_mode(dec)?;
781        }
782        Some(modes)
783    } else {
784        None
785    };
786
787    let uv_mode = read_if_uv_mode(dec, &probs.uv_mode_prob)?;
788
789    Ok(MacroblockModes {
790        segment_id,
791        mb_skip_coeff,
792        y_mode,
793        subblock_modes,
794        uv_mode,
795    })
796}
797
798/// `KF_BMODE_PROB[above][left]` — the fixed `[10][10][9]` table
799/// from RFC 6386 §11.5. Outer index is the `IntraBmode` of the
800/// sub-block above; middle index is the `IntraBmode` of the
801/// sub-block to the left; inner array is the nine internal-node
802/// probabilities for the `bmode_tree` walk (the leaves naturally
803/// produce one of `num_intra_bmodes = 10` values).
804pub(crate) const KF_BMODE_PROB: [[[u8; 9]; 10]; 10] = [
805    // above = B_DC_PRED
806    [
807        [231, 120, 48, 89, 115, 113, 120, 152, 112],
808        [152, 179, 64, 126, 170, 118, 46, 70, 95],
809        [175, 69, 143, 80, 85, 82, 72, 155, 103],
810        [56, 58, 10, 171, 218, 189, 17, 13, 152],
811        [144, 71, 10, 38, 171, 213, 144, 34, 26],
812        [114, 26, 17, 163, 44, 195, 21, 10, 173],
813        [121, 24, 80, 195, 26, 62, 44, 64, 85],
814        [170, 46, 55, 19, 136, 160, 33, 206, 71],
815        [63, 20, 8, 114, 114, 208, 12, 9, 226],
816        [81, 40, 11, 96, 182, 84, 29, 16, 36],
817    ],
818    // above = B_TM_PRED
819    [
820        [134, 183, 89, 137, 98, 101, 106, 165, 148],
821        [72, 187, 100, 130, 157, 111, 32, 75, 80],
822        [66, 102, 167, 99, 74, 62, 40, 234, 128],
823        [41, 53, 9, 178, 241, 141, 26, 8, 107],
824        [104, 79, 12, 27, 217, 255, 87, 17, 7],
825        [74, 43, 26, 146, 73, 166, 49, 23, 157],
826        [65, 38, 105, 160, 51, 52, 31, 115, 128],
827        [87, 68, 71, 44, 114, 51, 15, 186, 23],
828        [47, 41, 14, 110, 182, 183, 21, 17, 194],
829        [66, 45, 25, 102, 197, 189, 23, 18, 22],
830    ],
831    // above = B_VE_PRED
832    [
833        [88, 88, 147, 150, 42, 46, 45, 196, 205],
834        [43, 97, 183, 117, 85, 38, 35, 179, 61],
835        [39, 53, 200, 87, 26, 21, 43, 232, 171],
836        [56, 34, 51, 104, 114, 102, 29, 93, 77],
837        [107, 54, 32, 26, 51, 1, 81, 43, 31],
838        [39, 28, 85, 171, 58, 165, 90, 98, 64],
839        [34, 22, 116, 206, 23, 34, 43, 166, 73],
840        [68, 25, 106, 22, 64, 171, 36, 225, 114],
841        [34, 19, 21, 102, 132, 188, 16, 76, 124],
842        [62, 18, 78, 95, 85, 57, 50, 48, 51],
843    ],
844    // above = B_HE_PRED
845    [
846        [193, 101, 35, 159, 215, 111, 89, 46, 111],
847        [60, 148, 31, 172, 219, 228, 21, 18, 111],
848        [112, 113, 77, 85, 179, 255, 38, 120, 114],
849        [40, 42, 1, 196, 245, 209, 10, 25, 109],
850        [100, 80, 8, 43, 154, 1, 51, 26, 71],
851        [88, 43, 29, 140, 166, 213, 37, 43, 154],
852        [61, 63, 30, 155, 67, 45, 68, 1, 209],
853        [142, 78, 78, 16, 255, 128, 34, 197, 171],
854        [41, 40, 5, 102, 211, 183, 4, 1, 221],
855        [51, 50, 17, 168, 209, 192, 23, 25, 82],
856    ],
857    // above = B_LD_PRED
858    [
859        [125, 98, 42, 88, 104, 85, 117, 175, 82],
860        [95, 84, 53, 89, 128, 100, 113, 101, 45],
861        [75, 79, 123, 47, 51, 128, 81, 171, 1],
862        [57, 17, 5, 71, 102, 57, 53, 41, 49],
863        [115, 21, 2, 10, 102, 255, 166, 23, 6],
864        [38, 33, 13, 121, 57, 73, 26, 1, 85],
865        [41, 10, 67, 138, 77, 110, 90, 47, 114],
866        [101, 29, 16, 10, 85, 128, 101, 196, 26],
867        [57, 18, 10, 102, 102, 213, 34, 20, 43],
868        [117, 20, 15, 36, 163, 128, 68, 1, 26],
869    ],
870    // above = B_RD_PRED
871    [
872        [138, 31, 36, 171, 27, 166, 38, 44, 229],
873        [67, 87, 58, 169, 82, 115, 26, 59, 179],
874        [63, 59, 90, 180, 59, 166, 93, 73, 154],
875        [40, 40, 21, 116, 143, 209, 34, 39, 175],
876        [57, 46, 22, 24, 128, 1, 54, 17, 37],
877        [47, 15, 16, 183, 34, 223, 49, 45, 183],
878        [46, 17, 33, 183, 6, 98, 15, 32, 183],
879        [65, 32, 73, 115, 28, 128, 23, 128, 205],
880        [40, 3, 9, 115, 51, 192, 18, 6, 223],
881        [87, 37, 9, 115, 59, 77, 64, 21, 47],
882    ],
883    // above = B_VR_PRED
884    [
885        [104, 55, 44, 218, 9, 54, 53, 130, 226],
886        [64, 90, 70, 205, 40, 41, 23, 26, 57],
887        [54, 57, 112, 184, 5, 41, 38, 166, 213],
888        [30, 34, 26, 133, 152, 116, 10, 32, 134],
889        [75, 32, 12, 51, 192, 255, 160, 43, 51],
890        [39, 19, 53, 221, 26, 114, 32, 73, 255],
891        [31, 9, 65, 234, 2, 15, 1, 118, 73],
892        [88, 31, 35, 67, 102, 85, 55, 186, 85],
893        [56, 21, 23, 111, 59, 205, 45, 37, 192],
894        [55, 38, 70, 124, 73, 102, 1, 34, 98],
895    ],
896    // above = B_VL_PRED
897    [
898        [102, 61, 71, 37, 34, 53, 31, 243, 192],
899        [69, 60, 71, 38, 73, 119, 28, 222, 37],
900        [68, 45, 128, 34, 1, 47, 11, 245, 171],
901        [62, 17, 19, 70, 146, 85, 55, 62, 70],
902        [75, 15, 9, 9, 64, 255, 184, 119, 16],
903        [37, 43, 37, 154, 100, 163, 85, 160, 1],
904        [63, 9, 92, 136, 28, 64, 32, 201, 85],
905        [86, 6, 28, 5, 64, 255, 25, 248, 1],
906        [56, 8, 17, 132, 137, 255, 55, 116, 128],
907        [58, 15, 20, 82, 135, 57, 26, 121, 40],
908    ],
909    // above = B_HD_PRED
910    [
911        [164, 50, 31, 137, 154, 133, 25, 35, 218],
912        [51, 103, 44, 131, 131, 123, 31, 6, 158],
913        [86, 40, 64, 135, 148, 224, 45, 183, 128],
914        [22, 26, 17, 131, 240, 154, 14, 1, 209],
915        [83, 12, 13, 54, 192, 255, 68, 47, 28],
916        [45, 16, 21, 91, 64, 222, 7, 1, 197],
917        [56, 21, 39, 155, 60, 138, 23, 102, 213],
918        [85, 26, 85, 85, 128, 128, 32, 146, 171],
919        [18, 11, 7, 63, 144, 171, 4, 4, 246],
920        [35, 27, 10, 146, 174, 171, 12, 26, 128],
921    ],
922    // above = B_HU_PRED
923    [
924        [190, 80, 35, 99, 180, 80, 126, 54, 45],
925        [85, 126, 47, 87, 176, 51, 41, 20, 32],
926        [101, 75, 128, 139, 118, 146, 116, 128, 85],
927        [56, 41, 15, 176, 236, 85, 37, 9, 62],
928        [146, 36, 19, 30, 171, 255, 97, 27, 20],
929        [71, 30, 17, 119, 118, 255, 17, 18, 138],
930        [101, 38, 60, 138, 55, 70, 43, 26, 142],
931        [138, 45, 61, 62, 219, 1, 81, 188, 64],
932        [32, 41, 20, 117, 151, 142, 20, 21, 163],
933        [112, 19, 12, 61, 195, 128, 48, 4, 24],
934    ],
935];
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940
941    // In-test boolean encoder mirroring RFC 6386 §7.2 — same shape as
942    // the helpers already used in `bool_decoder::tests` and
943    // `coded_header::tests`. Kept module-local; the production crate
944    // exports nothing that resembles an encoder.
945    struct TestEncoder {
946        out: Vec<u8>,
947        range: u32,
948        bottom: u32,
949        bit_count: i32,
950    }
951
952    impl TestEncoder {
953        fn new() -> Self {
954            TestEncoder {
955                out: Vec::new(),
956                range: 255,
957                bottom: 0,
958                bit_count: 24,
959            }
960        }
961
962        fn write_bool(&mut self, prob: u8, val: bool) {
963            let split = 1 + (((self.range - 1) * prob as u32) >> 8);
964            if val {
965                self.bottom = self.bottom.wrapping_add(split);
966                self.range -= split;
967            } else {
968                self.range = split;
969            }
970            while self.range < 128 {
971                self.range <<= 1;
972                if (self.bottom >> 31) & 1 == 1 {
973                    let mut i = self.out.len();
974                    while i > 0 {
975                        i -= 1;
976                        if self.out[i] == 255 {
977                            self.out[i] = 0;
978                        } else {
979                            self.out[i] = self.out[i].wrapping_add(1);
980                            break;
981                        }
982                    }
983                }
984                self.bottom <<= 1;
985                self.bit_count -= 1;
986                if self.bit_count == 0 {
987                    let byte = (self.bottom >> 24) as u8;
988                    self.out.push(byte);
989                    self.bottom &= (1 << 24) - 1;
990                    self.bit_count = 8;
991                }
992            }
993        }
994
995        /// Write a tree-coded leaf by walking `tree` to find the path
996        /// of bits that lands on `-leaf`. Each path bit is encoded
997        /// against `prob_lookup(node_index >> 1)`, mirroring the
998        /// decoder's `treed_read` walk.
999        fn write_treed<F>(&mut self, tree: &[i8], prob_lookup: F, leaf: u8)
1000        where
1001            F: Fn(usize) -> u8,
1002        {
1003            // Recursive search for the path from node 0 to `-leaf`.
1004            fn find_path(tree: &[i8], i: i8, target: i8, path: &mut Vec<bool>) -> bool {
1005                for bit in 0..2 {
1006                    let next = tree[i as usize + bit];
1007                    path.push(bit == 1);
1008                    if next == target {
1009                        return true;
1010                    }
1011                    if next > 0 && find_path(tree, next, target, path) {
1012                        return true;
1013                    }
1014                    path.pop();
1015                }
1016                false
1017            }
1018            let mut path = Vec::new();
1019            let found = find_path(tree, 0, -(leaf as i8), &mut path);
1020            assert!(
1021                found,
1022                "test bug: leaf {} not reachable in tree {:?}",
1023                leaf, tree
1024            );
1025            // Walk the path against the actual tree to determine
1026            // the node index at every step (so we can call
1027            // prob_lookup with the same node-halved index the
1028            // decoder would).
1029            let mut i: i8 = 0;
1030            for bit in path {
1031                self.write_bool(prob_lookup((i as usize) >> 1), bit);
1032                i = tree[i as usize + bit as usize];
1033            }
1034        }
1035
1036        fn finish(mut self) -> Vec<u8> {
1037            let c = self.bit_count;
1038            let mut v = self.bottom;
1039            if v & (1u32 << (32 - c)) != 0 {
1040                let mut i = self.out.len();
1041                while i > 0 {
1042                    i -= 1;
1043                    if self.out[i] == 255 {
1044                        self.out[i] = 0;
1045                    } else {
1046                        self.out[i] = self.out[i].wrapping_add(1);
1047                        break;
1048                    }
1049                }
1050            }
1051            v <<= c & 7;
1052            let mut c_shift = c >> 3;
1053            while c_shift > 0 {
1054                v <<= 8;
1055                c_shift -= 1;
1056            }
1057            for _ in 0..4 {
1058                self.out.push((v >> 24) as u8);
1059                v <<= 8;
1060            }
1061            self.out
1062        }
1063    }
1064
1065    #[test]
1066    fn kf_ymode_tree_round_trips_all_five_modes() {
1067        for (leaf, mode) in [
1068            (0, IntraYMode::Dc),
1069            (1, IntraYMode::V),
1070            (2, IntraYMode::H),
1071            (3, IntraYMode::Tm),
1072            (4, IntraYMode::B),
1073        ] {
1074            let mut enc = TestEncoder::new();
1075            enc.write_treed(&KF_YMODE_TREE, |i| KF_YMODE_PROB[i], leaf);
1076            let buf = enc.finish();
1077
1078            let mut dec = BoolDecoder::init(&buf).unwrap();
1079            let decoded = read_kf_y_mode(&mut dec).unwrap();
1080            assert_eq!(decoded, mode, "leaf {} round-trip", leaf);
1081        }
1082    }
1083
1084    #[test]
1085    fn uv_mode_tree_round_trips_all_four_modes() {
1086        for (leaf, mode) in [
1087            (0, IntraUvMode::Dc),
1088            (1, IntraUvMode::V),
1089            (2, IntraUvMode::H),
1090            (3, IntraUvMode::Tm),
1091        ] {
1092            let mut enc = TestEncoder::new();
1093            enc.write_treed(&UV_MODE_TREE, |i| KF_UV_MODE_PROB[i], leaf);
1094            let buf = enc.finish();
1095
1096            let mut dec = BoolDecoder::init(&buf).unwrap();
1097            let decoded = read_kf_uv_mode(&mut dec).unwrap();
1098            assert_eq!(decoded, mode, "uv leaf {} round-trip", leaf);
1099        }
1100    }
1101
1102    #[test]
1103    fn bmode_tree_round_trips_all_ten_modes() {
1104        // Sub-block contexts: pick a representative (above, left)
1105        // pair so the inner KF_BMODE_PROB row is well-defined; the
1106        // round-trip is independent of which row we use.
1107        let above_idx = IntraBmode::Dc.idx();
1108        let left_idx = IntraBmode::Dc.idx();
1109        let row = &KF_BMODE_PROB[above_idx][left_idx];
1110
1111        for (leaf, mode) in [
1112            (0, IntraBmode::Dc),
1113            (1, IntraBmode::Tm),
1114            (2, IntraBmode::Ve),
1115            (3, IntraBmode::He),
1116            (4, IntraBmode::Ld),
1117            (5, IntraBmode::Rd),
1118            (6, IntraBmode::Vr),
1119            (7, IntraBmode::Vl),
1120            (8, IntraBmode::Hd),
1121            (9, IntraBmode::Hu),
1122        ] {
1123            let mut enc = TestEncoder::new();
1124            enc.write_treed(&BMODE_TREE, |i| row[i], leaf);
1125            let buf = enc.finish();
1126
1127            let mut dec = BoolDecoder::init(&buf).unwrap();
1128            let decoded = read_kf_b_mode(&mut dec, IntraBmode::Dc, IntraBmode::Dc).unwrap();
1129            assert_eq!(decoded, mode, "bmode leaf {} round-trip", leaf);
1130        }
1131    }
1132
1133    #[test]
1134    fn mb_segment_tree_round_trips_all_four_segments() {
1135        let probs = [200u8, 150, 100];
1136        for sid in 0..4 {
1137            let mut enc = TestEncoder::new();
1138            enc.write_treed(&MB_SEGMENT_TREE, |i| probs[i], sid);
1139            let buf = enc.finish();
1140
1141            let mut dec = BoolDecoder::init(&buf).unwrap();
1142            let decoded = read_segment_id(&mut dec, &probs).unwrap();
1143            assert_eq!(decoded, sid, "segment id {} round-trip", sid);
1144        }
1145    }
1146
1147    /// Minimal end-to-end check: a 2x1 macroblock frame, segmentation
1148    /// disabled, mb_no_skip_coeff disabled. The first MB picks
1149    /// `DC_PRED` plus UV `DC_PRED`; the second picks `B_PRED` plus
1150    /// UV `V_PRED` with sixteen sub-block modes (an all-Dc selection
1151    /// so the context-table lookup is well-defined).
1152    #[test]
1153    fn macroblock_decode_round_trips_minimal_two_mb_frame() {
1154        let mut enc = TestEncoder::new();
1155        // MB 0: DC_PRED, UV DC_PRED.
1156        enc.write_treed(&KF_YMODE_TREE, |i| KF_YMODE_PROB[i], 0);
1157        enc.write_treed(&UV_MODE_TREE, |i| KF_UV_MODE_PROB[i], 0);
1158        // MB 1: B_PRED, sixteen B_DC sub-block modes, UV V_PRED.
1159        enc.write_treed(&KF_YMODE_TREE, |i| KF_YMODE_PROB[i], 4);
1160        for j in 0..16 {
1161            // The above predictor for sub-block (0, col) comes from
1162            // above_subblock[1 * 4 + col]; for non-edge sub-blocks
1163            // we use the prior row. Both default to Dc on this
1164            // tiny frame (mb_row=0, mb above is non-existent).
1165            let row = j >> 2;
1166            let _col = j & 3;
1167            // Above defaults to Dc until we've populated the row.
1168            // Left defaults to Dc for col == 0 and for the row's
1169            // prior column also being Dc (since we're encoding all
1170            // Dcs).
1171            let _ = row;
1172            let row_probs = &KF_BMODE_PROB[IntraBmode::Dc.idx()][IntraBmode::Dc.idx()];
1173            enc.write_treed(&BMODE_TREE, |i| row_probs[i], 0);
1174        }
1175        enc.write_treed(&UV_MODE_TREE, |i| KF_UV_MODE_PROB[i], 1);
1176        let buf = enc.finish();
1177
1178        // Build a synthetic header that says "key frame, no
1179        // segmentation, no skip". We can't easily generate one
1180        // off of bytes without round-tripping the whole §19.2 block,
1181        // so construct one by hand for the macroblock decode entry
1182        // point.
1183        let header = crate::coded_header::Vp8CodedHeader {
1184            color_space: Some(false),
1185            clamping_type: Some(false),
1186            segmentation_enabled: false,
1187            update_segmentation: None,
1188            filter_type: false,
1189            loop_filter_level: 0,
1190            sharpness_level: 0,
1191            mb_lf_adjustments: crate::coded_header::MbLfAdjustments {
1192                loop_filter_adj_enable: false,
1193                mode_ref_lf_delta_update: false,
1194                ref_frame_delta_update: [None; 4],
1195                mb_mode_delta_update: [None; 4],
1196            },
1197            log2_nbr_of_dct_partitions: 0,
1198            nbr_of_dct_partitions: 1,
1199            quant_indices: crate::coded_header::QuantIndices {
1200                y_ac_qi: 0,
1201                y_dc_delta: None,
1202                y2_dc_delta: None,
1203                y2_ac_delta: None,
1204                uv_dc_delta: None,
1205                uv_ac_delta: None,
1206            },
1207            refresh_entropy_probs: false,
1208            refresh_golden_frame: None,
1209            refresh_alternate_frame: None,
1210            copy_buffer_to_golden: None,
1211            copy_buffer_to_alternate: None,
1212            sign_bias_golden: None,
1213            sign_bias_alternate: None,
1214            refresh_last: None,
1215            token_prob_updates: [[[[None; 11]; 3]; 8]; 4],
1216            mb_no_skip_coeff: false,
1217            prob_skip_false: None,
1218            prob_intra: None,
1219            prob_last: None,
1220            prob_gf: None,
1221            intra_y_mode_prob_update: None,
1222            intra_uv_mode_prob_update: None,
1223            mv_prob_update: None,
1224        };
1225
1226        let mut dec = BoolDecoder::init(&buf).unwrap();
1227        let mbs = parse_key_frame_macroblock_modes(&mut dec, &header, 1, 2).unwrap();
1228
1229        assert_eq!(mbs.len(), 2);
1230        assert_eq!(mbs[0].y_mode, IntraYMode::Dc);
1231        assert_eq!(mbs[0].uv_mode, IntraUvMode::Dc);
1232        assert!(mbs[0].subblock_modes.is_none());
1233        assert_eq!(mbs[0].segment_id, None);
1234        assert!(!mbs[0].mb_skip_coeff);
1235        assert_eq!(mbs[1].y_mode, IntraYMode::B);
1236        assert_eq!(mbs[1].uv_mode, IntraUvMode::V);
1237        let sub = mbs[1].subblock_modes.expect("B_PRED carries 16 sub-modes");
1238        assert!(sub.iter().all(|m| *m == IntraBmode::Dc));
1239    }
1240
1241    /// Segmentation enabled + mb_skip_coeff enabled — exercises the
1242    /// optional prefix bits of §10 and §11.1. One macroblock.
1243    #[test]
1244    fn macroblock_decode_handles_optional_segment_and_skip() {
1245        let mut enc = TestEncoder::new();
1246        // segment_id = 2 (path "10" against tree probs [200, 150, 100])
1247        let seg_probs = [200u8, 150, 100];
1248        enc.write_treed(&MB_SEGMENT_TREE, |i| seg_probs[i], 2);
1249        // mb_skip_coeff = true (read against prob_skip_false = 50).
1250        enc.write_bool(50, true);
1251        // Y mode = TM_PRED.
1252        enc.write_treed(&KF_YMODE_TREE, |i| KF_YMODE_PROB[i], 3);
1253        // UV mode = H_PRED.
1254        enc.write_treed(&UV_MODE_TREE, |i| KF_UV_MODE_PROB[i], 2);
1255        let buf = enc.finish();
1256
1257        let header = crate::coded_header::Vp8CodedHeader {
1258            color_space: Some(false),
1259            clamping_type: Some(false),
1260            segmentation_enabled: true,
1261            update_segmentation: Some(crate::coded_header::UpdateSegmentation {
1262                update_mb_segmentation_map: true,
1263                update_segment_feature_data: false,
1264                segment_feature_mode_absolute: false,
1265                quantizer_update: [None; 4],
1266                loop_filter_update: [None; 4],
1267                segment_prob: [Some(200), Some(150), Some(100)],
1268            }),
1269            filter_type: false,
1270            loop_filter_level: 0,
1271            sharpness_level: 0,
1272            mb_lf_adjustments: crate::coded_header::MbLfAdjustments {
1273                loop_filter_adj_enable: false,
1274                mode_ref_lf_delta_update: false,
1275                ref_frame_delta_update: [None; 4],
1276                mb_mode_delta_update: [None; 4],
1277            },
1278            log2_nbr_of_dct_partitions: 0,
1279            nbr_of_dct_partitions: 1,
1280            quant_indices: crate::coded_header::QuantIndices {
1281                y_ac_qi: 0,
1282                y_dc_delta: None,
1283                y2_dc_delta: None,
1284                y2_ac_delta: None,
1285                uv_dc_delta: None,
1286                uv_ac_delta: None,
1287            },
1288            refresh_entropy_probs: false,
1289            refresh_golden_frame: None,
1290            refresh_alternate_frame: None,
1291            copy_buffer_to_golden: None,
1292            copy_buffer_to_alternate: None,
1293            sign_bias_golden: None,
1294            sign_bias_alternate: None,
1295            refresh_last: None,
1296            token_prob_updates: [[[[None; 11]; 3]; 8]; 4],
1297            mb_no_skip_coeff: true,
1298            prob_skip_false: Some(50),
1299            prob_intra: None,
1300            prob_last: None,
1301            prob_gf: None,
1302            intra_y_mode_prob_update: None,
1303            intra_uv_mode_prob_update: None,
1304            mv_prob_update: None,
1305        };
1306
1307        let mut dec = BoolDecoder::init(&buf).unwrap();
1308        let mbs = parse_key_frame_macroblock_modes(&mut dec, &header, 1, 1).unwrap();
1309        assert_eq!(mbs.len(), 1);
1310        assert_eq!(mbs[0].segment_id, Some(2));
1311        assert!(mbs[0].mb_skip_coeff);
1312        assert_eq!(mbs[0].y_mode, IntraYMode::Tm);
1313        assert_eq!(mbs[0].uv_mode, IntraUvMode::H);
1314    }
1315
1316    /// `parse_key_frame_macroblock_modes` must refuse to run on an
1317    /// interframe header (where `color_space` is `None`).
1318    #[test]
1319    fn macroblock_decode_rejects_interframe_header() {
1320        let header = crate::coded_header::Vp8CodedHeader {
1321            color_space: None,
1322            clamping_type: None,
1323            segmentation_enabled: false,
1324            update_segmentation: None,
1325            filter_type: false,
1326            loop_filter_level: 0,
1327            sharpness_level: 0,
1328            mb_lf_adjustments: crate::coded_header::MbLfAdjustments {
1329                loop_filter_adj_enable: false,
1330                mode_ref_lf_delta_update: false,
1331                ref_frame_delta_update: [None; 4],
1332                mb_mode_delta_update: [None; 4],
1333            },
1334            log2_nbr_of_dct_partitions: 0,
1335            nbr_of_dct_partitions: 1,
1336            quant_indices: crate::coded_header::QuantIndices {
1337                y_ac_qi: 0,
1338                y_dc_delta: None,
1339                y2_dc_delta: None,
1340                y2_ac_delta: None,
1341                uv_dc_delta: None,
1342                uv_ac_delta: None,
1343            },
1344            refresh_entropy_probs: false,
1345            refresh_golden_frame: Some(false),
1346            refresh_alternate_frame: Some(false),
1347            copy_buffer_to_golden: Some(0),
1348            copy_buffer_to_alternate: Some(0),
1349            sign_bias_golden: Some(false),
1350            sign_bias_alternate: Some(false),
1351            refresh_last: Some(false),
1352            token_prob_updates: [[[[None; 11]; 3]; 8]; 4],
1353            mb_no_skip_coeff: false,
1354            prob_skip_false: None,
1355            prob_intra: Some(128),
1356            prob_last: Some(128),
1357            prob_gf: Some(128),
1358            intra_y_mode_prob_update: None,
1359            intra_uv_mode_prob_update: None,
1360            mv_prob_update: None,
1361        };
1362        // Two valid bytes for BoolDecoder::init; the macroblock
1363        // parser bails before consuming anything.
1364        let buf = [0u8, 0u8];
1365        let mut dec = BoolDecoder::init(&buf).unwrap();
1366        let err = parse_key_frame_macroblock_modes(&mut dec, &header, 1, 1).unwrap_err();
1367        assert_eq!(err, MacroblockError::NotAKeyFrame);
1368    }
1369
1370    /// Spec-listing transcription check on the KF Y / UV mode prob
1371    /// constants. Catches arithmetic typos at compile-time-of-test.
1372    #[test]
1373    fn kf_mode_probs_match_spec_listing() {
1374        assert_eq!(KF_YMODE_PROB, [145, 156, 163, 128]);
1375        assert_eq!(KF_UV_MODE_PROB, [142, 114, 183]);
1376    }
1377
1378    /// `KF_BMODE_PROB` is 10×10×9 — spot-check a handful of values
1379    /// drawn from §11.5 to confirm transcription.
1380    #[test]
1381    fn kf_bmode_prob_spot_checks() {
1382        // First row of the [B_DC][B_DC] sub-table:
1383        assert_eq!(
1384            KF_BMODE_PROB[0][0],
1385            [231, 120, 48, 89, 115, 113, 120, 152, 112]
1386        );
1387        // Last entry: [B_HU][B_HU] = {112, 19, 12, 61, 195, 128, 48, 4, 24}
1388        assert_eq!(KF_BMODE_PROB[9][9], [112, 19, 12, 61, 195, 128, 48, 4, 24]);
1389        // Middle sample: [B_LD][B_RD] = {38, 33, 13, 121, 57, 73, 26, 1, 85}
1390        assert_eq!(KF_BMODE_PROB[4][5], [38, 33, 13, 121, 57, 73, 26, 1, 85]);
1391    }
1392
1393    // ----- §16.1 interframe intra-MB mode tests -------------------------
1394
1395    /// Spec-listing transcription check on the §16.1 default
1396    /// probability tables. Catches arithmetic typos at compile-time
1397    /// of test.
1398    #[test]
1399    fn if_mode_probs_match_spec_listing() {
1400        assert_eq!(IF_YMODE_PROB_DEFAULTS, [112, 86, 140, 37]);
1401        assert_eq!(IF_UV_MODE_PROB_DEFAULTS, [162, 101, 204]);
1402        assert_eq!(IF_BMODE_PROB, [120, 90, 79, 133, 87, 85, 80, 111, 151]);
1403    }
1404
1405    /// `IF_YMODE_TREE` differs from `KF_YMODE_TREE`: on interframes
1406    /// the root left-leaf is `DC_PRED` ("0"), not `B_PRED`. The
1407    /// shape of the tree is the same eight signed entries but the
1408    /// leaves at the root differ.
1409    #[test]
1410    fn if_ymode_tree_shape_matches_spec() {
1411        // -DC_PRED, 2, 4, 6, -V_PRED, -H_PRED, -TM_PRED, -B_PRED.
1412        // DC=0, V=1, H=2, TM=3, B=4, so leaves are 0, -1, -2, -3, -4.
1413        assert_eq!(IF_YMODE_TREE, [0, 2, 4, 6, -1, -2, -3, -4]);
1414        // Tree[0] is the negative DC leaf (`-DC_PRED`); the KF tree
1415        // has the negative B_PRED leaf in the same slot. The two
1416        // trees disagree at exactly that position.
1417        assert_ne!(IF_YMODE_TREE[0], KF_YMODE_TREE[0]);
1418        assert_eq!(IF_YMODE_TREE[0], 0); // -DC_PRED
1419        assert_eq!(KF_YMODE_TREE[0], -4); // -B_PRED
1420    }
1421
1422    #[test]
1423    fn if_ymode_tree_round_trips_all_five_modes() {
1424        for (leaf, mode) in [
1425            (0, IntraYMode::Dc),
1426            (1, IntraYMode::V),
1427            (2, IntraYMode::H),
1428            (3, IntraYMode::Tm),
1429            (4, IntraYMode::B),
1430        ] {
1431            let mut enc = TestEncoder::new();
1432            enc.write_treed(&IF_YMODE_TREE, |i| IF_YMODE_PROB_DEFAULTS[i], leaf);
1433            let buf = enc.finish();
1434
1435            let mut dec = BoolDecoder::init(&buf).unwrap();
1436            let decoded = read_if_y_mode(&mut dec, &IF_YMODE_PROB_DEFAULTS).unwrap();
1437            assert_eq!(decoded, mode, "if y leaf {} round-trip", leaf);
1438        }
1439    }
1440
1441    #[test]
1442    fn if_uv_mode_tree_round_trips_all_four_modes() {
1443        for (leaf, mode) in [
1444            (0, IntraUvMode::Dc),
1445            (1, IntraUvMode::V),
1446            (2, IntraUvMode::H),
1447            (3, IntraUvMode::Tm),
1448        ] {
1449            let mut enc = TestEncoder::new();
1450            enc.write_treed(&UV_MODE_TREE, |i| IF_UV_MODE_PROB_DEFAULTS[i], leaf);
1451            let buf = enc.finish();
1452
1453            let mut dec = BoolDecoder::init(&buf).unwrap();
1454            let decoded = read_if_uv_mode(&mut dec, &IF_UV_MODE_PROB_DEFAULTS).unwrap();
1455            assert_eq!(decoded, mode, "if uv leaf {} round-trip", leaf);
1456        }
1457    }
1458
1459    #[test]
1460    fn if_bmode_tree_round_trips_all_ten_modes() {
1461        for (leaf, mode) in [
1462            (0, IntraBmode::Dc),
1463            (1, IntraBmode::Tm),
1464            (2, IntraBmode::Ve),
1465            (3, IntraBmode::He),
1466            (4, IntraBmode::Ld),
1467            (5, IntraBmode::Rd),
1468            (6, IntraBmode::Vr),
1469            (7, IntraBmode::Vl),
1470            (8, IntraBmode::Hd),
1471            (9, IntraBmode::Hu),
1472        ] {
1473            let mut enc = TestEncoder::new();
1474            enc.write_treed(&BMODE_TREE, |i| IF_BMODE_PROB[i], leaf);
1475            let buf = enc.finish();
1476
1477            let mut dec = BoolDecoder::init(&buf).unwrap();
1478            let decoded = read_if_b_mode(&mut dec).unwrap();
1479            assert_eq!(decoded, mode, "if bmode leaf {} round-trip", leaf);
1480        }
1481    }
1482
1483    /// Round-trip a complete §16.1 intra MB with a non-`B_PRED` Y
1484    /// mode against the default probability tables.
1485    #[test]
1486    fn if_intra_mb_decode_non_bpred_round_trip() {
1487        let mut enc = TestEncoder::new();
1488        // Y mode = V_PRED (leaf 1).
1489        enc.write_treed(&IF_YMODE_TREE, |i| IF_YMODE_PROB_DEFAULTS[i], 1);
1490        // UV mode = H_PRED (leaf 2).
1491        enc.write_treed(&UV_MODE_TREE, |i| IF_UV_MODE_PROB_DEFAULTS[i], 2);
1492        let buf = enc.finish();
1493
1494        let probs = InterFrameIntraProbs::defaults();
1495        let mut dec = BoolDecoder::init(&buf).unwrap();
1496        let mb = parse_inter_frame_intra_macroblock_modes(&mut dec, &probs, None, false).unwrap();
1497        assert_eq!(mb.y_mode, IntraYMode::V);
1498        assert_eq!(mb.uv_mode, IntraUvMode::H);
1499        assert!(mb.subblock_modes.is_none());
1500        assert_eq!(mb.segment_id, None);
1501        assert!(!mb.mb_skip_coeff);
1502    }
1503
1504    /// Round-trip a `B_PRED` Y mode with a mixed pattern of sub-block
1505    /// modes — proves the §16.1 fixed-prob `bmode_tree` walks
1506    /// produce the same leaf the encoder wrote.
1507    #[test]
1508    fn if_intra_mb_decode_bpred_with_sixteen_subblock_modes() {
1509        let leaves: [u8; 16] = [
1510            0, // Dc
1511            1, // Tm
1512            2, // Ve
1513            3, // He
1514            4, // Ld
1515            5, // Rd
1516            6, // Vr
1517            7, // Vl
1518            8, // Hd
1519            9, // Hu
1520            0, 1, 2, 3, 4, 5,
1521        ];
1522        let expected_modes = [
1523            IntraBmode::Dc,
1524            IntraBmode::Tm,
1525            IntraBmode::Ve,
1526            IntraBmode::He,
1527            IntraBmode::Ld,
1528            IntraBmode::Rd,
1529            IntraBmode::Vr,
1530            IntraBmode::Vl,
1531            IntraBmode::Hd,
1532            IntraBmode::Hu,
1533            IntraBmode::Dc,
1534            IntraBmode::Tm,
1535            IntraBmode::Ve,
1536            IntraBmode::He,
1537            IntraBmode::Ld,
1538            IntraBmode::Rd,
1539        ];
1540
1541        let mut enc = TestEncoder::new();
1542        // Y mode = B_PRED (leaf 4).
1543        enc.write_treed(&IF_YMODE_TREE, |i| IF_YMODE_PROB_DEFAULTS[i], 4);
1544        for leaf in leaves {
1545            enc.write_treed(&BMODE_TREE, |i| IF_BMODE_PROB[i], leaf);
1546        }
1547        // UV mode = TM_PRED (leaf 3).
1548        enc.write_treed(&UV_MODE_TREE, |i| IF_UV_MODE_PROB_DEFAULTS[i], 3);
1549        let buf = enc.finish();
1550
1551        let probs = InterFrameIntraProbs::defaults();
1552        let mut dec = BoolDecoder::init(&buf).unwrap();
1553        let mb = parse_inter_frame_intra_macroblock_modes(&mut dec, &probs, Some(2), true).unwrap();
1554        assert_eq!(mb.y_mode, IntraYMode::B);
1555        assert_eq!(mb.uv_mode, IntraUvMode::Tm);
1556        // The optional segment id / skip flag pass through verbatim
1557        // from the caller, matching the §16.1 contract that those
1558        // fields precede the intra-vs-inter discriminator and are
1559        // therefore read before this entry point.
1560        assert_eq!(mb.segment_id, Some(2));
1561        assert!(mb.mb_skip_coeff);
1562        let sub = mb.subblock_modes.expect("B_PRED carries 16 sub-modes");
1563        assert_eq!(sub, expected_modes);
1564    }
1565
1566    /// `InterFrameIntraProbs::for_frame_header` must reset both
1567    /// dynamic tables to their §16.1 defaults on a key frame,
1568    /// regardless of what the previous interframe state was.
1569    #[test]
1570    fn intra_probs_reset_on_key_frame() {
1571        let scratch = InterFrameIntraProbs {
1572            y_mode_prob: [10, 20, 30, 40],
1573            uv_mode_prob: [50, 60, 70],
1574        };
1575        let key_header = build_minimal_header_with_intra_overrides(true, None, None);
1576        let resolved = InterFrameIntraProbs::for_frame_header(scratch, &key_header);
1577        assert_eq!(resolved, InterFrameIntraProbs::defaults());
1578    }
1579
1580    /// On an interframe without override blocks, the previous-frame
1581    /// dynamic state must carry forward unchanged.
1582    #[test]
1583    fn intra_probs_carry_forward_on_interframe_without_overrides() {
1584        let previous = InterFrameIntraProbs {
1585            y_mode_prob: [10, 20, 30, 40],
1586            uv_mode_prob: [50, 60, 70],
1587        };
1588        let inter_header = build_minimal_header_with_intra_overrides(false, None, None);
1589        let resolved = InterFrameIntraProbs::for_frame_header(previous, &inter_header);
1590        assert_eq!(resolved, previous);
1591    }
1592
1593    /// On an interframe with override blocks, the override values
1594    /// replace the previous-frame entries wholesale (the §9.10 F
1595    /// gate is all-or-nothing on each of the Y / UV blocks).
1596    #[test]
1597    fn intra_probs_overlay_on_interframe_with_overrides() {
1598        let previous = InterFrameIntraProbs {
1599            y_mode_prob: [10, 20, 30, 40],
1600            uv_mode_prob: [50, 60, 70],
1601        };
1602        let inter_header = build_minimal_header_with_intra_overrides(
1603            false,
1604            Some([200, 150, 100, 50]),
1605            Some([180, 90, 1]),
1606        );
1607        let resolved = InterFrameIntraProbs::for_frame_header(previous, &inter_header);
1608        assert_eq!(resolved.y_mode_prob, [200, 150, 100, 50]);
1609        assert_eq!(resolved.uv_mode_prob, [180, 90, 1]);
1610    }
1611
1612    /// Only one of the two override blocks present — the other one
1613    /// must carry forward.
1614    #[test]
1615    fn intra_probs_mixed_overlay_y_only() {
1616        let previous = InterFrameIntraProbs {
1617            y_mode_prob: [10, 20, 30, 40],
1618            uv_mode_prob: [50, 60, 70],
1619        };
1620        let inter_header =
1621            build_minimal_header_with_intra_overrides(false, Some([200, 150, 100, 50]), None);
1622        let resolved = InterFrameIntraProbs::for_frame_header(previous, &inter_header);
1623        assert_eq!(resolved.y_mode_prob, [200, 150, 100, 50]);
1624        assert_eq!(resolved.uv_mode_prob, [50, 60, 70]);
1625    }
1626
1627    /// `Default` impl matches `defaults()`.
1628    #[test]
1629    fn intra_probs_default_matches_defaults_constructor() {
1630        assert_eq!(
1631            InterFrameIntraProbs::default(),
1632            InterFrameIntraProbs::defaults()
1633        );
1634    }
1635
1636    /// Build a minimal [`Vp8CodedHeader`] suitable for the
1637    /// `InterFrameIntraProbs::for_frame_header` tests. `key_frame`
1638    /// controls `color_space`; `y_overrides` / `uv_overrides` carry
1639    /// straight into the two §9.10 fields.
1640    fn build_minimal_header_with_intra_overrides(
1641        key_frame: bool,
1642        y_overrides: Option<[u8; 4]>,
1643        uv_overrides: Option<[u8; 3]>,
1644    ) -> crate::coded_header::Vp8CodedHeader {
1645        crate::coded_header::Vp8CodedHeader {
1646            color_space: if key_frame { Some(false) } else { None },
1647            clamping_type: if key_frame { Some(false) } else { None },
1648            segmentation_enabled: false,
1649            update_segmentation: None,
1650            filter_type: false,
1651            loop_filter_level: 0,
1652            sharpness_level: 0,
1653            mb_lf_adjustments: crate::coded_header::MbLfAdjustments {
1654                loop_filter_adj_enable: false,
1655                mode_ref_lf_delta_update: false,
1656                ref_frame_delta_update: [None; 4],
1657                mb_mode_delta_update: [None; 4],
1658            },
1659            log2_nbr_of_dct_partitions: 0,
1660            nbr_of_dct_partitions: 1,
1661            quant_indices: crate::coded_header::QuantIndices {
1662                y_ac_qi: 0,
1663                y_dc_delta: None,
1664                y2_dc_delta: None,
1665                y2_ac_delta: None,
1666                uv_dc_delta: None,
1667                uv_ac_delta: None,
1668            },
1669            refresh_entropy_probs: false,
1670            refresh_golden_frame: if key_frame { None } else { Some(false) },
1671            refresh_alternate_frame: if key_frame { None } else { Some(false) },
1672            copy_buffer_to_golden: if key_frame { None } else { Some(0) },
1673            copy_buffer_to_alternate: if key_frame { None } else { Some(0) },
1674            sign_bias_golden: if key_frame { None } else { Some(false) },
1675            sign_bias_alternate: if key_frame { None } else { Some(false) },
1676            refresh_last: if key_frame { None } else { Some(false) },
1677            token_prob_updates: [[[[None; 11]; 3]; 8]; 4],
1678            mb_no_skip_coeff: false,
1679            prob_skip_false: None,
1680            prob_intra: if key_frame { None } else { Some(128) },
1681            prob_last: if key_frame { None } else { Some(128) },
1682            prob_gf: if key_frame { None } else { Some(128) },
1683            intra_y_mode_prob_update: y_overrides,
1684            intra_uv_mode_prob_update: uv_overrides,
1685            mv_prob_update: None,
1686        }
1687    }
1688}