Skip to main content

oxideav_vp8/
coded_header.rs

1//! VP8 boolean-coded frame header (RFC 6386 §19.2).
2//!
3//! Where `frame_header.rs` parses the uncompressed three-byte frame
4//! tag (and key-frame start code + width/height/scale) directly out
5//! of the input bytes, **this** module reads through the
6//! [`BoolDecoder`](crate::bool_decoder::BoolDecoder) over the
7//! `first_partition_size`-byte control partition that immediately
8//! follows the uncompressed header. The whole §19.2 table is
9//! probability-128 fixed-width literals (no actual entropy coding of
10//! the values themselves; the bool decoder simply consumes bits at
11//! the arithmetic-coder's natural rate).
12//!
13//! # Scope of this round
14//!
15//! Round 4 closes out §19.2 by adding the inter-frame-only remainder
16//! that follows `prob_skip_false`: the three L(8) reference-selection
17//! probabilities (`prob_intra` / `prob_last` / `prob_gf`), the two
18//! gated intra-mode probability blocks (Y: F then 4 × L(8); UV: F then
19//! 3 × L(8)), and the `mv_prob_update()` sub-block of §17.2 (two
20//! 19-position MV_CONTEXTs, each position is `F? P(7)`). Round 3
21//! covered the table from the top of §19.2 through `mb_no_skip_coeff`
22//! / `prob_skip_false` (every field whose presence in the stream is
23//! determined by the frame's key/inter flag alone and one or two
24//! enable bits along the way). Specifically:
25//!
26//! 1. If `key_frame`: `color_space` (L1) and `clamping_type` (L1).
27//! 2. `segmentation_enabled` (L1). When set, the
28//!    `update_segmentation()` block follows; this round records the
29//!    *shape* of that block via the [`UpdateSegmentation`] struct (the
30//!    enable bits and the 4-segment / 4-loop-filter delta arrays).
31//! 3. `filter_type` (L1), `loop_filter_level` (L6), `sharpness_level` (L3).
32//! 4. `mb_lf_adjustments()` — `loop_filter_adj_enable` (L1) and, when
33//!    set, `mode_ref_lf_delta_update` (L1) plus the eight `ref_frame`/
34//!    `mb_mode` delta-update flag + 6-bit magnitude + sign triples.
35//! 5. `log2_nbr_of_dct_partitions` (L2). The decoded
36//!    `nbr_of_dct_partitions` = `1 << log2_nbr_of_dct_partitions` is
37//!    surfaced for caller convenience (1, 2, 4, or 8).
38//! 6. `quant_indices()` — `y_ac_qi` (L7) plus the five 5-bit
39//!    `present?` / `delta(L4)` / `sign(L1)` deltas for ydc, y2dc, y2ac,
40//!    uvdc, uvac.
41//! 7. `refresh_entropy_probs` (L1) on every frame.
42//! 8. Inter frames only: `refresh_golden_frame` (L1),
43//!    `refresh_alternate_frame` (L1), and — when the corresponding
44//!    refresh flag is 0 — `copy_buffer_to_golden` / `_to_alternate`
45//!    (L2 each), plus `sign_bias_golden` (L1), `sign_bias_alternate`
46//!    (L1), and `refresh_last` (L1). Key frames force refresh of all
47//!    three buffers per §9.7 / §9.8 and so the stream omits these
48//!    bits.
49//! 9. `token_prob_update()` — the `[4][8][3][11]` DCT-coefficient
50//!    context probability sweep (§19.2). Each entry is an
51//!    `update_flag` (L1) plus an optional 8-bit probability. This
52//!    block has to be consumed in order to reach the
53//!    `mb_no_skip_coeff` bit that follows it, so it is decoded here
54//!    even though the resulting probabilities are not yet used.
55//! 10. `mb_no_skip_coeff` (L1) and, when set, `prob_skip_false` (L8).
56//! 11. Inter frames only: `prob_intra` (L8), `prob_last` (L8),
57//!     `prob_gf` (L8) per §9.10.
58//! 12. Inter frames only: a single F flag gating four `L(8)` Y intra-
59//!     mode probability replacements (§9.10 / §16.1) — if the F is
60//!     false the four values are absent and the in-tree defaults
61//!     `{112, 86, 140, 37}` remain in force.
62//! 13. Inter frames only: a single F flag gating three `L(8)` UV
63//!     intra-mode probability replacements (§9.10 / §16.1) — if the
64//!     F is false the three values are absent and the defaults
65//!     `{162, 101, 204}` remain in force.
66//! 14. Inter frames only: `mv_prob_update()` (§17.2) — for each of
67//!     the two MV_CONTEXTs (row then column) 19 optional updates
68//!     read as `F? P(7)`, where each F is gated by the corresponding
69//!     entry in the constant `MV_UPDATE_PROBS` table. The L(7) value
70//!     `x` reconstructs to `x << 1` when non-zero and to `1` when
71//!     zero, per the §17.2 procedure.
72//!
73//! What this round deliberately does **not** decode:
74//!
75//! Nothing remains in §19.2 itself. Subsequent rounds wire up
76//! macroblock-level prediction records (§11 / §16), DCT-coefficient
77//! decoding (§13), the loop filter (§15), and motion-vector decoding
78//! against the resulting probability tables (§17). The decoded
79//! probability triples / mode-prob arrays / 19-position MV contexts
80//! surfaced here are the input to that work.
81//!
82//! # Reference
83//!
84//! RFC 6386 §19.2 (syntax table), §9.2–§9.10 (semantics of the
85//! individual fields), and §7 (the underlying boolean decoder).
86
87use crate::bool_decoder::{BoolDecoder, BoolDecoderError};
88use core::fmt;
89
90/// Errors surfaced by [`Vp8CodedHeader::parse`].
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[non_exhaustive]
93pub enum CodedHeaderError {
94    /// The boolean decoder ran out of input partway through the
95    /// header. Wraps the underlying [`BoolDecoderError`] which carries
96    /// the specific reason (input shorter than two bytes for `init`,
97    /// or end-of-stream during renormalisation).
98    BoolDecoder(BoolDecoderError),
99}
100
101impl fmt::Display for CodedHeaderError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            CodedHeaderError::BoolDecoder(inner) => {
105                write!(f, "vp8 coded header: {inner}")
106            }
107        }
108    }
109}
110
111impl std::error::Error for CodedHeaderError {}
112
113impl From<BoolDecoderError> for CodedHeaderError {
114    fn from(value: BoolDecoderError) -> Self {
115        CodedHeaderError::BoolDecoder(value)
116    }
117}
118
119/// `update_segmentation()` sub-block of §19.2.
120///
121/// Present in [`Vp8CodedHeader`] only when `segmentation_enabled` is
122/// `true` in the same frame.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct UpdateSegmentation {
125    /// L(1) — whether the per-MB segmentation map is updated for the
126    /// current frame.
127    pub update_mb_segmentation_map: bool,
128    /// L(1) — whether the segment-feature data block follows.
129    pub update_segment_feature_data: bool,
130    /// L(1) — `segment_feature_mode`: `false` = delta, `true` =
131    /// absolute (RFC 6386 §9.3 4.a). Only meaningful when
132    /// `update_segment_feature_data` is `true`.
133    pub segment_feature_mode_absolute: bool,
134    /// Per-segment quantizer deltas. `None` for segments whose
135    /// `quantizer_update` bit was 0; otherwise the signed delta value
136    /// reconstructed from L(7) magnitude + L(1) sign.
137    pub quantizer_update: [Option<i16>; 4],
138    /// Per-segment loop-filter deltas. `None` for segments whose
139    /// `loop_filter_update` bit was 0; otherwise the signed delta
140    /// reconstructed from L(6) magnitude + L(1) sign.
141    pub loop_filter_update: [Option<i16>; 4],
142    /// L(1) × 3 — segmentation-map branch probabilities, present only
143    /// when `update_mb_segmentation_map` is `true`. `None` for the
144    /// entries whose `segment_prob_update` flag was 0 (the decoder is
145    /// expected to fall back to 255 per §9.3 item 5); otherwise the
146    /// L(8) value from the bitstream.
147    pub segment_prob: [Option<u8>; 3],
148}
149
150/// `mb_lf_adjustments()` sub-block of §19.2.
151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
152pub struct MbLfAdjustments {
153    /// `loop_filter_adj_enable` — top-level toggle for per-macroblock
154    /// loop-filter adjustments (RFC 6386 §9.4).
155    pub loop_filter_adj_enable: bool,
156    /// `mode_ref_lf_delta_update` — only present when
157    /// `loop_filter_adj_enable` is set.
158    pub mode_ref_lf_delta_update: bool,
159    /// Per-reference-frame deltas (`MAX_REF_LF_DELTAS == 4`).
160    /// Reconstructed as L(6) magnitude + L(1) sign for each
161    /// flag-true entry; `None` for entries whose
162    /// `ref_frame_delta_update_flag` was 0.
163    pub ref_frame_delta_update: [Option<i16>; 4],
164    /// Per-prediction-mode deltas (`MAX_MODE_LF_DELTAS == 4`). Same
165    /// L(6) + L(1) reconstruction as `ref_frame_delta_update`.
166    pub mb_mode_delta_update: [Option<i16>; 4],
167}
168
169/// `quant_indices()` sub-block of §19.2 / §9.6.
170#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
171pub struct QuantIndices {
172    /// L(7) `y_ac_qi` — baseline dequantisation index always present.
173    pub y_ac_qi: u8,
174    /// Signed delta for Y DC. `None` when the `y_dc_delta_present`
175    /// flag was 0.
176    pub y_dc_delta: Option<i8>,
177    /// Signed delta for Y2 DC.
178    pub y2_dc_delta: Option<i8>,
179    /// Signed delta for Y2 AC.
180    pub y2_ac_delta: Option<i8>,
181    /// Signed delta for chroma DC.
182    pub uv_dc_delta: Option<i8>,
183    /// Signed delta for chroma AC.
184    pub uv_ac_delta: Option<i8>,
185}
186
187/// `token_prob_update()` block (§19.2). The four nested dimensions
188/// are `[block_type][band][prev_token_class][token_position]`. Each
189/// entry is `Some(prob)` when the encoder transmitted a new
190/// probability and `None` when the bitstream is signalling
191/// "inherit the default".
192pub type TokenProbUpdates = [[[[Option<u8>; 11]; 3]; 8]; 4];
193
194/// Number of probabilities in a single MV_CONTEXT — RFC 6386 §17
195/// `MVPcount = MVPbits + 10`, with `MVPbits = MVPshort + 7` and
196/// `MVPshort = 2`, giving 19 positions total per row / column
197/// component.
198pub const MV_PROB_COUNT: usize = 19;
199
200/// `mv_prob_update()` block (§17.2). Two 19-position contexts (row
201/// then column); each entry is `Some(prob)` when the encoder
202/// transmitted a new probability and `None` when the corresponding
203/// update flag was 0 (the in-tree default for that position remains
204/// in force).
205pub type MvProbUpdates = [[Option<u8>; MV_PROB_COUNT]; 2];
206
207/// Decoded prefix of the boolean-coded frame header — every field up
208/// to and including `prob_skip_false`.
209///
210/// Caller responsibility:
211///
212/// * Construct via [`Vp8CodedHeader::parse`], passing the parsed
213///   uncompressed header's `key_frame` flag and the slice
214///   `&bytes[header_bytes_consumed..][..first_partition_size]`.
215/// * The bool decoder cursor inside `parse` is advanced past every
216///   field listed at the module level (including the
217///   `token_prob_update()` sweep); subsequent rounds wiring up
218///   `prob_intra`, `prob_last`, `prob_gf` and `mv_prob_update()`
219///   re-`init` the bool decoder at the same partition start and
220///   replay this prefix to reach their entry point.
221#[derive(Debug, Clone, PartialEq, Eq, Default)]
222#[non_exhaustive]
223pub struct Vp8CodedHeader {
224    /// `color_space` (key frame only). Per §9.2 only value `0`
225    /// (BT.601-like) is defined; we surface the raw bit so audits can
226    /// confirm.
227    pub color_space: Option<bool>,
228    /// `clamping_type` (key frame only). Per §9.2: `0` requires
229    /// clamping; `1` declares pre-clamped pixels.
230    pub clamping_type: Option<bool>,
231    /// `segmentation_enabled` — frame-level segmentation toggle.
232    pub segmentation_enabled: bool,
233    /// `update_segmentation()` block. `None` when
234    /// `segmentation_enabled` is `false`.
235    pub update_segmentation: Option<UpdateSegmentation>,
236    /// `filter_type` — `false` = normal, `true` = simple loop filter.
237    pub filter_type: bool,
238    /// `loop_filter_level` (6 bits, `0..=63`).
239    pub loop_filter_level: u8,
240    /// `sharpness_level` (3 bits, `0..=7`).
241    pub sharpness_level: u8,
242    /// `mb_lf_adjustments()` block.
243    pub mb_lf_adjustments: MbLfAdjustments,
244    /// `log2_nbr_of_dct_partitions` (2 bits) per §9.5.
245    pub log2_nbr_of_dct_partitions: u8,
246    /// `1 << log2_nbr_of_dct_partitions` — 1, 2, 4, or 8.
247    pub nbr_of_dct_partitions: u8,
248    /// `quant_indices()` block.
249    pub quant_indices: QuantIndices,
250    /// `refresh_entropy_probs` — true means token-probability updates
251    /// in this frame persist to the next frame's defaults.
252    pub refresh_entropy_probs: bool,
253    /// `refresh_golden_frame` (inter only). Key frames implicitly
254    /// refresh the golden buffer per §9.7, so this is `None` on key
255    /// frames.
256    pub refresh_golden_frame: Option<bool>,
257    /// `refresh_alternate_frame` (inter only). Same key-frame
258    /// behaviour as `refresh_golden_frame`.
259    pub refresh_alternate_frame: Option<bool>,
260    /// `copy_buffer_to_golden` (inter only). 0 = no copy, 1 = copy
261    /// last_frame, 2 = copy alt_ref_frame. Present in the stream
262    /// only when `refresh_golden_frame` is 0; otherwise `None`.
263    pub copy_buffer_to_golden: Option<u8>,
264    /// `copy_buffer_to_alternate` (inter only). 0 = no copy, 1 =
265    /// copy last_frame, 2 = copy golden_frame. Present in the
266    /// stream only when `refresh_alternate_frame` is 0; otherwise
267    /// `None`.
268    pub copy_buffer_to_alternate: Option<u8>,
269    /// `sign_bias_golden` (inter only). Controls MV sign for the
270    /// golden reference.
271    pub sign_bias_golden: Option<bool>,
272    /// `sign_bias_alternate` (inter only).
273    pub sign_bias_alternate: Option<bool>,
274    /// `refresh_last` (inter only). Key frames implicitly refresh
275    /// the last buffer per §9.8, so this is `None` on key frames.
276    pub refresh_last: Option<bool>,
277    /// `token_prob_update()` block (§19.2). The 4×8×3×11 entries
278    /// each carry either `None` (the corresponding
279    /// `coeff_prob_update_flag` was 0) or the L(8) replacement
280    /// probability. The block has to be parsed in order to reach
281    /// the `mb_no_skip_coeff` bit that follows it.
282    pub token_prob_updates: TokenProbUpdates,
283    /// `mb_no_skip_coeff` — frame-level enable for per-MB
284    /// `mb_skip_coeff` flag.
285    pub mb_no_skip_coeff: bool,
286    /// `prob_skip_false` — probability used to decode the per-MB
287    /// `mb_skip_coeff` flag. `None` when `mb_no_skip_coeff` is
288    /// `false` (in which case `mb_skip_coeff` is forced to 0 for all
289    /// MBs per §9.10/§9.11).
290    pub prob_skip_false: Option<u8>,
291    /// `prob_intra` (inter only). L(8) — probability that a
292    /// macroblock is intra-predicted vs inter-predicted (§9.10 /
293    /// §16). `None` on key frames.
294    pub prob_intra: Option<u8>,
295    /// `prob_last` (inter only). L(8) — for an inter-predicted
296    /// macroblock, the probability of selecting `last_frame` over
297    /// `golden_frame` / `altref_frame` (§9.10 / §16.2). `None` on
298    /// key frames.
299    pub prob_last: Option<u8>,
300    /// `prob_gf` (inter only). L(8) — for a non-last inter-predicted
301    /// macroblock, the probability of selecting `golden_frame` over
302    /// `altref_frame` (§9.10 / §16.2). `None` on key frames.
303    pub prob_gf: Option<u8>,
304    /// `intra_y_mode_prob_update` (inter only). The §9.10 "F" gate
305    /// controls whether four replacement Y intra-mode probabilities
306    /// are read. When the F is `true`, all four entries carry the
307    /// transmitted `L(8)` values (in the order corresponding to the
308    /// even positions of `ymode_tree`, §16.1). When the F is
309    /// `false`, every entry is `None` and the §16.1 defaults
310    /// `{112, 86, 140, 37}` remain in force. `None`-of-array on key
311    /// frames.
312    pub intra_y_mode_prob_update: Option<[u8; 4]>,
313    /// `intra_uv_mode_prob_update` (inter only). Same F-gate
314    /// structure as `intra_y_mode_prob_update`, three entries
315    /// instead of four (even positions of `uv_mode_tree`). Defaults
316    /// are `{162, 101, 204}`. `None`-of-array on key frames.
317    pub intra_uv_mode_prob_update: Option<[u8; 3]>,
318    /// `mv_prob_update()` (inter only). Two 19-position MV_CONTEXTs
319    /// (row, then column) — each position is `F? P(7)` (§17.2).
320    /// `None` on key frames; otherwise `Some([[Option<u8>; 19]; 2])`
321    /// where each `Option<u8>` is the reconstructed replacement
322    /// probability (the §17.2 procedure: `x << 1` if non-zero, else
323    /// `1`) when the corresponding F was `true`, and `None` when the
324    /// F was `false`.
325    pub mv_prob_update: Option<MvProbUpdates>,
326}
327
328impl Vp8CodedHeader {
329    /// Set `color_space`.
330    #[must_use]
331    pub fn with_color_space(mut self, v: Option<bool>) -> Self {
332        self.color_space = v;
333        self
334    }
335
336    /// Set `clamping_type`.
337    #[must_use]
338    pub fn with_clamping_type(mut self, v: Option<bool>) -> Self {
339        self.clamping_type = v;
340        self
341    }
342
343    /// Set `segmentation_enabled`.
344    #[must_use]
345    pub fn with_segmentation_enabled(mut self, v: bool) -> Self {
346        self.segmentation_enabled = v;
347        self
348    }
349
350    /// Set `update_segmentation`.
351    #[must_use]
352    pub fn with_update_segmentation(mut self, v: Option<UpdateSegmentation>) -> Self {
353        self.update_segmentation = v;
354        self
355    }
356
357    /// Set `filter_type`.
358    #[must_use]
359    pub fn with_filter_type(mut self, v: bool) -> Self {
360        self.filter_type = v;
361        self
362    }
363
364    /// Set `loop_filter_level`.
365    #[must_use]
366    pub fn with_loop_filter_level(mut self, v: u8) -> Self {
367        self.loop_filter_level = v;
368        self
369    }
370
371    /// Set `sharpness_level`.
372    #[must_use]
373    pub fn with_sharpness_level(mut self, v: u8) -> Self {
374        self.sharpness_level = v;
375        self
376    }
377
378    /// Set `mb_lf_adjustments`.
379    #[must_use]
380    pub fn with_mb_lf_adjustments(mut self, v: MbLfAdjustments) -> Self {
381        self.mb_lf_adjustments = v;
382        self
383    }
384
385    /// Set `log2_nbr_of_dct_partitions`.
386    #[must_use]
387    pub fn with_log2_nbr_of_dct_partitions(mut self, v: u8) -> Self {
388        self.log2_nbr_of_dct_partitions = v;
389        self
390    }
391
392    /// Set `nbr_of_dct_partitions`.
393    #[must_use]
394    pub fn with_nbr_of_dct_partitions(mut self, v: u8) -> Self {
395        self.nbr_of_dct_partitions = v;
396        self
397    }
398
399    /// Set `quant_indices`.
400    #[must_use]
401    pub fn with_quant_indices(mut self, v: QuantIndices) -> Self {
402        self.quant_indices = v;
403        self
404    }
405
406    /// Set `refresh_entropy_probs`.
407    #[must_use]
408    pub fn with_refresh_entropy_probs(mut self, v: bool) -> Self {
409        self.refresh_entropy_probs = v;
410        self
411    }
412
413    /// Set `refresh_golden_frame`.
414    #[must_use]
415    pub fn with_refresh_golden_frame(mut self, v: Option<bool>) -> Self {
416        self.refresh_golden_frame = v;
417        self
418    }
419
420    /// Set `refresh_alternate_frame`.
421    #[must_use]
422    pub fn with_refresh_alternate_frame(mut self, v: Option<bool>) -> Self {
423        self.refresh_alternate_frame = v;
424        self
425    }
426
427    /// Set `copy_buffer_to_golden`.
428    #[must_use]
429    pub fn with_copy_buffer_to_golden(mut self, v: Option<u8>) -> Self {
430        self.copy_buffer_to_golden = v;
431        self
432    }
433
434    /// Set `copy_buffer_to_alternate`.
435    #[must_use]
436    pub fn with_copy_buffer_to_alternate(mut self, v: Option<u8>) -> Self {
437        self.copy_buffer_to_alternate = v;
438        self
439    }
440
441    /// Set `sign_bias_golden`.
442    #[must_use]
443    pub fn with_sign_bias_golden(mut self, v: Option<bool>) -> Self {
444        self.sign_bias_golden = v;
445        self
446    }
447
448    /// Set `sign_bias_alternate`.
449    #[must_use]
450    pub fn with_sign_bias_alternate(mut self, v: Option<bool>) -> Self {
451        self.sign_bias_alternate = v;
452        self
453    }
454
455    /// Set `refresh_last`.
456    #[must_use]
457    pub fn with_refresh_last(mut self, v: Option<bool>) -> Self {
458        self.refresh_last = v;
459        self
460    }
461
462    /// Set `token_prob_updates`.
463    #[must_use]
464    pub fn with_token_prob_updates(mut self, v: TokenProbUpdates) -> Self {
465        self.token_prob_updates = v;
466        self
467    }
468
469    /// Set `mb_no_skip_coeff`.
470    #[must_use]
471    pub fn with_mb_no_skip_coeff(mut self, v: bool) -> Self {
472        self.mb_no_skip_coeff = v;
473        self
474    }
475
476    /// Set `prob_skip_false`.
477    #[must_use]
478    pub fn with_prob_skip_false(mut self, v: Option<u8>) -> Self {
479        self.prob_skip_false = v;
480        self
481    }
482
483    /// Set `prob_intra`.
484    #[must_use]
485    pub fn with_prob_intra(mut self, v: Option<u8>) -> Self {
486        self.prob_intra = v;
487        self
488    }
489
490    /// Set `prob_last`.
491    #[must_use]
492    pub fn with_prob_last(mut self, v: Option<u8>) -> Self {
493        self.prob_last = v;
494        self
495    }
496
497    /// Set `prob_gf`.
498    #[must_use]
499    pub fn with_prob_gf(mut self, v: Option<u8>) -> Self {
500        self.prob_gf = v;
501        self
502    }
503
504    /// Set `intra_y_mode_prob_update`.
505    #[must_use]
506    pub fn with_intra_y_mode_prob_update(mut self, v: Option<[u8; 4]>) -> Self {
507        self.intra_y_mode_prob_update = v;
508        self
509    }
510
511    /// Set `intra_uv_mode_prob_update`.
512    #[must_use]
513    pub fn with_intra_uv_mode_prob_update(mut self, v: Option<[u8; 3]>) -> Self {
514        self.intra_uv_mode_prob_update = v;
515        self
516    }
517
518    /// Set `mv_prob_update`.
519    #[must_use]
520    pub fn with_mv_prob_update(mut self, v: Option<MvProbUpdates>) -> Self {
521        self.mv_prob_update = v;
522        self
523    }
524}
525
526impl Vp8CodedHeader {
527    /// Parse the boolean-coded frame header from the start of the
528    /// control partition.
529    ///
530    /// `partition` is the `first_partition_size` bytes the caller
531    /// extracted from the input slice using
532    /// [`Vp8FrameHeader::header_bytes_consumed`](crate::frame_header::Vp8FrameHeader)
533    /// and the parsed `first_partition_size`. `key_frame` is the
534    /// same field off the uncompressed header.
535    pub fn parse(partition: &[u8], key_frame: bool) -> Result<Self, CodedHeaderError> {
536        Self::parse_with_decoder(partition, key_frame).map(|(hdr, _dec)| hdr)
537    }
538
539    /// Same as [`parse`](Self::parse) but additionally returns the
540    /// [`BoolDecoder`] positioned immediately after the §19.2 header,
541    /// ready for the §11 macroblock layer to keep reading from. The
542    /// decoder borrows from `partition` for the lifetime of the
543    /// returned tuple.
544    pub fn parse_with_decoder<'a>(
545        partition: &'a [u8],
546        key_frame: bool,
547    ) -> Result<(Self, BoolDecoder<'a>), CodedHeaderError> {
548        let mut dec = BoolDecoder::init(partition)?;
549        let hdr = Self::parse_from_decoder(&mut dec, key_frame)?;
550        Ok((hdr, dec))
551    }
552
553    /// Internal entry point shared by [`parse`](Self::parse) and
554    /// [`parse_with_decoder`](Self::parse_with_decoder). Reads every
555    /// field from §19.2 (uncompressed-header → `mv_prob_update()`)
556    /// off `dec` in place.
557    fn parse_from_decoder(
558        dec: &mut BoolDecoder<'_>,
559        key_frame: bool,
560    ) -> Result<Self, CodedHeaderError> {
561        // §19.2 row 1–2: key-frame-only color_space / clamping_type.
562        let (color_space, clamping_type) = if key_frame {
563            let cs = dec.read_bool(128)?;
564            let ct = dec.read_bool(128)?;
565            (Some(cs), Some(ct))
566        } else {
567            (None, None)
568        };
569
570        // §19.2 row 3 + §9.3: segmentation toggle, optional sub-block.
571        let segmentation_enabled = dec.read_bool(128)?;
572        let update_segmentation = if segmentation_enabled {
573            Some(parse_update_segmentation(dec)?)
574        } else {
575            None
576        };
577
578        // §19.2 + §9.4 — loop filter knobs.
579        let filter_type = dec.read_bool(128)?;
580        let loop_filter_level = dec.read_literal(6)? as u8;
581        let sharpness_level = dec.read_literal(3)? as u8;
582
583        // mb_lf_adjustments() sub-block.
584        let mb_lf_adjustments = parse_mb_lf_adjustments(dec)?;
585
586        // §19.2 + §9.5 — DCT partition count.
587        let log2_nbr_of_dct_partitions = dec.read_literal(2)? as u8;
588        let nbr_of_dct_partitions = 1u8 << log2_nbr_of_dct_partitions;
589
590        // quant_indices() sub-block (§9.6).
591        let quant_indices = parse_quant_indices(dec)?;
592
593        // §19.2 — refresh / sign-bias bits. Key vs inter is asymmetric:
594        // key frames have only refresh_entropy_probs in the stream and
595        // implicitly refresh golden / alternate / last; inter frames
596        // carry refresh_golden / refresh_alternate / (copy bufs) /
597        // sign_bias_* / refresh_entropy_probs / refresh_last.
598        let (
599            refresh_golden_frame,
600            refresh_alternate_frame,
601            copy_buffer_to_golden,
602            copy_buffer_to_alternate,
603            sign_bias_golden,
604            sign_bias_alternate,
605            refresh_entropy_probs,
606            refresh_last,
607        ) = if key_frame {
608            let refresh_entropy_probs = dec.read_bool(128)?;
609            (
610                None,
611                None,
612                None,
613                None,
614                None,
615                None,
616                refresh_entropy_probs,
617                None,
618            )
619        } else {
620            let refresh_golden_frame = dec.read_bool(128)?;
621            let refresh_alternate_frame = dec.read_bool(128)?;
622            let copy_buffer_to_golden = if !refresh_golden_frame {
623                Some(dec.read_literal(2)? as u8)
624            } else {
625                None
626            };
627            let copy_buffer_to_alternate = if !refresh_alternate_frame {
628                Some(dec.read_literal(2)? as u8)
629            } else {
630                None
631            };
632            let sign_bias_golden = dec.read_bool(128)?;
633            let sign_bias_alternate = dec.read_bool(128)?;
634            let refresh_entropy_probs = dec.read_bool(128)?;
635            let refresh_last = dec.read_bool(128)?;
636            (
637                Some(refresh_golden_frame),
638                Some(refresh_alternate_frame),
639                copy_buffer_to_golden,
640                copy_buffer_to_alternate,
641                Some(sign_bias_golden),
642                Some(sign_bias_alternate),
643                refresh_entropy_probs,
644                Some(refresh_last),
645            )
646        };
647
648        // token_prob_update() — must be consumed in order to reach
649        // mb_no_skip_coeff. The probabilities themselves will be
650        // consumed by the macroblock decoder in a later round.
651        let token_prob_updates = parse_token_prob_update(dec)?;
652
653        // mb_no_skip_coeff and (conditionally) prob_skip_false.
654        let mb_no_skip_coeff = dec.read_bool(128)?;
655        let prob_skip_false = if mb_no_skip_coeff {
656            Some(dec.read_literal(8)? as u8)
657        } else {
658            None
659        };
660
661        // §9.10 inter-only tail: prob_intra / prob_last / prob_gf,
662        // gated Y / UV intra-mode probability updates, and the
663        // mv_prob_update() sub-block from §17.2. Key frames do not
664        // carry any of these fields per the §9.11 table.
665        let (
666            prob_intra,
667            prob_last,
668            prob_gf,
669            intra_y_mode_prob_update,
670            intra_uv_mode_prob_update,
671            mv_prob_update,
672        ) = if key_frame {
673            (None, None, None, None, None, None)
674        } else {
675            let prob_intra = dec.read_literal(8)? as u8;
676            let prob_last = dec.read_literal(8)? as u8;
677            let prob_gf = dec.read_literal(8)? as u8;
678
679            // F? L(8) × 4 — §9.10 row 7. The single F gate
680            // controls all four entries together.
681            let intra_y_mode_prob_update = if dec.read_bool(128)? {
682                let mut buf = [0u8; 4];
683                for slot in &mut buf {
684                    *slot = dec.read_literal(8)? as u8;
685                }
686                Some(buf)
687            } else {
688                None
689            };
690
691            // F? L(8) × 3 — §9.10 row 8.
692            let intra_uv_mode_prob_update = if dec.read_bool(128)? {
693                let mut buf = [0u8; 3];
694                for slot in &mut buf {
695                    *slot = dec.read_literal(8)? as u8;
696                }
697                Some(buf)
698            } else {
699                None
700            };
701
702            // mv_prob_update() — §17.2.
703            let mv_prob_update = Some(parse_mv_prob_update(dec)?);
704
705            (
706                Some(prob_intra),
707                Some(prob_last),
708                Some(prob_gf),
709                intra_y_mode_prob_update,
710                intra_uv_mode_prob_update,
711                mv_prob_update,
712            )
713        };
714
715        Ok(Vp8CodedHeader {
716            color_space,
717            clamping_type,
718            segmentation_enabled,
719            update_segmentation,
720            filter_type,
721            loop_filter_level,
722            sharpness_level,
723            mb_lf_adjustments,
724            log2_nbr_of_dct_partitions,
725            nbr_of_dct_partitions,
726            quant_indices,
727            refresh_entropy_probs,
728            refresh_golden_frame,
729            refresh_alternate_frame,
730            copy_buffer_to_golden,
731            copy_buffer_to_alternate,
732            sign_bias_golden,
733            sign_bias_alternate,
734            refresh_last,
735            token_prob_updates,
736            mb_no_skip_coeff,
737            prob_skip_false,
738            prob_intra,
739            prob_last,
740            prob_gf,
741            intra_y_mode_prob_update,
742            intra_uv_mode_prob_update,
743            mv_prob_update,
744        })
745    }
746}
747
748/// `coeff_update_probs[i][j][k][t]` — the fixed-probability table that
749/// each `coeff_prob_update_flag` in §19.2's `token_prob_update()` is
750/// read against. Transcribed verbatim from RFC 6386 §13.4 (block under
751/// "The (constant) update probabilities are as follows"). Note that
752/// `coeff_prob_update_flag` is NOT read at probability 128 — using the
753/// flat 128 would consume far more bits than the partition holds for
754/// frames that elect not to update any probabilities.
755const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [
756    [
757        [
758            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
759            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
760            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
761        ],
762        [
763            [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255],
764            [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255],
765            [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
766        ],
767        [
768            [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255],
769            [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
770            [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
771        ],
772        [
773            [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255],
774            [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
775            [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
776        ],
777        [
778            [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
779            [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
780            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
781        ],
782        [
783            [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
784            [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
785            [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
786        ],
787        [
788            [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255],
789            [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255],
790            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
791        ],
792        [
793            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
794            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
795            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
796        ],
797    ],
798    [
799        [
800            [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
801            [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255],
802            [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255],
803        ],
804        [
805            [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
806            [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
807            [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255],
808        ],
809        [
810            [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
811            [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
812            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
813        ],
814        [
815            [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255],
816            [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
817            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
818        ],
819        [
820            [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
821            [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
822            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
823        ],
824        [
825            [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
826            [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
827            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
828        ],
829        [
830            [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
831            [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
832            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
833        ],
834        [
835            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
836            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
837            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
838        ],
839    ],
840    [
841        [
842            [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255],
843            [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255],
844            [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255],
845        ],
846        [
847            [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
848            [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
849            [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255],
850        ],
851        [
852            [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
853            [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
854            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
855        ],
856        [
857            [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
858            [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
859            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
860        ],
861        [
862            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
863            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
864            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
865        ],
866        [
867            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
868            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
869            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
870        ],
871        [
872            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
873            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
874            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
875        ],
876        [
877            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
878            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
879            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
880        ],
881    ],
882    [
883        [
884            [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
885            [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255],
886            [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255],
887        ],
888        [
889            [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
890            [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
891            [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255],
892        ],
893        [
894            [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255],
895            [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
896            [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255],
897        ],
898        [
899            [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
900            [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
901            [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
902        ],
903        [
904            [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255],
905            [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
906            [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
907        ],
908        [
909            [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255],
910            [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
911            [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
912        ],
913        [
914            [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255],
915            [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
916            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
917        ],
918        [
919            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
920            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
921            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
922        ],
923    ],
924];
925
926/// `MV_UPDATE_PROBS[component][position]` — the never-changing table
927/// of update probabilities each `F` flag in `mv_prob_update()` is read
928/// against. Transcribed verbatim from RFC 6386 §17.2
929/// (`vp8_mv_update_probs[2]`). Row component first (index 0), then
930/// column (index 1). Each row carries 19 entries laid out in the
931/// `MV_CONTEXT` order:
932///
933/// * `[0]` — is_short
934/// * `[1]` — sign
935/// * `[2..=8]` — 7-position short tree
936/// * `[9..=18]` — 10 long-value independent bit probabilities
937// Crate-visible so an in-crate anchor in `encoder.rs` can byte-equal
938// the encoder-side `MV_UPDATE_PROBS_FLAT` 38-entry flat copy against
939// this canonical 2×19 spec table — see
940// `encoder::tests::mv_update_probs_flat_matches_spec_table` (round 253).
941pub(crate) const MV_UPDATE_PROBS: [[u8; MV_PROB_COUNT]; 2] = [
942    [
943        237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254,
944        254,
945    ],
946    [
947        231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254,
948        254,
949    ],
950];
951
952/// `DEFAULT_MV_CONTEXT[component][position]` — the in-tree default
953/// MV decoding probabilities, restored on every key frame
954/// (RFC 6386 §17.2 `default_mv_context[2]`). Surfaced as a public
955/// constant so the macroblock-decode round can seed its
956/// `MV_CONTEXT mvc[2]` table from it directly.
957pub const DEFAULT_MV_CONTEXT: [[u8; MV_PROB_COUNT]; 2] = [
958    // row
959    [
960        162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254,
961    ],
962    // column
963    [
964        164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254,
965        254,
966    ],
967];
968
969fn parse_mv_prob_update(dec: &mut BoolDecoder<'_>) -> Result<MvProbUpdates, BoolDecoderError> {
970    let mut out: MvProbUpdates = [[None; MV_PROB_COUNT]; 2];
971    for (i, ctx) in out.iter_mut().enumerate() {
972        for (j, slot) in ctx.iter_mut().enumerate() {
973            // F gate, read at the per-position table probability —
974            // NOT a flat 128.
975            if dec.read_bool(MV_UPDATE_PROBS[i][j])? {
976                // P(7) reconstruction (§17.2):
977                //   x = read_literal(d, 7);
978                //   *p = x ? x << 1 : 1;
979                let x = dec.read_literal(7)? as u8;
980                *slot = Some(if x == 0 { 1 } else { x << 1 });
981            }
982        }
983    }
984    Ok(out)
985}
986
987fn parse_token_prob_update(
988    dec: &mut BoolDecoder<'_>,
989) -> Result<TokenProbUpdates, BoolDecoderError> {
990    let mut out: TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
991    // §13.4: 4×8×3×11 = 1056 update flags, each read at the
992    // position-specific probability from the COEFF_UPDATE_PROBS table
993    // (NOT a flat 128). The walk order is fixed (i outermost over planes,
994    // then bands, then prev-token classes, then positions), so the output
995    // array and the probability table are traversed in exact lockstep:
996    // zip the two leaf `[…; 11]` rows so the inner read indexes neither
997    // array — the per-flag 4-level `COEFF_UPDATE_PROBS[i][j][k][t]`
998    // re-traversal (four bounds checks + index arithmetic per flag) is
999    // replaced by a single forward step over the already-flat probability
1000    // row. Output is bit-identical: same flags, same order, same
1001    // per-position probabilities.
1002    for (out_plane, prob_plane) in out.iter_mut().zip(COEFF_UPDATE_PROBS.iter()) {
1003        for (out_band, prob_band) in out_plane.iter_mut().zip(prob_plane.iter()) {
1004            for (out_ctx, prob_ctx) in out_band.iter_mut().zip(prob_band.iter()) {
1005                for (slot, &prob) in out_ctx.iter_mut().zip(prob_ctx.iter()) {
1006                    let present = dec.read_bool(prob)?;
1007                    *slot = if present {
1008                        Some(dec.read_literal(8)? as u8)
1009                    } else {
1010                        None
1011                    };
1012                }
1013            }
1014        }
1015    }
1016    Ok(out)
1017}
1018
1019/// Bench-only re-export of [`parse_token_prob_update`] (§13.4) so the
1020/// `parse_token_prob_update` micro-bench can drive the flag-read loop in
1021/// isolation against a pre-encoded header partition. Not part of the
1022/// public decode surface — the field is consumed inline by
1023/// [`Vp8CodedHeader::parse`] in production.
1024#[doc(hidden)]
1025pub fn bench_parse_token_prob_update(
1026    dec: &mut BoolDecoder<'_>,
1027) -> Result<TokenProbUpdates, BoolDecoderError> {
1028    parse_token_prob_update(dec)
1029}
1030
1031/// Read a magnitude-`n`-and-sign delta as defined throughout §19.2.
1032///
1033/// Returns the reconstructed signed value (`-((1<<n) - 1) ..=
1034/// (1<<n) - 1`). The boolean decoder reads `n` flag bits for the
1035/// magnitude (MSB-first) followed by a single sign bit; sign 1 is
1036/// negative.
1037fn read_signed_delta(dec: &mut BoolDecoder<'_>, n: u32) -> Result<i16, BoolDecoderError> {
1038    let magnitude = dec.read_literal(n)? as i16;
1039    let sign = dec.read_bool(128)?;
1040    Ok(if sign { -magnitude } else { magnitude })
1041}
1042
1043fn parse_update_segmentation(
1044    dec: &mut BoolDecoder<'_>,
1045) -> Result<UpdateSegmentation, BoolDecoderError> {
1046    let update_mb_segmentation_map = dec.read_bool(128)?;
1047    let update_segment_feature_data = dec.read_bool(128)?;
1048
1049    let mut segment_feature_mode_absolute = false;
1050    let mut quantizer_update: [Option<i16>; 4] = [None; 4];
1051    let mut loop_filter_update: [Option<i16>; 4] = [None; 4];
1052
1053    if update_segment_feature_data {
1054        segment_feature_mode_absolute = dec.read_bool(128)?;
1055        for slot in &mut quantizer_update {
1056            let present = dec.read_bool(128)?;
1057            *slot = if present {
1058                Some(read_signed_delta(dec, 7)?)
1059            } else {
1060                None
1061            };
1062        }
1063        for slot in &mut loop_filter_update {
1064            let present = dec.read_bool(128)?;
1065            *slot = if present {
1066                Some(read_signed_delta(dec, 6)?)
1067            } else {
1068                None
1069            };
1070        }
1071    }
1072
1073    let mut segment_prob: [Option<u8>; 3] = [None; 3];
1074    if update_mb_segmentation_map {
1075        for slot in &mut segment_prob {
1076            let present = dec.read_bool(128)?;
1077            *slot = if present {
1078                Some(dec.read_literal(8)? as u8)
1079            } else {
1080                None
1081            };
1082        }
1083    }
1084
1085    Ok(UpdateSegmentation {
1086        update_mb_segmentation_map,
1087        update_segment_feature_data,
1088        segment_feature_mode_absolute,
1089        quantizer_update,
1090        loop_filter_update,
1091        segment_prob,
1092    })
1093}
1094
1095fn parse_mb_lf_adjustments(dec: &mut BoolDecoder<'_>) -> Result<MbLfAdjustments, BoolDecoderError> {
1096    let loop_filter_adj_enable = dec.read_bool(128)?;
1097    let mut mode_ref_lf_delta_update = false;
1098    let mut ref_frame_delta_update: [Option<i16>; 4] = [None; 4];
1099    let mut mb_mode_delta_update: [Option<i16>; 4] = [None; 4];
1100
1101    if loop_filter_adj_enable {
1102        mode_ref_lf_delta_update = dec.read_bool(128)?;
1103        if mode_ref_lf_delta_update {
1104            for slot in &mut ref_frame_delta_update {
1105                let present = dec.read_bool(128)?;
1106                *slot = if present {
1107                    Some(read_signed_delta(dec, 6)?)
1108                } else {
1109                    None
1110                };
1111            }
1112            for slot in &mut mb_mode_delta_update {
1113                let present = dec.read_bool(128)?;
1114                *slot = if present {
1115                    Some(read_signed_delta(dec, 6)?)
1116                } else {
1117                    None
1118                };
1119            }
1120        }
1121    }
1122
1123    Ok(MbLfAdjustments {
1124        loop_filter_adj_enable,
1125        mode_ref_lf_delta_update,
1126        ref_frame_delta_update,
1127        mb_mode_delta_update,
1128    })
1129}
1130
1131fn parse_quant_indices(dec: &mut BoolDecoder<'_>) -> Result<QuantIndices, BoolDecoderError> {
1132    let y_ac_qi = dec.read_literal(7)? as u8;
1133    let mut deltas: [Option<i8>; 5] = [None; 5];
1134    for slot in &mut deltas {
1135        let present = dec.read_bool(128)?;
1136        *slot = if present {
1137            // §9.6: L(4) magnitude + L(1) sign. Range is
1138            // -15..=15, so i8 is plenty.
1139            let mag = dec.read_literal(4)? as i8;
1140            let sign = dec.read_bool(128)?;
1141            Some(if sign { -mag } else { mag })
1142        } else {
1143            None
1144        };
1145    }
1146
1147    Ok(QuantIndices {
1148        y_ac_qi,
1149        y_dc_delta: deltas[0],
1150        y2_dc_delta: deltas[1],
1151        y2_ac_delta: deltas[2],
1152        uv_dc_delta: deltas[3],
1153        uv_ac_delta: deltas[4],
1154    })
1155}
1156
1157#[cfg(test)]
1158mod tests {
1159    use super::*;
1160
1161    // In-test boolean encoder mirroring RFC 6386 §7.2 — copy of the
1162    // helper in `bool_decoder::tests`, kept module-local so the
1163    // production crate exports nothing that resembles an encoder.
1164    // This is the only practical way to build ground-truth payloads
1165    // for the round-trip tests below.
1166    struct TestEncoder {
1167        out: Vec<u8>,
1168        range: u32,
1169        bottom: u32,
1170        bit_count: i32,
1171    }
1172
1173    impl TestEncoder {
1174        fn new() -> Self {
1175            TestEncoder {
1176                out: Vec::new(),
1177                range: 255,
1178                bottom: 0,
1179                bit_count: 24,
1180            }
1181        }
1182
1183        fn write_bool(&mut self, prob: u8, val: bool) {
1184            let split = 1 + (((self.range - 1) * prob as u32) >> 8);
1185            if val {
1186                self.bottom = self.bottom.wrapping_add(split);
1187                self.range -= split;
1188            } else {
1189                self.range = split;
1190            }
1191            while self.range < 128 {
1192                self.range <<= 1;
1193                if (self.bottom >> 31) & 1 == 1 {
1194                    let mut i = self.out.len();
1195                    while i > 0 {
1196                        i -= 1;
1197                        if self.out[i] == 255 {
1198                            self.out[i] = 0;
1199                        } else {
1200                            self.out[i] = self.out[i].wrapping_add(1);
1201                            break;
1202                        }
1203                    }
1204                }
1205                self.bottom <<= 1;
1206                self.bit_count -= 1;
1207                if self.bit_count == 0 {
1208                    let byte = (self.bottom >> 24) as u8;
1209                    self.out.push(byte);
1210                    self.bottom &= (1 << 24) - 1;
1211                    self.bit_count = 8;
1212                }
1213            }
1214        }
1215
1216        fn write_literal(&mut self, value: u32, num_bits: u32) {
1217            for i in (0..num_bits).rev() {
1218                let bit = ((value >> i) & 1) == 1;
1219                self.write_bool(128, bit);
1220            }
1221        }
1222
1223        /// Convenience for the tests: emit a token_prob_update()
1224        /// sub-block whose every update_flag is 0 (no probability
1225        /// updates). The flag at position [i][j][k][t] is coded at
1226        /// `COEFF_UPDATE_PROBS[i][j][k][t]` per §13.4 — most are 255,
1227        /// so a `false` flag consumes only a fraction of a bit.
1228        fn write_empty_token_prob_update(&mut self) {
1229            for plane in &COEFF_UPDATE_PROBS {
1230                for band in plane {
1231                    for ctx in band {
1232                        for &prob in ctx {
1233                            self.write_bool(prob, false);
1234                        }
1235                    }
1236                }
1237            }
1238        }
1239
1240        /// Convenience for the tests: emit an `mv_prob_update()`
1241        /// sub-block (§17.2) whose every F flag is 0. Each F is read
1242        /// against the per-position `MV_UPDATE_PROBS` entry — most of
1243        /// those are 250+, so a `false` flag is nearly free.
1244        fn write_empty_mv_prob_update(&mut self) {
1245            for ctx in &MV_UPDATE_PROBS {
1246                for &prob in ctx {
1247                    self.write_bool(prob, false);
1248                }
1249            }
1250        }
1251
1252        fn finish(mut self) -> Vec<u8> {
1253            let c = self.bit_count;
1254            let mut v = self.bottom;
1255            if v & (1u32 << (32 - c)) != 0 {
1256                let mut i = self.out.len();
1257                while i > 0 {
1258                    i -= 1;
1259                    if self.out[i] == 255 {
1260                        self.out[i] = 0;
1261                    } else {
1262                        self.out[i] = self.out[i].wrapping_add(1);
1263                        break;
1264                    }
1265                }
1266            }
1267            v <<= c & 7;
1268            let mut c_shift = c >> 3;
1269            while c_shift > 0 {
1270                v <<= 8;
1271                c_shift -= 1;
1272            }
1273            for _ in 0..4 {
1274                self.out.push((v >> 24) as u8);
1275                v <<= 8;
1276            }
1277            self.out
1278        }
1279    }
1280
1281    /// Encode the minimal key-frame coded header — every optional
1282    /// sub-block omitted — and round-trip it through `parse`.
1283    fn build_minimal_key_frame() -> Vec<u8> {
1284        let mut enc = TestEncoder::new();
1285        enc.write_bool(128, false); // color_space = 0
1286        enc.write_bool(128, false); // clamping_type = 0
1287        enc.write_bool(128, false); // segmentation_enabled = false
1288        enc.write_bool(128, false); // filter_type = false
1289        enc.write_literal(0, 6); // loop_filter_level = 0
1290        enc.write_literal(0, 3); // sharpness_level = 0
1291        enc.write_bool(128, false); // loop_filter_adj_enable = false
1292        enc.write_literal(0, 2); // log2_nbr_of_dct_partitions = 0
1293        enc.write_literal(4, 7); // y_ac_qi = 4
1294        for _ in 0..5 {
1295            enc.write_bool(128, false); // each delta-present flag = 0
1296        }
1297        enc.write_bool(128, true); // refresh_entropy_probs = true
1298        enc.write_empty_token_prob_update();
1299        enc.write_bool(128, false); // mb_no_skip_coeff = false
1300        enc.finish()
1301    }
1302
1303    #[test]
1304    fn minimal_key_frame_round_trips() {
1305        let buf = build_minimal_key_frame();
1306        let hdr = Vp8CodedHeader::parse(&buf, true).unwrap();
1307        assert_eq!(hdr.color_space, Some(false));
1308        assert_eq!(hdr.clamping_type, Some(false));
1309        assert!(!hdr.segmentation_enabled);
1310        assert!(hdr.update_segmentation.is_none());
1311        assert!(!hdr.filter_type);
1312        assert_eq!(hdr.loop_filter_level, 0);
1313        assert_eq!(hdr.sharpness_level, 0);
1314        assert!(!hdr.mb_lf_adjustments.loop_filter_adj_enable);
1315        assert!(!hdr.mb_lf_adjustments.mode_ref_lf_delta_update);
1316        assert_eq!(hdr.log2_nbr_of_dct_partitions, 0);
1317        assert_eq!(hdr.nbr_of_dct_partitions, 1);
1318        assert_eq!(hdr.quant_indices.y_ac_qi, 4);
1319        assert_eq!(hdr.quant_indices.y_dc_delta, None);
1320        assert_eq!(hdr.quant_indices.uv_ac_delta, None);
1321        assert!(hdr.refresh_entropy_probs);
1322        assert_eq!(hdr.refresh_golden_frame, None);
1323        assert_eq!(hdr.refresh_alternate_frame, None);
1324        assert_eq!(hdr.refresh_last, None);
1325        assert!(!hdr.mb_no_skip_coeff);
1326        assert_eq!(hdr.prob_skip_false, None);
1327    }
1328
1329    #[test]
1330    fn key_frame_filter_and_partition_fields_round_trip() {
1331        let mut enc = TestEncoder::new();
1332        enc.write_bool(128, false); // color_space
1333        enc.write_bool(128, true); // clamping_type
1334        enc.write_bool(128, false); // segmentation_enabled
1335        enc.write_bool(128, true); // filter_type = simple
1336        enc.write_literal(63, 6); // loop_filter_level = 63 (6-bit max)
1337        enc.write_literal(7, 3); // sharpness_level = 7 (3-bit max)
1338        enc.write_bool(128, false); // loop_filter_adj_enable = false
1339        enc.write_literal(3, 2); // log2_nbr_of_dct_partitions = 3 → 8 parts
1340        enc.write_literal(127, 7); // y_ac_qi = 127 (7-bit max)
1341        for _ in 0..5 {
1342            enc.write_bool(128, false);
1343        }
1344        enc.write_bool(128, false); // refresh_entropy_probs
1345        enc.write_empty_token_prob_update();
1346        enc.write_bool(128, true); // mb_no_skip_coeff
1347        enc.write_literal(0xab, 8); // prob_skip_false = 0xab
1348        let buf = enc.finish();
1349
1350        let hdr = Vp8CodedHeader::parse(&buf, true).unwrap();
1351        assert_eq!(hdr.clamping_type, Some(true));
1352        assert!(hdr.filter_type);
1353        assert_eq!(hdr.loop_filter_level, 63);
1354        assert_eq!(hdr.sharpness_level, 7);
1355        assert_eq!(hdr.log2_nbr_of_dct_partitions, 3);
1356        assert_eq!(hdr.nbr_of_dct_partitions, 8);
1357        assert_eq!(hdr.quant_indices.y_ac_qi, 127);
1358        assert!(!hdr.refresh_entropy_probs);
1359        assert!(hdr.mb_no_skip_coeff);
1360        assert_eq!(hdr.prob_skip_false, Some(0xab));
1361    }
1362
1363    #[test]
1364    fn mb_lf_adjustments_full_block_round_trips() {
1365        // loop_filter_adj_enable = 1, mode_ref_lf_delta_update = 1,
1366        // with the eight delta-update flags carrying a mix of
1367        // present-with-value and absent entries that exercise the
1368        // sign-bit encoding.
1369        let mut enc = TestEncoder::new();
1370        enc.write_bool(128, false); // color_space
1371        enc.write_bool(128, false); // clamping_type
1372        enc.write_bool(128, false); // segmentation_enabled
1373        enc.write_bool(128, false); // filter_type
1374        enc.write_literal(0, 6); // lf_level
1375        enc.write_literal(0, 3); // sharpness
1376        enc.write_bool(128, true); // loop_filter_adj_enable = true
1377        enc.write_bool(128, true); // mode_ref_lf_delta_update = true
1378        // ref_frame deltas: (+1, none, -2, +5)
1379        enc.write_bool(128, true); // present
1380        enc.write_literal(1, 6);
1381        enc.write_bool(128, false); // sign +
1382        enc.write_bool(128, false); // not present
1383        enc.write_bool(128, true);
1384        enc.write_literal(2, 6);
1385        enc.write_bool(128, true); // sign -
1386        enc.write_bool(128, true);
1387        enc.write_literal(5, 6);
1388        enc.write_bool(128, false);
1389        // mb_mode deltas: (none, +3, -1, none)
1390        enc.write_bool(128, false);
1391        enc.write_bool(128, true);
1392        enc.write_literal(3, 6);
1393        enc.write_bool(128, false);
1394        enc.write_bool(128, true);
1395        enc.write_literal(1, 6);
1396        enc.write_bool(128, true);
1397        enc.write_bool(128, false);
1398        enc.write_literal(0, 2); // log2_dct_parts
1399        enc.write_literal(0, 7); // y_ac_qi
1400        for _ in 0..5 {
1401            enc.write_bool(128, false);
1402        }
1403        enc.write_bool(128, false); // refresh_entropy_probs
1404        enc.write_empty_token_prob_update();
1405        enc.write_bool(128, false); // mb_no_skip_coeff
1406        let buf = enc.finish();
1407
1408        let hdr = Vp8CodedHeader::parse(&buf, true).unwrap();
1409        let lf = hdr.mb_lf_adjustments;
1410        assert!(lf.loop_filter_adj_enable);
1411        assert!(lf.mode_ref_lf_delta_update);
1412        assert_eq!(
1413            lf.ref_frame_delta_update,
1414            [Some(1), None, Some(-2), Some(5)]
1415        );
1416        assert_eq!(lf.mb_mode_delta_update, [None, Some(3), Some(-1), None]);
1417    }
1418
1419    #[test]
1420    fn update_segmentation_block_round_trips() {
1421        // segmentation_enabled = true, both sub-updates exercised:
1422        // - quantizer deltas: (+10, none, none, -20)
1423        // - lf deltas:        (none, +5, -3, none)
1424        // - segment_prob:     (255, none, 0)
1425        // - segment_feature_mode_absolute = true
1426        let mut enc = TestEncoder::new();
1427        enc.write_bool(128, false); // color_space
1428        enc.write_bool(128, false); // clamping_type
1429        enc.write_bool(128, true); // segmentation_enabled = true
1430        // update_segmentation():
1431        enc.write_bool(128, true); // update_mb_segmentation_map = 1
1432        enc.write_bool(128, true); // update_segment_feature_data = 1
1433        enc.write_bool(128, true); // segment_feature_mode = 1 (absolute)
1434        // quantizer_update[0..4]:
1435        enc.write_bool(128, true);
1436        enc.write_literal(10, 7);
1437        enc.write_bool(128, false); // +10
1438        enc.write_bool(128, false); // absent
1439        enc.write_bool(128, false); // absent
1440        enc.write_bool(128, true);
1441        enc.write_literal(20, 7);
1442        enc.write_bool(128, true); // -20
1443        // loop_filter_update[0..4]:
1444        enc.write_bool(128, false);
1445        enc.write_bool(128, true);
1446        enc.write_literal(5, 6);
1447        enc.write_bool(128, false); // +5
1448        enc.write_bool(128, true);
1449        enc.write_literal(3, 6);
1450        enc.write_bool(128, true); // -3
1451        enc.write_bool(128, false);
1452        // segment_prob[0..3] (update_mb_segmentation_map=1 so this fires):
1453        enc.write_bool(128, true);
1454        enc.write_literal(255, 8);
1455        enc.write_bool(128, false);
1456        enc.write_bool(128, true);
1457        enc.write_literal(0, 8);
1458
1459        // Remaining required fields after update_segmentation():
1460        enc.write_bool(128, false); // filter_type
1461        enc.write_literal(0, 6); // lf_level
1462        enc.write_literal(0, 3); // sharpness
1463        enc.write_bool(128, false); // lf_adj_enable
1464        enc.write_literal(0, 2); // log2_dct_parts
1465        enc.write_literal(0, 7); // y_ac_qi
1466        for _ in 0..5 {
1467            enc.write_bool(128, false);
1468        }
1469        enc.write_bool(128, false); // refresh_entropy_probs
1470        enc.write_empty_token_prob_update();
1471        enc.write_bool(128, false); // mb_no_skip_coeff
1472        let buf = enc.finish();
1473
1474        let hdr = Vp8CodedHeader::parse(&buf, true).unwrap();
1475        assert!(hdr.segmentation_enabled);
1476        let seg = hdr.update_segmentation.unwrap();
1477        assert!(seg.update_mb_segmentation_map);
1478        assert!(seg.update_segment_feature_data);
1479        assert!(seg.segment_feature_mode_absolute);
1480        assert_eq!(seg.quantizer_update, [Some(10), None, None, Some(-20)]);
1481        assert_eq!(seg.loop_filter_update, [None, Some(5), Some(-3), None]);
1482        assert_eq!(seg.segment_prob, [Some(255), None, Some(0)]);
1483    }
1484
1485    #[test]
1486    fn quant_indices_all_deltas_present() {
1487        // y_ac_qi = 64, deltas = (+1, -2, +15, -15, +0)
1488        let mut enc = TestEncoder::new();
1489        enc.write_bool(128, false); // color_space
1490        enc.write_bool(128, false); // clamping_type
1491        enc.write_bool(128, false); // segmentation_enabled
1492        enc.write_bool(128, false); // filter_type
1493        enc.write_literal(0, 6); // lf_level
1494        enc.write_literal(0, 3); // sharpness
1495        enc.write_bool(128, false); // lf_adj_enable
1496        enc.write_literal(0, 2); // log2_dct_parts
1497        enc.write_literal(64, 7); // y_ac_qi
1498        // y_dc_delta = +1
1499        enc.write_bool(128, true);
1500        enc.write_literal(1, 4);
1501        enc.write_bool(128, false);
1502        // y2_dc_delta = -2
1503        enc.write_bool(128, true);
1504        enc.write_literal(2, 4);
1505        enc.write_bool(128, true);
1506        // y2_ac_delta = +15
1507        enc.write_bool(128, true);
1508        enc.write_literal(15, 4);
1509        enc.write_bool(128, false);
1510        // uv_dc_delta = -15
1511        enc.write_bool(128, true);
1512        enc.write_literal(15, 4);
1513        enc.write_bool(128, true);
1514        // uv_ac_delta = +0
1515        enc.write_bool(128, true);
1516        enc.write_literal(0, 4);
1517        enc.write_bool(128, false);
1518
1519        enc.write_bool(128, false); // refresh_entropy_probs
1520        enc.write_empty_token_prob_update();
1521        enc.write_bool(128, false); // mb_no_skip_coeff
1522        let buf = enc.finish();
1523
1524        let hdr = Vp8CodedHeader::parse(&buf, true).unwrap();
1525        assert_eq!(hdr.quant_indices.y_ac_qi, 64);
1526        assert_eq!(hdr.quant_indices.y_dc_delta, Some(1));
1527        assert_eq!(hdr.quant_indices.y2_dc_delta, Some(-2));
1528        assert_eq!(hdr.quant_indices.y2_ac_delta, Some(15));
1529        assert_eq!(hdr.quant_indices.uv_dc_delta, Some(-15));
1530        assert_eq!(hdr.quant_indices.uv_ac_delta, Some(0));
1531    }
1532
1533    #[test]
1534    fn interframe_refresh_block_full_path() {
1535        // refresh_golden_frame = 0 → copy_buffer_to_golden present
1536        // refresh_alternate_frame = 1 → no copy_buffer_to_alternate
1537        // sign_bias_golden = 1, sign_bias_alternate = 0
1538        // refresh_entropy_probs = 0
1539        // refresh_last = 1
1540        // Tail: prob_intra/last/gf = 17/130/240, no intra-mode prob
1541        // updates, no MV prob updates.
1542        let mut enc = TestEncoder::new();
1543        // Inter frame: no color_space / clamping_type.
1544        enc.write_bool(128, false); // segmentation_enabled
1545        enc.write_bool(128, false); // filter_type
1546        enc.write_literal(10, 6); // lf_level
1547        enc.write_literal(2, 3); // sharpness
1548        enc.write_bool(128, false); // lf_adj_enable
1549        enc.write_literal(1, 2); // log2_dct_parts = 1 → 2 parts
1550        enc.write_literal(8, 7); // y_ac_qi
1551        for _ in 0..5 {
1552            enc.write_bool(128, false);
1553        }
1554        // Inter-frame refresh ladder:
1555        enc.write_bool(128, false); // refresh_golden_frame = 0
1556        enc.write_bool(128, true); // refresh_alternate_frame = 1
1557        enc.write_literal(2, 2); // copy_buffer_to_golden = 2 (alt → gold)
1558        // (no copy_buffer_to_alternate because refresh_alt = 1)
1559        enc.write_bool(128, true); // sign_bias_golden
1560        enc.write_bool(128, false); // sign_bias_alternate
1561        enc.write_bool(128, false); // refresh_entropy_probs
1562        enc.write_bool(128, true); // refresh_last
1563        enc.write_empty_token_prob_update();
1564        enc.write_bool(128, true); // mb_no_skip_coeff
1565        enc.write_literal(200, 8); // prob_skip_false
1566        enc.write_literal(17, 8); // prob_intra
1567        enc.write_literal(130, 8); // prob_last
1568        enc.write_literal(240, 8); // prob_gf
1569        enc.write_bool(128, false); // intra_y_mode F = 0
1570        enc.write_bool(128, false); // intra_uv_mode F = 0
1571        enc.write_empty_mv_prob_update();
1572        let buf = enc.finish();
1573
1574        let hdr = Vp8CodedHeader::parse(&buf, false).unwrap();
1575        assert_eq!(hdr.color_space, None);
1576        assert_eq!(hdr.clamping_type, None);
1577        assert_eq!(hdr.loop_filter_level, 10);
1578        assert_eq!(hdr.sharpness_level, 2);
1579        assert_eq!(hdr.nbr_of_dct_partitions, 2);
1580        assert_eq!(hdr.refresh_golden_frame, Some(false));
1581        assert_eq!(hdr.refresh_alternate_frame, Some(true));
1582        assert_eq!(hdr.copy_buffer_to_golden, Some(2));
1583        assert_eq!(hdr.copy_buffer_to_alternate, None);
1584        assert_eq!(hdr.sign_bias_golden, Some(true));
1585        assert_eq!(hdr.sign_bias_alternate, Some(false));
1586        assert!(!hdr.refresh_entropy_probs);
1587        assert_eq!(hdr.refresh_last, Some(true));
1588        assert!(hdr.mb_no_skip_coeff);
1589        assert_eq!(hdr.prob_skip_false, Some(200));
1590        // §9.10 tail (this round):
1591        assert_eq!(hdr.prob_intra, Some(17));
1592        assert_eq!(hdr.prob_last, Some(130));
1593        assert_eq!(hdr.prob_gf, Some(240));
1594        assert_eq!(hdr.intra_y_mode_prob_update, None);
1595        assert_eq!(hdr.intra_uv_mode_prob_update, None);
1596        let mv = hdr.mv_prob_update.unwrap();
1597        assert!(mv[0].iter().all(|s| s.is_none()));
1598        assert!(mv[1].iter().all(|s| s.is_none()));
1599    }
1600
1601    #[test]
1602    fn mb_no_skip_coeff_false_omits_prob_skip_false() {
1603        let buf = build_minimal_key_frame();
1604        let hdr = Vp8CodedHeader::parse(&buf, true).unwrap();
1605        assert!(!hdr.mb_no_skip_coeff);
1606        assert_eq!(hdr.prob_skip_false, None);
1607    }
1608
1609    #[test]
1610    fn input_too_short_surfaces_bool_decoder_error() {
1611        // Empty input → BoolDecoder::init rejects it.
1612        let err = Vp8CodedHeader::parse(&[], true).unwrap_err();
1613        assert!(matches!(
1614            err,
1615            CodedHeaderError::BoolDecoder(BoolDecoderError::InputTooShort)
1616        ));
1617        // One byte is also too short.
1618        let err = Vp8CodedHeader::parse(&[0x00], true).unwrap_err();
1619        assert!(matches!(
1620            err,
1621            CodedHeaderError::BoolDecoder(BoolDecoderError::InputTooShort)
1622        ));
1623    }
1624
1625    #[test]
1626    fn parses_real_tiny_fixture_partition() {
1627        // Re-use the 16x16 key frame from docs/video/vp8/fixtures/
1628        // tiny-i-only-16x16/input.ivf. The IVF frame payload starts
1629        // at file offset 0x2c. The 10-byte uncompressed header sits at
1630        // 0x2c..0x36 (parsed in frame_header.rs tests); the bool-coded
1631        // partition is the next first_partition_size=23 bytes —
1632        // i.e. file offset 0x36..0x4d.
1633        //
1634        // Expected values per docs/video/vp8/fixtures/
1635        // tiny-i-only-16x16/trace.txt line 1:
1636        //   filter_simple=0, filter_level=1, filter_sharpness=0,
1637        //   lf_delta_enabled=1, num_partitions=1, seg_enabled=0,
1638        //   mbskip_enabled=1, prob_skip=255, qi_y_ac=4,
1639        //   all qi_*_d=0, update_probs=1.
1640        let partition: [u8; 23] = [
1641            0x00, 0x47, 0x08, 0x85, 0x85, 0x88, 0x85, 0x84, 0x88, 0x02, 0x02, 0x02, 0x75, 0xaa,
1642            0x03, 0xf8, 0x03, 0xfa, 0x02, 0x0d, 0x4d, 0x18, 0x00,
1643        ];
1644        let hdr = Vp8CodedHeader::parse(&partition, true).unwrap();
1645        // color_space and clamping_type are not in the trace listing —
1646        // §9.2 only defines color_space=0; clamping_type may be either
1647        // 0 or 1. We just confirm both bits decoded (i.e. didn't
1648        // collapse to None on this key frame).
1649        assert!(hdr.color_space.is_some());
1650        assert!(hdr.clamping_type.is_some());
1651        assert!(!hdr.segmentation_enabled);
1652        assert!(!hdr.filter_type, "filter_simple=0 per trace");
1653        assert_eq!(hdr.loop_filter_level, 1, "filter_level=1 per trace");
1654        assert_eq!(hdr.sharpness_level, 0, "filter_sharpness=0 per trace");
1655        assert!(
1656            hdr.mb_lf_adjustments.loop_filter_adj_enable,
1657            "lf_delta_enabled=1 per trace"
1658        );
1659        assert_eq!(
1660            hdr.log2_nbr_of_dct_partitions, 0,
1661            "num_partitions=1 per trace → log2=0"
1662        );
1663        assert_eq!(hdr.nbr_of_dct_partitions, 1);
1664        assert_eq!(hdr.quant_indices.y_ac_qi, 4, "qi_y_ac=4 per trace");
1665        assert_eq!(hdr.quant_indices.y_dc_delta, None, "qi_y_dc_d=0 per trace");
1666        assert_eq!(hdr.quant_indices.y2_dc_delta, None);
1667        assert_eq!(hdr.quant_indices.y2_ac_delta, None);
1668        assert_eq!(hdr.quant_indices.uv_dc_delta, None);
1669        assert_eq!(hdr.quant_indices.uv_ac_delta, None);
1670        assert!(hdr.refresh_entropy_probs, "update_probs=1 per trace");
1671        assert!(hdr.mb_no_skip_coeff, "mbskip_enabled=1 per trace");
1672        assert_eq!(hdr.prob_skip_false, Some(255), "prob_skip=255 per trace");
1673        // Key-frame §9.11 has no §9.10 tail — confirm every inter-only
1674        // field collapsed to None.
1675        assert_eq!(hdr.prob_intra, None);
1676        assert_eq!(hdr.prob_last, None);
1677        assert_eq!(hdr.prob_gf, None);
1678        assert_eq!(hdr.intra_y_mode_prob_update, None);
1679        assert_eq!(hdr.intra_uv_mode_prob_update, None);
1680        assert!(hdr.mv_prob_update.is_none());
1681    }
1682
1683    #[test]
1684    fn key_frame_omits_section_9_10_tail() {
1685        // Round 3's minimal key frame should still parse cleanly with
1686        // every §9.10 inter-only tail field absent.
1687        let buf = build_minimal_key_frame();
1688        let hdr = Vp8CodedHeader::parse(&buf, true).unwrap();
1689        assert_eq!(hdr.prob_intra, None);
1690        assert_eq!(hdr.prob_last, None);
1691        assert_eq!(hdr.prob_gf, None);
1692        assert_eq!(hdr.intra_y_mode_prob_update, None);
1693        assert_eq!(hdr.intra_uv_mode_prob_update, None);
1694        assert!(hdr.mv_prob_update.is_none());
1695    }
1696
1697    /// Build a minimal interframe coded header — no segmentation, no
1698    /// LF adjustments, every refresh flag 0, no token-prob updates,
1699    /// `mb_no_skip_coeff = 0` so `prob_skip_false` is omitted. Tail
1700    /// parameters (prob_intra/last/gf, two F gates, mv block) are
1701    /// emitted by the caller as needed.
1702    fn write_inter_prefix_through_skip_block(enc: &mut TestEncoder) {
1703        enc.write_bool(128, false); // segmentation_enabled
1704        enc.write_bool(128, false); // filter_type
1705        enc.write_literal(0, 6); // lf_level
1706        enc.write_literal(0, 3); // sharpness
1707        enc.write_bool(128, false); // lf_adj_enable
1708        enc.write_literal(0, 2); // log2_dct_parts
1709        enc.write_literal(0, 7); // y_ac_qi
1710        for _ in 0..5 {
1711            enc.write_bool(128, false); // each delta-present flag = 0
1712        }
1713        // Inter-frame refresh ladder — every refresh / sign_bias / etc.
1714        // flag = 0; copy_buffer_to_* = 0 (no copy).
1715        enc.write_bool(128, false); // refresh_golden_frame
1716        enc.write_bool(128, false); // refresh_alternate_frame
1717        enc.write_literal(0, 2); // copy_buffer_to_golden = 0 (no copy)
1718        enc.write_literal(0, 2); // copy_buffer_to_alternate = 0
1719        enc.write_bool(128, false); // sign_bias_golden
1720        enc.write_bool(128, false); // sign_bias_alternate
1721        enc.write_bool(128, false); // refresh_entropy_probs
1722        enc.write_bool(128, false); // refresh_last
1723        enc.write_empty_token_prob_update();
1724        enc.write_bool(128, false); // mb_no_skip_coeff = 0 → prob_skip_false omitted
1725    }
1726
1727    #[test]
1728    fn interframe_prob_intra_last_gf_round_trip() {
1729        // Exercises the three L(8) reference-selection probabilities
1730        // at the head of the new tail. Pick distinct values that span
1731        // the L(8) range.
1732        let mut enc = TestEncoder::new();
1733        write_inter_prefix_through_skip_block(&mut enc);
1734        enc.write_literal(0x00, 8); // prob_intra = 0
1735        enc.write_literal(0x80, 8); // prob_last = 128
1736        enc.write_literal(0xff, 8); // prob_gf = 255
1737        enc.write_bool(128, false); // intra_y_mode F = 0
1738        enc.write_bool(128, false); // intra_uv_mode F = 0
1739        enc.write_empty_mv_prob_update();
1740        let buf = enc.finish();
1741
1742        let hdr = Vp8CodedHeader::parse(&buf, false).unwrap();
1743        assert_eq!(hdr.prob_intra, Some(0));
1744        assert_eq!(hdr.prob_last, Some(128));
1745        assert_eq!(hdr.prob_gf, Some(255));
1746    }
1747
1748    #[test]
1749    fn interframe_intra_y_mode_prob_update_full_block() {
1750        // F gate = 1 followed by the four §16.1 Y intra-mode probs
1751        // overridden from their {112, 86, 140, 37} defaults.
1752        let mut enc = TestEncoder::new();
1753        write_inter_prefix_through_skip_block(&mut enc);
1754        enc.write_literal(0, 8); // prob_intra
1755        enc.write_literal(0, 8); // prob_last
1756        enc.write_literal(0, 8); // prob_gf
1757        enc.write_bool(128, true); // intra_y_mode F = 1
1758        for &p in &[200u8, 100, 33, 250] {
1759            enc.write_literal(p as u32, 8);
1760        }
1761        enc.write_bool(128, false); // intra_uv_mode F = 0
1762        enc.write_empty_mv_prob_update();
1763        let buf = enc.finish();
1764
1765        let hdr = Vp8CodedHeader::parse(&buf, false).unwrap();
1766        assert_eq!(hdr.intra_y_mode_prob_update, Some([200, 100, 33, 250]));
1767        assert_eq!(hdr.intra_uv_mode_prob_update, None);
1768    }
1769
1770    #[test]
1771    fn interframe_intra_uv_mode_prob_update_full_block() {
1772        // F gate = 1 followed by the three §16.1 UV intra-mode probs.
1773        // Defaults are {162, 101, 204}; pick three different values.
1774        let mut enc = TestEncoder::new();
1775        write_inter_prefix_through_skip_block(&mut enc);
1776        enc.write_literal(0, 8); // prob_intra
1777        enc.write_literal(0, 8); // prob_last
1778        enc.write_literal(0, 8); // prob_gf
1779        enc.write_bool(128, false); // intra_y_mode F = 0
1780        enc.write_bool(128, true); // intra_uv_mode F = 1
1781        for &p in &[10u8, 20, 30] {
1782            enc.write_literal(p as u32, 8);
1783        }
1784        enc.write_empty_mv_prob_update();
1785        let buf = enc.finish();
1786
1787        let hdr = Vp8CodedHeader::parse(&buf, false).unwrap();
1788        assert_eq!(hdr.intra_y_mode_prob_update, None);
1789        assert_eq!(hdr.intra_uv_mode_prob_update, Some([10, 20, 30]));
1790    }
1791
1792    #[test]
1793    fn interframe_mv_prob_update_round_trip() {
1794        // Exercise the §17.2 per-position F? P(7) reconstruction. Set
1795        // a non-zero P(7) on row[0] and a zero P(7) on column[18] to
1796        // hit both branches of `x ? x << 1 : 1` — and leave a couple
1797        // of positions un-updated to confirm None passthrough.
1798        let mut enc = TestEncoder::new();
1799        write_inter_prefix_through_skip_block(&mut enc);
1800        enc.write_literal(0, 8); // prob_intra
1801        enc.write_literal(0, 8); // prob_last
1802        enc.write_literal(0, 8); // prob_gf
1803        enc.write_bool(128, false); // intra_y_mode F = 0
1804        enc.write_bool(128, false); // intra_uv_mode F = 0
1805
1806        // Row context (i = 0). 19 F? P(7) pairs.
1807        for (j, &update_prob) in MV_UPDATE_PROBS[0].iter().enumerate() {
1808            if j == 0 {
1809                // Non-zero P(7) → reconstructed = 50 << 1 = 100.
1810                enc.write_bool(update_prob, true);
1811                enc.write_literal(50, 7);
1812            } else if j == 5 {
1813                // P(7) = 0 → reconstructed = 1 (the spec's
1814                // `x ? x<<1 : 1` clause).
1815                enc.write_bool(update_prob, true);
1816                enc.write_literal(0, 7);
1817            } else {
1818                enc.write_bool(update_prob, false);
1819            }
1820        }
1821        // Column context (i = 1).
1822        for (j, &update_prob) in MV_UPDATE_PROBS[1].iter().enumerate() {
1823            if j == MV_PROB_COUNT - 1 {
1824                // Non-zero P(7) → 127 << 1 = 254 (max representable
1825                // via this encoding).
1826                enc.write_bool(update_prob, true);
1827                enc.write_literal(127, 7);
1828            } else {
1829                enc.write_bool(update_prob, false);
1830            }
1831        }
1832        let buf = enc.finish();
1833
1834        let hdr = Vp8CodedHeader::parse(&buf, false).unwrap();
1835        let mv = hdr.mv_prob_update.unwrap();
1836        // Row asserts.
1837        assert_eq!(mv[0][0], Some(100));
1838        assert_eq!(mv[0][1], None);
1839        assert_eq!(mv[0][5], Some(1));
1840        for (j, &slot) in mv[0].iter().enumerate() {
1841            if j != 0 && j != 5 {
1842                assert!(slot.is_none(), "row[{j}] should be None");
1843            }
1844        }
1845        // Column asserts.
1846        assert_eq!(mv[1][MV_PROB_COUNT - 1], Some(254));
1847        for (j, &slot) in mv[1].iter().enumerate().take(MV_PROB_COUNT - 1) {
1848            assert!(slot.is_none(), "col[{j}] should be None");
1849        }
1850    }
1851
1852    #[test]
1853    fn mv_default_context_matches_spec_listing() {
1854        // §17.2 default_mv_context[2] — sanity-check the transcribed
1855        // table against the spec's listed values so a transcription
1856        // typo would surface here rather than as a downstream
1857        // mis-decode.
1858        // Row component:
1859        assert_eq!(DEFAULT_MV_CONTEXT[0][0], 162); // is_short
1860        assert_eq!(DEFAULT_MV_CONTEXT[0][1], 128); // sign
1861        assert_eq!(DEFAULT_MV_CONTEXT[0][2], 225); // short tree [0]
1862        assert_eq!(DEFAULT_MV_CONTEXT[0][8], 156); // short tree [6]
1863        assert_eq!(DEFAULT_MV_CONTEXT[0][9], 128); // bit 0
1864        assert_eq!(DEFAULT_MV_CONTEXT[0][18], 254); // bit 9
1865        // Column component:
1866        assert_eq!(DEFAULT_MV_CONTEXT[1][0], 164); // is_short
1867        assert_eq!(DEFAULT_MV_CONTEXT[1][1], 128); // sign
1868        assert_eq!(DEFAULT_MV_CONTEXT[1][2], 204); // short tree [0]
1869        assert_eq!(DEFAULT_MV_CONTEXT[1][8], 228); // short tree [6]
1870        assert_eq!(DEFAULT_MV_CONTEXT[1][9], 128); // bit 0
1871        assert_eq!(DEFAULT_MV_CONTEXT[1][18], 254); // bit 9
1872        // Update-probs table sanity.
1873        assert_eq!(MV_UPDATE_PROBS[0][0], 237);
1874        assert_eq!(MV_UPDATE_PROBS[0][18], 254);
1875        assert_eq!(MV_UPDATE_PROBS[1][0], 231);
1876        assert_eq!(MV_UPDATE_PROBS[1][18], 254);
1877    }
1878
1879    /// Round-291 equivalence anchor: the zipped-iterator
1880    /// `parse_token_prob_update` must decode byte-identically to a
1881    /// verbatim copy of the pre-291 4-level-indexed reference loop, over
1882    /// a payload that exercises both the `None` (flag-only) and `Some`
1883    /// (flag + `L(8)` literal) branches. Encodes each of the 1056 §13.4
1884    /// positions at its `COEFF_UPDATE_PROBS[i][j][k][t]` probability — a
1885    /// deterministic minority `Some(prob)` so the literal-read branch
1886    /// fires across all four planes — and asserts the production parser
1887    /// reproduces both the reference decode and the intended payload.
1888    fn reference_parse_token_prob_update_indexed(
1889        dec: &mut BoolDecoder<'_>,
1890    ) -> Result<TokenProbUpdates, BoolDecoderError> {
1891        let mut out: TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
1892        for (i, plane) in out.iter_mut().enumerate() {
1893            for (j, band) in plane.iter_mut().enumerate() {
1894                for (k, ctx) in band.iter_mut().enumerate() {
1895                    for (t, slot) in ctx.iter_mut().enumerate() {
1896                        let present = dec.read_bool(COEFF_UPDATE_PROBS[i][j][k][t])?;
1897                        *slot = if present {
1898                            Some(dec.read_literal(8)? as u8)
1899                        } else {
1900                            None
1901                        };
1902                    }
1903                }
1904            }
1905        }
1906        Ok(out)
1907    }
1908
1909    #[test]
1910    fn parse_token_prob_update_matches_indexed_reference() {
1911        // Build a mixed Some/None payload deterministically.
1912        let mut intended: TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
1913        let mut salt: u32 = 1;
1914        for (i, plane) in intended.iter_mut().enumerate() {
1915            for (j, band) in plane.iter_mut().enumerate() {
1916                for (k, ctx) in band.iter_mut().enumerate() {
1917                    for (t, slot) in ctx.iter_mut().enumerate() {
1918                        salt = salt.wrapping_mul(1103515245).wrapping_add(12345);
1919                        // ~1 in 5 positions carries a replacement.
1920                        if (i + j + k + t + (salt >> 16) as usize).is_multiple_of(5) {
1921                            *slot = Some(((salt >> 8) & 0xFF) as u8);
1922                        }
1923                    }
1924                }
1925            }
1926        }
1927
1928        // Encode the payload at the §13.4 per-position probabilities.
1929        let mut enc = TestEncoder::new();
1930        for (i, plane) in intended.iter().enumerate() {
1931            for (j, band) in plane.iter().enumerate() {
1932                for (k, ctx) in band.iter().enumerate() {
1933                    for (t, slot) in ctx.iter().enumerate() {
1934                        let p = COEFF_UPDATE_PROBS[i][j][k][t];
1935                        match slot {
1936                            Some(prob) => {
1937                                enc.write_bool(p, true);
1938                                enc.write_literal(*prob as u32, 8);
1939                            }
1940                            None => enc.write_bool(p, false),
1941                        }
1942                    }
1943                }
1944            }
1945        }
1946        // Trailing bit so the final renormalisation has input to pull.
1947        enc.write_bool(128, false);
1948        let bytes = enc.finish();
1949
1950        let mut dec_prod = BoolDecoder::init(&bytes).unwrap();
1951        let produced = parse_token_prob_update(&mut dec_prod).unwrap();
1952
1953        let mut dec_ref = BoolDecoder::init(&bytes).unwrap();
1954        let reference = reference_parse_token_prob_update_indexed(&mut dec_ref).unwrap();
1955
1956        assert_eq!(
1957            produced, reference,
1958            "zipped loop must match the 4-level-indexed reference loop"
1959        );
1960        assert_eq!(
1961            produced, intended,
1962            "decode must recover the intended payload"
1963        );
1964        // Both decoders must have consumed exactly the same input.
1965        assert_eq!(
1966            dec_prod.remaining_input(),
1967            dec_ref.remaining_input(),
1968            "both parsers must leave the decoder at the same stream position"
1969        );
1970    }
1971}