Skip to main content

oxideav_vp8/
encoder.rs

1//! VP8 encoder — Phase 1 (RFC 6386 §9 frame-header writers + the
2//! all-zero-quantization "silent keyframe" path).
3//!
4//! This module is the bitstream-formatting half of the VP8 encoder.
5//! It does **not** perform rate-distortion search, mode selection,
6//! quantization-step optimisation, or pixel-level encoding decisions
7//! of any kind. What it provides:
8//!
9//! 1. [`BoolEncoder`] — a Rust port of the RFC 6386 §7.3
10//!    `bool_encoder` / `write_bool` / `flush_bool_encoder` C listing
11//!    that the RFC embeds inline. The encoder is validated by
12//!    round-tripping every flag through [`crate::bool_decoder`] in
13//!    this crate (see the tests at the bottom of this file).
14//!
15//! 2. The §9.1 / §9.3 / §9.4 / §9.5 / §9.6 / §9.7 / §13 / §9.10 / §9.11
16//!    frame-header writer subroutines, each exposed as a small
17//!    callable so the higher-level encoder rounds can compose them
18//!    against a parameter struct rather than having one monolithic
19//!    `encode_frame` body. The four called out by the round goal are:
20//!
21//!    * [`write_frame_tag`] — §9.1 3-byte tag + key-frame start code
22//!      `0x9d 0x01 0x2a` + 14-bit width + 2-bit horizontal scale +
23//!      14-bit height + 2-bit vertical scale.
24//!    * [`write_segment_update_flags`] — §9.3 segment-update sub-block.
25//!      Phase 1 supports `segmentation_enabled = false` only; the
26//!      stream emits the single `L(1) = 0` toggle and skips the rest.
27//!    * [`write_loop_filter`] — §9.4 `filter_type` / `loop_filter_level`
28//!      / `sharpness_level` plus the `mb_lf_adjustments()` sub-block.
29//!      Phase 1 supports `loop_filter_adj_enable = false` only.
30//!    * [`write_token_partition_count`] — §9.5 `log2_nbr_of_dct_partitions`
31//!      (2 bits, encoding 1/2/4/8 partitions).
32//!
33//! 3. [`encode_silent_keyframe`] — a trivial all-zero-quantizer
34//!    keyframe emitter. Every macroblock is coded as
35//!    `mb_skip_coeff = 1` so the DCT partition carries no token data;
36//!    the macroblock prediction layer picks `DC_PRED` for both luma
37//!    and chroma; the §9.4 loop filter is set to level 0 (whole-frame
38//!    skip per the §15 page-84 rule). The emitted stream is a
39//!    structurally-valid VP8 frame that the crate's own decoder
40//!    consumes and that `ffmpeg -c:v vp8` accepts when wrapped in an
41//!    IVF container.
42//!
43//! # Out of scope for Phase 1
44//!
45//! * Rate-distortion-driven mode selection, vector search, transform
46//!   coefficient encoding. These will land in a later round once the
47//!   frame-header writers are solid.
48//! * Inter-frame encoding. The §16 inter path needs the §13 token
49//!   encoder + the §17 MV encoder + the §16 reference-frame management,
50//!   all of which are deferred to subsequent rounds.
51//! * Segmentation (`§9.3`'s `update_segmentation` non-trivial path) —
52//!   the writer only handles the "disabled" case.
53//! * Per-macroblock loop-filter deltas (§9.4's `mb_lf_adjustments`
54//!   non-trivial path) — same treatment.
55//!
56//! # Reference
57//!
58//! * RFC 6386 §7.3 (the `bool_encoder` C listing embedded in the RFC).
59//! * RFC 6386 §9.1 – §9.11 (the uncompressed + boolean-coded frame
60//!   header layouts).
61//! * RFC 6386 §11 (key-frame macroblock prediction records).
62
63use crate::coded_header::TokenProbUpdates;
64use crate::frame_header::KEY_FRAME_START_CODE;
65
66/// Errors surfaced by the encoder.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum EncodeError {
70    /// Visible width or height is zero or exceeds the 14-bit VP8 field
71    /// (`width > 0x3FFF` or `height > 0x3FFF`).
72    InvalidDimensions { width: u32, height: u32 },
73    /// `loop_filter_level` outside the 6-bit field (`> 63`).
74    LoopFilterLevelOutOfRange { value: u8 },
75    /// `sharpness_level` outside the 3-bit field (`> 7`).
76    SharpnessLevelOutOfRange { value: u8 },
77    /// `nbr_of_dct_partitions` is not one of the four legal values
78    /// (1 / 2 / 4 / 8) per §9.5.
79    InvalidDctPartitionCount { value: u8 },
80    /// `y_ac_qi` outside the 7-bit field (`> 127`) per §9.6.
81    QuantIndexOutOfRange { value: u8 },
82    /// First-partition payload exceeded the 19-bit field VP8 reserves
83    /// for it in §9.1 (`> 0x7_FFFF`). At the partition sizes Phase 1
84    /// emits this is unreachable, but the check sits at the boundary
85    /// for future encoder rounds that may push it.
86    FirstPartitionTooLarge { bytes: usize },
87    /// The §13 token-block encoder rejected a macroblock's residual
88    /// (a coefficient out of the §13.2 alphabet range). Surfaces the
89    /// underlying [`TokenEncodeError`].
90    Token(TokenEncodeError),
91    /// The §14.2 / §12.3 reconstruction orchestrator (the decoder's own,
92    /// reused to evolve neighbours) rejected the encoder's per-MB inputs.
93    /// Surfaces the underlying [`crate::reconstruct::ReconstructError`].
94    Reconstruct(crate::reconstruct::ReconstructError),
95    /// The reference frame supplied to a P-frame encode does not match
96    /// the source frame's macroblock-aligned dimensions
97    /// (`mb_cols * 16 × mb_rows * 16`). Surfaced by
98    /// [`encode_p_frame_zero_mv`].
99    ReferenceDimensionsMismatch {
100        /// `(width, height)` of the source frame's macroblock-aligned grid.
101        source: (u32, u32),
102        /// `(width, height)` of the reference [`crate::frame::KeyframePlanes`].
103        reference: (u32, u32),
104    },
105    /// Reserved for inter-mode picker fall-throughs. The Phase-11
106    /// `encode_p_frame_zero_mv` picker now emits all five §16.2
107    /// `mv_ref_tree` leaves (ZEROMV / NEARESTMV / NEARMV / NEWMV /
108    /// SPLITMV); this variant is retained for forward-compatibility with
109    /// a future picker that may surface an InterMode not handled by the
110    /// emit layer (e.g. an `Intra` fallback in a mixed-mode inter pass).
111    UnsupportedInterMode {
112        /// The resolved mode the picker handed the emit layer.
113        mode: crate::near_mv::InterMode,
114    },
115    /// `copy_buffer_to_golden` or `copy_buffer_to_alternate` was outside
116    /// the 2-bit field (`0..=2`) per §9.7. Surfaced by
117    /// [`encode_p_frame_multi_ref_with_refresh`] when its
118    /// [`RefreshControls`] argument fails validation.
119    InvalidCopyBufferSelector {
120        /// The §9.7 selector field whose value was out of range.
121        which: CopyBufferSelector,
122        /// The offending value (must be `0`, `1`, or `2`).
123        value: u8,
124    },
125    /// A §9.4 reference or mode `loop_filter_delta` value exceeded the
126    /// 6-bit-magnitude + 1-bit-sign field (`abs(value) > 63`). Surfaced
127    /// by [`LoopFilterDeltas::validate`] and
128    /// [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas`].
129    LoopFilterDeltaOutOfRange {
130        /// The §9.4 delta slot whose value was out of range.
131        which: LoopFilterDeltaSlot,
132        /// The offending signed value (must be `-63..=63`).
133        value: i16,
134    },
135}
136
137/// Names the two §9.7 `copy_buffer_to_*` selector fields so a rejected
138/// value in [`RefreshControls`] can report which one failed.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum CopyBufferSelector {
141    /// §9.7 `copy_buffer_to_golden` — 0 = none, 1 = copy `last_frame`,
142    /// 2 = copy `alt_ref_frame`.
143    Golden,
144    /// §9.7 `copy_buffer_to_alternate` — 0 = none, 1 = copy `last_frame`,
145    /// 2 = copy `golden_frame`.
146    Alternate,
147}
148
149/// Names the §9.4 per-reference + per-mode `loop_filter_delta` slots so
150/// a rejected value in [`LoopFilterDeltas`] can report which one failed.
151///
152/// The four reference slots are indexed by their §20.6 `ref_frame`
153/// order (`CURRENT_FRAME = 0`, `LAST_FRAME = 1`, `GOLDEN_FRAME = 2`,
154/// `ALTREF_FRAME = 3`); the four mode slots are indexed by the §20.6
155/// `mode_delta[]` order (`B_PRED = 0`, `ZERO_MV = 1`, `NEAREST/NEAR/NEW = 2`,
156/// `SPLIT_MV = 3`).
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum LoopFilterDeltaSlot {
159    /// §20.6 `ref_delta[CURRENT_FRAME]` — applied to intra-coded MBs.
160    RefCurrent,
161    /// §20.6 `ref_delta[LAST_FRAME]` — applied to inter MBs predicting
162    /// from `LAST`.
163    RefLast,
164    /// §20.6 `ref_delta[GOLDEN_FRAME]` — applied to inter MBs predicting
165    /// from `GOLDEN`.
166    RefGolden,
167    /// §20.6 `ref_delta[ALTREF_FRAME]` — applied to inter MBs predicting
168    /// from `ALTREF`.
169    RefAltref,
170    /// §20.6 `mode_delta[0]` — applied to intra MBs with `y_mode = B_PRED`.
171    ModeBpred,
172    /// §20.6 `mode_delta[1]` — applied to inter MBs with `y_mode = ZEROMV`.
173    ModeZeroMv,
174    /// §20.6 `mode_delta[2]` — applied to inter MBs with `y_mode` in
175    /// `{NEARESTMV, NEARMV, NEWMV}`.
176    ModeOtherMv,
177    /// §20.6 `mode_delta[3]` — applied to inter MBs with `y_mode = SPLITMV`.
178    ModeSplitMv,
179}
180
181impl core::fmt::Display for EncodeError {
182    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
183        match self {
184            EncodeError::InvalidDimensions { width, height } => write!(
185                f,
186                "vp8 encode: invalid frame dimensions {width}x{height} \
187                 (must be 1..=0x3FFF in both axes)"
188            ),
189            EncodeError::LoopFilterLevelOutOfRange { value } => write!(
190                f,
191                "vp8 encode: loop_filter_level={value} exceeds the 6-bit field (0..=63)"
192            ),
193            EncodeError::SharpnessLevelOutOfRange { value } => write!(
194                f,
195                "vp8 encode: sharpness_level={value} exceeds the 3-bit field (0..=7)"
196            ),
197            EncodeError::InvalidDctPartitionCount { value } => write!(
198                f,
199                "vp8 encode: nbr_of_dct_partitions={value} is not one of 1/2/4/8 (§9.5)"
200            ),
201            EncodeError::QuantIndexOutOfRange { value } => write!(
202                f,
203                "vp8 encode: y_ac_qi={value} exceeds the 7-bit field (0..=127)"
204            ),
205            EncodeError::FirstPartitionTooLarge { bytes } => write!(
206                f,
207                "vp8 encode: first-partition size {bytes} exceeds the 19-bit field (0..=0x7_FFFF)"
208            ),
209            EncodeError::Token(inner) => write!(f, "vp8 encode: {inner}"),
210            EncodeError::Reconstruct(inner) => write!(f, "vp8 encode: {inner}"),
211            EncodeError::ReferenceDimensionsMismatch { source, reference } => write!(
212                f,
213                "vp8 encode: P-frame source frame {}x{} (macroblock-aligned) does \
214                 not match the supplied reference frame {}x{}",
215                source.0, source.1, reference.0, reference.1
216            ),
217            EncodeError::UnsupportedInterMode { mode } => write!(
218                f,
219                "vp8 encode: inter-mode {mode:?} is not supported by the \
220                 Phase-11 ZEROMV / NEARESTMV / NEARMV / NEWMV / SPLITMV picker"
221            ),
222            EncodeError::InvalidCopyBufferSelector { which, value } => write!(
223                f,
224                "vp8 encode: copy_buffer_to_{} = {value} is outside the \
225                 2-bit field 0..=2 (§9.7)",
226                match which {
227                    CopyBufferSelector::Golden => "golden",
228                    CopyBufferSelector::Alternate => "alternate",
229                }
230            ),
231            EncodeError::LoopFilterDeltaOutOfRange { which, value } => write!(
232                f,
233                "vp8 encode: loop_filter_delta[{}] = {value} is outside the \
234                 §9.4 6-bit-magnitude + 1-bit-sign field (-63..=63)",
235                match which {
236                    LoopFilterDeltaSlot::RefCurrent => "ref_current",
237                    LoopFilterDeltaSlot::RefLast => "ref_last",
238                    LoopFilterDeltaSlot::RefGolden => "ref_golden",
239                    LoopFilterDeltaSlot::RefAltref => "ref_altref",
240                    LoopFilterDeltaSlot::ModeBpred => "mode_bpred",
241                    LoopFilterDeltaSlot::ModeZeroMv => "mode_zero_mv",
242                    LoopFilterDeltaSlot::ModeOtherMv => "mode_other_mv",
243                    LoopFilterDeltaSlot::ModeSplitMv => "mode_split_mv",
244                }
245            ),
246        }
247    }
248}
249
250impl std::error::Error for EncodeError {}
251
252/// VP8 boolean (range) encoder per RFC 6386 §7.3.
253///
254/// The structure mirrors the spec's `bool_encoder` C type one-for-one:
255/// `range`, `bottom`, and a per-position `bit_count` of remaining shifts
256/// before the next high-byte output. Encoded bytes accumulate in `out`.
257///
258/// Implements §7.3 of RFC 6386 (the `init_bool_encoder` /
259/// `write_bool` / `add_one_to_output` / `flush_bool_encoder`
260/// C listing the RFC embeds inline).
261#[derive(Debug, Default)]
262pub struct BoolEncoder {
263    out: Vec<u8>,
264    range: u32,
265    bottom: u32,
266    bit_count: i32,
267}
268
269impl BoolEncoder {
270    /// Construct an encoder with the §7.3 `init_bool_encoder` initial
271    /// state (`range = 255`, `bottom = 0`, `bit_count = 24`).
272    pub fn new() -> Self {
273        BoolEncoder {
274            out: Vec::new(),
275            range: 255,
276            bottom: 0,
277            bit_count: 24,
278        }
279    }
280
281    /// Encode one boolean against the §7.3 probability split formula.
282    /// `prob` is the (approximate) probability that `value` is `false`,
283    /// expressed as `prob / 256`.
284    ///
285    /// The §7.3 listing renormalises one bit at a time: while
286    /// `range < 128` it doubles `range`, propagates a carry if bit 31 of
287    /// `bottom` is set, doubles `bottom`, and emits the top byte every
288    /// time `bit_count` reaches zero. This routine takes the whole
289    /// renormalisation in one step. The shift count is the number of
290    /// leading zeros of the 8-bit `range` (1..=7), and at most one byte
291    /// boundary falls inside it. Bit 31 can only be set at the doubling
292    /// that completes a byte: `bottom` is below `2^24` after a byte is
293    /// emitted (below `2^8` initially) and gains less than `2^8` between
294    /// doublings (the splits added while `range` stays ≥ 128 sum to less
295    /// than 128), so after `k` doublings it is below `(2^24 + 2^8)·2^k`,
296    /// which stays under `2^31` until the eighth. The carry test is
297    /// therefore needed exactly once, on the value shifted to just
298    /// before the boundary. `write_bool_matches_bitwise_listing` pins
299    /// the byte stream and the final state against the one-bit loop.
300    #[inline]
301    pub fn write_bool(&mut self, prob: u8, value: bool) {
302        // split = 1 + (((range - 1) * prob) >> 8) — the same formula as
303        // §7.3's decoder so the value→bit split is exact.
304        let split = 1 + (((self.range - 1) * prob as u32) >> 8);
305        let (range, mut bottom) = if value {
306            (self.range - split, self.bottom.wrapping_add(split))
307        } else {
308            (split, self.bottom)
309        };
310        // Renormalise: `range` is in 1..=255, so the shift is 0..=7 —
311        // zero when no renormalisation is due, which the arithmetic
312        // below handles without a branch of its own.
313        let shift = range.leading_zeros() - 24;
314        let count = self.bit_count as u32;
315        if shift < count {
316            bottom <<= shift;
317            self.bit_count -= shift as i32;
318        } else {
319            bottom = self.emit_byte(bottom, shift, count);
320        }
321        self.range = range << shift;
322        self.bottom = bottom;
323    }
324
325    /// The renormalisation step that crosses a byte boundary: shift up
326    /// to the doubling that brings `bit_count` to zero, run the carry
327    /// test (§7.3 `add_one_to_output`), emit the high byte, keep the low
328    /// 24 bits and apply the rest of the shift. Kept out of line so
329    /// [`write_bool`](Self::write_bool)'s common path stays small.
330    #[cold]
331    #[inline(never)]
332    fn emit_byte(&mut self, mut bottom: u32, shift: u32, count: u32) -> u32 {
333        bottom <<= count - 1;
334        if bottom >> 31 == 1 {
335            add_one_to_output(&mut self.out);
336        }
337        bottom <<= 1;
338        self.out.push((bottom >> 24) as u8);
339        bottom &= (1 << 24) - 1;
340        let rest = shift - count;
341        self.bit_count = 8 - rest as i32;
342        bottom << rest
343    }
344
345    /// Encode `num_bits` flag bits MSB-first at the flat probability of
346    /// 128 (i.e. the §7.3 `L(n)` macro), exactly as `num_bits`
347    /// iterations of [`write_bool`]`(128, …)` would.
348    ///
349    /// Specialised register-local loop: at the fixed probability 128 the
350    /// §7.3 interval split collapses to a pure shift —
351    /// `1 + (((range - 1) * 128) >> 8)` is exactly
352    /// `1 + ((range - 1) >> 1)` (`* 2⁷ >> 8` ≡ `>> 1`, an algebraic
353    /// identity on the `1..=255` range domain) — and hoisting `range` /
354    /// `bottom` / `bit_count` into locals lets the whole loop run
355    /// without touching `self` except to emit bytes / propagate a
356    /// carry. State-for-state equality with the generic loop is pinned
357    /// by `write_literal_fast_matches_generic_loop` (the decoder-side
358    /// twin of this specialisation landed in round 306).
359    pub fn write_literal(&mut self, value: u32, num_bits: u32) {
360        debug_assert!(num_bits <= 32);
361        let mut range = self.range;
362        let mut bottom = self.bottom;
363        let mut bit_count = self.bit_count;
364        // MSB-first, paired with `BoolDecoder::read_literal`.
365        let mut i = num_bits;
366        while i > 0 {
367            i -= 1;
368            let split = 1 + ((range - 1) >> 1);
369            if ((value >> i) & 1) != 0 {
370                bottom = bottom.wrapping_add(split);
371                range -= split;
372            } else {
373                range = split;
374            }
375            while range < 128 {
376                range <<= 1;
377                if (bottom >> 31) & 1 == 1 {
378                    add_one_to_output(&mut self.out);
379                }
380                bottom <<= 1;
381                bit_count -= 1;
382                if bit_count == 0 {
383                    self.out.push((bottom >> 24) as u8);
384                    bottom &= (1 << 24) - 1;
385                    bit_count = 8;
386                }
387            }
388        }
389        self.range = range;
390        self.bottom = bottom;
391        self.bit_count = bit_count;
392    }
393
394    /// Encode a signed value as L(n) magnitude followed by L(1) sign,
395    /// the §9.3 / §9.4 / §9.6 idiom. Panics in debug builds if `value`
396    /// does not fit in `num_bits` magnitude bits.
397    pub fn write_signed_literal(&mut self, value: i32, num_bits: u32) {
398        let magnitude = value.unsigned_abs();
399        debug_assert!(
400            magnitude < (1u32 << num_bits),
401            "signed literal {value} does not fit in {num_bits} magnitude bits"
402        );
403        self.write_literal(magnitude, num_bits);
404        self.write_bool(128, value < 0);
405    }
406
407    /// Write a tree-coded leaf by walking `tree` to find the path of
408    /// bits that lands on `-leaf`, encoding each path bit against
409    /// `prob_lookup(node_index >> 1)`. This is the §8.1 `treed_read`
410    /// walk run in reverse: the decoder's [`crate::macroblock`]
411    /// `treed_read` recovers exactly the leaf this method writes,
412    /// against the same tree and probability lookup.
413    ///
414    /// Used by the §11 macroblock-mode layer (`kf_ymode_tree` /
415    /// `uv_mode_tree` / `bmode_tree`). Panics in debug builds if `leaf`
416    /// is not reachable in `tree`.
417    pub fn write_treed<F>(&mut self, tree: &[i8], prob_lookup: F, leaf: u8)
418    where
419        F: Fn(usize) -> u8,
420    {
421        // Depth-first search for the bit path from the root (node 0) to
422        // the leaf `-leaf`, into a fixed stack buffer (no per-call heap
423        // allocation — see `treed_find_path`).
424        let mut path = [false; 16];
425        let len = treed_find_path(tree, leaf, &mut path);
426        // Replay the path, calling `prob_lookup` with the same
427        // node-halved index the decoder uses at each step.
428        let mut i: i8 = 0;
429        for &bit in &path[..len] {
430            self.write_bool(prob_lookup((i as usize) >> 1), bit);
431            i = tree[i as usize + bit as usize];
432        }
433    }
434
435    /// [`write_treed`](Self::write_treed) from a precomputed path table:
436    /// the same `(probability index, bit)` steps in the same order,
437    /// without the per-symbol tree search.
438    fn write_treed_cached<F>(&mut self, paths: &[TreedLeafPath], prob_lookup: F, leaf: u8)
439    where
440        F: Fn(usize) -> u8,
441    {
442        let p = &paths[leaf as usize];
443        for s in 0..p.len as usize {
444            self.write_bool(prob_lookup(p.prob_index[s] as usize), p.bits[s]);
445        }
446    }
447
448    /// Finalise the encoder per §7.3 `flush_bool_encoder` and return
449    /// the encoded bytes. Always writes 4 tail bytes (the spec's
450    /// `c = 4; while (--c >= 0)` loop), so the smallest possible
451    /// partition is 4 bytes — comfortably above the 2-byte minimum
452    /// [`crate::bool_decoder::BoolDecoder::init`] requires.
453    pub fn finish(mut self) -> Vec<u8> {
454        let c = self.bit_count;
455        let v = self.bottom;
456        // Propagate any pending carry into the already-written tail.
457        if v & (1u32 << (32 - c)) != 0 {
458            add_one_to_output(&mut self.out);
459        }
460        let mut v = v;
461        // `v <<= c & 7;` followed by `while (--c >= 0) v <<= 8;` after
462        // `c >>= 3;` — same byte-realignment dance as the spec.
463        v = v.wrapping_shl((c & 7) as u32);
464        let mut shifts = c >> 3;
465        while shifts > 0 {
466            v = v.wrapping_shl(8);
467            shifts -= 1;
468        }
469        for _ in 0..4 {
470            self.out.push((v >> 24) as u8);
471            v = v.wrapping_shl(8);
472        }
473        self.out
474    }
475
476    /// Number of bytes the encoder has already committed (not counting
477    /// the four trailing bytes [`finish`](Self::finish) will append).
478    /// Useful for diagnostics; not otherwise consumed by the writer
479    /// helpers.
480    pub fn bytes_written(&self) -> usize {
481        self.out.len()
482    }
483}
484
485/// §7.3 `add_one_to_output`: increment the last-written byte by 1,
486/// propagating the carry leftward through any trailing `0xFF` bytes.
487fn add_one_to_output(out: &mut [u8]) {
488    let mut i = out.len();
489    while i > 0 {
490        i -= 1;
491        if out[i] == 255 {
492            out[i] = 0;
493        } else {
494            out[i] = out[i].wrapping_add(1);
495            return;
496        }
497    }
498}
499
500/// Two-bit horizontal / vertical scale code per §9.1's Table.
501///
502/// Parallels the decoder-side [`crate::frame_header::ScaleCode`] enum
503/// but is duplicated here as a `u8` for unambiguous round-trip with the
504/// 2-bit field on the wire. Encoder Phase 1 only emits
505/// [`ScaleCode::None`] (`= 0`) since upscaling has no decode effect.
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
507#[repr(u8)]
508pub enum ScaleCode {
509    /// 0 — no upscaling. Encoder default.
510    None = 0,
511    /// 1 — upscale by 5/4.
512    FiveFourths = 1,
513    /// 2 — upscale by 5/3.
514    FiveThirds = 2,
515    /// 3 — upscale by 2.
516    Double = 3,
517}
518
519/// §9.1 uncompressed-data-chunk writer.
520///
521/// Writes the 3-byte frame tag for every frame and, for key frames,
522/// the additional 7 bytes (`0x9d 0x01 0x2a` start code + 14-bit width
523/// + 2-bit horizontal scale + 14-bit height + 2-bit vertical scale).
524///
525/// Returns the number of bytes appended to `out` (3 for an interframe,
526/// 10 for a key frame). Validates that `width` and `height` fit the
527/// 14-bit field on key frames; for non-key frames `width` and `height`
528/// are ignored (the inherited dimensions live in the decoder's state).
529///
530/// The encoder's higher layers must back-patch the 19-bit
531/// `first_partition_size` into bits 5..23 of the frame tag after the
532/// first partition has been fully written and its length is known. To
533/// keep the layering crisp this function takes the size as a parameter:
534/// callers that don't know it yet pass `0` and patch the bytes in place
535/// using [`patch_first_partition_size`].
536#[allow(clippy::too_many_arguments)]
537pub fn write_frame_tag(
538    out: &mut Vec<u8>,
539    key_frame: bool,
540    version: u8,
541    show_frame: bool,
542    first_partition_size: u32,
543    width: u32,
544    height: u32,
545    horizontal_scale: ScaleCode,
546    vertical_scale: ScaleCode,
547) -> Result<usize, EncodeError> {
548    if first_partition_size > 0x7_FFFF {
549        return Err(EncodeError::FirstPartitionTooLarge {
550            bytes: first_partition_size as usize,
551        });
552    }
553    // §9.1 frame tag bit layout (LSB-first within the 24-bit word):
554    //   bit  0   : frame_type (0 = key, 1 = inter)
555    //   bits 1..3: version (3 bits)
556    //   bit  4   : show_frame
557    //   bits 5..23: first_partition_size (19 bits)
558    let frame_type_bit: u32 = if key_frame { 0 } else { 1 };
559    let show_bit: u32 = if show_frame { 1 } else { 0 };
560    let tmp: u32 = frame_type_bit
561        | ((version as u32 & 0x7) << 1)
562        | (show_bit << 4)
563        | ((first_partition_size & 0x7_FFFF) << 5);
564    out.push((tmp & 0xff) as u8);
565    out.push(((tmp >> 8) & 0xff) as u8);
566    out.push(((tmp >> 16) & 0xff) as u8);
567
568    if !key_frame {
569        return Ok(3);
570    }
571
572    if width == 0 || width > 0x3FFF || height == 0 || height > 0x3FFF {
573        return Err(EncodeError::InvalidDimensions { width, height });
574    }
575    out.extend_from_slice(&KEY_FRAME_START_CODE);
576    // §9.1 page 31 listing:
577    //   h_word = (h_scale << 14) | width
578    //   v_word = (v_scale << 14) | height
579    // emitted little-endian.
580    let h_word: u16 = ((horizontal_scale as u16) << 14) | (width as u16 & 0x3FFF);
581    let v_word: u16 = ((vertical_scale as u16) << 14) | (height as u16 & 0x3FFF);
582    out.push((h_word & 0xff) as u8);
583    out.push(((h_word >> 8) & 0xff) as u8);
584    out.push((v_word & 0xff) as u8);
585    out.push(((v_word >> 8) & 0xff) as u8);
586    Ok(10)
587}
588
589/// Back-patch the §9.1 `first_partition_size` field of an
590/// already-written frame tag in `buf`. `buf` must start with the three
591/// frame-tag bytes [`write_frame_tag`] produced. The frame_type /
592/// version / show_frame bits are preserved verbatim.
593pub fn patch_first_partition_size(buf: &mut [u8], size: u32) -> Result<(), EncodeError> {
594    if size > 0x7_FFFF {
595        return Err(EncodeError::FirstPartitionTooLarge {
596            bytes: size as usize,
597        });
598    }
599    debug_assert!(buf.len() >= 3, "frame tag must be present");
600    let tmp = (buf[0] as u32) | ((buf[1] as u32) << 8) | ((buf[2] as u32) << 16);
601    // Clear bits 5..23 (the 19-bit size field) and OR the new value in.
602    let new = (tmp & 0x1F) | ((size & 0x7_FFFF) << 5);
603    buf[0] = (new & 0xff) as u8;
604    buf[1] = ((new >> 8) & 0xff) as u8;
605    buf[2] = ((new >> 16) & 0xff) as u8;
606    Ok(())
607}
608
609/// §9.3 segment-update flags writer (disabled path).
610///
611/// Emits the single `segmentation_enabled = L(1) = 0` toggle. The richer
612/// enabled path — `update_mb_segmentation_map`, the per-segment quantizer
613/// / loop-filter feature data, and the `mb_segment_tree_probs` block — is
614/// written by [`write_update_segmentation`] when the encoder turns
615/// segmentation on. `debug_assert` guards against a caller passing
616/// `enabled = true` here (it would emit the toggle but none of the
617/// dependent §9.3 sub-blocks the decoder then expects to read).
618pub fn write_segment_update_flags(enc: &mut BoolEncoder, enabled: bool) {
619    debug_assert!(
620        !enabled,
621        "use write_update_segmentation for the segmentation_enabled = true path"
622    );
623    enc.write_bool(128, enabled);
624}
625
626/// Encoder-side mirror of [`crate::coded_header::UpdateSegmentation`] —
627/// the §9.3 `update_segmentation()` sub-block emitted when
628/// `segmentation_enabled = true`.
629///
630/// The four `quantizer` / `loop_filter` slots carry the per-segment
631/// feature deltas (or absolute values, when `feature_mode_absolute`).
632/// `None` means "this segment's feature is not updated this frame" — the
633/// decoder leaves it at its persisted value (0 on a key frame). The three
634/// `segment_prob` slots are the `mb_segment_tree_probs[3]` branch
635/// probabilities used to code each MB's `segment_id`; `None` means the
636/// decoder uses the default 255 ("always read a zero branch") for that
637/// node.
638///
639/// The writer ([`write_update_segmentation`]) lays the bits out exactly as
640/// [`crate::coded_header::parse_update_segmentation`] reads them, so the
641/// decoder recovers this struct field-for-field.
642#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
643pub struct UpdateSegmentationLayer {
644    /// `update_mb_segmentation_map` (§9.3). When `true`, the per-MB
645    /// `segment_id` codes follow in the §11 mode layer (against
646    /// `segment_prob`) and the `segment_prob` sub-block is written here.
647    pub update_mb_segmentation_map: bool,
648    /// `segment_feature_mode`: `false` = delta mode (the segment value is
649    /// added to the §9.6 baseline), `true` = absolute mode (the segment
650    /// value replaces the baseline). Only meaningful when at least one
651    /// `quantizer` / `loop_filter` slot is `Some`.
652    pub feature_mode_absolute: bool,
653    /// Per-segment §10 quantizer feature (`quantizer_update_value` +
654    /// `quantizer_update_sign`, 7-bit magnitude). `None` skips the
655    /// segment's `quantizer_update` flag (codes a 0).
656    pub quantizer: [Option<i16>; 4],
657    /// Per-segment §10 loop-filter feature (`lf_update_value` +
658    /// `lf_update_sign`, 6-bit magnitude). `None` skips the segment's
659    /// `loop_filter_update` flag (codes a 0).
660    pub loop_filter: [Option<i16>; 4],
661    /// `mb_segment_tree_probs[3]` (§10). `None` codes a 0
662    /// `segment_prob_update` flag for that node (decoder uses 255).
663    pub segment_prob: [Option<u8>; 3],
664}
665
666/// Write the §9.3 `update_segmentation()` sub-block for the
667/// `segmentation_enabled = true` path.
668///
669/// Emits, in §19.2 `update_segmentation()` order:
670///
671/// 1. `segmentation_enabled = L(1) = 1`;
672/// 2. `update_mb_segmentation_map` (L1);
673/// 3. `update_segment_feature_data` (L1), set iff any `quantizer` /
674///    `loop_filter` slot is `Some`; when set: `segment_feature_mode`
675///    (L1), then four `quantizer_update` flags (each followed by a signed
676///    7-bit magnitude when present), then four `loop_filter_update` flags
677///    (each followed by a signed 6-bit magnitude when present);
678/// 4. when `update_mb_segmentation_map`, three `segment_prob_update`
679///    flags, each followed by an 8-bit `segment_prob` when present.
680///
681/// This is the exact byte layout
682/// [`crate::coded_header::parse_update_segmentation`] reads (which is
683/// itself the §19.2 table verbatim), so the decoder reconstructs the
684/// [`crate::coded_header::UpdateSegmentation`] this layer describes.
685pub fn write_update_segmentation(enc: &mut BoolEncoder, layer: &UpdateSegmentationLayer) {
686    // §19.2 row 3: segmentation_enabled = 1 introduces the sub-block.
687    enc.write_bool(128, true);
688    enc.write_bool(128, layer.update_mb_segmentation_map);
689
690    // update_segment_feature_data: only when some feature is actually
691    // carried. Matching the decoder, the four quantizer + four loop-filter
692    // flags are only present when this bit is set.
693    let update_feature_data = layer.quantizer.iter().any(Option::is_some)
694        || layer.loop_filter.iter().any(Option::is_some);
695    enc.write_bool(128, update_feature_data);
696    if update_feature_data {
697        enc.write_bool(128, layer.feature_mode_absolute);
698        for slot in &layer.quantizer {
699            match slot {
700                Some(v) => {
701                    enc.write_bool(128, true);
702                    // §9.3: 7-bit magnitude + sign. write_signed_literal
703                    // pairs with the decoder's read_signed_delta(_, 7).
704                    enc.write_signed_literal(*v as i32, 7);
705                }
706                None => enc.write_bool(128, false),
707            }
708        }
709        for slot in &layer.loop_filter {
710            match slot {
711                Some(v) => {
712                    enc.write_bool(128, true);
713                    // §9.3: 6-bit magnitude + sign.
714                    enc.write_signed_literal(*v as i32, 6);
715                }
716                None => enc.write_bool(128, false),
717            }
718        }
719    }
720
721    if layer.update_mb_segmentation_map {
722        for slot in &layer.segment_prob {
723            match slot {
724                Some(p) => {
725                    enc.write_bool(128, true);
726                    enc.write_literal(*p as u32, 8);
727                }
728                None => enc.write_bool(128, false),
729            }
730        }
731    }
732}
733
734/// §9.4 loop-filter type / level / sharpness + `mb_lf_adjustments`
735/// writer.
736///
737/// `filter_type` chooses normal (`false`) vs simple (`true`) loop
738/// filter. `loop_filter_level` is the 6-bit baseline level; setting it
739/// to 0 triggers the §15 page-84 whole-frame filter skip in any
740/// compliant decoder. `sharpness_level` is the 3-bit sharpness knob.
741/// `loop_filter_adj_enable` controls whether the per-macroblock loop
742/// filter delta machinery is on; Phase 1 only supports the disabled
743/// case, paralleling the segmentation writer above.
744pub fn write_loop_filter(
745    enc: &mut BoolEncoder,
746    filter_type: bool,
747    loop_filter_level: u8,
748    sharpness_level: u8,
749    loop_filter_adj_enable: bool,
750) -> Result<(), EncodeError> {
751    if loop_filter_level > 63 {
752        return Err(EncodeError::LoopFilterLevelOutOfRange {
753            value: loop_filter_level,
754        });
755    }
756    if sharpness_level > 7 {
757        return Err(EncodeError::SharpnessLevelOutOfRange {
758            value: sharpness_level,
759        });
760    }
761    debug_assert!(
762        !loop_filter_adj_enable,
763        "Phase 1 encoder only supports loop_filter_adj_enable = false"
764    );
765
766    enc.write_bool(128, filter_type);
767    enc.write_literal(loop_filter_level as u32, 6);
768    enc.write_literal(sharpness_level as u32, 3);
769
770    // mb_lf_adjustments() sub-block (§9.4): just the disable bit
771    // when the feature is off — the rest of the table is gated on it.
772    enc.write_bool(128, loop_filter_adj_enable);
773    Ok(())
774}
775
776/// Caller-supplied per-reference + per-mode loop-filter delta layer
777/// per RFC 6386 §9.4 (the `mb_lf_adjustments()` sub-block).
778///
779/// The decoder already honours these deltas
780/// ([`crate::loop_filter::calculate_mb_filter_level_inter`]): each
781/// per-MB filter level starts from the frame `loop_filter_level`, then
782/// receives the matching `ref_frame_delta[ref]` plus the matching
783/// `mode_delta[mode]`, with the final level clamped into `0..=63`.
784/// This struct gives the encoder a way to *transmit* the deltas in the
785/// §19.2 frame header so the decoder applies them, and to use the same
786/// deltas during the encoder's own §15 post-walk filter pass so the
787/// encoder's reconstruction buffer stays byte-identical to what the
788/// decoder rebuilds.
789///
790/// `enabled` corresponds to the §19.2 `loop_filter_adj_enable` bit
791/// (`true` ⇒ the delta layer is on for this frame). `update`
792/// corresponds to the §19.2 `mode_ref_lf_delta_update` bit (`true` ⇒
793/// the frame carries fresh delta values; `false` ⇒ the decoder reuses
794/// the deltas from a prior frame). When `enabled` is `false` no per-MB
795/// delta is applied (and `update` is irrelevant). When `enabled` is
796/// `true` but `update` is `false`, no per-slot values are written to
797/// the bitstream — the decoder pulls from its carried state.
798///
799/// When `update` is `true`, each per-slot `Option<i8>` is either
800/// `Some(v)` (a fresh signed value with `abs(v) <= 63` is emitted) or
801/// `None` (the slot's bit `delta_update_flag` is 0 and the decoder
802/// keeps its carried value for that slot). The four `ref_frame_delta`
803/// slots are indexed by `CURRENT_FRAME = 0`, `LAST_FRAME = 1`,
804/// `GOLDEN_FRAME = 2`, `ALTREF_FRAME = 3` (§20.6 `ref_delta[]` order).
805/// The four `mode_delta` slots are indexed by `B_PRED = 0`,
806/// `ZERO_MV = 1`, `NEAREST/NEAR/NEW = 2`, `SPLIT_MV = 3` (§20.6
807/// `mode_delta[]` order).
808///
809/// The encoder's §15 post-walk filter pass reads the *effective*
810/// deltas — the values it just wrote plus the carried values for any
811/// `None` slot. The encoder maintains its own carried state across
812/// frames inside [`Vp8InterStreamEncoder`].
813#[derive(Debug, Clone, Copy, PartialEq, Eq)]
814pub struct LoopFilterDeltas {
815    /// §19.2 `loop_filter_adj_enable` (L1).
816    pub enabled: bool,
817    /// §19.2 `mode_ref_lf_delta_update` (L1). Only consulted when
818    /// `enabled` is `true`; if `false`, no per-slot values are written
819    /// and the decoder reuses the prior frame's deltas.
820    pub update: bool,
821    /// §19.2 four per-reference deltas, in the §20.6 `{CURRENT, LAST,
822    /// GOLDEN, ALTREF}` index order. Each `Some(v)` writes the
823    /// per-slot flag = 1 followed by L(6) magnitude + L(1) sign;
824    /// `None` writes the flag = 0 (decoder keeps its carried value).
825    /// Magnitudes greater than 63 are rejected by [`Self::validate`].
826    pub ref_frame_delta: [Option<i8>; 4],
827    /// §19.2 four per-mode deltas, in the §20.6 `{B_PRED, ZERO_MV,
828    /// OTHER_MV, SPLIT_MV}` index order. Same encoding as
829    /// `ref_frame_delta`.
830    pub mode_delta: [Option<i8>; 4],
831}
832
833impl Default for LoopFilterDeltas {
834    /// Disabled deltas: matches the round-150-and-earlier behaviour
835    /// (`loop_filter_adj_enable = 0`).
836    fn default() -> Self {
837        Self {
838            enabled: false,
839            update: false,
840            ref_frame_delta: [None; 4],
841            mode_delta: [None; 4],
842        }
843    }
844}
845
846impl LoopFilterDeltas {
847    /// Per-slot magnitude check: every `Some(v)` must satisfy
848    /// `abs(v) <= 63` (the §9.4 L(6) + L(1) field). Out-of-range values
849    /// surface as [`EncodeError::LoopFilterDeltaOutOfRange`] before any
850    /// encoding work runs.
851    pub fn validate(&self) -> Result<(), EncodeError> {
852        const REF_SLOTS: [LoopFilterDeltaSlot; 4] = [
853            LoopFilterDeltaSlot::RefCurrent,
854            LoopFilterDeltaSlot::RefLast,
855            LoopFilterDeltaSlot::RefGolden,
856            LoopFilterDeltaSlot::RefAltref,
857        ];
858        const MODE_SLOTS: [LoopFilterDeltaSlot; 4] = [
859            LoopFilterDeltaSlot::ModeBpred,
860            LoopFilterDeltaSlot::ModeZeroMv,
861            LoopFilterDeltaSlot::ModeOtherMv,
862            LoopFilterDeltaSlot::ModeSplitMv,
863        ];
864        for (slot, value) in REF_SLOTS.iter().zip(self.ref_frame_delta.iter()) {
865            if let Some(v) = value {
866                let mag = (*v as i16).unsigned_abs();
867                if mag > 63 {
868                    return Err(EncodeError::LoopFilterDeltaOutOfRange {
869                        which: *slot,
870                        value: *v as i16,
871                    });
872                }
873            }
874        }
875        for (slot, value) in MODE_SLOTS.iter().zip(self.mode_delta.iter()) {
876            if let Some(v) = value {
877                let mag = (*v as i16).unsigned_abs();
878                if mag > 63 {
879                    return Err(EncodeError::LoopFilterDeltaOutOfRange {
880                        which: *slot,
881                        value: *v as i16,
882                    });
883                }
884            }
885        }
886        Ok(())
887    }
888
889    /// Resolve the effective per-slot ref + mode deltas the §15 filter
890    /// pass must use this frame, given the carried (across-frame) delta
891    /// state. Matches the §9.4 / §20.6 "previous-frame values are used
892    /// unless updated in the current header" rule:
893    ///
894    /// * If `enabled` is `false`, every effective slot resolves to 0
895    ///   (the per-MB delta layer is off — the §15 filter level is the
896    ///   frame base only).
897    /// * If `enabled` is `true` and `update` is `false`, every
898    ///   effective slot equals the carried value (no fresh values
899    ///   transmitted, the decoder reuses its carried state).
900    /// * If `enabled` is `true` and `update` is `true`, each slot
901    ///   resolves to its `Some(v)` value if updated this frame,
902    ///   otherwise to the carried value (the per-slot "absent" path
903    ///   keeps prior state).
904    ///
905    /// Returns `(effective_ref_deltas, effective_mode_deltas)` in the
906    /// §20.6 `{CURRENT, LAST, GOLDEN, ALTREF}` / `{B_PRED, ZERO_MV,
907    /// OTHER_MV, SPLIT_MV}` index order. The returned arrays match
908    /// what [`crate::loop_filter::FrameFilterConfig::interframe`]
909    /// resolves from the parsed `mb_lf_adjustments` block — encoder
910    /// and decoder agree on the effective values byte-for-byte.
911    pub fn effective(
912        &self,
913        carried_ref_deltas: [i16; 4],
914        carried_mode_deltas: [i16; 4],
915    ) -> ([i16; 4], [i16; 4]) {
916        if !self.enabled {
917            return ([0; 4], [0; 4]);
918        }
919        if !self.update {
920            return (carried_ref_deltas, carried_mode_deltas);
921        }
922        let mut eff_ref = carried_ref_deltas;
923        let mut eff_mode = carried_mode_deltas;
924        for (slot, value) in eff_ref.iter_mut().zip(self.ref_frame_delta.iter()) {
925            if let Some(v) = value {
926                *slot = *v as i16;
927            }
928        }
929        for (slot, value) in eff_mode.iter_mut().zip(self.mode_delta.iter()) {
930            if let Some(v) = value {
931                *slot = *v as i16;
932            }
933        }
934        (eff_ref, eff_mode)
935    }
936}
937
938/// §9.4 loop-filter writer with caller-supplied per-reference + per-mode
939/// `mb_lf_adjustments()` deltas.
940///
941/// Extends [`write_loop_filter`] with [`LoopFilterDeltas`] support: the
942/// `loop_filter_adj_enable` bit + (when set) the `mode_ref_lf_delta_update`
943/// bit + (when set) the four per-reference + four per-mode L(1) presence
944/// flags and gated L(6) magnitude + L(1) sign values follow the §19.2
945/// frame-header layout exactly. Passing
946/// [`LoopFilterDeltas::default`] (with `enabled = false`) reproduces
947/// the round-150 wire (`loop_filter_adj_enable = 0`) byte-for-byte.
948pub fn write_loop_filter_with_deltas(
949    enc: &mut BoolEncoder,
950    filter_type: bool,
951    loop_filter_level: u8,
952    sharpness_level: u8,
953    deltas: &LoopFilterDeltas,
954) -> Result<(), EncodeError> {
955    if loop_filter_level > 63 {
956        return Err(EncodeError::LoopFilterLevelOutOfRange {
957            value: loop_filter_level,
958        });
959    }
960    if sharpness_level > 7 {
961        return Err(EncodeError::SharpnessLevelOutOfRange {
962            value: sharpness_level,
963        });
964    }
965    deltas.validate()?;
966
967    enc.write_bool(128, filter_type);
968    enc.write_literal(loop_filter_level as u32, 6);
969    enc.write_literal(sharpness_level as u32, 3);
970
971    // mb_lf_adjustments() — §9.4 / §19.2 (page 121–122).
972    enc.write_bool(128, deltas.enabled);
973    if deltas.enabled {
974        enc.write_bool(128, deltas.update);
975        if deltas.update {
976            for slot in &deltas.ref_frame_delta {
977                match slot {
978                    Some(v) => {
979                        enc.write_bool(128, true);
980                        write_signed_lf_delta(enc, *v);
981                    }
982                    None => enc.write_bool(128, false),
983                }
984            }
985            for slot in &deltas.mode_delta {
986                match slot {
987                    Some(v) => {
988                        enc.write_bool(128, true);
989                        write_signed_lf_delta(enc, *v);
990                    }
991                    None => enc.write_bool(128, false),
992                }
993            }
994        }
995    }
996    Ok(())
997}
998
999/// Emit the §9.4 L(6) magnitude + L(1) sign payload for a single
1000/// `loop_filter_delta` slot. Mirrors the decoder's `read_signed_delta`
1001/// reconstruction in [`crate::coded_header`].
1002fn write_signed_lf_delta(enc: &mut BoolEncoder, value: i8) {
1003    debug_assert!((-63..=63).contains(&(value as i16)));
1004    let magnitude = (value as i16).unsigned_abs() as u32;
1005    enc.write_literal(magnitude, 6);
1006    enc.write_bool(128, value < 0);
1007}
1008
1009/// §9.5 `log2_nbr_of_dct_partitions` writer.
1010///
1011/// `count` must be one of `1`, `2`, `4`, `8` (the only legal values
1012/// per the §9.5 table). The two-bit field on the wire is
1013/// `log2(count)`.
1014pub fn write_token_partition_count(enc: &mut BoolEncoder, count: u8) -> Result<(), EncodeError> {
1015    let log2: u32 = match count {
1016        1 => 0,
1017        2 => 1,
1018        4 => 2,
1019        8 => 3,
1020        other => return Err(EncodeError::InvalidDctPartitionCount { value: other }),
1021    };
1022    enc.write_literal(log2, 2);
1023    Ok(())
1024}
1025
1026/// §9.6 `quant_indices()` writer.
1027///
1028/// Writes the baseline `y_ac_qi` (always present) followed by five
1029/// presence-gated `L(4) + L(1)` signed deltas for `ydc / y2dc / y2ac /
1030/// uvdc / uvac`. Phase 1 callers pass `0` for the baseline (lossless
1031/// dequant scaling at this index) and `None` for every delta, but the
1032/// signature accepts the full set so the §13 encoder round can wire
1033/// arbitrary quantiser policies through unchanged.
1034pub fn write_quant_indices(
1035    enc: &mut BoolEncoder,
1036    y_ac_qi: u8,
1037    y_dc_delta: Option<i8>,
1038    y2_dc_delta: Option<i8>,
1039    y2_ac_delta: Option<i8>,
1040    uv_dc_delta: Option<i8>,
1041    uv_ac_delta: Option<i8>,
1042) -> Result<(), EncodeError> {
1043    if y_ac_qi > 127 {
1044        return Err(EncodeError::QuantIndexOutOfRange { value: y_ac_qi });
1045    }
1046    enc.write_literal(y_ac_qi as u32, 7);
1047    for delta in [
1048        y_dc_delta,
1049        y2_dc_delta,
1050        y2_ac_delta,
1051        uv_dc_delta,
1052        uv_ac_delta,
1053    ] {
1054        match delta {
1055            Some(d) => {
1056                enc.write_bool(128, true);
1057                enc.write_signed_literal(d as i32, 4);
1058            }
1059            None => enc.write_bool(128, false),
1060        }
1061    }
1062    Ok(())
1063}
1064
1065/// §9.10 / §9.11 `mb_no_skip_coeff` writer.
1066///
1067/// On a key frame the §9.11 row 2 `prob_skip_false` follows the toggle
1068/// when enabled; on an interframe §9.10 carries the same first two
1069/// fields then the §16-only `prob_intra` / `prob_last` / `prob_gf` /
1070/// intra-mode-prob updates / `mv_prob_update()` (none of which Phase 1
1071/// emits — it only writes key frames).
1072pub fn write_mb_no_skip_coeff(enc: &mut BoolEncoder, enabled: bool, prob_skip_false: u8) {
1073    enc.write_bool(128, enabled);
1074    if enabled {
1075        enc.write_literal(prob_skip_false as u32, 8);
1076    }
1077}
1078
1079/// Write `count` "no update" flags for the §13 / §9.9 token-probability
1080/// update sub-block. The four-dimensional structure of
1081/// `token_prob_update()` is `[4][8][3][11]` = 1056 single-bit flags, each
1082/// read at the §13.4 `coeff_update_probs[i][j][k][t]` table entry. With
1083/// every flag set to `0` no replacement probabilities follow and the
1084/// default §13.5 token-probability table remains in force for the frame.
1085///
1086/// `flag_probs` must be a flat 1056-entry view of the update-probability
1087/// table (`[i][j][k][t]` flattened row-major). The encoder passes the
1088/// crate-local [`COEFF_UPDATE_PROBS_FLAT`]; the decoder reads each flag
1089/// at the corresponding position-specific probability per §13.4 (NOT a
1090/// flat 128), so the encoder must use the same numbers.
1091pub fn write_no_token_prob_updates(enc: &mut BoolEncoder, flag_probs: &[u8; 1056]) {
1092    for &p in flag_probs.iter() {
1093        enc.write_bool(p, false);
1094    }
1095}
1096
1097/// Write a §13.4 `token_prob_update()` block from a [`TokenProbUpdates`]
1098/// array. Each of the 1056 `[i][j][k][t]` positions gets a single
1099/// "is this position being replaced?" flag written at
1100/// `coeff_update_probs[i][j][k][t]` (the same per-position probability
1101/// the decoder reads against); when the slot is `Some(prob)` an
1102/// additional `L(8)` literal carrying the replacement value follows.
1103///
1104/// The walk order matches RFC 6386 §13.4's four nested `do/while` loops
1105/// (`i` outermost over `0..4` planes, then `j` over `0..8` bands, then
1106/// `k` over `0..3` previous-token classes, then `t` over `0..11` token
1107/// positions). The decoder's
1108/// [`crate::coded_header::Vp8CodedHeader::parse`] consumes the same
1109/// order; encoder + decoder loops are byte-paired.
1110///
1111/// `flag_probs` is a flat 1056-entry view of the §13.4 table — pass the
1112/// crate-local [`COEFF_UPDATE_PROBS_FLAT`]. `updates` is the
1113/// `[plane][band][prev_ctx][pos]` array (each entry `Some(prob)` to
1114/// replace or `None` to keep the §13.5 default). An all-`None` `updates`
1115/// produces the same bytes [`write_no_token_prob_updates`] does, so the
1116/// two writers are byte-equivalent in that special case.
1117pub fn write_token_prob_updates(
1118    enc: &mut BoolEncoder,
1119    updates: &TokenProbUpdates,
1120    flag_probs: &[u8; 1056],
1121) {
1122    for i in 0..4 {
1123        for j in 0..8 {
1124            for k in 0..3 {
1125                for t in 0..11 {
1126                    let p = flag_probs[i * 8 * 3 * 11 + j * 3 * 11 + k * 11 + t];
1127                    match updates[i][j][k][t] {
1128                        Some(new_prob) => {
1129                            enc.write_bool(p, true);
1130                            enc.write_literal(new_prob as u32, 8);
1131                        }
1132                        None => {
1133                            enc.write_bool(p, false);
1134                        }
1135                    }
1136                }
1137            }
1138        }
1139    }
1140}
1141
1142// ─────────────────────── silent-keyframe entry point ───────────────────────
1143
1144/// Parameters for [`encode_silent_keyframe`].
1145///
1146/// Phase 1 keeps the surface minimal: dimensions, optional override of
1147/// the §9.4 loop filter (default disabled via `loop_filter_level = 0`),
1148/// and an optional override of the §9.6 `y_ac_qi` baseline (default 0).
1149#[derive(Debug, Clone, Copy)]
1150#[non_exhaustive]
1151pub struct SilentKeyframeParams {
1152    /// Visible width in pixels (1..=0x3FFF per §9.1).
1153    pub width: u32,
1154    /// Visible height in pixels (1..=0x3FFF per §9.1).
1155    pub height: u32,
1156    /// §9.4 baseline loop filter level (0..=63). 0 triggers the §15
1157    /// page-84 whole-frame loop-filter skip.
1158    pub loop_filter_level: u8,
1159    /// §9.4 sharpness knob (0..=7). Only consulted when
1160    /// `loop_filter_level > 0`.
1161    pub sharpness_level: u8,
1162    /// §9.6 `y_ac_qi` baseline (0..=127). Irrelevant for the silent
1163    /// path (every coefficient is zero anyway) but exposed so a later
1164    /// round can drive non-trivial quantization through the same
1165    /// entry.
1166    pub y_ac_qi: u8,
1167    /// §9.5 DCT partition count. Must be one of 1 / 2 / 4 / 8.
1168    pub nbr_of_dct_partitions: u8,
1169}
1170
1171impl SilentKeyframeParams {
1172    /// Set `width`.
1173    #[must_use]
1174    pub fn with_width(mut self, v: u32) -> Self {
1175        self.width = v;
1176        self
1177    }
1178
1179    /// Set `height`.
1180    #[must_use]
1181    pub fn with_height(mut self, v: u32) -> Self {
1182        self.height = v;
1183        self
1184    }
1185
1186    /// Set `loop_filter_level`.
1187    #[must_use]
1188    pub fn with_loop_filter_level(mut self, v: u8) -> Self {
1189        self.loop_filter_level = v;
1190        self
1191    }
1192
1193    /// Set `sharpness_level`.
1194    #[must_use]
1195    pub fn with_sharpness_level(mut self, v: u8) -> Self {
1196        self.sharpness_level = v;
1197        self
1198    }
1199
1200    /// Set `y_ac_qi`.
1201    #[must_use]
1202    pub fn with_y_ac_qi(mut self, v: u8) -> Self {
1203        self.y_ac_qi = v;
1204        self
1205    }
1206
1207    /// Set `nbr_of_dct_partitions`.
1208    #[must_use]
1209    pub fn with_nbr_of_dct_partitions(mut self, v: u8) -> Self {
1210        self.nbr_of_dct_partitions = v;
1211        self
1212    }
1213}
1214
1215impl Default for SilentKeyframeParams {
1216    fn default() -> Self {
1217        SilentKeyframeParams {
1218            width: 16,
1219            height: 16,
1220            loop_filter_level: 0,
1221            sharpness_level: 0,
1222            y_ac_qi: 0,
1223            nbr_of_dct_partitions: 1,
1224        }
1225    }
1226}
1227
1228impl SilentKeyframeParams {
1229    /// Convenience constructor for the most common case — pick the
1230    /// dimensions, leave everything else at its silent-keyframe
1231    /// default.
1232    pub fn new(width: u32, height: u32) -> Self {
1233        SilentKeyframeParams {
1234            width,
1235            height,
1236            ..Self::default()
1237        }
1238    }
1239}
1240
1241/// Encode a trivial all-zero-quantizer VP8 key frame for `params`.
1242///
1243/// Layout of the emitted bytes:
1244///
1245/// 1. §9.1 frame tag (3 bytes) — `frame_type=0` (key), `version=0`,
1246///    `show_frame=1`, `first_partition_size` back-patched after step 2.
1247/// 2. §9.1 key-frame extension (7 bytes) — start code `0x9d 0x01 0x2a`
1248///    + 14-bit width + 14-bit height (both scale codes 0).
1249/// 3. §19.2 boolean-coded first partition:
1250///    * §9.2 `color_space = 0` + `clamping_type = 0`.
1251///    * §9.3 segmentation_enabled = 0 (writer skips the sub-block).
1252///    * §9.4 filter_type = 0, `loop_filter_level` / `sharpness_level`
1253///      per `params`, `loop_filter_adj_enable = 0`.
1254///    * §9.5 `log2_nbr_of_dct_partitions` = `log2(params.nbr_of_dct_partitions)`.
1255///    * §9.6 quant_indices — `y_ac_qi = params.y_ac_qi`, every delta
1256///      omitted.
1257///    * §9.7 key-frame `refresh_entropy_probs = 1`.
1258///    * §13 / §9.9 token-prob update sub-block — every flag = 0
1259///      (defaults retained).
1260///    * §9.11 `mb_no_skip_coeff = 1`, `prob_skip_false = 1` (skip flag
1261///      is the high-probability branch so we encode it cheaply).
1262///    * §11 macroblock prediction records: per MB, `mb_skip_coeff = 1`,
1263///      `y_mode = DC_PRED`, `uv_mode = DC_PRED`. No subblock modes,
1264///      no segment id.
1265///    * §7.3 `flush_bool_encoder` (4 tail bytes).
1266/// 4. §9.5 DCT partition table — `(nbr_of_dct_partitions - 1) * 3`
1267///    bytes of 24-bit little-endian sizes.
1268/// 5. One DCT partition per row-stripe (every MB has
1269///    `mb_skip_coeff = 1`, so each partition emits only its
1270///    §7.3 4-byte flush trailer).
1271///
1272/// The result decodes through the crate's own [`crate::decode_vp8`]
1273/// driver and (when wrapped in an IVF container) through
1274/// `ffmpeg -c:v vp8`.
1275pub fn encode_silent_keyframe(params: SilentKeyframeParams) -> Result<Vec<u8>, EncodeError> {
1276    if params.width == 0 || params.width > 0x3FFF || params.height == 0 || params.height > 0x3FFF {
1277        return Err(EncodeError::InvalidDimensions {
1278            width: params.width,
1279            height: params.height,
1280        });
1281    }
1282
1283    let mb_cols = params.width.div_ceil(16) as usize;
1284    let mb_rows = params.height.div_ceil(16) as usize;
1285
1286    // ---- (3) Build the boolean-coded first partition ---------------------
1287    let mut enc = BoolEncoder::new();
1288
1289    // §9.2 — color_space + clamping_type.
1290    enc.write_bool(128, false);
1291    enc.write_bool(128, false);
1292
1293    // §9.3 — segmentation off.
1294    write_segment_update_flags(&mut enc, false);
1295
1296    // §9.4 — loop filter knobs.
1297    write_loop_filter(
1298        &mut enc,
1299        false,
1300        params.loop_filter_level,
1301        params.sharpness_level,
1302        false,
1303    )?;
1304
1305    // §9.5 — partition count.
1306    write_token_partition_count(&mut enc, params.nbr_of_dct_partitions)?;
1307
1308    // §9.6 — quant indices (baseline only).
1309    write_quant_indices(&mut enc, params.y_ac_qi, None, None, None, None, None)?;
1310
1311    // §9.7 (key frame) — refresh_entropy_probs.
1312    enc.write_bool(128, true);
1313
1314    // §13 / §9.9 — token-prob update sub-block: every flag false.
1315    write_no_token_prob_updates(&mut enc, &COEFF_UPDATE_PROBS_FLAT);
1316
1317    // §9.11 — mb_no_skip_coeff + prob_skip_false. prob_skip_false = 1
1318    // → P(mb_skip_coeff=false) ≈ 1/256, so the `mb_skip_coeff=true`
1319    // branch we emit per MB costs nearly nothing.
1320    write_mb_no_skip_coeff(&mut enc, true, 1);
1321
1322    // §11 macroblock prediction records.
1323    //
1324    //   1. mb_skip_coeff = true (prob = 1).
1325    //   2. y_mode = DC_PRED. Tree path "1, 0, 0" against
1326    //      KF_YMODE_PROB = {145, 156, 163, 128}.
1327    //   3. (no subblock modes: y_mode != B_PRED.)
1328    //   4. uv_mode = DC_PRED. Tree path "0" against KF_UV_MODE_PROB.
1329    for _ in 0..(mb_rows * mb_cols) {
1330        // mb_skip_coeff = true.
1331        enc.write_bool(1, true);
1332        // y_mode = DC_PRED.
1333        enc.write_bool(145, true);
1334        enc.write_bool(156, false);
1335        enc.write_bool(163, false);
1336        // uv_mode = DC_PRED.
1337        enc.write_bool(142, false);
1338    }
1339
1340    let first_partition = enc.finish();
1341    let first_partition_size = first_partition.len();
1342    if first_partition_size > 0x7_FFFF {
1343        return Err(EncodeError::FirstPartitionTooLarge {
1344            bytes: first_partition_size,
1345        });
1346    }
1347
1348    // ---- (1) + (2) Frame tag + key-frame extension ----------------------
1349    let mut out: Vec<u8> = Vec::with_capacity(10 + first_partition_size + 16);
1350    write_frame_tag(
1351        &mut out,
1352        true,
1353        0,
1354        true,
1355        first_partition_size as u32,
1356        params.width,
1357        params.height,
1358        ScaleCode::None,
1359        ScaleCode::None,
1360    )?;
1361
1362    out.extend_from_slice(&first_partition);
1363
1364    // ---- (4) + (5) DCT partition table + per-partition payloads --------
1365    let num_partitions = params.nbr_of_dct_partitions as usize;
1366    let mut dct_partitions: Vec<Vec<u8>> = Vec::with_capacity(num_partitions);
1367    for _ in 0..num_partitions {
1368        // Every MB had mb_skip_coeff = true, so no per-block tokens
1369        // were emitted into any DCT partition. Each partition still
1370        // pays the §7.3 4-byte flush trailer.
1371        let p = BoolEncoder::new();
1372        dct_partitions.push(p.finish());
1373    }
1374    // §9.5 size table: `(num_partitions - 1) * 3` LE bytes.
1375    for part in dct_partitions.iter().take(num_partitions.saturating_sub(1)) {
1376        let sz = part.len();
1377        out.push((sz & 0xff) as u8);
1378        out.push(((sz >> 8) & 0xff) as u8);
1379        out.push(((sz >> 16) & 0xff) as u8);
1380    }
1381    for p in &dct_partitions {
1382        out.extend_from_slice(p);
1383    }
1384
1385    Ok(out)
1386}
1387
1388/// Flattened view of the §13.4 `coeff_update_probs[4][8][3][11]` table.
1389/// Each of the 1056 entries is the per-position probability the
1390/// corresponding `coeff_prob_update_flag` is read against on the decode
1391/// side. The encoder must use the same numbers — using a flat 128 here
1392/// would produce a far larger partition than the decoder expects, since
1393/// the table's values cluster near 255 ("almost always no update").
1394///
1395/// Built at compile time from a copy of the §13.4 table. The decoder's
1396/// [`crate::coded_header`] holds the same numbers in its nested-array
1397/// form; transcribing them once here avoids cross-module visibility
1398/// without re-typing them by hand at call time.
1399#[doc(hidden)]
1400pub const COEFF_UPDATE_PROBS_FLAT: [u8; 1056] = {
1401    let mut out = [0u8; 1056];
1402    let mut i = 0;
1403    while i < 4 {
1404        let mut j = 0;
1405        while j < 8 {
1406            let mut k = 0;
1407            while k < 3 {
1408                let mut t = 0;
1409                while t < 11 {
1410                    out[i * 8 * 3 * 11 + j * 3 * 11 + k * 11 + t] = COEFF_UPDATE_PROBS[i][j][k][t];
1411                    t += 1;
1412                }
1413                k += 1;
1414            }
1415            j += 1;
1416        }
1417        i += 1;
1418    }
1419    out
1420};
1421
1422/// `coeff_update_probs[i][j][k][t]` transcribed verbatim from RFC 6386
1423/// §13.4 — the same numbers the decoder's [`crate::coded_header`] uses
1424/// (this file re-types them to keep the encoder module
1425/// dependency-free of the decoder's internal table). Any change to the
1426/// decoder copy must mirror the change here; the
1427/// `coeff_update_probs_flat_walk_is_consistent` test below pins the
1428/// two tables together at test time.
1429const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [
1430    [
1431        [
1432            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1433            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1434            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1435        ],
1436        [
1437            [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1438            [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255],
1439            [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
1440        ],
1441        [
1442            [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255],
1443            [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1444            [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1445        ],
1446        [
1447            [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1448            [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1449            [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1450        ],
1451        [
1452            [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1453            [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1454            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1455        ],
1456        [
1457            [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1458            [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1459            [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1460        ],
1461        [
1462            [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255],
1463            [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255],
1464            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1465        ],
1466        [
1467            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1468            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1469            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1470        ],
1471    ],
1472    [
1473        [
1474            [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1475            [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255],
1476            [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255],
1477        ],
1478        [
1479            [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1480            [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1481            [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255],
1482        ],
1483        [
1484            [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1485            [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1486            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1487        ],
1488        [
1489            [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1490            [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1491            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1492        ],
1493        [
1494            [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1495            [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1496            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1497        ],
1498        [
1499            [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1500            [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1501            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1502        ],
1503        [
1504            [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
1505            [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1506            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1507        ],
1508        [
1509            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1510            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1511            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1512        ],
1513    ],
1514    [
1515        [
1516            [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255],
1517            [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255],
1518            [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255],
1519        ],
1520        [
1521            [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1522            [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1523            [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255],
1524        ],
1525        [
1526            [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1527            [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1528            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1529        ],
1530        [
1531            [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1532            [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1533            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1534        ],
1535        [
1536            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1537            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1538            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1539        ],
1540        [
1541            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1542            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1543            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1544        ],
1545        [
1546            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1547            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1548            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1549        ],
1550        [
1551            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1552            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1553            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1554        ],
1555    ],
1556    [
1557        [
1558            [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1559            [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255],
1560            [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255],
1561        ],
1562        [
1563            [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
1564            [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
1565            [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255],
1566        ],
1567        [
1568            [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255],
1569            [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
1570            [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255],
1571        ],
1572        [
1573            [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1574            [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1575            [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1576        ],
1577        [
1578            [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255],
1579            [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1580            [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1581        ],
1582        [
1583            [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1584            [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1585            [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
1586        ],
1587        [
1588            [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255],
1589            [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1590            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1591        ],
1592        [
1593            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1594            [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1595            [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
1596        ],
1597    ],
1598];
1599
1600// ───────────────────────── Phase 2: §13 DCT-token encoder ─────────────────────
1601
1602use crate::dct_tokens::{BlockType, COEFF_BANDS, CoeffProbs, DctToken};
1603
1604/// §13.2 `coeff_tree` — duplicated here for the encoder's tree walk so
1605/// the inverse mapping (`token -> bit path`) can be computed against
1606/// the exact same eleven-internal-node, twelve-leaf structure the
1607/// decoder traverses. Values follow the decoder's convention: entry
1608/// `2*i` is the left child of internal node `i`, entry `2*i + 1` is
1609/// the right child; non-negative entries point to the next internal
1610/// node, non-positive entries `-t` denote leaf `DctToken` with
1611/// discriminant `t`.
1612const ENC_COEFF_TREE: [i8; 22] = [
1613    -(DctToken::Eob as i8),
1614    2,
1615    -(DctToken::Dct0 as i8),
1616    4,
1617    -(DctToken::Dct1 as i8),
1618    6,
1619    8,
1620    12,
1621    -(DctToken::Dct2 as i8),
1622    10,
1623    -(DctToken::Dct3 as i8),
1624    -(DctToken::Dct4 as i8),
1625    14,
1626    16,
1627    -(DctToken::Cat1 as i8),
1628    -(DctToken::Cat2 as i8),
1629    18,
1630    20,
1631    -(DctToken::Cat3 as i8),
1632    -(DctToken::Cat4 as i8),
1633    -(DctToken::Cat5 as i8),
1634    -(DctToken::Cat6 as i8),
1635];
1636
1637/// §13.2 `Pcat1..Pcat6` extra-bits probability lists (terminator
1638/// removed; mirrors the decoder copy in `dct_tokens.rs`).
1639const ENC_PCAT1: &[u8] = &[159];
1640const ENC_PCAT2: &[u8] = &[165, 145];
1641const ENC_PCAT3: &[u8] = &[173, 148, 140];
1642const ENC_PCAT4: &[u8] = &[176, 155, 140, 135];
1643const ENC_PCAT5: &[u8] = &[180, 157, 141, 134, 130];
1644const ENC_PCAT6: &[u8] = &[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129];
1645
1646/// §13.2 `categoryBase[6]` — first value in each cat1..cat6 range.
1647const ENC_CAT_BASE: [u16; 6] = [5, 7, 11, 19, 35, 67];
1648
1649/// Classify the absolute value of a single coefficient into its
1650/// RFC 6386 §13.2 DCT-token alphabet entry. Caller is responsible for
1651/// the sign bit (which is emitted separately by the encoder at fixed
1652/// probability 128).
1653///
1654/// Returns `DctToken::Dct0` for the literal zero value (not `Eob` —
1655/// EOB is a separate decision made by the surrounding block-encoder
1656/// based on whether any non-zero coefficient follows).
1657pub fn classify_coeff_token(abs_value: u16) -> DctToken {
1658    match abs_value {
1659        0 => DctToken::Dct0,
1660        1 => DctToken::Dct1,
1661        2 => DctToken::Dct2,
1662        3 => DctToken::Dct3,
1663        4 => DctToken::Dct4,
1664        5..=6 => DctToken::Cat1,
1665        7..=10 => DctToken::Cat2,
1666        11..=18 => DctToken::Cat3,
1667        19..=34 => DctToken::Cat4,
1668        35..=66 => DctToken::Cat5,
1669        _ => DctToken::Cat6,
1670    }
1671}
1672
1673/// Errors surfaced by the §13 token-block encoder.
1674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1675#[non_exhaustive]
1676pub enum TokenEncodeError {
1677    /// A coefficient magnitude exceeded the §13.2 alphabet's largest
1678    /// representable value (`67 + (2^11 - 1) = 2114`). The encoder
1679    /// makes no attempt to clamp; the caller is expected to have run
1680    /// the §14 quantizer and have its results in range. Surfaces the
1681    /// offending raster index and value so the caller can pin the
1682    /// quantizer bug.
1683    CoefficientOutOfRange { index: usize, value: i16 },
1684}
1685
1686impl core::fmt::Display for TokenEncodeError {
1687    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1688        match self {
1689            TokenEncodeError::CoefficientOutOfRange { index, value } => write!(
1690                f,
1691                "vp8 token encode: coefficient[{index}]={value} exceeds the §13.2 alphabet maximum (±2114)"
1692            ),
1693        }
1694    }
1695}
1696
1697impl std::error::Error for TokenEncodeError {}
1698
1699/// One step of a §13.2 token bit-path: the `coeff_probs[…][prob_index]`
1700/// slot to consult and the bit to emit / decode at that node.
1701///
1702/// Width matches the `(usize, bool)` tuple the three call sites in this
1703/// module iterate over so the table reads as a drop-in replacement for
1704/// the prior `Vec<(usize, bool)>`.
1705#[derive(Clone, Copy, Debug)]
1706struct TokenBitStep {
1707    /// The `coeff_probs[plane][band][ctx3][prob_index]` slot index — the
1708    /// `i_half` value the call sites pass into `probs[i_half]`.
1709    prob_index: u8,
1710    /// The boolean to emit (encoder) / accumulate against the prob
1711    /// (RD scorer / fitter).
1712    bit: bool,
1713}
1714
1715/// Maximum bit-path width across the 24 reachable `(start_index, token)`
1716/// combinations. Computed in `precompute_token_bit_paths` below — the
1717/// deepest leaves (`Cat3..Cat6` from root) emit exactly 7 bits; every
1718/// other path is shorter. The fixed-width buffer lets the table live in
1719/// static storage with zero per-call allocation.
1720const TOKEN_BIT_PATH_MAX_LEN: usize = 7;
1721
1722/// One precomputed table entry: a fixed-width buffer of up to
1723/// [`TOKEN_BIT_PATH_MAX_LEN`] [`TokenBitStep`]s plus the number of valid
1724/// leading slots. Type-aliased to keep [`TOKEN_BIT_PATHS`] readable.
1725type TokenBitPathEntry = ([TokenBitStep; TOKEN_BIT_PATH_MAX_LEN], u8);
1726
1727/// The full table: `[start_slot ∈ {0, 1}][token ∈ 0..12]` →
1728/// [`TokenBitPathEntry`]. See [`TOKEN_BIT_PATHS`] for indexing.
1729type TokenBitPathTable = [[TokenBitPathEntry; 12]; 2];
1730
1731/// Precomputed token bit paths for every `(start_index, token)` pair
1732/// reachable from [`ENC_COEFF_TREE`]. Indexed as
1733/// `TOKEN_BIT_PATHS[start_slot][token as usize]`, where `start_slot` is
1734/// `0` for `start_index = 0` (the §13.2 root including the Eob branch)
1735/// and `1` for `start_index = 2` (the "previous coefficient was DCT_0"
1736/// shortcut that bypasses the Eob split).
1737///
1738/// Each entry is `(buffer, length)`; only the leading `length` slots of
1739/// `buffer` are valid. `(start_slot = 1, token = Eob)` is unreachable
1740/// (§13.2 explicitly forbids EOB after a DCT_0) and stores `length = 0`
1741/// as a tombstone; the call sites never request it.
1742///
1743/// Computed at module load via `std::sync::LazyLock`. The first call
1744/// inside the encoder hot path drives the one-time cost; every
1745/// subsequent token emission resolves to a single index-and-slice.
1746static TOKEN_BIT_PATHS: std::sync::LazyLock<TokenBitPathTable> =
1747    std::sync::LazyLock::new(precompute_token_bit_paths);
1748
1749fn precompute_token_bit_paths() -> TokenBitPathTable {
1750    let zero = TokenBitStep {
1751        prob_index: 0,
1752        bit: false,
1753    };
1754    let mut out = [[([zero; TOKEN_BIT_PATH_MAX_LEN], 0u8); 12]; 2];
1755
1756    fn descend(
1757        i: i8,
1758        target: i8,
1759        buf: &mut [TokenBitStep; TOKEN_BIT_PATH_MAX_LEN],
1760        len: &mut usize,
1761    ) -> bool {
1762        for &bit in &[false, true] {
1763            let child = ENC_COEFF_TREE[i as usize + bit as usize];
1764            if child <= 0 {
1765                if -child == target {
1766                    buf[*len] = TokenBitStep {
1767                        prob_index: (i as usize >> 1) as u8,
1768                        bit,
1769                    };
1770                    *len += 1;
1771                    return true;
1772                }
1773            } else {
1774                buf[*len] = TokenBitStep {
1775                    prob_index: (i as usize >> 1) as u8,
1776                    bit,
1777                };
1778                *len += 1;
1779                if descend(child, target, buf, len) {
1780                    return true;
1781                }
1782                *len -= 1;
1783            }
1784        }
1785        false
1786    }
1787
1788    for (slot, &start) in [0i8, 2i8].iter().enumerate() {
1789        for token in 0i8..12 {
1790            let mut buf = [zero; TOKEN_BIT_PATH_MAX_LEN];
1791            let mut len = 0usize;
1792            if descend(start, token, &mut buf, &mut len) {
1793                out[slot][token as usize] = (buf, len as u8);
1794            }
1795            // (slot = 1, token = Eob) is unreachable; the (zeros, 0)
1796            // tombstone is correct and never indexed by the encoder.
1797        }
1798    }
1799    out
1800}
1801
1802/// Walk [`ENC_COEFF_TREE`] starting at internal node `start_index` and
1803/// return the `(prob_index, bit)` sequence that lands at the leaf for
1804/// `target`. Mirrors the decoder's `treed_read_coef` traversal but
1805/// runs backwards from a known leaf.
1806///
1807/// Resolves through the precomputed [`TOKEN_BIT_PATHS`] table — every
1808/// reachable `(start_index, token)` pair is materialised at module load,
1809/// so each call is a single index + slice borrow with no allocation.
1810/// The `start_index` distinguishes the §13.2 "may emit EOB" case (`0`)
1811/// from the "previous coefficient was DCT_0" case (`2`, EOB branch
1812/// bypassed).
1813fn token_to_bit_path(token: DctToken, start_index: i8) -> &'static [TokenBitStep] {
1814    let slot = match start_index {
1815        0 => 0usize,
1816        2 => 1usize,
1817        _ => {
1818            debug_assert!(false, "unsupported coeff_tree start_index {start_index}");
1819            0
1820        }
1821    };
1822    let (buf, len) = &TOKEN_BIT_PATHS[slot][token as usize];
1823    debug_assert!(
1824        *len > 0,
1825        "token {token:?} not reachable from coeff_tree index {start_index}"
1826    );
1827    &buf[..*len as usize]
1828}
1829
1830/// Look up the cat-token's `(base, prob_list)` pair. Returns `None`
1831/// for the non-cat tokens (Dct0..Dct4, Eob) where there are no
1832/// trailing extra bits.
1833fn cat_extras(token: DctToken) -> Option<(u16, &'static [u8])> {
1834    match token {
1835        DctToken::Cat1 => Some((ENC_CAT_BASE[0], ENC_PCAT1)),
1836        DctToken::Cat2 => Some((ENC_CAT_BASE[1], ENC_PCAT2)),
1837        DctToken::Cat3 => Some((ENC_CAT_BASE[2], ENC_PCAT3)),
1838        DctToken::Cat4 => Some((ENC_CAT_BASE[3], ENC_PCAT4)),
1839        DctToken::Cat5 => Some((ENC_CAT_BASE[4], ENC_PCAT5)),
1840        DctToken::Cat6 => Some((ENC_CAT_BASE[5], ENC_PCAT6)),
1841        _ => None,
1842    }
1843}
1844
1845/// Encode one 16-coefficient sub-block per RFC 6386 §13.3 into `enc`.
1846///
1847/// `coeffs` is a 16-entry array in **scan (zig-zag) order** — i.e. the
1848/// exact order the §13.3 token loop visits positions. Position
1849/// `block_type.first_coeff()` is the first slot read; earlier slots
1850/// are ignored (for `YAfterY2` the DC is part of the Y2 block and
1851/// `coeffs[0]` is unused by the encoder).
1852///
1853/// `block_type` selects the §13.3 plane index and the `firstCoeff`
1854/// value. `coeff_probs` is the resolved `coeff_probs[4][8][3][11]`
1855/// from [`merge_default_token_probs`](crate::merge_default_token_probs).
1856/// `above_has_nonzero` / `left_has_nonzero` are the §13.3 neighbour
1857/// non-zero predictors that seed `ctx3` for the very first
1858/// coefficient (off-frame neighbours pass `false`).
1859///
1860/// Returns `Ok(non_zero_count)` — the number of non-zero coefficients
1861/// emitted. The encoder always concludes with an `Eob` token unless
1862/// all 16 (or 15 for `YAfterY2`) coefficients are non-zero, in which
1863/// case §13.2's "implicit eob after the last coefficient" rule
1864/// applies and the encoder omits the explicit `Eob`.
1865///
1866/// This is the Phase-2 inverse of [`crate::decode_block`]. The unit
1867/// tests in this module prove byte-exact round-trip at the coefficient
1868/// layer: encode the block, hand the resulting bytes to a
1869/// `BoolDecoder`, walk `decode_block` with the same `block_type` /
1870/// `coeff_probs` / neighbour predictors, and assert the recovered
1871/// `coeffs` array equals the input.
1872pub fn encode_coeff_block(
1873    enc: &mut BoolEncoder,
1874    block_type: BlockType,
1875    coeff_probs: &CoeffProbs,
1876    above_has_nonzero: bool,
1877    left_has_nonzero: bool,
1878    coeffs: &[i16; 16],
1879) -> Result<usize, TokenEncodeError> {
1880    encode_coeff_block_into(
1881        enc,
1882        block_type,
1883        coeff_probs,
1884        above_has_nonzero,
1885        left_has_nonzero,
1886        coeffs,
1887    )
1888}
1889
1890/// Where the §13 token walk sends its §7.3 boolean decisions: straight
1891/// into a [`BoolEncoder`], or onto a token tape (`tape.rs`) that is
1892/// coded into one later (the frame drivers tokenise rows in their
1893/// workers and leave only the arithmetic coding in order).
1894trait BoolSink {
1895    /// One decision: `value` at probability-of-zero `prob / 256`.
1896    fn put(&mut self, prob: u8, value: bool);
1897
1898    /// One §13.2 coefficient-tree decision: as [`put`](Self::put), with
1899    /// the flat index (`((plane·8 + band)·3 + ctx)·11 + node`) of the
1900    /// coefficient probability it is coded against.
1901    #[inline]
1902    fn put_tree(&mut self, _slot: u16, prob: u8, value: bool) {
1903        self.put(prob, value);
1904    }
1905}
1906
1907impl BoolSink for BoolEncoder {
1908    #[inline]
1909    fn put(&mut self, prob: u8, value: bool) {
1910        self.write_bool(prob, value);
1911    }
1912}
1913
1914/// [`encode_coeff_block`] into any [`BoolSink`].
1915fn encode_coeff_block_into<S: BoolSink>(
1916    enc: &mut S,
1917    block_type: BlockType,
1918    coeff_probs: &CoeffProbs,
1919    above_has_nonzero: bool,
1920    left_has_nonzero: bool,
1921    coeffs: &[i16; 16],
1922) -> Result<usize, TokenEncodeError> {
1923    let plane = block_type.plane_index();
1924    let first_coeff = block_type.first_coeff();
1925
1926    // One pass over the coded positions: the largest magnitude (for the
1927    // §13.2 range check — Cat6 maxes out at 67 + 2047 = 2114) and the
1928    // last non-zero coefficient, which tells the encoder where (if
1929    // anywhere) to emit the explicit EOB token. If the entire block is
1930    // zero the EOB lands at `first_coeff` immediately.
1931    let mut last_non_zero: i32 = -1;
1932    let mut max_abs = 0u16;
1933    for (i, &v) in coeffs.iter().enumerate().skip(first_coeff) {
1934        max_abs = max_abs.max(v.unsigned_abs());
1935        if v != 0 {
1936            last_non_zero = i as i32;
1937        }
1938    }
1939    if max_abs > 2114 {
1940        // Report the first offender.
1941        for (i, &v) in coeffs.iter().enumerate().skip(first_coeff) {
1942            if v.unsigned_abs() > 2114 {
1943                return Err(TokenEncodeError::CoefficientOutOfRange { index: i, value: v });
1944            }
1945        }
1946    }
1947    let token_paths = &*TOKEN_BIT_PATHS;
1948
1949    let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
1950    let mut prev_was_zero = false;
1951    let mut non_zero_count = 0usize;
1952
1953    let mut i = first_coeff;
1954    while i < 16 {
1955        let band = COEFF_BANDS[i];
1956        let probs = &coeff_probs[plane][band][ctx3];
1957
1958        // Decide what token to emit at this position.
1959        let emit_eob = (i as i32) > last_non_zero;
1960        let (token, abs_value, sign) = if emit_eob {
1961            (DctToken::Eob, 0u16, false)
1962        } else {
1963            let v = coeffs[i];
1964            let abs = v.unsigned_abs();
1965            (classify_coeff_token(abs), abs, v < 0)
1966        };
1967
1968        // The §13.2 "skip EOB branch" optimisation: enter the tree at
1969        // internal node 1 (raw index 2) when the previous coefficient
1970        // was a literal `DCT_0` — the decoder will not have read the
1971        // EOB-vs-rest split bit, so neither must we write it.
1972        let (path, path_len) = &token_paths[prev_was_zero as usize][token as usize];
1973        debug_assert!(*path_len > 0, "EOB cannot follow a literal DCT_0");
1974        let slot_base = (((plane * 8 + band) * 3 + ctx3) * 11) as u16;
1975        for step in &path[..*path_len as usize] {
1976            enc.put_tree(
1977                slot_base + step.prob_index as u16,
1978                probs[step.prob_index as usize],
1979                step.bit,
1980            );
1981        }
1982
1983        if token == DctToken::Eob {
1984            break;
1985        }
1986
1987        // Cat tokens carry a fixed-width little-endian extra-bits
1988        // suffix (MSB-first within the suffix per the decoder's
1989        // `read_extra_bits` loop), then the universal sign bit at
1990        // probability 128.
1991        if let Some((base, plist)) = cat_extras(token) {
1992            let extra = abs_value - base;
1993            let n = plist.len();
1994            for (j, &p) in plist.iter().enumerate() {
1995                let bit = ((extra >> (n - 1 - j)) & 1) == 1;
1996                enc.put(p, bit);
1997            }
1998        }
1999
2000        if abs_value != 0 {
2001            enc.put(128, sign);
2002            non_zero_count += 1;
2003        }
2004
2005        // §13.3 rollover of `ctx3` to the token's magnitude class.
2006        ctx3 = if abs_value == 0 {
2007            0
2008        } else if abs_value == 1 {
2009            1
2010        } else {
2011            2
2012        };
2013        prev_was_zero = token == DctToken::Dct0;
2014
2015        i += 1;
2016    }
2017
2018    Ok(non_zero_count)
2019}
2020
2021/// Phase-2 token-block encoder handle.
2022///
2023/// A thin wrapper around the §13 `encode_coeff_block` free function
2024/// that owns its own [`BoolEncoder`] + resolved `coeff_probs` table
2025/// and exposes a stateful `encode_block` method. Useful for the
2026/// higher-level encoder rounds that will emit many blocks into the
2027/// same partition.
2028///
2029/// The encoder is **stateless across blocks** in the §13.3 sense —
2030/// the `ctx3` rollover lives entirely inside `encode_coeff_block` and
2031/// the neighbour predictors are passed in per call. What the wrapper
2032/// owns is the underlying entropy-coder byte stream + the (large)
2033/// probability table.
2034#[derive(Debug)]
2035pub struct TokenEncoder {
2036    enc: BoolEncoder,
2037    coeff_probs: CoeffProbs,
2038}
2039
2040impl TokenEncoder {
2041    /// Build an encoder against the supplied resolved coefficient
2042    /// probabilities. Pass [`crate::DEFAULT_COEFF_PROBS`] (or the
2043    /// `merge_default_token_probs(&updates)` result) to match the
2044    /// `decode_block` path callers go through on the other side.
2045    pub fn new(coeff_probs: CoeffProbs) -> Self {
2046        TokenEncoder {
2047            enc: BoolEncoder::new(),
2048            coeff_probs,
2049        }
2050    }
2051
2052    /// Encode one 16-coefficient sub-block. See
2053    /// [`encode_coeff_block`] for the parameter semantics.
2054    pub fn encode_block(
2055        &mut self,
2056        block_type: BlockType,
2057        above_has_nonzero: bool,
2058        left_has_nonzero: bool,
2059        coeffs: &[i16; 16],
2060    ) -> Result<usize, TokenEncodeError> {
2061        encode_coeff_block(
2062            &mut self.enc,
2063            block_type,
2064            &self.coeff_probs,
2065            above_has_nonzero,
2066            left_has_nonzero,
2067            coeffs,
2068        )
2069    }
2070
2071    /// Finalise the underlying [`BoolEncoder`] and return the byte
2072    /// stream the decoder should consume.
2073    pub fn finish(self) -> Vec<u8> {
2074        self.enc.finish()
2075    }
2076
2077    /// Number of bytes committed so far (excludes the §7.3 4-byte
2078    /// flush trailer that [`finish`](Self::finish) will append).
2079    pub fn bytes_written(&self) -> usize {
2080        self.enc.bytes_written()
2081    }
2082}
2083
2084// ───────────────────────── Phase 2: per-MB block-set encoder ──────────────────
2085
2086use crate::dct_tokens::MbEntropyCtx;
2087use crate::forward_transform::{forward_dct_4x4, forward_wht_4x4, raster_to_scan};
2088use crate::frame::MbCoeffs;
2089use crate::intra_predict::{
2090    DEFAULT_ABOVE_PIXEL, DEFAULT_LEFT_PIXEL, predict_b4x4, predict_uv8x8, predict_y16x16,
2091};
2092use crate::inverse_transform::{add_residue_4x4, inverse_dct_4x4, inverse_wht_4x4};
2093use crate::macroblock::{
2094    BMODE_TREE, IF_UV_MODE_PROB_DEFAULTS, IF_YMODE_PROB_DEFAULTS, IF_YMODE_TREE, IntraBmode,
2095    IntraUvMode, IntraYMode, KF_BMODE_PROB, KF_UV_MODE_PROB, KF_YMODE_PROB, KF_YMODE_TREE,
2096    MacroblockModes, UV_MODE_TREE,
2097};
2098
2099mod effort;
2100mod inter;
2101mod inter_search;
2102mod pilot;
2103mod tape;
2104mod wavefront;
2105
2106pub use effort::{EncodeEffort, KeyframeEncodeOptions, KeyframeEncoded};
2107
2108/// Round-half-away-from-zero integer division — the natural inverse of
2109/// the §14.1 `q * factor` dequant multiply. Used by the encoder to
2110/// quantise a single 16-bit coefficient by an `i16` factor.
2111#[inline]
2112fn enc_round_div(num: i32, den: i32) -> i16 {
2113    debug_assert!(den > 0, "encoder quantiser factor must be positive");
2114    let r = if num >= 0 {
2115        (num + den / 2) / den
2116    } else {
2117        -(((-num) + den / 2) / den)
2118    };
2119    r as i16
2120}
2121
2122/// Quantise a raster-order 4×4 coefficient block in place against a
2123/// `(dc_factor, ac_factor)` pair — coefficient 0 is divided by `dc`,
2124/// coefficients 1..=15 by `ac`, with round-half-away-from-zero rounding.
2125/// This is the inverse of [`crate::dequant_block`].
2126#[inline]
2127fn enc_quantize_block(block: &mut [i16; 16], dc: i16, ac: i16) {
2128    block[0] = enc_round_div(block[0] as i32, dc as i32);
2129    for c in block.iter_mut().skip(1) {
2130        *c = enc_round_div(*c as i32, ac as i32);
2131    }
2132}
2133
2134/// Inputs to the §14 per-macroblock encoder — a single raw 16×16 Y plane
2135/// and two 8×8 chroma planes, plus a chosen quantizer.
2136///
2137/// Pixels are 8-bit unsigned (`u8`) in raster order. The MB encoder
2138/// computes the §11 / §12 intra prediction internally (Phase 2 ships
2139/// only the `DC_PRED` constant-prediction path for both luma and
2140/// chroma) and feeds the residual through §14 / §13.
2141#[derive(Debug, Clone, Copy)]
2142pub struct MbPixels {
2143    /// 16×16 Y plane, row-major.
2144    pub y: [u8; 256],
2145    /// 8×8 Cb plane, row-major.
2146    pub u: [u8; 64],
2147    /// 8×8 Cr plane, row-major.
2148    pub v: [u8; 64],
2149}
2150
2151/// Sum of squared differences (SSD) between a reconstructed candidate and
2152/// the source pixels — the distortion term `D` of the §-non-normative
2153/// rate-distortion cost `J = D + lambda * R`. Unlike SAD this matches the
2154/// MSE that PSNR is computed from, so minimising `D` at a fixed `R`
2155/// directly maximises self-decode PSNR. Computed in `u64` because a full
2156/// 16×16 luma block of maximal error sums to `256 * 255^2 ≈ 1.66e7`,
2157/// well inside `u64` (and even `u32`), but `u64` keeps the chroma + luma
2158/// accumulation headroom-free.
2159#[inline]
2160fn block_ssd(recon: &[u8], src: &[u8]) -> u64 {
2161    debug_assert_eq!(recon.len(), src.len());
2162    // A term is at most 255² and a block at most 256 pixels, so a `u32`
2163    // accumulator cannot overflow (4096-pixel chunks keep that true for
2164    // longer slices) and the loop vectorises.
2165    recon
2166        .chunks(4096)
2167        .zip(src.chunks(4096))
2168        .map(|(r, s)| {
2169            r.iter()
2170                .zip(s)
2171                .map(|(&a, &b)| {
2172                    let d = a as i32 - b as i32;
2173                    (d * d) as u32
2174                })
2175                .sum::<u32>() as u64
2176        })
2177        .sum()
2178}
2179
2180// ─────────────────────── rate-distortion cost machinery ───────────────────────
2181//
2182// RFC 6386 does not specify mode selection (§14.1 page 76: the spec
2183// "describes only the *decoding* process"); rate-distortion is therefore
2184// a non-normative encoder choice. The cost is the textbook Lagrangian
2185//
2186//     J = D + lambda * R
2187//
2188// where `D` is the reconstruction SSD against the source and `R` is the
2189// number of bits the candidate's tokens + mode signal will cost. The
2190// picker minimises `J` over the candidate modes.
2191//
2192// Bit cost (`R`). Every entropy-coded decision is a §7.3 `write_bool`
2193// against a probability `p` that the bit is 0. The information content of
2194// writing `value` is `-log2(P(value))` bits, with `P(0) = p / 256` and
2195// `P(1) = (256 - p) / 256`. The encoder accumulates these exactly (in
2196// fractional bits) without touching the real `BoolEncoder`, so the
2197// estimate equals the bits the token pass below will actually emit
2198// (modulo the §7.3 renormalisation, which adds < 1 byte per partition,
2199// not per block — negligible for a per-block relative comparison).
2200//
2201// Lambda. For a uniform quantiser of step `q`, high-rate RD theory gives
2202// `D ~ q^2 / 12` and the RD-optimal multiplier `lambda ~ c * q^2`. We use
2203// the luma AC dequant factor as the step `q` and a constant `c`
2204// calibrated so the trade stays mild (the picker should shave bits, not
2205// crater PSNR). See [`rd_lambda`].
2206
2207/// Cost in fractional bits of one §7.3 boolean written at probability
2208/// `prob` (the chance the bit is 0) carrying `value`. `-log2` of the
2209/// event probability. `prob` is clamped to `1..=255` so the logarithm is
2210/// always finite (the spec's probabilities are themselves in `1..=255`).
2211///
2212/// Round-170 perf note: this function is on the per-token-bit hot path
2213/// of the encoder's RD scoring (`estimate_block_bits` calls it for every
2214/// emitted bit of every candidate block, and the per-MB mode picker
2215/// scores many candidates). The per-call `f64::log2` was the single
2216/// dominant self-time symbol on a `sample` profile of the
2217/// `inter_encode_short_clip` bench (60 / 12,721 samples — see
2218/// `BENCHMARKS.md`). The implementation now consults a precomputed
2219/// 256-entry table: `BIT_COST_BY_FALSE_PROB[p]` stores
2220/// `-log2(p / 256)` (the bit-cost when the encoded bit is 0 and the
2221/// frame's table assigns it probability `p`), with the `p = 0` slot
2222/// clamped to `-log2(1/256) = 8.0` to match the original `prob.max(1)` +
2223/// floor-at-`1/256` clamp. The `true` branch reads slot `256 - p` (i.e.
2224/// `-log2(1 - p / 256)`), with the `p = 256` (encoded bit guaranteed 1)
2225/// case naturally handled by reading slot 0 of the same table — and the
2226/// `p = 0` (encoded bit guaranteed 0, asked for true) case staying at
2227/// the same `8.0` floor for symmetry.
2228#[inline]
2229pub(crate) fn bool_bits(prob: u8, value: bool) -> f64 {
2230    if value {
2231        // -log2(1 - prob/256). prob == 0 ⇒ index = 256, but we clamp
2232        // it to 255 (i.e. -log2(1/256) = 8.0) so the asymmetric
2233        // 1/256-floor of the original `p.max(1.0 / 256.0).log2()`
2234        // survives the rewrite without an extra branch.
2235        let idx = 256usize - prob as usize;
2236        BIT_COST_BY_FALSE_PROB[idx.min(255)]
2237    } else {
2238        BIT_COST_BY_FALSE_PROB[prob as usize]
2239    }
2240}
2241
2242/// `BIT_COST_BY_FALSE_PROB[p] = -log2(p / 256)` in fractional bits.
2243///
2244/// 257 entries are conceptually needed (`p ∈ 0..=256`), but the original
2245/// `bool_bits` clamps `prob` into `1..=255` and floors the resulting
2246/// probability at `1/256`, so the `p = 0` slot stores the same `8.0` as
2247/// `p = 1` (and the `value == true` branch's `256 - 0 = 256` index is
2248/// pre-clamped to `255` so we only ever read in-bounds). This table is
2249/// precomputed at module-load (`std::sync::OnceLock`) so the only
2250/// arithmetic on the hot path is the bool / index pair above.
2251static BIT_COST_BY_FALSE_PROB: std::sync::LazyLock<[f64; 256]> = std::sync::LazyLock::new(|| {
2252    let mut t = [0f64; 256];
2253    // p = 0 ⇒ same floor as the original `.max(1.0 / 256.0)` (i.e. 1/256).
2254    t[0] = -((1.0f64 / 256.0).log2());
2255    for (p, slot) in t.iter_mut().enumerate().skip(1) {
2256        // -log2(p / 256). `slot` is the lvalue.
2257        *slot = -((p as f64) / 256.0).log2();
2258    }
2259    t
2260});
2261
2262/// Depth-first search for the bit path from the root (node 0) of `tree`
2263/// to the leaf `-leaf`, written into the caller's fixed `path` buffer.
2264/// Returns the path length (0 when the leaf is unreachable, matching the
2265/// empty-path behaviour of the previous heap-allocating walk; debug
2266/// builds assert reachability).
2267///
2268/// The buffer is 16 entries: a §8.1 tree path visits distinct internal
2269/// nodes, so its length is bounded by the node count `tree.len() / 2`,
2270/// and the largest tree this crate walks (`BMODE_TREE`, 18 entries) has
2271/// 9 internal nodes. Round-276 profiling showed the per-call `Vec` this
2272/// replaces was a top allocator-churn source in the mode-RD loop.
2273fn treed_find_path(tree: &[i8], leaf: u8, path: &mut [bool; 16]) -> usize {
2274    fn dfs(tree: &[i8], i: i8, target: i8, path: &mut [bool; 16], len: &mut usize) -> bool {
2275        for bit in 0..2 {
2276            let next = tree[i as usize + bit];
2277            path[*len] = bit == 1;
2278            *len += 1;
2279            if next == target {
2280                return true;
2281            }
2282            if next > 0 && dfs(tree, next, target, path, len) {
2283                return true;
2284            }
2285            *len -= 1;
2286        }
2287        false
2288    }
2289    let mut len = 0;
2290    let found = dfs(tree, 0, -(leaf as i8), path, &mut len);
2291    debug_assert!(found, "leaf {leaf} not reachable in tree {tree:?}");
2292    len
2293}
2294
2295/// Cost in fractional bits of writing `value` through `tree` with the
2296/// per-node probability `prob_lookup`, mirroring [`BoolEncoder::write_treed`]
2297/// but accumulating `-log2(p)` instead of emitting. The RD scorers now
2298/// price against the precomputed [`treed_bits_cached`] tables; this
2299/// DFS-walk form is retained as the reference the
2300/// `treed_bits_cached_matches_dfs_walk` pin compares them to.
2301#[cfg_attr(not(test), allow(dead_code))]
2302fn treed_bits<F>(tree: &[i8], prob_lookup: F, leaf: u8) -> f64
2303where
2304    F: Fn(usize) -> u8,
2305{
2306    let mut path = [false; 16];
2307    let len = treed_find_path(tree, leaf, &mut path);
2308    let mut bits = 0.0;
2309    let mut i: i8 = 0;
2310    for &bit in &path[..len] {
2311        bits += bool_bits(prob_lookup((i as usize) >> 1), bit);
2312        i = tree[i as usize + bit as usize];
2313    }
2314    bits
2315}
2316
2317/// One leaf's precomputed §8.1 walk through a mode tree: the bit path
2318/// [`treed_find_path`] discovers, plus the node-halved probability-index
2319/// sequence [`treed_bits`] derives while replaying it. The trees the RD
2320/// scorers price against are compile-time constants, so the DFS is a
2321/// pure function of `(tree, leaf)` — precomputing it once per tree
2322/// removes the per-candidate `treed_find_path::dfs` walk (≈ 4 % of
2323/// keyframe-encode self-time on the round-409 profile) while replaying
2324/// the identical `(prob_index, bit)` step sequence in the identical
2325/// order, so every priced `f64` is bit-for-bit the DFS-walk value
2326/// (`treed_bits_cached_matches_dfs_walk` pins all four tables).
2327#[derive(Clone, Copy)]
2328struct TreedLeafPath {
2329    /// Number of valid steps in `bits` / `prob_index`.
2330    len: u8,
2331    /// The bit at each step of the root-to-leaf path.
2332    bits: [bool; 16],
2333    /// The node-halved probability index consumed at each step.
2334    prob_index: [u8; 16],
2335}
2336
2337/// Build the per-leaf path table for a mode tree whose leaves are
2338/// numbered `0..N` (true for every §8.1 mode tree this crate prices).
2339fn precompute_treed_paths<const N: usize>(tree: &[i8]) -> [TreedLeafPath; N] {
2340    core::array::from_fn(|leaf| {
2341        let mut bits = [false; 16];
2342        let len = treed_find_path(tree, leaf as u8, &mut bits);
2343        let mut prob_index = [0u8; 16];
2344        let mut i: i8 = 0;
2345        for (s, &bit) in bits[..len].iter().enumerate() {
2346            prob_index[s] = ((i as usize) >> 1) as u8;
2347            i = tree[i as usize + bit as usize];
2348        }
2349        TreedLeafPath {
2350            len: len as u8,
2351            bits,
2352            prob_index,
2353        }
2354    })
2355}
2356
2357/// Precomputed paths for the §11.2 keyframe luma mode tree.
2358static KF_YMODE_PATHS: std::sync::LazyLock<[TreedLeafPath; 5]> =
2359    std::sync::LazyLock::new(|| precompute_treed_paths(&KF_YMODE_TREE));
2360/// Precomputed paths for the §11.2 chroma mode tree (shared by the
2361/// keyframe and interframe chroma scorers — the tree is the same, only
2362/// the probability tables differ).
2363static UV_MODE_PATHS: std::sync::LazyLock<[TreedLeafPath; 4]> =
2364    std::sync::LazyLock::new(|| precompute_treed_paths(&UV_MODE_TREE));
2365/// Precomputed paths for the §11.2 / §11.4 4×4 sub-block mode tree.
2366static BMODE_PATHS: std::sync::LazyLock<[TreedLeafPath; 10]> =
2367    std::sync::LazyLock::new(|| precompute_treed_paths(&BMODE_TREE));
2368/// `KF_BMODE_BITS[above][left][mode]` — the §11.3 key-frame sub-block
2369/// mode-signal cost in bits: [`treed_bits_cached`] over [`BMODE_PATHS`]
2370/// against `KF_BMODE_PROB[above][left]`, for every context pair.
2371static KF_BMODE_BITS: std::sync::LazyLock<[[[f64; 10]; 10]; 10]> = std::sync::LazyLock::new(|| {
2372    core::array::from_fn(|above| {
2373        core::array::from_fn(|left| {
2374            let prob_row = &KF_BMODE_PROB[above][left];
2375            core::array::from_fn(|mode| {
2376                treed_bits_cached(&*BMODE_PATHS, |k| prob_row[k], mode as u8)
2377            })
2378        })
2379    })
2380});
2381/// Precomputed paths for the §11.3 interframe intra luma mode tree.
2382static IF_YMODE_PATHS: std::sync::LazyLock<[TreedLeafPath; 5]> =
2383    std::sync::LazyLock::new(|| precompute_treed_paths(&IF_YMODE_TREE));
2384
2385/// [`treed_bits`] against a precomputed path table: the same
2386/// `bool_bits(prob_lookup(node >> 1), bit)` accumulation in the same
2387/// step order, with the DFS and the node-chasing replay replaced by the
2388/// table row. Bit-for-bit the DFS-walk sum.
2389fn treed_bits_cached<F>(paths: &[TreedLeafPath], prob_lookup: F, leaf: u8) -> f64
2390where
2391    F: Fn(usize) -> u8,
2392{
2393    let p = &paths[leaf as usize];
2394    let mut bits = 0.0;
2395    for s in 0..p.len as usize {
2396        bits += bool_bits(prob_lookup(p.prob_index[s] as usize), p.bits[s]);
2397    }
2398    bits
2399}
2400
2401/// Estimate the bit cost of one §13.3 residual block exactly as
2402/// [`encode_coeff_block`] would emit it, but accumulating `-log2(p)`
2403/// fractional bits instead of writing to a [`BoolEncoder`]. The control
2404/// flow is a line-for-line mirror of `encode_coeff_block` so the estimate
2405/// tracks the real token pass (token tree path, cat extra bits, and the
2406/// per-coefficient sign bit), threading the same `ctx3` rollover.
2407///
2408/// `above_has_nonzero` / `left_has_nonzero` seed `ctx3` exactly as the
2409/// real encoder does. The block is in scan (zig-zag) order. Coefficients
2410/// out of the §13.2 alphabet are priced at the Cat6 maximum rather than
2411/// erroring — the RD picker only ever scores in-range quantiser output,
2412/// and an out-of-range candidate should simply lose.
2413fn estimate_block_bits(
2414    block_type: BlockType,
2415    coeff_probs: &CoeffProbs,
2416    above_has_nonzero: bool,
2417    left_has_nonzero: bool,
2418    coeffs: &[i16; 16],
2419) -> f64 {
2420    let plane = block_type.plane_index();
2421    let first_coeff = block_type.first_coeff();
2422
2423    let mut last_non_zero: i32 = -1;
2424    for (i, &v) in coeffs.iter().enumerate() {
2425        if i >= first_coeff && v != 0 {
2426            last_non_zero = i as i32;
2427        }
2428    }
2429
2430    let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
2431    let mut prev_was_zero = false;
2432    let mut bits = 0.0;
2433
2434    let mut i = first_coeff;
2435    while i < 16 {
2436        let band = COEFF_BANDS[i];
2437        let probs = &coeff_probs[plane][band][ctx3];
2438
2439        let emit_eob = (i as i32) > last_non_zero;
2440        let (token, abs_value, _sign) = if emit_eob {
2441            (DctToken::Eob, 0u16, false)
2442        } else {
2443            let v = coeffs[i];
2444            (
2445                classify_coeff_token(v.unsigned_abs()),
2446                v.unsigned_abs(),
2447                v < 0,
2448            )
2449        };
2450
2451        let start = if prev_was_zero { 2i8 } else { 0i8 };
2452        for step in token_to_bit_path(token, start) {
2453            bits += bool_bits(probs[step.prob_index as usize], step.bit);
2454        }
2455
2456        if token == DctToken::Eob {
2457            break;
2458        }
2459
2460        if let Some((base, plist)) = cat_extras(token) {
2461            // Cat6 caps the alphabet at 67 + 2047; price an out-of-range
2462            // value at its maximum extra-bits string so it loses the RD
2463            // race instead of panicking.
2464            let extra = abs_value.saturating_sub(base);
2465            let n = plist.len();
2466            for (j, &p) in plist.iter().enumerate() {
2467                let bit = ((extra >> (n - 1 - j)) & 1) == 1;
2468                bits += bool_bits(p, bit);
2469            }
2470        }
2471
2472        if abs_value != 0 {
2473            bits += bool_bits(128, false); // sign bit, flat probability
2474        }
2475
2476        ctx3 = if abs_value == 0 {
2477            0
2478        } else if abs_value == 1 {
2479            1
2480        } else {
2481            2
2482        };
2483        prev_was_zero = token == DctToken::Dct0;
2484        i += 1;
2485    }
2486
2487    bits
2488}
2489
2490/// [`estimate_block_bits`] priced from the per-frame
2491/// [`TrellisRateTables::step`] costs instead of per-step [`bool_bits`]
2492/// calls. The accumulation visits the same terms in the same order, and
2493/// each table entry is the very `f64` the direct call returns, so the sum
2494/// is bit-for-bit the reference estimate
2495/// (`estimate_block_bits_tabled_matches_direct`).
2496fn estimate_block_bits_tabled(
2497    tables: &TrellisRateTables,
2498    block_type: BlockType,
2499    above_has_nonzero: bool,
2500    left_has_nonzero: bool,
2501    coeffs: &[i16; 16],
2502) -> f64 {
2503    let first_coeff = block_type.first_coeff();
2504    let plane_steps = &tables.step[block_type.plane_index()];
2505    let paths = &*TOKEN_BIT_PATHS;
2506
2507    // One past the last non-zero scan position (`first_coeff` when none).
2508    let mut end = 16;
2509    while end > first_coeff && coeffs[end - 1] == 0 {
2510        end -= 1;
2511    }
2512
2513    let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
2514    let mut prev_was_zero = false;
2515    let mut bits = 0.0;
2516    for (i, &v) in coeffs.iter().enumerate().take(end).skip(first_coeff) {
2517        let steps = &plane_steps[COEFF_BANDS[i]][ctx3];
2518        let abs_value = v.unsigned_abs();
2519        let token = classify_coeff_token(abs_value);
2520        let (path, len) = &paths[prev_was_zero as usize][token as usize];
2521        for step in &path[..*len as usize] {
2522            bits += steps[step.prob_index as usize][step.bit as usize];
2523        }
2524        if let Some((base, plist)) = cat_extras(token) {
2525            let extra = abs_value.saturating_sub(base);
2526            let n = plist.len();
2527            for (j, &p) in plist.iter().enumerate() {
2528                let bit = ((extra >> (n - 1 - j)) & 1) == 1;
2529                bits += bool_bits(p, bit);
2530            }
2531        }
2532        if abs_value != 0 {
2533            bits += bool_bits(128, false);
2534        }
2535        ctx3 = level_ctx3(abs_value);
2536        prev_was_zero = abs_value == 0;
2537    }
2538    if end < 16 {
2539        // Explicit EOB: the root's left branch (node 0, bit 0). A block
2540        // never ends on a literal zero, so the root is always reachable.
2541        bits += plane_steps[COEFF_BANDS[end]][ctx3][0][0];
2542    }
2543    bits
2544}
2545
2546/// [`estimate_block_bits`] from the pre-summed per-token rates
2547/// ([`TrellisRateTables::small`] / [`TrellisRateTables::level_rate`] /
2548/// [`TrellisRateTables::eob`]): one table read per coefficient instead of
2549/// one per tree step.
2550///
2551/// It adds up exactly the terms the reference estimate adds, but grouped
2552/// per token, so the two results can differ in the last few units of
2553/// rounding and nowhere else. The mode pickers use it only to *rank*
2554/// candidates, behind [`RD_TIE_GUARD`].
2555fn estimate_block_bits_presummed(
2556    tables: &TrellisRateTables,
2557    block_type: BlockType,
2558    above_has_nonzero: bool,
2559    left_has_nonzero: bool,
2560    coeffs: &[i16; 16],
2561) -> f64 {
2562    let first_coeff = block_type.first_coeff();
2563    let plane = block_type.plane_index();
2564    let small = &tables.small[plane];
2565    let mut end = 16;
2566    while end > first_coeff && coeffs[end - 1] == 0 {
2567        end -= 1;
2568    }
2569    let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
2570    let mut prev_was_zero = 0usize;
2571    let mut bits = 0.0;
2572    for (i, &v) in coeffs.iter().enumerate().take(end).skip(first_coeff) {
2573        let level = v.unsigned_abs() as u32;
2574        let band = COEFF_BANDS[i];
2575        bits += if level <= TRELLIS_SMALL_LEVEL_MAX as u32 {
2576            small[band][ctx3][prev_was_zero][level as usize]
2577        } else {
2578            TrellisRateTables::level_rate(
2579                &small[band],
2580                &tables.cat_path[plane][band],
2581                ctx3,
2582                prev_was_zero == 1,
2583                level,
2584            )
2585        };
2586        ctx3 = (level as usize).min(2);
2587        prev_was_zero = (level == 0) as usize;
2588    }
2589    if end < 16 {
2590        bits += tables.eob[plane][COEFF_BANDS[end]][ctx3];
2591    }
2592    bits
2593}
2594
2595/// Margin below which two candidate costs ranked through
2596/// [`estimate_block_bits_presummed`] are treated as undecided.
2597///
2598/// A pre-summed token-bit total and the reference total are two
2599/// groupings of the same at most ~300 terms, each at most 8 bits, so they
2600/// agree to within `2 · 300 · 2^-53 · 2400 < 2e-10` bits; scaled by a
2601/// mode lambda of at most `157² / 32 < 771` and carried through the cost
2602/// expression (magnitude below `4e6`, one unit of rounding `< 1e-9`), a
2603/// ranking cost is within `2e-7` of the reference cost. When the leading
2604/// candidate beats every other by more than this guard — four orders of
2605/// magnitude wider — the reference costs order the same way with no tie,
2606/// so the reference search would pick the same candidate. Anything
2607/// closer is re-decided with the reference costs in the reference order.
2608const RD_TIE_GUARD: f64 = 1e-3;
2609
2610#[cfg(test)]
2611thread_local! {
2612    /// When set, [`decisive_minimum`] reports every decision as
2613    /// undecided, so the pickers run the reference search throughout —
2614    /// the oracle `ranked_search_matches_reference_search` compares the
2615    /// guarded ranking against.
2616    static FORCE_REFERENCE_SEARCH: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2617}
2618
2619/// The first minimum of `costs` and whether it leads every other entry
2620/// by more than [`RD_TIE_GUARD`].
2621fn decisive_minimum(costs: &[f64]) -> (usize, bool) {
2622    let mut best = 0usize;
2623    for (n, &cost) in costs.iter().enumerate().skip(1) {
2624        if cost < costs[best] {
2625            best = n;
2626        }
2627    }
2628    // Test hook: route every decision through the reference search.
2629    #[cfg(test)]
2630    if FORCE_REFERENCE_SEARCH.with(|f| f.get()) {
2631        return (best, false);
2632    }
2633    let decisive = costs
2634        .iter()
2635        .enumerate()
2636        .all(|(n, &cost)| n == best || cost - costs[best] > RD_TIE_GUARD);
2637    (best, decisive)
2638}
2639
2640/// Fraction of the mode-decision Lagrange multiplier the §13 coefficient
2641/// trellis spends at [`TrellisStrength::DEFAULT`] (`= 1.0`). Coefficient-level
2642/// RDO is a much finer rate lever than the mode picker (it can drop one
2643/// trailing coefficient instead of a whole mode), so applying the full mode
2644/// `lambda` over-trades PSNR for rate. Swept on the `natural_test_frame_64x64`
2645/// keyframe RD fixtures: at the raw mode lambda the trellis cuts keyframe
2646/// bytes ~45 % but loses 1–2.5 dB; `0.04` is the largest scale that *holds
2647/// the SAD-picker PSNR floor at every quantiser* (the conservative "shave
2648/// bits, never drop below the prior PSNR" regime the `rd_lambda` doctrine
2649/// targets) while still trimming 12–13 % of bytes at the low/mid quantisers
2650/// where VP8 keyframes actually operate. [`TrellisStrength`] multiplies this
2651/// base: a strength `> 1.0` spends more bits-vs-quality (smaller output,
2652/// steeper PSNR trade), `< 1.0` is more conservative, `0.0` disables the
2653/// trellis (plain round-quantisation).
2654const TRELLIS_LAMBDA_SCALE: f64 = 0.04;
2655
2656/// Trellis-quantiser aggressiveness knob — a clean-room encoder quality/size
2657/// dial multiplying the calibrated [`TRELLIS_LAMBDA_SCALE`] base.
2658///
2659/// RFC 6386 specifies only token *decoding*; the level-assignment search the
2660/// §13 trellis runs is a non-normative encoder decision (the spec is silent
2661/// on it by design), so this knob is entirely a clean-room rate/quality
2662/// control. `1.0` reproduces the historically-calibrated conservative trade
2663/// (hold the SAD-picker PSNR floor, trim 12–13 % of bytes); higher values
2664/// trade more PSNR for fewer bytes, `0.0` falls back to plain
2665/// round-quantisation (the pre-trellis bytes). The value is clamped to
2666/// `0.0..=MAX` so a caller cannot push the trellis into an unbounded
2667/// distortion regime.
2668#[derive(Debug, Clone, Copy, PartialEq)]
2669pub struct TrellisStrength(f64);
2670
2671impl TrellisStrength {
2672    /// The calibrated default — reproduces the round-354 trellis bytes
2673    /// exactly (`scale = 1.0 × TRELLIS_LAMBDA_SCALE`).
2674    pub const DEFAULT: TrellisStrength = TrellisStrength(1.0);
2675    /// Disable the trellis: every block falls back to plain
2676    /// round-quantisation (the pre-trellis wire).
2677    pub const OFF: TrellisStrength = TrellisStrength(0.0);
2678    /// Upper clamp. Beyond this the trellis zeroes nearly every AC
2679    /// coefficient at the working quantisers, so it is a safety rail rather
2680    /// than a useful operating point.
2681    pub const MAX: f64 = 8.0;
2682
2683    /// Build a strength from a raw multiplier, clamping into `0.0..=MAX`.
2684    /// `NaN` maps to the default (safe, conservative) rather than `OFF`.
2685    pub fn new(strength: f64) -> Self {
2686        if strength.is_nan() {
2687            return Self::DEFAULT;
2688        }
2689        TrellisStrength(strength.clamp(0.0, Self::MAX))
2690    }
2691
2692    /// The clamped multiplier.
2693    pub fn get(self) -> f64 {
2694        self.0
2695    }
2696
2697    /// The effective coefficient-level lambda scale — the calibrated base
2698    /// times this strength. `0.0` (the [`OFF`](Self::OFF) state) yields a
2699    /// zero scale, routing [`trellis_quantize_block`] to its plain-rounding
2700    /// fallback.
2701    fn lambda_scale(self) -> f64 {
2702        self.0 * TRELLIS_LAMBDA_SCALE
2703    }
2704}
2705
2706impl Default for TrellisStrength {
2707    fn default() -> Self {
2708        Self::DEFAULT
2709    }
2710}
2711
2712// ───────────────────────── §13 trellis coefficient quantisation ─────────────
2713//
2714// RFC 6386 specifies only the *decoding* of §13.3 residual tokens; the
2715// choice of which quantised level to assign each coefficient is a
2716// non-normative encoder decision (the spec is silent on it by design).
2717// The baseline `enc_quantize_block` rounds each coefficient independently
2718// (round-half-away-from-zero divide by the §14.1 step). That is optimal
2719// for distortion alone, but the §13.3 token stream couples successive
2720// coefficients: the `ctx3` carried into the next position depends on this
2721// coefficient's magnitude class (0 / 1 / ≥2), the band/EOB-skip depends on
2722// whether it was a literal `DCT_0`, and the implicit-EOB tail means
2723// trailing low-magnitude coefficients can cost many bits for little
2724// distortion reduction. Trellis quantisation jointly minimises the
2725// Lagrangian `J = D + lambda·R` over the level assignment by a Viterbi
2726// pass in scan order.
2727//
2728// **Candidate levels.** For each coefficient the search considers its
2729// rounded magnitude `m = round(|x| / q)` and `m − 1` (the standard
2730// down-only set: rounding up never both lowers rate and distortion, and a
2731// level above `round` raises distortion *and* — for magnitudes past the
2732// Dct token boundaries — rate). `m − 1 = 0` is the "drop to zero"
2733// candidate that the trellis spends elsewhere or terminates before. The
2734// sign always follows `x` (the §13.3 sign bit is a flat-128 bit, identical
2735// cost for either polarity).
2736//
2737// **Distortion.** Computed in the transform domain as
2738// `w_k · (x_k − level_k·q)^2`, where `w_k` is the squared L2 norm of the
2739// k-th inverse-DCT basis vector ([`IDCT_BASIS_NORM_SQ`]). Because the §14
2740// inverse transform is linear (modulo a sub-LSB rounding bit), summing the
2741// per-coefficient transform-domain errors weighted by their basis norms
2742// reproduces the pixel-domain reconstruction SSD — so this `D` is on the
2743// same scale as [`block_ssd`] and the existing [`rd_lambda`] applies
2744// unchanged.
2745//
2746// **Rate.** The exact §13.3 token bits for the chosen token at the
2747// position's band + context, including cat extra bits and the sign bit,
2748// priced through the same [`bool_bits`] table the mode pickers use.
2749//
2750// The trellis only *chooses levels*; reconstruction still runs the
2751// identical dequant → IDCT → add chain the decoder runs, so the
2752// encoder/decoder pixel-lockstep contract is preserved exactly.
2753
2754/// Squared L2 norm of each §14.4 inverse-DCT basis vector, indexed by
2755/// **scan position** (so entry `k` weights the error of scan coefficient
2756/// `k`). Computed once at module load by running the real
2757/// [`inverse_dct_4x4`] on a unit impulse at the raster position
2758/// `ZIGZAG[k]` and summing the squared outputs — i.e. the exact
2759/// pixel-domain energy one unit of quantisation error at scan position `k`
2760/// injects. Using the actual decoder IDCT (not an idealised orthonormal
2761/// transform) keeps the trellis distortion on the same scale as the
2762/// pixel-domain [`block_ssd`].
2763static IDCT_BASIS_NORM_SQ: std::sync::LazyLock<[f64; 16]> = std::sync::LazyLock::new(|| {
2764    let mut norms = [0f64; 16];
2765    for (k, slot) in norms.iter_mut().enumerate() {
2766        let raster = crate::dct_tokens::ZIGZAG[k];
2767        let mut coeffs = [0i16; 16];
2768        // A unit impulse large enough that the IDCT's `+4 >> 3` rounding
2769        // does not swallow the response, then normalise by the same
2770        // factor squared so the result is the per-unit basis energy.
2771        const IMPULSE: i16 = 256;
2772        coeffs[raster] = IMPULSE;
2773        let mut out = [0i16; 16];
2774        inverse_dct_4x4(&coeffs, &mut out);
2775        let energy: f64 = out.iter().map(|&v| (v as f64).powi(2)).sum();
2776        *slot = energy / (IMPULSE as f64).powi(2);
2777    }
2778    norms
2779});
2780
2781/// Exact §13.3 token-rate (in fractional bits) of coding `abs_level` at
2782/// scan position `i` with the entry context `ctx3` and the §13.2
2783/// "previous coefficient was DCT_0" EOB-skip flag `prev_was_zero`,
2784/// against the resolved `plane` probability bank. Includes the token-tree
2785/// bits, cat extra bits, and the flat-128 sign bit (for non-zero levels).
2786/// This is the per-position `R` term the trellis minimises against; it is
2787/// a slice of the same control flow [`estimate_block_bits`] walks.
2788#[inline]
2789fn coeff_token_bits(
2790    coeff_probs: &CoeffProbs,
2791    plane: usize,
2792    i: usize,
2793    ctx3: usize,
2794    prev_was_zero: bool,
2795    abs_level: u16,
2796) -> f64 {
2797    let band = COEFF_BANDS[i];
2798    let probs = &coeff_probs[plane][band][ctx3];
2799    let token = classify_coeff_token(abs_level);
2800    let start = if prev_was_zero { 2i8 } else { 0i8 };
2801    let mut bits = 0.0;
2802    for step in token_to_bit_path(token, start) {
2803        bits += bool_bits(probs[step.prob_index as usize], step.bit);
2804    }
2805    if let Some((base, plist)) = cat_extras(token) {
2806        let extra = abs_level.saturating_sub(base);
2807        let n = plist.len();
2808        for (j, &p) in plist.iter().enumerate() {
2809            let bit = ((extra >> (n - 1 - j)) & 1) == 1;
2810            bits += bool_bits(p, bit);
2811        }
2812    }
2813    if abs_level != 0 {
2814        bits += bool_bits(128, false); // sign bit, flat probability
2815    }
2816    bits
2817}
2818
2819/// Bits of the §13.3 EOB token at scan position `i` with context `ctx3`.
2820/// EOB is the first leaf of the §13.2 tree and is only reachable when the
2821/// previous coefficient was *not* a literal `DCT_0` (otherwise the decoder
2822/// has already skipped the EOB-vs-rest split). Returns the cost of the
2823/// single EOB branch bit.
2824#[inline]
2825fn eob_token_bits(coeff_probs: &CoeffProbs, plane: usize, i: usize, ctx3: usize) -> f64 {
2826    let band = COEFF_BANDS[i];
2827    let probs = &coeff_probs[plane][band][ctx3];
2828    // EOB is the left branch at the root (prob index 0, bit = false).
2829    bool_bits(probs[0], false)
2830}
2831
2832/// Map an absolute level to its §13.3 next-context class (0 / 1 / ≥2).
2833#[inline]
2834fn level_ctx3(abs_level: u16) -> usize {
2835    match abs_level {
2836        0 => 0,
2837        1 => 1,
2838        _ => 2,
2839    }
2840}
2841
2842/// Largest absolute level whose §13.3 token carries **no** cat extra
2843/// bits (`DCT_0` … `DCT_4`). For these the token rate is a pure function
2844/// of `(plane, band, ctx3, prev_was_zero, abs_level)` — the domain the
2845/// per-frame [`TrellisRateTables`] covers.
2846const TRELLIS_SMALL_LEVEL_MAX: u16 = 4;
2847
2848/// Per-frame precomputed §13.3 token-rate tables for the trellis hot
2849/// loop. `coeff_probs` is fixed for a whole frame, so every
2850/// [`coeff_token_bits`] / [`eob_token_bits`] value the Viterbi scan asks
2851/// for at the extra-bit-free levels (`0..=4`, the overwhelming majority
2852/// of candidates at the working quantisers) is a pure per-frame constant.
2853/// Each entry is filled by calling the reference functions themselves, so
2854/// a table lookup returns the **bit-for-bit identical** `f64` the direct
2855/// call would have produced — the trellis costs, and therefore every
2856/// chosen level and every emitted byte, cannot move.
2857///
2858/// Levels `≥ 5` (cat1–cat6, value-dependent extra bits) always take the
2859/// direct [`coeff_token_bits`] path.
2860struct TrellisRateTables {
2861    /// `small[plane][band][ctx3][prev_was_zero][abs_level]` — the exact
2862    /// [`coeff_token_bits`] value for `abs_level ∈ 0..=4`.
2863    small: [[[[[f64; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3]; 8]; 4],
2864    /// `eob[plane][band][ctx3]` — the exact [`eob_token_bits`] value.
2865    eob: [[[f64; 3]; 8]; 4],
2866    /// `step[plane][band][ctx3][prob_index][bit]` — the exact
2867    /// [`bool_bits`] cost of coding `bit` at §13.2 tree node
2868    /// `prob_index` against `coeff_probs[plane][band][ctx3]`, the
2869    /// per-step term [`estimate_block_bits`] accumulates.
2870    step: [[[[[f64; 2]; 11]; 3]; 8]; 4],
2871    /// `cat_path[plane][band][ctx3][prev_was_zero][cat]` — the §13.2
2872    /// tree-path part of [`coeff_token_bits`] for the six extra-bit
2873    /// tokens (`cat = token − Cat1`): the running sum that function holds
2874    /// before it adds the value-dependent extra bits and the sign bit.
2875    cat_path: [[[[[f64; 6]; 2]; 3]; 8]; 4],
2876    /// `zero_run[plane][k]` — the bits of literal `DCT_0` tokens at scan
2877    /// positions `0..k`, each following another `DCT_0` (context 0, no
2878    /// end-of-block branch): the prefix sums of
2879    /// `small[plane][band(j)][0][1][0]`. A run of zeros inside a block
2880    /// costs the difference of two entries.
2881    zero_run: [[f64; 17]; 4],
2882    /// `small` and `eob` already multiplied by the trellis's per-bit
2883    /// price — built on the first trellis call of the frame, for that
2884    /// call's price (one frame has one, or one per segment; any other
2885    /// price takes the multiply-as-you-go path, with the same products).
2886    priced: std::sync::OnceLock<Box<PricedRates>>,
2887}
2888
2889/// [`TrellisRateTables::small`] and [`TrellisRateTables::eob`] times a
2890/// per-bit price `lambda`: every entry is the `lambda * rate` product
2891/// the trellis step would otherwise form on each visit.
2892struct PricedRates {
2893    lambda: f64,
2894    small: [[[[[f64; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3]; 8]; 4],
2895    eob: [[[f64; 3]; 8]; 4],
2896}
2897
2898impl PricedRates {
2899    fn new(tables: &TrellisRateTables, lambda: f64) -> Box<Self> {
2900        let mut priced = Box::new(PricedRates {
2901            lambda,
2902            small: tables.small,
2903            eob: tables.eob,
2904        });
2905        let small = priced
2906            .small
2907            .as_flattened_mut()
2908            .as_flattened_mut()
2909            .as_flattened_mut()
2910            .as_flattened_mut();
2911        for rate in small.iter_mut() {
2912            *rate *= lambda;
2913        }
2914        for rate in priced.eob.as_flattened_mut().as_flattened_mut() {
2915            *rate *= lambda;
2916        }
2917        priced
2918    }
2919}
2920
2921impl TrellisRateTables {
2922    /// Build the tables for one frame's resolved `coeff_probs` by
2923    /// evaluating the reference rate functions at every covered point
2924    /// (≈ 1k calls — noise next to a single macroblock's mode search).
2925    fn for_probs(coeff_probs: &CoeffProbs) -> Self {
2926        // First scan position of each §13.3 band. `coeff_token_bits`
2927        // depends on the position only through `COEFF_BANDS[i]`, so any
2928        // representative position per band yields the identical value.
2929        let mut band_pos = [0usize; 8];
2930        for (band, pos) in band_pos.iter_mut().enumerate() {
2931            *pos = COEFF_BANDS
2932                .iter()
2933                .position(|&b| b == band)
2934                .expect("every §13.3 band has at least one scan position");
2935        }
2936        let mut tables = TrellisRateTables {
2937            small: [[[[[0.0; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3]; 8]; 4],
2938            eob: [[[0.0; 3]; 8]; 4],
2939            step: [[[[[0.0; 2]; 11]; 3]; 8]; 4],
2940            cat_path: [[[[[0.0; 6]; 2]; 3]; 8]; 4],
2941            zero_run: [[0.0; 17]; 4],
2942            priced: std::sync::OnceLock::new(),
2943        };
2944        for plane in 0..4 {
2945            for (band, &i) in band_pos.iter().enumerate() {
2946                for ctx3 in 0..3 {
2947                    let probs = &coeff_probs[plane][band][ctx3];
2948                    for (node, costs) in tables.step[plane][band][ctx3].iter_mut().enumerate() {
2949                        *costs = [bool_bits(probs[node], false), bool_bits(probs[node], true)];
2950                    }
2951                    for (pwz, slot) in tables.cat_path[plane][band][ctx3].iter_mut().enumerate() {
2952                        for (cat, cell) in slot.iter_mut().enumerate() {
2953                            let (path, len) = &TOKEN_BIT_PATHS[pwz][DctToken::Cat1 as usize + cat];
2954                            let mut bits = 0.0;
2955                            for step in &path[..*len as usize] {
2956                                bits += bool_bits(probs[step.prob_index as usize], step.bit);
2957                            }
2958                            *cell = bits;
2959                        }
2960                    }
2961                    tables.eob[plane][band][ctx3] = eob_token_bits(coeff_probs, plane, i, ctx3);
2962                    for (pwz, slot) in tables.small[plane][band][ctx3].iter_mut().enumerate() {
2963                        for (abs, cell) in slot.iter_mut().enumerate() {
2964                            *cell =
2965                                coeff_token_bits(coeff_probs, plane, i, ctx3, pwz == 1, abs as u16);
2966                        }
2967                    }
2968                }
2969            }
2970        }
2971        for plane in 0..4 {
2972            for k in 0..16 {
2973                tables.zero_run[plane][k + 1] =
2974                    tables.zero_run[plane][k] + tables.small[plane][COEFF_BANDS[k]][0][1][0];
2975            }
2976        }
2977        tables
2978    }
2979
2980    /// [`level_rate`](Self::level_rate) of one extra-bit level (`> 4`)
2981    /// from all three contexts at once — context 0 with the given
2982    /// "previous token was `DCT_0`" state, contexts 1 and 2 without (a
2983    /// non-zero level precedes them). Each context's sum takes the same
2984    /// additions in the same order as `level_rate`; only the token
2985    /// classification and the extra-bit costs are shared.
2986    #[inline]
2987    fn cat_level_rates(cat_path: &[[[f64; 6]; 2]; 3], zero_run: usize, level: u32) -> [f64; 3] {
2988        let abs_level = level as u16;
2989        let token = classify_coeff_token(abs_level);
2990        let cat = token as usize - DctToken::Cat1 as usize;
2991        let mut rates = [
2992            cat_path[0][zero_run][cat],
2993            cat_path[1][0][cat],
2994            cat_path[2][0][cat],
2995        ];
2996        if let Some((base, plist)) = cat_extras(token) {
2997            let extra = abs_level.saturating_sub(base);
2998            let n = plist.len();
2999            for (j, &p) in plist.iter().enumerate() {
3000                let cost = bool_bits(p, ((extra >> (n - 1 - j)) & 1) == 1);
3001                for rate in rates.iter_mut() {
3002                    *rate += cost;
3003                }
3004            }
3005        }
3006        let sign = bool_bits(128, false);
3007        for rate in rates.iter_mut() {
3008            *rate += sign;
3009        }
3010        rates
3011    }
3012
3013    /// [`coeff_token_bits`] for any level from the tables of one
3014    /// `(plane, band)` cell pair: a direct lookup up to level 4, else the
3015    /// tabled tree-path sum followed by the same extra-bit and sign-bit
3016    /// additions, in the same order (`level_rate_matches_coeff_token_bits`).
3017    #[inline]
3018    fn level_rate(
3019        small: &[[[f64; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3],
3020        cat_path: &[[[f64; 6]; 2]; 3],
3021        ctx3: usize,
3022        prev_was_zero: bool,
3023        level: u32,
3024    ) -> f64 {
3025        if level <= TRELLIS_SMALL_LEVEL_MAX as u32 {
3026            return small[ctx3][prev_was_zero as usize][level as usize];
3027        }
3028        let abs_level = level as u16;
3029        let token = classify_coeff_token(abs_level);
3030        let mut bits =
3031            cat_path[ctx3][prev_was_zero as usize][token as usize - DctToken::Cat1 as usize];
3032        if let Some((base, plist)) = cat_extras(token) {
3033            let extra = abs_level.saturating_sub(base);
3034            let n = plist.len();
3035            for (j, &p) in plist.iter().enumerate() {
3036                let bit = ((extra >> (n - 1 - j)) & 1) == 1;
3037                bits += bool_bits(p, bit);
3038            }
3039        }
3040        bits += bool_bits(128, false);
3041        bits
3042    }
3043}
3044
3045/// One Viterbi decision record of the retained test-module reference
3046/// trellis: accumulated cost, chosen absolute level, predecessor context.
3047#[cfg(test)]
3048#[derive(Clone, Copy)]
3049struct TrellisCell {
3050    cost: f64,
3051    level: u16,
3052    prev_ctx: usize,
3053}
3054
3055/// The per-block §13/§14 parameters a [`trellis_quantize_block`] call
3056/// needs beyond the coefficients themselves: the §14.1 dequant steps, the
3057/// §13.3 `firstCoeff`, the seeded entry context, and the `coeff_probs`
3058/// plane index. Bundled into one struct so the trellis entry point keeps a
3059/// small argument list.
3060#[derive(Clone, Copy)]
3061struct TrellisBlockSpec {
3062    /// §14.1 DC dequant step (coefficient 0).
3063    dc: i16,
3064    /// §14.1 AC dequant step (coefficients 1..15).
3065    ac: i16,
3066    /// §13.3 `firstCoeff` — 1 for `YAfterY2` (DC lives in Y2), else 0.
3067    first_coeff: usize,
3068    /// Seeded §13.3 neighbour non-zero context (`above + left`, 0..2).
3069    entry_ctx3: usize,
3070    /// `coeff_probs` outermost plane index for this block type.
3071    plane: usize,
3072}
3073
3074/// Trellis-quantise one raster-order 4×4 coefficient block in place,
3075/// minimising `J = D + lambda·R` over the §13.3 token stream.
3076///
3077/// `block` is the **raster-order** forward-DCT output; on return it holds
3078/// the trellis-chosen **raster-order** quantised levels (the same layout
3079/// `enc_quantize_block` produces), ready to feed `reconstruct_block_4x4`
3080/// and `encode_coeff_block`. `dc` / `ac` are the §14.1 dequant steps,
3081/// `spec` carries the §14.1 dequant steps, §13.3 `firstCoeff`, the seeded
3082/// neighbour non-zero context, and the `coeff_probs` plane index; `lambda`
3083/// is the per-bit distortion price.
3084///
3085/// Falls back to plain rounding when `lambda <= 0` (lossless / qi-0 paths
3086/// where the rate trade has no benefit), keeping those streams unchanged.
3087///
3088/// Two production forms share the recurrence of the retained test-module
3089/// reference, evaluated in the same order with the same `f64` expressions
3090/// (so every comparison, and therefore every chosen level, is identical):
3091/// [`trellis_scan_tabled`] when per-frame rate tables are supplied and
3092/// [`trellis_scan_direct`] otherwise. Both replace the per-coefficient
3093/// divisions with an exact reciprocal multiply. Pinned level-for-level
3094/// against the reference by `trellis_lut_and_early_exit_match_reference`.
3095fn trellis_quantize_block(
3096    block: &mut [i16; 16],
3097    spec: TrellisBlockSpec,
3098    coeff_probs: &CoeffProbs,
3099    tables: Option<&TrellisRateTables>,
3100    lambda: f64,
3101) {
3102    if lambda <= 0.0 {
3103        enc_quantize_block_range(block, spec.dc, spec.ac, spec.first_coeff);
3104        return;
3105    }
3106    match tables {
3107        Some(tables) => {
3108            let priced = tables
3109                .priced
3110                .get_or_init(|| PricedRates::new(tables, lambda));
3111            if priced.lambda == lambda {
3112                trellis_scan_tabled::<true>(
3113                    block,
3114                    spec,
3115                    (&priced.small, &priced.eob, &tables.cat_path),
3116                    lambda,
3117                )
3118            } else {
3119                trellis_scan_tabled::<false>(
3120                    block,
3121                    spec,
3122                    (&tables.small, &tables.eob, &tables.cat_path),
3123                    lambda,
3124                )
3125            }
3126        }
3127        None => trellis_scan_direct(block, spec, coeff_probs, lambda),
3128    }
3129}
3130
3131/// Scan-order view of one block for the trellis: coefficient magnitudes,
3132/// signs, round-half-up candidate levels, the per-position drop-to-zero
3133/// distortion with its suffix sums (accumulated from position 15
3134/// downward), and the last position whose candidate level is non-zero.
3135struct TrellisScan {
3136    ax: [u32; 16],
3137    negative: [bool; 16],
3138    m_rounds: [u32; 16],
3139    zero_dist: [f64; 16],
3140    suffix_zero_dist: [f64; 17],
3141    /// `None` when every in-scan coefficient rounds to level 0 — the
3142    /// search then provably returns the all-zero block.
3143    last_cand_nonzero: Option<usize>,
3144}
3145
3146impl TrellisScan {
3147    #[inline]
3148    fn new(block: &[i16; 16], dc_q: u32, ac_q: u32, first_coeff: usize) -> Self {
3149        let norms = &*IDCT_BASIS_NORM_SQ;
3150        let mut scan = TrellisScan {
3151            ax: [0; 16],
3152            negative: [false; 16],
3153            m_rounds: [0; 16],
3154            zero_dist: [0.0; 16],
3155            suffix_zero_dist: [0.0; 17],
3156            last_cand_nonzero: None,
3157        };
3158        for k in (first_coeff..16).rev() {
3159            let x = block[crate::dct_tokens::ZIGZAG[k]];
3160            let q = if k == 0 { dc_q } else { ac_q };
3161            let ax = x.unsigned_abs() as u32;
3162            scan.ax[k] = ax;
3163            scan.negative[k] = x < 0;
3164            scan.m_rounds[k] = rounded_level(ax, q);
3165            if scan.m_rounds[k] != 0 && scan.last_cand_nonzero.is_none() {
3166                scan.last_cand_nonzero = Some(k);
3167            }
3168            scan.zero_dist[k] = norms[k] * (ax as u64 * ax as u64) as f64;
3169            scan.suffix_zero_dist[k] = scan.suffix_zero_dist[k + 1] + scan.zero_dist[k];
3170        }
3171        scan
3172    }
3173
3174    /// Transform-domain distortion of coding position `k` at `level`.
3175    #[inline]
3176    fn dist(&self, k: usize, level: u32, q: u32) -> f64 {
3177        let err = self.ax[k] as i64 - level as i64 * q as i64;
3178        IDCT_BASIS_NORM_SQ[k] * (err * err) as f64
3179    }
3180}
3181
3182/// `if take { a } else { b }` — written as a value selection so the
3183/// trellis step compiles to conditional moves rather than
3184/// data-dependent branches.
3185#[inline(always)]
3186fn select<T: Copy>(take: bool, a: T, b: T) -> T {
3187    if take { a } else { b }
3188}
3189
3190/// `cost(c)` for each context `c` in the `ALIVE` set (bit `c`), infinity
3191/// for the others — the costs of a dead context, without forming them.
3192#[inline(always)]
3193fn alive_costs<const ALIVE: u8>(cost: impl Fn(usize) -> f64) -> [f64; 3] {
3194    [
3195        if ALIVE & 1 != 0 {
3196            cost(0)
3197        } else {
3198            f64::INFINITY
3199        },
3200        if ALIVE & 2 != 0 {
3201            cost(1)
3202        } else {
3203            f64::INFINITY
3204        },
3205        if ALIVE & 4 != 0 {
3206            cost(2)
3207        } else {
3208            f64::INFINITY
3209        },
3210    ]
3211}
3212
3213/// The first minimum of three costs and its index: a later entry wins
3214/// only when strictly smaller.
3215#[inline(always)]
3216fn first_min3(c: [f64; 3]) -> (f64, u8) {
3217    let lt1 = c[1] < c[0];
3218    let m01 = select(lt1, c[1], c[0]);
3219    let i01 = lt1 as u8;
3220    let lt2 = c[2] < m01;
3221    (select(lt2, c[2], m01), select(lt2, 2, i01))
3222}
3223
3224/// The trellis against the per-frame [`TrellisRateTables`].
3225///
3226/// Same recurrence and evaluation order as [`trellis_scan_direct`], with
3227/// the step specialised by the position's rounded level `m`. The
3228/// candidates are `m`, `m − 1` and `0` (those that exist) and the carried
3229/// context of a level is `min(level, 2)`, so:
3230///
3231/// * context 0 is only ever reached by level 0;
3232/// * context 1 by level 1 — the `m` candidate when `m = 1`, the `m − 1`
3233///   candidate when `m = 2`;
3234/// * context 2 by `m` when `m ≥ 2` and by `m − 1` when `m ≥ 3`.
3235///
3236/// Each next-context survivor is therefore the first minimum over a fixed
3237/// list of `(incoming context, candidate)` costs in the reference order
3238/// (incoming context outer, `m` before `m − 1`), which [`first_min3`]
3239/// reduces pairwise — a later entry wins only when strictly smaller at
3240/// every level, so ties resolve exactly as the sequential scan does. A
3241/// dead incoming context carries infinite cost and loses every strict
3242/// comparison just as if it had been skipped (no cost is ever NaN).
3243///
3244/// A survivor in context 0 always arrived through a literal zero except
3245/// before the first position, so the "previous token was `DCT_0`" flag
3246/// needs no per-survivor storage.
3247///
3248/// `PRICED` says the `small` / `eob` tables handed in already hold
3249/// `lambda * rate` ([`PricedRates`]); the products are the same `f64`s
3250/// either way.
3251#[allow(clippy::type_complexity)] // the three table shapes, spelled out once
3252fn trellis_scan_tabled<const PRICED: bool>(
3253    block: &mut [i16; 16],
3254    spec: TrellisBlockSpec,
3255    (small, eob, cat_path): (
3256        &[[[[[f64; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3]; 8]; 4],
3257        &[[[f64; 3]; 8]; 4],
3258        &[[[[[f64; 6]; 2]; 3]; 8]; 4],
3259    ),
3260    lambda: f64,
3261) {
3262    // The price of a tabled rate.
3263    let price = |rate: f64| if PRICED { rate } else { lambda * rate };
3264    let TrellisBlockSpec {
3265        dc,
3266        ac,
3267        first_coeff,
3268        entry_ctx3,
3269        plane,
3270    } = spec;
3271    let norms: &[f64; 16] = &IDCT_BASIS_NORM_SQ;
3272    let (dc_q, ac_q) = (dc as u32, ac as u32);
3273
3274    // Scan-order magnitudes, sign / non-zero-candidate bitmaps and
3275    // round-half-up candidate levels.
3276    let mut ax = [0u32; 16];
3277    let mut m_rounds = [0u32; 16];
3278    let mut negative = 0u32;
3279    let mut candidate = 0u32;
3280    for k in first_coeff..16 {
3281        let x = block[crate::dct_tokens::ZIGZAG[k]];
3282        ax[k] = x.unsigned_abs() as u32;
3283        negative |= ((x < 0) as u32) << k;
3284        let q = if k == 0 { dc_q } else { ac_q };
3285        m_rounds[k] = rounded_level(ax[k], q);
3286        candidate |= ((m_rounds[k] != 0) as u32) << k;
3287    }
3288    if candidate == 0 {
3289        *block = [0i16; 16];
3290        return;
3291    }
3292    let last = 31 - candidate.leading_zeros() as usize;
3293
3294    // Drop-to-zero distortion per position and its suffix sums,
3295    // accumulated from position 15 downward.
3296    let mut zero_dist = [0f64; 16];
3297    let mut suffix_zero_dist = [0f64; 17];
3298    for k in first_coeff..16 {
3299        zero_dist[k] = norms[k] * (ax[k] as u64 * ax[k] as u64) as f64;
3300    }
3301    for k in (first_coeff..16).rev() {
3302        suffix_zero_dist[k] = suffix_zero_dist[k + 1] + zero_dist[k];
3303    }
3304    let dist = |k: usize, level: u32, q: u32| -> f64 {
3305        let err = ax[k] as i64 - level as i64 * q as i64;
3306        norms[k] * (err * err) as f64
3307    };
3308
3309    let small = &small[plane];
3310    let cat_path = &cat_path[plane];
3311    let eob = &eob[plane];
3312
3313    const INF: f64 = f64::INFINITY;
3314    let mut surv = [INF, INF, INF];
3315    surv[entry_ctx3] = 0.0;
3316    let mut zero_run = 0usize;
3317    // Per position: predecessor context of each carried context, and the
3318    // level behind carried context 2 (contexts 0 / 1 imply levels 0 / 1).
3319    let mut choice_prev = [[0u8; 3]; 16];
3320    let mut choice_level2 = [0u16; 16];
3321
3322    let mut best_term_cost =
3323        0.0 + price(eob[COEFF_BANDS[first_coeff]][entry_ctx3]) + suffix_zero_dist[first_coeff];
3324    let mut best_term_pos = usize::MAX;
3325    let mut best_term_ctx = entry_ctx3;
3326
3327    // Which carried contexts hold a survivor (bit `c` for context `c`).
3328    // A position leaves context 0 alive always, context 1 only when its
3329    // rounded level is 1 or 2, context 2 only when it is 2 or more — so
3330    // after a zero a single context is alive, and the step below is
3331    // instantiated per alive set to price only the transitions that
3332    // exist. A dead context's cost stays infinite, exactly what the
3333    // sums over it would have produced.
3334    let mut alive = 1u8 << entry_ctx3;
3335
3336    macro_rules! step {
3337        ($alive:literal, $k:expr) => {{
3338            let k: usize = $k;
3339            let m = m_rounds[k];
3340            let band = COEFF_BANDS[k];
3341            let q = if k == 0 { dc_q } else { ac_q };
3342            let band_small = &small[band];
3343            let rows = [
3344                &band_small[0][zero_run],
3345                &band_small[1][0],
3346                &band_small[2][0],
3347            ];
3348            let [s0, s1, s2] = surv;
3349            let s = [s0, s1, s2];
3350
3351            // Context 0: first minimum of the level-0 costs.
3352            let d_zero = zero_dist[k];
3353            let (n0, p0) = first_min3(alive_costs::<$alive>(|i| s[i] + d_zero + price(rows[i][0])));
3354            // The costs of coding one non-zero `level` from each
3355            // context.
3356            let level_costs = |level: u32| -> [f64; 3] {
3357                let d = dist(k, level, q);
3358                if level <= TRELLIS_SMALL_LEVEL_MAX as u32 {
3359                    alive_costs::<$alive>(|i| s[i] + d + price(rows[i][level as usize]))
3360                } else {
3361                    let rates =
3362                        TrellisRateTables::cat_level_rates(&cat_path[band], zero_run, level);
3363                    alive_costs::<$alive>(|i| s[i] + d + lambda * rates[i])
3364                }
3365            };
3366            let (n1, p1, n2, p2, l2) = match m {
3367                0 => (INF, 0, INF, 0, 0),
3368                1 => {
3369                    let (n1, p1) = first_min3(level_costs(1));
3370                    (n1, p1, INF, 0, 0)
3371                }
3372                2 => {
3373                    let (n2, p2) = first_min3(level_costs(2));
3374                    let (n1, p1) = first_min3(level_costs(1));
3375                    (n1, p1, n2, p2, 2)
3376                }
3377                _ => {
3378                    // `m` then `m − 1` per incoming context, then across
3379                    // contexts.
3380                    let high = level_costs(m);
3381                    let low = level_costs(m - 1);
3382                    let take_low = [low[0] < high[0], low[1] < high[1], low[2] < high[2]];
3383                    let (n2, p2) = first_min3([
3384                        select(take_low[0], low[0], high[0]),
3385                        select(take_low[1], low[1], high[1]),
3386                        select(take_low[2], low[2], high[2]),
3387                    ]);
3388                    (INF, 0, n2, p2, m - take_low[p2 as usize] as u32)
3389                }
3390            };
3391            choice_prev[k] = [p0, p1, p2];
3392            choice_level2[k] = l2 as u16;
3393
3394            // Terminating after position k needs a non-zero level there:
3395            // carried context 1, then 2. A dead survivor's infinite cost
3396            // never beats the (finite) running best.
3397            if m != 0 {
3398                let (t1, t2) = if k + 1 < 16 {
3399                    let eob_next = &eob[COEFF_BANDS[k + 1]];
3400                    let tail = suffix_zero_dist[k + 1];
3401                    (
3402                        n1 + price(eob_next[1]) + tail,
3403                        n2 + price(eob_next[2]) + tail,
3404                    )
3405                } else {
3406                    (n1, n2)
3407                };
3408                let better = t1 < best_term_cost;
3409                best_term_cost = select(better, t1, best_term_cost);
3410                best_term_pos = select(better, k, best_term_pos);
3411                best_term_ctx = select(better, 1, best_term_ctx);
3412                let better = t2 < best_term_cost;
3413                best_term_cost = select(better, t2, best_term_cost);
3414                best_term_pos = select(better, k, best_term_pos);
3415                best_term_ctx = select(better, 2, best_term_ctx);
3416            }
3417
3418            surv = [n0, n1, n2];
3419            zero_run = 1;
3420            alive = match m {
3421                0 => 0b001,
3422                1 => 0b011,
3423                2 => 0b111,
3424                _ => 0b101,
3425            };
3426        }};
3427    }
3428
3429    for k in first_coeff..=last {
3430        match alive {
3431            0b001 => step!(0b001, k),
3432            0b010 => step!(0b010, k),
3433            0b100 => step!(0b100, k),
3434            0b011 => step!(0b011, k),
3435            0b101 => step!(0b101, k),
3436            _ => step!(0b111, k),
3437        }
3438    }
3439
3440    *block = [0i16; 16];
3441    if best_term_pos != usize::MAX {
3442        let mut k = best_term_pos;
3443        let mut ctx = best_term_ctx;
3444        loop {
3445            let level = match ctx {
3446                0 => 0,
3447                1 => 1,
3448                _ => choice_level2[k] as i16,
3449            };
3450            block[crate::dct_tokens::ZIGZAG[k]] = if (negative >> k) & 1 != 0 {
3451                -level
3452            } else {
3453                level
3454            };
3455            if k == first_coeff {
3456                break;
3457            }
3458            ctx = choice_prev[k][ctx] as usize;
3459            k -= 1;
3460        }
3461    }
3462}
3463
3464/// The trellis pricing every token through the direct reference rate
3465/// functions — the path the per-macroblock public entries take when no
3466/// per-frame tables exist. Level-for-level identical to
3467/// [`trellis_scan_tabled`].
3468fn trellis_scan_direct(
3469    block: &mut [i16; 16],
3470    spec: TrellisBlockSpec,
3471    coeff_probs: &CoeffProbs,
3472    lambda: f64,
3473) {
3474    let TrellisBlockSpec {
3475        dc,
3476        ac,
3477        first_coeff,
3478        entry_ctx3,
3479        plane,
3480    } = spec;
3481    let (dc_q, ac_q) = (dc as u32, ac as u32);
3482    let scan = TrellisScan::new(block, dc_q, ac_q, first_coeff);
3483    let Some(last) = scan.last_cand_nonzero else {
3484        *block = [0i16; 16];
3485        return;
3486    };
3487
3488    const INF: f64 = f64::INFINITY;
3489    // Survivor per carried context: accumulated cost and whether the
3490    // coefficient that produced it was a literal zero.
3491    let mut surv_cost = [INF; 3];
3492    let mut surv_pwz = [false; 3];
3493    surv_cost[entry_ctx3] = 0.0;
3494    // Decision records for the traceback.
3495    let mut choice_level = [[0u16; 3]; 16];
3496    let mut choice_prev = [[0u8; 3]; 16];
3497
3498    let entry_eob = eob_token_bits(coeff_probs, plane, first_coeff, entry_ctx3);
3499    let mut best_term_cost = 0.0 + lambda * entry_eob + scan.suffix_zero_dist[first_coeff];
3500    let mut best_term_pos = usize::MAX;
3501    let mut best_term_ctx = entry_ctx3;
3502
3503    for k in first_coeff..=last {
3504        let m = scan.m_rounds[k];
3505        let q = if k == 0 { dc_q } else { ac_q };
3506        // Candidates in evaluation order: the rounded level, one below it,
3507        // and zero — without repeats.
3508        let cands = [m, m.saturating_sub(1), 0];
3509        let ncand = (m as usize).min(2) + 1;
3510        let mut cand_dist = [0f64; 3];
3511        for c in 0..ncand {
3512            cand_dist[c] = if cands[c] == 0 {
3513                scan.zero_dist[k]
3514            } else {
3515                scan.dist(k, cands[c], q)
3516            };
3517        }
3518
3519        let mut next_cost = [INF; 3];
3520        let mut next_pwz = [false; 3];
3521        let mut next_level = [0u16; 3];
3522        let mut next_prev = [0u8; 3];
3523        for in_ctx in 0..3 {
3524            let base = surv_cost[in_ctx];
3525            if base >= INF {
3526                continue;
3527            }
3528            let pwz = surv_pwz[in_ctx];
3529            for c in 0..ncand {
3530                let level = cands[c];
3531                let r = coeff_token_bits(coeff_probs, plane, k, in_ctx, pwz, level as u16);
3532                let cost = base + cand_dist[c] + lambda * r;
3533                let out_ctx = level_ctx3(level as u16);
3534                if cost < next_cost[out_ctx] {
3535                    next_cost[out_ctx] = cost;
3536                    next_pwz[out_ctx] = level == 0;
3537                    next_level[out_ctx] = level as u16;
3538                    next_prev[out_ctx] = in_ctx as u8;
3539                }
3540            }
3541        }
3542        choice_level[k] = next_level;
3543        choice_prev[k] = next_prev;
3544
3545        // Terminating after position k needs a non-zero level there, i.e.
3546        // a survivor in carried context 1 or 2 (context 0 is reached only
3547        // through level 0).
3548        for (out_ctx, &cost) in next_cost.iter().enumerate().skip(1) {
3549            if cost >= INF {
3550                continue;
3551            }
3552            let term_cost = if k + 1 < 16 {
3553                cost + lambda * eob_token_bits(coeff_probs, plane, k + 1, out_ctx)
3554                    + scan.suffix_zero_dist[k + 1]
3555            } else {
3556                cost
3557            };
3558            if term_cost < best_term_cost {
3559                best_term_cost = term_cost;
3560                best_term_pos = k;
3561                best_term_ctx = out_ctx;
3562            }
3563        }
3564
3565        surv_cost = next_cost;
3566        surv_pwz = next_pwz;
3567    }
3568
3569    *block = [0i16; 16];
3570    if best_term_pos != usize::MAX {
3571        let mut k = best_term_pos;
3572        let mut ctx = best_term_ctx;
3573        loop {
3574            let level = choice_level[k][ctx] as i16;
3575            block[crate::dct_tokens::ZIGZAG[k]] = if scan.negative[k] { -level } else { level };
3576            if k == first_coeff {
3577                break;
3578            }
3579            ctx = choice_prev[k][ctx] as usize;
3580            k -= 1;
3581        }
3582    }
3583}
3584
3585/// `QUANT_RECIPROCAL[q] = floor(2^32 / q) + 1` for `q` in `1..1024` — the
3586/// multiplier that turns the trellis's round-half-up division into one
3587/// multiply and shift (see [`rounded_level`]).
3588const QUANT_RECIPROCAL: [u64; 1024] = {
3589    let mut table = [0u64; 1024];
3590    let mut q = 1usize;
3591    while q < 1024 {
3592        table[q] = (1u64 << 32) / q as u64 + 1;
3593        q += 1;
3594    }
3595    table
3596};
3597
3598/// `floor((magnitude + q / 2) / q)` — the round-half-up quantised level of
3599/// a coefficient magnitude at step `q`.
3600///
3601/// For `q < 1024` (every §14.1 step is far below that) the quotient comes
3602/// from a reciprocal multiply. With `r = floor(2^32 / q) + 1` we have
3603/// `r·q = 2^32 + e`, `0 < e <= q`, so `n·r / 2^32 = n/q + n·e / (q·2^32)`;
3604/// the excess stays below `1/q` — too small to carry the value across the
3605/// next integer — whenever `n·e < 2^32`, which `n < 2^17`, `q < 2^10`
3606/// guarantees. `rounded_level_matches_division` checks every pair.
3607#[inline(always)]
3608fn rounded_level(magnitude: u32, q: u32) -> u32 {
3609    let n = magnitude as u64 + (q / 2) as u64;
3610    if (q as usize) < QUANT_RECIPROCAL.len() && q != 0 {
3611        ((n * QUANT_RECIPROCAL[q as usize]) >> 32) as u32
3612    } else {
3613        (n / q as u64) as u32
3614    }
3615}
3616
3617/// Plain round-quantise a raster block but only from `first_coeff`
3618/// onward, leaving earlier slots zeroed. Used as the trellis's
3619/// `lambda <= 0` fallback so the §13.3 `firstCoeff` semantics match.
3620#[inline]
3621fn enc_quantize_block_range(block: &mut [i16; 16], dc: i16, ac: i16, first_coeff: usize) {
3622    if first_coeff == 0 {
3623        block[0] = enc_round_div(block[0] as i32, dc as i32);
3624    } else {
3625        block[0] = 0;
3626    }
3627    for c in block.iter_mut().skip(1) {
3628        *c = enc_round_div(*c as i32, ac as i32);
3629    }
3630}
3631
3632/// Per-macroblock rate-distortion context shared across the mode pickers:
3633/// the §14.1 dequant factors (so a candidate can be reconstructed exactly
3634/// as the decoder will), the resolved §13.5 coefficient probabilities (so
3635/// token bits are priced against the table the decoder retains), and the
3636/// derived Lagrange multiplier `lambda`.
3637struct MbRdCtx<'a> {
3638    factors: &'a crate::dequant::MbDequantFactors,
3639    coeff_probs: &'a CoeffProbs,
3640    /// Per-frame precomputed §13.3 trellis rate tables for `coeff_probs`
3641    /// (see [`TrellisRateTables`]). `None` routes the trellis to the
3642    /// direct reference rate calls — the values (and therefore the
3643    /// bytes) are identical either way; frame-level drivers pass
3644    /// `Some` so the cost of the tree walks is paid once per frame.
3645    rate_tables: Option<&'a TrellisRateTables>,
3646    lambda: f64,
3647    /// §13 trellis aggressiveness — multiplies the calibrated
3648    /// [`TRELLIS_LAMBDA_SCALE`] base. Decoupled from the mode-decision
3649    /// `lambda` above so dialing the coefficient trade does not perturb the
3650    /// mode picker's `J = SSD + lambda·R`. [`TrellisStrength::DEFAULT`]
3651    /// reproduces the historical bytes.
3652    trellis: TrellisStrength,
3653}
3654
3655impl MbRdCtx<'_> {
3656    /// The effective per-bit price the §13 trellis minimises against — the
3657    /// mode `lambda` scaled by the resolved [`TrellisStrength`]. When the
3658    /// strength is [`TrellisStrength::OFF`] this is `0.0`, routing
3659    /// [`trellis_quantize_block`] to its plain-rounding fallback.
3660    #[inline]
3661    fn trellis_lambda(&self) -> f64 {
3662        self.lambda * self.trellis.lambda_scale()
3663    }
3664
3665    /// Whether the §13 trellis is active for this macroblock (a positive
3666    /// mode lambda *and* a non-`OFF` strength).
3667    #[inline]
3668    fn trellis_active(&self) -> bool {
3669        self.trellis_lambda() > 0.0
3670    }
3671
3672    /// Token bits of one scan-order block for *ranking* candidates: the
3673    /// pre-summed estimate when per-frame tables are attached (see
3674    /// [`RD_TIE_GUARD`]), else the reference estimate itself.
3675    #[inline]
3676    fn ranking_block_bits(
3677        &self,
3678        block_type: BlockType,
3679        above_has_nonzero: bool,
3680        left_has_nonzero: bool,
3681        coeffs: &[i16; 16],
3682    ) -> f64 {
3683        match self.rate_tables {
3684            Some(tables) => estimate_block_bits_presummed(
3685                tables,
3686                block_type,
3687                above_has_nonzero,
3688                left_has_nonzero,
3689                coeffs,
3690            ),
3691            None => estimate_block_bits(
3692                block_type,
3693                self.coeff_probs,
3694                above_has_nonzero,
3695                left_has_nonzero,
3696                coeffs,
3697            ),
3698        }
3699    }
3700
3701    /// §13.3 token bits of one scan-order block — [`estimate_block_bits`],
3702    /// priced from the per-frame step table when one is attached (the
3703    /// two forms return the identical `f64`).
3704    #[inline]
3705    fn block_bits(
3706        &self,
3707        block_type: BlockType,
3708        above_has_nonzero: bool,
3709        left_has_nonzero: bool,
3710        coeffs: &[i16; 16],
3711    ) -> f64 {
3712        match self.rate_tables {
3713            Some(tables) => estimate_block_bits_tabled(
3714                tables,
3715                block_type,
3716                above_has_nonzero,
3717                left_has_nonzero,
3718                coeffs,
3719            ),
3720            None => estimate_block_bits(
3721                block_type,
3722                self.coeff_probs,
3723                above_has_nonzero,
3724                left_has_nonzero,
3725                coeffs,
3726            ),
3727        }
3728    }
3729}
3730
3731/// Derive the Lagrange multiplier from the frame quantiser.
3732///
3733/// Non-normative. We use `lambda = q^2 / 32` where `q` is the luma AC
3734/// dequant step (`factors.y1_ac`). The `q^2` shape is the high-rate
3735/// RD-optimal relation (distortion of a uniform quantiser scales as
3736/// `q^2`); the `/ 32` constant was calibrated on the keyframe round-trip
3737/// fixtures so the picker trims bits without dropping below the SAD
3738/// picker's PSNR. `lambda` is in (distortion-units / bit) — SSD per bit —
3739/// so a candidate must save more than `lambda` SSD-units to be worth one
3740/// extra bit.
3741#[inline]
3742fn rd_lambda(factors: &crate::dequant::MbDequantFactors) -> f64 {
3743    let q = factors.y1_ac as f64;
3744    q * q / 32.0
3745}
3746
3747/// Reconstruct one already-quantised 4×4 luma/chroma residual block on
3748/// top of `pred` (the candidate's prediction) exactly as the decoder
3749/// will — dequantise with `(dc, ac)`, §14.3 inverse DCT, add to the
3750/// predictor with the §14.5 clamp — and return the 16-pixel
3751/// reconstruction. The encoder feeds the same kernels the decoder runs
3752/// (`inverse_dct_4x4` / `add_residue_4x4`), so the SSD scored here is the
3753/// SSD the decoder produces.
3754#[inline]
3755fn reconstruct_block_4x4(pred: &[u8; 16], quant: &[i16; 16], dc: i16, ac: i16) -> [u8; 16] {
3756    let mut dq = *quant;
3757    dq[0] = (dq[0] as i32 * dc as i32) as i16;
3758    for c in dq.iter_mut().skip(1) {
3759        *c = (*c as i32 * ac as i32) as i16;
3760    }
3761    // §14.4 DC-only fast path (the per-candidate twin of the fused
3762    // decoder kernel's shortcut — see `inverse_dct_4x4_add_into`): with
3763    // every AC coefficient zero both separable passes carry only the DC
3764    // term and all sixteen residue outputs are `(dq[0] + 4) >> 3`, so the
3765    // reconstruction is one uniform add-clamp — and a pure predictor copy
3766    // when that value is 0 (which also covers the all-zero blocks the RD
3767    // fan-out and the §13 trellis produce constantly). Bit-exact against
3768    // the general path (`reconstruct_block_4x4_dc_only_matches_general`).
3769    if dq[1..].iter().all(|&c| c == 0) {
3770        let d = ((dq[0] as i32) + 4) >> 3;
3771        if d == 0 {
3772            return *pred;
3773        }
3774        let mut recon = [0u8; 16];
3775        for (r, &p) in recon.iter_mut().zip(pred.iter()) {
3776            *r = (p as i32 + d).clamp(0, 255) as u8;
3777        }
3778        return recon;
3779    }
3780    let mut residue = [0i16; 16];
3781    inverse_dct_4x4(&dq, &mut residue);
3782    let mut recon = [0u8; 16];
3783    add_residue_4x4(pred, &residue, &mut recon);
3784    recon
3785}
3786
3787/// The §12.2 whole-block luma transform/quant outcome for one candidate
3788/// mode, carried out of [`pick_y16x16_mode`] so the main encode path can
3789/// reuse the winner's coefficients instead of recomputing the FDCT.
3790struct WholeBlockLuma {
3791    /// The chosen §12.2 mode (DC / V / H / TM).
3792    mode: IntraYMode,
3793    /// The sixteen quantised Y sub-blocks (DC already moved into `y2`).
3794    y_coeffs: [[i16; 16]; 16],
3795    /// The quantised Y2 (WHT) block.
3796    y2_coeffs: [i16; 16],
3797    /// The §-non-normative RD cost `J = SSD + lambda * bits` of the
3798    /// chosen mode — the value the top-level luma decision compares
3799    /// against the §11.3 / §12.3 B_PRED pass.
3800    rd_cost: f64,
3801}
3802
3803/// Transform + quantise one whole-block luma candidate's residual exactly
3804/// as the §14 encode chain will (sixteen §14.4 4×4 FDCTs, §14.3 forward
3805/// WHT collecting the sub-block DCs into Y2), returning the quantised
3806/// Y / Y2 coefficients. Shared by the RD scorer and never recomputed for
3807/// the winner.
3808///
3809/// When `trellis` is `Some` the sixteen `YAfterY2` sub-blocks and the `Y2`
3810/// (WHT) block are quantised by the §13 [`trellis_quantize_block`] RD
3811/// search rather than plain rounding. The Y2 block is trellised against
3812/// `BlockType::Y2` (plane 1, full 0..15 scan), each Y sub-block against
3813/// `BlockType::YAfterY2` (plane 0, `firstCoeff = 1` — the DC now lives in
3814/// Y2 and is excluded). `None` preserves the plain-rounding bytes exactly.
3815fn transform_whole_block_luma_rd(
3816    src: &[u8; 256],
3817    pred: &[u8; 256],
3818    factors: &crate::dequant::MbDequantFactors,
3819    trellis: Option<&MbRdCtx>,
3820) -> ([[i16; 16]; 16], [i16; 16]) {
3821    let mut y = [[0i16; 16]; 16];
3822    for i in 0..4 {
3823        for j in 0..4 {
3824            let mut residual = [0i16; 16];
3825            for r in 0..4 {
3826                for c in 0..4 {
3827                    let off = (i * 4 + r) * 16 + (j * 4 + c);
3828                    residual[r * 4 + c] = src[off] as i16 - pred[off] as i16;
3829                }
3830            }
3831            let mut coeffs = [0i16; 16];
3832            forward_dct_4x4(&residual, &mut coeffs);
3833            y[i * 4 + j] = coeffs;
3834        }
3835    }
3836    // §14.3 forward WHT: collect the sixteen DCs into Y2, then zero each
3837    // Y sub-block's DC (it now lives in Y2).
3838    let mut y_dc_block = [0i16; 16];
3839    for (slot, blk) in y_dc_block.iter_mut().zip(y.iter()) {
3840        *slot = blk[0];
3841    }
3842    let mut y2 = [0i16; 16];
3843    forward_wht_4x4(&y_dc_block, &mut y2);
3844    for blk in y.iter_mut() {
3845        blk[0] = 0;
3846    }
3847    // Quantise (plain rounding, or §13 trellis when an RD context is given).
3848    match trellis {
3849        Some(rd) if rd.trellis_active() => {
3850            let tlambda = rd.trellis_lambda();
3851            trellis_quantize_block(
3852                &mut y2,
3853                TrellisBlockSpec {
3854                    dc: factors.y2_dc,
3855                    ac: factors.y2_ac,
3856                    first_coeff: 0,
3857                    entry_ctx3: 0,
3858                    plane: BlockType::Y2.plane_index(),
3859                },
3860                rd.coeff_probs,
3861                rd.rate_tables,
3862                tlambda,
3863            );
3864            for blk in y.iter_mut() {
3865                trellis_quantize_block(
3866                    blk,
3867                    TrellisBlockSpec {
3868                        dc: factors.y1_dc,
3869                        ac: factors.y1_ac,
3870                        first_coeff: BlockType::YAfterY2.first_coeff(),
3871                        entry_ctx3: 0,
3872                        plane: BlockType::YAfterY2.plane_index(),
3873                    },
3874                    rd.coeff_probs,
3875                    rd.rate_tables,
3876                    tlambda,
3877                );
3878            }
3879        }
3880        _ => {
3881            enc_quantize_block(&mut y2, factors.y2_dc, factors.y2_ac);
3882            for blk in y.iter_mut() {
3883                enc_quantize_block(blk, factors.y1_dc, factors.y1_ac);
3884            }
3885        }
3886    }
3887    (y, y2)
3888}
3889
3890/// Reconstruct a whole-block luma candidate from its quantised Y / Y2
3891/// coefficients exactly as the decoder will (dequantise, §14.3 inverse
3892/// WHT to recover each sub-block DC, §14.3 inverse DCT, §14.5 add), and
3893/// return the 256-pixel reconstruction so the picker can score its SSD.
3894fn reconstruct_whole_block_luma(
3895    pred: &[u8; 256],
3896    y_quant: &[[i16; 16]; 16],
3897    y2_quant: &[i16; 16],
3898    factors: &crate::dequant::MbDequantFactors,
3899) -> [u8; 256] {
3900    // Dequantise Y2 and recover the sixteen sub-block DCs via inverse WHT.
3901    let mut y2 = *y2_quant;
3902    y2[0] = (y2[0] as i32 * factors.y2_dc as i32) as i16;
3903    for c in y2.iter_mut().skip(1) {
3904        *c = (*c as i32 * factors.y2_ac as i32) as i16;
3905    }
3906    let mut dcs = [0i16; 16];
3907    inverse_wht_4x4(&y2, &mut dcs);
3908
3909    let mut recon = [0u8; 256];
3910    for i in 0..4 {
3911        for j in 0..4 {
3912            let idx = i * 4 + j;
3913            let mut blk = y_quant[idx];
3914            // Seed this sub-block's DC from the WHT output, then dequant
3915            // the ACs with the Y1 factor.
3916            blk[0] = dcs[idx];
3917            for c in blk.iter_mut().skip(1) {
3918                *c = (*c as i32 * factors.y1_ac as i32) as i16;
3919            }
3920            let mut residue = [0i16; 16];
3921            inverse_dct_4x4(&blk, &mut residue);
3922            let mut sb_pred = [0u8; 16];
3923            for r in 0..4 {
3924                for c in 0..4 {
3925                    sb_pred[r * 4 + c] = pred[(i * 4 + r) * 16 + (j * 4 + c)];
3926                }
3927            }
3928            let mut sb_recon = [0u8; 16];
3929            add_residue_4x4(&sb_pred, &residue, &mut sb_recon);
3930            for r in 0..4 {
3931                for c in 0..4 {
3932                    recon[(i * 4 + r) * 16 + (j * 4 + c)] = sb_recon[r * 4 + c];
3933                }
3934            }
3935        }
3936    }
3937    recon
3938}
3939
3940/// Estimate the token bits of one whole-block luma candidate: the §13.3
3941/// Y2 block plus the sixteen Y sub-blocks (DC carried in Y2, so the Y
3942/// blocks code from coefficient 1). Threads the §13.3 above/left
3943/// non-zero predictors locally — the picker scores an isolated MB, which
3944/// matches the relative ranking the frame-shared contexts produce (a
3945/// neighbour's non-zero state shifts every candidate's first-band cost by
3946/// the same amount, so it does not change the winner).
3947///
3948/// `ranking` selects the pre-summed per-block estimate (see
3949/// [`RD_TIE_GUARD`]); `false` is the reference estimate.
3950fn estimate_whole_block_luma_bits(
3951    rd: &MbRdCtx,
3952    y_quant: &[[i16; 16]; 16],
3953    y2_quant: &[i16; 16],
3954    ranking: bool,
3955) -> f64 {
3956    let mut above = MbEntropyCtx::default();
3957    let mut left = MbEntropyCtx::default();
3958    let mut bits = 0.0;
3959
3960    let scan_y2 = raster_to_scan(y2_quant);
3961    bits += estimate_block_bits_with_ctx(
3962        24,
3963        BlockType::Y2,
3964        rd,
3965        &scan_y2,
3966        &mut above,
3967        &mut left,
3968        ranking,
3969    );
3970    for (i, blk) in y_quant.iter().enumerate() {
3971        let scan = raster_to_scan(blk);
3972        bits += estimate_block_bits_with_ctx(
3973            i,
3974            BlockType::YAfterY2,
3975            rd,
3976            &scan,
3977            &mut above,
3978            &mut left,
3979            ranking,
3980        );
3981    }
3982    bits
3983}
3984
3985/// §13.3 token bits of the eight chroma blocks of one candidate (4 U
3986/// sub-blocks 16..19, then 4 V 20..23), threading the local above / left
3987/// non-zero contexts. `ranking` as in [`estimate_whole_block_luma_bits`].
3988fn estimate_chroma_bits(
3989    rd: &MbRdCtx,
3990    u_quant: &[[i16; 16]; 4],
3991    v_quant: &[[i16; 16]; 4],
3992    ranking: bool,
3993) -> f64 {
3994    let mut above = MbEntropyCtx::default();
3995    let mut left = MbEntropyCtx::default();
3996    let mut token_bits = 0.0;
3997    for (i, blk) in u_quant.iter().chain(v_quant.iter()).enumerate() {
3998        let scan = raster_to_scan(blk);
3999        token_bits += estimate_block_bits_with_ctx(
4000            16 + i,
4001            BlockType::UV,
4002            rd,
4003            &scan,
4004            &mut above,
4005            &mut left,
4006            ranking,
4007        );
4008    }
4009    token_bits
4010}
4011
4012/// Bit cost of one residual block at `block_index`, threading the §13.3
4013/// / §20.16 above/left non-zero predictor contexts in place — the
4014/// estimator partner of [`encode_block_with_ctx`].
4015fn estimate_block_bits_with_ctx(
4016    block_index: usize,
4017    block_type: BlockType,
4018    rd: &MbRdCtx,
4019    scan_coeffs: &[i16; 16],
4020    above: &mut MbEntropyCtx,
4021    left: &mut MbEntropyCtx,
4022    ranking: bool,
4023) -> f64 {
4024    const LEFT_CTX: [usize; 25] = [
4025        0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
4026    ];
4027    const ABOVE_CTX: [usize; 25] = [
4028        0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8,
4029    ];
4030    let a_slot = ABOVE_CTX[block_index];
4031    let l_slot = LEFT_CTX[block_index];
4032    let (a_nonzero, l_nonzero) = (above.nonzero[a_slot], left.nonzero[l_slot]);
4033    let bits = if ranking {
4034        rd.ranking_block_bits(block_type, a_nonzero, l_nonzero, scan_coeffs)
4035    } else {
4036        rd.block_bits(block_type, a_nonzero, l_nonzero, scan_coeffs)
4037    };
4038    let first = block_type.first_coeff();
4039    let has_coeffs = scan_coeffs[first..].iter().any(|&v| v != 0);
4040    above.nonzero[a_slot] = has_coeffs;
4041    left.nonzero[l_slot] = has_coeffs;
4042    bits
4043}
4044
4045/// Pick the §12.2 whole-block 16×16 luma intra mode (DC / V / H / TM) by
4046/// the §-non-normative rate-distortion cost `J = SSD + lambda * R`. Each
4047/// candidate is run through the full §14 chain — predict, FDCT, Y2/WHT,
4048/// quantise, then dequantise + inverse-transform + reconstruct — so the
4049/// distortion `D` is the exact self-decode SSD and the rate `R` is the
4050/// §13.3 token bits plus the §11.2 luma-mode-signal bits.
4051///
4052/// Returns the winning [`WholeBlockLuma`] (mode, prediction, quantised
4053/// Y / Y2 coefficients, and RD cost). `topleft` is the (-1,-1) corner
4054/// pixel TM_PRED reads; supply [`crate::intra_predict::DEFAULT_ABOVE_PIXEL`]
4055/// when the corner is off-frame, mirroring the decoder's
4056/// `decode_keyframe_mb_non_bpred` convention.
4057fn pick_y16x16_mode(
4058    src: &[u8; 256],
4059    above: Option<&[u8; 16]>,
4060    left: Option<&[u8; 16]>,
4061    topleft: u8,
4062    rd: &MbRdCtx,
4063) -> WholeBlockLuma {
4064    const CANDIDATES: [IntraYMode; 4] =
4065        [IntraYMode::Dc, IntraYMode::V, IntraYMode::H, IntraYMode::Tm];
4066    // Every candidate goes through the full chain; the token bits are
4067    // first taken from the pre-summed ranking estimate.
4068    let mut quant = [([[0i16; 16]; 16], [0i16; 16]); 4];
4069    let mut ssd = [0f64; 4];
4070    let mut mode_bits = [0f64; 4];
4071    let mut ranking_cost = [0f64; 4];
4072    for (n, &mode) in CANDIDATES.iter().enumerate() {
4073        let mut pred = [0u8; 256];
4074        // predict_y16x16 returns None only for B_PRED, which is not in
4075        // CANDIDATES, so this is always Some.
4076        predict_y16x16(&mut pred, mode, above, left, topleft).expect("CANDIDATES excludes B_PRED");
4077
4078        let (y_quant, y2_quant) = transform_whole_block_luma_rd(src, &pred, rd.factors, Some(rd));
4079        let recon = reconstruct_whole_block_luma(&pred, &y_quant, &y2_quant, rd.factors);
4080        ssd[n] = block_ssd(&recon, src) as f64;
4081        mode_bits[n] = treed_bits_cached(&*KF_YMODE_PATHS, |i| KF_YMODE_PROB[i], mode.leaf());
4082        let token_bits = estimate_whole_block_luma_bits(rd, &y_quant, &y2_quant, true);
4083        ranking_cost[n] = ssd[n] + rd.lambda * (token_bits + mode_bits[n]);
4084        quant[n] = (y_quant, y2_quant);
4085    }
4086    // The reference cost of a candidate: exact token bits.
4087    let reference_cost = |n: usize| {
4088        let token_bits = estimate_whole_block_luma_bits(rd, &quant[n].0, &quant[n].1, false);
4089        ssd[n] + rd.lambda * (token_bits + mode_bits[n])
4090    };
4091    let (leader, decisive) = decisive_minimum(&ranking_cost);
4092    let (winner, rd_cost) = if decisive {
4093        (leader, reference_cost(leader))
4094    } else {
4095        // Too close to call on the ranking estimate: the reference
4096        // search — first strictly smaller reference cost wins.
4097        let mut winner = 0usize;
4098        let mut best_cost = reference_cost(0);
4099        for n in 1..CANDIDATES.len() {
4100            let cost = reference_cost(n);
4101            if cost < best_cost {
4102                best_cost = cost;
4103                winner = n;
4104            }
4105        }
4106        (winner, best_cost)
4107    };
4108    WholeBlockLuma {
4109        mode: CANDIDATES[winner],
4110        y_coeffs: quant[winner].0,
4111        y2_coeffs: quant[winner].1,
4112        rd_cost,
4113    }
4114}
4115
4116/// One chroma plane's source pixels plus its three §12 prediction
4117/// edges, bundled so [`pick_uv8x8_mode`] takes one argument per plane
4118/// instead of six positional inputs.
4119struct ChromaPlane<'a> {
4120    src: &'a [u8; 64],
4121    above: Option<&'a [u8; 8]>,
4122    left: Option<&'a [u8; 8]>,
4123    topleft: u8,
4124}
4125
4126/// Transform + quantise one 8×8 chroma plane's residual into its four
4127/// §13.3 `UV` sub-blocks (each carrying its own DC — chroma has no Y2),
4128/// returning the quantised blocks in raster sub-block order (`i*2 + j`).
4129///
4130/// When `trellis` is `Some` each `UV` sub-block is quantised by the §13
4131/// [`trellis_quantize_block`] RD search (plane 2, `firstCoeff = 0`);
4132/// `None` preserves plain-rounding bytes.
4133fn transform_chroma_plane_rd(
4134    src: &[u8; 64],
4135    pred: &[u8; 64],
4136    factors: &crate::dequant::MbDequantFactors,
4137    trellis: Option<&MbRdCtx>,
4138) -> [[i16; 16]; 4] {
4139    let mut blocks = [[0i16; 16]; 4];
4140    for i in 0..2 {
4141        for j in 0..2 {
4142            let mut residual = [0i16; 16];
4143            for r in 0..4 {
4144                for c in 0..4 {
4145                    let off = (i * 4 + r) * 8 + (j * 4 + c);
4146                    residual[r * 4 + c] = src[off] as i16 - pred[off] as i16;
4147                }
4148            }
4149            let mut coeffs = [0i16; 16];
4150            forward_dct_4x4(&residual, &mut coeffs);
4151            match trellis {
4152                Some(rd) if rd.trellis_active() => trellis_quantize_block(
4153                    &mut coeffs,
4154                    TrellisBlockSpec {
4155                        dc: factors.uv_dc,
4156                        ac: factors.uv_ac,
4157                        first_coeff: BlockType::UV.first_coeff(),
4158                        entry_ctx3: 0,
4159                        plane: BlockType::UV.plane_index(),
4160                    },
4161                    rd.coeff_probs,
4162                    rd.rate_tables,
4163                    rd.trellis_lambda(),
4164                ),
4165                _ => enc_quantize_block(&mut coeffs, factors.uv_dc, factors.uv_ac),
4166            }
4167            blocks[i * 2 + j] = coeffs;
4168        }
4169    }
4170    blocks
4171}
4172
4173/// Reconstruct one 8×8 chroma plane from its four quantised `UV`
4174/// sub-blocks on top of `pred`, returning the 64-pixel reconstruction
4175/// (the exact pixels the decoder produces) for SSD scoring.
4176fn reconstruct_chroma_plane(
4177    pred: &[u8; 64],
4178    quant: &[[i16; 16]; 4],
4179    factors: &crate::dequant::MbDequantFactors,
4180) -> [u8; 64] {
4181    let mut recon = [0u8; 64];
4182    for i in 0..2 {
4183        for j in 0..2 {
4184            let mut sb_pred = [0u8; 16];
4185            for r in 0..4 {
4186                for c in 0..4 {
4187                    sb_pred[r * 4 + c] = pred[(i * 4 + r) * 8 + (j * 4 + c)];
4188                }
4189            }
4190            let sb_recon =
4191                reconstruct_block_4x4(&sb_pred, &quant[i * 2 + j], factors.uv_dc, factors.uv_ac);
4192            for r in 0..4 {
4193                for c in 0..4 {
4194                    recon[(i * 4 + r) * 8 + (j * 4 + c)] = sb_recon[r * 4 + c];
4195                }
4196            }
4197        }
4198    }
4199    recon
4200}
4201
4202/// Pick the §12.2 whole-block 8×8 chroma intra mode (DC / V / H / TM) by
4203/// the rate-distortion cost `J = SSD + lambda * R`, jointly over both
4204/// chroma planes (VP8 codes a single `uv_mode` shared by Cb and Cr). Each
4205/// candidate is reconstructed through the full §14 chain; `D` is the
4206/// summed self-decode SSD across U and V, `R` the eight §13.3 `UV`-block
4207/// token bits plus the §11.4 chroma-mode-signal bits. Returns the joint
4208/// winner plus its quantised `U` / `V` blocks (the blocks the residual
4209/// pass emits — re-deriving them would repeat the same deterministic
4210/// transform and quantisation).
4211fn pick_uv8x8_mode(
4212    u: &ChromaPlane,
4213    v: &ChromaPlane,
4214    rd: &MbRdCtx,
4215) -> (IntraUvMode, [[i16; 16]; 4], [[i16; 16]; 4]) {
4216    const CANDIDATES: [IntraUvMode; 4] = [
4217        IntraUvMode::Dc,
4218        IntraUvMode::V,
4219        IntraUvMode::H,
4220        IntraUvMode::Tm,
4221    ];
4222    let mut quant = [([[0i16; 16]; 4], [[0i16; 16]; 4]); 4];
4223    let mut ssd = [0f64; 4];
4224    let mut mode_bits = [0f64; 4];
4225    let mut ranking_cost = [0f64; 4];
4226    for (n, &mode) in CANDIDATES.iter().enumerate() {
4227        let mut u_pred = [0u8; 64];
4228        let mut v_pred = [0u8; 64];
4229        predict_uv8x8(&mut u_pred, mode, u.above, u.left, u.topleft);
4230        predict_uv8x8(&mut v_pred, mode, v.above, v.left, v.topleft);
4231
4232        let u_quant = transform_chroma_plane_rd(u.src, &u_pred, rd.factors, Some(rd));
4233        let v_quant = transform_chroma_plane_rd(v.src, &v_pred, rd.factors, Some(rd));
4234        let u_recon = reconstruct_chroma_plane(&u_pred, &u_quant, rd.factors);
4235        let v_recon = reconstruct_chroma_plane(&v_pred, &v_quant, rd.factors);
4236        ssd[n] = (block_ssd(&u_recon, u.src) + block_ssd(&v_recon, v.src)) as f64;
4237        mode_bits[n] = treed_bits_cached(&*UV_MODE_PATHS, |i| KF_UV_MODE_PROB[i], mode.leaf());
4238        let token_bits = estimate_chroma_bits(rd, &u_quant, &v_quant, true);
4239        ranking_cost[n] = ssd[n] + rd.lambda * (token_bits + mode_bits[n]);
4240        quant[n] = (u_quant, v_quant);
4241    }
4242    let (leader, decisive) = decisive_minimum(&ranking_cost);
4243    let winner = if decisive {
4244        leader
4245    } else {
4246        // Too close to call on the ranking estimate: the reference
4247        // search — first strictly smaller reference cost wins.
4248        let reference_cost = |n: usize| {
4249            let token_bits = estimate_chroma_bits(rd, &quant[n].0, &quant[n].1, false);
4250            ssd[n] + rd.lambda * (token_bits + mode_bits[n])
4251        };
4252        let mut winner = 0usize;
4253        let mut best_cost = reference_cost(0);
4254        for n in 1..CANDIDATES.len() {
4255            let cost = reference_cost(n);
4256            if cost < best_cost {
4257                best_cost = cost;
4258                winner = n;
4259            }
4260        }
4261        winner
4262    };
4263    (CANDIDATES[winner], quant[winner].0, quant[winner].1)
4264}
4265
4266// ─────────────────────── §11.3 / §12.3 B_PRED luma picker ──────────────────────
4267
4268/// Stride (pixels per row) of the encoder's `B_PRED` working luma
4269/// buffer — mirrors the decoder's `reconstruct::BPRED_STRIDE`:
4270/// `[ left-border (1) | 16 columns | above-right extension (4) ]`.
4271const ENC_BPRED_STRIDE: usize = 1 + 16 + 4;
4272
4273/// Number of rows in the working buffer: one top-border row plus the
4274/// sixteen reconstruction rows.
4275const ENC_BPRED_ROWS: usize = 1 + 16;
4276
4277/// Flat index of the working buffer's reconstruction origin `(0, 0)`.
4278const ENC_BPRED_ORIGIN: usize = ENC_BPRED_STRIDE + 1;
4279
4280/// The ten §12.3 4×4 sub-block intra modes, in `intra_bmode` order.
4281const BMODE_CANDIDATES: [IntraBmode; 10] = [
4282    IntraBmode::Dc,
4283    IntraBmode::Tm,
4284    IntraBmode::Ve,
4285    IntraBmode::He,
4286    IntraBmode::Ld,
4287    IntraBmode::Rd,
4288    IntraBmode::Vr,
4289    IntraBmode::Vl,
4290    IntraBmode::Hd,
4291    IntraBmode::Hu,
4292];
4293
4294/// Outcome of the §12.3 B_PRED luma encode pass.
4295struct BpredLuma {
4296    /// The sixteen chosen 4×4 sub-block modes (raster order).
4297    modes: [IntraBmode; 16],
4298    /// The sixteen quantised 4×4 Y coefficient blocks (raster order).
4299    /// Unlike the whole-block path these carry their **own** DC (no Y2
4300    /// block exists for a `B_PRED` macroblock per §13 / §14.2).
4301    y_coeffs: [[i16; 16]; 16],
4302    /// Total rate-distortion cost `J = SSD + lambda * R` of the chosen
4303    /// sub-block modes — the metric the top-level luma decision compares
4304    /// against the best whole-block RD cost. `R` is the §13.3 token bits
4305    /// plus the §11.3 / §11.5 sub-block-mode-signal bits; the §11.2
4306    /// B_PRED luma-mode flag itself is added by the caller (it is common
4307    /// to all sixteen sub-blocks and cancels in the per-sub-block scoring
4308    /// but must be charged once against the whole-block alternative).
4309    rd_cost: f64,
4310}
4311
4312/// Build the encoder's `B_PRED` working luma buffer with its border row
4313/// / column pre-filled from the macroblock's neighbours, applying the
4314/// §12.3 right-edge "above-right" fixup. Mirrors the decoder's
4315/// `reconstruct::build_bpred_work_buffer` so the encoder evolves
4316/// neighbours over the exact pixels the decoder will.
4317fn build_enc_bpred_buffer(
4318    neighbors: &crate::reconstruct::MbNeighbors,
4319) -> [u8; ENC_BPRED_ROWS * ENC_BPRED_STRIDE] {
4320    let mut buf = [0u8; ENC_BPRED_ROWS * ENC_BPRED_STRIDE];
4321
4322    // Top border row: col 0 = corner P, cols 1..=16 = 16 above pixels,
4323    // cols 17..=20 = the 4 above-right pixels.
4324    let above = neighbors.y_above.unwrap_or([DEFAULT_ABOVE_PIXEL; 16]);
4325    let topleft = neighbors.y_topleft.unwrap_or(DEFAULT_ABOVE_PIXEL);
4326    buf[0] = topleft;
4327    buf[1..17].copy_from_slice(&above);
4328    let above_right = neighbors.y_above_right.unwrap_or([DEFAULT_ABOVE_PIXEL; 4]);
4329    buf[17..21].copy_from_slice(&above_right);
4330
4331    // Left border column.
4332    let left = neighbors.y_left.unwrap_or([DEFAULT_LEFT_PIXEL; 16]);
4333    for (r, &v) in left.iter().enumerate() {
4334        buf[(r + 1) * ENC_BPRED_STRIDE] = v;
4335    }
4336
4337    // §12.3 right-edge fixup: the four above-right pixels are shared by
4338    // sub-blocks 3, 7, 11, 15 — copy them above sub-block rows 1, 2, 3.
4339    let extra = [buf[17], buf[18], buf[19], buf[20]];
4340    for &recon_row_above in &[3usize, 7, 11] {
4341        let buf_row = 1 + recon_row_above;
4342        let base = buf_row * ENC_BPRED_STRIDE + 17;
4343        buf[base..base + 4].copy_from_slice(&extra);
4344    }
4345
4346    buf
4347}
4348
4349/// Encode the luma plane as a §11.3 / §12.3 `B_PRED` macroblock:
4350/// sixteen independent 4×4 sub-blocks, each choosing the
4351/// rate-distortion-minimising one of the ten §12.3 sub-modes, with
4352/// **in-place neighbour evolution** — every sub-block predicts from the
4353/// already-reconstructed (predictor + dequantised residue) pixels of the
4354/// sub-blocks above and to its left, exactly as the decoder's
4355/// `decode_keyframe_mb_bpred` walk does. Sharing the decoder's
4356/// `predict_b4x4` kernel and `inverse_dct_4x4` / `add_residue_4x4`
4357/// guarantees the reconstruction the encoder evolves against is the one
4358/// the decoder produces.
4359///
4360/// Each sub-block's cost is `J = SSD + lambda * R`, where `D` is the
4361/// reconstructed-vs-source SSD of that 4×4 block and `R` is its §13.3
4362/// `YNoY2` token bits plus the §11.3 / §11.5 sub-block-mode-signal bits
4363/// (priced against `KF_BMODE_PROB[above_mode][left_mode]`, with the
4364/// within-MB neighbour modes threaded and B_DC_PRED at the MB edges — the
4365/// same locality the bitstream layer's first-MB context uses). The chosen
4366/// sub-block mode evolves the neighbour-mode context greedily.
4367///
4368/// Returns the chosen modes, the sixteen quantised coefficient blocks
4369/// (each carrying its own DC — a `B_PRED` MB has no Y2 block), and the
4370/// total RD cost for the top-level luma decision.
4371fn encode_bpred_luma(
4372    src: &[u8; 256],
4373    neighbors: &crate::reconstruct::MbNeighbors,
4374    rd: &MbRdCtx,
4375) -> BpredLuma {
4376    let factors = rd.factors;
4377    let mut buf = build_enc_bpred_buffer(neighbors);
4378    let mut modes = [IntraBmode::Dc; 16];
4379    let mut y_coeffs = [[0i16; 16]; 16];
4380    let mut total_cost = 0.0f64;
4381    // Within-MB sub-block-mode context for §11.3 mode-bit pricing: edge
4382    // sub-blocks read B_DC_PRED, matching the first-MB context the
4383    // bitstream layer initialises.
4384    let mut sub_modes = [IntraBmode::Dc; 16];
4385    // §13.3 non-zero token context, threaded across the sixteen Y blocks.
4386    let mut tok_above = MbEntropyCtx::default();
4387    let mut tok_left = MbEntropyCtx::default();
4388
4389    for i in 0..4 {
4390        for j in 0..4 {
4391            let idx = i * 4 + j;
4392            let sb_base = ENC_BPRED_ORIGIN + (i * 4) * ENC_BPRED_STRIDE + (j * 4);
4393
4394            // Gather the §12.3 neighbour inputs from the evolving buffer.
4395            let above_base = sb_base - ENC_BPRED_STRIDE;
4396            let mut above = [0u8; 8];
4397            above.copy_from_slice(&buf[above_base..above_base + 8]);
4398            let mut left = [0u8; 4];
4399            for (r, slot) in left.iter_mut().enumerate() {
4400                *slot = buf[sb_base + r * ENC_BPRED_STRIDE - 1];
4401            }
4402            let p = buf[above_base - 1];
4403
4404            // Read the source 4×4 sub-block.
4405            let mut sb_src = [0u8; 16];
4406            for r in 0..4 {
4407                for c in 0..4 {
4408                    sb_src[r * 4 + c] = src[(i * 4 + r) * 16 + (j * 4 + c)];
4409                }
4410            }
4411
4412            // §11.3 mode-bit context: above sub-block (or B_DC_PRED at the
4413            // MB top edge) and left sub-block (or B_DC_PRED at the left
4414            // edge).
4415            let above_mode = if i == 0 {
4416                IntraBmode::Dc
4417            } else {
4418                sub_modes[(i - 1) * 4 + j]
4419            };
4420            let left_mode = if j == 0 {
4421                IntraBmode::Dc
4422            } else {
4423                sub_modes[i * 4 + (j - 1)]
4424            };
4425            let mode_bits_row = &KF_BMODE_BITS[above_mode.idx()][left_mode.idx()];
4426
4427            // RD-pick the sub-mode: reconstruct each candidate, score
4428            // SSD + lambda*(token bits + mode bits). The token bits are
4429            // first taken from the pre-summed ranking estimate; the
4430            // reference estimate prices the winner (and re-decides the
4431            // sub-block when the ranking is too close to call).
4432            let mut cand_coeffs = [[0i16; 16]; 10];
4433            let mut cand_scan = [[0i16; 16]; 10];
4434            let mut cand_recon = [[0u8; 16]; 10];
4435            let mut cand_ssd = [0f64; 10];
4436            let mut cand_rank_bits = [0f64; 10];
4437            let mut cand_pred = [[0u8; 16]; 10];
4438            let mut ranking_cost = [0f64; 10];
4439            let (above_nonzero, left_nonzero) = (tok_above.nonzero[j], tok_left.nonzero[i]);
4440            for (n, &mode) in BMODE_CANDIDATES.iter().enumerate() {
4441                let mut pred = [0u8; 16];
4442                predict_b4x4(&mut pred, mode, &above, &left, p);
4443                cand_pred[n] = pred;
4444                // A prediction identical to an earlier sub-mode's (flat
4445                // or edge-less neighbourhoods make several modes
4446                // coincide) yields the identical residual, levels,
4447                // reconstruction and token bits — only the mode-signal
4448                // cost differs.
4449                if let Some(twin) = cand_pred[..n].iter().position(|earlier| *earlier == pred) {
4450                    cand_coeffs[n] = cand_coeffs[twin];
4451                    cand_scan[n] = cand_scan[twin];
4452                    cand_recon[n] = cand_recon[twin];
4453                    cand_ssd[n] = cand_ssd[twin];
4454                    cand_rank_bits[n] = cand_rank_bits[twin];
4455                    ranking_cost[n] =
4456                        cand_ssd[n] + rd.lambda * (cand_rank_bits[n] + mode_bits_row[mode.idx()]);
4457                    continue;
4458                }
4459
4460                let mut residual = [0i16; 16];
4461                for k in 0..16 {
4462                    residual[k] = sb_src[k] as i16 - pred[k] as i16;
4463                }
4464                let mut coeffs = [0i16; 16];
4465                forward_dct_4x4(&residual, &mut coeffs);
4466                if rd.trellis_active() {
4467                    // §13 trellis: B_PRED sub-blocks are `YNoY2` (own DC,
4468                    // plane 3); seed the entry context from the real §13.3
4469                    // above/left non-zero predictors for this sub-block.
4470                    let entry_ctx3 = (above_nonzero as usize) + (left_nonzero as usize);
4471                    trellis_quantize_block(
4472                        &mut coeffs,
4473                        TrellisBlockSpec {
4474                            dc: factors.y1_dc,
4475                            ac: factors.y1_ac,
4476                            first_coeff: BlockType::YNoY2.first_coeff(),
4477                            entry_ctx3,
4478                            plane: BlockType::YNoY2.plane_index(),
4479                        },
4480                        rd.coeff_probs,
4481                        rd.rate_tables,
4482                        rd.trellis_lambda(),
4483                    );
4484                } else {
4485                    enc_quantize_block(&mut coeffs, factors.y1_dc, factors.y1_ac);
4486                }
4487
4488                let recon = reconstruct_block_4x4(&pred, &coeffs, factors.y1_dc, factors.y1_ac);
4489                let scan = raster_to_scan(&coeffs);
4490                let token_bits =
4491                    rd.ranking_block_bits(BlockType::YNoY2, above_nonzero, left_nonzero, &scan);
4492                cand_ssd[n] = block_ssd(&recon, &sb_src) as f64;
4493                cand_rank_bits[n] = token_bits;
4494                ranking_cost[n] =
4495                    cand_ssd[n] + rd.lambda * (token_bits + mode_bits_row[mode.idx()]);
4496                cand_coeffs[n] = coeffs;
4497                cand_scan[n] = scan;
4498                cand_recon[n] = recon;
4499            }
4500            let reference_cost = |n: usize| {
4501                let token_bits =
4502                    rd.block_bits(BlockType::YNoY2, above_nonzero, left_nonzero, &cand_scan[n]);
4503                cand_ssd[n] + rd.lambda * (token_bits + mode_bits_row[BMODE_CANDIDATES[n].idx()])
4504            };
4505            let (leader, decisive) = decisive_minimum(&ranking_cost);
4506            let (winner, best_cost) = if decisive {
4507                (leader, reference_cost(leader))
4508            } else {
4509                // The reference search: first strictly smaller cost wins.
4510                let mut winner = 0usize;
4511                let mut best_cost = reference_cost(0);
4512                for n in 1..BMODE_CANDIDATES.len() {
4513                    let cost = reference_cost(n);
4514                    if cost < best_cost {
4515                        best_cost = cost;
4516                        winner = n;
4517                    }
4518                }
4519                (winner, best_cost)
4520            };
4521            let best_mode = BMODE_CANDIDATES[winner];
4522            let best_coeffs = cand_coeffs[winner];
4523            let best_recon = cand_recon[winner];
4524            modes[idx] = best_mode;
4525            sub_modes[idx] = best_mode;
4526            y_coeffs[idx] = best_coeffs;
4527            total_cost += best_cost;
4528
4529            // Roll the §13.3 non-zero token context forward for the
4530            // winning sub-block (Y block index `idx`, above slot = col j,
4531            // left slot = row i).
4532            let has_coeffs = best_coeffs.iter().any(|&v| v != 0);
4533            tok_above.nonzero[j] = has_coeffs;
4534            tok_left.nonzero[i] = has_coeffs;
4535
4536            // Write the winning reconstruction back into the working
4537            // buffer so it becomes a neighbour for the sub-blocks below /
4538            // to its right — identical to the decoder's evolution step.
4539            for r in 0..4 {
4540                let dst = sb_base + r * ENC_BPRED_STRIDE;
4541                buf[dst..dst + 4].copy_from_slice(&best_recon[r * 4..r * 4 + 4]);
4542            }
4543        }
4544    }
4545
4546    BpredLuma {
4547        modes,
4548        y_coeffs,
4549        rd_cost: total_cost,
4550    }
4551}
4552
4553/// Result of [`encode_mb_block_set`] — the per-MB raw-quantised
4554/// coefficient bundle (for inspection / testing) plus the byte stream
4555/// emitted by the token-encoder's underlying boolean encoder.
4556///
4557/// The bytes are positioned to feed a `BoolDecoder` directly; the
4558/// caller wraps them in any outer-frame framing (the §9.x first
4559/// partition + §9.5 DCT partition table) it needs.
4560#[derive(Debug, Clone)]
4561pub struct EncodedMb {
4562    /// The 25 raw-quantised coefficient blocks the encoder emitted, in
4563    /// raster order per [`MbCoeffs`]. Useful as a fixture for
4564    /// roundtrip tests; the decoder side recovers the same arrays.
4565    pub coeffs: MbCoeffs,
4566    /// The token-encoder's finished byte stream. Concatenates §13.3
4567    /// for Y2 → 16 Y → 4 U → 4 V at the supplied predictor seeds, then
4568    /// the §7.3 4-byte boolean-encoder flush trailer.
4569    pub bytes: Vec<u8>,
4570    /// The non-zero block count across the 25 residual blocks, useful
4571    /// as a regression knob and for assertions in tests.
4572    pub nonzero_block_count: usize,
4573    /// The luma mode the picker chose for this MB. One of the four
4574    /// §12.2 whole-block modes (DC / V / H / TM) when the whole-block
4575    /// path wins, or [`IntraYMode::B`] (`B_PRED`) when the §11.3 / §12.3
4576    /// per-4×4-sub-block path wins. The caller writes this into the §11.2
4577    /// mode layer and feeds it to the decoder's reconstruction
4578    /// orchestrator so prediction matches.
4579    pub y_mode: IntraYMode,
4580    /// The §12.2 whole-block 8×8 chroma mode the picker chose (shared by
4581    /// Cb and Cr per §11.4).
4582    pub uv_mode: IntraUvMode,
4583    /// The sixteen §11.3 / §12.3 4×4 luma sub-block modes in raster
4584    /// order (`i * 4 + j`), present **iff** `y_mode == IntraYMode::B`.
4585    /// `None` for the four whole-block luma modes. Feeds the decoder's
4586    /// `decode_keyframe_mb_bpred` `subblock_modes` argument.
4587    pub b_subblock_modes: Option<[IntraBmode; 16]>,
4588}
4589
4590/// Encode one macroblock's residual through the §13 / §14 block-set
4591/// walker — the inverse of the §14.2 reconstruction orchestrator.
4592///
4593/// # Behavior (Phase 5 scope)
4594///
4595/// * **Prediction + mode pick**: rate-distortion. Each §12.2 whole-block
4596///   luma mode (`DC` / `V` / `H` / `TM`), the §11.3 / §12.3 `B_PRED`
4597///   per-4×4-sub-block path, and each §12.2 chroma mode are run through
4598///   the full §14 chain (predict → FDCT → Y2/WHT → quantise →
4599///   dequantise → inverse-transform → reconstruct) and scored by the
4600///   non-normative Lagrangian cost `J = SSD + lambda * R`, where `D` is
4601///   the exact self-decode reconstruction SSD and `R` is the §13.3 token
4602///   bits plus the §11.2 / §11.4 mode-signal bits. `lambda` is derived
4603///   from the frame quantiser (see [`rd_lambda`]). Luma and chroma modes
4604///   are chosen independently; B_PRED wins over the whole-block luma
4605///   modes when its total RD cost (plus the §11.2 B_PRED mode-flag) is
4606///   lower. The same [`predict_y16x16`] / [`predict_uv8x8`] /
4607///   [`predict_b4x4`] kernels the decoder reconstructs with are shared.
4608/// * **Forward transforms**: §14.4 forward DCT on every Y, U, V 4×4
4609///   sub-block (16 + 4 + 4 = 24 blocks); for the whole-block luma path
4610///   the 16 Y DCs are collected into a Y2 block and §14.3 forward-WHT'd.
4611/// * **Quantisation**: §14.1 / §20.4 factors per
4612///   [`MbDequantFactors::from_quant_indices`], with the `MbCoeffs`
4613///   plane layout matching what the decoder produces.
4614/// * **Token coding**: §13.3 walk in residual order Y2 → 16 Y
4615///   (`YAfterY2` / `YNoY2`) → 4 U (`UV`) → 4 V (`UV`), threaded through
4616///   fresh above / left [`MbEntropyCtx`] (off-frame neighbours, matching
4617///   the test fixture's single-MB frame).
4618///
4619/// # Roundtrip guarantee
4620///
4621/// On a flat-colour Y / U / V macroblock at `yac_qi = 0` the bytes
4622/// `decode_mb_coeffs` + `MbDequantFactors::dequantize` + the §14.2 /
4623/// §12.2 reconstruction orchestrator return exactly recover the input
4624/// pixel value. The
4625/// `mb_block_set_roundtrip_flat_color_recovers_within_one_lsb` test in
4626/// the same module checks this end-to-end.
4627///
4628/// # Out of scope (deferred)
4629///
4630/// * Inter prediction and a full trellis / residual-quantisation RD
4631///   search (the picker scores at the mode granularity, not per-token).
4632///   Those land in subsequent rounds.
4633/// * The RD bit estimate prices an isolated MB's §13.3 contexts; the
4634///   frame raster driver threads the genuine cross-MB `MbEntropyCtx`
4635///   columns when it re-walks the chosen coefficients into the shared
4636///   token partition.
4637pub fn encode_mb_block_set(
4638    pixels: &MbPixels,
4639    yac_qi: u8,
4640    coeff_probs: &crate::dct_tokens::CoeffProbs,
4641) -> Result<EncodedMb, TokenEncodeError> {
4642    // The standalone entry encodes a single isolated macroblock, so
4643    // every neighbour edge is off-frame (`MbNeighbors::default()` is all
4644    // `None`) — exactly what the decoder's `decode_keyframe_mb_non_bpred`
4645    // substitutes for the top-left MB.
4646    encode_mb_block_set_with_neighbors(
4647        pixels,
4648        &crate::reconstruct::MbNeighbors::default(),
4649        yac_qi,
4650        coeff_probs,
4651    )
4652}
4653
4654/// Encode one macroblock's residual exactly like [`encode_mb_block_set`],
4655/// but score the §12.2 whole-block mode picker against the supplied
4656/// reconstructed-neighbour strips rather than off-frame defaults.
4657///
4658/// `neighbors` carries the same `(-1, *)` / `(*, -1)` edge pixels the
4659/// decoder's [`crate::reconstruct::MbNeighbors`] holds, so V_PRED /
4660/// H_PRED / TM_PRED are scored (and residual-coded) against the actual
4661/// pixels the decoder will reconstruct from. A `None` edge means
4662/// off-frame, and the shared `predict_*` kernels then apply the §12
4663/// 127 / 129 defaults — identical on both encode and decode sides.
4664///
4665/// This is the per-MB primitive the eventual frame raster driver calls
4666/// once per macroblock, feeding it the bottom row / right column of the
4667/// already-reconstructed neighbours.
4668pub fn encode_mb_block_set_with_neighbors(
4669    pixels: &MbPixels,
4670    neighbors: &crate::reconstruct::MbNeighbors,
4671    yac_qi: u8,
4672    coeff_probs: &crate::dct_tokens::CoeffProbs,
4673) -> Result<EncodedMb, TokenEncodeError> {
4674    encode_mb_block_set_with_neighbors_strength(
4675        pixels,
4676        neighbors,
4677        yac_qi,
4678        coeff_probs,
4679        TrellisStrength::DEFAULT,
4680    )
4681}
4682
4683/// Like [`encode_mb_block_set_with_neighbors`] but with the §13 trellis
4684/// aggressiveness dialed by `trellis`. The public no-strength entry above
4685/// delegates here with [`TrellisStrength::DEFAULT`] (byte-identical to the
4686/// historical wire); the keyframe driver threads the per-stream knob down
4687/// to this entry so a quality/size dial reaches the per-MB coefficient
4688/// search. [`TrellisStrength::OFF`] reproduces the pre-trellis bytes.
4689pub fn encode_mb_block_set_with_neighbors_strength(
4690    pixels: &MbPixels,
4691    neighbors: &crate::reconstruct::MbNeighbors,
4692    yac_qi: u8,
4693    coeff_probs: &crate::dct_tokens::CoeffProbs,
4694    trellis: TrellisStrength,
4695) -> Result<EncodedMb, TokenEncodeError> {
4696    encode_mb_block_set_with_neighbors_strength_rates(
4697        pixels,
4698        neighbors,
4699        yac_qi,
4700        coeff_probs,
4701        None,
4702        trellis,
4703    )
4704}
4705
4706/// One macroblock's mode decision and quantised residual — what the
4707/// frame drivers need from the per-macroblock search, without the token
4708/// bytes the standalone [`EncodedMb`] entries also produce.
4709struct MbAnalysis {
4710    /// The 25 raw-quantised coefficient blocks ([`MbCoeffs`] layout).
4711    coeffs: MbCoeffs,
4712    /// Chosen luma mode (`B_PRED` or one of the four §12.2 modes).
4713    y_mode: IntraYMode,
4714    /// Chosen §12.2 chroma mode.
4715    uv_mode: IntraUvMode,
4716    /// The sixteen §12.3 sub-block modes, present iff `y_mode` is
4717    /// `B_PRED`.
4718    b_subblock_modes: Option<[IntraBmode; 16]>,
4719    /// Number of residual blocks the §13.3 walk codes with at least one
4720    /// non-zero coefficient (`0` ⇒ the macroblock is a §11.1 skip).
4721    nonzero_block_count: usize,
4722}
4723
4724impl MbAnalysis {
4725    /// Bundle a decision, counting the non-zero blocks exactly as the
4726    /// §13.3 walk in [`encode_mb_tokens`] reports them: the Y2 block only
4727    /// off `B_PRED`, the sixteen Y blocks from their first coded position
4728    /// (1 when the DC lives in Y2), and the eight chroma blocks.
4729    fn from_coeffs(
4730        coeffs: MbCoeffs,
4731        y_mode: IntraYMode,
4732        uv_mode: IntraUvMode,
4733        b_subblock_modes: Option<[IntraBmode; 16]>,
4734    ) -> Self {
4735        let use_bpred = y_mode == IntraYMode::B;
4736        let y_first = usize::from(!use_bpred);
4737        let any = |block: &[i16]| block.iter().any(|&v| v != 0);
4738        let nonzero_block_count = usize::from(!use_bpred && any(&coeffs.y2))
4739            + coeffs.y.iter().filter(|b| any(&b[y_first..])).count()
4740            + coeffs.u.iter().filter(|b| any(&b[..])).count()
4741            + coeffs.v.iter().filter(|b| any(&b[..])).count();
4742        MbAnalysis {
4743            coeffs,
4744            y_mode,
4745            uv_mode,
4746            b_subblock_modes,
4747            nonzero_block_count,
4748        }
4749    }
4750}
4751
4752/// The exhaustive per-macroblock search: every §12.2 luma mode, the
4753/// §12.3 `B_PRED` pass with all ten sub-modes per sub-block, and every
4754/// §12.2 chroma mode, each candidate carried through the full transform /
4755/// trellis / reconstruction chain and scored by `J = SSD + lambda·R`.
4756fn analyze_mb_exhaustive(
4757    pixels: &MbPixels,
4758    neighbors: &crate::reconstruct::MbNeighbors,
4759    rd: &MbRdCtx,
4760) -> MbAnalysis {
4761    // ---- 2. Pick the §12.2 whole-block luma mode by rate-distortion.
4762    //         Each candidate is reconstructed through the full §14 chain
4763    //         (predict → FDCT → Y2/WHT → quant → dequant → IDCT → add),
4764    //         so the distortion term is the exact self-decode SSD and the
4765    //         rate term is the §13.3 token bits + §11.2 mode bits. The
4766    //         shared `predict_*` kernels apply each mode's off-frame
4767    //         default (V → 127, H → 129, TM → 129, DC → 128 fill) for any
4768    //         `None` edge, identically on both sides, so the residual the
4769    //         picker scores is the one the decoder reconstructs. The
4770    //         corner (-1,-1) read only by TM_PRED defaults to the §12
4771    //         `DEFAULT_ABOVE_PIXEL` (127) when off-frame, mirroring
4772    //         `decode_keyframe_mb_non_bpred`.
4773    let default_corner = crate::intra_predict::DEFAULT_ABOVE_PIXEL;
4774    let whole = pick_y16x16_mode(
4775        &pixels.y,
4776        neighbors.y_above.as_ref(),
4777        neighbors.y_left.as_ref(),
4778        neighbors.y_topleft.unwrap_or(default_corner),
4779        rd,
4780    );
4781
4782    // ---- 2b. Score the §11.3 / §12.3 B_PRED per-4×4-sub-block luma pass
4783    //          and decide luma by RD cost. The §11.2 luma-mode flag
4784    //          differs between the two paths, so add each path's
4785    //          mode-signal bits to its residual RD cost before comparing:
4786    //          the whole-block cost already folds its mode bits inside
4787    //          `pick_y16x16_mode`, and we charge the B_PRED MB its §11.2
4788    //          B-flag here (its per-sub-block mode bits are already inside
4789    //          `encode_bpred_luma`'s RD cost). B_PRED wins iff its total
4790    //          RD cost is strictly lower.
4791    let bpred = encode_bpred_luma(&pixels.y, neighbors, rd);
4792    let bpred_flag_bits =
4793        treed_bits_cached(&*KF_YMODE_PATHS, |i| KF_YMODE_PROB[i], IntraYMode::B.leaf());
4794    let bpred_total_cost = bpred.rd_cost + rd.lambda * bpred_flag_bits;
4795    let use_bpred = bpred_total_cost < whole.rd_cost;
4796    let y_mode = if use_bpred { IntraYMode::B } else { whole.mode };
4797
4798    let (uv_mode, u_coeffs, v_coeffs) = pick_uv8x8_mode(
4799        &ChromaPlane {
4800            src: &pixels.u,
4801            above: neighbors.u_above.as_ref(),
4802            left: neighbors.u_left.as_ref(),
4803            topleft: neighbors.u_topleft.unwrap_or(default_corner),
4804        },
4805        &ChromaPlane {
4806            src: &pixels.v,
4807            above: neighbors.v_above.as_ref(),
4808            left: neighbors.v_left.as_ref(),
4809            topleft: neighbors.v_topleft.unwrap_or(default_corner),
4810        },
4811        rd,
4812    );
4813
4814    // ---- 3. Assemble the quantised coefficients from the winning modes.
4815    //         The pickers already ran the §14 FDCT / Y2-WHT / quant chain
4816    //         for their winner, so the luma blocks are reused directly:
4817    //   * whole-block: `whole.y_coeffs` (DC in Y2) + `whole.y2_coeffs`;
4818    //   * B_PRED: `bpred.y_coeffs` (each sub-block carries its own DC),
4819    //     Y2 stays zero (§13 / §14.2: a B_PRED MB has no Y2 block).
4820    //         The chroma blocks are the chroma picker's winner.
4821    let mut raw_coeffs = MbCoeffs::default();
4822    if use_bpred {
4823        raw_coeffs.y = bpred.y_coeffs;
4824    } else {
4825        raw_coeffs.y = whole.y_coeffs;
4826        raw_coeffs.y2 = whole.y2_coeffs;
4827    }
4828    raw_coeffs.u = u_coeffs;
4829    raw_coeffs.v = v_coeffs;
4830
4831    MbAnalysis::from_coeffs(
4832        raw_coeffs,
4833        y_mode,
4834        uv_mode,
4835        use_bpred.then_some(bpred.modes),
4836    )
4837}
4838
4839/// [`encode_mb_block_set_with_neighbors_strength`] with an optional
4840/// per-frame [`TrellisRateTables`] built for `coeff_probs`. The
4841/// frame-level drivers pass `Some` so the §13 trellis prices tokens from
4842/// the precomputed tables (bit-for-bit the same values the direct calls
4843/// produce — the emitted bytes are identical either way); the public
4844/// per-MB entry above passes `None` and keeps its call cost unchanged.
4845fn encode_mb_block_set_with_neighbors_strength_rates(
4846    pixels: &MbPixels,
4847    neighbors: &crate::reconstruct::MbNeighbors,
4848    yac_qi: u8,
4849    coeff_probs: &crate::dct_tokens::CoeffProbs,
4850    rate_tables: Option<&TrellisRateTables>,
4851    trellis: TrellisStrength,
4852) -> Result<EncodedMb, TokenEncodeError> {
4853    // ---- 1. Build the §14.1 dequant factors + derive the RD lambda.
4854    // The encoder's quantisation step is the inverse — divide by these.
4855    let factors =
4856        crate::dequant::MbDequantFactors::from_base_and_deltas(yac_qi as i32, 0, 0, 0, 0, 0);
4857    let rd = MbRdCtx {
4858        factors: &factors,
4859        coeff_probs,
4860        rate_tables,
4861        lambda: rd_lambda(&factors),
4862        trellis,
4863    };
4864    let MbAnalysis {
4865        coeffs: raw_coeffs,
4866        y_mode,
4867        uv_mode,
4868        b_subblock_modes,
4869        ..
4870    } = analyze_mb_exhaustive(pixels, neighbors, &rd);
4871    let use_bpred = y_mode == IntraYMode::B;
4872
4873    // ---- 6. Walk §13.3 residual order, encode each block in scan
4874    //         order against fresh above / left predictor contexts.
4875    //
4876    // Walk order matches `decode_mb_coeffs`:
4877    //   1. Y2 (only when has_y2 — i.e. NOT B_PRED)  — block 24
4878    //   2. 16 Y sub-blocks                          — blocks 0..15
4879    //        plane = YAfterY2 (DC in Y2) for whole-block modes,
4880    //        plane = YNoY2   (own DC)    for B_PRED;
4881    //   3. 4 U sub-blocks (UV plane)                — blocks 16..19
4882    //   4. 4 V sub-blocks (UV plane)                — blocks 20..23
4883    //
4884    // The above / left predictor seeds for the first block are both
4885    // off-frame ("false") since this entry encodes a single isolated
4886    // MB. Each block updates its slot in both contexts per §13.3.
4887    let mut enc = BoolEncoder::new();
4888    let mut above = MbEntropyCtx::default();
4889    let mut left = MbEntropyCtx::default();
4890    let nonzero_block_count = encode_mb_tokens(
4891        &mut enc,
4892        &raw_coeffs,
4893        use_bpred,
4894        coeff_probs,
4895        &mut above,
4896        &mut left,
4897    )?;
4898
4899    let bytes = enc.finish();
4900    Ok(EncodedMb {
4901        coeffs: raw_coeffs,
4902        bytes,
4903        nonzero_block_count,
4904        y_mode,
4905        uv_mode,
4906        b_subblock_modes,
4907    })
4908}
4909
4910/// Walk the §13.3 residual order for one macroblock's raw-quantised
4911/// coefficients into the shared boolean encoder `enc`, threading the
4912/// supplied above / left [`MbEntropyCtx`] in place. Returns the number
4913/// of non-zero residual blocks emitted.
4914///
4915/// Walk order matches `decode_mb_coeffs`:
4916///   1. Y2 (only when `!use_bpred`)              — block 24
4917///   2. 16 Y sub-blocks                          — blocks 0..15
4918///      (plane = `YAfterY2` (DC in Y2) for whole-block modes,
4919///      plane = `YNoY2` (own DC) for B_PRED);
4920///   3. 4 U sub-blocks (`UV` plane)              — blocks 16..19
4921///   4. 4 V sub-blocks (`UV` plane)              — blocks 20..23
4922///
4923/// Unlike the per-MB `encode_mb_block_set*` entries (which call this
4924/// against fresh off-frame contexts and a per-MB encoder), the frame
4925/// raster driver shares one `enc` and threads `above` (per column,
4926/// frame-lived) / `left` (per row) so the §13.3 non-zero predictor
4927/// state evolves macroblock-to-macroblock exactly as the decoder
4928/// reconstructs it.
4929fn encode_mb_tokens<S: BoolSink>(
4930    enc: &mut S,
4931    raw_coeffs: &MbCoeffs,
4932    use_bpred: bool,
4933    coeff_probs: &crate::dct_tokens::CoeffProbs,
4934    above: &mut MbEntropyCtx,
4935    left: &mut MbEntropyCtx,
4936) -> Result<usize, TokenEncodeError> {
4937    let mut nonzero_block_count = 0usize;
4938
4939    // Y2 is emitted only for the whole-block path; a B_PRED macroblock
4940    // has no Y2 record at all (§13.3 skips block 24 when has_y2 is false).
4941    if !use_bpred {
4942        let scan_y2 = raster_to_scan(&raw_coeffs.y2);
4943        let nz = encode_block_with_ctx(enc, 24, BlockType::Y2, coeff_probs, &scan_y2, above, left)?;
4944        if nz != 0 {
4945            nonzero_block_count += 1;
4946        }
4947    }
4948
4949    let y_block_type = if use_bpred {
4950        BlockType::YNoY2
4951    } else {
4952        BlockType::YAfterY2
4953    };
4954    for (i, y_block) in raw_coeffs.y.iter().enumerate() {
4955        let scan = raster_to_scan(y_block);
4956        let nz = encode_block_with_ctx(enc, i, y_block_type, coeff_probs, &scan, above, left)?;
4957        if nz != 0 {
4958            nonzero_block_count += 1;
4959        }
4960    }
4961
4962    for (i, u_block) in raw_coeffs.u.iter().enumerate() {
4963        let scan = raster_to_scan(u_block);
4964        let nz =
4965            encode_block_with_ctx(enc, 16 + i, BlockType::UV, coeff_probs, &scan, above, left)?;
4966        if nz != 0 {
4967            nonzero_block_count += 1;
4968        }
4969    }
4970
4971    for (i, v_block) in raw_coeffs.v.iter().enumerate() {
4972        let scan = raster_to_scan(v_block);
4973        let nz =
4974            encode_block_with_ctx(enc, 20 + i, BlockType::UV, coeff_probs, &scan, above, left)?;
4975        if nz != 0 {
4976            nonzero_block_count += 1;
4977        }
4978    }
4979
4980    Ok(nonzero_block_count)
4981}
4982
4983/// Encode one residual block at `block_index` against the §13.3 above /
4984/// left predictor slots, threading the §20.16 `left_context_index` /
4985/// `above_context_index` lookups so the encoder's per-position
4986/// probability index matches the decoder's. Returns the non-zero
4987/// coefficient count from `encode_coeff_block`.
4988///
4989/// This is the encoder partner of the `decode_one` closure inside
4990/// `decode_mb_coeffs`; both update the predictor contexts in place.
4991fn encode_block_with_ctx<S: BoolSink>(
4992    enc: &mut S,
4993    block_index: usize,
4994    block_type: BlockType,
4995    coeff_probs: &crate::dct_tokens::CoeffProbs,
4996    scan_coeffs: &[i16; 16],
4997    above: &mut MbEntropyCtx,
4998    left: &mut MbEntropyCtx,
4999) -> Result<usize, TokenEncodeError> {
5000    // The §20.16 LEFT/ABOVE context index tables are crate-private
5001    // inside `dct_tokens`, but their layout is fixed by RFC 6386
5002    // §20.16 (and confirmed by the `decode_mb_coeffs` walk). The
5003    // encoder duplicates the mapping here so it doesn't need to grow
5004    // the `dct_tokens` public surface.
5005    const LEFT_CTX: [usize; 25] = [
5006        0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, // 16 Y
5007        4, 4, 5, 5, // 4 U
5008        6, 6, 7, 7, // 4 V
5009        8, // Y2
5010    ];
5011    const ABOVE_CTX: [usize; 25] = [
5012        0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, // 16 Y
5013        4, 5, 4, 5, // 4 U
5014        6, 7, 6, 7, // 4 V
5015        8, // Y2
5016    ];
5017
5018    let a_slot = ABOVE_CTX[block_index];
5019    let l_slot = LEFT_CTX[block_index];
5020
5021    let nz = encode_coeff_block_into(
5022        enc,
5023        block_type,
5024        coeff_probs,
5025        above.nonzero[a_slot],
5026        left.nonzero[l_slot],
5027        scan_coeffs,
5028    )?;
5029
5030    let has_coeffs = nz != 0;
5031    above.nonzero[a_slot] = has_coeffs;
5032    left.nonzero[l_slot] = has_coeffs;
5033    Ok(nz)
5034}
5035
5036// ─────────────────────── §13.4 observed-counts fitter (round 157) ───────────────────────
5037
5038/// Per-position branch counters for the §13.4 `token_prob_update()`
5039/// table: for every `(plane, band, prev_ctx, position)` slot of the
5040/// `coeff_probs[4][8][3][11]` table the encoder uses, count how many
5041/// times the §13.3 token-tree walk emitted a `0` bit at that position
5042/// (`zeros`) and how many times it emitted a `1` bit (`ones`). One
5043/// such counter per slot suffices: every bit the encoder emits against
5044/// `coeff_probs[i][j][k][t]` lands in `[i][j][k][t]` exactly once, so
5045/// a frame-wide accumulator is the natural rate-statistic for the §13.4
5046/// caller-driven update layer landed in rounds 155 / 156.
5047///
5048/// Used by [`count_keyframe_branches`] and the round-157
5049/// [`encode_keyframe_with_fitted_token_prob_updates`] fitter that
5050/// derives per-position `Some(p_obs)` replacement probabilities from
5051/// the observed counts and emits a §13.4 update only when the body bit
5052/// saving outweighs the §13.4 transmission cost.
5053///
5054/// The element type is `(u32, u32)` for `(zeros, ones)`. The maximum
5055/// per-frame count at any one position is bounded by the number of
5056/// coefficients in the frame (`16 * mb_cols * mb_rows` for the full-band
5057/// case), well within `u32`'s range for any realistic VP8 picture.
5058pub type BranchCounts = [[[[(u32, u32); 11]; 3]; 8]; 4];
5059
5060/// Zeroed [`BranchCounts`] suitable as the start of an accumulator.
5061///
5062/// Equivalent to `[[[[(0, 0); 11]; 3]; 8]; 4]`; named so `count_*`
5063/// helpers can be called without the caller having to repeat the
5064/// 4-dimension initialiser literal at every site.
5065pub fn empty_branch_counts() -> BranchCounts {
5066    [[[[(0u32, 0u32); 11]; 3]; 8]; 4]
5067}
5068
5069/// Walk one §13.3 sub-block exactly as [`encode_coeff_block`] would
5070/// emit it, but accumulating `(zeros, ones)` branch counts into
5071/// `counts` instead of writing to a [`BoolEncoder`]. The control flow
5072/// mirrors `encode_coeff_block` line for line so the counts track the
5073/// real token pass (token-tree path traversal; cat-token extra bits
5074/// and per-coefficient sign bits are intentionally not counted — those
5075/// are coded against fixed probabilities outside the `coeff_probs`
5076/// table the §13.4 layer can update).
5077///
5078/// `coeffs` is in **scan (zig-zag) order**, matching `encode_coeff_block`.
5079/// `above_has_nonzero` / `left_has_nonzero` seed `ctx3` exactly as the
5080/// real encoder does. Returns the non-zero coefficient count so the
5081/// caller can thread the §13.3 predictor update through `MbEntropyCtx`
5082/// in lockstep with the real encoder.
5083pub fn count_block_branches(
5084    block_type: BlockType,
5085    above_has_nonzero: bool,
5086    left_has_nonzero: bool,
5087    coeffs: &[i16; 16],
5088    counts: &mut BranchCounts,
5089) -> usize {
5090    let plane = block_type.plane_index();
5091    let first_coeff = block_type.first_coeff();
5092
5093    let mut last_non_zero: i32 = -1;
5094    for (i, &v) in coeffs.iter().enumerate() {
5095        if i >= first_coeff && v != 0 {
5096            last_non_zero = i as i32;
5097        }
5098    }
5099
5100    let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
5101    let mut prev_was_zero = false;
5102    let mut non_zero_count = 0usize;
5103
5104    let mut i = first_coeff;
5105    while i < 16 {
5106        let band = COEFF_BANDS[i];
5107
5108        let emit_eob = (i as i32) > last_non_zero;
5109        let (token, abs_value) = if emit_eob {
5110            (DctToken::Eob, 0u16)
5111        } else {
5112            let v = coeffs[i];
5113            let abs = v.unsigned_abs();
5114            (classify_coeff_token(abs), abs)
5115        };
5116
5117        let start = if prev_was_zero { 2i8 } else { 0i8 };
5118        for step in token_to_bit_path(token, start) {
5119            let slot = &mut counts[plane][band][ctx3][step.prob_index as usize];
5120            if step.bit {
5121                slot.1 += 1;
5122            } else {
5123                slot.0 += 1;
5124            }
5125        }
5126
5127        if token == DctToken::Eob {
5128            break;
5129        }
5130
5131        if abs_value != 0 {
5132            non_zero_count += 1;
5133        }
5134
5135        ctx3 = if abs_value == 0 {
5136            0
5137        } else if abs_value == 1 {
5138            1
5139        } else {
5140            2
5141        };
5142        prev_was_zero = token == DctToken::Dct0;
5143        i += 1;
5144    }
5145
5146    non_zero_count
5147}
5148
5149/// Count the §13.4 branch counts for one whole macroblock's residual,
5150/// mirroring [`encode_mb_tokens`] (Y2 if present, 16 Y sub-blocks, 4 U
5151/// sub-blocks, 4 V sub-blocks) and threading the §13.3 above / left
5152/// predictor contexts through `count_block_branches`. The §20.16
5153/// ABOVE / LEFT context-index tables match `encode_block_with_ctx`.
5154///
5155/// Like `encode_mb_tokens`, this is the per-MB driver; the frame
5156/// driver ([`count_keyframe_branches`]) calls it row-by-row with
5157/// frame-lived `above_ctx` and per-row `left_ctx` and respects
5158/// `mb_skip_coeff` (skip MBs emit no tokens but clear their predictor
5159/// slots via [`clear_skip_ctx`]).
5160pub fn count_mb_branches(
5161    raw_coeffs: &MbCoeffs,
5162    use_bpred: bool,
5163    above: &mut MbEntropyCtx,
5164    left: &mut MbEntropyCtx,
5165    counts: &mut BranchCounts,
5166) {
5167    const LEFT_CTX: [usize; 25] = [
5168        0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, // 16 Y
5169        4, 4, 5, 5, // 4 U
5170        6, 6, 7, 7, // 4 V
5171        8, // Y2
5172    ];
5173    const ABOVE_CTX: [usize; 25] = [
5174        0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, // 16 Y
5175        4, 5, 4, 5, // 4 U
5176        6, 7, 6, 7, // 4 V
5177        8, // Y2
5178    ];
5179
5180    let walk = |block_index: usize,
5181                block_type: BlockType,
5182                scan: &[i16; 16],
5183                above: &mut MbEntropyCtx,
5184                left: &mut MbEntropyCtx,
5185                counts: &mut BranchCounts| {
5186        let a = ABOVE_CTX[block_index];
5187        let l = LEFT_CTX[block_index];
5188        let nz = count_block_branches(block_type, above.nonzero[a], left.nonzero[l], scan, counts);
5189        let has = nz != 0;
5190        above.nonzero[a] = has;
5191        left.nonzero[l] = has;
5192    };
5193
5194    if !use_bpred {
5195        let scan_y2 = raster_to_scan(&raw_coeffs.y2);
5196        walk(24, BlockType::Y2, &scan_y2, above, left, counts);
5197    }
5198    let y_plane = if use_bpred {
5199        BlockType::YNoY2
5200    } else {
5201        BlockType::YAfterY2
5202    };
5203    for (i, y_block) in raw_coeffs.y.iter().enumerate() {
5204        let scan = raster_to_scan(y_block);
5205        walk(i, y_plane, &scan, above, left, counts);
5206    }
5207    for (i, u_block) in raw_coeffs.u.iter().enumerate() {
5208        let scan = raster_to_scan(u_block);
5209        walk(16 + i, BlockType::UV, &scan, above, left, counts);
5210    }
5211    for (i, v_block) in raw_coeffs.v.iter().enumerate() {
5212        let scan = raster_to_scan(v_block);
5213        walk(20 + i, BlockType::UV, &scan, above, left, counts);
5214    }
5215}
5216
5217/// Walk a whole keyframe's already-picked macroblock modes + raw
5218/// coefficients and accumulate §13.4 branch counts into `counts`,
5219/// mirroring the §13.3 token-encode pass of
5220/// [`encode_keyframe_with_reconstruction_and_token_updates`] —
5221/// row-major raster, frame-lived `above` per-column context, per-row
5222/// `left` reset, skip-MB context clearing via [`clear_skip_ctx`].
5223///
5224/// `modes` and `all_coeffs` are the same per-MB outputs the keyframe
5225/// driver feeds to its multi-partition token pass; `mb_cols` /
5226/// `mb_rows` are the macroblock-grid dimensions. The partition index a
5227/// given row routes to is irrelevant to the counts (the §13.3
5228/// above-context is shared across partitions and the per-row left
5229/// context resets identically regardless of partition assignment).
5230pub fn count_keyframe_branches(
5231    modes: &[MacroblockModes],
5232    all_coeffs: &[MbCoeffs],
5233    mb_cols: usize,
5234    mb_rows: usize,
5235    counts: &mut BranchCounts,
5236) {
5237    let mut above_ctx: Vec<MbEntropyCtx> = vec![MbEntropyCtx::default(); mb_cols];
5238    for mb_row in 0..mb_rows {
5239        let mut left_ctx = MbEntropyCtx::default();
5240        for (mb_col, above_col) in above_ctx.iter_mut().enumerate() {
5241            let raster = mb_row * mb_cols + mb_col;
5242            let mb = &modes[raster];
5243            let use_bpred = mb.y_mode == IntraYMode::B;
5244            if mb.mb_skip_coeff {
5245                clear_skip_ctx(use_bpred, above_col, &mut left_ctx);
5246                continue;
5247            }
5248            count_mb_branches(
5249                &all_coeffs[raster],
5250                use_bpred,
5251                above_col,
5252                &mut left_ctx,
5253                counts,
5254            );
5255        }
5256    }
5257}
5258
5259/// Walk a whole inter (P-) frame's already-picked macroblock modes +
5260/// raw coefficients and accumulate §13.4 branch counts into `counts`,
5261/// mirroring the §13.3 token-encode pass of
5262/// [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates`]
5263/// — row-major raster, frame-lived `above` per-column context, per-row
5264/// `left` reset, skip-MB context clearing via `clear_skip_ctx`.
5265///
5266/// The shape mirrors [`count_keyframe_branches`] exactly with one
5267/// addition: a per-MB `use_bpred` slice is required because the inter
5268/// path's "no Y2" decision is **not** carried in [`MacroblockModes`]'s
5269/// `y_mode` field (the inter picker stamps `y_mode = IntraYMode::Dc`
5270/// onto every MB; per §13.1 / §14.2 page 76, SPLITMV MBs also omit Y2
5271/// independent of `y_mode`). The inter inner driver records the
5272/// effective "no Y2" flag in its `use_bpred_per_mb` vector — which is
5273/// exactly what this walker consumes.
5274///
5275/// `modes`, `use_bpred_per_mb`, and `all_coeffs` must share the
5276/// macroblock-grid length (`mb_cols * mb_rows`); a mismatch is a caller
5277/// bug. The partition index a given row routes to is irrelevant to the
5278/// counts (the §13.3 above-context is shared across partitions and the
5279/// per-row left context resets identically regardless of partition
5280/// assignment).
5281pub fn count_inter_frame_branches(
5282    modes: &[MacroblockModes],
5283    use_bpred_per_mb: &[bool],
5284    all_coeffs: &[MbCoeffs],
5285    mb_cols: usize,
5286    mb_rows: usize,
5287    counts: &mut BranchCounts,
5288) {
5289    debug_assert_eq!(modes.len(), mb_cols * mb_rows);
5290    debug_assert_eq!(use_bpred_per_mb.len(), mb_cols * mb_rows);
5291    debug_assert_eq!(all_coeffs.len(), mb_cols * mb_rows);
5292
5293    let mut above_ctx: Vec<MbEntropyCtx> = vec![MbEntropyCtx::default(); mb_cols];
5294    for mb_row in 0..mb_rows {
5295        let mut left_ctx = MbEntropyCtx::default();
5296        for (mb_col, above_col) in above_ctx.iter_mut().enumerate() {
5297            let raster = mb_row * mb_cols + mb_col;
5298            let mb = &modes[raster];
5299            let use_bpred = use_bpred_per_mb[raster];
5300            if mb.mb_skip_coeff {
5301                clear_skip_ctx(use_bpred, above_col, &mut left_ctx);
5302                continue;
5303            }
5304            count_mb_branches(
5305                &all_coeffs[raster],
5306                use_bpred,
5307                above_col,
5308                &mut left_ctx,
5309                counts,
5310            );
5311        }
5312    }
5313}
5314
5315/// Derive a §13.4 [`TokenProbUpdates`] payload from observed branch
5316/// counts that **saves bits** when applied: each
5317/// `(plane, band, prev_ctx, position)` slot is set to `Some(p_obs)` if
5318/// and only if the body bit saving at that slot — coding `(zeros, ones)`
5319/// against the new probability vs the §13.5 default — outweighs the
5320/// §13.4 transmission cost (one flag-bit at the position's update
5321/// probability + an `L(8)` literal carrying the replacement, less the
5322/// flag-bit cost the no-update path would have paid). Slots with zero
5323/// total count, or where the saving is below `min_saving_bits`, stay
5324/// `None` (defaults retained).
5325///
5326/// `p_obs` is the maximum-likelihood estimate of the per-bit
5327/// probability of `0` at this slot, scaled to the §13.5 0..=255
5328/// `Prob`-byte range: `round(256 * zeros / total)`, clamped to `1..=255`
5329/// to mirror the boolean coder's `[1, 255]` valid range (and to keep
5330/// `bool_bits(p, bit)` finite when this fitter's output is fed back to
5331/// the encoder's cost estimator).
5332///
5333/// `min_saving_bits` is a small positive guard against round-trip
5334/// instability: the body saving is computed against the **observed**
5335/// distribution (which differs from the encoder's next-pass token
5336/// distribution once the new probs perturb the RD pick), so a
5337/// near-break-even slot may actually be net-negative after re-encode.
5338/// A guard of `~2 bits` is a reasonable starting point and is exposed
5339/// for tests that want the strict break-even output.
5340pub fn fit_token_prob_updates(
5341    counts: &BranchCounts,
5342    min_saving_bits: f64,
5343) -> crate::coded_header::TokenProbUpdates {
5344    let defaults = &crate::dct_tokens::DEFAULT_COEFF_PROBS;
5345    let mut out: crate::coded_header::TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
5346
5347    for i in 0..4 {
5348        for j in 0..8 {
5349            for k in 0..3 {
5350                for t in 0..11 {
5351                    let (n0, n1) = counts[i][j][k][t];
5352                    let total = n0 + n1;
5353                    if total == 0 {
5354                        continue;
5355                    }
5356                    let p_old = defaults[i][j][k][t];
5357
5358                    // Maximum-likelihood p_obs scaled to the §13.5
5359                    // 0..=255 byte range, clamped to [1, 255] so the
5360                    // resulting Prob is always valid (the boolean
5361                    // coder rejects 0 / 256).
5362                    let p_new_raw = ((n0 as u64) * 256 + (total as u64) / 2) / (total as u64);
5363                    let p_new = p_new_raw.clamp(1, 255) as u8;
5364
5365                    if p_new == p_old {
5366                        continue;
5367                    }
5368
5369                    // Body bit-cost in each direction, using the same
5370                    // `bool_bits` cost model the encoder's RD estimator
5371                    // uses. Saving > 0 ⇒ the new prob codes the
5372                    // observed counts more cheaply than the default.
5373                    let body_old = (n0 as f64) * bool_bits(p_old, false)
5374                        + (n1 as f64) * bool_bits(p_old, true);
5375                    let body_new = (n0 as f64) * bool_bits(p_new, false)
5376                        + (n1 as f64) * bool_bits(p_new, true);
5377                    let body_saving = body_old - body_new;
5378
5379                    // §13.4 transmission cost: replacing the no-op
5380                    // `flag = 0` (cost = bool_bits(update_prob, false))
5381                    // with `flag = 1` (cost = bool_bits(update_prob,
5382                    // true)) plus an 8-bit literal carrying p_new.
5383                    let update_prob =
5384                        COEFF_UPDATE_PROBS_FLAT[i * 8 * 3 * 11 + j * 3 * 11 + k * 11 + t];
5385                    let header_extra =
5386                        bool_bits(update_prob, true) + 8.0 - bool_bits(update_prob, false);
5387
5388                    if body_saving > header_extra + min_saving_bits {
5389                        out[i][j][k][t] = Some(p_new);
5390                    }
5391                }
5392            }
5393        }
5394    }
5395
5396    out
5397}
5398
5399/// `true` when at least one §13.4 slot of `updates` carries a
5400/// replacement probability — the "is the fitted table a no-op?" test
5401/// every two-pass fitter runs before paying for a second encode pass.
5402fn any_token_prob_update(updates: &crate::coded_header::TokenProbUpdates) -> bool {
5403    updates.iter().any(|p| {
5404        p.iter()
5405            .any(|b| b.iter().any(|c| c.iter().any(|s| s.is_some())))
5406    })
5407}
5408
5409// ─────────────────────── §9 / §11 / §19.2 keyframe raster driver ───────────────────────
5410
5411/// A source I420 (YCbCr 4:2:0) picture handed to the keyframe raster
5412/// encoder. The three planes are row-major; chroma is half-resolution in
5413/// both dimensions (`(width + 1) / 2 × (height + 1) / 2`), matching the
5414/// §9.1 dimensions the decoder reconstructs.
5415///
5416/// Strides default to the tightly-packed widths; supply `y_stride` etc.
5417/// when the planes carry row padding.
5418#[derive(Debug, Clone, Copy)]
5419pub struct I420Frame<'a> {
5420    /// Visible width in luma pixels (1..=0x3FFF per §9.1).
5421    pub width: u32,
5422    /// Visible height in luma pixels (1..=0x3FFF per §9.1).
5423    pub height: u32,
5424    /// Luma plane, row-major, at least `y_stride * height` bytes.
5425    pub y: &'a [u8],
5426    /// U chroma plane, row-major, at least `uv_stride * uv_height` bytes.
5427    pub u: &'a [u8],
5428    /// V chroma plane, same dimensions as `u`.
5429    pub v: &'a [u8],
5430    /// Luma row stride in bytes (≥ `width`).
5431    pub y_stride: usize,
5432    /// Chroma row stride in bytes (≥ `(width + 1) / 2`).
5433    pub uv_stride: usize,
5434}
5435
5436impl<'a> I420Frame<'a> {
5437    /// Build an `I420Frame` from every field (explicit strides).
5438    #[allow(clippy::too_many_arguments)]
5439    pub fn new(
5440        width: u32,
5441        height: u32,
5442        y: &'a [u8],
5443        u: &'a [u8],
5444        v: &'a [u8],
5445        y_stride: usize,
5446        uv_stride: usize,
5447    ) -> Self {
5448        Self {
5449            width,
5450            height,
5451            y,
5452            u,
5453            v,
5454            y_stride,
5455            uv_stride,
5456        }
5457    }
5458
5459    /// Set `width`.
5460    #[must_use]
5461    pub fn with_width(mut self, v: u32) -> Self {
5462        self.width = v;
5463        self
5464    }
5465
5466    /// Set `height`.
5467    #[must_use]
5468    pub fn with_height(mut self, v: u32) -> Self {
5469        self.height = v;
5470        self
5471    }
5472
5473    /// Set `y`.
5474    #[must_use]
5475    pub fn with_y(mut self, v: &'a [u8]) -> Self {
5476        self.y = v;
5477        self
5478    }
5479
5480    /// Set `u`.
5481    #[must_use]
5482    pub fn with_u(mut self, v: &'a [u8]) -> Self {
5483        self.u = v;
5484        self
5485    }
5486
5487    /// Set `v`.
5488    #[must_use]
5489    pub fn with_v(mut self, v: &'a [u8]) -> Self {
5490        self.v = v;
5491        self
5492    }
5493
5494    /// Set `y_stride`.
5495    #[must_use]
5496    pub fn with_y_stride(mut self, v: usize) -> Self {
5497        self.y_stride = v;
5498        self
5499    }
5500
5501    /// Set `uv_stride`.
5502    #[must_use]
5503    pub fn with_uv_stride(mut self, v: usize) -> Self {
5504        self.uv_stride = v;
5505        self
5506    }
5507
5508    /// Construct a frame whose planes are tightly packed (`y_stride =
5509    /// width`, `uv_stride = (width + 1) / 2`).
5510    pub fn packed(width: u32, height: u32, y: &'a [u8], u: &'a [u8], v: &'a [u8]) -> Self {
5511        I420Frame {
5512            width,
5513            height,
5514            y,
5515            u,
5516            v,
5517            y_stride: width as usize,
5518            uv_stride: width.div_ceil(2) as usize,
5519        }
5520    }
5521
5522    /// Read luma pixel `(x, py)`, clamping the coordinates into the
5523    /// visible plane so a partial right / bottom macroblock samples the
5524    /// nearest edge pixel (edge-replication padding).
5525    #[inline]
5526    fn y_at(&self, x: usize, py: usize) -> u8 {
5527        let w = self.width as usize;
5528        let h = self.height as usize;
5529        let cx = x.min(w - 1);
5530        let cy = py.min(h - 1);
5531        self.y[cy * self.y_stride + cx]
5532    }
5533
5534    /// Read U / V pixel `(x, py)` with the same edge-replication clamp.
5535    /// `is_v` selects U (`false`) or V (`true`).
5536    #[inline]
5537    fn uv_at(&self, x: usize, py: usize, is_v: bool) -> u8 {
5538        let cw = self.width.div_ceil(2) as usize;
5539        let ch = self.height.div_ceil(2) as usize;
5540        let cx = x.min(cw - 1);
5541        let cy = py.min(ch - 1);
5542        let plane = if is_v { self.v } else { self.u };
5543        plane[cy * self.uv_stride + cx]
5544    }
5545
5546    /// Extract the [`MbPixels`] for macroblock `(mb_row, mb_col)`,
5547    /// edge-replicating into the padding region of a partial right /
5548    /// bottom macroblock.
5549    fn extract_mb(&self, mb_row: usize, mb_col: usize) -> MbPixels {
5550        let mut p = MbPixels {
5551            y: [0u8; 256],
5552            u: [0u8; 64],
5553            v: [0u8; 64],
5554        };
5555        let y0 = mb_row * 16;
5556        let x0 = mb_col * 16;
5557        let cy0 = mb_row * 8;
5558        let cx0 = mb_col * 8;
5559        let (w, h) = (self.width as usize, self.height as usize);
5560        let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
5561        if x0 + 16 <= w && y0 + 16 <= h && cx0 + 8 <= cw && cy0 + 8 <= ch {
5562            // Entirely inside the picture: straight row copies.
5563            for r in 0..16 {
5564                let src = (y0 + r) * self.y_stride + x0;
5565                p.y[r * 16..r * 16 + 16].copy_from_slice(&self.y[src..src + 16]);
5566            }
5567            for r in 0..8 {
5568                let src = (cy0 + r) * self.uv_stride + cx0;
5569                p.u[r * 8..r * 8 + 8].copy_from_slice(&self.u[src..src + 8]);
5570                p.v[r * 8..r * 8 + 8].copy_from_slice(&self.v[src..src + 8]);
5571            }
5572            return p;
5573        }
5574        for r in 0..16 {
5575            for c in 0..16 {
5576                p.y[r * 16 + c] = self.y_at(x0 + c, y0 + r);
5577            }
5578        }
5579        for r in 0..8 {
5580            for c in 0..8 {
5581                p.u[r * 8 + c] = self.uv_at(cx0 + c, cy0 + r, false);
5582                p.v[r * 8 + c] = self.uv_at(cx0 + c, cy0 + r, true);
5583            }
5584        }
5585        p
5586    }
5587}
5588
5589/// Parameters for [`encode_keyframe`].
5590#[derive(Debug, Clone, Copy)]
5591pub struct KeyframeParams {
5592    /// §9.6 `y_ac_qi` baseline quantiser index (0..=127). All five §9.6
5593    /// deltas are omitted (set to 0). Lower = higher quality / larger
5594    /// output; a mid value (e.g. 32) targets ~30+ dB on natural content.
5595    pub y_ac_qi: u8,
5596    /// §9.4 baseline loop filter level (0..=63). `0` triggers the §15
5597    /// whole-frame loop-filter skip — the encoder leaves the residual
5598    /// reconstruction unfiltered. For any non-zero value the encoder
5599    /// runs the §15 filter over its own reconstruction buffer after the
5600    /// per-MB raster walk finishes, so the encoder's self-decode
5601    /// produces the same pixels the decoder will (the per-MB neighbour
5602    /// gather happens before the filter pass — §15.1 page 84 specifies
5603    /// the filter is a post-reconstruction stage).
5604    ///
5605    /// The §9.4 `mode_ref_lf_delta_enabled` flag is held at 0 by this
5606    /// encoder; the per-MB level therefore reduces to the frame base
5607    /// (with no segmentation override either, since segmentation is
5608    /// off). Values > 63 are rejected with
5609    /// [`EncodeError::LoopFilterLevelOutOfRange`].
5610    pub loop_filter_level: u8,
5611    /// §9.4 `sharpness_level` (0..=7). Feeds the §15.4 `interior_limit`
5612    /// derivation alongside the per-MB `loop_filter_level`. Only
5613    /// consulted when `loop_filter_level != 0` (the §15 skip path also
5614    /// skips the §15.4 control derivation). Values > 7 are rejected with
5615    /// [`EncodeError::SharpnessLevelOutOfRange`].
5616    pub sharpness_level: u8,
5617    /// §9.5 DCT-coefficient partition count. Must be one of 1 / 2 / 4 / 8
5618    /// (the on-wire `log2_nbr_of_dct_partitions` field is two bits per
5619    /// the §9.5 table). Macroblock rows are distributed round-robin per
5620    /// the §20.4 loop: row `r` is encoded into partition `r % N`. This
5621    /// is a layout reorganisation only — the residual coding inside each
5622    /// partition is bit-identical to the 1-partition case, so the
5623    /// decoded picture is unchanged across all four choices.
5624    pub nbr_of_dct_partitions: u8,
5625    /// §9.4 `filter_type` — `false` selects the §15.3 *normal* loop
5626    /// filter (the default; matches every earlier round's wire), `true`
5627    /// selects the §15.2 *simple* filter. The simple filter is a 4-pixel
5628    /// edge-only kernel (no §15.3 inner-window high-edge-variance branch
5629    /// and no chroma plane), so it costs the decoder less work but on a
5630    /// natural-content frame yields lower PSNR than the normal filter.
5631    /// The encoder runs the same selection inside its own §15 post-walk
5632    /// filter pass so encoder-vs-decoder pixel lockstep holds at both
5633    /// values. Only consulted when `loop_filter_level != 0`; the §15
5634    /// whole-frame skip path bypasses the filter entirely either way.
5635    pub filter_type: bool,
5636    /// §13 trellis coefficient-RDO aggressiveness — a clean-room
5637    /// quality/size dial (RFC 6386 specifies only token *decoding*; the
5638    /// level-assignment search is a non-normative encoder decision).
5639    /// [`TrellisStrength::DEFAULT`] reproduces the calibrated
5640    /// "shave-bits-hold-PSNR" trade; higher values trade more PSNR for
5641    /// smaller output, [`TrellisStrength::OFF`] reverts to plain
5642    /// round-quantisation. Threaded onto both the keyframe and the inter
5643    /// residual emit. The reconstruction the encoder writes back always
5644    /// uses the trellis-chosen levels, so encoder↔decoder pixel lockstep
5645    /// holds at every strength.
5646    pub trellis_strength: TrellisStrength,
5647}
5648
5649impl KeyframeParams {
5650    /// Set `y_ac_qi`.
5651    #[must_use]
5652    pub fn with_y_ac_qi(mut self, v: u8) -> Self {
5653        self.y_ac_qi = v;
5654        self
5655    }
5656
5657    /// Set `loop_filter_level`.
5658    #[must_use]
5659    pub fn with_loop_filter_level(mut self, v: u8) -> Self {
5660        self.loop_filter_level = v;
5661        self
5662    }
5663
5664    /// Set `sharpness_level`.
5665    #[must_use]
5666    pub fn with_sharpness_level(mut self, v: u8) -> Self {
5667        self.sharpness_level = v;
5668        self
5669    }
5670
5671    /// Set `nbr_of_dct_partitions`.
5672    #[must_use]
5673    pub fn with_nbr_of_dct_partitions(mut self, v: u8) -> Self {
5674        self.nbr_of_dct_partitions = v;
5675        self
5676    }
5677
5678    /// Set `filter_type`.
5679    #[must_use]
5680    pub fn with_filter_type(mut self, v: bool) -> Self {
5681        self.filter_type = v;
5682        self
5683    }
5684
5685    /// Set `trellis_strength`.
5686    #[must_use]
5687    pub fn with_trellis_strength(mut self, v: TrellisStrength) -> Self {
5688        self.trellis_strength = v;
5689        self
5690    }
5691}
5692
5693impl Default for KeyframeParams {
5694    fn default() -> Self {
5695        KeyframeParams {
5696            y_ac_qi: 32,
5697            loop_filter_level: 0,
5698            sharpness_level: 0,
5699            nbr_of_dct_partitions: 1,
5700            filter_type: false,
5701            trellis_strength: TrellisStrength::DEFAULT,
5702        }
5703    }
5704}
5705
5706/// Encode a complete VP8 key frame from a source I420 picture.
5707///
5708/// This is the §9 / §11 / §19.2 raster driver: it walks the source
5709/// macroblock-by-macroblock in raster order, and for each macroblock
5710///
5711/// 1. extracts the 16×16 luma / 8×8 chroma source block (edge-replicating
5712///    a partial right / bottom macroblock);
5713/// 2. gathers the reconstructed-neighbour strips from the
5714///    already-encoded part of the frame (the exact [`MbNeighbors`] the
5715///    decoder's frame walker assembles via `gather_neighbors`);
5716/// 3. picks the §12.2 whole-block or §11.3 / §12.3 `B_PRED` intra mode
5717///    and forward-transforms / quantises the residual
5718///    ([`encode_mb_block_set_with_neighbors`]);
5719/// 4. dequantises and reconstructs the macroblock through the **decoder's
5720///    own** §14.2 / §12.3 reconstruction orchestrators and writes the
5721///    result back into the running reconstruction buffer, so the next
5722///    macroblock predicts from genuine reconstructed pixels;
5723/// 5. records the chosen [`MacroblockModes`] and the raw-quantised
5724///    [`MbCoeffs`].
5725///
5726/// After the walk it assembles the §9 frame header + §19.2 first
5727/// (control) partition (with the §11 macroblock-mode layer threaded
5728/// through the cross-macroblock `B_PRED` sub-block context buffers) and
5729/// `params.nbr_of_dct_partitions` §19.2 DCT partitions carrying every
5730/// non-skipped macroblock's §13.3 token data, with the §13.3 above
5731/// (per-column, frame-lived) / left (per-row) non-zero predictor contexts
5732/// evolving exactly as the decoder reads them. Per the §20.4 row-loop,
5733/// macroblock row `r` is encoded into partition `r % N`; each partition
5734/// uses its own [`BoolEncoder`] and is finalised independently with the
5735/// usual §7.3 4-byte flush trailer (§4 page 9 — "All partitions are
5736/// decoded using separate instances of the boolean entropy decoder").
5737/// A §9.5 size table of `(N - 1) * 3` little-endian bytes precedes the
5738/// partition bodies when `N > 1`.
5739///
5740/// The emitted bytes decode through the crate's own [`crate::decode_vp8`]
5741/// and reproduce the source within the §14 quantiser's distortion.
5742///
5743/// # Scope (this round)
5744///
5745/// Single key frame, RD intra mode pick, no inter prediction. The §9.5
5746/// DCT partition count is configurable (1 / 2 / 4 / 8) through
5747/// [`KeyframeParams::nbr_of_dct_partitions`]; the residual coding inside
5748/// each partition is bit-identical to the 1-partition case (multi-
5749/// partition output is a layout reorganisation, not a coding change).
5750/// The §15 loop filter runs as a post-reconstruction stage when
5751/// `KeyframeParams::loop_filter_level != 0`; the §9.4 reference / mode
5752/// delta layer is disabled (the encoder writes
5753/// `mode_ref_lf_delta_enabled = false`).
5754///
5755/// [`MbNeighbors`]: crate::reconstruct::MbNeighbors
5756pub fn encode_keyframe(frame: &I420Frame, params: &KeyframeParams) -> Result<Vec<u8>, EncodeError> {
5757    let (bytes, _planes) = encode_keyframe_with_reconstruction(frame, params)?;
5758    Ok(bytes)
5759}
5760
5761/// Encode a key frame with a caller-supplied §13.4 `token_prob_update()`
5762/// payload. The 4×8×3×11 `updates` array carries `Some(prob)` for each
5763/// `coeff_probs[i][j][k][t]` position the caller wants to replace and
5764/// `None` for the positions the §13.5 defaults should keep. The encoder
5765/// merges `updates` onto the §13.5 defaults via
5766/// [`merge_default_token_probs`](crate::merge_default_token_probs)
5767/// before its picker / token-encode passes, so both the rate-distortion
5768/// token-bit estimates and the emitted bitstream use the same merged
5769/// table the decoder will rebuild after reading the same updates.
5770///
5771/// When every entry of `updates` is `None`, the emitted bytes match
5772/// [`encode_keyframe`] byte-for-byte (the §13.4 sub-block reduces to
5773/// the 1056 zero-flag wire and the merged `coeff_probs` is identical to
5774/// the defaults). Otherwise the §13.4 sub-block carries the changed
5775/// positions and downstream token decoding uses the merged table for
5776/// the lifetime of the frame **only**: a key frame carrying updates
5777/// writes `refresh_entropy_probs = 0`, so the decoder's carried table
5778/// reverts to the §13.5 defaults afterwards (the base every inter
5779/// entry point in this crate codes against — see the §9.7 comment in
5780/// the keyframe driver).
5781///
5782/// Returns the bitstream bytes only; pair with the underlying
5783/// [`encode_keyframe_with_reconstruction_and_token_updates`] when the
5784/// post-§15 reconstruction planes are also needed (e.g. by a stream
5785/// encoder seeding its reference slots).
5786pub fn encode_keyframe_with_token_prob_updates(
5787    frame: &I420Frame,
5788    params: &KeyframeParams,
5789    updates: &TokenProbUpdates,
5790) -> Result<Vec<u8>, EncodeError> {
5791    let (bytes, _planes) =
5792        encode_keyframe_with_reconstruction_and_token_updates(frame, params, Some(updates))?;
5793    Ok(bytes)
5794}
5795
5796/// Encode a key frame, **fitting** the §13.4 `token_prob_update()`
5797/// per-position replacements from this frame's observed token-tree
5798/// branch counts (RFC 6386 §13.4 / §13.5).
5799///
5800/// Rounds 155 and 156 landed the caller-driven §13.4 layer for the
5801/// keyframe and inter paths respectively — they let an external caller
5802/// hand in any `TokenProbUpdates` payload and the encoder writes the
5803/// §13.4 sub-block, threads the merged `coeff_probs` through the §13.3
5804/// token-encode pass, and the decoder rebuilds the same merged table
5805/// from the on-wire updates. Round 157 closes the natural follow-up:
5806/// the encoder now *picks* the §13.4 updates itself, from the very
5807/// counts the residual it is about to emit would produce against the
5808/// §13.5 defaults.
5809///
5810/// The fit is the obvious one: at each
5811/// `(plane, band, prev_ctx, position)` slot of the 4×8×3×11 table,
5812/// `p_obs = round(256 * zeros / total)` clamped to `[1, 255]` (the
5813/// boolean coder's valid `Prob` range) is the maximum-likelihood
5814/// estimate of the per-bit "probability of `0`" the encoder just
5815/// observed. An update is emitted only when the body bit saving
5816/// `(n0 * cost(p_old,0) + n1 * cost(p_old,1)) - (n0 * cost(p_new,0) +
5817/// n1 * cost(p_new,1))` exceeds the §13.4 transmission cost
5818/// `(cost(update_prob,1) + 8) - cost(update_prob,0)` plus a small
5819/// `min_saving_bits = 2.0` guard against re-encode drift. Slots with
5820/// zero observed count keep the §13.5 default. See
5821/// [`fit_token_prob_updates`] for the full cost-model.
5822///
5823/// Internally the function takes two passes:
5824///
5825///   1. Encode with the §13.5 defaults and collect the per-position
5826///      branch counts via the [`encode_keyframe_inner`]
5827///      `counts` side-channel.
5828///   2. Run [`fit_token_prob_updates`] to derive the
5829///      [`TokenProbUpdates`] payload that nets a positive bit saving
5830///      against those counts, then re-encode with that payload through
5831///      [`encode_keyframe_with_token_prob_updates`].
5832///
5833/// If the fitter returns an all-`None` payload (no slot crossed the
5834/// saving threshold), or the fitted re-encode is **larger** than the
5835/// default-encode wire (the model's saving estimate is computed
5836/// against pass-1's coefficient distribution; pass-2's RD pick perturbs
5837/// it slightly), the default-encode bytes are returned instead — so
5838/// this entry-point is guaranteed to be `<=` the
5839/// `encode_keyframe_with_token_prob_updates(.., all-None)` wire in
5840/// every case. The returned bytes always decode through the crate's
5841/// own [`crate::decode_vp8`] and any compliant VP8 decoder.
5842///
5843/// Out of round-157 scope: the inter (P-frame) path's analogous
5844/// `encode_p_frame_*_with_fitted_token_prob_updates` entry — this round
5845/// scopes to the keyframe path mirroring the r155-then-r156 split that
5846/// landed the caller-driven layer; the inter fitter can stack on top
5847/// in a subsequent round through the same [`fit_token_prob_updates`]
5848/// machinery (the cost-model and the [`BranchCounts`] type are shared).
5849pub fn encode_keyframe_with_fitted_token_prob_updates(
5850    frame: &I420Frame,
5851    params: &KeyframeParams,
5852) -> Result<Vec<u8>, EncodeError> {
5853    // Pass 1 — defaults + observed branch counts.
5854    let mut counts = empty_branch_counts();
5855    let (bytes_default, _planes_default) =
5856        encode_keyframe_inner(frame, params, None, Some(&mut counts))?;
5857
5858    // Fit. 2.0 bits of slack guards against the small body-saving
5859    // overstatement that comes from the pass-2 RD pick perturbing
5860    // the coefficient distribution slightly relative to pass-1's
5861    // counts.
5862    let fitted = fit_token_prob_updates(&counts, 2.0);
5863
5864    // If no slot crossed the threshold, the default encode wins
5865    // trivially (the all-`None` path is byte-identical to the
5866    // round-154 wire).
5867    let any_update = any_token_prob_update(&fitted);
5868    if !any_update {
5869        return Ok(bytes_default);
5870    }
5871
5872    // Pass 2 — re-encode with the fitted updates. The pick / forward-
5873    // transform layer re-runs against the merged probabilities (the RD
5874    // estimator uses the merged table), so the chosen coefficients may
5875    // shift relative to pass 1. The encoder remains self-consistent —
5876    // the decoder rebuilds the same merged table from the on-wire
5877    // updates and reconstructs the same picture.
5878    let bytes_fitted = encode_keyframe_with_token_prob_updates(frame, params, &fitted)?;
5879
5880    // Guard against the cost-model overstating the saving: only ship
5881    // the fitted bytes when they actually shrink the wire.
5882    if bytes_fitted.len() <= bytes_default.len() {
5883        Ok(bytes_fitted)
5884    } else {
5885        Ok(bytes_default)
5886    }
5887}
5888
5889/// Encode a key frame with an automatically-fitted §13.4
5890/// `token_prob_update()` payload **and** return the post-§15
5891/// reconstructed [`crate::frame::KeyframePlanes`] alongside the wire.
5892///
5893/// Planes-returning companion to
5894/// [`encode_keyframe_with_fitted_token_prob_updates`] (round 157),
5895/// shaped the same way [`encode_keyframe_with_reconstruction`] relates
5896/// to [`encode_keyframe`]. The bytes are byte-identical to the no-
5897/// reconstruction fitter and the returned planes are the **macroblock-
5898/// aligned** post-§15 frame the decoder would rebuild from those bytes —
5899/// the exact shape the §9 three-slot reference-frame buffer wants for
5900/// `LAST` / `GOLDEN` / `ALTREF` installation.
5901///
5902/// Round 159 wires this into
5903/// [`crate::stream::Vp8KeyframeStreamEncoder::encode_frame_with_fitted_token_prob_updates`]
5904/// so the multi-frame keyframe stream driver can fit the §13.4 payload
5905/// per frame while keeping a sound LAST slot for the (currently-unused
5906/// for the keyframe driver, but populated for symmetry with the §9
5907/// three-slot ladder) downstream frame to predict from. The bytes-only
5908/// variant remains available for callers that don't need the planes.
5909///
5910/// The two-pass fitter + safety-guard semantics mirror
5911/// [`encode_keyframe_with_fitted_token_prob_updates`] exactly: pass 1
5912/// encodes with §13.5 defaults and records branch counts; pass 2
5913/// re-encodes with the fitted payload; if pass 2 isn't strictly smaller
5914/// the default-pass bytes **and** default-pass planes are returned so
5915/// the caller's downstream LAST slot stays consistent with the wire
5916/// (mirrors the round-158 inter fitter's matching-planes guarantee).
5917pub fn encode_keyframe_with_reconstruction_and_fitted_token_prob_updates(
5918    frame: &I420Frame,
5919    params: &KeyframeParams,
5920) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
5921    // Pass 1 — defaults + observed branch counts.
5922    let mut counts = empty_branch_counts();
5923    let (bytes_default, planes_default) =
5924        encode_keyframe_inner(frame, params, None, Some(&mut counts))?;
5925
5926    // Fit. 2.0 bits of slack matches the round-157/158 fitter shape.
5927    let fitted = fit_token_prob_updates(&counts, 2.0);
5928
5929    // No slot crossed the threshold ⇒ default encode wins trivially
5930    // (all-`None` path is byte-identical to the round-154 wire).
5931    let any_update = any_token_prob_update(&fitted);
5932    if !any_update {
5933        return Ok((bytes_default, planes_default));
5934    }
5935
5936    // Pass 2 — re-encode with the fitted updates AND keep the matching
5937    // reconstruction. The picker re-runs against the merged probabilities
5938    // (RD estimator uses the merged table), so the chosen coefficients
5939    // may shift relative to pass 1; the encoder remains self-consistent
5940    // because the decoder rebuilds the same merged table from the on-
5941    // wire updates and reconstructs the same picture as `planes_fitted`.
5942    let (bytes_fitted, planes_fitted) =
5943        encode_keyframe_with_reconstruction_and_token_updates(frame, params, Some(&fitted))?;
5944
5945    // Guard against the cost-model overstating the saving: only ship
5946    // the fitted bytes when they actually shrink the wire. On the
5947    // fall-back path we MUST also return the default-pass planes,
5948    // otherwise a streaming caller's next-frame LAST slot would not
5949    // match what the decoder will hold (the two passes' picker outputs
5950    // differ when the merged table differs). Mirrors the round-158
5951    // inter fitter's matching-planes guarantee.
5952    if bytes_fitted.len() <= bytes_default.len() {
5953        Ok((bytes_fitted, planes_fitted))
5954    } else {
5955        Ok((bytes_default, planes_default))
5956    }
5957}
5958
5959/// Encode a key frame and return both the bitstream bytes **and** the
5960/// post-loop-filter reconstructed [`crate::frame::KeyframePlanes`] the
5961/// decoder will rebuild from those bytes.
5962///
5963/// This is the same machinery as [`encode_keyframe`] — the encoder
5964/// already maintains a running reconstruction buffer internally so each
5965/// macroblock can predict from genuine reconstructed neighbours, and
5966/// the §15 post-walk loop filter pass mutates that buffer in place. The
5967/// only difference is that here we hand the resulting buffer back to
5968/// the caller instead of dropping it on return.
5969///
5970/// The returned planes are the **macroblock-aligned** post-§15 frame
5971/// (width rounded up to `mb_cols * 16`, height to `mb_rows * 16`),
5972/// matching the layout of [`crate::frame::KeyframePlanes`] and the
5973/// per-slot storage of [`crate::state::RefFrameSlot`]. This is exactly
5974/// the shape the §9 reference-frame buffer wants — a multi-frame
5975/// keyframe driver can drop the planes straight into the LAST / GOLDEN
5976/// / ALTREF slots that a subsequent inter frame would predict from.
5977///
5978/// The visible-cropped (`width × height`) picture suitable for display
5979/// is what the crate's own [`crate::decode_vp8`] produces when handed
5980/// the returned bytes.
5981pub fn encode_keyframe_with_reconstruction(
5982    frame: &I420Frame,
5983    params: &KeyframeParams,
5984) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
5985    encode_keyframe_with_reconstruction_and_token_updates(frame, params, None)
5986}
5987
5988/// Encode a key frame with RD-selected §9.4 `loop_filter_level`.
5989///
5990/// Identical to [`encode_keyframe`] except that `params.loop_filter_level`
5991/// is **ignored**: after the raster walk, the encoder searches the §9.4
5992/// level range for the level that minimises post-§15 visible-window SSD
5993/// against the source (clean-room — RFC 6386 leaves the level choice to
5994/// the encoder; see [`crate::loop_filter::select_filter_level`]) and
5995/// writes that level into the §9.4 header. All other `params` fields
5996/// (quantiser, sharpness, filter type, partition count) are honoured
5997/// verbatim. Returns the on-the-wire bytes.
5998pub fn encode_keyframe_auto_loop_filter(
5999    frame: &I420Frame,
6000    params: &KeyframeParams,
6001) -> Result<Vec<u8>, EncodeError> {
6002    encode_keyframe_inner_lf(frame, params, None, None, true).map(|(bytes, _)| bytes)
6003}
6004
6005/// [`encode_keyframe_auto_loop_filter`] returning both the bitstream and
6006/// the post-§15 reconstruction planes (for a multi-frame driver that
6007/// installs the keyframe as the §9 reference without re-decoding).
6008pub fn encode_keyframe_auto_loop_filter_with_reconstruction(
6009    frame: &I420Frame,
6010    params: &KeyframeParams,
6011) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6012    encode_keyframe_inner_lf(frame, params, None, None, true)
6013}
6014
6015/// Orthogonal per-frame quality/size feature toggles for the generic
6016/// key-frame front door
6017/// [`encode_keyframe_with_reconstruction_and_coding_options`].
6018///
6019/// Each flag switches on one already-proven encoder feature; the
6020/// all-`false` default reproduces
6021/// [`encode_keyframe_with_reconstruction`] byte-for-byte. This struct
6022/// replaces the combinatorial `_auto_loop_filter` /
6023/// `_fitted_token_prob_updates` function-name ladder for callers (like
6024/// the lagged stream driver) that need the features **combined**.
6025#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
6026pub struct KeyframeCodingOptions {
6027    /// RD-select the §9.4 `loop_filter_level` / sharpness per frame
6028    /// (ignoring `params.loop_filter_level`) — the
6029    /// [`encode_keyframe_auto_loop_filter`] behaviour.
6030    pub auto_loop_filter: bool,
6031    /// Two-pass §13.4 `token_prob_update()` fit: pass 1 records the
6032    /// observed §13.3 branch counts, [`fit_token_prob_updates`] derives
6033    /// the profitable replacements, pass 2 re-encodes against the
6034    /// merged table, and the smaller wire ships — the
6035    /// [`encode_keyframe_with_fitted_token_prob_updates`] behaviour.
6036    pub fitted_token_prob_updates: bool,
6037}
6038
6039impl KeyframeCodingOptions {
6040    /// Set `auto_loop_filter`.
6041    #[must_use]
6042    pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
6043        self.auto_loop_filter = v;
6044        self
6045    }
6046
6047    /// Set `fitted_token_prob_updates`.
6048    #[must_use]
6049    pub fn with_fitted_token_prob_updates(mut self, v: bool) -> Self {
6050        self.fitted_token_prob_updates = v;
6051        self
6052    }
6053}
6054
6055/// Generic key-frame front door combining the §9.4 auto-loop-filter
6056/// selector and the §13.4 fitted token-prob-update emission behind one
6057/// [`KeyframeCodingOptions`] toggle set.
6058///
6059/// * `options == Default` — byte-identical to
6060///   [`encode_keyframe_with_reconstruction`];
6061/// * only `auto_loop_filter` — byte-identical to
6062///   [`encode_keyframe_auto_loop_filter_with_reconstruction`];
6063/// * only `fitted_token_prob_updates` — byte-identical to
6064///   [`encode_keyframe_with_reconstruction_and_fitted_token_prob_updates`];
6065/// * both — the previously unreachable combination: the two-pass fitter
6066///   runs with the RD loop-filter selector active on **both** passes
6067///   (each pass picks its own §9.4 level; the shipped wire's header
6068///   level always matches the shipped reconstruction, so decoder
6069///   lockstep holds).
6070///
6071/// Returns the wire bytes plus the matching post-§15 reconstruction
6072/// planes for the §9 reference ladder.
6073pub fn encode_keyframe_with_reconstruction_and_coding_options(
6074    frame: &I420Frame,
6075    params: &KeyframeParams,
6076    options: &KeyframeCodingOptions,
6077) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6078    if !options.fitted_token_prob_updates {
6079        return encode_keyframe_inner_lf(frame, params, None, None, options.auto_loop_filter);
6080    }
6081
6082    // Pass 1 — §13.5 defaults + observed branch counts (same shape as
6083    // the dedicated keyframe fitter, with the auto-LF switch threaded).
6084    let mut counts = empty_branch_counts();
6085    let (bytes_default, planes_default) = encode_keyframe_inner_lf(
6086        frame,
6087        params,
6088        None,
6089        Some(&mut counts),
6090        options.auto_loop_filter,
6091    )?;
6092
6093    // 2.0 bits of slack — matches every other fitter in the crate.
6094    let fitted = fit_token_prob_updates(&counts, 2.0);
6095    if !any_token_prob_update(&fitted) {
6096        return Ok((bytes_default, planes_default));
6097    }
6098
6099    // Pass 2 — re-encode with the fitted updates (picker + token emit
6100    // run against the merged table; auto-LF re-selects on the pass-2
6101    // reconstruction).
6102    let (bytes_fitted, planes_fitted) =
6103        encode_keyframe_inner_lf(frame, params, Some(&fitted), None, options.auto_loop_filter)?;
6104
6105    // Ship the smaller wire, always with its matching planes so a
6106    // streaming caller's LAST slot equals the decoder's reconstruction.
6107    if bytes_fitted.len() <= bytes_default.len() {
6108        Ok((bytes_fitted, planes_fitted))
6109    } else {
6110        Ok((bytes_default, planes_default))
6111    }
6112}
6113
6114/// Encode a key frame under [`KeyframeEncodeOptions`] — the entry point
6115/// for callers that want to trade output size for encode time
6116/// ([`EncodeEffort`]) or spread the encode over several threads.
6117///
6118/// `KeyframeEncodeOptions::default()` is byte-identical to
6119/// [`encode_keyframe`]; for any options the bytes are independent of
6120/// `options.threads`. Returns the bitstream only — see
6121/// [`encode_keyframe_with_reconstruction_and_options`] for the planes.
6122///
6123/// ```
6124/// use oxideav_vp8::{
6125///     EncodeEffort, I420Frame, KeyframeEncodeOptions, KeyframeParams,
6126///     encode_keyframe_with_options,
6127/// };
6128/// # let (width, height) = (64u32, 48u32);
6129/// # let y_plane = vec![128u8; (width * height) as usize];
6130/// # let u_plane = vec![128u8; ((width / 2) * (height / 2)) as usize];
6131/// # let v_plane = u_plane.clone();
6132/// let frame = I420Frame::packed(width, height, &y_plane, &u_plane, &v_plane);
6133/// let options = KeyframeEncodeOptions::new()
6134///     .with_effort(EncodeEffort::Fast)
6135///     .with_threads(4);
6136/// let bytes = encode_keyframe_with_options(&frame, &KeyframeParams::default(), &options)?;
6137/// # assert!(!bytes.is_empty());
6138/// # Ok::<(), oxideav_vp8::EncodeError>(())
6139/// ```
6140pub fn encode_keyframe_with_options(
6141    frame: &I420Frame,
6142    params: &KeyframeParams,
6143    options: &KeyframeEncodeOptions,
6144) -> Result<Vec<u8>, EncodeError> {
6145    encode_keyframe_with_reconstruction_and_options(frame, params, options).map(|(bytes, _)| bytes)
6146}
6147
6148/// [`encode_keyframe_with_options`] returning both the bitstream and the
6149/// macroblock-aligned post-§15 reconstruction (the planes a decoder
6150/// rebuilds from those bytes).
6151///
6152/// With `options.fitted_token_prob_updates` the encode runs twice — once
6153/// against the §13.5 defaults to collect the branch counts, once against
6154/// the fitted table — and the smaller wire ships with its matching
6155/// planes, exactly as
6156/// [`encode_keyframe_with_reconstruction_and_coding_options`] does.
6157pub fn encode_keyframe_with_reconstruction_and_options(
6158    frame: &I420Frame,
6159    params: &KeyframeParams,
6160    options: &KeyframeEncodeOptions,
6161) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6162    encode_keyframe_under_options(frame, params, options).map(|out| (out.bytes, out.planes))
6163}
6164
6165/// [`encode_keyframe_with_options`] returning, next to the bitstream and
6166/// its reconstruction, what the encoder settled on: the §13.4
6167/// token-probability updates the frame carries and its §9.4 loop-filter
6168/// level / sharpness.
6169///
6170/// The returned updates are what
6171/// [`KeyframeEncodeOptions::with_search_token_probs`] takes: an encoder
6172/// of many similar pictures (animation frames, tiles of one picture)
6173/// hands each encode the table the previous one came out with, so the
6174/// search prices tokens against statistics close to its own from the
6175/// first macroblock on.
6176///
6177/// ```
6178/// use oxideav_vp8::{
6179///     I420Frame, KeyframeEncodeOptions, KeyframeParams, encode_keyframe_detailed,
6180/// };
6181/// # let (width, height) = (64u32, 48u32);
6182/// # let y_plane: Vec<u8> = (0..width * height).map(|i| (i * 7 % 251) as u8).collect();
6183/// # let u_plane = vec![128u8; ((width / 2) * (height / 2)) as usize];
6184/// # let v_plane = u_plane.clone();
6185/// let frame = I420Frame::packed(width, height, &y_plane, &u_plane, &v_plane);
6186/// let params = KeyframeParams::default();
6187/// let first = encode_keyframe_detailed(&frame, &params, &KeyframeEncodeOptions::new())?;
6188/// // The next similar picture searches against the first one's table.
6189/// let options = KeyframeEncodeOptions::new().with_search_token_probs(first.token_prob_updates);
6190/// let second = encode_keyframe_detailed(&frame, &params, &options)?;
6191/// assert!(second.bytes.len() <= first.bytes.len() + first.bytes.len() / 50);
6192/// # Ok::<(), oxideav_vp8::EncodeError>(())
6193/// ```
6194pub fn encode_keyframe_detailed(
6195    frame: &I420Frame,
6196    params: &KeyframeParams,
6197    options: &KeyframeEncodeOptions,
6198) -> Result<KeyframeEncoded, EncodeError> {
6199    let out = encode_keyframe_under_options(frame, params, options)?;
6200    Ok(KeyframeEncoded {
6201        bytes: out.bytes,
6202        reconstruction: out.planes,
6203        token_prob_updates: out.shipped_updates,
6204        loop_filter_level: out.loop_filter.0,
6205        sharpness_level: out.loop_filter.1,
6206    })
6207}
6208
6209/// One key-frame encode as [`KeyframeEncodeOptions`] describes it.
6210fn encode_keyframe_under_options(
6211    frame: &I420Frame,
6212    params: &KeyframeParams,
6213    options: &KeyframeEncodeOptions,
6214) -> Result<KeyframeDriven, EncodeError> {
6215    let drive = KeyframeDrive {
6216        search_updates: options.search_token_probs.as_ref(),
6217        fit_in_place: options.token_prob_fit,
6218        // The pilot costs about as much as a tenth of the lowest level's
6219        // whole search for a third of a percent of its bytes; from `Fast`
6220        // up it is a few percent of the time for up to a percent.
6221        pilot_stride: (options.effort != EncodeEffort::Fastest).then_some(4),
6222        loop_filter: if options.auto_loop_filter {
6223            LoopFilterPick::Search
6224        } else if options.sampled_loop_filter {
6225            LoopFilterPick::Sampled
6226        } else {
6227            LoopFilterPick::Fixed
6228        },
6229        effort: options.effort,
6230        threads: options.threads,
6231    };
6232    if !options.fitted_token_prob_updates {
6233        return encode_keyframe_driven(frame, params, None, &drive);
6234    }
6235    // Second search against the table fitted to the first one. With the
6236    // fit in place the first pass already shipped that table; without
6237    // it the table comes from the first pass's branch counts (2.0 bits
6238    // of slack, the search of pass two shifting the statistics a
6239    // little).
6240    let mut counts = empty_branch_counts();
6241    let first = encode_keyframe_driven(frame, params, Some(&mut counts), &drive)?;
6242    let fitted = if drive.fit_in_place {
6243        first.shipped_updates
6244    } else {
6245        let fitted = fit_token_prob_updates(&counts, 2.0);
6246        any_token_prob_update(&fitted).then_some(fitted)
6247    };
6248    let Some(fitted) = fitted else {
6249        return Ok(first);
6250    };
6251    let second = encode_keyframe_driven(
6252        frame,
6253        params,
6254        None,
6255        &KeyframeDrive {
6256            search_updates: Some(&fitted),
6257            ..drive
6258        },
6259    )?;
6260    Ok(if second.bytes.len() <= first.bytes.len() {
6261        second
6262    } else {
6263        first
6264    })
6265}
6266
6267/// Encode a key frame and return both the bitstream bytes **and** the
6268/// post-loop-filter reconstructed [`crate::frame::KeyframePlanes`],
6269/// optionally threading a §13.4 `token_prob_update()` payload through
6270/// the encode.
6271///
6272/// `token_updates = None` is the round-154 wire (every §13.4 flag = 0,
6273/// §13.5 defaults retained); `token_updates = Some(u)` writes the
6274/// per-position replacement layer and uses the merged `coeff_probs` for
6275/// both the picker's RD estimate and the §13.3 token-encode pass. The
6276/// emitted bitstream decodes through the crate's own [`crate::decode_vp8`]
6277/// and through any compliant VP8 decoder under either path.
6278///
6279/// See [`encode_keyframe_with_token_prob_updates`] for the no-plane
6280/// variant and [`encode_keyframe_with_reconstruction`] for the
6281/// no-updates variant.
6282pub fn encode_keyframe_with_reconstruction_and_token_updates(
6283    frame: &I420Frame,
6284    params: &KeyframeParams,
6285    token_updates: Option<&TokenProbUpdates>,
6286) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6287    encode_keyframe_inner(frame, params, token_updates, None)
6288}
6289
6290/// Internal keyframe driver shared by
6291/// [`encode_keyframe_with_reconstruction_and_token_updates`] and the
6292/// round-157 [`encode_keyframe_with_fitted_token_prob_updates`] fitter.
6293///
6294/// `counts` (when `Some`) is filled with the per-position §13.4 branch
6295/// counts the §13.3 token-encode pass produces against the supplied
6296/// `token_updates` table. With `counts = None` the function reduces
6297/// exactly to the public entry-point above (no extra work, no behaviour
6298/// change). With `counts = Some(&mut c)` the §13.3 walk records each
6299/// `(plane, band, prev_ctx, position)` bit-event into `c` alongside its
6300/// regular `BoolEncoder` write — `c`'s contents are the only side-effect
6301/// of the parameter; the emitted bytes are byte-identical to the
6302/// `counts = None` invocation with the same `token_updates`.
6303fn encode_keyframe_inner(
6304    frame: &I420Frame,
6305    params: &KeyframeParams,
6306    token_updates: Option<&TokenProbUpdates>,
6307    counts: Option<&mut BranchCounts>,
6308) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6309    encode_keyframe_inner_lf(frame, params, token_updates, counts, false)
6310}
6311
6312/// `encode_keyframe_inner` extended with the round-373 §9.4 RD
6313/// loop-filter-level auto-selection switch.
6314///
6315/// When `auto_lf` is `false` the behaviour is byte-identical to the
6316/// historical [`encode_keyframe_inner`]: `params.loop_filter_level` is the
6317/// frame's filter level verbatim. When `auto_lf` is `true` the level
6318/// stored in `params` is *ignored* and, after the raster walk produces the
6319/// unfiltered reconstruction, [`crate::loop_filter::select_filter_level`]
6320/// picks the level that minimises post-§15 visible-window SSD against the
6321/// source `frame`; that chosen level is then both applied to the
6322/// reconstruction and written into the §9.4 header, so the encoder's
6323/// reconstruction stays in lock-step with a compliant decoder.
6324fn encode_keyframe_inner_lf(
6325    frame: &I420Frame,
6326    params: &KeyframeParams,
6327    token_updates: Option<&TokenProbUpdates>,
6328    counts: Option<&mut BranchCounts>,
6329    auto_lf: bool,
6330) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6331    encode_keyframe_tuned(
6332        frame,
6333        params,
6334        token_updates,
6335        counts,
6336        auto_lf,
6337        EncodeEffort::Thorough,
6338        1,
6339    )
6340}
6341
6342/// The key-frame driver behind every front door: [`encode_keyframe_inner_lf`]
6343/// plus the mode-search `effort` and the `threads` budget of the
6344/// macroblock-row wavefront (see the `wavefront` module). `Thorough` on
6345/// one thread is the historical encode; the bytes never depend on
6346/// `threads`.
6347fn encode_keyframe_tuned(
6348    frame: &I420Frame,
6349    params: &KeyframeParams,
6350    token_updates: Option<&TokenProbUpdates>,
6351    counts: Option<&mut BranchCounts>,
6352    auto_lf: bool,
6353    effort: EncodeEffort,
6354    threads: usize,
6355) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6356    let drive = KeyframeDrive {
6357        search_updates: token_updates,
6358        fit_in_place: false,
6359        pilot_stride: None,
6360        loop_filter: if auto_lf {
6361            LoopFilterPick::Search
6362        } else {
6363            LoopFilterPick::Fixed
6364        },
6365        effort,
6366        threads,
6367    };
6368    encode_keyframe_driven(frame, params, counts, &drive).map(|out| (out.bytes, out.planes))
6369}
6370
6371/// How a key-frame encode settles its §9.4 loop-filter level and
6372/// sharpness.
6373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6374enum LoopFilterPick {
6375    /// `KeyframeParams::loop_filter_level` / `sharpness_level` as given.
6376    Fixed,
6377    /// The search run on a sample of the picture (bands of macroblock
6378    /// rows), coarse to fine.
6379    Sampled,
6380    /// Measure every candidate on the reconstruction and keep the best.
6381    Search,
6382}
6383
6384/// Everything that steers one run of the key-frame driver.
6385struct KeyframeDrive<'a> {
6386    /// §13.4 updates the mode search prices tokens against (`None` = the
6387    /// §13.5 defaults). They are also what ships, unless `fit_in_place`.
6388    search_updates: Option<&'a TokenProbUpdates>,
6389    /// Fit the §13.4 updates to the recorded token decisions of this
6390    /// very search and code the tokens against the fitted table.
6391    fit_in_place: bool,
6392    /// With `fit_in_place` and no `search_updates`: derive the search's
6393    /// table from a pilot pass over every this-many-th macroblock row.
6394    pilot_stride: Option<usize>,
6395    loop_filter: LoopFilterPick,
6396    effort: EncodeEffort,
6397    threads: usize,
6398}
6399
6400/// What one run of the key-frame driver produced.
6401struct KeyframeDriven {
6402    bytes: Vec<u8>,
6403    /// Macroblock-aligned post-§15 reconstruction.
6404    planes: crate::frame::KeyframePlanes,
6405    /// The §13.4 updates in the stream (`None` = none, the §13.5
6406    /// defaults are in force).
6407    shipped_updates: Option<TokenProbUpdates>,
6408    /// The §9.4 level and sharpness in the stream.
6409    loop_filter: (u8, u8),
6410}
6411
6412/// The key-frame driver proper.
6413fn encode_keyframe_driven(
6414    frame: &I420Frame,
6415    params: &KeyframeParams,
6416    counts: Option<&mut BranchCounts>,
6417    drive: &KeyframeDrive,
6418) -> Result<KeyframeDriven, EncodeError> {
6419    let (effort, threads) = (drive.effort, drive.threads);
6420    let token_updates = drive.search_updates;
6421    let auto_lf = drive.loop_filter == LoopFilterPick::Search;
6422    let width = frame.width;
6423    let height = frame.height;
6424    if width == 0 || width > 0x3FFF || height == 0 || height > 0x3FFF {
6425        return Err(EncodeError::InvalidDimensions { width, height });
6426    }
6427    if params.y_ac_qi > 127 {
6428        return Err(EncodeError::QuantIndexOutOfRange {
6429            value: params.y_ac_qi,
6430        });
6431    }
6432    if params.loop_filter_level > 63 {
6433        return Err(EncodeError::LoopFilterLevelOutOfRange {
6434            value: params.loop_filter_level,
6435        });
6436    }
6437    if params.sharpness_level > 7 {
6438        return Err(EncodeError::SharpnessLevelOutOfRange {
6439            value: params.sharpness_level,
6440        });
6441    }
6442    // §9.5 — the partition-count is validated here so a bad value is
6443    // rejected before the long mode-pick / forward-transform walk runs.
6444    // `write_token_partition_count` re-validates at the actual bitstream
6445    // emission point.
6446    let num_partitions = match params.nbr_of_dct_partitions {
6447        1 | 2 | 4 | 8 => params.nbr_of_dct_partitions as usize,
6448        other => return Err(EncodeError::InvalidDctPartitionCount { value: other }),
6449    };
6450
6451    let mb_cols = width.div_ceil(16) as usize;
6452    let mb_rows = height.div_ceil(16) as usize;
6453
6454    // §13.4 token-prob update: when the caller supplies a non-empty
6455    // `token_updates` array, the encoder writes its replacement layer
6456    // through `write_token_prob_updates` below AND uses the merged
6457    // `coeff_probs` table for both the picker's RD estimate and the
6458    // §13.3 token-encode pass. The decoder reads the same updates and
6459    // rebuilds the same merged table, so the bitstream stays sound on
6460    // either path. `None` (or an all-`None` array) preserves the
6461    // round-154 wire byte-for-byte.
6462    let mut coeff_probs = match token_updates {
6463        Some(u) => crate::dct_tokens::merge_default_token_probs(u),
6464        None => crate::dct_tokens::DEFAULT_COEFF_PROBS,
6465    };
6466    let factors = crate::dequant::MbDequantFactors::from_base_and_deltas(
6467        params.y_ac_qi as i32,
6468        0,
6469        0,
6470        0,
6471        0,
6472        0,
6473    );
6474    // With the fit in place the search's table never ships, so when the
6475    // caller brought none it is taken from a pilot look at the picture
6476    // (see `pilot.rs`) rather than left at the §13.5 defaults.
6477    if let (Some(stride), None) = (drive.pilot_stride, token_updates)
6478        && drive.fit_in_place
6479    {
6480        let defaults = crate::dct_tokens::DEFAULT_COEFF_PROBS;
6481        let default_tables = TrellisRateTables::for_probs(&defaults);
6482        let pilot_rd = MbRdCtx {
6483            factors: &factors,
6484            coeff_probs: &defaults,
6485            rate_tables: Some(&default_tables),
6486            lambda: rd_lambda(&factors),
6487            trellis: params.trellis_strength,
6488        };
6489        let seen =
6490            pilot::pilot_branch_counts(frame, &pilot_rd, (mb_cols, mb_rows), stride, threads);
6491        coeff_probs = pilot::blend_into_defaults(&seen);
6492    }
6493    // Per-frame §13 trellis rate tables for the resolved `coeff_probs`
6494    // (see `TrellisRateTables`) — built once here so the per-MB mode
6495    // search prices tokens from lookups instead of re-walking the §13.2
6496    // tree per candidate. Values (and bytes) are identical either way.
6497    let trellis_rate_tables = Some(TrellisRateTables::for_probs(&coeff_probs));
6498
6499    // Running reconstruction buffer — identical layout to the decoder's
6500    // `decode_keyframe` output. Each MB's neighbours are gathered from
6501    // here via the decoder's own `gather_neighbors`, guaranteeing the
6502    // encoder predicts from the exact pixels the decoder will.
6503    let mut planes = crate::frame::KeyframePlanes {
6504        y: vec![0u8; mb_cols * 16 * mb_rows * 16],
6505        u: vec![0u8; mb_cols * 8 * mb_rows * 8],
6506        v: vec![0u8; mb_cols * 8 * mb_rows * 8],
6507        y_stride: mb_cols * 16,
6508        uv_stride: mb_cols * 8,
6509        mb_cols,
6510        mb_rows,
6511    };
6512
6513    // ---- Macroblock analysis + §19.2 DCT partitions ----------------------
6514    //
6515    // Each macroblock: gather the reconstructed neighbour strips, pick
6516    // the modes and quantise the residual (exhaustively, or through the
6517    // cost model at a reduced effort), reconstruct through the decoder's
6518    // own §14.2 / §12.3 orchestrators, and write the result back so
6519    // later macroblocks predict from genuine reconstructed pixels. A
6520    // macroblock with no non-zero residual is coded as a §11.1 skip.
6521    //
6522    // The §13.3 token data follows the analysis row by row: macroblock
6523    // row `r` is coded into partition `r % N` (§20.4), each partition
6524    // through its own [`BoolEncoder`] (§4 page 9 — "All partitions are
6525    // decoded using separate instances of the boolean entropy decoder")
6526    // finalised with its own §7.3 flush trailer; the "above" non-zero
6527    // context is per column and frame-lived, the "left" context resets
6528    // at each row start.
6529    let search = wavefront::KeyframeSearch {
6530        frame,
6531        rd: MbRdCtx {
6532            factors: &factors,
6533            coeff_probs: &coeff_probs,
6534            rate_tables: trellis_rate_tables.as_ref(),
6535            lambda: rd_lambda(&factors),
6536            trellis: params.trellis_strength,
6537        },
6538        effort,
6539        mb_cols,
6540        mb_rows,
6541        num_partitions,
6542        defer_token_coding: drive.fit_in_place,
6543        tape_hint: std::sync::atomic::AtomicUsize::new(0),
6544    };
6545    let mut analysed = wavefront::analyse_and_tokenize(&search, &mut planes, threads)?;
6546    // §13.4: with the fit in place the updates that ship are fitted to
6547    // the decisions the search just recorded, and the tapes are coded
6548    // against the fitted table — the search itself priced tokens against
6549    // `coeff_probs`, which the decoder never needs to know. The fit's
6550    // saving is exact for these counts, so it needs no slack.
6551    let shipped_updates: Option<TokenProbUpdates> = if drive.fit_in_place {
6552        let mut observed = empty_branch_counts();
6553        analysed.tally(&mut observed, threads);
6554        let fitted = fit_token_prob_updates(&observed, 0.0);
6555        any_token_prob_update(&fitted).then_some(fitted)
6556    } else {
6557        token_updates.copied()
6558    };
6559    let coded_in_search = analysed.partitions.take();
6560    let code_tapes = |analysed: &wavefront::AnalysedFrame, threads: usize| {
6561        let emit_probs = match &shipped_updates {
6562            Some(u) => crate::dct_tokens::merge_default_token_probs(u),
6563            None => crate::dct_tokens::DEFAULT_COEFF_PROBS,
6564        };
6565        analysed.code_partitions(&emit_probs, num_partitions, threads)
6566    };
6567    let token_updates = shipped_updates.as_ref();
6568    let modes = &analysed.modes;
6569    let has_coeffs = &analysed.has_coeffs;
6570
6571    // ---- §15 loop-filter post-pass --------------------------------------
6572    //
6573    // RFC 6386 §15 page 84: "After the predictor and residue have been
6574    // summed for every macroblock, the filter is applied to the edges
6575    // between adjacent macroblocks and the edges between adjacent
6576    // subblocks." We run the filter here, after the raster walk has
6577    // completed and *before* the bitstream is assembled, so the encoder's
6578    // reconstruction buffer ends up bit-identical to what the decoder
6579    // will produce after its own §15.1 pass over the same frame.
6580    //
6581    // The per-MB neighbour gather inside the raster loop above
6582    // intentionally runs against the *unfiltered* reconstruction (the
6583    // §15.1 filter is a post-reconstruction stage — the predictors that
6584    // feed each macroblock's intra prediction always sample the
6585    // unfiltered neighbour). The filter only adjusts pixels at MB / sub-
6586    // block edges after every MB has been reconstructed.
6587    //
6588    // `filter_frame` uses `MbCoeffs` only for the §15.1 page 86
6589    // "any-coded-coefficient" test that gates the inter-subblock edges
6590    // (steps 2 and 4); that test reduces to "any non-zero coefficient",
6591    // which is invariant under dequantisation by the non-zero §14.1 Q
6592    // steps, so the flag computed from the raw quantised coefficients
6593    // (`has_coeffs`) is the flag the decoder derives.
6594    // The §15 base config (level filled in below). Segmentation off and
6595    // `mode_ref_lf_delta_enabled = false`, so every per-MB override is 0
6596    // and each MB's effective level reduces to the frame base.
6597    // The token coding and the loop filter do not depend on each other:
6598    // with a thread budget the tapes are coded on a thread of their own
6599    // while this one settles and applies the filter.
6600    let filter_stage = |planes: &mut crate::frame::KeyframePlanes| {
6601        let mut lf_config = crate::loop_filter::FrameFilterConfig {
6602            // §9.4 `filter_type`: `false` ⇒ §15.3 normal, `true` ⇒ §15.2
6603            // simple. Mirrors the bit `write_loop_filter` writes below;
6604            // the encoder's own post-walk filter must match what the
6605            // decoder will run.
6606            simple: params.filter_type,
6607            key_frame: true,
6608            loop_filter_level: params.loop_filter_level,
6609            sharpness_level: params.sharpness_level,
6610            segmentation_enabled: false,
6611            segment_abs: false,
6612            segment_lf_level: [0; crate::loop_filter::MAX_MB_SEGMENTS],
6613            delta_enabled: false,
6614            ref_delta_current: 0,
6615            bpred_mode_delta: 0,
6616            ref_delta_last: 0,
6617            ref_delta_golden: 0,
6618            ref_delta_altref: 0,
6619            zero_mv_mode_delta: 0,
6620            other_mv_mode_delta: 0,
6621            split_mv_mode_delta: 0,
6622        };
6623        // §9.4 effective loop-filter level + sharpness. When `auto_lf` is set
6624        // the RD selector jointly replaces `params.loop_filter_level` /
6625        // `params.sharpness_level` with the distortion-minimising pair
6626        // (clean-room; RFC 6386 is silent on the encoder's choice). Both
6627        // chosen values are written to the header below so the decoder runs
6628        // the identical §15 pass.
6629        let src = crate::loop_filter::SourcePlanes {
6630            width: width as usize,
6631            height: height as usize,
6632            y: frame.y,
6633            u: frame.u,
6634            v: frame.v,
6635            y_stride: frame.y_stride,
6636            uv_stride: frame.uv_stride,
6637        };
6638        let (eff_lf_level, eff_sharpness) = if auto_lf {
6639            crate::loop_filter::select_filter_params_threaded(
6640                planes, modes, has_coeffs, &lf_config, &src, None, threads,
6641            )
6642        } else if drive.loop_filter == LoopFilterPick::Sampled {
6643            crate::loop_filter::select_filter_params_sampled(
6644                planes,
6645                modes,
6646                has_coeffs,
6647                &lf_config,
6648                &src,
6649                None,
6650                crate::loop_filter::FilterSampling::for_key_frame(mb_rows),
6651                threads,
6652            )
6653        } else {
6654            (params.loop_filter_level, params.sharpness_level)
6655        };
6656        lf_config.loop_filter_level = eff_lf_level;
6657        lf_config.sharpness_level = eff_sharpness;
6658        if eff_lf_level != 0 {
6659            crate::loop_filter::filter_frame_flags_threaded(
6660                planes, modes, has_coeffs, &lf_config, threads,
6661            );
6662        }
6663        (eff_lf_level, eff_sharpness)
6664    };
6665    let ((eff_lf_level, eff_sharpness), dct_partitions) = match coded_in_search {
6666        Some(coded) => (filter_stage(&mut planes), coded),
6667        None if threads > 1 => std::thread::scope(|scope| {
6668            let coder = scope.spawn(|| code_tapes(&analysed, threads));
6669            let filter = filter_stage(&mut planes);
6670            match coder.join() {
6671                Ok(coded) => (filter, coded),
6672                Err(panic) => std::panic::resume_unwind(panic),
6673            }
6674        }),
6675        None => {
6676            let coded = code_tapes(&analysed, 1);
6677            (filter_stage(&mut planes), coded)
6678        }
6679    };
6680    // `planes` is the macroblock-aligned post-§15 reconstruction. It is
6681    // returned to the caller alongside the bitstream below so a
6682    // multi-frame keyframe driver can install it into the §9
6683    // reference-frame buffer (LAST / GOLDEN / ALTREF) without paying the
6684    // cost of re-decoding the bytes we just emitted.
6685
6686    // ---- §19.2 first (control) partition --------------------------------
6687    let mut hdr = BoolEncoder::new();
6688
6689    // §9.2 — color_space + clamping_type both 0.
6690    hdr.write_bool(128, false);
6691    hdr.write_bool(128, false);
6692    // §9.3 — segmentation off.
6693    write_segment_update_flags(&mut hdr, false);
6694    // §9.4 — loop filter. `filter_type` follows `params.filter_type`
6695    // (false ⇒ §15.3 normal, true ⇒ §15.2 simple);
6696    // `mode_ref_lf_delta_enabled = false` (per the [`KeyframeParams`]
6697    // docs) so no per-MB delta layer is emitted.
6698    // `loop_filter_level == 0` triggers the §15 whole-frame skip on the
6699    // decoder side; any non-zero value is honoured by both ends of the
6700    // round-trip via the post-walk filter pass above.
6701    write_loop_filter(
6702        &mut hdr,
6703        params.filter_type,
6704        eff_lf_level,
6705        eff_sharpness,
6706        false,
6707    )?;
6708    // §9.5 — DCT partition count.
6709    write_token_partition_count(&mut hdr, params.nbr_of_dct_partitions)?;
6710    // §9.6 — quant indices (baseline only).
6711    write_quant_indices(&mut hdr, params.y_ac_qi, None, None, None, None, None)?;
6712    // §9.7 (key frame) — refresh_entropy_probs. An update-free key
6713    // frame keeps the historical 1 (its merged table IS the §13.5
6714    // defaults, so persisting it is a no-op). A key frame that carries
6715    // a §13.4 update payload writes 0 instead, so per §9.10 the
6716    // decoder's carried table reverts to the key-frame reset state (the
6717    // §13.5 defaults) once the frame is done: every inter entry point
6718    // in this crate codes its §13.4 overlay against a defaults carried
6719    // base, and a persisted key-frame overlay would silently diverge
6720    // the encoder's and decoder's probability tables on every following
6721    // P-frame (pixel drift with no decode error — caught by the
6722    // round-387 lagged-driver fitter integration test).
6723    let persists_updates = token_updates.is_some_and(any_token_prob_update);
6724    hdr.write_bool(128, !persists_updates);
6725    // §13 / §9.9 — token-prob update sub-block. With `token_updates =
6726    // Some(u)` the per-position replacement layer is written and the
6727    // merged `coeff_probs` above is what the encoder's tokens are coded
6728    // against (and what the decoder will rebuild after reading the same
6729    // updates). With `None`, every flag is 0 and the §13.5 defaults
6730    // stay in force — byte-identical to the round-154 wire.
6731    match token_updates {
6732        Some(u) => write_token_prob_updates(&mut hdr, u, &COEFF_UPDATE_PROBS_FLAT),
6733        None => write_no_token_prob_updates(&mut hdr, &COEFF_UPDATE_PROBS_FLAT),
6734    }
6735    // §9.11 — mb_no_skip_coeff enabled with a balanced prob so skip and
6736    // non-skip macroblocks both code cheaply.
6737    let prob_skip_false = 128u8;
6738    write_mb_no_skip_coeff(&mut hdr, true, prob_skip_false);
6739
6740    // §11 macroblock-mode layer, threading the §11.3 cross-macroblock
6741    // B_PRED sub-block context buffers exactly as `parse_key_frame_*`
6742    // reads them.
6743    write_mode_layer(&mut hdr, modes, mb_rows, mb_cols, prob_skip_false);
6744
6745    let first_partition = hdr.finish();
6746    let first_partition_size = first_partition.len();
6747    if first_partition_size > 0x7_FFFF {
6748        return Err(EncodeError::FirstPartitionTooLarge {
6749            bytes: first_partition_size,
6750        });
6751    }
6752
6753    // §13.4 observed-counts side-channel (round 157). Re-walks the
6754    // §13.3 token loop with `count_keyframe_branches`, driving
6755    // its own private above / left predictor contexts in lockstep —
6756    // so the recorded per-position counts are bit-for-bit the events
6757    // the bytes in `dct_partitions` carry. With `counts = None`
6758    // this is a no-op.
6759    if let Some(c) = counts {
6760        analysed.tally(c, threads);
6761    }
6762    let dct_total: usize = dct_partitions.iter().map(|p| p.len()).sum();
6763    let size_table_len = (num_partitions - 1) * 3;
6764
6765    // ---- §9.1 frame tag + key-frame extension + assembly ----------------
6766    let mut out: Vec<u8> =
6767        Vec::with_capacity(10 + first_partition_size + size_table_len + dct_total);
6768    write_frame_tag(
6769        &mut out,
6770        true,
6771        0,
6772        true,
6773        first_partition_size as u32,
6774        width,
6775        height,
6776        ScaleCode::None,
6777        ScaleCode::None,
6778    )?;
6779    out.extend_from_slice(&first_partition);
6780    // §9.5 size table: 3-byte little-endian length for every partition
6781    // except the last (whose size the decoder infers from what is left
6782    // in the frame). One partition → no table.
6783    for part in dct_partitions.iter().take(num_partitions - 1) {
6784        let sz = part.len();
6785        out.push((sz & 0xff) as u8);
6786        out.push(((sz >> 8) & 0xff) as u8);
6787        out.push(((sz >> 16) & 0xff) as u8);
6788    }
6789    for part in &dct_partitions {
6790        out.extend_from_slice(part);
6791    }
6792
6793    Ok(KeyframeDriven {
6794        bytes: out,
6795        planes,
6796        shipped_updates,
6797        loop_filter: (eff_lf_level, eff_sharpness),
6798    })
6799}
6800
6801/// Configuration for the §9.3 / §10 segment-based adaptive-quant key-frame
6802/// encoder ([`encode_keyframe_adaptive_quant`]).
6803///
6804/// The encoder sorts each macroblock into one of four segments by its
6805/// luma activity (variance), then applies a per-segment quantizer feature
6806/// so detailed macroblocks can be coded at a finer quantizer than flat
6807/// ones (or vice-versa). All segmentation machinery — the §9.3
6808/// `update_segmentation()` block, the per-MB §10 `segment_id`, the
6809/// per-segment §14.1 dequant factors — is driven from this config. The
6810/// segmentation is **delta-mode** (`segment_feature_mode = 0`): each
6811/// segment's `quant_delta` is added to the §9.6 `base_y_ac_qi`.
6812#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6813#[non_exhaustive]
6814pub struct AdaptiveQuantConfig {
6815    /// §9.6 baseline `y_ac_qi` (0..=127). Each segment's effective qindex
6816    /// is `clamp(base_y_ac_qi + quant_delta[seg], 0, 127)`.
6817    pub base_y_ac_qi: u8,
6818    /// Three ascending luma-variance boundaries splitting macroblocks into
6819    /// the four segments: segment `s` is the count of boundaries the MB's
6820    /// variance meets-or-exceeds (so a flat MB → segment 0, the busiest →
6821    /// segment 3). Values need not be sorted by the caller; the classifier
6822    /// uses them as independent "≥" tests, but ascending order gives the
6823    /// intended monotone mapping.
6824    pub variance_boundaries: [u32; 3],
6825    /// Per-segment §10 `quantizer_update_value` deltas (signed, magnitude
6826    /// ≤ 127), added to `base_y_ac_qi` in delta mode. The natural AQ
6827    /// choice raises the quantizer on flat segments (`+`) and lowers it on
6828    /// detailed segments (`-`); the default does exactly that.
6829    pub quant_delta: [i8; 4],
6830    /// §9.4 baseline loop-filter level (0..=63); `0` skips the §15 filter.
6831    pub loop_filter_level: u8,
6832    /// §9.4 sharpness (0..=7).
6833    pub sharpness_level: u8,
6834    /// §9.4 `filter_type`: false = §15.3 normal, true = §15.2 simple.
6835    pub filter_type: bool,
6836}
6837
6838impl AdaptiveQuantConfig {
6839    /// Set `base_y_ac_qi`.
6840    #[must_use]
6841    pub fn with_base_y_ac_qi(mut self, v: u8) -> Self {
6842        self.base_y_ac_qi = v;
6843        self
6844    }
6845
6846    /// Set `variance_boundaries`.
6847    #[must_use]
6848    pub fn with_variance_boundaries(mut self, v: [u32; 3]) -> Self {
6849        self.variance_boundaries = v;
6850        self
6851    }
6852
6853    /// Set `quant_delta`.
6854    #[must_use]
6855    pub fn with_quant_delta(mut self, v: [i8; 4]) -> Self {
6856        self.quant_delta = v;
6857        self
6858    }
6859
6860    /// Set `loop_filter_level`.
6861    #[must_use]
6862    pub fn with_loop_filter_level(mut self, v: u8) -> Self {
6863        self.loop_filter_level = v;
6864        self
6865    }
6866
6867    /// Set `sharpness_level`.
6868    #[must_use]
6869    pub fn with_sharpness_level(mut self, v: u8) -> Self {
6870        self.sharpness_level = v;
6871        self
6872    }
6873
6874    /// Set `filter_type`.
6875    #[must_use]
6876    pub fn with_filter_type(mut self, v: bool) -> Self {
6877        self.filter_type = v;
6878        self
6879    }
6880}
6881
6882impl Default for AdaptiveQuantConfig {
6883    fn default() -> Self {
6884        AdaptiveQuantConfig {
6885            base_y_ac_qi: 32,
6886            variance_boundaries: [
6887                SEGMENT_VARIANCE_THRESHOLDS[1],
6888                SEGMENT_VARIANCE_THRESHOLDS[2],
6889                SEGMENT_VARIANCE_THRESHOLDS[3],
6890            ],
6891            // Flat → coarser (+), detailed → finer (−): the classic
6892            // activity-masking AQ gradient.
6893            quant_delta: [8, 0, -6, -12],
6894            loop_filter_level: 0,
6895            sharpness_level: 0,
6896            filter_type: false,
6897        }
6898    }
6899}
6900
6901/// Population variance of a 16×16 luma macroblock (×1, integer), the §10
6902/// activity metric the [`AdaptiveQuantConfig`] classifier sorts on.
6903///
6904/// One-pass `E[X²] − E[X]²` in `u64` (256 `u8` samples sum to at most
6905/// `256·255² ≈ 1.66e7`, far inside `u64`). The `saturating_sub` guards the
6906/// rare case where integer rounding of the two terms inverts their order.
6907fn mb_luma_variance(y: &[u8; 256]) -> u32 {
6908    let mut sum: u64 = 0;
6909    let mut sumsq: u64 = 0;
6910    for &px in y.iter() {
6911        sum += px as u64;
6912        sumsq += (px as u64) * (px as u64);
6913    }
6914    let n = 256u64;
6915    let mean_sq = (sum * sum) / (n * n);
6916    let e_sq = sumsq / n;
6917    e_sq.saturating_sub(mean_sq) as u32
6918}
6919
6920/// Classify a macroblock variance into a 0..=3 segment id: the number of
6921/// `variance_boundaries` the variance meets-or-exceeds, capped at 3.
6922fn classify_segment(variance: u32, boundaries: &[u32; 3]) -> u8 {
6923    boundaries.iter().filter(|&&b| variance >= b).count().min(3) as u8
6924}
6925
6926/// Encode a key frame with §9.3 / §10 segment-based adaptive quantisation.
6927///
6928/// Each macroblock is sorted into one of four segments by its §10 luma
6929/// variance ([`mb_luma_variance`] vs the config's `variance_boundaries`),
6930/// and quantised at that segment's effective qindex
6931/// (`clamp(base_y_ac_qi + quant_delta[seg], 0, 127)`). The frame header
6932/// carries the §9.3 `update_segmentation()` block (delta-mode per-segment
6933/// `quantizer_update` values + the `mb_segment_tree_probs`), and the §11
6934/// mode layer carries each MB's §10 `segment_id`. The decoder's
6935/// `resolve_segment_dequant_factors` rebuilds the same four
6936/// [`crate::dequant::MbDequantFactors`] and applies the matching one per
6937/// MB, so the emitted bytes self-decode to the encoder's own
6938/// reconstruction within the per-segment quantiser's distortion.
6939///
6940/// The quantiser used to *quantise* each MB's residual is the same one
6941/// used to *dequantise* it for the running reconstruction buffer, so the
6942/// encoder predicts from the exact pixels the decoder will reconstruct
6943/// (the standard encoder/decoder pixel-lockstep contract). The §15 loop
6944/// filter (when `loop_filter_level != 0`) runs as a post-reconstruction
6945/// stage with segmentation-aware levels left at the frame base (the §10
6946/// per-segment loop-filter feature is not emitted by this path).
6947pub fn encode_keyframe_adaptive_quant(
6948    frame: &I420Frame,
6949    config: &AdaptiveQuantConfig,
6950) -> Result<Vec<u8>, EncodeError> {
6951    let (bytes, _planes) = encode_keyframe_adaptive_quant_with_reconstruction(frame, config)?;
6952    Ok(bytes)
6953}
6954
6955/// As [`encode_keyframe_adaptive_quant`] but with the §13 trellis
6956/// aggressiveness dialed by `trellis` ([`TrellisStrength`]).
6957/// `AdaptiveQuantConfig` derives `Eq`, so the strength is a separate
6958/// argument rather than a struct field; [`TrellisStrength::DEFAULT`]
6959/// reproduces the historical bytes, [`TrellisStrength::OFF`] reverts to
6960/// plain round-quantisation. Per-segment quantisation is unchanged — the
6961/// strength only re-prices the §13 coefficient search inside each MB.
6962pub fn encode_keyframe_adaptive_quant_with_trellis(
6963    frame: &I420Frame,
6964    config: &AdaptiveQuantConfig,
6965    trellis: TrellisStrength,
6966) -> Result<Vec<u8>, EncodeError> {
6967    let (bytes, _planes) = encode_keyframe_adaptive_quant_inner(frame, config, trellis)?;
6968    Ok(bytes)
6969}
6970
6971/// As [`encode_keyframe_adaptive_quant`], but also returns the
6972/// macroblock-aligned post-§15 reconstruction planes (the LAST/GOLDEN/
6973/// ALTREF candidate a multi-frame driver would install) so callers avoid
6974/// re-decoding the bytes just emitted.
6975pub fn encode_keyframe_adaptive_quant_with_reconstruction(
6976    frame: &I420Frame,
6977    config: &AdaptiveQuantConfig,
6978) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6979    encode_keyframe_adaptive_quant_inner(frame, config, TrellisStrength::DEFAULT)
6980}
6981
6982/// As [`encode_keyframe_adaptive_quant_with_reconstruction`] but with the
6983/// §13 trellis aggressiveness dialed by `trellis`.
6984pub fn encode_keyframe_adaptive_quant_with_reconstruction_and_trellis(
6985    frame: &I420Frame,
6986    config: &AdaptiveQuantConfig,
6987    trellis: TrellisStrength,
6988) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
6989    encode_keyframe_adaptive_quant_inner(frame, config, trellis)
6990}
6991
6992/// Encode a key frame with §9.3 / §10 segment-based adaptive
6993/// quantisation **and** the §10 per-segment loop-filter feature — the
6994/// full two-feature `update_segment_feature_data` block.
6995///
6996/// On top of [`encode_keyframe_adaptive_quant`]'s per-segment quantiser
6997/// gradient, `segment_lf_deltas[s]` is the §9.3 `loop_filter_update`
6998/// value for segment `s` (delta mode, signed, magnitude ≤ 63): each
6999/// macroblock's §15 filter level resolves to
7000/// `clamp(loop_filter_level + segment_lf_deltas[seg], 0, 63)` per
7001/// §20.6, in the encoder's own post-walk pass and in any compliant
7002/// decoder alike. The natural pairing with the quantiser gradient is
7003/// **coarser segments filter harder** (they carry more blocking) while
7004/// detailed segments filter lighter (preserving texture) — i.e. deltas
7005/// with the same sign as `quant_delta`.
7006///
7007/// Values outside ±63 are rejected with
7008/// [`EncodeError::LoopFilterLevelOutOfRange`]. The §15 whole-frame skip
7009/// mirrors the decoder: `config.loop_filter_level == 0` skips the
7010/// filter regardless of the deltas. `[0; 4]` emits the feature with
7011/// explicit zero deltas (wire differs from the no-feature encode; the
7012/// resolved levels do not).
7013///
7014/// Returns the wire bytes plus the matching post-§15 reconstruction.
7015pub fn encode_keyframe_adaptive_quant_with_segment_lf_deltas(
7016    frame: &I420Frame,
7017    config: &AdaptiveQuantConfig,
7018    segment_lf_deltas: &[i8; 4],
7019) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
7020    encode_keyframe_adaptive_quant_inner_lf(
7021        frame,
7022        config,
7023        TrellisStrength::DEFAULT,
7024        Some(segment_lf_deltas),
7025    )
7026}
7027
7028/// As [`encode_keyframe_adaptive_quant_with_segment_lf_deltas`] with
7029/// the §13 trellis aggressiveness dialed by `trellis`.
7030pub fn encode_keyframe_adaptive_quant_with_segment_lf_deltas_and_trellis(
7031    frame: &I420Frame,
7032    config: &AdaptiveQuantConfig,
7033    segment_lf_deltas: &[i8; 4],
7034    trellis: TrellisStrength,
7035) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
7036    encode_keyframe_adaptive_quant_inner_lf(frame, config, trellis, Some(segment_lf_deltas))
7037}
7038
7039fn encode_keyframe_adaptive_quant_inner(
7040    frame: &I420Frame,
7041    config: &AdaptiveQuantConfig,
7042    trellis: TrellisStrength,
7043) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
7044    encode_keyframe_adaptive_quant_inner_lf(frame, config, trellis, None)
7045}
7046
7047/// [`encode_keyframe_adaptive_quant_inner`] extended with the round-387
7048/// §10 per-segment **loop-filter feature**: when `segment_lf_deltas =
7049/// Some(d)`, the §9.3 `update_segmentation()` block additionally
7050/// carries the four `loop_filter_update` values (delta mode, added to
7051/// the frame base and clamped to `0..=63` per §20.6), and the
7052/// encoder's own §15 post-walk filter pass resolves each MB's level
7053/// through the same segment override the decoder applies
7054/// ([`crate::loop_filter::calculate_mb_filter_level`]) — so the
7055/// per-segment quantiser gradient can pair with a matching per-segment
7056/// deblock gradient (coarser segments → stronger filtering).
7057///
7058/// The §15 whole-frame skip mirrors the decoder's gate exactly: a frame
7059/// base `loop_filter_level == 0` skips the filter regardless of the
7060/// segment deltas (they still travel in the header for state
7061/// completeness). `None` reproduces the historical wire byte-for-byte.
7062fn encode_keyframe_adaptive_quant_inner_lf(
7063    frame: &I420Frame,
7064    config: &AdaptiveQuantConfig,
7065    trellis: TrellisStrength,
7066    segment_lf_deltas: Option<&[i8; 4]>,
7067) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
7068    let width = frame.width;
7069    let height = frame.height;
7070    if width == 0 || width > 0x3FFF || height == 0 || height > 0x3FFF {
7071        return Err(EncodeError::InvalidDimensions { width, height });
7072    }
7073    if config.base_y_ac_qi > 127 {
7074        return Err(EncodeError::QuantIndexOutOfRange {
7075            value: config.base_y_ac_qi,
7076        });
7077    }
7078    if config.loop_filter_level > 63 {
7079        return Err(EncodeError::LoopFilterLevelOutOfRange {
7080            value: config.loop_filter_level,
7081        });
7082    }
7083    if config.sharpness_level > 7 {
7084        return Err(EncodeError::SharpnessLevelOutOfRange {
7085            value: config.sharpness_level,
7086        });
7087    }
7088    // §9.3: the loop-filter feature value is a signed 6-bit magnitude —
7089    // reject anything outside ±63 before the walk runs.
7090    if let Some(d) = segment_lf_deltas
7091        && let Some(&bad) = d.iter().find(|v| v.unsigned_abs() > 63)
7092    {
7093        return Err(EncodeError::LoopFilterLevelOutOfRange {
7094            value: bad.unsigned_abs(),
7095        });
7096    }
7097
7098    let mb_cols = width.div_ceil(16) as usize;
7099    let mb_rows = height.div_ceil(16) as usize;
7100
7101    let coeff_probs = crate::dct_tokens::DEFAULT_COEFF_PROBS;
7102    // Per-frame §13 trellis rate tables (see `TrellisRateTables`); the
7103    // tables depend only on `coeff_probs`, not on the per-segment
7104    // quantiser factors, so one build serves every segment.
7105    let trellis_rate_tables = Some(TrellisRateTables::for_probs(&coeff_probs));
7106
7107    // §10 per-segment effective qindex + the matching §14.1 dequant
7108    // factors. Delta mode: q_seg = clamp(base + delta, 0, 127). The
7109    // decoder rebuilds the identical factors from the §9.3 quantizer
7110    // deltas via `resolve_segment_dequant_factors`.
7111    let base = config.base_y_ac_qi as i32;
7112    let mut seg_qindex = [0u8; crate::loop_filter::MAX_MB_SEGMENTS];
7113    let mut seg_factors =
7114        [crate::dequant::MbDequantFactors::from_base_and_deltas(base, 0, 0, 0, 0, 0);
7115            crate::loop_filter::MAX_MB_SEGMENTS];
7116    for s in 0..crate::loop_filter::MAX_MB_SEGMENTS {
7117        let q = (base + config.quant_delta[s] as i32).clamp(0, 127) as u8;
7118        seg_qindex[s] = q;
7119        seg_factors[s] =
7120            crate::dequant::MbDequantFactors::from_base_and_deltas(q as i32, 0, 0, 0, 0, 0);
7121    }
7122
7123    let mut planes = crate::frame::KeyframePlanes {
7124        y: vec![0u8; mb_cols * 16 * mb_rows * 16],
7125        u: vec![0u8; mb_cols * 8 * mb_rows * 8],
7126        v: vec![0u8; mb_cols * 8 * mb_rows * 8],
7127        y_stride: mb_cols * 16,
7128        uv_stride: mb_cols * 8,
7129        mb_cols,
7130        mb_rows,
7131    };
7132
7133    let mut modes: Vec<MacroblockModes> = Vec::with_capacity(mb_rows * mb_cols);
7134    let mut all_coeffs: Vec<MbCoeffs> = Vec::with_capacity(mb_rows * mb_cols);
7135
7136    for mb_row in 0..mb_rows {
7137        for mb_col in 0..mb_cols {
7138            let pixels = frame.extract_mb(mb_row, mb_col);
7139            let neighbors = crate::frame::gather_neighbors_public(&planes, mb_row, mb_col);
7140
7141            // §10 classify by luma activity, then quantise at the
7142            // segment's qindex.
7143            let variance = mb_luma_variance(&pixels.y);
7144            let seg = classify_segment(variance, &config.variance_boundaries);
7145            let q = seg_qindex[seg as usize];
7146
7147            let encoded = encode_mb_block_set_with_neighbors_strength_rates(
7148                &pixels,
7149                &neighbors,
7150                q,
7151                &coeff_probs,
7152                trellis_rate_tables.as_ref(),
7153                trellis,
7154            )
7155            .map_err(EncodeError::Token)?;
7156
7157            let mb_skip_coeff = encoded.nonzero_block_count == 0;
7158
7159            // Dequantise with the SAME segment factors used to quantise,
7160            // so the encoder's reconstruction matches the decoder's.
7161            let mut dq = encoded.coeffs;
7162            seg_factors[seg as usize].dequantize(&mut dq);
7163            let use_bpred = encoded.y_mode == IntraYMode::B;
7164            let recon = if use_bpred {
7165                crate::reconstruct::decode_keyframe_mb_bpred(
7166                    encoded.b_subblock_modes.as_ref(),
7167                    encoded.uv_mode,
7168                    mb_skip_coeff,
7169                    &neighbors,
7170                    &dq.y,
7171                    &dq.u,
7172                    &dq.v,
7173                )
7174            } else {
7175                crate::reconstruct::decode_keyframe_mb_non_bpred(
7176                    encoded.y_mode,
7177                    encoded.uv_mode,
7178                    mb_skip_coeff,
7179                    &neighbors,
7180                    &dq.y2,
7181                    &dq.y,
7182                    &dq.u,
7183                    &dq.v,
7184                )
7185            }
7186            .map_err(EncodeError::Reconstruct)?;
7187            crate::frame::write_mb_public(&mut planes, mb_row, mb_col, &recon);
7188
7189            modes.push(MacroblockModes {
7190                segment_id: Some(seg),
7191                mb_skip_coeff,
7192                y_mode: encoded.y_mode,
7193                subblock_modes: encoded.b_subblock_modes,
7194                uv_mode: encoded.uv_mode,
7195            });
7196            all_coeffs.push(encoded.coeffs);
7197        }
7198    }
7199
7200    // ---- §15 loop-filter post-pass ---------------------------------------
7201    // Gate mirrors the decoder exactly: frame base level 0 skips the
7202    // whole-frame filter even when segment deltas are present.
7203    if config.loop_filter_level != 0 {
7204        let mut segment_lf_level = [0i16; crate::loop_filter::MAX_MB_SEGMENTS];
7205        if let Some(d) = segment_lf_deltas {
7206            for (dst, &src) in segment_lf_level.iter_mut().zip(d.iter()) {
7207                *dst = i16::from(src);
7208            }
7209        }
7210        let lf_config = crate::loop_filter::FrameFilterConfig {
7211            simple: config.filter_type,
7212            key_frame: true,
7213            loop_filter_level: config.loop_filter_level,
7214            sharpness_level: config.sharpness_level,
7215            // With `segment_lf_deltas = Some`, each MB's §15 level is
7216            // `clamp(base + delta[seg], 0, 63)` per §20.6 — the same
7217            // resolution the decoder's `FrameFilterConfig::keyframe`
7218            // performs from the §9.3 header we emit below. `None` keeps
7219            // the frame base for every segment (historical wire).
7220            segmentation_enabled: segment_lf_deltas.is_some(),
7221            segment_abs: false,
7222            segment_lf_level,
7223            delta_enabled: false,
7224            ref_delta_current: 0,
7225            bpred_mode_delta: 0,
7226            ref_delta_last: 0,
7227            ref_delta_golden: 0,
7228            ref_delta_altref: 0,
7229            zero_mv_mode_delta: 0,
7230            other_mv_mode_delta: 0,
7231            split_mv_mode_delta: 0,
7232        };
7233        crate::loop_filter::filter_frame(&mut planes, &modes, &all_coeffs, &lf_config);
7234    }
7235
7236    // ---- §19.2 first (control) partition --------------------------------
7237    let mut hdr = BoolEncoder::new();
7238
7239    // §9.2 — color_space + clamping_type both 0.
7240    hdr.write_bool(128, false);
7241    hdr.write_bool(128, false);
7242
7243    // §9.3 — segmentation ON: delta-mode per-segment quantizer features +
7244    // the map update with explicit tree probabilities. We emit a fixed,
7245    // mid-range `mb_segment_tree_probs` (170 ≈ "leans toward 0") for all
7246    // three nodes; the per-MB `segment_id` codes below use the same probs.
7247    const SEG_TREE_PROB: u8 = 170;
7248    let seg_probs: [u8; 3] = [SEG_TREE_PROB; 3];
7249    let layer = UpdateSegmentationLayer {
7250        update_mb_segmentation_map: true,
7251        feature_mode_absolute: false,
7252        // Each segment carries its quant delta. A 0 delta is still emitted
7253        // (Some(0)) so the decoder's segment base for that slot is exactly
7254        // `base + 0`, matching `seg_qindex` above.
7255        quantizer: [
7256            Some(config.quant_delta[0] as i16),
7257            Some(config.quant_delta[1] as i16),
7258            Some(config.quant_delta[2] as i16),
7259            Some(config.quant_delta[3] as i16),
7260        ],
7261        // §10 per-segment loop-filter feature (round 387): each segment
7262        // carries its delta when the caller supplied one (a 0 delta is
7263        // still emitted as Some(0), mirroring the quantizer convention
7264        // above so the decoder's persisted value is explicit).
7265        loop_filter: match segment_lf_deltas {
7266            Some(d) => [
7267                Some(i16::from(d[0])),
7268                Some(i16::from(d[1])),
7269                Some(i16::from(d[2])),
7270                Some(i16::from(d[3])),
7271            ],
7272            None => [None; 4],
7273        },
7274        segment_prob: [Some(seg_probs[0]), Some(seg_probs[1]), Some(seg_probs[2])],
7275    };
7276    write_update_segmentation(&mut hdr, &layer);
7277
7278    // §9.4 — loop filter; mode_ref_lf_delta disabled.
7279    write_loop_filter(
7280        &mut hdr,
7281        config.filter_type,
7282        config.loop_filter_level,
7283        config.sharpness_level,
7284        false,
7285    )?;
7286    // §9.5 — single DCT partition.
7287    write_token_partition_count(&mut hdr, 1)?;
7288    // §9.6 — quant indices: the §9.6 baseline. The per-segment override
7289    // rides on top of this base via the §9.3 quantizer deltas above.
7290    write_quant_indices(&mut hdr, config.base_y_ac_qi, None, None, None, None, None)?;
7291    // §9.7 (key frame) — refresh_entropy_probs.
7292    hdr.write_bool(128, true);
7293    // §13 / §9.9 — no token-prob updates.
7294    write_no_token_prob_updates(&mut hdr, &COEFF_UPDATE_PROBS_FLAT);
7295    // §9.11 — mb_no_skip_coeff enabled, balanced prob.
7296    let prob_skip_false = 128u8;
7297    write_mb_no_skip_coeff(&mut hdr, true, prob_skip_false);
7298
7299    // §11 mode layer WITH the §10 per-MB segment_id prefix.
7300    write_mode_layer_segmented(
7301        &mut hdr,
7302        &modes,
7303        mb_rows,
7304        mb_cols,
7305        prob_skip_false,
7306        Some(&seg_probs),
7307    );
7308
7309    let first_partition = hdr.finish();
7310    let first_partition_size = first_partition.len();
7311    if first_partition_size > 0x7_FFFF {
7312        return Err(EncodeError::FirstPartitionTooLarge {
7313            bytes: first_partition_size,
7314        });
7315    }
7316
7317    // ---- §19.2 DCT partition: per-MB §13.3 token data (single part) ------
7318    let mut tok = BoolEncoder::new();
7319    let mut above_ctx: Vec<MbEntropyCtx> = vec![MbEntropyCtx::default(); mb_cols];
7320    for mb_row in 0..mb_rows {
7321        let mut left_ctx = MbEntropyCtx::default();
7322        for (mb_col, above_col) in above_ctx.iter_mut().enumerate() {
7323            let raster = mb_row * mb_cols + mb_col;
7324            let mb = &modes[raster];
7325            let use_bpred = mb.y_mode == IntraYMode::B;
7326            if mb.mb_skip_coeff {
7327                clear_skip_ctx(use_bpred, above_col, &mut left_ctx);
7328                continue;
7329            }
7330            encode_mb_tokens(
7331                &mut tok,
7332                &all_coeffs[raster],
7333                use_bpred,
7334                &coeff_probs,
7335                above_col,
7336                &mut left_ctx,
7337            )
7338            .map_err(EncodeError::Token)?;
7339        }
7340    }
7341    let dct_partition = tok.finish();
7342
7343    // ---- §9.1 frame tag + assembly --------------------------------------
7344    let mut out: Vec<u8> = Vec::with_capacity(10 + first_partition_size + dct_partition.len());
7345    write_frame_tag(
7346        &mut out,
7347        true,
7348        0,
7349        true,
7350        first_partition_size as u32,
7351        width,
7352        height,
7353        ScaleCode::None,
7354        ScaleCode::None,
7355    )?;
7356    out.extend_from_slice(&first_partition);
7357    out.extend_from_slice(&dct_partition);
7358
7359    Ok((out, planes))
7360}
7361
7362/// Clear the §13.3 non-zero predictor slots a skip macroblock touches.
7363///
7364/// §13.1: a skipped macroblock writes no token data, so all of its
7365/// residual blocks are implicitly all-zero. The decoder's
7366/// `decode_mb_coeffs` clears every above / left predictor slot the
7367/// macroblock owns; the encoder mirrors that so a non-skip neighbour to
7368/// the right / below sees `has_coeffs = false`.
7369fn clear_skip_ctx(use_bpred: bool, above: &mut MbEntropyCtx, left: &mut MbEntropyCtx) {
7370    // The Y / U / V slots (0..=7) are always cleared. The Y2 slot (8)
7371    // is cleared only when the macroblock carries a Y2 block (every
7372    // non-B_PRED MB) — a B_PRED MB leaves the inherited Y2 context
7373    // untouched, matching the decoder's `decode_mb_coeffs` skip path.
7374    for slot in 0..8 {
7375        above.nonzero[slot] = false;
7376        left.nonzero[slot] = false;
7377    }
7378    if !use_bpred {
7379        above.nonzero[8] = false;
7380        left.nonzero[8] = false;
7381    }
7382}
7383
7384/// Write the §11 key-frame macroblock-mode layer for the whole frame
7385/// into the first-partition encoder `hdr`.
7386///
7387/// Per macroblock (raster order) this writes, in §11 order:
7388///   1. `mb_skip_coeff` (§11.1) against `prob_skip_false`;
7389///   2. the 16×16 luma mode via `kf_ymode_tree` (§11.2);
7390///   3. for a `B_PRED` macroblock, sixteen 4×4 sub-block modes via
7391///      `bmode_tree` (§11.3 / §11.5), each against the context-driven
7392///      `KF_BMODE_PROB[above][left]` row;
7393///   4. the 8×8 chroma mode via `uv_mode_tree` (§11.4).
7394///
7395/// The §11.3 `above_subblock` / `left_subblock` context buffers evolve
7396/// macroblock-to-macroblock exactly as `parse_key_frame_macroblock_modes`
7397/// reads them, so the decoder recovers the modes bit-for-bit.
7398fn write_mode_layer(
7399    hdr: &mut BoolEncoder,
7400    modes: &[MacroblockModes],
7401    mb_rows: usize,
7402    mb_cols: usize,
7403    prob_skip_false: u8,
7404) {
7405    write_mode_layer_segmented(hdr, modes, mb_rows, mb_cols, prob_skip_false, None);
7406}
7407
7408/// As [`write_mode_layer`], but with the optional §10 per-MB `segment_id`
7409/// prefix. When `segment_probs` is `Some(probs)` — meaning the frame set
7410/// `segmentation_enabled && update_mb_segmentation_map` — each macroblock
7411/// emits its `segment_id` (via the §10 `mb_segment_tree` against the
7412/// effective `probs`, defaults-of-255 already folded in) *before* the
7413/// §11.1 `mb_skip_coeff` bit, matching the decoder's read order in
7414/// [`crate::macroblock`] `parse_key_frame_macroblock_modes`. When `None`
7415/// the layer is identical to the non-segmented wire.
7416fn write_mode_layer_segmented(
7417    hdr: &mut BoolEncoder,
7418    modes: &[MacroblockModes],
7419    mb_rows: usize,
7420    mb_cols: usize,
7421    prob_skip_false: u8,
7422    segment_probs: Option<&[u8; 3]>,
7423) {
7424    // §11.3 item 3: the "above" sub-block context spans the whole frame
7425    // width (4 sub-blocks per MB column), initialised to B_DC_PRED.
7426    let mut above_subblock = vec![IntraBmode::Dc; mb_cols * 4];
7427    let bmode_paths: &[TreedLeafPath] = &*BMODE_PATHS;
7428
7429    for mb_row in 0..mb_rows {
7430        // §11.3 item 3: the four left predictors reset to B_DC_PRED at
7431        // the start of every macroblock row.
7432        let mut left_subblock = [IntraBmode::Dc; 4];
7433
7434        for mb_col in 0..mb_cols {
7435            let mb = &modes[mb_row * mb_cols + mb_col];
7436
7437            // 0. segment_id (§10), only when the frame updates the
7438            //    segmentation map. Coded before mb_skip_coeff via the
7439            //    §10 mb_segment_tree.
7440            if let Some(probs) = segment_probs {
7441                let sid = mb.segment_id.unwrap_or(0);
7442                hdr.write_treed(&crate::macroblock::MB_SEGMENT_TREE, |i| probs[i], sid);
7443            }
7444
7445            // 1. mb_skip_coeff (§11.1) — mb_no_skip_coeff is enabled.
7446            hdr.write_bool(prob_skip_false, mb.mb_skip_coeff);
7447
7448            // 2. Luma mode (§11.2).
7449            hdr.write_treed_cached(&*KF_YMODE_PATHS, |i| KF_YMODE_PROB[i], mb.y_mode.leaf());
7450
7451            // 3. Sub-block modes (§11.3 / §11.5) for B_PRED only.
7452            if let Some(sub) = &mb.subblock_modes {
7453                for j in 0..16 {
7454                    let row = j >> 2;
7455                    let col = j & 3;
7456                    let above = if row == 0 {
7457                        above_subblock[mb_col * 4 + col]
7458                    } else {
7459                        sub[(row - 1) * 4 + col]
7460                    };
7461                    let left = if col == 0 {
7462                        left_subblock[row]
7463                    } else {
7464                        sub[row * 4 + (col - 1)]
7465                    };
7466                    let prob_row = &KF_BMODE_PROB[above.idx()][left.idx()];
7467                    hdr.write_treed_cached(bmode_paths, |i| prob_row[i], sub[j].idx() as u8);
7468                }
7469            }
7470
7471            // 4. Chroma mode (§11.4).
7472            hdr.write_treed_cached(&*UV_MODE_PATHS, |i| KF_UV_MODE_PROB[i], mb.uv_mode.leaf());
7473
7474            // §11.3 item 3 / 4: update the cross-macroblock context.
7475            match &mb.subblock_modes {
7476                Some(sub) => {
7477                    above_subblock[mb_col * 4..mb_col * 4 + 4].copy_from_slice(&sub[12..16]);
7478                    for (row, slot) in left_subblock.iter_mut().enumerate() {
7479                        *slot = sub[row * 4 + 3];
7480                    }
7481                }
7482                None => {
7483                    let projected = mb.y_mode.project_to_subblock_context();
7484                    for slot in &mut above_subblock[mb_col * 4..mb_col * 4 + 4] {
7485                        *slot = projected;
7486                    }
7487                    left_subblock.fill(projected);
7488                }
7489            }
7490        }
7491    }
7492}
7493
7494// ─── P-frame encoder (ZEROMV / NEARESTMV / NEARMV / NEWMV / SPLITMV / LAST) ──
7495//
7496// RFC 6386 §9 / §16 / §17 / §18 inter-frame encoder. Every emitted
7497// macroblock is inter against the LAST reference (§16.2
7498// `prob_last`-selected); the per-MB inter mode is picked between the
7499// five §16.2 `mv_ref_tree` leaves via a non-normative §-not-specified
7500// rate-distortion trade:
7501//
7502//   J(zero)    = SAD_at_(0,0)
7503//                + lambda * mv_ref_tree("0")     bits
7504//   J(nearest) = SAD_at_clamp(near.mvs[1])
7505//                + lambda * mv_ref_tree("10")    bits
7506//   J(near)    = SAD_at_clamp(near.mvs[2])
7507//                + lambda * mv_ref_tree("110")   bits
7508//   J(new)     = SAD_at_searched_mv
7509//                + lambda * (mv_ref_tree("1110") bits + §17 mv bits)
7510//   J(split)   = min over the four §16.4 partitions of
7511//                  (sum_groups group_SAD
7512//                   + lambda * (mv_ref_tree("1111") + mvpartition_tree(p)
7513//                               + sum_groups sub_mv_ref_tree + NEW4X4 bits))
7514//
7515// Lower J wins. The whole-MB §17 motion search is the whole-pixel
7516// `small_diamond_search_luma` primitive followed by a §18.3
7517// `half_pixel_refine_luma` probe of the 8 half-pixel offsets around
7518// the whole-pixel result, and then a §18.3 `quarter_pixel_refine_luma`
7519// probe of the 8 quarter-pixel offsets around the half-pixel result
7520// — all clamped to `[-1023, +1023]` per §17.1. When the chosen MV is
7521// sub-pixel-aligned the §18 prediction runs the §18.3 six-tap
7522// synthesis (`version == 0` bicubic tap-set, indexed by
7523// `(stored_luma_mv(mv) & 7)`); at a whole-pixel MV it collapses to the
7524// §18.2 / §18.3 copy path. The §16.3 NEARESTMV / NEARMV candidates are
7525// the §16.3 census `near.mvs[1]` / `near.mvs[2]` slots clamped through
7526// the per-MB `MvClampRect`, scored at the clamped MV the decoder will
7527// reconstruct from (so the SAD-evaluator is the §18.3 sixtap-aware
7528// `mb_luma_sad_at_mv`).
7529//
7530// The §16.4 SPLITMV picker evaluates each of the four partition shapes
7531// (TopBottom / LeftRight / Quarters / Mv16); for each partition group
7532// it runs a whole-pixel sub-block diamond search around the clamped
7533// `near.mvs[0]` "best" predictor (no §18.1 secondary clamp per §18.1
7534// page 114) and prices the four §16.4 `sub_mv_ref` modes (LEFT4X4 /
7535// ABOVE4X4 / ZERO4X4 / NEW4X4) at the group anchor's left / above
7536// neighbour vectors. The lowest-J group SAD + sub_mv_ref bits wins;
7537// the partition with the smallest summed J — added to the partition
7538// tree bits and the §16.2 SPLITMV path bits — is the SPLITMV
7539// candidate. When J(split) < J(other-four), SPLITMV emits.
7540//
7541// The §14 residual = source - prediction is quantised and §13.3-token-
7542// coded through the existing pipeline regardless of which mode was
7543// picked. SPLITMV has no Y2 block (§14.2 page 76); its luma sub-blocks
7544// code from coefficient 0 like B_PRED. Per §17 the §17.2
7545// `mv_prob_update()` block is still emitted with every `F` flag set
7546// to 0 — "no update", matching the no-token-prob-update pattern — so
7547// the decoder's MV-decode runs against the §17.2 defaults; the same
7548// `MvContexts` is used encoder-side to write the NEWMV / NEW4X4
7549// differentials.
7550
7551// ─── §16.4 SPLITMV picker helpers ───────────────────────────────────────────
7552//
7553// All four §16.4 partition shapes (`MvPartition::TopBottom`,
7554// `LeftRight`, `Quarters`, `Mv16`) are evaluated per MB. For each
7555// partition group we pick a vector by combining a whole-pixel diamond
7556// search (around the clamped `near.mvs[0]` "best" predictor) with a
7557// §16.4 `sub_mv_ref` mode choice (LEFT4X4 / ABOVE4X4 / ZERO4X4 /
7558// NEW4X4) priced by `sub_mv_ref_tree` + §17.2 NEW4X4 component bits.
7559// The SPLITMV picker is intentionally whole-pixel-only this round
7560// (matching the §16.4 `MAX_DIAMOND_ITERS` bound below) so its
7561// per-group search cost stays linear in partition count without an
7562// extra §18.3 sixtap pass per sub-block.
7563
7564/// One §16.4 SPLITMV picker result: the chosen partition, the sixteen
7565/// per-sub-block vectors, the per-group `sub_mv_ref` modes, the
7566/// per-group NEW4X4 differentials (zero when the mode is not NEW4X4),
7567/// and the total rate-distortion cost the partition scored at.
7568///
7569/// The picker walks `[TopBottom, LeftRight, Quarters, Mv16]` and keeps
7570/// whichever shape produces the smallest `j`; `j` then competes with
7571/// the whole-MB picker's `J(zero/nearest/near/new)`.
7572#[derive(Debug, Clone)]
7573struct SplitMvCandidate {
7574    /// The §16.4 partition shape this candidate scored under.
7575    partition: crate::near_mv::MvPartition,
7576    /// `this->split.mvs[16]` — the resolved per-sub-block quarter-pixel
7577    /// vectors, in raster order (matching `MV_PARTITIONS` layout).
7578    split_mvs: [crate::motion_vector::Mv; 16],
7579    /// The per-partition-group `sub_mv_ref` mode (indexed in partition-id
7580    /// order: group 0 first, then 1, …). Only the partition's group
7581    /// count (2 for TopBottom/LeftRight, 4 for Quarters, 16 for Mv16)
7582    /// leading entries are meaningful; the rest stay at the `Zero4x4`
7583    /// fill and are never read (the emitter iterates exactly the
7584    /// partition's groups). Fixed-size since round 277 — the previous
7585    /// per-candidate `Vec` pair was a measurable slice of the encoder's
7586    /// residual allocator churn.
7587    submv_modes: [crate::near_mv::SubMvRefMode; 16],
7588    /// The per-group NEW4X4 differential (zero `Mv` for groups whose
7589    /// `sub_mv_ref` mode is not NEW4X4). Same indexing as `submv_modes`.
7590    submv_new_diffs: [crate::motion_vector::Mv; 16],
7591    /// Total `J = sum_groups group_SAD + lambda * (mv_ref_tree("1111") +
7592    /// mvpartition_tree(p) + sum_groups sub_mv_ref_tree + NEW4X4 bits)`
7593    /// for this partition. Lower wins.
7594    j: f64,
7595}
7596
7597/// `MAX_DIAMOND_ITERS` for the SPLITMV per-group sub-block search.
7598/// Smaller than the whole-MB MAX_DIAMOND_ITERS = 8 (line ~3535) since
7599/// SPLITMV evaluates up to 16 groups per MB across 4 partition shapes
7600/// and the per-group region is small (≤ 8 sub-blocks).
7601const SPLIT_MV_MAX_DIAMOND_ITERS: u32 = 4;
7602
7603/// 4×4 luma block SAD — sum |src[i] - pred[i]|, i in 0..16. The
7604/// SPLITMV per-group score sums [`sub_block_sad_4x4`] across the group's
7605/// member sub-blocks.
7606#[inline]
7607fn sub_block_sad_4x4(src: &[u8; 16], pred: &[u8; 16]) -> u32 {
7608    let mut sad: u32 = 0;
7609    for i in 0..16 {
7610        sad += (src[i] as i32 - pred[i] as i32).unsigned_abs();
7611    }
7612    sad
7613}
7614
7615/// Extract one 4×4 source sub-block (raster sub-block index `b`, b in
7616/// 0..=15) from a 16×16 luma source MB.
7617#[inline]
7618fn extract_src_subblock_4x4(src: &[u8; 256], b: usize) -> [u8; 16] {
7619    let sb_row = b >> 2; // 0..=3
7620    let sb_col = b & 3; // 0..=3
7621    let mut out = [0u8; 16];
7622    for r in 0..4 {
7623        let dst_off = r * 4;
7624        let src_off = (sb_row * 4 + r) * 16 + sb_col * 4;
7625        out[dst_off..dst_off + 4].copy_from_slice(&src[src_off..src_off + 4]);
7626    }
7627    out
7628}
7629
7630/// Sum the 4×4 SADs across the partition group `[group_subblocks]` for
7631/// a whole-pixel candidate vector `mv`.
7632///
7633/// Every member of one §16.4 partition group shares the one candidate
7634/// vector, and a whole-pixel §18.3 prediction is "simply copied", so
7635/// each member's 4×4 prediction is a direct window into the reference
7636/// plane at integer offset `(mb_x0, mb_y0) + (eighth-pixel mv >> 3)`.
7637/// When the whole 16×16 MB-extent source region lands strictly inside
7638/// the plane (a conservative gate — every member sub-block lies inside
7639/// the MB extent; the dominant case mid-frame) the SAD is accumulated
7640/// **directly against the reference and source rows** — no
7641/// per-sub-block patch fetch and no source sub-block extraction copy
7642/// (the fused fetch-and-SAD shape of the round-279 BENCHMARKS
7643/// candidate, SPLITMV-group half). A border-straddling candidate falls
7644/// back to the per-member
7645/// [`crate::motion_comp::fetch_block_whole_pixel`] path (§20.14
7646/// `build_mc_border` edge replication), bit-identical to the
7647/// pre-round-281 listing for every candidate
7648/// (`group_sad_fused_fast_path_matches_per_subblock_fetch`). §18.1
7649/// page 114 says no secondary clamp applies to SPLITMV sub-block MVs.
7650fn group_sad_at_whole_mv(
7651    luma_ref: crate::motion_search::LumaRef<'_>,
7652    mb_col: usize,
7653    mb_row: usize,
7654    src_y: &[u8; 256],
7655    group_subblocks: &[usize],
7656    mv: crate::motion_vector::Mv,
7657) -> u32 {
7658    // §18.1 stored_luma_mv doubles the §17 quarter-pixel vector into
7659    // the §18 eighth-pixel resolution `fetch_block_whole_pixel` uses.
7660    let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
7661    let mb_x0 = mb_col * 16;
7662    let mb_y0 = mb_row * 16;
7663    let mut sad: u32 = 0;
7664
7665    // §18.2: integer pixel offset is the eighth-pixel vector shifted
7666    // right 3 with sign propagation.
7667    let src_x0 = mb_x0 as isize + (mv_eighth.col >> 3) as isize;
7668    let src_y0 = mb_y0 as isize + (mv_eighth.row >> 3) as isize;
7669    if src_x0 >= 0
7670        && src_y0 >= 0
7671        && src_x0 + 16 <= luma_ref.width as isize
7672        && src_y0 + 16 <= luma_ref.height as isize
7673    {
7674        // Fused fast path: the whole MB-extent source region is
7675        // strictly in-bounds, so each member's prediction row is the
7676        // contiguous 4-byte reference run at its sub-block offset — SAD
7677        // it against the matching `src_y` run without materialising
7678        // either side.
7679        let x0 = src_x0 as usize;
7680        let y0 = src_y0 as usize;
7681        for &b in group_subblocks {
7682            let sb_row = b >> 2;
7683            let sb_col = b & 3;
7684            for r in 0..4 {
7685                let pred_start = (y0 + sb_row * 4 + r) * luma_ref.stride + x0 + sb_col * 4;
7686                let pred_row = &luma_ref.plane[pred_start..pred_start + 4];
7687                let src_start = (sb_row * 4 + r) * 16 + sb_col * 4;
7688                let src_row = &src_y[src_start..src_start + 4];
7689                for c in 0..4 {
7690                    sad += (src_row[c] as i32 - pred_row[c] as i32).unsigned_abs();
7691                }
7692            }
7693        }
7694        return sad;
7695    }
7696
7697    // Border-straddling candidate: per-member §20.14 edge-replicating
7698    // fetch (rare — only candidates whose motion walks off the
7699    // picture).
7700    for &b in group_subblocks {
7701        let sb_row = b >> 2;
7702        let sb_col = b & 3;
7703        let blk_x = mb_x0 + sb_col * 4;
7704        let blk_y = mb_y0 + sb_row * 4;
7705        let patch = crate::motion_comp::fetch_block_whole_pixel(
7706            luma_ref.plane,
7707            luma_ref.stride,
7708            luma_ref.width,
7709            luma_ref.height,
7710            blk_x,
7711            blk_y,
7712            mv_eighth,
7713        );
7714        let src_sb = extract_src_subblock_4x4(src_y, b);
7715        sad += sub_block_sad_4x4(&src_sb, &patch);
7716    }
7717    sad
7718}
7719
7720/// Contiguous-row SAD over one in-bounds group rectangle, monomorphised
7721/// on the pixel row width `PXW` ∈ {4, 8, 16}. `x0` / `y0` are the
7722/// in-plane pixel origin of the MB-extent source region (already offset
7723/// by the candidate MV). The per-row array conversion gives the
7724/// compiler a constant-length reduction; `u32` addition of non-negative
7725/// per-pixel terms (bounded by 256·255) is exact and order-free, so the
7726/// row-merged sum equals the per-member-sub-block sum term for term.
7727#[inline]
7728fn group_rect_rows_sad<const PXW: usize>(
7729    plane: &[u8],
7730    stride: usize,
7731    x0: usize,
7732    y0: usize,
7733    src_y: &[u8; 256],
7734    shape: GroupShape,
7735) -> u32 {
7736    let mut sad = 0u32;
7737    for r in shape.row0..shape.row0 + shape.h_px {
7738        let pred_start = (y0 + r) * stride + x0 + shape.col0;
7739        let pred: &[u8; PXW] = plane[pred_start..pred_start + PXW]
7740            .try_into()
7741            .expect("row width");
7742        let src: &[u8; PXW] = src_y[r * 16 + shape.col0..r * 16 + shape.col0 + PXW]
7743            .try_into()
7744            .expect("row width");
7745        for i in 0..PXW {
7746            sad += src[i].abs_diff(pred[i]) as u32;
7747        }
7748    }
7749    sad
7750}
7751
7752/// [`group_sad_at_whole_mv`] with the group's precomputed §20.13
7753/// rectangle ([`PartitionGroups::shape`]): the in-bounds fast path SADs
7754/// the rectangle's contiguous pixel rows (4·`w_sb` bytes each) instead
7755/// of one 4-byte run per member sub-block row, dispatched once per call
7756/// onto a constant-width kernel. Row-merging reorders an exact
7757/// (non-overflowing, non-negative) `u32` sum only, so the result is
7758/// bit-for-bit the per-member value — pinned against the per-subblock
7759/// fetch reference for every partition shape, group, and border/interior
7760/// candidate by `group_sad_shaped_matches_per_subblock_fetch`.
7761///
7762/// `shape` MUST be the exact rectangle decomposition of
7763/// `group_subblocks` (every [`PartitionGroups`] group is one — see
7764/// `partition_group_shapes_are_exact_rectangles`); the member list is
7765/// still consumed by the border-straddling fallback, which is the
7766/// unchanged per-member §20.14 edge-replicating path.
7767#[allow(clippy::too_many_arguments)] // mirrors group_sad_at_whole_mv + shape.
7768fn group_sad_at_whole_mv_shaped(
7769    luma_ref: crate::motion_search::LumaRef<'_>,
7770    mb_col: usize,
7771    mb_row: usize,
7772    src_y: &[u8; 256],
7773    group_subblocks: &[usize],
7774    shape: GroupShape,
7775    mv: crate::motion_vector::Mv,
7776) -> u32 {
7777    let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
7778    let mb_x0 = mb_col * 16;
7779    let mb_y0 = mb_row * 16;
7780    let src_x0 = mb_x0 as isize + (mv_eighth.col >> 3) as isize;
7781    let src_y0 = mb_y0 as isize + (mv_eighth.row >> 3) as isize;
7782    if src_x0 >= 0
7783        && src_y0 >= 0
7784        && src_x0 + 16 <= luma_ref.width as isize
7785        && src_y0 + 16 <= luma_ref.height as isize
7786    {
7787        let x0 = src_x0 as usize;
7788        let y0 = src_y0 as usize;
7789        return match shape.w_px {
7790            16 => group_rect_rows_sad::<16>(luma_ref.plane, luma_ref.stride, x0, y0, src_y, shape),
7791            8 => group_rect_rows_sad::<8>(luma_ref.plane, luma_ref.stride, x0, y0, src_y, shape),
7792            _ => group_rect_rows_sad::<4>(luma_ref.plane, luma_ref.stride, x0, y0, src_y, shape),
7793        };
7794    }
7795    // Border-straddling candidate: identical per-member fallback.
7796    group_sad_at_whole_mv(luma_ref, mb_col, mb_row, src_y, group_subblocks, mv)
7797}
7798
7799/// Small whole-pixel diamond search for ONE SPLITMV partition group —
7800/// per-sub-block analogue of [`crate::motion_search::small_diamond_search_luma`].
7801///
7802/// Sums [`group_sad_at_whole_mv`] over the group's member sub-blocks
7803/// for each candidate MV and follows a 4-neighbour diamond descent
7804/// from `center` (which should be the clamped `near.mvs[0]` "best"
7805/// predictor, the same base the decoder's NEW4X4 differential adds
7806/// to). Returns the best (mv, sad) pair found.
7807///
7808/// Each step clamps candidates to §17.1's `[MV_MIN, MV_MAX]`; SPLITMV
7809/// sub-block MVs themselves are not §18.1-secondary-clamped per §18.1
7810/// page 114.
7811#[allow(clippy::too_many_arguments)] // mirrors the search entry + shape.
7812fn group_small_diamond_search(
7813    luma_ref: crate::motion_search::LumaRef<'_>,
7814    mb_col: usize,
7815    mb_row: usize,
7816    src_y: &[u8; 256],
7817    group_subblocks: &[usize],
7818    shape: GroupShape,
7819    center: crate::motion_vector::Mv,
7820    max_iters: u32,
7821) -> (crate::motion_vector::Mv, u32) {
7822    use crate::motion_search::{MV_MAX, MV_MIN, WHOLE_PIXEL_STEP};
7823    // Snap to whole-pixel grid then clamp into §17.1 range.
7824    let snap = |v: i16| -> i16 {
7825        let q = (v / WHOLE_PIXEL_STEP) * WHOLE_PIXEL_STEP;
7826        q.clamp(MV_MIN, MV_MAX)
7827    };
7828    let mut best_mv = crate::motion_vector::Mv {
7829        row: snap(center.row),
7830        col: snap(center.col),
7831    };
7832    let mut best_sad = group_sad_at_whole_mv_shaped(
7833        luma_ref,
7834        mb_col,
7835        mb_row,
7836        src_y,
7837        group_subblocks,
7838        shape,
7839        best_mv,
7840    );
7841    let offsets: [(i16, i16); 4] = [
7842        (-WHOLE_PIXEL_STEP, 0),
7843        (WHOLE_PIXEL_STEP, 0),
7844        (0, -WHOLE_PIXEL_STEP),
7845        (0, WHOLE_PIXEL_STEP),
7846    ];
7847    for _ in 0..max_iters {
7848        let mut improved = false;
7849        for (dr, dc) in offsets {
7850            let cand_row = (best_mv.row as i32 + dr as i32).clamp(MV_MIN as i32, MV_MAX as i32);
7851            let cand_col = (best_mv.col as i32 + dc as i32).clamp(MV_MIN as i32, MV_MAX as i32);
7852            let cand_mv = crate::motion_vector::Mv {
7853                row: cand_row as i16,
7854                col: cand_col as i16,
7855            };
7856            if cand_mv == best_mv {
7857                continue;
7858            }
7859            let cand_sad = group_sad_at_whole_mv_shaped(
7860                luma_ref,
7861                mb_col,
7862                mb_row,
7863                src_y,
7864                group_subblocks,
7865                shape,
7866                cand_mv,
7867            );
7868            if cand_sad < best_sad {
7869                best_sad = cand_sad;
7870                best_mv = cand_mv;
7871                improved = true;
7872            }
7873        }
7874        if !improved {
7875            break;
7876        }
7877    }
7878    (best_mv, best_sad)
7879}
7880
7881/// The §16.4 sub-block index ordering — `MV_PARTITIONS` is indexed by
7882/// sub-block raster id and stores group ids, but the partition decode
7883/// emits groups in `partition_id` order with the anchor as the first
7884/// sub-block carrying that group id. [`PartitionGroups`] precomputes
7885/// `groups[g] = [list of sub-block indices belonging to group g]` for
7886/// each of the four partitions — at compile time, since the §20.13
7887/// `MV_PARTITIONS` table is a constant. Round 277 replaced the previous
7888/// per-call `Vec<Vec<usize>>` builder with this table: the SPLITMV
7889/// scorer runs once per (MB, partition shape) and the nested-`Vec`
7890/// build dominated the encoder's residual allocator churn.
7891struct PartitionGroups {
7892    /// `members[g][..len[g]]` — the raster sub-block indices of group
7893    /// `g`, ascending (so `members[g][0]` is the §16.4 group anchor,
7894    /// "the first sub-block whose partition entry is `g`").
7895    members: [[usize; 16]; 16],
7896    /// Per-group member count.
7897    len: [usize; 16],
7898    /// Per-group pixel-space rectangle. Every §20.13 partition group is
7899    /// a rectangle of sub-blocks (16×8 / 8×16 / 8×8 / 4×4 pixels), so
7900    /// its member sub-blocks tile the bounding box exactly — pinned for
7901    /// all four tables by `partition_group_shapes_are_exact_rectangles`.
7902    shapes: [GroupShape; 16],
7903    /// Number of groups in this partition (2 / 2 / 4 / 16).
7904    num_groups: usize,
7905}
7906
7907/// Pixel-space rectangle of one §20.13 partition group inside its
7908/// 16×16 MB: top-left pixel `(row0, col0)`, extent `w_px × h_px`
7909/// (multiples of 4).
7910#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7911struct GroupShape {
7912    /// Top pixel row of the group inside the MB (0, 4, 8 or 12).
7913    row0: usize,
7914    /// Left pixel column of the group inside the MB (0, 4, 8 or 12).
7915    col0: usize,
7916    /// Pixel width (4, 8 or 16).
7917    w_px: usize,
7918    /// Pixel height (4, 8 or 16).
7919    h_px: usize,
7920}
7921
7922impl PartitionGroups {
7923    /// Decompose row `pid` of [`crate::near_mv::MV_PARTITIONS`]
7924    /// (`pid` = the §16.4 `partition_id`) into its member groups.
7925    const fn build(pid: usize) -> Self {
7926        let table = &crate::near_mv::MV_PARTITIONS[pid];
7927        let mut members = [[0usize; 16]; 16];
7928        let mut len = [0usize; 16];
7929        let mut num_groups = 0usize;
7930        let mut idx = 0usize;
7931        while idx < 16 {
7932            let g = table[idx] as usize;
7933            members[g][len[g]] = idx;
7934            len[g] += 1;
7935            if g + 1 > num_groups {
7936                num_groups = g + 1;
7937            }
7938            idx += 1;
7939        }
7940        // Per-group pixel bounding box. The §20.13 groups are exact
7941        // rectangles (their members tile the box), asserted for all
7942        // four tables by `partition_group_shapes_are_exact_rectangles`.
7943        let mut shapes = [GroupShape {
7944            row0: 0,
7945            col0: 0,
7946            w_px: 0,
7947            h_px: 0,
7948        }; 16];
7949        let mut g = 0usize;
7950        while g < num_groups {
7951            let (mut min_r, mut max_r, mut min_c, mut max_c) = (3usize, 0usize, 3usize, 0usize);
7952            let mut m = 0usize;
7953            while m < len[g] {
7954                let b = members[g][m];
7955                let (sb_r, sb_c) = (b >> 2, b & 3);
7956                if sb_r < min_r {
7957                    min_r = sb_r;
7958                }
7959                if sb_r > max_r {
7960                    max_r = sb_r;
7961                }
7962                if sb_c < min_c {
7963                    min_c = sb_c;
7964                }
7965                if sb_c > max_c {
7966                    max_c = sb_c;
7967                }
7968                m += 1;
7969            }
7970            shapes[g] = GroupShape {
7971                row0: min_r * 4,
7972                col0: min_c * 4,
7973                w_px: (max_c + 1 - min_c) * 4,
7974                h_px: (max_r + 1 - min_r) * 4,
7975            };
7976            g += 1;
7977        }
7978        PartitionGroups {
7979            members,
7980            len,
7981            shapes,
7982            num_groups,
7983        }
7984    }
7985
7986    /// The member sub-block indices of group `g` (`g < num_groups`).
7987    #[inline]
7988    fn group(&self, g: usize) -> &[usize] {
7989        &self.members[g][..self.len[g]]
7990    }
7991
7992    /// The pixel-space rectangle of group `g` (`g < num_groups`).
7993    #[inline]
7994    fn shape(&self, g: usize) -> GroupShape {
7995        self.shapes[g]
7996    }
7997
7998    /// Iterate the groups in partition-id order.
7999    #[inline]
8000    fn iter(&self) -> impl Iterator<Item = &[usize]> + '_ {
8001        (0..self.num_groups).map(move |g| self.group(g))
8002    }
8003}
8004
8005/// The four [`PartitionGroups`] decompositions, indexed by
8006/// `crate::near_mv::partition_id` order (TopBottom / LeftRight /
8007/// Quarters / Mv16) — built at compile time from the §20.13 table.
8008static PARTITION_GROUP_TABLE: [PartitionGroups; 4] = [
8009    PartitionGroups::build(0),
8010    PartitionGroups::build(1),
8011    PartitionGroups::build(2),
8012    PartitionGroups::build(3),
8013];
8014
8015/// Look up the precomputed group decomposition for partition `p`.
8016#[inline]
8017fn partition_groups(p: crate::near_mv::MvPartition) -> &'static PartitionGroups {
8018    &PARTITION_GROUP_TABLE[crate::near_mv::partition_id(p)]
8019}
8020
8021/// Per-group `sub_mv_ref` mode cost in fractional bits — the
8022/// `sub_mv_ref_tree` path bits at `SUBMV_REF_PROBS[ctx]`.
8023///
8024/// Tree paths per §16.4 / §20.13:
8025///   LEFT4X4  = "0"   → bool_bits(probs[0], false)
8026///   ABOVE4X4 = "10"  → bool_bits(probs[0], true) + bool_bits(probs[1], false)
8027///   ZERO4X4  = "110" → bool_bits(probs[0..=1], true) + bool_bits(probs[2], false)
8028///   NEW4X4   = "111" → bool_bits(probs[0..=2], true)
8029fn submv_ref_bits(probs: &[u8; 3], mode: crate::near_mv::SubMvRefMode) -> f64 {
8030    use crate::near_mv::SubMvRefMode as M;
8031    match mode {
8032        M::Left4x4 => bool_bits(probs[0], false),
8033        M::Above4x4 => bool_bits(probs[0], true) + bool_bits(probs[1], false),
8034        M::Zero4x4 => {
8035            bool_bits(probs[0], true) + bool_bits(probs[1], true) + bool_bits(probs[2], false)
8036        }
8037        M::New4x4 => {
8038            bool_bits(probs[0], true) + bool_bits(probs[1], true) + bool_bits(probs[2], true)
8039        }
8040    }
8041}
8042
8043/// `mvpartition_tree` path bits — RFC 6386 §16.4 / §20.13.
8044///
8045/// Mv16        = "0"   → bool_bits(MV_PARTITION_PROBS[0], false)
8046/// Quarters    = "10"  → bool_bits([0], true) + bool_bits([1], false)
8047/// TopBottom   = "110" → bool_bits([0..=1], true) + bool_bits([2], false)
8048/// LeftRight   = "111" → bool_bits([0..=2], true)
8049fn mv_partition_bits(p: crate::near_mv::MvPartition) -> f64 {
8050    let probs = &crate::near_mv::MV_PARTITION_PROBS;
8051    use crate::near_mv::MvPartition as P;
8052    match p {
8053        P::Mv16 => bool_bits(probs[0], false),
8054        P::Quarters => bool_bits(probs[0], true) + bool_bits(probs[1], false),
8055        P::TopBottom => {
8056            bool_bits(probs[0], true) + bool_bits(probs[1], true) + bool_bits(probs[2], false)
8057        }
8058        P::LeftRight => {
8059            bool_bits(probs[0], true) + bool_bits(probs[1], true) + bool_bits(probs[2], true)
8060        }
8061    }
8062}
8063
8064/// Score one §16.4 partition: walk its groups in partition-id order,
8065/// search whole-pixel SAD per group, evaluate the four §16.4
8066/// `sub_mv_ref` modes (LEFT4X4 / ABOVE4X4 / ZERO4X4 / NEW4X4) for the
8067/// group anchor, and assemble the (`split_mvs[16]`, group modes, group
8068/// new-diffs, total J) candidate.
8069///
8070/// Mirrors `decode_split_mv`'s "find the first sub-block whose
8071/// partition entry is `j`, look up its left/above neighbours, run
8072/// `sub_mv_ref`, fill every member of the group with the resolved
8073/// vector" walk so the encoder's per-group choice is exactly what the
8074/// decoder will reconstruct from the emitted bits.
8075///
8076/// Returns `None` if no in-range candidate is found (every NEW4X4
8077/// differential overflowed §17.1 and the LEFT/ABOVE/ZERO modes were
8078/// all dominated by SAD).
8079#[allow(clippy::too_many_arguments)] // each parameter is a distinct §16.4 input.
8080fn score_split_partition(
8081    partition: crate::near_mv::MvPartition,
8082    luma_ref: crate::motion_search::LumaRef<'_>,
8083    mb_col: usize,
8084    mb_row: usize,
8085    src_y: &[u8; 256],
8086    best_predictor: crate::motion_vector::Mv,
8087    above_mb: &crate::near_mv::MbInfo,
8088    left_mb: &crate::near_mv::MbInfo,
8089    mv_contexts: &crate::motion_vector::MvContexts,
8090    lambda: f64,
8091) -> Option<SplitMvCandidate> {
8092    let groups = partition_groups(partition);
8093    let mut split_mvs = [crate::motion_vector::Mv::default(); 16];
8094    let mut submv_modes = [crate::near_mv::SubMvRefMode::Zero4x4; 16];
8095    let mut submv_new_diffs = [crate::motion_vector::Mv::default(); 16];
8096    let mut total_sad: u32 = 0;
8097    let mut total_submv_bits: f64 = 0.0;
8098
8099    for (g_idx, group) in groups.iter().enumerate() {
8100        // The anchor is the smallest sub-block index in the group
8101        // (§16.4 / §20.11 "find the first sub-block whose partition
8102        // entry is j" — `partition_groups` already collects in raster
8103        // order, so `group[0]` is the anchor).
8104        let anchor = group[0];
8105        let left_neighbour_mv = crate::near_mv::left_block_mv(&split_mvs, left_mb, anchor);
8106        let above_neighbour_mv = crate::near_mv::above_block_mv(&split_mvs, above_mb, anchor);
8107        let ctx = crate::near_mv::submv_ref_context(left_neighbour_mv, above_neighbour_mv);
8108        let probs = &crate::near_mv::SUBMV_REF_PROBS[ctx];
8109
8110        // Whole-pixel search for a per-group NEW4X4 candidate (the
8111        // only mode that costs bits for a custom vector). The diamond
8112        // descents from the clamped near.mvs[0] "best" predictor — same
8113        // base the decoder's NEW4X4 will add the differential onto.
8114        let shape = groups.shape(g_idx);
8115        let (search_mv, search_sad) = group_small_diamond_search(
8116            luma_ref,
8117            mb_col,
8118            mb_row,
8119            src_y,
8120            group,
8121            shape,
8122            best_predictor,
8123            SPLIT_MV_MAX_DIAMOND_ITERS,
8124        );
8125
8126        // Score each of the four §16.4 sub_mv_ref modes.
8127        use crate::near_mv::SubMvRefMode as M;
8128        let mut best_mode: M = M::Zero4x4;
8129        let mut best_group_mv = crate::motion_vector::Mv::default();
8130        let mut best_group_diff = crate::motion_vector::Mv::default();
8131        let mut best_group_j: f64 = f64::INFINITY;
8132
8133        // Helper: probe one candidate (mode, resolved-mv, diff) and
8134        // update the best slot in place. SAD is recomputed at
8135        // `mv` so each candidate scores against the same evaluator.
8136        let mut try_cand = |mode: M,
8137                            mv: crate::motion_vector::Mv,
8138                            diff: crate::motion_vector::Mv,
8139                            diff_bits: f64| {
8140            let sad =
8141                group_sad_at_whole_mv_shaped(luma_ref, mb_col, mb_row, src_y, group, shape, mv)
8142                    as f64;
8143            let mode_bits = submv_ref_bits(probs, mode);
8144            let j = sad + lambda * (mode_bits + diff_bits);
8145            if j < best_group_j {
8146                best_group_j = j;
8147                best_mode = mode;
8148                best_group_mv = mv;
8149                best_group_diff = diff;
8150            }
8151        };
8152
8153        // LEFT4X4 — the resolved MV is the left neighbour, no diff bits.
8154        try_cand(
8155            M::Left4x4,
8156            left_neighbour_mv,
8157            crate::motion_vector::Mv::default(),
8158            0.0,
8159        );
8160        // ABOVE4X4 — the above neighbour, no diff bits.
8161        try_cand(
8162            M::Above4x4,
8163            above_neighbour_mv,
8164            crate::motion_vector::Mv::default(),
8165            0.0,
8166        );
8167        // ZERO4X4 — zero MV, no diff bits.
8168        try_cand(
8169            M::Zero4x4,
8170            crate::motion_vector::Mv::default(),
8171            crate::motion_vector::Mv::default(),
8172            0.0,
8173        );
8174        // NEW4X4 — searched MV, diff = search_mv - best_predictor.
8175        //
8176        // §17.1: each component of the diff fits in [-1023, +1023] — the
8177        // §17.2 component coder's range. An out-of-range diff is priced
8178        // at +inf so this candidate is dropped.
8179        let diff_row = (search_mv.row as i32) - (best_predictor.row as i32);
8180        let diff_col = (search_mv.col as i32) - (best_predictor.col as i32);
8181        let diff_in_range =
8182            (-1023..=1023).contains(&diff_row) && (-1023..=1023).contains(&diff_col);
8183        if diff_in_range {
8184            let diff = crate::motion_vector::Mv {
8185                row: diff_row as i16,
8186                col: diff_col as i16,
8187            };
8188            let diff_bits = crate::motion_vector::mv_component_bits(&mv_contexts[0], diff_row)
8189                + crate::motion_vector::mv_component_bits(&mv_contexts[1], diff_col);
8190            // SAD at `search_mv` is already known.
8191            let mode_bits = submv_ref_bits(probs, M::New4x4);
8192            let j = search_sad as f64 + lambda * (mode_bits + diff_bits);
8193            if j < best_group_j {
8194                best_group_j = j;
8195                best_mode = M::New4x4;
8196                best_group_mv = search_mv;
8197                best_group_diff = diff;
8198            }
8199        }
8200
8201        if !best_group_j.is_finite() {
8202            // No viable candidate (shouldn't be reachable — Zero4x4 is
8203            // always in-range — but guard for completeness).
8204            return None;
8205        }
8206
8207        // Fill every member sub-block of this group with the chosen MV
8208        // and accumulate its SAD into the partition total. The SAD
8209        // re-evaluation uses the same evaluator each candidate scored
8210        // against, so the total matches the picker's running sum.
8211        let group_sad = group_sad_at_whole_mv_shaped(
8212            luma_ref,
8213            mb_col,
8214            mb_row,
8215            src_y,
8216            group,
8217            shape,
8218            best_group_mv,
8219        );
8220        for &b in group {
8221            split_mvs[b] = best_group_mv;
8222        }
8223        total_sad += group_sad;
8224        total_submv_bits += submv_ref_bits(probs, best_mode);
8225        if matches!(best_mode, M::New4x4) {
8226            total_submv_bits += crate::motion_vector::mv_bits(mv_contexts, best_group_diff);
8227        }
8228        submv_modes[g_idx] = best_mode;
8229        submv_new_diffs[g_idx] = best_group_diff;
8230    }
8231
8232    // Total J adds the partition's §16.4 `mvpartition_tree` bits to
8233    // the per-group `sub_mv_ref` totals (the §16.2 SPLITMV
8234    // `mv_ref_tree` path bits are added by the caller once across all
8235    // four partition candidates).
8236    let partition_bits = mv_partition_bits(partition);
8237    let j = total_sad as f64 + lambda * (partition_bits + total_submv_bits);
8238
8239    Some(SplitMvCandidate {
8240        partition,
8241        split_mvs,
8242        submv_modes,
8243        submv_new_diffs,
8244        j,
8245    })
8246}
8247
8248/// Build the §13.3 raw-coefficient (no Y2) `MbCoeffs` for one SPLITMV
8249/// macroblock: per-sub-block luma forward DCT + quantise (no WHT —
8250/// SPLITMV has no Y2), and the standard chroma path (4 sub-blocks per
8251/// plane). Mirrors the `B_PRED` luma transform path (`transform_b_pred_luma`
8252/// would, if it existed; we inline it here since the SPLITMV picker is
8253/// the only inter caller that needs no-Y2 luma).
8254///
8255/// When `trellis` is `Some` each `YNoY2` luma sub-block and each `UV`
8256/// chroma sub-block is quantised by the §13 [`trellis_quantize_block`] RD
8257/// search; `None` preserves the plain-rounding SPLITMV wire byte-for-byte.
8258#[allow(clippy::too_many_arguments)]
8259fn transform_split_mv_mb_rd(
8260    src: &[u8; 256],
8261    pred: &[u8; 256],
8262    chroma_src_u: &[u8; 64],
8263    chroma_pred_u: &[u8; 64],
8264    chroma_src_v: &[u8; 64],
8265    chroma_pred_v: &[u8; 64],
8266    factors: &crate::dequant::MbDequantFactors,
8267    trellis: Option<&MbRdCtx>,
8268) -> MbCoeffs {
8269    // Per-sub-block luma forward DCT + Y1 quantisation. SPLITMV codes
8270    // every coefficient (0..=15) of each Y sub-block — no Y2, so the
8271    // DC is *not* extracted into a separate WHT block.
8272    let mut y = [[0i16; 16]; 16];
8273    for i in 0..4 {
8274        for j in 0..4 {
8275            let mut residual = [0i16; 16];
8276            for r in 0..4 {
8277                for c in 0..4 {
8278                    let off = (i * 4 + r) * 16 + (j * 4 + c);
8279                    residual[r * 4 + c] = src[off] as i16 - pred[off] as i16;
8280                }
8281            }
8282            let mut coeffs = [0i16; 16];
8283            forward_dct_4x4(&residual, &mut coeffs);
8284            // No DC extraction — every coefficient is quantised in
8285            // place under the Y1 (dc, ac) factors. The decoder's
8286            // `BlockType::YNoY2` path reads them the same way.
8287            match trellis {
8288                Some(rd) if rd.trellis_active() => trellis_quantize_block(
8289                    &mut coeffs,
8290                    TrellisBlockSpec {
8291                        dc: factors.y1_dc,
8292                        ac: factors.y1_ac,
8293                        first_coeff: BlockType::YNoY2.first_coeff(),
8294                        entry_ctx3: 0,
8295                        plane: BlockType::YNoY2.plane_index(),
8296                    },
8297                    rd.coeff_probs,
8298                    rd.rate_tables,
8299                    rd.trellis_lambda(),
8300                ),
8301                _ => enc_quantize_block(&mut coeffs, factors.y1_dc, factors.y1_ac),
8302            }
8303            y[i * 4 + j] = coeffs;
8304        }
8305    }
8306
8307    // Chroma uses the same path the whole-MB encoder uses.
8308    let u = transform_chroma_plane_rd(chroma_src_u, chroma_pred_u, factors, trellis);
8309    let v = transform_chroma_plane_rd(chroma_src_v, chroma_pred_v, factors, trellis);
8310
8311    MbCoeffs {
8312        y,
8313        y2: [0i16; 16], // unused (no Y2 for SPLITMV); the emitter
8314        // skips block 24 via `use_bpred = true` below.
8315        u,
8316        v,
8317    }
8318}
8319
8320/// Write the §16.4 `mvpartition_tree` path for `partition` — RFC 6386
8321/// §16.4 / §20.13. Mirrors the encoder side of [`crate::near_mv::read_mv_partition`].
8322///
8323/// `Mv16 = "0"`, `Quarters = "10"`, `TopBottom = "110"`,
8324/// `LeftRight = "111"`, all coded against `MV_PARTITION_PROBS`.
8325fn write_split_mv_partition(enc: &mut BoolEncoder, partition: crate::near_mv::MvPartition) {
8326    let probs = &crate::near_mv::MV_PARTITION_PROBS;
8327    use crate::near_mv::MvPartition as P;
8328    match partition {
8329        P::Mv16 => {
8330            enc.write_bool(probs[0], false);
8331        }
8332        P::Quarters => {
8333            enc.write_bool(probs[0], true);
8334            enc.write_bool(probs[1], false);
8335        }
8336        P::TopBottom => {
8337            enc.write_bool(probs[0], true);
8338            enc.write_bool(probs[1], true);
8339            enc.write_bool(probs[2], false);
8340        }
8341        P::LeftRight => {
8342            enc.write_bool(probs[0], true);
8343            enc.write_bool(probs[1], true);
8344            enc.write_bool(probs[2], true);
8345        }
8346    }
8347}
8348
8349/// Write one §16.4 `sub_mv_ref_tree` mode bit-path against `probs`
8350/// (a row of `SUBMV_REF_PROBS` selected by [`crate::near_mv::submv_ref_context`]).
8351///
8352/// `Left4x4 = "0"`, `Above4x4 = "10"`, `Zero4x4 = "110"`,
8353/// `New4x4 = "111"`. The §17.2 NEW4X4 component differential is *not*
8354/// written here — the caller emits it after this routine returns.
8355fn write_submv_ref(enc: &mut BoolEncoder, probs: &[u8; 3], mode: crate::near_mv::SubMvRefMode) {
8356    use crate::near_mv::SubMvRefMode as M;
8357    match mode {
8358        M::Left4x4 => {
8359            enc.write_bool(probs[0], false);
8360        }
8361        M::Above4x4 => {
8362            enc.write_bool(probs[0], true);
8363            enc.write_bool(probs[1], false);
8364        }
8365        M::Zero4x4 => {
8366            enc.write_bool(probs[0], true);
8367            enc.write_bool(probs[1], true);
8368            enc.write_bool(probs[2], false);
8369        }
8370        M::New4x4 => {
8371            enc.write_bool(probs[0], true);
8372            enc.write_bool(probs[1], true);
8373            enc.write_bool(probs[2], true);
8374        }
8375    }
8376}
8377
8378/// Encode one VP8 P-frame whose every macroblock is inter against the
8379/// LAST reference, with per-MB `ZEROMV` / `NEARESTMV` / `NEARMV` /
8380/// `NEWMV` / `SPLITMV` chosen by a non-normative rate-distortion trade.
8381///
8382/// Each MB on the wire is one §19.3 `macroblock_header()` (mb-skip /
8383/// is_inter / ref_frame selector / inter-mode tree walk / optional
8384/// §17.2 `read_mv` differential for `NEWMV`) plus its §13.3 residual
8385/// (or just the skip bit when the residual is all-zero).
8386///
8387/// Returns the emitted bytes alongside the macroblock-aligned post-§15
8388/// reconstruction the decoder will rebuild. The reconstruction is the
8389/// same shape as the §9 reference-frame buffer slot
8390/// ([`crate::state::RefFrameSlot`]); a multi-frame inter driver can
8391/// install it as the next frame's LAST without paying the cost of a
8392/// re-decode.
8393///
8394/// `reference` must be the macroblock-aligned reconstruction the
8395/// decoder produced for the previous frame (i.e. its `mb_cols * 16` /
8396/// `mb_rows * 8` planes), matching the source frame's macroblock-grid
8397/// dimensions. A mismatch is surfaced as
8398/// [`EncodeError::ReferenceDimensionsMismatch`].
8399///
8400/// # Scope (this round)
8401///
8402/// * **Whole-pixel + §18.3 half- and quarter-pixel motion search,
8403///   four-way `mv_ref_tree` pick.** A
8404///   [`crate::motion_search::small_diamond_search_luma`] descent runs
8405///   per MB against the clamped §16.3 "best" predictor (the running
8406///   `find_near_mvs[CNT_BEST]` vector), followed by a
8407///   [`crate::motion_search::half_pixel_refine_luma`] probe of the 8
8408///   half-pixel offsets around the whole-pixel result, and then a
8409///   [`crate::motion_search::quarter_pixel_refine_luma`] probe of the
8410///   8 quarter-pixel offsets around the half-pixel result (each
8411///   evaluated through the §18.3 six-tap synthesis the decoder will
8412///   reproduce). The chosen MV is whichever of the four whole-MB
8413///   `mv_ref_tree` leaves
8414///   ([`ZEROMV`](crate::near_mv::InterMode::Zero) — search-skipped,
8415///   `J = SAD at MV (0,0)`;
8416///   [`NEARESTMV`](crate::near_mv::InterMode::Nearest) — `J = SAD at
8417///   clamp(near.mvs[1]) + lambda * mv_ref_tree("10") bits`;
8418///   [`NEARMV`](crate::near_mv::InterMode::Near) — `J = SAD at
8419///   clamp(near.mvs[2]) + lambda * mv_ref_tree("110") bits`;
8420///   [`NEWMV`](crate::near_mv::InterMode::New) — `J = SAD at searched
8421///   MV + lambda * (mv_ref_tree("1110") bits + §17 component bits)`)
8422///   gives the smallest J. The §16.3 NEARESTMV / NEARMV candidates
8423///   are scored through the §18.3 sixtap-aware
8424///   [`crate::motion_search::mb_luma_sad_at_mv`] evaluator (neighbour
8425///   MVs can land at any §17 quarter-pixel position), at the clamped
8426///   MV the decoder's [`crate::near_mv::resolve_inter_mb_mv`] will
8427///   reconstruct from.
8428/// * **§16.4 SPLITMV with per-sub-block whole-pixel motion search.**
8429///   For each MB we additionally score all four
8430///   [`MvPartition`](crate::near_mv::MvPartition) shapes (`TopBottom`,
8431///   `LeftRight`, `Quarters`, `Mv16`); each partition's per-group MV
8432///   is the lowest-J among the four §16.4 `sub_mv_ref` modes
8433///   ([`Left4x4`](crate::near_mv::SubMvRefMode::Left4x4) — the group
8434///   anchor's left neighbour MV; [`Above4x4`] — its above neighbour;
8435///   [`Zero4x4`] — `(0, 0)`; [`New4x4`] — a per-group small whole-
8436///   pixel diamond search around the clamped `near.mvs[0]` predictor,
8437///   coded as a §17.2 differential added to that same `best`). The
8438///   §16.4 partition + sub_mv_ref + per-group NEW4X4 component bits
8439///   are summed with the §16.2 SPLITMV path bits ("1111") to give the
8440///   total `J(split)`; when smaller than the whole-MB picker's J the
8441///   SPLITMV path emits. `GOLDEN` / `ALTREF` source selection remains
8442///   deferred to a later round.
8443///
8444///   [`Above4x4`]: crate::near_mv::SubMvRefMode::Above4x4
8445///   [`Zero4x4`]: crate::near_mv::SubMvRefMode::Zero4x4
8446///   [`New4x4`]: crate::near_mv::SubMvRefMode::New4x4
8447/// * **`prob_intra` is 255**, so the decoder reads every MB as
8448///   inter without a bit on the wire wasted on intra-vs-inter
8449///   classification. Token-prob and intra-mode-prob update blocks
8450///   carry no updates; the §17.2 `mv_prob_update()` block is
8451///   emitted with every F-gate set to 0 so the MV-decode
8452///   infrastructure runs against the §17.2 defaults — the encoder
8453///   writes the NEWMV differential against the same default
8454///   [`MvContexts`].
8455/// * **§9.7 refresh ladder**: `refresh_last = 1`,
8456///   `refresh_golden_frame = 0`, `refresh_alternate_frame = 0`,
8457///   `copy_buffer_to_golden = 0`, `copy_buffer_to_alternate = 0`,
8458///   `refresh_entropy_probs = 0`. The post-§15 reconstruction
8459///   replaces LAST; GOLDEN / ALTREF stay as the caller left them.
8460/// * **§15 loop filter**: runs over the encoder's own reconstruction
8461///   when `params.loop_filter_level != 0`, mirroring the
8462///   keyframe-encoder pattern. The §9.4 `mode_ref_lf_delta_enabled`
8463///   flag is held at 0 (the per-MB delta layer is not emitted),
8464///   matching `encode_keyframe_with_reconstruction`.
8465/// * **§9.5 partition count** is fixed at 1 this round. Multi-
8466///   partition output for inter is the same layout reorganisation as
8467///   for keyframes; it can be wired in by a follow-up.
8468///
8469/// Outcome of running the §16.2 / §16.3 / §16.4 + §17 / §18 / §14
8470/// per-MB picker for one reference frame. Used by
8471/// [`encode_p_frame_multi_ref`] to score each available reference
8472/// (`LAST` / optional `GOLDEN` / optional `ALTREF`) and pick the
8473/// winning ref + mode + MV per MB.
8474#[derive(Clone)]
8475struct PickedMbForRef {
8476    /// The reference frame this candidate scored against.
8477    ref_frame: crate::motion_comp::RefFrame,
8478    /// The §16.2 whole-MB inter mode (or `Split` for SPLITMV) that
8479    /// won inside this ref's per-MB pick.
8480    chosen_mode: crate::near_mv::InterMode,
8481    /// The §17 quarter-pixel MV the chosen mode resolves to (the
8482    /// SPLITMV path stores `split_mvs[15]`, matching the §16.3
8483    /// `MbInfo::mv` convention).
8484    chosen_mv: crate::motion_vector::Mv,
8485    /// `Some(..)` iff `chosen_mode == InterMode::Split`. The §16.4
8486    /// partition, per-group `sub_mv_ref` modes, per-group NEW4X4
8487    /// differentials, and resolved `split_mvs[16]`.
8488    chosen_split: Option<SplitMvCandidate>,
8489    /// Per-MB residual coefficients (Y2 + 16 Y + 4 U + 4 V), already
8490    /// quantised — what the §13 token emit walks for this MB.
8491    raw_coeffs: MbCoeffs,
8492    /// §11.1 mb_skip_coeff. True iff every coded block is all-zero
8493    /// after quantisation.
8494    mb_skip_coeff: bool,
8495    /// Post-§14 reconstruction the encoder writes into its running
8496    /// `planes` buffer (and into the next-frame LAST slot once §15
8497    /// has filtered it).
8498    recon: crate::reconstruct::ReconstructedMb,
8499    /// True iff the §13.3 token walk routes through the B_PRED /
8500    /// SPLITMV "no Y2" path (`encode_mb_tokens(use_bpred = true)`).
8501    use_bpred: bool,
8502    /// `J = SAD + lambda * (mv_ref_tree + §17 mv + §16.4 partition +
8503    /// sub_mv_ref + NEW4X4) bits`. Does NOT include the §16.2
8504    /// `ref_frame_tree` bits — the caller adds those, since the
8505    /// `prob_last` / `prob_gf` used during picking and the
8506    /// distribution-fitted values used at emit-time can differ.
8507    j: f64,
8508}
8509
8510/// Run the full per-MB picker for one reference frame. Mirrors the
8511/// per-MB body of [`encode_p_frame_multi_ref`]'s search loop but
8512/// parameterised by the reference frame + its planes + its luma SAD
8513/// view. Used to compare LAST / GOLDEN / ALTREF candidates for the
8514/// same MB.
8515#[allow(clippy::too_many_arguments)]
8516fn pick_mb_for_ref(
8517    ref_frame: crate::motion_comp::RefFrame,
8518    reference_planes: &crate::motion_comp::ReferencePlanes<'_>,
8519    luma_ref: crate::motion_search::LumaRef<'_>,
8520    pixels: &MbPixels,
8521    above_slot: &crate::near_mv::MbInfo,
8522    left_mb: &crate::near_mv::MbInfo,
8523    aboveleft_mb: &crate::near_mv::MbInfo,
8524    mb_col: usize,
8525    mb_row: usize,
8526    mb_cols: usize,
8527    mb_rows: usize,
8528    mv_contexts: &crate::motion_vector::MvContexts,
8529    lambda: f64,
8530    filters: &[[i32; 6]; 8],
8531    factors: &crate::dequant::MbDequantFactors,
8532    coeff_probs: Option<&CoeffProbs>,
8533    rate_tables: Option<&TrellisRateTables>,
8534    trellis_strength: TrellisStrength,
8535) -> PickedMbForRef {
8536    // §13 trellis RD context for the inter residual emit, available once
8537    // the caller resolves this frame's coefficient probs. `None` keeps the
8538    // pre-trellis inter wire byte-for-byte.
8539    let trellis_rd = coeff_probs.map(|cp| MbRdCtx {
8540        factors,
8541        coeff_probs: cp,
8542        rate_tables,
8543        lambda,
8544        trellis: trellis_strength,
8545    });
8546    // ---- §16.3 census + §17 motion search ------------------------
8547    //
8548    // The §16.3 `find_near_mvs[CNT_BEST]` slot is the "best"
8549    // predictor a NEWMV differential is added to (see
8550    // `resolve_inter_mb_mv` in `crate::near_mv`). Clamp it through
8551    // the §18.1 / §20.11 per-MB rectangle before the search uses it
8552    // as the descent center, exactly matching what the decoder will
8553    // do when re-reading the NEWMV path. The census is per-ref:
8554    // neighbour MVs only count toward `near.mvs[]` when their
8555    // recorded `ref_frame` matches ours.
8556    let near = crate::near_mv::find_near_mvs(
8557        above_slot,
8558        left_mb,
8559        aboveleft_mb,
8560        ref_frame,
8561        crate::near_mv::SignBias::default(),
8562    );
8563    let bounds = crate::near_mv::MvClampRect::for_mb(mb_col, mb_row, mb_cols, mb_rows);
8564    let best_predictor = crate::near_mv::clamp_mv(near.mvs[0], &bounds);
8565    let mv_ref_probs = crate::near_mv::mv_ref_probs(&near.cnt);
8566
8567    // SAD at MV (0,0) is the ZEROMV distortion term.
8568    let sad_zero = crate::motion_search::mb_luma_sad_at_whole_mv(
8569        luma_ref,
8570        mb_col,
8571        mb_row,
8572        &pixels.y,
8573        crate::motion_vector::Mv::default(),
8574    );
8575    const MAX_DIAMOND_ITERS: u32 = 8;
8576    let whole_pel = crate::motion_search::small_diamond_search_luma(
8577        luma_ref,
8578        mb_col,
8579        mb_row,
8580        &pixels.y,
8581        best_predictor,
8582        MAX_DIAMOND_ITERS,
8583    );
8584    let half_pel = crate::motion_search::half_pixel_refine_luma(
8585        luma_ref,
8586        mb_col,
8587        mb_row,
8588        &pixels.y,
8589        whole_pel.mv,
8590    );
8591    let search = crate::motion_search::quarter_pixel_refine_luma(
8592        luma_ref,
8593        mb_col,
8594        mb_row,
8595        &pixels.y,
8596        half_pel.mv,
8597    );
8598
8599    // §16.2 inter-mode tree bit costs.
8600    let bits_mode_zero = bool_bits(mv_ref_probs[0], false);
8601    let bits_mode_nearest = bool_bits(mv_ref_probs[0], true) + bool_bits(mv_ref_probs[1], false);
8602    let bits_mode_near = bool_bits(mv_ref_probs[0], true)
8603        + bool_bits(mv_ref_probs[1], true)
8604        + bool_bits(mv_ref_probs[2], false);
8605    let bits_mode_new = bool_bits(mv_ref_probs[0], true)
8606        + bool_bits(mv_ref_probs[1], true)
8607        + bool_bits(mv_ref_probs[2], true)
8608        + bool_bits(mv_ref_probs[3], false);
8609    let diff_row = (search.mv.row as i32) - (best_predictor.row as i32);
8610    let diff_col = (search.mv.col as i32) - (best_predictor.col as i32);
8611    let diff_in_range = (-1023..=1023).contains(&diff_row) && (-1023..=1023).contains(&diff_col);
8612    let bits_mv_diff = if diff_in_range {
8613        crate::motion_vector::mv_component_bits(&mv_contexts[0], diff_row)
8614            + crate::motion_vector::mv_component_bits(&mv_contexts[1], diff_col)
8615    } else {
8616        f64::INFINITY
8617    };
8618
8619    let nearest_mv = crate::near_mv::clamp_mv(near.mvs[1], &bounds);
8620    let near_mv = crate::near_mv::clamp_mv(near.mvs[2], &bounds);
8621    let sad_nearest =
8622        crate::motion_search::mb_luma_sad_at_mv(luma_ref, mb_col, mb_row, &pixels.y, nearest_mv);
8623    let sad_near =
8624        crate::motion_search::mb_luma_sad_at_mv(luma_ref, mb_col, mb_row, &pixels.y, near_mv);
8625
8626    let j_zero = sad_zero as f64 + lambda * bits_mode_zero;
8627    let j_nearest = sad_nearest as f64 + lambda * bits_mode_nearest;
8628    let j_near = sad_near as f64 + lambda * bits_mode_near;
8629    let j_new = search.sad as f64 + lambda * (bits_mode_new + bits_mv_diff);
8630
8631    let nearest_eligible = nearest_mv != crate::motion_vector::Mv::default();
8632    let near_eligible = near_mv != crate::motion_vector::Mv::default();
8633    let new_eligible = diff_in_range && search.mv != crate::motion_vector::Mv::default();
8634
8635    let mut chosen_mode = crate::near_mv::InterMode::Zero;
8636    let mut chosen_mv = crate::motion_vector::Mv::default();
8637    let mut chosen_j = j_zero;
8638    if nearest_eligible && j_nearest < chosen_j {
8639        chosen_mode = crate::near_mv::InterMode::Nearest;
8640        chosen_mv = nearest_mv;
8641        chosen_j = j_nearest;
8642    }
8643    if near_eligible && j_near < chosen_j {
8644        chosen_mode = crate::near_mv::InterMode::Near;
8645        chosen_mv = near_mv;
8646        chosen_j = j_near;
8647    }
8648    if new_eligible && j_new < chosen_j {
8649        chosen_mode = crate::near_mv::InterMode::New;
8650        chosen_mv = search.mv;
8651        chosen_j = j_new;
8652    }
8653
8654    // ---- §16.4 SPLITMV picker --------------------------------------
8655    let bits_mode_split = bool_bits(mv_ref_probs[0], true)
8656        + bool_bits(mv_ref_probs[1], true)
8657        + bool_bits(mv_ref_probs[2], true)
8658        + bool_bits(mv_ref_probs[3], true);
8659    let mut best_split: Option<SplitMvCandidate> = None;
8660    for &partition in &[
8661        crate::near_mv::MvPartition::TopBottom,
8662        crate::near_mv::MvPartition::LeftRight,
8663        crate::near_mv::MvPartition::Quarters,
8664        crate::near_mv::MvPartition::Mv16,
8665    ] {
8666        if let Some(cand) = score_split_partition(
8667            partition,
8668            luma_ref,
8669            mb_col,
8670            mb_row,
8671            &pixels.y,
8672            best_predictor,
8673            above_slot,
8674            left_mb,
8675            mv_contexts,
8676            lambda,
8677        ) {
8678            let total_j = cand.j + lambda * bits_mode_split;
8679            if best_split
8680                .as_ref()
8681                .map(|b| total_j < b.j + lambda * bits_mode_split)
8682                .unwrap_or(true)
8683            {
8684                best_split = Some(SplitMvCandidate {
8685                    partition: cand.partition,
8686                    split_mvs: cand.split_mvs,
8687                    submv_modes: cand.submv_modes,
8688                    submv_new_diffs: cand.submv_new_diffs,
8689                    j: total_j,
8690                });
8691            }
8692        }
8693    }
8694    let mut chosen_split: Option<SplitMvCandidate> = None;
8695    if let Some(cand) = best_split
8696        && cand.j < chosen_j
8697    {
8698        chosen_mode = crate::near_mv::InterMode::Split;
8699        chosen_mv = cand.split_mvs[15];
8700        chosen_j = cand.j;
8701        chosen_split = Some(cand);
8702    }
8703
8704    // ---- §18 / §14 prediction + residual + reconstruction at the
8705    //      chosen (mode, mv) for THIS ref ---------------------------
8706    let (raw_coeffs, use_bpred) = if let Some(ref cand) = chosen_split {
8707        let pred = crate::motion_comp::predict_split_mv(
8708            reference_planes,
8709            mb_col,
8710            mb_row,
8711            &cand.split_mvs,
8712            false,
8713            filters,
8714        );
8715        let raw_coeffs = transform_split_mv_mb_rd(
8716            &pixels.y,
8717            &pred.y,
8718            &pixels.u,
8719            &pred.u,
8720            &pixels.v,
8721            &pred.v,
8722            factors,
8723            trellis_rd.as_ref(),
8724        );
8725        (raw_coeffs, true)
8726    } else {
8727        let pred = crate::motion_comp::predict_inter_mb(
8728            reference_planes,
8729            mb_col,
8730            mb_row,
8731            chosen_mv,
8732            false,
8733            filters,
8734        );
8735        let (y_quant, y2_quant) =
8736            transform_whole_block_luma_rd(&pixels.y, &pred.y, factors, trellis_rd.as_ref());
8737        let u_quant = transform_chroma_plane_rd(&pixels.u, &pred.u, factors, trellis_rd.as_ref());
8738        let v_quant = transform_chroma_plane_rd(&pixels.v, &pred.v, factors, trellis_rd.as_ref());
8739        let raw_coeffs = MbCoeffs {
8740            y: y_quant,
8741            y2: y2_quant,
8742            u: u_quant,
8743            v: v_quant,
8744        };
8745        (raw_coeffs, false)
8746    };
8747
8748    // §11.1 skip-detection.
8749    let mut nonzero_block_count = 0usize;
8750    if !use_bpred && raw_coeffs.y2.iter().any(|&v| v != 0) {
8751        nonzero_block_count += 1;
8752    }
8753    for blk in raw_coeffs.y.iter() {
8754        let first = if use_bpred { 0 } else { 1 };
8755        if blk.iter().skip(first).any(|&v| v != 0) {
8756            nonzero_block_count += 1;
8757        }
8758    }
8759    for blk in raw_coeffs.u.iter() {
8760        if blk.iter().any(|&v| v != 0) {
8761            nonzero_block_count += 1;
8762        }
8763    }
8764    for blk in raw_coeffs.v.iter() {
8765        if blk.iter().any(|&v| v != 0) {
8766            nonzero_block_count += 1;
8767        }
8768    }
8769    let mb_skip_coeff = nonzero_block_count == 0;
8770
8771    // §14.1: the `reconstruct_inter_mb` / `reconstruct_split_mv_mb`
8772    // orchestrators consume *dequantised* coefficients (the keyframe
8773    // raster loop above performs the same dequant on a copy before
8774    // calling its decoder reconstructor). Keep `raw_coeffs` quantised
8775    // for the later §13 token-emit path on the same call site; mirror
8776    // the keyframe pattern by dequantising a separate copy purely for
8777    // the §14.2/§14.5 reconstruction step.
8778    let mut dq = raw_coeffs;
8779    factors.dequantize(&mut dq);
8780    let recon = if let Some(ref cand) = chosen_split {
8781        crate::motion_comp::reconstruct_split_mv_mb(
8782            reference_planes,
8783            mb_col,
8784            mb_row,
8785            &cand.split_mvs,
8786            false,
8787            filters,
8788            mb_skip_coeff,
8789            &dq.y,
8790            &dq.u,
8791            &dq.v,
8792        )
8793    } else {
8794        crate::motion_comp::reconstruct_inter_mb(
8795            reference_planes,
8796            mb_col,
8797            mb_row,
8798            chosen_mv,
8799            false,
8800            filters,
8801            mb_skip_coeff,
8802            &dq.y2,
8803            &dq.y,
8804            &dq.u,
8805            &dq.v,
8806        )
8807    };
8808
8809    PickedMbForRef {
8810        ref_frame,
8811        chosen_mode,
8812        chosen_mv,
8813        chosen_split,
8814        raw_coeffs,
8815        mb_skip_coeff,
8816        recon,
8817        use_bpred,
8818        j: chosen_j,
8819    }
8820}
8821
8822/// Outcome of scoring an intra candidate against the
8823/// already-reconstructed in-frame neighbours during the round-160 /
8824/// round-161 intra-within-inter MB picker. Mirrors [`PickedMbForRef`]'s
8825/// shape so the per-MB driver can compare J side-by-side with the inter
8826/// winner and pick whichever wins.
8827///
8828/// Round 161 widens the scope to score all four §11.2 whole-block luma
8829/// modes (DC_PRED / V_PRED / H_PRED / TM_PRED) crossed with all four
8830/// §11.4 chroma modes (the same four), returning the best of the sixteen
8831/// candidates rather than the round-160 single DC_PRED candidate.
8832/// `B_PRED` stays out — the per-sub-block intra walker is a separate
8833/// fitter family and we don't have storage for it on this path.
8834#[derive(Clone)]
8835struct IntraMbPick {
8836    /// §11.2 whole-block luma mode the picker chose. Round 161 can be
8837    /// any of `Dc` / `V` / `H` / `Tm`; the storage type allows `B` but
8838    /// `pick_intra_mb_all` never returns it.
8839    y_mode: IntraYMode,
8840    /// §11.4 whole-block chroma mode the picker chose.
8841    uv_mode: IntraUvMode,
8842    /// Per-MB residual coefficients (Y2 + 16 Y + 4 U + 4 V), already
8843    /// quantised — what the §13 token-emit walk consumes when the
8844    /// per-MB driver records this candidate as the winner.
8845    raw_coeffs: MbCoeffs,
8846    /// §11.1 mb_skip_coeff. True iff every coded block is all-zero
8847    /// after quantisation.
8848    mb_skip_coeff: bool,
8849    /// Post-§14 reconstruction the encoder writes into its running
8850    /// `planes` buffer (and into the next-frame LAST slot once §15 has
8851    /// filtered it).
8852    recon: crate::reconstruct::ReconstructedMb,
8853    /// `J = Y-SAD + lambda * (intra-mode-tree bits)`. Does NOT include
8854    /// the §16 `is_inter_mb = false` bit — the caller adds that
8855    /// alongside the inter J's `is_inter_mb = true` bit so the picker
8856    /// trade includes the §16 discriminator bit equally on both sides
8857    /// (the `prob_intra` charge cancels out when picking against the
8858    /// uniform `prob_intra_pick = 128`, but we still account for it
8859    /// symbolically).
8860    j: f64,
8861}
8862
8863/// `-log2 P` cost in fractional bits of the §11.2 / §16.1 interframe
8864/// `IF_YMODE_TREE` path for one whole-block luma intra mode, given the
8865/// §16.1 default `ymode_prob` table (we hold `intra_y_mode_prob_update`
8866/// at its no-update gate, so the wire table stays at the defaults the
8867/// decoder's `InterFrameIntraProbs::defaults` exposes).
8868fn if_ymode_tree_bits(mode: IntraYMode) -> f64 {
8869    treed_bits_cached(&*IF_YMODE_PATHS, |i| IF_YMODE_PROB_DEFAULTS[i], mode.leaf())
8870}
8871
8872/// `-log2 P` cost in fractional bits of the §11.4 / §16.1 interframe
8873/// `UV_MODE_TREE` path for one whole-block chroma intra mode, against
8874/// the §16.1 default `uv_mode_prob` table.
8875fn if_uv_mode_tree_bits(mode: IntraUvMode) -> f64 {
8876    treed_bits_cached(
8877        &*UV_MODE_PATHS,
8878        |i| IF_UV_MODE_PROB_DEFAULTS[i],
8879        mode.leaf(),
8880    )
8881}
8882
8883/// Score one (y_mode, uv_mode) whole-block intra candidate for a
8884/// macroblock on an inter frame against the running in-frame neighbours
8885/// (`MbNeighbors` gathered from the encoder's reconstruction buffer the
8886/// SAME way the decoder's `gather_neighbors_public` will when it walks
8887/// the bytes). `y_mode == IntraYMode::B` is rejected (debug-asserted) —
8888/// the per-sub-block intra walker is a separate fitter family.
8889///
8890/// The full §14 chain — predict → FDCT → Y2/WHT → quantise → dequant →
8891/// IDCT → add — runs so the returned `recon` is the exact pixels the
8892/// decoder will produce on this MB.
8893///
8894/// The returned `J` is `Y-SAD + lambda * (Y-mode + UV-mode tree bits)`,
8895/// mirroring the inter picker's `J = SAD + lambda * mv_ref_tree_bits`
8896/// convention (the inter picker doesn't include token bits either; the
8897/// Y2/Y/UV token mass is roughly proportional across candidates of
8898/// similar prediction quality, and matching the inter picker's
8899/// distortion form keeps the cross-candidate trade apples-to-apples).
8900#[allow(clippy::too_many_arguments)]
8901fn score_intra_mb_candidate(
8902    y_mode: IntraYMode,
8903    uv_mode: IntraUvMode,
8904    pixels: &MbPixels,
8905    neighbors: &crate::reconstruct::MbNeighbors,
8906    factors: &crate::dequant::MbDequantFactors,
8907    lambda: f64,
8908    coeff_probs: Option<&CoeffProbs>,
8909    rate_tables: Option<&TrellisRateTables>,
8910    trellis_strength: TrellisStrength,
8911) -> IntraMbPick {
8912    debug_assert!(
8913        y_mode != IntraYMode::B,
8914        "score_intra_mb_candidate is whole-block only; B_PRED is routed via the per-sub-block walker",
8915    );
8916    // §13 trellis RD context for the intra-in-P-frame whole-block paths,
8917    // available once the caller resolves this frame's coefficient probs.
8918    // The strength is the per-stream knob threaded down from the inter
8919    // encode entry (the same `KeyframeParams::trellis_strength` field).
8920    let trellis_rd = coeff_probs.map(|cp| MbRdCtx {
8921        factors,
8922        coeff_probs: cp,
8923        rate_tables,
8924        lambda,
8925        trellis: trellis_strength,
8926    });
8927
8928    // ---- §12 prediction. Each `predict_y16x16` / `predict_uv8x8`
8929    //      dispatcher applies the §12 default-fill rules when the
8930    //      requested mode's neighbour is `None` (off-frame edge), so the
8931    //      V / H / TM modes safely cover the top-row / left-column /
8932    //      top-left-corner MBs the same way the decoder does.
8933    let topleft_y = neighbors
8934        .y_topleft
8935        .unwrap_or(crate::intra_predict::DEFAULT_ABOVE_PIXEL);
8936    let mut y_pred = [0u8; 256];
8937    crate::intra_predict::predict_y16x16(
8938        &mut y_pred,
8939        y_mode,
8940        neighbors.y_above.as_ref(),
8941        neighbors.y_left.as_ref(),
8942        topleft_y,
8943    )
8944    .expect("y_mode != B asserted above");
8945
8946    let topleft_u = neighbors
8947        .u_topleft
8948        .unwrap_or(crate::intra_predict::DEFAULT_ABOVE_PIXEL);
8949    let mut u_pred = [0u8; 64];
8950    crate::intra_predict::predict_uv8x8(
8951        &mut u_pred,
8952        uv_mode,
8953        neighbors.u_above.as_ref(),
8954        neighbors.u_left.as_ref(),
8955        topleft_u,
8956    );
8957    let topleft_v = neighbors
8958        .v_topleft
8959        .unwrap_or(crate::intra_predict::DEFAULT_ABOVE_PIXEL);
8960    let mut v_pred = [0u8; 64];
8961    crate::intra_predict::predict_uv8x8(
8962        &mut v_pred,
8963        uv_mode,
8964        neighbors.v_above.as_ref(),
8965        neighbors.v_left.as_ref(),
8966        topleft_v,
8967    );
8968
8969    // ---- Distortion: Y-plane SAD on the prediction residual, matching
8970    //      the inter picker's metric (`|src - reference[mv]|` summed
8971    //      over the 16×16 luma block, BEFORE residual coding /
8972    //      reconstruction). The post-reconstruction SSD a keyframe RD
8973    //      picker would use is finer-grained but on a different scale
8974    //      than the inter picker's SAD; matching the inter picker's
8975    //      pre-recon SAD keeps the cross-candidate J comparison
8976    //      apples-to-apples.
8977    let mut sad: u32 = 0;
8978    for (a, b) in pixels.y.iter().zip(y_pred.iter()) {
8979        sad += (*a as i32 - *b as i32).unsigned_abs();
8980    }
8981
8982    // ---- §14 forward transform + quantise (§13 trellis when this frame's
8983    //      coeff_probs are resolved; plain rounding otherwise — keeps the
8984    //      pre-trellis inter wire byte-for-byte for callers that pass None).
8985    let (y_quant, y2_quant) =
8986        transform_whole_block_luma_rd(&pixels.y, &y_pred, factors, trellis_rd.as_ref());
8987    let u_quant = transform_chroma_plane_rd(&pixels.u, &u_pred, factors, trellis_rd.as_ref());
8988    let v_quant = transform_chroma_plane_rd(&pixels.v, &v_pred, factors, trellis_rd.as_ref());
8989    let raw_coeffs = MbCoeffs {
8990        y: y_quant,
8991        y2: y2_quant,
8992        u: u_quant,
8993        v: v_quant,
8994    };
8995
8996    // §11.1 mb_skip_coeff — every non-B_PRED whole-block intra has Y2,
8997    // so every block (Y2 + 16 Y coded from coefficient 1 + 4 U + 4 V)
8998    // contributes to the count.
8999    let mut nonzero_block_count = 0usize;
9000    if raw_coeffs.y2.iter().any(|&v| v != 0) {
9001        nonzero_block_count += 1;
9002    }
9003    for blk in raw_coeffs.y.iter() {
9004        if blk.iter().skip(1).any(|&v| v != 0) {
9005            nonzero_block_count += 1;
9006        }
9007    }
9008    for blk in raw_coeffs.u.iter() {
9009        if blk.iter().any(|&v| v != 0) {
9010            nonzero_block_count += 1;
9011        }
9012    }
9013    for blk in raw_coeffs.v.iter() {
9014        if blk.iter().any(|&v| v != 0) {
9015            nonzero_block_count += 1;
9016        }
9017    }
9018    let mb_skip_coeff = nonzero_block_count == 0;
9019
9020    // ---- §14 reconstruction (decoder-shared path) ----
9021    let mut dq = raw_coeffs;
9022    factors.dequantize(&mut dq);
9023    let recon = crate::reconstruct::decode_keyframe_mb_non_bpred(
9024        y_mode,
9025        uv_mode,
9026        mb_skip_coeff,
9027        neighbors,
9028        &dq.y2,
9029        &dq.y,
9030        &dq.u,
9031        &dq.v,
9032    )
9033    .expect("decode_keyframe_mb_non_bpred rejects only B_PRED, ruled out above");
9034
9035    // Mode bits: Y-mode (IF_YMODE_TREE leaf) + UV-mode (UV_MODE_TREE leaf).
9036    let mode_bits = if_ymode_tree_bits(y_mode) + if_uv_mode_tree_bits(uv_mode);
9037    let j = sad as f64 + lambda * mode_bits;
9038
9039    IntraMbPick {
9040        y_mode,
9041        uv_mode,
9042        raw_coeffs,
9043        mb_skip_coeff,
9044        recon,
9045        j,
9046    }
9047}
9048
9049/// Round 161 — score every whole-block intra `(y_mode, uv_mode)`
9050/// combination (4 luma × 4 chroma = 16 candidates, `B_PRED` excluded
9051/// because the per-sub-block intra walker is a separate fitter family)
9052/// and return the winner on `J = Y-SAD + lambda * mode-tree-bits`.
9053///
9054/// Mirrors the round-160 [`score_intra_mb_candidate`]-of-just-DC entry
9055/// shape so the per-MB driver only needs to swap the call and propagate
9056/// the chosen `(y_mode, uv_mode)` into the `intra_y_modes` /
9057/// `intra_uv_modes` per-MB storage that the round-160 driver already
9058/// laid out.
9059///
9060/// Iteration order matches the encoder enum declaration
9061/// (`Dc, V, H, Tm` — `B` skipped). Strict `<` on J means ties go to
9062/// the earliest-tried, i.e. `(Dc, Dc)` — the round-160 pick. Encode-wire
9063/// bytes are therefore identical to round 160 on any source where DC
9064/// would have won there.
9065#[allow(clippy::too_many_arguments)]
9066fn pick_intra_mb_all(
9067    pixels: &MbPixels,
9068    neighbors: &crate::reconstruct::MbNeighbors,
9069    factors: &crate::dequant::MbDequantFactors,
9070    lambda: f64,
9071    coeff_probs: Option<&CoeffProbs>,
9072    rate_tables: Option<&TrellisRateTables>,
9073    trellis_strength: TrellisStrength,
9074) -> IntraMbPick {
9075    const Y_MODES: [IntraYMode; 4] = [IntraYMode::Dc, IntraYMode::V, IntraYMode::H, IntraYMode::Tm];
9076    const UV_MODES: [IntraUvMode; 4] = [
9077        IntraUvMode::Dc,
9078        IntraUvMode::V,
9079        IntraUvMode::H,
9080        IntraUvMode::Tm,
9081    ];
9082    let mut best: Option<IntraMbPick> = None;
9083    for &y_mode in Y_MODES.iter() {
9084        for &uv_mode in UV_MODES.iter() {
9085            let cand = score_intra_mb_candidate(
9086                y_mode,
9087                uv_mode,
9088                pixels,
9089                neighbors,
9090                factors,
9091                lambda,
9092                coeff_probs,
9093                rate_tables,
9094                trellis_strength,
9095            );
9096            match best.as_ref() {
9097                None => best = Some(cand),
9098                Some(b) if cand.j < b.j => best = Some(cand),
9099                _ => {}
9100            }
9101        }
9102    }
9103    best.expect("Y_MODES × UV_MODES is non-empty")
9104}
9105
9106/// `-log2 P` cost in fractional bits of the §16.2 `ref_frame_tree`
9107/// path for one reference frame, given the wire probs.
9108fn ref_frame_tree_bits(ref_frame: crate::motion_comp::RefFrame, prob_last: u8, prob_gf: u8) -> f64 {
9109    match ref_frame {
9110        // LAST: B(prob_last) reads `false`.
9111        crate::motion_comp::RefFrame::Last => bool_bits(prob_last, false),
9112        // GOLDEN: B(prob_last) reads `true`, B(prob_gf) reads `false`.
9113        crate::motion_comp::RefFrame::Golden => {
9114            bool_bits(prob_last, true) + bool_bits(prob_gf, false)
9115        }
9116        // ALTREF: B(prob_last) reads `true`, B(prob_gf) reads `true`.
9117        crate::motion_comp::RefFrame::AltRef => {
9118            bool_bits(prob_last, true) + bool_bits(prob_gf, true)
9119        }
9120    }
9121}
9122
9123/// Pick the L(8) wire value for `prob` that minimises the total
9124/// `-count_true * log2(1 - p/256) - count_false * log2(p/256)` cost
9125/// of `count_false` "false" reads + `count_true` "true" reads. The
9126/// optimum is `256 * count_false / total`, clamped into `1..=255` to
9127/// keep the §7.3 bool range from collapsing.
9128fn fit_prob_l8(count_false: u32, count_true: u32) -> u8 {
9129    let total = count_false + count_true;
9130    if total == 0 {
9131        return 128; // arbitrary; nobody reads it.
9132    }
9133    let raw = ((count_false as u64 * 256) / total as u64) as u32;
9134    raw.clamp(1, 255) as u8
9135}
9136
9137/// Caller-driven §9.7 / §9.8 reference-slot refresh pattern for a single
9138/// P-frame.
9139///
9140/// The five fields map one-for-one to the §9.7 / §9.8 bits the inter
9141/// frame header carries (RFC 6386 §9.7 page 38, §9.8 page 39):
9142///
9143/// * `refresh_golden_frame` — `L(1)`. `true` replaces the GOLDEN slot
9144///   with the current reconstruction; `false` leaves it in place (or
9145///   defers to `copy_buffer_to_golden`).
9146/// * `refresh_alternate_frame` — `L(1)`. `true` replaces the ALTREF
9147///   slot with the current reconstruction; `false` defers to
9148///   `copy_buffer_to_alternate`.
9149/// * `copy_buffer_to_golden` — `L(2)`, only read when
9150///   `refresh_golden_frame == 0`. `0` no copy; `1` copies LAST into
9151///   GOLDEN; `2` copies ALTREF into GOLDEN.
9152/// * `copy_buffer_to_alternate` — `L(2)`, only read when
9153///   `refresh_alternate_frame == 0`. `0` no copy; `1` copies LAST into
9154///   ALTREF; `2` copies GOLDEN into ALTREF.
9155/// * `refresh_last` — `L(1)`. `true` replaces the LAST slot with the
9156///   current reconstruction (the conventional inter pattern); `false`
9157///   leaves LAST in place so the next P-frame predicts off the
9158///   already-held picture.
9159///
9160/// The decoder's §9.7 / §9.8 walk (page 147 of RFC 6386:
9161/// `copy_arf → copy_gf → refresh_gf → refresh_arf → refresh_last`)
9162/// is implemented verbatim in [`crate::state::Vp8DecoderState`], so any
9163/// pattern this struct can express is decodable by the in-tree decoder
9164/// — `Vp8InterStreamEncoder` mirrors the same walk on its own slot
9165/// trio to keep encoder and decoder lockstep.
9166///
9167/// [`Default`] reproduces the round-149 pattern
9168/// ([`encode_p_frame_multi_ref`]'s hardwired ladder):
9169/// `refresh_last = true`, everything else 0 / `false`. With those
9170/// defaults the new public
9171/// [`encode_p_frame_multi_ref_with_refresh`] emits a wire that is
9172/// byte-identical to [`encode_p_frame_multi_ref`].
9173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9174pub struct RefreshControls {
9175    /// §9.7 `refresh_golden_frame` (L1). `true` replaces GOLDEN with
9176    /// the current reconstruction.
9177    pub refresh_golden_frame: bool,
9178    /// §9.7 `refresh_alternate_frame` (L1). `true` replaces ALTREF with
9179    /// the current reconstruction.
9180    pub refresh_alternate_frame: bool,
9181    /// §9.7 `copy_buffer_to_golden` (L2, gated on
9182    /// `refresh_golden_frame == 0`). 0 = none, 1 = LAST → GOLDEN,
9183    /// 2 = ALTREF → GOLDEN. Values > 2 are rejected with
9184    /// [`EncodeError::InvalidCopyBufferSelector`].
9185    pub copy_buffer_to_golden: u8,
9186    /// §9.7 `copy_buffer_to_alternate` (L2, gated on
9187    /// `refresh_alternate_frame == 0`). 0 = none, 1 = LAST → ALTREF,
9188    /// 2 = GOLDEN → ALTREF. Values > 2 are rejected with
9189    /// [`EncodeError::InvalidCopyBufferSelector`].
9190    pub copy_buffer_to_alternate: u8,
9191    /// §9.8 `refresh_last` (L1). `true` replaces LAST with the current
9192    /// reconstruction (the conventional inter behaviour); `false` keeps
9193    /// the previous LAST picture so the next P-frame predicts off it.
9194    pub refresh_last: bool,
9195}
9196
9197impl Default for RefreshControls {
9198    /// Round-149 default: `refresh_last = true`, every other field at
9199    /// zero. Reproduces the wire and slot semantics of
9200    /// [`encode_p_frame_multi_ref`].
9201    fn default() -> Self {
9202        Self {
9203            refresh_golden_frame: false,
9204            refresh_alternate_frame: false,
9205            copy_buffer_to_golden: 0,
9206            copy_buffer_to_alternate: 0,
9207            refresh_last: true,
9208        }
9209    }
9210}
9211
9212impl RefreshControls {
9213    /// Validate the per-field constraints. `copy_buffer_to_*`
9214    /// selectors outside `0..=2` are rejected with
9215    /// [`EncodeError::InvalidCopyBufferSelector`].
9216    ///
9217    /// The §19.2 page-122 listing gates the L(2) `copy_buffer_to_*`
9218    /// emission on `if (!refresh_*_frame)`: the encoder does not
9219    /// transmit the selector when the matching refresh bit is 1, so a
9220    /// caller that sets both `refresh_golden_frame = true` AND
9221    /// `copy_buffer_to_golden != 0` would silently lose the copy
9222    /// intent (the slot is overwritten by the current reconstruction
9223    /// regardless). To make that misuse impossible we reject it here.
9224    pub fn validate(&self) -> Result<(), EncodeError> {
9225        if self.copy_buffer_to_golden > 2 {
9226            return Err(EncodeError::InvalidCopyBufferSelector {
9227                which: CopyBufferSelector::Golden,
9228                value: self.copy_buffer_to_golden,
9229            });
9230        }
9231        if self.copy_buffer_to_alternate > 2 {
9232            return Err(EncodeError::InvalidCopyBufferSelector {
9233                which: CopyBufferSelector::Alternate,
9234                value: self.copy_buffer_to_alternate,
9235            });
9236        }
9237        if self.refresh_golden_frame && self.copy_buffer_to_golden != 0 {
9238            return Err(EncodeError::InvalidCopyBufferSelector {
9239                which: CopyBufferSelector::Golden,
9240                value: self.copy_buffer_to_golden,
9241            });
9242        }
9243        if self.refresh_alternate_frame && self.copy_buffer_to_alternate != 0 {
9244            return Err(EncodeError::InvalidCopyBufferSelector {
9245                which: CopyBufferSelector::Alternate,
9246                value: self.copy_buffer_to_alternate,
9247            });
9248        }
9249        Ok(())
9250    }
9251}
9252
9253/// Self-decode validation: the emitted bytes decode through
9254/// [`crate::state::Vp8DecoderState`] (after the I-frame the LAST slot
9255/// holds) and reproduce the source within the §14 quantiser's
9256/// distortion (≥ 30 dB whole-frame PSNR at a mid quantiser on a
9257/// slow-motion synthetic source).
9258pub fn encode_p_frame_zero_mv(
9259    frame: &I420Frame,
9260    reference: &crate::frame::KeyframePlanes,
9261    params: &KeyframeParams,
9262) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9263    encode_p_frame_multi_ref(frame, reference, None, None, params)
9264}
9265
9266/// Backward-compatible wrapper for
9267/// [`encode_p_frame_multi_ref_with_refresh`]: passes
9268/// [`RefreshControls::default`] so the wire ladder matches the
9269/// round-149 hardwired pattern (`refresh_last = 1`, every other
9270/// §9.7 / §9.8 bit `0`).
9271pub fn encode_p_frame_multi_ref(
9272    frame: &I420Frame,
9273    last: &crate::frame::KeyframePlanes,
9274    golden: Option<&crate::frame::KeyframePlanes>,
9275    altref: Option<&crate::frame::KeyframePlanes>,
9276    params: &KeyframeParams,
9277) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9278    encode_p_frame_multi_ref_with_refresh(
9279        frame,
9280        last,
9281        golden,
9282        altref,
9283        params,
9284        &RefreshControls::default(),
9285    )
9286}
9287
9288/// Rewrite the §9.1 frame-tag `show_frame` bit in an already-assembled
9289/// VP8 frame.
9290///
9291/// The §9.1 tag is a 3-byte little-endian word whose bit 4 is
9292/// `show_frame` ("0 when current frame is not for display, 1 when
9293/// current frame is for display"); the surrounding bits (`frame_type`,
9294/// `version`, `first_partition_size`) are independent fields, so
9295/// flipping bit 4 in byte 0 changes the frame's visibility and nothing
9296/// else. Every partition boundary, probability, and coefficient byte
9297/// stays untouched — the invisible wire is byte-identical to the
9298/// visible one except for this single bit.
9299pub(crate) fn set_show_frame_bit(frame: &mut [u8], show_frame: bool) {
9300    debug_assert!(
9301        frame.len() >= 3,
9302        "a VP8 frame is at least the 3-byte §9.1 tag"
9303    );
9304    if let Some(b0) = frame.first_mut() {
9305        if show_frame {
9306            *b0 |= 0x10;
9307        } else {
9308            *b0 &= !0x10;
9309        }
9310    }
9311}
9312
9313/// Encode an **invisible altref-update frame** — the §9.1 / §9.7
9314/// building block of B-frame-less GOLDEN / ALTREF management.
9315///
9316/// The frame is a regular §16.2 multi-reference interframe (full
9317/// motion-search / mode-decision walk, §11 intra-within-inter picker
9318/// enabled) with two deliberate departures from the conventional
9319/// P-frame pattern:
9320///
9321/// * the §9.7 / §9.8 refresh ladder is
9322///   `refresh_alternate_frame = 1, refresh_last = 0` (GOLDEN untouched)
9323///   — the reconstruction lands **only** in the ALTREF slot, so the
9324///   LAST chain of the display sequence is not perturbed;
9325/// * the §9.1 frame-tag `show_frame` bit is 0 ("not for display"), so
9326///   a compliant player decodes the frame for its reference-slot side
9327///   effects and drops the picture from presentation.
9328///
9329/// Feeding a *future* (or temporally-filtered) source picture through
9330/// this entry gives subsequent P-frames a forward-looking prediction
9331/// anchor via the per-MB §16.2 `ref_frame` selector — prediction from
9332/// a picture that has never been displayed, without any bidirectional
9333/// coding machinery. The returned reconstruction is exactly what the
9334/// decoder's ALTREF slot will hold after it processes these bytes.
9335///
9336/// `last` / `golden` / `altref` are the encoder-side reference slots
9337/// the update frame itself may predict from (same contract as
9338/// [`encode_p_frame_multi_ref`]).
9339pub fn encode_invisible_altref_update(
9340    frame: &I420Frame,
9341    last: &crate::frame::KeyframePlanes,
9342    golden: Option<&crate::frame::KeyframePlanes>,
9343    altref: Option<&crate::frame::KeyframePlanes>,
9344    params: &KeyframeParams,
9345) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9346    let refresh = RefreshControls {
9347        refresh_alternate_frame: true,
9348        refresh_last: false,
9349        ..RefreshControls::default()
9350    };
9351    let (mut bytes, planes) = encode_p_frame_multi_ref_with_refresh_and_intra_pick(
9352        frame, last, golden, altref, params, &refresh,
9353    )?;
9354    set_show_frame_bit(&mut bytes, false);
9355    Ok((bytes, planes))
9356}
9357
9358/// §16.2 multi-reference P-frame encoder with RD-selected §9.4
9359/// `loop_filter_level` and the §11 intra-mode picker enabled.
9360///
9361/// Identical to [`encode_p_frame_multi_ref_with_refresh_and_intra_pick`]
9362/// (default refresh ladder) except that `params.loop_filter_level` is
9363/// **ignored**: after the inter mode-decision / motion-search walk, the
9364/// encoder searches the §9.4 level range for the level that minimises
9365/// post-§15 visible-window SSD of its own reconstruction against the
9366/// source `frame` (clean-room — RFC 6386 leaves the level choice to the
9367/// encoder; see [`crate::loop_filter::select_filter_level`]) and writes
9368/// that level into the §9.4 header. The per-MB §9.4 reference / mode
9369/// deltas default off (`LoopFilterDeltas::default()`), so each MB's
9370/// effective level reduces to the frame base. Returns the bitstream and
9371/// the post-§15 reconstruction (for installation into the §9 reference
9372/// ladder).
9373pub fn encode_p_frame_multi_ref_auto_loop_filter(
9374    frame: &I420Frame,
9375    last: &crate::frame::KeyframePlanes,
9376    golden: Option<&crate::frame::KeyframePlanes>,
9377    altref: Option<&crate::frame::KeyframePlanes>,
9378    params: &KeyframeParams,
9379) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9380    encode_p_frame_multi_ref_inner_with_counts_and_pick(
9381        frame,
9382        last,
9383        golden,
9384        altref,
9385        params,
9386        &RefreshControls::default(),
9387        &LoopFilterDeltas::default(),
9388        [0; 4],
9389        [0; 4],
9390        None,
9391        None,
9392        true,
9393        true,
9394    )
9395}
9396
9397/// §16.2 multi-reference P-frame encoder with caller-driven §9.7 /
9398/// §9.8 reference-slot refresh control **and** caller-driven §9.4
9399/// per-reference / per-mode `loop_filter_delta` layer.
9400///
9401/// Extends [`encode_p_frame_multi_ref_with_refresh`] with the §9.4
9402/// `mb_lf_adjustments()` sub-block: the frame header emits the new
9403/// `loop_filter_adj_enable` / `mode_ref_lf_delta_update` bits and the
9404/// gated per-slot L(6) + L(1) values per [`LoopFilterDeltas`], and the
9405/// encoder's own §15 post-walk filter pass uses the effective per-MB
9406/// filter level ([`crate::loop_filter::calculate_mb_filter_level_inter`])
9407/// so the encoder's reconstruction buffer matches what the decoder
9408/// rebuilds from the same wire byte-for-byte.
9409///
9410/// `carried_ref_deltas` and `carried_mode_deltas` represent the
9411/// across-frame delta state per RFC 6386 §9.4: "the values from the
9412/// previous frame are used, unless they are updated in the current
9413/// header." For a standalone encode (no prior frame state), pass
9414/// `[0; 4]` for both; for a streaming caller, thread the values from
9415/// the previous frame's effective deltas — [`Vp8InterStreamEncoder`]
9416/// does this automatically.
9417///
9418/// Wire compatibility: `LoopFilterDeltas::default()` (with
9419/// `enabled = false`) and `[0; 4]` carried state reproduce the
9420/// round-150 wire byte-for-byte. Setting `enabled = true` flips on the
9421/// §9.4 layer; setting `update = false` while `enabled = true` reuses
9422/// the carried deltas without writing fresh values.
9423#[allow(clippy::too_many_arguments)]
9424pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas(
9425    frame: &I420Frame,
9426    last: &crate::frame::KeyframePlanes,
9427    golden: Option<&crate::frame::KeyframePlanes>,
9428    altref: Option<&crate::frame::KeyframePlanes>,
9429    params: &KeyframeParams,
9430    refresh: &RefreshControls,
9431    lf_deltas: &LoopFilterDeltas,
9432    carried_ref_deltas: [i16; 4],
9433    carried_mode_deltas: [i16; 4],
9434) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9435    encode_p_frame_multi_ref_inner(
9436        frame,
9437        last,
9438        golden,
9439        altref,
9440        params,
9441        refresh,
9442        lf_deltas,
9443        carried_ref_deltas,
9444        carried_mode_deltas,
9445        None,
9446    )
9447}
9448
9449/// §16.2 multi-reference P-frame encoder with caller-driven §9.7 /
9450/// §9.8 reference-slot refresh control, caller-driven §9.4 per-
9451/// reference / per-mode `loop_filter_delta` layer, **and** caller-driven
9452/// §13.4 `token_prob_update()` payload.
9453///
9454/// This is the inter-frame mirror of
9455/// [`encode_keyframe_with_token_prob_updates`] (round 155). When
9456/// `token_updates` is `Some(u)` the encoder writes the §13.4
9457/// per-position replacement layer into the first-partition header and
9458/// encodes the §13.3 residual tokens against the merged
9459/// `coeff_probs[4][8][3][11]` table (defaults overlaid with `u`). The
9460/// decoder reads the same updates from the wire and applies the same
9461/// overlay on top of its carried entropy state via
9462/// [`crate::dct_tokens::merge_default_token_probs`]-equivalent
9463/// machinery, so the round-trip is sound on either path.
9464///
9465/// `refresh_entropy_probs` stays `false` on inter frames (the §9.10
9466/// row-1 bit the encoder hardwires) — per RFC 6386 §9.10, this means
9467/// the frame's token-prob overlay is in force for THIS frame only; the
9468/// decoder restores the saved (key-frame) table afterwards. Setting
9469/// `token_updates = Some(u)` therefore re-prices the token bits of just
9470/// this inter frame without leaking into subsequent P-frames, which is
9471/// the natural fit for a per-frame "fit prob to observed token counts"
9472/// strategy.
9473///
9474/// Wire compatibility: `token_updates = None` (or an all-`None` array)
9475/// reproduces the round-155 inter wire byte-for-byte (the §13.4
9476/// sub-block reduces to 1056 zero flags and tokens are coded against
9477/// the §13.5 defaults). Every pre-r156 caller of
9478/// [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas`] stays
9479/// unchanged.
9480#[allow(clippy::too_many_arguments)]
9481pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates(
9482    frame: &I420Frame,
9483    last: &crate::frame::KeyframePlanes,
9484    golden: Option<&crate::frame::KeyframePlanes>,
9485    altref: Option<&crate::frame::KeyframePlanes>,
9486    params: &KeyframeParams,
9487    refresh: &RefreshControls,
9488    lf_deltas: &LoopFilterDeltas,
9489    carried_ref_deltas: [i16; 4],
9490    carried_mode_deltas: [i16; 4],
9491    token_updates: Option<&TokenProbUpdates>,
9492) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9493    encode_p_frame_multi_ref_inner(
9494        frame,
9495        last,
9496        golden,
9497        altref,
9498        params,
9499        refresh,
9500        lf_deltas,
9501        carried_ref_deltas,
9502        carried_mode_deltas,
9503        token_updates,
9504    )
9505}
9506
9507/// §16.2 multi-reference P-frame encoder with caller-driven §13.4
9508/// `token_prob_update()` payload (and round-150 defaults for refresh +
9509/// §9.4 deltas).
9510///
9511/// Thin wrapper over
9512/// [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates`]
9513/// that uses [`RefreshControls::default`] / [`LoopFilterDeltas::default`]
9514/// and `[0; 4]` carried delta state — i.e. the configuration that makes
9515/// the round-149 / round-150 / round-151 wire byte-for-byte equivalent
9516/// to the historical [`encode_p_frame_multi_ref`] when
9517/// `token_updates = None`.
9518pub fn encode_p_frame_multi_ref_with_token_updates(
9519    frame: &I420Frame,
9520    last: &crate::frame::KeyframePlanes,
9521    golden: Option<&crate::frame::KeyframePlanes>,
9522    altref: Option<&crate::frame::KeyframePlanes>,
9523    params: &KeyframeParams,
9524    token_updates: Option<&TokenProbUpdates>,
9525) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9526    encode_p_frame_multi_ref_inner(
9527        frame,
9528        last,
9529        golden,
9530        altref,
9531        params,
9532        &RefreshControls::default(),
9533        &LoopFilterDeltas::default(),
9534        [0; 4],
9535        [0; 4],
9536        token_updates,
9537    )
9538}
9539
9540/// §16.2 multi-reference P-frame encoder with an automatically-fitted
9541/// §13.4 `token_prob_update()` payload — the inter-path mirror of
9542/// [`encode_keyframe_with_fitted_token_prob_updates`] (round 157).
9543///
9544/// Round 156 wired the inter caller-driven layer; round 158 closes the
9545/// natural follow-up by letting the encoder *fit* the §13.4 payload
9546/// from observed branch counts instead of asking the caller for one.
9547/// The fitter shares its cost-model ([`fit_token_prob_updates`]) and
9548/// counter type ([`BranchCounts`]) with the keyframe path; only the
9549/// per-frame collection plumbing — [`count_inter_frame_branches`] —
9550/// is inter-specific (the inter picker stamps `IntraYMode::Dc` onto
9551/// every MB so the "no Y2" decision can't be recovered from `y_mode`;
9552/// the inner driver records it in a `use_bpred_per_mb` vector that
9553/// this walker consumes).
9554///
9555/// Internally the function takes two passes:
9556///
9557///   1. Encode with the §13.5 defaults and collect the per-position
9558///      branch counts via the [`encode_p_frame_multi_ref_inner_with_counts`]
9559///      `counts` side-channel.
9560///   2. Run [`fit_token_prob_updates`] to derive the
9561///      [`TokenProbUpdates`] payload that nets a positive bit saving
9562///      against those counts, then re-encode with that payload through
9563///      [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates`].
9564///
9565/// If the fitter returns an all-`None` payload (no slot crossed the
9566/// saving threshold), or the fitted re-encode is **larger** than the
9567/// default-encode wire (the model's saving estimate is computed
9568/// against pass-1's coefficient distribution; pass-2's RD pick perturbs
9569/// it slightly), the default-encode bytes are returned instead — so
9570/// this entry-point is guaranteed to be `<=` the
9571/// `encode_p_frame_multi_ref_with_token_updates(.., None)` wire in
9572/// every case. The returned bytes always decode through the crate's
9573/// own [`crate::state::Vp8DecoderState`] and any compliant VP8 decoder.
9574///
9575/// **Carried-base assumption.** Same as the round-156 inter caller-
9576/// driven entry-point: this function assumes the prior key frame was
9577/// emitted with the §13.5 defaults (i.e. `encode_keyframe` or
9578/// `encode_keyframe_with_token_prob_updates(.., None)`). The decoder
9579/// overlays the fitted payload on top of that base via
9580/// [`Vp8DecoderState::decode_inter_frame`] (`overlay_token_probs(self.
9581/// coeff_probs, &coded.token_prob_updates)`); the encoder's two-pass
9582/// fit also overlays on the §13.5 defaults, so the merged tables match
9583/// byte-for-byte. Mixing a non-default-base keyframe with this
9584/// entry-point is out of round-158 scope.
9585///
9586/// Out of round-158 scope: threading the fitter into
9587/// [`crate::stream::Vp8InterStreamEncoder`]'s `encode_frame` ladder —
9588/// the stream-driver method
9589/// [`crate::stream::Vp8InterStreamEncoder::encode_p_frame_with_refresh_and_lf_deltas_and_token_updates`]
9590/// stays on the caller-driven entry-point for now; a subsequent round
9591/// adds the analogous `_with_fitted_token_prob_updates` stream method.
9592#[allow(clippy::too_many_arguments)]
9593pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates(
9594    frame: &I420Frame,
9595    last: &crate::frame::KeyframePlanes,
9596    golden: Option<&crate::frame::KeyframePlanes>,
9597    altref: Option<&crate::frame::KeyframePlanes>,
9598    params: &KeyframeParams,
9599    refresh: &RefreshControls,
9600    lf_deltas: &LoopFilterDeltas,
9601    carried_ref_deltas: [i16; 4],
9602    carried_mode_deltas: [i16; 4],
9603) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9604    // Pass 1 — defaults + observed branch counts.
9605    let mut counts = empty_branch_counts();
9606    let (bytes_default, planes_default) = encode_p_frame_multi_ref_inner_with_counts(
9607        frame,
9608        last,
9609        golden,
9610        altref,
9611        params,
9612        refresh,
9613        lf_deltas,
9614        carried_ref_deltas,
9615        carried_mode_deltas,
9616        None,
9617        Some(&mut counts),
9618    )?;
9619
9620    // Fit. 2.0 bits of slack guards against the small body-saving
9621    // overstatement that comes from the pass-2 RD pick perturbing the
9622    // coefficient distribution slightly relative to pass-1's counts.
9623    let fitted = fit_token_prob_updates(&counts, 2.0);
9624
9625    // If no slot crossed the threshold, the default encode wins
9626    // trivially (the all-`None` path is byte-identical to the round-156
9627    // inter wire).
9628    let any_update = any_token_prob_update(&fitted);
9629    if !any_update {
9630        return Ok((bytes_default, planes_default));
9631    }
9632
9633    // Pass 2 — re-encode with the fitted updates. The picker re-runs
9634    // against the merged probabilities (RD estimator uses the merged
9635    // table), so the chosen coefficients may shift relative to pass 1.
9636    // The encoder remains self-consistent: the decoder rebuilds the
9637    // same merged table from the on-wire updates and reconstructs the
9638    // same picture.
9639    let (bytes_fitted, planes_fitted) =
9640        encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates(
9641            frame,
9642            last,
9643            golden,
9644            altref,
9645            params,
9646            refresh,
9647            lf_deltas,
9648            carried_ref_deltas,
9649            carried_mode_deltas,
9650            Some(&fitted),
9651        )?;
9652
9653    // Guard against the cost-model overstating the saving: only ship
9654    // the fitted bytes when they actually shrink the wire (or match).
9655    // Note: when we fall back we MUST also fall back to the default-
9656    // pass reconstruction, otherwise a streaming caller's next-frame
9657    // LAST slot would mis-match what the decoder will hold (the two
9658    // passes' picker outputs differ when the merged table differs).
9659    if bytes_fitted.len() <= bytes_default.len() {
9660        Ok((bytes_fitted, planes_fitted))
9661    } else {
9662        Ok((bytes_default, planes_default))
9663    }
9664}
9665
9666/// §16.2 multi-reference P-frame encoder with an automatically-fitted
9667/// §13.4 `token_prob_update()` payload (and round-150 defaults for
9668/// refresh + §9.4 deltas).
9669///
9670/// Thin wrapper over
9671/// [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`]
9672/// that uses [`RefreshControls::default`] / [`LoopFilterDeltas::default`]
9673/// and `[0; 4]` carried delta state — i.e. the configuration that makes
9674/// the round-149 / round-150 / round-151 wire byte-for-byte equivalent
9675/// to the historical [`encode_p_frame_multi_ref`] when the fitter falls
9676/// back to "no updates win" (the `bytes_fitted <= bytes_default` safety
9677/// guard).
9678pub fn encode_p_frame_multi_ref_with_fitted_token_prob_updates(
9679    frame: &I420Frame,
9680    last: &crate::frame::KeyframePlanes,
9681    golden: Option<&crate::frame::KeyframePlanes>,
9682    altref: Option<&crate::frame::KeyframePlanes>,
9683    params: &KeyframeParams,
9684) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9685    encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates(
9686        frame,
9687        last,
9688        golden,
9689        altref,
9690        params,
9691        &RefreshControls::default(),
9692        &LoopFilterDeltas::default(),
9693        [0; 4],
9694        [0; 4],
9695    )
9696}
9697
9698/// §16.2 multi-reference P-frame encoder with caller-driven §9.7 /
9699/// §9.8 reference-slot refresh control.
9700///
9701/// Extends [`encode_p_frame_zero_mv`] with optional `golden` and
9702/// `altref` reference planes; the per-MB picker scores every available
9703/// reference against the §17 / §16.2 / §16.3 / §16.4 candidate ladder
9704/// and emits whichever (`ref_frame`, mode, MV) tuple minimises
9705/// `J = SAD + lambda * (mv_ref_tree_bits + ref_frame_tree_bits + §17 mv bits)`.
9706///
9707/// `last` is required (every inter frame must hold a `LAST` reference
9708/// at the §9 three-slot ladder). `golden` and `altref` are optional;
9709/// pass `None` for a slot to disable that reference. All three planes
9710/// must share `(mb_cols, mb_rows)` with the source frame's
9711/// macroblock-grid dimensions; a mismatch is surfaced as
9712/// [`EncodeError::ReferenceDimensionsMismatch`].
9713///
9714/// `refresh` carries the five §9.7 / §9.8 reference-slot bits the
9715/// frame header emits (`refresh_golden_frame`,
9716/// `refresh_alternate_frame`, `copy_buffer_to_golden`,
9717/// `copy_buffer_to_alternate`, `refresh_last`). The wrapper
9718/// [`encode_p_frame_multi_ref`] passes [`RefreshControls::default`]
9719/// (which keeps the round-149 ladder: `refresh_last = 1`, every other
9720/// bit `0`); call this entry-point directly to express GOLDEN / ALTREF
9721/// rotation patterns (e.g. promote a low-noise reconstruction into
9722/// GOLDEN, copy LAST into ALTREF before a scene transition, hold LAST
9723/// across a synthetic disturbance). `refresh` is validated up front
9724/// with [`RefreshControls::validate`].
9725///
9726/// # Wire layout differences vs. [`encode_p_frame_zero_mv`]
9727///
9728/// * `prob_intra` stays 255 (no intra MBs this round). `prob_last`
9729///   and `prob_gf` are derived from the post-picker per-MB reference
9730///   distribution so the §16.2 selector bits compress against an
9731///   on-distribution prior (a Laplace-of-counts step clamped into
9732///   `1..=255`).
9733/// * The per-MB §19.3 `ref_frame` selector emits the chosen
9734///   reference: LAST → `B(prob_last)` reads `false`; GOLDEN →
9735///   `B(prob_last)` reads `true` then `B(prob_gf)` reads `false`;
9736///   ALTREF → both bools read `true`.
9737/// * Reconstruction reads from whichever reference's planes the
9738///   picker chose for each MB, so a single P-frame can mix LAST /
9739///   GOLDEN / ALTREF predictors.
9740/// * The §9.7 / §9.8 ladder follows `refresh`: the
9741///   `refresh_golden_frame` / `refresh_alternate_frame` bits emit
9742///   first, then the two `copy_buffer_to_*` selectors (always
9743///   transmitted; the decoder ignores the copy when the matching
9744///   refresh bit is 1 — see §9.7 page 38), then `refresh_last`.
9745///
9746/// All other behaviour (NEAREST / NEAR / NEW / SPLITMV picking,
9747/// §17.2 differential coding, §15 loop filter, §13 token emit)
9748/// matches [`encode_p_frame_zero_mv`].
9749///
9750/// `params.nbr_of_dct_partitions` (1 / 2 / 4 / 8) controls the §9.5
9751/// token-partition layout: macroblock rows are distributed round-robin
9752/// across the partitions per the §20.4 row-loop (row `r` → partition
9753/// `r % N`). This is a layout reorganisation only — the residual coding
9754/// inside each partition is bit-identical to the 1-partition case, so
9755/// the self-decoded picture is unchanged across all four legal values
9756/// and the wire grows by `(N - 1) * 3` bytes of size table plus
9757/// `(N - 1) * 4` bytes of extra §7.3 flush trailers. Values outside
9758/// the `1 | 2 | 4 | 8` set are rejected with
9759/// [`EncodeError::InvalidDctPartitionCount`] before the per-MB pick
9760/// walk runs.
9761pub fn encode_p_frame_multi_ref_with_refresh(
9762    frame: &I420Frame,
9763    last: &crate::frame::KeyframePlanes,
9764    golden: Option<&crate::frame::KeyframePlanes>,
9765    altref: Option<&crate::frame::KeyframePlanes>,
9766    params: &KeyframeParams,
9767    refresh: &RefreshControls,
9768) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9769    encode_p_frame_multi_ref_inner(
9770        frame,
9771        last,
9772        golden,
9773        altref,
9774        params,
9775        refresh,
9776        &LoopFilterDeltas::default(),
9777        [0; 4],
9778        [0; 4],
9779        None,
9780    )
9781}
9782
9783/// §16.2 multi-reference P-frame encoder with caller-driven §9.7 /
9784/// §9.8 reference-slot refresh control **and** round-160 / round-161
9785/// §11 intra-within-inter MB picking.
9786///
9787/// Extends [`encode_p_frame_multi_ref_with_refresh`] with the
9788/// round-160 per-MB intra candidate ladder, widened in round 161 to
9789/// score the full §11.2 × §11.4 whole-block intra grid (4 luma × 4
9790/// chroma = 16 candidates, `B_PRED` excluded). In addition to scoring
9791/// the §16 inter ladder (ZEROMV / NEARESTMV / NEARMV / NEWMV / SPLITMV
9792/// across every available reference frame), the picker scores every
9793/// whole-block intra `(y_mode, uv_mode)` pair against the running
9794/// in-frame neighbours. Whichever of (best inter pick, J-best intra)
9795/// has the lower `J + lambda * is_inter_mb-bit` wins per MB; when the
9796/// intra candidate wins on at least one MB the §9.10 `prob_intra` byte
9797/// drops below 255 and the §16.1 intra-mode-tree path emits on those
9798/// MBs, with the chosen Y / UV mode tree-encoded against the §16.1
9799/// defaults.
9800///
9801/// Decoder side: zero changes. The bytes re-enter
9802/// [`crate::state::Vp8DecoderState::decode_frame`] on a fresh decoder
9803/// state; the §16.1 `parse_inter_frame_intra_macroblock_modes` walker
9804/// + the keyframe per-MB reconstructor handle the intra-on-interframe
9805///   branch the same way they handle a key frame's intra MBs.
9806///
9807/// Wire compatibility: with a `pixels` content that never makes intra
9808/// beat inter (e.g. a flat or low-detail source where the §17 motion
9809/// search resolves to a near-zero residual), the picker stays
9810/// inter-only, `prob_intra` is fitted to `1` (the §16 spec-neutral
9811/// "no intra MB" value clamped up from 0 — the `is_inter_mb = true`
9812/// bit then codes at probability 255/256, costing ~6 bits per frame
9813/// on top of the historical "prob_intra = 255" path's ~0). Wire
9814/// growth is therefore bounded by a frame-constant ~6 bits ≈ 1 byte
9815/// even in the pathological no-intra-pick case.
9816pub fn encode_p_frame_multi_ref_with_refresh_and_intra_pick(
9817    frame: &I420Frame,
9818    last: &crate::frame::KeyframePlanes,
9819    golden: Option<&crate::frame::KeyframePlanes>,
9820    altref: Option<&crate::frame::KeyframePlanes>,
9821    params: &KeyframeParams,
9822    refresh: &RefreshControls,
9823) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9824    refresh.validate()?;
9825    encode_p_frame_multi_ref_inner_with_counts_and_pick(
9826        frame,
9827        last,
9828        golden,
9829        altref,
9830        params,
9831        refresh,
9832        &LoopFilterDeltas::default(),
9833        [0; 4],
9834        [0; 4],
9835        None,
9836        None,
9837        true,
9838        false,
9839    )
9840}
9841
9842/// Backward-compatible wrapper for
9843/// [`encode_p_frame_multi_ref_with_refresh_and_intra_pick`]: passes
9844/// [`RefreshControls::default`] so the wire ladder matches the
9845/// round-149 hardwired refresh pattern (`refresh_last = 1`, every
9846/// other §9.7 / §9.8 bit `0`) while the round-160 / round-161
9847/// intra-pick path runs.
9848pub fn encode_p_frame_multi_ref_with_intra_pick(
9849    frame: &I420Frame,
9850    last: &crate::frame::KeyframePlanes,
9851    golden: Option<&crate::frame::KeyframePlanes>,
9852    altref: Option<&crate::frame::KeyframePlanes>,
9853    params: &KeyframeParams,
9854) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9855    encode_p_frame_multi_ref_with_refresh_and_intra_pick(
9856        frame,
9857        last,
9858        golden,
9859        altref,
9860        params,
9861        &RefreshControls::default(),
9862    )
9863}
9864
9865/// §16.2 multi-reference P-frame encoder with caller-driven §9.7 /
9866/// §9.8 reference-slot refresh control, caller-driven §9.4 per-
9867/// reference / per-mode `loop_filter_delta` layer, **and** round-160 /
9868/// round-161 §11 intra-within-inter MB picking.
9869///
9870/// Composition of
9871/// [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas`] (round 151
9872/// caller-driven §9.4 layer + carried-state inputs) and
9873/// [`encode_p_frame_multi_ref_with_refresh_and_intra_pick`] (round
9874/// 160 / 161 §11 picker toggle). Closes the round-162 next-step
9875/// follow-up that called out the missing composition: the §9.4
9876/// deltas and the intra-pick were each exposed individually but never
9877/// together. This entry-point lets a caller drive both knobs in the
9878/// same call.
9879///
9880/// Argument shape matches
9881/// [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas`] exactly —
9882/// the intra-pick toggle is implicit (this function always engages
9883/// it, just like
9884/// [`encode_p_frame_multi_ref_with_refresh_and_intra_pick`]). Callers
9885/// that want the §9.4 layer without the intra picker stay on the
9886/// non-intra-pick entry-point.
9887///
9888/// Wire compatibility:
9889///
9890/// * Calling with [`LoopFilterDeltas::default`] + carried `[0; 4]` /
9891///   `[0; 4]` reproduces
9892///   [`encode_p_frame_multi_ref_with_refresh_and_intra_pick`]
9893///   byte-for-byte. The §9.4 delta layer is gated on `lf_deltas.enabled`
9894///   exactly as on the non-intra-pick path.
9895/// * Calling with `pick_intra` engaged on a source where intra never
9896///   beats inter (a flat or near-flat P-frame against a populated
9897///   LAST) yields a wire whose `prob_intra` byte sits at `1` (the
9898///   §16 spec-neutral "no intra MB" value clamped up from the
9899///   fitter's `fit_prob_l8(0, count_inter)` output) instead of `255`
9900///   — the same ~6 bits ≈ 1 byte frame-constant bound documented on
9901///   [`encode_p_frame_multi_ref_with_refresh_and_intra_pick`].
9902///
9903/// `refresh` is validated up front via [`RefreshControls::validate`];
9904/// `lf_deltas` is validated via [`LoopFilterDeltas::validate`].
9905#[allow(clippy::too_many_arguments)]
9906pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick(
9907    frame: &I420Frame,
9908    last: &crate::frame::KeyframePlanes,
9909    golden: Option<&crate::frame::KeyframePlanes>,
9910    altref: Option<&crate::frame::KeyframePlanes>,
9911    params: &KeyframeParams,
9912    refresh: &RefreshControls,
9913    lf_deltas: &LoopFilterDeltas,
9914    carried_ref_deltas: [i16; 4],
9915    carried_mode_deltas: [i16; 4],
9916) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9917    refresh.validate()?;
9918    lf_deltas.validate()?;
9919    encode_p_frame_multi_ref_inner_with_counts_and_pick(
9920        frame,
9921        last,
9922        golden,
9923        altref,
9924        params,
9925        refresh,
9926        lf_deltas,
9927        carried_ref_deltas,
9928        carried_mode_deltas,
9929        None,
9930        None,
9931        true,
9932        false,
9933    )
9934}
9935
9936/// §16.2 multi-reference P-frame encoder composing the round-160 / 161 §11
9937/// intra-within-inter MB picker **with** the round-157 / 158 §13.4 token-
9938/// prob observed-counts fitter, on top of the caller-driven §9.7 / §9.8
9939/// reference-slot refresh control and the §9.4 per-reference / per-mode
9940/// loop-filter delta layer.
9941///
9942/// Composition of:
9943///
9944/// * [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick`]
9945///   (round-163 §11 picker toggle on the refresh + §9.4 deltas axis), and
9946/// * [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates`]
9947///   (round-158 two-pass fitter on the refresh + §9.4 deltas axis).
9948///
9949/// Closes round-164 follow-up item (5): the §11 picker and the §13.4
9950/// fitter were each composed individually with the refresh + lf-deltas
9951/// axis, but never together. This entry-point drives both knobs in the
9952/// same call — same shape as the two single-knob siblings, with `pick_intra`
9953/// engaged on both fitter passes.
9954///
9955/// Internally takes two passes:
9956///
9957///   1. Encode with the §13.5 defaults — `token_updates = None` — and
9958///      `pick_intra = true`, collecting per-position branch counts via
9959///      [`encode_p_frame_multi_ref_inner_with_counts_and_pick`]'s
9960///      `counts` side-channel.
9961///   2. Run [`fit_token_prob_updates`] (slack 2.0 — matches every other
9962///      inter fitter) to derive a [`TokenProbUpdates`] payload that nets
9963///      a positive saving, then re-encode with that payload and
9964///      `pick_intra = true`.
9965///
9966/// If the fitter returns an all-`None` payload (no slot crossed the
9967/// saving threshold) **or** the fitted re-encode is larger than the
9968/// default-encode wire (the saving estimate is against pass-1's
9969/// coefficient distribution; pass-2's RD pick perturbs it slightly), the
9970/// default-encode bytes / planes are returned instead — so this entry-
9971/// point is guaranteed `<=` the
9972/// [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick`]
9973/// wire on every input. **When the fallback fires we also fall back to
9974/// the pass-1 planes** (matching the round-158 sibling) so a streaming
9975/// caller's LAST never mis-matches the decoder's reconstruction.
9976///
9977/// `refresh` is validated up front via [`RefreshControls::validate`];
9978/// `lf_deltas` is validated via [`LoopFilterDeltas::validate`].
9979///
9980/// **Carried-base assumption.** Same as the round-158 sibling: this
9981/// function assumes the prior key frame was emitted with the §13.5
9982/// defaults (i.e. either [`encode_keyframe`] /
9983/// [`encode_keyframe_with_reconstruction`], or
9984/// [`encode_keyframe_with_token_prob_updates`] called with an all-`None`
9985/// array). Mixing a non-default-base keyframe with this entry-point is
9986/// out of round-165 scope.
9987#[allow(clippy::too_many_arguments)]
9988pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick_and_fitted_token_prob_updates(
9989    frame: &I420Frame,
9990    last: &crate::frame::KeyframePlanes,
9991    golden: Option<&crate::frame::KeyframePlanes>,
9992    altref: Option<&crate::frame::KeyframePlanes>,
9993    params: &KeyframeParams,
9994    refresh: &RefreshControls,
9995    lf_deltas: &LoopFilterDeltas,
9996    carried_ref_deltas: [i16; 4],
9997    carried_mode_deltas: [i16; 4],
9998) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
9999    refresh.validate()?;
10000    lf_deltas.validate()?;
10001
10002    // Pass 1 — §13.5 defaults + observed branch counts. The §11 intra
10003    // picker runs on this pass so the recorded counts already reflect
10004    // the intra/inter MB mix that will reappear on pass 2.
10005    let mut counts = empty_branch_counts();
10006    let (bytes_default, planes_default) = encode_p_frame_multi_ref_inner_with_counts_and_pick(
10007        frame,
10008        last,
10009        golden,
10010        altref,
10011        params,
10012        refresh,
10013        lf_deltas,
10014        carried_ref_deltas,
10015        carried_mode_deltas,
10016        None,
10017        Some(&mut counts),
10018        true,
10019        false,
10020    )?;
10021
10022    // Fit. 2.0 bits of slack — matches every other inter fitter and
10023    // guards against the small overstatement of saving that comes from
10024    // pass-2's RD pick perturbing the coefficient distribution slightly
10025    // relative to pass-1's counts.
10026    let fitted = fit_token_prob_updates(&counts, 2.0);
10027
10028    // If no slot crossed the threshold, the default encode wins trivially
10029    // (the all-`None` path is byte-identical to the round-163
10030    // _intra_pick wire).
10031    let any_update = any_token_prob_update(&fitted);
10032    if !any_update {
10033        return Ok((bytes_default, planes_default));
10034    }
10035
10036    // Pass 2 — re-encode with the fitted updates AND `pick_intra = true`
10037    // so the picker re-runs against the merged probabilities (the RD
10038    // estimator uses the merged table). The encoder remains self-
10039    // consistent: the decoder rebuilds the same merged table from the
10040    // on-wire updates and reconstructs the same picture.
10041    let (bytes_fitted, planes_fitted) = encode_p_frame_multi_ref_inner_with_counts_and_pick(
10042        frame,
10043        last,
10044        golden,
10045        altref,
10046        params,
10047        refresh,
10048        lf_deltas,
10049        carried_ref_deltas,
10050        carried_mode_deltas,
10051        Some(&fitted),
10052        None,
10053        true,
10054        false,
10055    )?;
10056
10057    // Bytes-vs-default safety guard. Falling back also drops the pass-2
10058    // planes — a streaming caller's next-frame LAST slot must match the
10059    // decoder's reconstruction from the bytes we just shipped.
10060    if bytes_fitted.len() <= bytes_default.len() {
10061        Ok((bytes_fitted, planes_fitted))
10062    } else {
10063        Ok((bytes_default, planes_default))
10064    }
10065}
10066
10067/// Orthogonal per-frame quality/size feature toggles for the generic
10068/// inter front door
10069/// [`encode_p_frame_multi_ref_with_refresh_and_coding_options`].
10070///
10071/// Each flag switches on one already-proven inter encoder feature; the
10072/// all-`false` default reproduces
10073/// [`encode_p_frame_multi_ref_with_refresh`] byte-for-byte. This struct
10074/// replaces the combinatorial `_intra_pick` / `_auto_loop_filter` /
10075/// `_fitted_token_prob_updates` function-name ladder for callers (like
10076/// the lagged stream driver) that need the features **combined**.
10077#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
10078#[non_exhaustive]
10079pub struct InterCodingOptions {
10080    /// §11 intra-within-inter picker: every MB additionally scores the
10081    /// 16 whole-block `(y_mode, uv_mode)` intra candidates against the
10082    /// best inter pick — the
10083    /// [`encode_p_frame_multi_ref_with_refresh_and_intra_pick`]
10084    /// behaviour.
10085    pub intra_pick: bool,
10086    /// RD-select the §9.4 `loop_filter_level` / sharpness per frame
10087    /// (ignoring `params.loop_filter_level`) — the
10088    /// [`encode_p_frame_multi_ref_auto_loop_filter`] behaviour, but
10089    /// composable with any refresh ladder and the other toggles.
10090    pub auto_loop_filter: bool,
10091    /// Two-pass §13.4 `token_prob_update()` fit (defaults pass →
10092    /// [`fit_token_prob_updates`] → fitted pass → smaller wire ships).
10093    pub fitted_token_prob_updates: bool,
10094    /// The rate-distortion search at an [`EncodeEffort`] level. `None`
10095    /// (the default) is the original exhaustive search — the bytes of the
10096    /// option-less entry points, kept for compatibility; it is both
10097    /// slower and less rate-efficient than any level.
10098    pub effort: Option<EncodeEffort>,
10099    /// Thread budget for the encode. `0` and `1` both mean serial (the
10100    /// default); with `n > 1` the macroblock search runs as a
10101    /// macroblock-row wavefront on up to `n` scoped threads that end
10102    /// with the call. The output bytes are the same for every budget.
10103    pub threads: usize,
10104    /// §13.4 updates the search prices tokens against instead of the
10105    /// §13.5 defaults — typically the
10106    /// [`InterEncoded::token_prob_updates`] of the previous frame. With
10107    /// an [`effort`](Self::effort) level and
10108    /// [`fitted_token_prob_updates`](Self::fitted_token_prob_updates)
10109    /// they only steer the search and the frame ships its own fit;
10110    /// without the fit they are shipped as given. (The two-pass fit of
10111    /// the original search — `fitted_token_prob_updates` without an
10112    /// effort level — ignores them.)
10113    pub search_token_probs: Option<TokenProbUpdates>,
10114}
10115
10116/// A finished inter-frame encode with the §13.4 table it carries — the
10117/// result of [`encode_p_frame_detailed`].
10118#[derive(Debug, Clone)]
10119#[non_exhaustive]
10120pub struct InterEncoded {
10121    /// The VP8 inter frame.
10122    pub bytes: Vec<u8>,
10123    /// The macroblock-aligned post-§15 reconstruction.
10124    pub reconstruction: crate::frame::KeyframePlanes,
10125    /// The §13.4 token-probability updates the frame carries (`None`
10126    /// when it codes against the §13.5 defaults).
10127    pub token_prob_updates: Option<TokenProbUpdates>,
10128}
10129
10130impl InterCodingOptions {
10131    /// Select the rate-distortion search at effort level `v`.
10132    #[must_use]
10133    pub fn with_effort(mut self, v: EncodeEffort) -> Self {
10134        self.effort = Some(v);
10135        self
10136    }
10137
10138    /// Set `threads`.
10139    #[must_use]
10140    pub fn with_threads(mut self, v: usize) -> Self {
10141        self.threads = v;
10142        self
10143    }
10144
10145    /// The speed controls these options carry.
10146    fn speed(&self) -> inter::InterSpeed {
10147        inter::InterSpeed {
10148            effort: self.effort,
10149            threads: self.threads,
10150            fit_token_probs: self.fitted_token_prob_updates,
10151            search_token_probs: self.search_token_probs,
10152        }
10153    }
10154
10155    /// Set `search_token_probs`.
10156    #[must_use]
10157    pub fn with_search_token_probs(mut self, v: Option<TokenProbUpdates>) -> Self {
10158        self.search_token_probs = v;
10159        self
10160    }
10161
10162    /// Set `intra_pick`.
10163    #[must_use]
10164    pub fn with_intra_pick(mut self, v: bool) -> Self {
10165        self.intra_pick = v;
10166        self
10167    }
10168
10169    /// Set `auto_loop_filter`.
10170    #[must_use]
10171    pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
10172        self.auto_loop_filter = v;
10173        self
10174    }
10175
10176    /// Set `fitted_token_prob_updates`.
10177    #[must_use]
10178    pub fn with_fitted_token_prob_updates(mut self, v: bool) -> Self {
10179        self.fitted_token_prob_updates = v;
10180        self
10181    }
10182}
10183
10184/// Generic §16.2 multi-reference P-frame front door combining the §11
10185/// intra-within-inter picker, the §9.4 auto-loop-filter selector, and
10186/// the §13.4 fitted token-prob-update emission behind one
10187/// [`InterCodingOptions`] toggle set, with caller-driven §9.7 / §9.8
10188/// refresh control.
10189///
10190/// Equivalences (each pinned by `tests/encoder_coding_options.rs`):
10191///
10192/// * `options == Default` — byte-identical to
10193///   [`encode_p_frame_multi_ref_with_refresh`];
10194/// * only `intra_pick` — byte-identical to
10195///   [`encode_p_frame_multi_ref_with_refresh_and_intra_pick`];
10196/// * only `auto_loop_filter` (with the default refresh ladder) —
10197///   byte-identical to [`encode_p_frame_multi_ref_auto_loop_filter`]
10198///   minus that entry's hardwired intra pick — pass
10199///   `intra_pick: true, auto_loop_filter: true` for the exact match;
10200/// * `intra_pick + fitted_token_prob_updates` — byte-identical to
10201///   [`encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick_and_fitted_token_prob_updates`]
10202///   at default `LoopFilterDeltas` / zero carried deltas.
10203///
10204/// The §9.4 per-reference / per-mode delta layer stays off on this
10205/// entry (`LoopFilterDeltas::default()`, zero carried state) — a caller
10206/// that threads LF deltas across frames should keep using the explicit
10207/// `_with_refresh_and_lf_deltas_*` ladder.
10208///
10209/// Returns the wire bytes plus the matching post-§15 reconstruction
10210/// planes (what the decoder's refreshed slots will hold).
10211pub fn encode_p_frame_multi_ref_with_refresh_and_coding_options(
10212    frame: &I420Frame,
10213    last: &crate::frame::KeyframePlanes,
10214    golden: Option<&crate::frame::KeyframePlanes>,
10215    altref: Option<&crate::frame::KeyframePlanes>,
10216    params: &KeyframeParams,
10217    refresh: &RefreshControls,
10218    options: &InterCodingOptions,
10219) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10220    encode_p_frame_options_and_segmentation(
10221        frame, last, golden, altref, params, refresh, options, None,
10222    )
10223}
10224
10225/// §9.3 / §10 segmentation layer for the inter (P-frame) encoder — the
10226/// round-387 companion of the keyframe path's [`AdaptiveQuantConfig`].
10227///
10228/// Macroblocks are classified into four segments by §10 source-luma
10229/// variance ([`AdaptiveQuantConfig::variance_boundaries`] semantics);
10230/// each segment carries a §9.3 `quantizer_update` delta (added to the
10231/// frame `y_ac_qi`, clamped to `0..=127`) and, optionally, a §9.3
10232/// `loop_filter_update` delta (added to the frame filter level, clamped
10233/// to `0..=63` per §20.6). The per-MB RD picker prices every candidate
10234/// at its segment's quantiser, so flat segments genuinely code coarser
10235/// and busy segments finer — activity-masking AQ on P-frames.
10236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10237#[non_exhaustive]
10238pub struct InterSegmentationConfig {
10239    /// Three ascending luma-variance boundaries splitting macroblocks
10240    /// into the four segments (see
10241    /// [`AdaptiveQuantConfig::variance_boundaries`]).
10242    pub variance_boundaries: [u32; 3],
10243    /// Per-segment §10 `quantizer_update_value` deltas (signed,
10244    /// magnitude ≤ 127), added to the frame `y_ac_qi` in delta mode.
10245    pub quant_delta: [i8; 4],
10246    /// Optional per-segment §10 loop-filter deltas (signed, magnitude
10247    /// ≤ 63). `None` omits the §9.3 loop-filter feature entirely (every
10248    /// MB filters at the frame base level).
10249    pub lf_delta: Option<[i8; 4]>,
10250}
10251
10252impl InterSegmentationConfig {
10253    /// Set `variance_boundaries`.
10254    #[must_use]
10255    pub fn with_variance_boundaries(mut self, v: [u32; 3]) -> Self {
10256        self.variance_boundaries = v;
10257        self
10258    }
10259
10260    /// Set `quant_delta`.
10261    #[must_use]
10262    pub fn with_quant_delta(mut self, v: [i8; 4]) -> Self {
10263        self.quant_delta = v;
10264        self
10265    }
10266
10267    /// Set `lf_delta`.
10268    #[must_use]
10269    pub fn with_lf_delta(mut self, v: Option<[i8; 4]>) -> Self {
10270        self.lf_delta = v;
10271        self
10272    }
10273}
10274
10275impl Default for InterSegmentationConfig {
10276    /// The [`AdaptiveQuantConfig`] default gradient: flat → coarser,
10277    /// detailed → finer; no loop-filter feature.
10278    fn default() -> Self {
10279        InterSegmentationConfig {
10280            variance_boundaries: [
10281                SEGMENT_VARIANCE_THRESHOLDS[1],
10282                SEGMENT_VARIANCE_THRESHOLDS[2],
10283                SEGMENT_VARIANCE_THRESHOLDS[3],
10284            ],
10285            quant_delta: [8, 0, -6, -12],
10286            lf_delta: None,
10287        }
10288    }
10289}
10290
10291/// §16.2 multi-reference P-frame encoder with §9.3 / §10 **segment-based
10292/// adaptive quantisation** (and optionally the per-segment loop-filter
10293/// feature), composable with the full [`InterCodingOptions`] toggle set
10294/// and caller-driven §9.7 / §9.8 refresh control.
10295///
10296/// The inter mirror of [`encode_keyframe_adaptive_quant`]: each MB is
10297/// classified by §10 source-luma variance, quantised and RD-priced at
10298/// its segment's effective qindex, and the frame header carries the
10299/// §9.3 `update_segmentation()` block (delta-mode features + the
10300/// distribution-fitted `mb_segment_tree_probs`) while the §11 / §16
10301/// mode layer prefixes each MB with its `segment_id` — exactly the
10302/// stream the decoder's inter path resolves through its per-segment
10303/// dequant factors and the §20.6 per-segment filter override.
10304///
10305/// `lf_delta` magnitudes above 63 are rejected with
10306/// [`EncodeError::LoopFilterLevelOutOfRange`]. Returns the wire bytes
10307/// plus the matching post-§15 reconstruction planes.
10308#[allow(clippy::too_many_arguments)]
10309pub fn encode_p_frame_multi_ref_adaptive_quant(
10310    frame: &I420Frame,
10311    last: &crate::frame::KeyframePlanes,
10312    golden: Option<&crate::frame::KeyframePlanes>,
10313    altref: Option<&crate::frame::KeyframePlanes>,
10314    params: &KeyframeParams,
10315    refresh: &RefreshControls,
10316    segmentation: &InterSegmentationConfig,
10317    options: &InterCodingOptions,
10318) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10319    if let Some(d) = segmentation.lf_delta
10320        && let Some(&bad) = d.iter().find(|v| v.unsigned_abs() > 63)
10321    {
10322        return Err(EncodeError::LoopFilterLevelOutOfRange {
10323            value: bad.unsigned_abs(),
10324        });
10325    }
10326    encode_p_frame_options_and_segmentation(
10327        frame,
10328        last,
10329        golden,
10330        altref,
10331        params,
10332        refresh,
10333        options,
10334        Some(segmentation),
10335    )
10336}
10337
10338/// Shared body of the two coding-options front doors above: the
10339/// optional two-pass §13.4 fitter around the full inter driver, with
10340/// the §9.3 / §10 segmentation layer threaded through both passes.
10341#[allow(clippy::too_many_arguments)]
10342pub(crate) fn encode_p_frame_options_and_segmentation(
10343    frame: &I420Frame,
10344    last: &crate::frame::KeyframePlanes,
10345    golden: Option<&crate::frame::KeyframePlanes>,
10346    altref: Option<&crate::frame::KeyframePlanes>,
10347    params: &KeyframeParams,
10348    refresh: &RefreshControls,
10349    options: &InterCodingOptions,
10350    segmentation: Option<&InterSegmentationConfig>,
10351) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10352    encode_p_frame_options_reporting(
10353        frame,
10354        last,
10355        golden,
10356        altref,
10357        params,
10358        refresh,
10359        options,
10360        segmentation,
10361        &mut None,
10362    )
10363}
10364
10365/// Encode an inter frame under [`InterCodingOptions`] and return, next
10366/// to the bitstream and its reconstruction, the §13.4 token-probability
10367/// updates the frame carries — the table to hand the next frame's
10368/// [`InterCodingOptions::with_search_token_probs`], so that its search
10369/// prices tokens against statistics close to its own.
10370///
10371/// The bytes and the reconstruction are those of
10372/// [`encode_p_frame_multi_ref_with_refresh_and_coding_options`].
10373#[allow(clippy::too_many_arguments)]
10374pub fn encode_p_frame_detailed(
10375    frame: &I420Frame,
10376    last: &crate::frame::KeyframePlanes,
10377    golden: Option<&crate::frame::KeyframePlanes>,
10378    altref: Option<&crate::frame::KeyframePlanes>,
10379    params: &KeyframeParams,
10380    refresh: &RefreshControls,
10381    options: &InterCodingOptions,
10382) -> Result<InterEncoded, EncodeError> {
10383    let mut shipped = None;
10384    let (bytes, reconstruction) = encode_p_frame_options_reporting(
10385        frame,
10386        last,
10387        golden,
10388        altref,
10389        params,
10390        refresh,
10391        options,
10392        None,
10393        &mut shipped,
10394    )?;
10395    Ok(InterEncoded {
10396        bytes,
10397        reconstruction,
10398        token_prob_updates: shipped,
10399    })
10400}
10401
10402/// [`encode_p_frame_options_and_segmentation`], reporting the §13.4
10403/// updates of the returned frame in `shipped`.
10404#[allow(clippy::too_many_arguments)]
10405fn encode_p_frame_options_reporting(
10406    frame: &I420Frame,
10407    last: &crate::frame::KeyframePlanes,
10408    golden: Option<&crate::frame::KeyframePlanes>,
10409    altref: Option<&crate::frame::KeyframePlanes>,
10410    params: &KeyframeParams,
10411    refresh: &RefreshControls,
10412    options: &InterCodingOptions,
10413    segmentation: Option<&InterSegmentationConfig>,
10414    shipped: &mut Option<TokenProbUpdates>,
10415) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10416    refresh.validate()?;
10417    // §9.3: the loop-filter feature value is a signed 6-bit magnitude.
10418    if let Some(d) = segmentation.and_then(|s| s.lf_delta)
10419        && let Some(&bad) = d.iter().find(|v| v.unsigned_abs() > 63)
10420    {
10421        return Err(EncodeError::LoopFilterLevelOutOfRange {
10422            value: bad.unsigned_abs(),
10423        });
10424    }
10425
10426    if !options.fitted_token_prob_updates || options.effort.is_some() {
10427        return encode_p_frame_multi_ref_inner_driven(
10428            frame,
10429            last,
10430            golden,
10431            altref,
10432            params,
10433            refresh,
10434            &LoopFilterDeltas::default(),
10435            [0; 4],
10436            [0; 4],
10437            None,
10438            None,
10439            options.intra_pick,
10440            options.auto_loop_filter,
10441            segmentation,
10442            options.speed(),
10443            Some(&mut *shipped),
10444        );
10445    }
10446
10447    // Pass 1 — §13.5 defaults + observed branch counts, with the
10448    // requested picker / auto-LF / segmentation switches active so the
10449    // recorded counts reflect the MB mix pass 2 will re-produce.
10450    // The two-pass fit searches pass one against the §13.5 defaults and
10451    // pass two against its own fit; a search-only table has no place in
10452    // it.
10453    let two_pass_speed = inter::InterSpeed {
10454        search_token_probs: None,
10455        ..options.speed()
10456    };
10457    let mut counts = empty_branch_counts();
10458    let (bytes_default, planes_default) = encode_p_frame_multi_ref_inner_driven(
10459        frame,
10460        last,
10461        golden,
10462        altref,
10463        params,
10464        refresh,
10465        &LoopFilterDeltas::default(),
10466        [0; 4],
10467        [0; 4],
10468        None,
10469        Some(&mut counts),
10470        options.intra_pick,
10471        options.auto_loop_filter,
10472        segmentation,
10473        two_pass_speed,
10474        None,
10475    )?;
10476
10477    // 2.0 bits of slack — matches every other inter fitter.
10478    let fitted = fit_token_prob_updates(&counts, 2.0);
10479    if !any_token_prob_update(&fitted) {
10480        return Ok((bytes_default, planes_default));
10481    }
10482
10483    // Pass 2 — re-encode against the merged table.
10484    let (bytes_fitted, planes_fitted) = encode_p_frame_multi_ref_inner_driven(
10485        frame,
10486        last,
10487        golden,
10488        altref,
10489        params,
10490        refresh,
10491        &LoopFilterDeltas::default(),
10492        [0; 4],
10493        [0; 4],
10494        Some(&fitted),
10495        None,
10496        options.intra_pick,
10497        options.auto_loop_filter,
10498        segmentation,
10499        two_pass_speed,
10500        None,
10501    )?;
10502
10503    // Bytes-vs-default guard; the shipped planes always match the
10504    // shipped wire so a streaming caller's slots stay in decoder
10505    // lockstep.
10506    if bytes_fitted.len() <= bytes_default.len() {
10507        *shipped = Some(fitted);
10508        Ok((bytes_fitted, planes_fitted))
10509    } else {
10510        Ok((bytes_default, planes_default))
10511    }
10512}
10513
10514/// [`encode_invisible_altref_update`] with the full
10515/// [`InterCodingOptions`] toggle set — the §9.1 `show_frame = 0` /
10516/// §9.7 `refresh_alternate_frame = 1` anchor-update frame, but with the
10517/// §9.4 auto-loop-filter selector and/or the §13.4 fitted
10518/// token-prob-update emission active on the underlying inter encode.
10519///
10520/// With `options = InterCodingOptions { intra_pick: true, ..Default }`
10521/// the wire is byte-identical to [`encode_invisible_altref_update`]
10522/// (that entry hardwires the §11 intra picker on).
10523pub fn encode_invisible_altref_update_with_coding_options(
10524    frame: &I420Frame,
10525    last: &crate::frame::KeyframePlanes,
10526    golden: Option<&crate::frame::KeyframePlanes>,
10527    altref: Option<&crate::frame::KeyframePlanes>,
10528    params: &KeyframeParams,
10529    options: &InterCodingOptions,
10530) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10531    encode_invisible_altref_update_full(frame, last, golden, altref, params, options, None)
10532}
10533
10534/// [`encode_invisible_altref_update_with_coding_options`] with the
10535/// §9.3 / §10 segmentation layer threaded through the underlying inter
10536/// encode — the anchor-side face the lagged stream driver uses when its
10537/// segmentation knob is on.
10538pub(crate) fn encode_invisible_altref_update_full(
10539    frame: &I420Frame,
10540    last: &crate::frame::KeyframePlanes,
10541    golden: Option<&crate::frame::KeyframePlanes>,
10542    altref: Option<&crate::frame::KeyframePlanes>,
10543    params: &KeyframeParams,
10544    options: &InterCodingOptions,
10545    segmentation: Option<&InterSegmentationConfig>,
10546) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10547    let refresh = RefreshControls {
10548        refresh_alternate_frame: true,
10549        refresh_last: false,
10550        ..RefreshControls::default()
10551    };
10552    let (mut bytes, planes) = encode_p_frame_options_and_segmentation(
10553        frame,
10554        last,
10555        golden,
10556        altref,
10557        params,
10558        &refresh,
10559        options,
10560        segmentation,
10561    )?;
10562    set_show_frame_bit(&mut bytes, false);
10563    Ok((bytes, planes))
10564}
10565
10566#[allow(clippy::too_many_arguments)]
10567fn encode_p_frame_multi_ref_inner(
10568    frame: &I420Frame,
10569    last: &crate::frame::KeyframePlanes,
10570    golden: Option<&crate::frame::KeyframePlanes>,
10571    altref: Option<&crate::frame::KeyframePlanes>,
10572    params: &KeyframeParams,
10573    refresh: &RefreshControls,
10574    lf_deltas: &LoopFilterDeltas,
10575    carried_ref_deltas: [i16; 4],
10576    carried_mode_deltas: [i16; 4],
10577    token_updates: Option<&TokenProbUpdates>,
10578) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10579    encode_p_frame_multi_ref_inner_with_counts_and_pick(
10580        frame,
10581        last,
10582        golden,
10583        altref,
10584        params,
10585        refresh,
10586        lf_deltas,
10587        carried_ref_deltas,
10588        carried_mode_deltas,
10589        token_updates,
10590        None,
10591        false,
10592        false,
10593    )
10594}
10595
10596/// Inter (P-frame) driver shared by every public inter entry-point.
10597///
10598/// Mirrors [`encode_keyframe_inner`]'s `counts` side-channel: when
10599/// `counts = Some(&mut c)` the §13.3 token-encode pass also records
10600/// each `(plane, band, prev_ctx, position)` bit-event into `c`
10601/// alongside its regular `BoolEncoder` write — `c`'s contents are the
10602/// only side-effect of the parameter; the emitted bytes are byte-
10603/// identical to the `counts = None` invocation with the same
10604/// `token_updates`. The walk runs `count_inter_frame_branches` against
10605/// the same `(modes, use_bpred_per_mb, all_coeffs, mb_cols, mb_rows)`
10606/// the §13.3 emit loop just consumed, so the recorded counts are bit-
10607/// for-bit the events the partitions emitted.
10608///
10609/// Used by the round-158 [`encode_p_frame_multi_ref_with_fitted_token_prob_updates`]
10610/// fitter to drive its two-pass observed-counts fitter without
10611/// duplicating the long picker/motion-search/§15 walk.
10612#[allow(clippy::too_many_arguments)]
10613fn encode_p_frame_multi_ref_inner_with_counts(
10614    frame: &I420Frame,
10615    last: &crate::frame::KeyframePlanes,
10616    golden: Option<&crate::frame::KeyframePlanes>,
10617    altref: Option<&crate::frame::KeyframePlanes>,
10618    params: &KeyframeParams,
10619    refresh: &RefreshControls,
10620    lf_deltas: &LoopFilterDeltas,
10621    carried_ref_deltas: [i16; 4],
10622    carried_mode_deltas: [i16; 4],
10623    token_updates: Option<&TokenProbUpdates>,
10624    counts: Option<&mut BranchCounts>,
10625) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10626    encode_p_frame_multi_ref_inner_with_counts_and_pick(
10627        frame,
10628        last,
10629        golden,
10630        altref,
10631        params,
10632        refresh,
10633        lf_deltas,
10634        carried_ref_deltas,
10635        carried_mode_deltas,
10636        token_updates,
10637        counts,
10638        false,
10639        false,
10640    )
10641}
10642
10643/// Same as [`encode_p_frame_multi_ref_inner_with_counts`] plus the
10644/// round-160 / round-161 `pick_intra` toggle: when `pick_intra = true`
10645/// the per-MB picker additionally scores every §11.2 × §11.4
10646/// whole-block intra `(y_mode, uv_mode)` candidate (16 in total,
10647/// `B_PRED` excluded) against the running in-frame neighbours, then
10648/// picks whichever of (best inter pick, J-best intra) wins on
10649/// `J + lambda * is_inter_mb-bit`. When `pick_intra = false` the
10650/// inter-only ladder runs (every MB stays inter; `prob_intra` is
10651/// hard-wired to 255), reproducing every pre-round-160 wire
10652/// byte-for-byte.
10653#[allow(clippy::too_many_arguments)]
10654fn encode_p_frame_multi_ref_inner_with_counts_and_pick(
10655    frame: &I420Frame,
10656    last: &crate::frame::KeyframePlanes,
10657    golden: Option<&crate::frame::KeyframePlanes>,
10658    altref: Option<&crate::frame::KeyframePlanes>,
10659    params: &KeyframeParams,
10660    refresh: &RefreshControls,
10661    lf_deltas: &LoopFilterDeltas,
10662    carried_ref_deltas: [i16; 4],
10663    carried_mode_deltas: [i16; 4],
10664    token_updates: Option<&TokenProbUpdates>,
10665    counts: Option<&mut BranchCounts>,
10666    pick_intra: bool,
10667    auto_lf: bool,
10668) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10669    encode_p_frame_multi_ref_inner_full(
10670        frame,
10671        last,
10672        golden,
10673        altref,
10674        params,
10675        refresh,
10676        lf_deltas,
10677        carried_ref_deltas,
10678        carried_mode_deltas,
10679        token_updates,
10680        counts,
10681        pick_intra,
10682        auto_lf,
10683        None,
10684        inter::InterSpeed::default(),
10685    )
10686}
10687
10688/// The complete inter (P-frame) driver — every public inter entry point
10689/// funnels here. Adds the round-387 §9.3 / §10 `segmentation` layer on
10690/// top of [`encode_p_frame_multi_ref_inner_with_counts_and_pick`]'s
10691/// toggles: when `Some(seg)`, each macroblock is classified into one of
10692/// four segments by §10 luma variance, quantised (and RD-priced) at
10693/// that segment's effective qindex, the §9.3 `update_segmentation()`
10694/// block travels in the header (quant deltas + optional loop-filter
10695/// deltas + distribution-fitted `mb_segment_tree_probs`), and the §11 /
10696/// §16 mode layer prefixes each MB with its `segment_id`. `None`
10697/// reproduces the historical wire byte-for-byte.
10698#[allow(clippy::too_many_arguments)]
10699fn encode_p_frame_multi_ref_inner_full(
10700    frame: &I420Frame,
10701    last: &crate::frame::KeyframePlanes,
10702    golden: Option<&crate::frame::KeyframePlanes>,
10703    altref: Option<&crate::frame::KeyframePlanes>,
10704    params: &KeyframeParams,
10705    refresh: &RefreshControls,
10706    lf_deltas: &LoopFilterDeltas,
10707    carried_ref_deltas: [i16; 4],
10708    carried_mode_deltas: [i16; 4],
10709    token_updates: Option<&TokenProbUpdates>,
10710    counts: Option<&mut BranchCounts>,
10711    pick_intra: bool,
10712    auto_lf: bool,
10713    segmentation: Option<&InterSegmentationConfig>,
10714    speed: inter::InterSpeed,
10715) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10716    encode_p_frame_multi_ref_inner_driven(
10717        frame,
10718        last,
10719        golden,
10720        altref,
10721        params,
10722        refresh,
10723        lf_deltas,
10724        carried_ref_deltas,
10725        carried_mode_deltas,
10726        token_updates,
10727        counts,
10728        pick_intra,
10729        auto_lf,
10730        segmentation,
10731        speed,
10732        None,
10733    )
10734}
10735
10736/// [`encode_p_frame_multi_ref_inner_full`], reporting the §13.4 updates
10737/// the frame ships in `shipped_out`.
10738#[allow(clippy::too_many_arguments)]
10739fn encode_p_frame_multi_ref_inner_driven(
10740    frame: &I420Frame,
10741    last: &crate::frame::KeyframePlanes,
10742    golden: Option<&crate::frame::KeyframePlanes>,
10743    altref: Option<&crate::frame::KeyframePlanes>,
10744    params: &KeyframeParams,
10745    refresh: &RefreshControls,
10746    lf_deltas: &LoopFilterDeltas,
10747    carried_ref_deltas: [i16; 4],
10748    carried_mode_deltas: [i16; 4],
10749    token_updates: Option<&TokenProbUpdates>,
10750    counts: Option<&mut BranchCounts>,
10751    pick_intra: bool,
10752    auto_lf: bool,
10753    segmentation: Option<&InterSegmentationConfig>,
10754    speed: inter::InterSpeed,
10755    shipped_out: Option<&mut Option<TokenProbUpdates>>,
10756) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
10757    refresh.validate()?;
10758    lf_deltas.validate()?;
10759    let width = frame.width;
10760    let height = frame.height;
10761    if width == 0 || width > 0x3FFF || height == 0 || height > 0x3FFF {
10762        return Err(EncodeError::InvalidDimensions { width, height });
10763    }
10764    if params.y_ac_qi > 127 {
10765        return Err(EncodeError::QuantIndexOutOfRange {
10766            value: params.y_ac_qi,
10767        });
10768    }
10769    if params.loop_filter_level > 63 {
10770        return Err(EncodeError::LoopFilterLevelOutOfRange {
10771            value: params.loop_filter_level,
10772        });
10773    }
10774    if params.sharpness_level > 7 {
10775        return Err(EncodeError::SharpnessLevelOutOfRange {
10776            value: params.sharpness_level,
10777        });
10778    }
10779    // §9.5 — the partition-count is validated here so a bad value is
10780    // rejected before the long mode-pick / motion-search walk runs.
10781    // `write_token_partition_count` re-validates at the actual
10782    // bitstream emission point.
10783    let num_partitions = match params.nbr_of_dct_partitions {
10784        1 | 2 | 4 | 8 => params.nbr_of_dct_partitions as usize,
10785        other => return Err(EncodeError::InvalidDctPartitionCount { value: other }),
10786    };
10787
10788    // §13 trellis aggressiveness for the inter residual emit, dialed by the
10789    // shared [`KeyframeParams::trellis_strength`] knob (the same field the
10790    // keyframe path threads). `DEFAULT` reproduces the historical bytes.
10791    let inter_trellis_strength = params.trellis_strength;
10792
10793    let mb_cols = width.div_ceil(16) as usize;
10794    let mb_rows = height.div_ceil(16) as usize;
10795    if last.mb_cols != mb_cols || last.mb_rows != mb_rows {
10796        return Err(EncodeError::ReferenceDimensionsMismatch {
10797            source: ((mb_cols * 16) as u32, (mb_rows * 16) as u32),
10798            reference: ((last.mb_cols * 16) as u32, (last.mb_rows * 16) as u32),
10799        });
10800    }
10801    if let Some(g) = golden
10802        && (g.mb_cols != mb_cols || g.mb_rows != mb_rows)
10803    {
10804        return Err(EncodeError::ReferenceDimensionsMismatch {
10805            source: ((mb_cols * 16) as u32, (mb_rows * 16) as u32),
10806            reference: ((g.mb_cols * 16) as u32, (g.mb_rows * 16) as u32),
10807        });
10808    }
10809    if let Some(a) = altref
10810        && (a.mb_cols != mb_cols || a.mb_rows != mb_rows)
10811    {
10812        return Err(EncodeError::ReferenceDimensionsMismatch {
10813            source: ((mb_cols * 16) as u32, (mb_rows * 16) as u32),
10814            reference: ((a.mb_cols * 16) as u32, (a.mb_rows * 16) as u32),
10815        });
10816    }
10817
10818    // The decoder's inter path overlays the §13.4 update payload on top
10819    // of its carried entropy state ([`Vp8DecoderState::decode_inter_frame`]
10820    // — `overlay_token_probs(self.coeff_probs, &coded.token_prob_updates)`).
10821    // We assume the prior keyframe was encoded with the §13.5 defaults
10822    // (i.e. either [`encode_keyframe`] or
10823    // [`encode_keyframe_with_token_prob_updates`] called with an
10824    // all-`None` array), in which case the carried base is
10825    // `DEFAULT_COEFF_PROBS` and the overlay reduces to
10826    // [`crate::dct_tokens::merge_default_token_probs`] on this frame's
10827    // `token_updates`. Mixing a non-default-base keyframe with this
10828    // entry-point is out of round-156 scope.
10829    //
10830    // With `token_updates = None` (or all-`None`) the merged table is
10831    // byte-identical to the §13.5 defaults and the §13.4 sub-block
10832    // reduces to the 1056-zero-flag wire — i.e. the round-155 inter
10833    // wire byte-for-byte.
10834    // The table the search prices tokens against: the caller's updates
10835    // to ship, else its search-only seed, else the §13.5 defaults.
10836    let search_updates = token_updates.or(speed.search_token_probs.as_ref());
10837    let coeff_probs = match search_updates {
10838        Some(u) => crate::dct_tokens::merge_default_token_probs(u),
10839        None => crate::dct_tokens::DEFAULT_COEFF_PROBS,
10840    };
10841    // Per-frame §13 trellis rate tables (see `TrellisRateTables`): one
10842    // build per frame, shared by every per-ref / intra-in-P mode pick.
10843    // The effort-level search (as against the original exhaustive one).
10844    let reduced_search = speed.effort.is_some();
10845    let trellis_rate_tables = (reduced_search || inter_trellis_strength.get() > 0.0)
10846        .then(|| TrellisRateTables::for_probs(&coeff_probs));
10847    let factors = crate::dequant::MbDequantFactors::from_base_and_deltas(
10848        params.y_ac_qi as i32,
10849        0,
10850        0,
10851        0,
10852        0,
10853        0,
10854    );
10855
10856    // §9.3 / §10 segmentation context: the four per-segment §14.1
10857    // dequant factor sets (delta mode on the §9.6 baseline — exactly
10858    // what the decoder's `resolve_segment_dequant_factors` rebuilds
10859    // from the header we emit below) plus the matching per-segment RD
10860    // lambdas. `None` leaves the historical single-factor path.
10861    let seg_ctx = segmentation.map(|s| {
10862        let mut seg_factors = [factors; crate::loop_filter::MAX_MB_SEGMENTS];
10863        let mut seg_lambdas = [0.0f64; crate::loop_filter::MAX_MB_SEGMENTS];
10864        for i in 0..crate::loop_filter::MAX_MB_SEGMENTS {
10865            seg_factors[i] = crate::dequant::MbDequantFactors::from_base_and_deltas(
10866                params.y_ac_qi as i32 + s.quant_delta[i] as i32,
10867                0,
10868                0,
10869                0,
10870                0,
10871                0,
10872            );
10873            seg_lambdas[i] = rd_lambda(&seg_factors[i]);
10874        }
10875        (s, seg_factors, seg_lambdas)
10876    });
10877    // Per-reference plane bundle. `Last` is always populated; the
10878    // optional Golden / AltRef refs are populated when their slot is
10879    // available.
10880    let reference_planes_last = crate::motion_comp::ReferencePlanes {
10881        y: &last.y,
10882        u: &last.u,
10883        v: &last.v,
10884        y_stride: last.y_stride,
10885        uv_stride: last.uv_stride,
10886        mb_cols: last.mb_cols,
10887        mb_rows: last.mb_rows,
10888    };
10889    let reference_planes_golden = golden.map(|g| crate::motion_comp::ReferencePlanes {
10890        y: &g.y,
10891        u: &g.u,
10892        v: &g.v,
10893        y_stride: g.y_stride,
10894        uv_stride: g.uv_stride,
10895        mb_cols: g.mb_cols,
10896        mb_rows: g.mb_rows,
10897    });
10898    let reference_planes_altref = altref.map(|a| crate::motion_comp::ReferencePlanes {
10899        y: &a.y,
10900        u: &a.u,
10901        v: &a.v,
10902        y_stride: a.y_stride,
10903        uv_stride: a.uv_stride,
10904        mb_cols: a.mb_cols,
10905        mb_rows: a.mb_rows,
10906    });
10907    // §18.3 filter set (the version=0 default tap-set is fine — every
10908    // MB has a (0,0) MV, so the convolution collapses to whole-pixel
10909    // copy and the chosen tap set never runs).
10910    let filters = crate::motion_comp::filter_set_for_version(0).taps();
10911
10912    // Running reconstruction buffer — same shape `decode_keyframe`
10913    // produces. The §18 prediction for the NEXT MB does not depend on
10914    // the current frame's already-reconstructed pixels (ZEROMV always
10915    // samples LAST, not the current frame), but we still fill this so
10916    // the §15 loop filter pass can operate on a single picture.
10917    let mut planes = crate::frame::KeyframePlanes {
10918        y: vec![0u8; mb_cols * 16 * mb_rows * 16],
10919        u: vec![0u8; mb_cols * 8 * mb_rows * 8],
10920        v: vec![0u8; mb_cols * 8 * mb_rows * 8],
10921        y_stride: mb_cols * 16,
10922        uv_stride: mb_cols * 8,
10923        mb_cols,
10924        mb_rows,
10925    };
10926
10927    // §17.2 MV-component contexts the encoder writes NEWMV diffs
10928    // against. We emit every `mv_prob_update()` F-gate as 0 (no update)
10929    // so the decoder reads against the same §17.2 defaults.
10930    let mv_contexts = crate::motion_vector::default_mv_contexts();
10931
10932    // §-non-normative RD lambda — same `q^2 / 32` shape the keyframe
10933    // RD picker uses (see `rd_lambda`).
10934    let lambda = rd_lambda(&factors);
10935
10936    // Available references for the §16.2 ref_frame selector, in the
10937    // decoder's `ref_frame_tree` walk order. LAST is always present;
10938    // GOLDEN / ALTREF appear iff the caller passed their planes.
10939    let mut available_refs: Vec<inter::RefPicture> = Vec::with_capacity(3);
10940    available_refs.push(inter::RefPicture {
10941        frame: crate::motion_comp::RefFrame::Last,
10942        planes: reference_planes_last,
10943    });
10944    if let Some(rp) = reference_planes_golden {
10945        available_refs.push(inter::RefPicture {
10946            frame: crate::motion_comp::RefFrame::Golden,
10947            planes: rp,
10948        });
10949    }
10950    if let Some(rp) = reference_planes_altref {
10951        available_refs.push(inter::RefPicture {
10952            frame: crate::motion_comp::RefFrame::AltRef,
10953            planes: rp,
10954        });
10955    }
10956
10957    // ---- Per-macroblock search (macroblock-row wavefront) ----------------
10958    //
10959    // Each macroblock's reference / mode / vector decision, its quantised
10960    // residual (as a §13.3 token tape per row) and its unfiltered
10961    // reconstruction (into `planes`). See `inter.rs`.
10962    let analysis = inter::analyse_inter_frame(
10963        &inter::InterSearch {
10964            frame,
10965            refs: &available_refs,
10966            factors: &factors,
10967            lambda,
10968            segments: seg_ctx.as_ref().map(|(s, f, l)| inter::SegmentContext {
10969                config: s,
10970                factors: *f,
10971                lambdas: *l,
10972            }),
10973            coeff_probs: &coeff_probs,
10974            rate_tables: trellis_rate_tables.as_ref(),
10975            trellis_strength: inter_trellis_strength,
10976            mv_contexts: &mv_contexts,
10977            filters,
10978            pick_intra,
10979            effort: speed.effort,
10980            mv_costs: reduced_search.then(|| inter_search::MvCostTable::new(&mv_contexts)),
10981            mb_cols,
10982            mb_rows,
10983        },
10984        &mut planes,
10985        speed.threads,
10986    )?;
10987    // The reduced search's decisions do not depend on the token
10988    // probabilities that ship, so the §13.4 fit runs on the recorded
10989    // decisions directly (2.0 bits of slack, as every other fitter).
10990    let fit_in_place = reduced_search && speed.fit_token_probs && token_updates.is_none();
10991    let fitted_in_place: Option<TokenProbUpdates> = if fit_in_place {
10992        let mut observed = empty_branch_counts();
10993        for tape in &analysis.tapes {
10994            tape.tally(&mut observed);
10995        }
10996        let fitted = fit_token_prob_updates(&observed, 2.0);
10997        any_token_prob_update(&fitted).then_some(fitted)
10998    } else {
10999        None
11000    };
11001    // What ships: the fit when it ran (possibly nothing), else the table
11002    // the search used. The tapes are coded against exactly that.
11003    let token_updates = if fit_in_place {
11004        fitted_in_place.as_ref()
11005    } else {
11006        search_updates
11007    };
11008    let emit_probs = match token_updates {
11009        Some(u) if fit_in_place => crate::dct_tokens::merge_default_token_probs(u),
11010        None if fit_in_place => crate::dct_tokens::DEFAULT_COEFF_PROBS,
11011        _ => coeff_probs,
11012    };
11013    if let Some(out) = shipped_out {
11014        *out = token_updates.filter(|u| any_token_prob_update(u)).copied();
11015    }
11016    let seg_counts = analysis.segment_counts;
11017    let records = &analysis.records;
11018    // Per-macroblock views of the decisions for the §15 loop filter and
11019    // the mode layer below.
11020    //
11021    // §15 loop-filter geometry: a whole-block inter macroblock filters
11022    // like `DC_PRED` (the "skip" rule on page 86 keys on `B_PRED ||
11023    // any-coded-coeff`), a `SPLITMV` one like `B_PRED` (internal edges
11024    // always filtered), an intra one by its own mode.
11025    let modes: Vec<MacroblockModes> = records
11026        .iter()
11027        .map(|r| MacroblockModes {
11028            segment_id: r.segment_id,
11029            mb_skip_coeff: r.skip,
11030            y_mode: if r.is_intra {
11031                r.y_mode
11032            } else if r.split.is_some() {
11033                IntraYMode::B
11034            } else {
11035                IntraYMode::Dc
11036            },
11037            subblock_modes: None,
11038            uv_mode: if r.is_intra {
11039                r.uv_mode
11040            } else {
11041                IntraUvMode::Dc
11042            },
11043        })
11044        .collect();
11045    let has_coeffs: Vec<bool> = records.iter().map(|r| r.has_coeffs).collect();
11046    // `None` marks an intra macroblock (the §9.4 / §15.2 ref_delta lookup
11047    // uses the intra slot for it).
11048    let ref_frames_out: Vec<Option<crate::motion_comp::RefFrame>> = records
11049        .iter()
11050        .map(|r| (!r.is_intra).then_some(r.ref_frame))
11051        .collect();
11052    let inter_modes_out: Vec<Option<crate::near_mv::InterMode>> = records
11053        .iter()
11054        .map(|r| (!r.is_intra).then_some(r.mode))
11055        .collect();
11056
11057    // ---- §9.10 prob_last / prob_gf fit -----------------------------------
11058    //
11059    // Now that every MB has a chosen reference, derive the L(8) wire
11060    // probabilities that minimise the §16.2 selector-bit cost over
11061    // the observed per-MB distribution. `prob_last` is "P(B(prob_last)
11062    // reads 0)" = P(LAST); `prob_gf` is "P(B(prob_gf) reads 0 | not
11063    // LAST)" = P(GOLDEN | GOLDEN ∪ ALTREF).
11064    let mut count_last: u32 = 0;
11065    let mut count_golden: u32 = 0;
11066    let mut count_altref: u32 = 0;
11067    for r in ref_frames_out.iter().flatten() {
11068        match r {
11069            crate::motion_comp::RefFrame::Last => count_last += 1,
11070            crate::motion_comp::RefFrame::Golden => count_golden += 1,
11071            crate::motion_comp::RefFrame::AltRef => count_altref += 1,
11072        }
11073    }
11074    let prob_last_fit = fit_prob_l8(count_last, count_golden + count_altref);
11075    let prob_gf_fit = fit_prob_l8(count_golden, count_altref);
11076
11077    // ---- §10 mb_segment_tree_probs fit -----------------------------------
11078    //
11079    // The §10 segment tree is: node 0 splits {0,1} vs {2,3}, node 1
11080    // splits 0 vs 1, node 2 splits 2 vs 3. Fit each node's L(8) prob to
11081    // the observed per-MB segment distribution (same `fit_prob_l8`
11082    // machinery as the §16.2 ref_frame selector above); an unvisited
11083    // node gets the neutral 128 that nothing reads.
11084    let seg_tree_probs: Option<[u8; 3]> = seg_ctx.as_ref().map(|_| {
11085        [
11086            fit_prob_l8(seg_counts[0] + seg_counts[1], seg_counts[2] + seg_counts[3]),
11087            fit_prob_l8(seg_counts[0], seg_counts[1]),
11088            fit_prob_l8(seg_counts[2], seg_counts[3]),
11089        ]
11090    });
11091
11092    // ---- §9.4 effective per-reference / per-mode delta resolution -------
11093    //
11094    // RFC 6386 §9.4: per-slot deltas persist across frames; a slot's
11095    // `delta_update_flag = 0` (`None` in `LoopFilterDeltas`) means the
11096    // decoder keeps the value it carried in from the previous frame.
11097    // The encoder's §15 post-walk filter must use the SAME effective
11098    // value the decoder will use (otherwise our reconstruction would
11099    // diverge from the wire), so resolve effective deltas here.
11100    let (effective_ref_deltas, effective_mode_deltas) =
11101        lf_deltas.effective(carried_ref_deltas, carried_mode_deltas);
11102
11103    // ---- §15 loop-filter post-pass --------------------------------------
11104    //
11105    // Base §15 config, level filled in below. `filter_type` mirrors the
11106    // bit `write_loop_filter_with_deltas` writes; the encoder's post-walk
11107    // filter must match what the decoder will run. The per-MB §9.4
11108    // reference / mode deltas are the effective (carried + this-frame)
11109    // values resolved above.
11110    let mut seg_lf_level = [0i16; crate::loop_filter::MAX_MB_SEGMENTS];
11111    if let Some((s, _, _)) = &seg_ctx
11112        && let Some(d) = s.lf_delta
11113    {
11114        for (dst, &src) in seg_lf_level.iter_mut().zip(d.iter()) {
11115            *dst = i16::from(src);
11116        }
11117    }
11118    let mut lf_config = crate::loop_filter::FrameFilterConfig {
11119        simple: params.filter_type,
11120        key_frame: false,
11121        loop_filter_level: params.loop_filter_level,
11122        sharpness_level: params.sharpness_level,
11123        // With segmentation on, each MB's §15 level resolves through
11124        // the §20.6 segment override (delta mode; an absent lf_delta
11125        // resolves to 0 exactly as the decoder's
11126        // `FrameFilterConfig::interframe` maps `loop_filter_update =
11127        // None` slots).
11128        segmentation_enabled: seg_ctx.is_some(),
11129        segment_abs: false,
11130        segment_lf_level: seg_lf_level,
11131        delta_enabled: lf_deltas.enabled,
11132        ref_delta_current: effective_ref_deltas[0],
11133        bpred_mode_delta: effective_mode_deltas[0],
11134        ref_delta_last: effective_ref_deltas[1],
11135        ref_delta_golden: effective_ref_deltas[2],
11136        ref_delta_altref: effective_ref_deltas[3],
11137        zero_mv_mode_delta: effective_mode_deltas[1],
11138        other_mv_mode_delta: effective_mode_deltas[2],
11139        split_mv_mode_delta: effective_mode_deltas[3],
11140    };
11141    // §9.4 effective loop-filter level + sharpness. With `auto_lf` the RD
11142    // selector jointly replaces `params.loop_filter_level` /
11143    // `params.sharpness_level` with the pair that minimises post-§15
11144    // reconstruction SSD against the source (clean-room; RFC 6386 is silent
11145    // on the encoder's choice). The selector runs the SAME §15 inter pass —
11146    // including the per-MB ref/mode deltas above — for each candidate, so
11147    // the chosen pair reaches the wire and decoder lockstep holds.
11148    let (eff_lf_level, eff_sharpness) = if auto_lf {
11149        let src = crate::loop_filter::SourcePlanes {
11150            width: width as usize,
11151            height: height as usize,
11152            y: frame.y,
11153            u: frame.u,
11154            v: frame.v,
11155            y_stride: frame.y_stride,
11156            uv_stride: frame.uv_stride,
11157        };
11158        let inter_info = crate::loop_filter::InterFilterInfo {
11159            ref_frames: &ref_frames_out,
11160            inter_modes: &inter_modes_out,
11161        };
11162        match speed.effort {
11163            // The original search and the top level run the full-frame
11164            // grid search (its candidates scored under the thread
11165            // budget).
11166            None | Some(EncodeEffort::Thorough) => {
11167                crate::loop_filter::select_filter_params_threaded(
11168                    &planes,
11169                    &modes,
11170                    &has_coeffs,
11171                    &lf_config,
11172                    &src,
11173                    Some(&inter_info),
11174                    speed.threads,
11175                )
11176            }
11177            // The lower levels choose the level on a sample of the
11178            // picture and keep the configured sharpness.
11179            Some(effort) => (
11180                crate::loop_filter::select_filter_level_sampled(
11181                    &planes,
11182                    &modes,
11183                    &has_coeffs,
11184                    &lf_config,
11185                    &src,
11186                    &inter_info,
11187                    if effort == EncodeEffort::Balanced {
11188                        8
11189                    } else {
11190                        16
11191                    },
11192                    speed.threads,
11193                ),
11194                params.sharpness_level.min(7),
11195            ),
11196        }
11197    } else {
11198        (params.loop_filter_level, params.sharpness_level)
11199    };
11200    lf_config.loop_filter_level = eff_lf_level;
11201    lf_config.sharpness_level = eff_sharpness;
11202    if eff_lf_level != 0 {
11203        crate::loop_filter::filter_inter_frame_flags_threaded(
11204            &mut planes,
11205            &modes,
11206            &has_coeffs,
11207            &ref_frames_out,
11208            &inter_modes_out,
11209            &lf_config,
11210            speed.threads,
11211        );
11212    }
11213
11214    // ---- §19.2 first (control) partition --------------------------------
11215    let mut hdr = BoolEncoder::new();
11216
11217    // Inter frames do NOT emit color_space / clamping_type (those are
11218    // key-frame-only per §9.2).
11219    // §9.3 — segmentation. With the round-387 segmentation layer on,
11220    // the full update_segmentation() block travels: per-segment §10
11221    // quantizer deltas (always, including explicit zeros so the
11222    // decoder's persisted state matches `seg_factors` exactly),
11223    // optional per-segment loop-filter deltas, map update, and the
11224    // distribution-fitted mb_segment_tree_probs.
11225    match (&seg_ctx, &seg_tree_probs) {
11226        (Some((s, _, _)), Some(probs)) => {
11227            let layer = UpdateSegmentationLayer {
11228                update_mb_segmentation_map: true,
11229                feature_mode_absolute: false,
11230                quantizer: [
11231                    Some(i16::from(s.quant_delta[0])),
11232                    Some(i16::from(s.quant_delta[1])),
11233                    Some(i16::from(s.quant_delta[2])),
11234                    Some(i16::from(s.quant_delta[3])),
11235                ],
11236                loop_filter: match s.lf_delta {
11237                    Some(d) => [
11238                        Some(i16::from(d[0])),
11239                        Some(i16::from(d[1])),
11240                        Some(i16::from(d[2])),
11241                        Some(i16::from(d[3])),
11242                    ],
11243                    None => [None; 4],
11244                },
11245                segment_prob: [Some(probs[0]), Some(probs[1]), Some(probs[2])],
11246            };
11247            write_update_segmentation(&mut hdr, &layer);
11248        }
11249        _ => write_segment_update_flags(&mut hdr, false),
11250    }
11251    // §9.4 — loop filter. `filter_type` follows `params.filter_type`
11252    // (false ⇒ §15.3 normal, true ⇒ §15.2 simple). The §19.2
11253    // `mb_lf_adjustments()` sub-block follows whatever the caller's
11254    // `LoopFilterDeltas` says — including the default
11255    // `loop_filter_adj_enable = 0` for the round-150 wire shape.
11256    write_loop_filter_with_deltas(
11257        &mut hdr,
11258        params.filter_type,
11259        eff_lf_level,
11260        eff_sharpness,
11261        lf_deltas,
11262    )?;
11263    // §9.5 — partition count. Macroblock rows are distributed
11264    // round-robin across the §9.5 partitions per the §20.4 row-loop
11265    // (row `r` → partition `r % N`). This is a layout reorganisation
11266    // only — the residual coding inside each partition is bit-
11267    // identical to the 1-partition case, so the self-decoded picture
11268    // is unchanged across all four legal values.
11269    write_token_partition_count(&mut hdr, params.nbr_of_dct_partitions)?;
11270    // §9.6 — quant indices (baseline only).
11271    write_quant_indices(&mut hdr, params.y_ac_qi, None, None, None, None, None)?;
11272
11273    // §9.7 / §9.8 (inter) — refresh / sign-bias / entropy ladder.
11274    // The §19.2 listing (page 122) gates the L(2) copy_buffer_to_*
11275    // fields on `if (!refresh_*_frame)`. We mirror that gating
11276    // exactly so the wire is byte-identical to what
11277    // `Vp8CodedHeader::parse` expects to read back.
11278    hdr.write_bool(128, refresh.refresh_golden_frame); // §9.7 refresh_golden_frame
11279    hdr.write_bool(128, refresh.refresh_alternate_frame); // §9.7 refresh_alternate_frame
11280    if !refresh.refresh_golden_frame {
11281        hdr.write_literal(refresh.copy_buffer_to_golden as u32, 2); // copy_buffer_to_golden
11282    }
11283    if !refresh.refresh_alternate_frame {
11284        hdr.write_literal(refresh.copy_buffer_to_alternate as u32, 2); // copy_buffer_to_alternate
11285    }
11286    hdr.write_bool(128, false); // sign_bias_golden
11287    hdr.write_bool(128, false); // sign_bias_alternate
11288    hdr.write_bool(128, false); // refresh_entropy_probs
11289    hdr.write_bool(128, refresh.refresh_last); // §9.8 refresh_last
11290
11291    // §13 / §9.9 — token-prob update sub-block. With
11292    // `token_updates = Some(u)` the per-position replacement layer is
11293    // written and the merged `coeff_probs` above is what tokens are
11294    // coded against; the decoder reads the same updates and overlays
11295    // them on its carried state to rebuild the same table. With `None`
11296    // every flag is 0 and the §13.5 defaults stay in force — byte-
11297    // identical to the round-155 inter wire.
11298    match token_updates {
11299        Some(u) => write_token_prob_updates(&mut hdr, u, &COEFF_UPDATE_PROBS_FLAT),
11300        None => write_no_token_prob_updates(&mut hdr, &COEFF_UPDATE_PROBS_FLAT),
11301    }
11302
11303    // §9.11 — mb_no_skip_coeff enabled. The exhaustive search keeps the
11304    // balanced `prob_skip_false` its bytes were pinned with; the reduced
11305    // search fits it to the frame's skip decisions.
11306    let prob_skip_false = if reduced_search {
11307        let skipped = records.iter().filter(|r| r.skip).count() as u32;
11308        fit_prob_l8(records.len() as u32 - skipped, skipped)
11309    } else {
11310        128u8
11311    };
11312    write_mb_no_skip_coeff(&mut hdr, true, prob_skip_false);
11313
11314    // §9.10 — inter-only tail:
11315    //   prob_intra (L8), prob_last (L8), prob_gf (L8),
11316    //   intra_y_mode_prob_update gate (F? L8 × 4),
11317    //   intra_uv_mode_prob_update gate (F? L8 × 3),
11318    //   mv_prob_update() (38 F? L7 entries).
11319    //
11320    // When `pick_intra = false` (every pre-r160 entry-point):
11321    //   prob_intra = 255 forces every MB to read as inter (the decoder
11322    //   does `dec.read_bool(prob_intra)` and `prob_intra = 255` makes
11323    //   the result "true" almost-always for the bool we'll emit). We
11324    //   emit `is_inter_mb = true` for every MB, which against
11325    //   `prob_intra = 255` costs essentially zero bits.
11326    //
11327    // When `pick_intra = true` (round 160 intra-within-inter
11328    // entry-point): prob_intra is fitted to the picker's observed
11329    // (intra, inter) per-MB count distribution via [`fit_prob_l8`].
11330    // `prob_intra` is P(`is_inter_mb == false`) ⇒
11331    // `fit_prob_l8(intra_count, inter_count)`. With no MBs picking
11332    // intra the fitter returns 1 (clamped from 0) — `is_inter_mb`
11333    // codes cheaply (one bit per MB at probability 255/256). With
11334    // every MB picking intra the fitter returns 255.
11335    //
11336    // prob_last / prob_gf are fitted to the picker's observed per-MB
11337    // distribution by [`fit_prob_l8`] above so the §16.2 selector bits
11338    // compress against an on-distribution prior. When every MB picks
11339    // LAST (no GOLDEN / ALTREF was passed or LAST always won the J
11340    // trade) `prob_last_fit == 255` and the path collapses to the
11341    // single-ref encoder's behaviour. When the GOLDEN / ALTREF refs
11342    // were not provided to the caller, both counts are zero and
11343    // `fit_prob_l8` returns the spec-neutral 128 — that prob is never
11344    // read in that case, since `prob_last_fit == 255` forces every
11345    // selector to LAST.
11346    let prob_intra: u8 = if pick_intra {
11347        let count_intra: u32 = records.iter().filter(|r| r.is_intra).count() as u32;
11348        let count_inter: u32 = records.len() as u32 - count_intra;
11349        fit_prob_l8(count_intra, count_inter)
11350    } else {
11351        255
11352    };
11353    let prob_last: u8 = prob_last_fit;
11354    let prob_gf: u8 = prob_gf_fit;
11355    hdr.write_literal(prob_intra as u32, 8);
11356    hdr.write_literal(prob_last as u32, 8);
11357    hdr.write_literal(prob_gf as u32, 8);
11358    // intra_y_mode_prob_update gate: no update.
11359    hdr.write_bool(128, false);
11360    // intra_uv_mode_prob_update gate: no update.
11361    hdr.write_bool(128, false);
11362    // mv_prob_update(): every F flag = 0, against the §17.2
11363    // MV_UPDATE_PROBS table. The encoder mirrors the decoder's
11364    // `parse_mv_prob_update` walk.
11365    for ctx in MV_UPDATE_PROBS_FLAT.iter() {
11366        hdr.write_bool(*ctx, false);
11367    }
11368
11369    // ---- §11 / §16 macroblock-mode layer --------------------------------
11370    //
11371    // For each MB we emit (in §19.3 order):
11372    //   1. mb_skip_coeff (when mb_no_skip_coeff = 1)
11373    //   2. is_inter_mb (against prob_intra)
11374    //   3. ref_frame selector (against prob_last; LAST = false)
11375    //   4. inter-mode tree walk (ZEROMV = "0", NEWMV = "1110",
11376    //      SPLITMV = "1111")
11377    //   5. NEWMV: §17.2 row + column MV differential, written against
11378    //      the §17.2 default MV contexts (the same defaults the
11379    //      decoder reads with because we emit `mv_prob_update()` with
11380    //      every F-gate = 0 above).
11381    //      SPLITMV: §16.4 `mvpartition_tree` partition id, then for
11382    //      each partition group the §16.4 `sub_mv_ref_tree` mode at
11383    //      the group anchor's left/above context, with NEW4X4 modes
11384    //      followed by their §17.2 component differential.
11385    //
11386    // The §16.3 census determines the four probabilities the inter-
11387    // mode tree's bool reads, and depends on the already-decoded
11388    // neighbours' resolved `ref_frame` + `mv` (+ `is_split` /
11389    // `split_mvs` for SPLITMV neighbours). We re-run the census here
11390    // against the SAME neighbour state the search loop walked above,
11391    // so the bits we write are consumed at exactly the probabilities
11392    // the decoder reads them at.
11393    let mut above_mb: Vec<crate::near_mv::MbInfo> = vec![crate::near_mv::MbInfo::border(); mb_cols];
11394
11395    for mb_row in 0..mb_rows {
11396        let mut left_mb = crate::near_mv::MbInfo::border();
11397        let mut aboveleft_mb = crate::near_mv::MbInfo::border();
11398        for (mb_col, above_slot) in above_mb.iter_mut().enumerate() {
11399            let raster = mb_row * mb_cols + mb_col;
11400            let mb = &modes[raster];
11401            let record = &records[raster];
11402            let is_intra = record.is_intra;
11403
11404            // 0. segment_id (§10) — only when the frame updates the
11405            //    segmentation map. Coded via the §10 mb_segment_tree
11406            //    against the fitted probs, BEFORE mb_skip_coeff,
11407            //    matching the decoder's inter read order
11408            //    (segment_id → mb_skip_coeff → is_inter_mb).
11409            if let Some(probs) = &seg_tree_probs {
11410                let sid = mb.segment_id.unwrap_or(0);
11411                hdr.write_treed(&crate::macroblock::MB_SEGMENT_TREE, |i| probs[i], sid);
11412            }
11413
11414            // 1. mb_skip_coeff (mb_no_skip_coeff = 1).
11415            hdr.write_bool(prob_skip_false, mb.mb_skip_coeff);
11416            // 2. is_inter_mb. Round 160's intra-pick path can land
11417            //    here with `is_intra = true`, in which case we write a
11418            //    `false` against `prob_intra` and the §16.1 intra
11419            //    branch runs below. With `pick_intra = false` (every
11420            //    pre-r160 entry-point) `is_intra` is always `false`,
11421            //    `prob_intra = 255`, and the wire is byte-identical to
11422            //    the historical inter-only path.
11423            hdr.write_bool(prob_intra, !is_intra);
11424
11425            if is_intra {
11426                // §16.1 intra-on-interframe macroblock mode layer:
11427                //   * y_mode against `IF_YMODE_TREE` + the §16.1
11428                //     default `IF_YMODE_PROB_DEFAULTS` (we hold the
11429                //     §9.10 `intra_y_mode_prob_update` gate at 0 so
11430                //     the wire table stays at the defaults the
11431                //     decoder's `InterFrameIntraProbs::defaults`
11432                //     exposes);
11433                //   * uv_mode against `UV_MODE_TREE` + the §16.1
11434                //     default `IF_UV_MODE_PROB_DEFAULTS` (same gate
11435                //     held at 0).
11436                //
11437                // Round 161 picks the J-best `(y_mode, uv_mode)` pair
11438                // from the 4×4 whole-block grid; the tree walks emit
11439                // one to four bits depending on which leaf the picker
11440                // settled on (the §11.2 / §11.4 trees are unbalanced).
11441                hdr.write_treed(
11442                    &IF_YMODE_TREE,
11443                    |i| IF_YMODE_PROB_DEFAULTS[i],
11444                    record.y_mode.leaf(),
11445                );
11446                hdr.write_treed(
11447                    &UV_MODE_TREE,
11448                    |i| IF_UV_MODE_PROB_DEFAULTS[i],
11449                    record.uv_mode.leaf(),
11450                );
11451
11452                // Neighbour record advances: intra MBs go in as
11453                // `ref_frame = None` / `mv = 0` so the §16.3 census
11454                // skips them exactly like the off-frame border.
11455                let cur = crate::near_mv::MbInfo {
11456                    ref_frame: None,
11457                    mv: crate::motion_vector::Mv::default(),
11458                    is_split: false,
11459                    split_mvs: None,
11460                };
11461                aboveleft_mb = *above_slot;
11462                left_mb = cur;
11463                *above_slot = cur;
11464                continue;
11465            }
11466
11467            let chosen_mode = inter_modes_out[raster].expect("inter mode recorded above");
11468            let chosen_mv = record.mv;
11469            let chosen_ref_frame = ref_frames_out[raster].expect("inter ref_frame recorded above");
11470
11471            // 3. ref_frame selector — RFC 6386 §16.2 `ref_frame_tree`.
11472            //    LAST   → B(prob_last)=false
11473            //    GOLDEN → B(prob_last)=true,  B(prob_gf)=false
11474            //    ALTREF → B(prob_last)=true,  B(prob_gf)=true
11475            match chosen_ref_frame {
11476                crate::motion_comp::RefFrame::Last => {
11477                    hdr.write_bool(prob_last, false);
11478                }
11479                crate::motion_comp::RefFrame::Golden => {
11480                    hdr.write_bool(prob_last, true);
11481                    hdr.write_bool(prob_gf, false);
11482                }
11483                crate::motion_comp::RefFrame::AltRef => {
11484                    hdr.write_bool(prob_last, true);
11485                    hdr.write_bool(prob_gf, true);
11486                }
11487            }
11488
11489            // 4. Inter-mode tree (RFC 6386 §16.2 / §20.13 `mv_ref_tree`).
11490            //    ZEROMV    = leaf 0, path "0"
11491            //    NEARESTMV = leaf 1, path "10"
11492            //    NEARMV    = leaf 2, path "110"
11493            //    NEWMV     = leaf 3, path "1110"
11494            //    SPLITMV   = leaf 4, path "1111"
11495            //
11496            // §16.3 `find_near_mvs` is per-MB-ref-frame: neighbours
11497            // whose recorded `ref_frame` matches ours count toward
11498            // `near.mvs[]`. The wire emit must call the census with
11499            // the SAME ref_frame the search loop used (the chosen ref
11500            // for this MB) so the bits we emit are consumed at
11501            // exactly the probabilities the decoder reads them at.
11502            let near = crate::near_mv::find_near_mvs(
11503                above_slot,
11504                &left_mb,
11505                &aboveleft_mb,
11506                chosen_ref_frame,
11507                crate::near_mv::SignBias::default(),
11508            );
11509            let probs = crate::near_mv::mv_ref_probs(&near.cnt);
11510            match chosen_mode {
11511                crate::near_mv::InterMode::Zero => {
11512                    // "0" against probs[0].
11513                    hdr.write_bool(probs[0], false);
11514                }
11515                crate::near_mv::InterMode::Nearest => {
11516                    // "10" against probs[0..=1]. The decoder's
11517                    // `resolve_inter_mb_mv` reconstructs the MV as
11518                    // `clamp_mv(near.mvs[1], bounds)` — no extra bits.
11519                    hdr.write_bool(probs[0], true);
11520                    hdr.write_bool(probs[1], false);
11521                }
11522                crate::near_mv::InterMode::Near => {
11523                    // "110" against probs[0..=2]. The decoder
11524                    // reconstructs the MV as `clamp_mv(near.mvs[2],
11525                    // bounds)` — no extra bits.
11526                    hdr.write_bool(probs[0], true);
11527                    hdr.write_bool(probs[1], true);
11528                    hdr.write_bool(probs[2], false);
11529                }
11530                crate::near_mv::InterMode::New => {
11531                    // "1110": three true bits at probs[0..=2] then one
11532                    // false at probs[3]. Pinned by `MV_REF_TREE`.
11533                    hdr.write_bool(probs[0], true);
11534                    hdr.write_bool(probs[1], true);
11535                    hdr.write_bool(probs[2], true);
11536                    hdr.write_bool(probs[3], false);
11537                    // §17.2 NEWMV differential = chosen_mv -
11538                    // clamp_mv(near.mvs[0]). The decoder reads `best`
11539                    // through the same §16.3 / §18.1 clamp before adding.
11540                    let bounds =
11541                        crate::near_mv::MvClampRect::for_mb(mb_col, mb_row, mb_cols, mb_rows);
11542                    let best = crate::near_mv::clamp_mv(near.mvs[0], &bounds);
11543                    let diff = crate::motion_vector::Mv {
11544                        row: chosen_mv.row.wrapping_sub(best.row),
11545                        col: chosen_mv.col.wrapping_sub(best.col),
11546                    };
11547                    crate::motion_vector::write_mv(&mut hdr, &mv_contexts, diff);
11548                }
11549                crate::near_mv::InterMode::Split => {
11550                    // "1111": four true bits at probs[0..=3]. Pinned by
11551                    // `MV_REF_TREE`.
11552                    hdr.write_bool(probs[0], true);
11553                    hdr.write_bool(probs[1], true);
11554                    hdr.write_bool(probs[2], true);
11555                    hdr.write_bool(probs[3], true);
11556
11557                    // §16.4 partition + per-group sub_mv_ref walk. The
11558                    // candidate carries the picker's resolved partition,
11559                    // group modes, and NEW4X4 diffs from the search-and-RD
11560                    // pass; we re-emit each in order against the same
11561                    // probability tables.
11562                    let cand = record
11563                        .split
11564                        .as_ref()
11565                        .expect("a SPLITMV macroblock carries its candidate");
11566                    write_split_mv_partition(&mut hdr, cand.partition);
11567
11568                    // For each partition group, re-resolve the anchor's
11569                    // left / above neighbours against the SAME running
11570                    // split_mvs buffer the decoder will rebuild, look up
11571                    // the §16.4 `sub_mv_ref` context, and emit the
11572                    // group's mode + (NEW4X4 only) §17.2 differential.
11573                    let groups = partition_groups(cand.partition);
11574                    let mut running_split = [crate::motion_vector::Mv::default(); 16];
11575                    for (g_idx, group) in groups.iter().enumerate() {
11576                        let anchor = group[0];
11577                        let left_nb =
11578                            crate::near_mv::left_block_mv(&running_split, &left_mb, anchor);
11579                        let above_nb =
11580                            crate::near_mv::above_block_mv(&running_split, above_slot, anchor);
11581                        let ctx = crate::near_mv::submv_ref_context(left_nb, above_nb);
11582                        let sub_probs = &crate::near_mv::SUBMV_REF_PROBS[ctx];
11583
11584                        let mode = cand.submv_modes[g_idx];
11585                        write_submv_ref(&mut hdr, sub_probs, mode);
11586
11587                        if matches!(mode, crate::near_mv::SubMvRefMode::New4x4) {
11588                            // §16.4: NEW4X4 differential is added to
11589                            // `best_mv` (the clamped near.mvs[0]); the
11590                            // picker computed and stored the diff.
11591                            crate::motion_vector::write_mv(
11592                                &mut hdr,
11593                                &mv_contexts,
11594                                cand.submv_new_diffs[g_idx],
11595                            );
11596                        }
11597
11598                        // Fill the running split buffer with the
11599                        // group's resolved vector so subsequent groups'
11600                        // left/above neighbour lookups see exactly what
11601                        // the decoder will see.
11602                        for &b in group {
11603                            running_split[b] = cand.split_mvs[b];
11604                        }
11605                    }
11606                }
11607            }
11608
11609            // Update neighbour records for the next MB. SPLITMV
11610            // neighbours feed the §20.11 per-sub-block lookups, so we
11611            // record the full `split_mvs[16]` (the same layout the
11612            // decoder writes into `MbInfo`).
11613            let cur = if matches!(chosen_mode, crate::near_mv::InterMode::Split) {
11614                let cand = record.split.as_ref().expect("split candidate");
11615                crate::near_mv::MbInfo {
11616                    ref_frame: Some(chosen_ref_frame),
11617                    mv: cand.split_mvs[15],
11618                    is_split: true,
11619                    split_mvs: Some(cand.split_mvs),
11620                }
11621            } else {
11622                crate::near_mv::MbInfo {
11623                    ref_frame: Some(chosen_ref_frame),
11624                    mv: chosen_mv,
11625                    is_split: false,
11626                    split_mvs: None,
11627                }
11628            };
11629            aboveleft_mb = *above_slot;
11630            left_mb = cur;
11631            *above_slot = cur;
11632        }
11633    }
11634
11635    let first_partition = hdr.finish();
11636    let first_partition_size = first_partition.len();
11637    if first_partition_size > 0x7_FFFF {
11638        return Err(EncodeError::FirstPartitionTooLarge {
11639            bytes: first_partition_size,
11640        });
11641    }
11642
11643    // ---- §19.2 DCT partition group: §13.3 residual tokens --------------
11644    //
11645    // Macroblock rows are distributed round-robin across the §9.5
11646    // partitions per the §20.4 row-loop: row `r` is encoded into
11647    // partition `r % N`. Each partition gets its own [`BoolEncoder`]
11648    // instance (§4 page 9 — "All partitions are decoded using separate
11649    // instances of the boolean entropy decoder"), finalised
11650    // independently with its own §7.3 4-byte flush trailer. The §13.3
11651    // above-context is column-wise and frame-lived — shared across
11652    // partitions because the decoder's `decode_residuals` also keeps
11653    // one above slot per column for the whole frame. The "left"
11654    // context resets at every row start so it does not need to cross
11655    // partitions.
11656    //
11657    // The search recorded each row's §13.3 decisions on a token tape
11658    // (see `inter.rs`); here they are arithmetic-coded in row order
11659    // against this frame's coefficient probabilities.
11660    let mut partitions: Vec<BoolEncoder> =
11661        (0..num_partitions).map(|_| BoolEncoder::new()).collect();
11662    for (mb_row, tape) in analysis.tapes.iter().enumerate() {
11663        tape.replay(&mut partitions[mb_row % num_partitions], &emit_probs);
11664    }
11665    // §13.4 observed-counts side-channel: the per-position branch counts
11666    // of exactly the decisions just coded. With `counts = None` this is
11667    // a no-op.
11668    if let Some(c) = counts {
11669        for tape in &analysis.tapes {
11670            tape.tally(c);
11671        }
11672    }
11673    let dct_partitions: Vec<Vec<u8>> = partitions.into_iter().map(|p| p.finish()).collect();
11674    let dct_total: usize = dct_partitions.iter().map(|p| p.len()).sum();
11675    let size_table_len = (num_partitions - 1) * 3;
11676
11677    // ---- §9.1 inter frame tag + assembly --------------------------------
11678    let mut out: Vec<u8> =
11679        Vec::with_capacity(3 + first_partition_size + size_table_len + dct_total);
11680    write_frame_tag(
11681        &mut out,
11682        false, // inter frame
11683        0,     // version 0 — full-pel chroma off, version 0 §18.3 6-tap filters
11684        true,  // show_frame
11685        first_partition_size as u32,
11686        width,
11687        height,
11688        ScaleCode::None,
11689        ScaleCode::None,
11690    )?;
11691    out.extend_from_slice(&first_partition);
11692    // §9.5 size table: 3-byte little-endian length for every partition
11693    // except the last (whose size the decoder infers from what is left
11694    // in the frame). One partition → no table.
11695    for part in dct_partitions.iter().take(num_partitions - 1) {
11696        let sz = part.len();
11697        out.push((sz & 0xff) as u8);
11698        out.push(((sz >> 8) & 0xff) as u8);
11699        out.push(((sz >> 16) & 0xff) as u8);
11700    }
11701    for part in &dct_partitions {
11702        out.extend_from_slice(part);
11703    }
11704
11705    Ok((out, planes))
11706}
11707
11708/// Flattened §17.2 MV update-probability table (`2 * MV_PROB_COUNT = 38`
11709/// entries, `[row..; column..]`). Each entry is the probability the
11710/// encoder writes the corresponding "no update" F-gate at, matching the
11711/// decoder's per-position `read_bool(MV_UPDATE_PROBS[i][j])`.
11712const MV_UPDATE_PROBS_FLAT: [u8; 38] = [
11713    237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254,
11714    231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254,
11715];
11716
11717// ───────────────────────── factory + dual-API surface ─────────────────────────
11718
11719/// Phase 1 encoder handle. Stateless; one-shot
11720/// [`encode_keyframe`](Self::encode_keyframe) calls map directly to
11721/// [`encode_silent_keyframe`].
11722#[derive(Debug, Default, Clone, Copy)]
11723pub struct SilentKeyframeEncoder;
11724
11725impl SilentKeyframeEncoder {
11726    /// Encode a single silent key frame. `_pixels` is currently
11727    /// ignored — the Phase 1 path emits a fixed-content key frame
11728    /// regardless of input pixel data.
11729    pub fn encode_keyframe(
11730        &self,
11731        _pixels: &[u8],
11732        width: u32,
11733        height: u32,
11734    ) -> Result<Vec<u8>, EncodeError> {
11735        encode_silent_keyframe(SilentKeyframeParams::new(width, height))
11736    }
11737}
11738
11739/// Standalone-reachable helper that hands out a [`SilentKeyframeEncoder`].
11740///
11741/// Pre-dates the framework `make_encoder(params)` factory below. Kept
11742/// for the historical direct-API consumer that built against the no-arg
11743/// helper; the registry / framework path is now [`make_encoder`].
11744pub fn make_silent_keyframe_encoder() -> SilentKeyframeEncoder {
11745    SilentKeyframeEncoder
11746}
11747
11748// ───────────────────────── WebP-canonical quality mapping ─────────────────────────
11749
11750/// Map a WebP-canonical `0.0..=100.0` quality scalar onto the VP8
11751/// §9.6 `y_ac_qi` quantiser index (`0..=127`, lower = higher quality).
11752///
11753/// The mapping matches the on-wire convention `oxideav-webp`'s VP8 lossy
11754/// path uses: `round((100 - quality) * 1.27)`. Defined precisely:
11755///
11756/// * Inputs `<= 0.0` clamp to `quality = 0.0`, returning `127` (worst).
11757/// * Inputs `>= 100.0` clamp to `quality = 100.0`, returning `0` (best).
11758/// * `NaN` returns `127` (the "couldn't tell — keep the file small" choice).
11759/// * Otherwise the floating-point result is rounded half-away-from-zero
11760///   (the default behaviour of `f32::round`) and then clamped into the
11761///   `0..=127` `u8` range, so an out-of-range numeric input cannot trip
11762///   an `as u8` truncation overflow.
11763///
11764/// The function is pure — it does not touch [`crate::Encoder`] or
11765/// [`oxideav_core`] — so it is reachable under
11766/// `--no-default-features` for an embedded image / video pipeline that
11767/// wants to choose a `qindex` without building the framework adapter.
11768pub fn quality_to_qindex(quality: f32) -> u8 {
11769    if quality.is_nan() {
11770        return 127;
11771    }
11772    let clamped = quality.clamp(0.0, 100.0);
11773    let q = ((100.0_f32 - clamped) * 1.27).round();
11774    // After the clamp + the constant factor the result is in 0.0..=127.0,
11775    // but pin the bounds explicitly so any future change to the formula
11776    // can't silently overflow `as u8`.
11777    q.clamp(0.0, 127.0) as u8
11778}
11779
11780/// Map a WebP-canonical `0.0..=100.0` quality scalar onto a coherent
11781/// [`TrellisStrength`] for the §13 coefficient trellis.
11782///
11783/// The mapping pairs the quality dial with the trellis aggressiveness so a
11784/// single quality number tunes *both* the §9.6 quantiser
11785/// ([`quality_to_qindex`]) and how hard the trellis shaves coefficient
11786/// bits. The shape is clean-room (RFC 6386 is silent on encoder rate
11787/// control):
11788///
11789/// * `quality >= 90` (visually-lossless target) → [`TrellisStrength::DEFAULT`]
11790///   (`1.0`): the conservative "hold the PSNR floor" trade — a
11791///   high-quality stream should not sacrifice PSNR for marginal byte
11792///   savings.
11793/// * As quality falls the strength ramps linearly toward `4.0` at
11794///   `quality = 0` (the empirically-strong operating point that trims
11795///   ~24–40 % of the no-trellis bytes for ~0.3 dB at mid/high quantisers,
11796///   where a low-quality stream already lives).
11797/// * `NaN` returns [`TrellisStrength::DEFAULT`] (the safe, conservative
11798///   choice, matching the `quality_to_qindex` "couldn't tell" policy of
11799///   not over-trading).
11800///
11801/// Pure — no [`oxideav_core`] / framework dependency — so it is reachable
11802/// under `--no-default-features`. Callers that want the quantiser and the
11803/// trellis tuned together can write
11804/// `KeyframeParams { y_ac_qi: quality_to_qindex(q), trellis_strength:
11805/// quality_to_trellis_strength(q), ..Default::default() }`.
11806pub fn quality_to_trellis_strength(quality: f32) -> TrellisStrength {
11807    if quality.is_nan() {
11808        return TrellisStrength::DEFAULT;
11809    }
11810    let clamped = quality.clamp(0.0, 100.0);
11811    // 1.0 at quality 90+, ramping to 4.0 at quality 0. Above 90 the
11812    // `max(0.0)` floors the ramp term so the strength stays at the default.
11813    const KNEE: f32 = 90.0;
11814    const TOP_STRENGTH: f32 = 4.0;
11815    let ramp = ((KNEE - clamped).max(0.0) / KNEE) * (TOP_STRENGTH - 1.0);
11816    TrellisStrength::new((1.0 + ramp) as f64)
11817}
11818
11819// ───────────────────────── framework factory (registry-gated) ─────────────────────────
11820
11821#[cfg(feature = "registry")]
11822mod factory {
11823    //! [`oxideav_core::Encoder`] adapter for the VP8 encoder.
11824    //!
11825    //! The historical `oxideav-vp8` direct-API entry points
11826    //! ([`encode_keyframe`], [`encode_silent_keyframe`],
11827    //! [`encode_p_frame_multi_ref_with_*`] ladder) operate on
11828    //! per-frame [`I420Frame`] / [`KeyframeParams`] / [`MbPixels`]
11829    //! values and are reachable without `oxideav-core`. This adapter
11830    //! plugs that direct API into the framework's
11831    //! [`oxideav_core::Encoder`] trait so the registry path
11832    //! ([`oxideav_vp8::register`](crate::register)) can hand a
11833    //! `Box<dyn Encoder>` to a generic muxer / pipeline.
11834
11835    use std::collections::VecDeque;
11836
11837    use oxideav_core::time::TimeBase;
11838    use oxideav_core::{
11839        CodecId, CodecParameters, Encoder, Error, Frame, MediaType, Packet, PixelFormat, Result,
11840        VideoFrame,
11841    };
11842
11843    use super::{
11844        EncodeEffort, I420Frame, KeyframeEncodeOptions, KeyframeParams,
11845        encode_keyframe_with_options,
11846    };
11847    use crate::decoder::VP8_CODEC_ID;
11848
11849    /// Typed options of the registry key-frame encoder — the struct
11850    /// behind the `CodecParameters::options` bag the registered factory
11851    /// ([`make_encoder_from_param_options`]) parses, and the argument of
11852    /// the direct [`make_encoder_with_options`] door.
11853    ///
11854    /// | key | kind | default | meaning |
11855    /// |---|---|---|---|
11856    /// | `effort` | u32 | `3` | mode-search effort, `0` fastest ..= `3` thorough ([`EncodeEffort`]) |
11857    /// | `threads` | u32 | `0` | thread budget; `0` follows the `ExecutionContext` (serial when none is announced) |
11858    /// | `qindex` | u32 | `32` | §9.6 `y_ac_qi`, `0..=127` |
11859    /// | `quality` | f32 | `-1` | `0..=100` quality; when ≥ 0 it replaces `qindex` and also sets the trellis strength |
11860    /// | `loop_filter_level` | u32 | `0` | §9.4 level, `0..=63` |
11861    /// | `auto_loop_filter` | bool | `false` | RD-select the §9.4 level / sharpness per frame |
11862    /// | `partitions` | u32 | `1` | §9.5 token partition count (1 / 2 / 4 / 8) |
11863    #[derive(Debug, Clone, Copy, PartialEq)]
11864    #[non_exhaustive]
11865    pub struct Vp8EncoderOptions {
11866        /// Mode-search effort.
11867        pub effort: EncodeEffort,
11868        /// Thread budget; `0` follows the announced `ExecutionContext`.
11869        pub threads: usize,
11870        /// §9.6 `y_ac_qi` (ignored when `quality` is set).
11871        pub qindex: u8,
11872        /// `0..=100` quality (see [`super::quality_to_qindex`] /
11873        /// [`super::quality_to_trellis_strength`]); `None` uses `qindex`.
11874        pub quality: Option<f32>,
11875        /// §9.4 `loop_filter_level`.
11876        pub loop_filter_level: u8,
11877        /// RD-select the §9.4 level / sharpness.
11878        pub auto_loop_filter: bool,
11879        /// §9.5 token partition count.
11880        pub partitions: u8,
11881    }
11882
11883    impl Default for Vp8EncoderOptions {
11884        fn default() -> Self {
11885            let keyframe = KeyframeParams::default();
11886            Vp8EncoderOptions {
11887                effort: EncodeEffort::Thorough,
11888                threads: 0,
11889                qindex: keyframe.y_ac_qi,
11890                quality: None,
11891                loop_filter_level: keyframe.loop_filter_level,
11892                auto_loop_filter: false,
11893                partitions: keyframe.nbr_of_dct_partitions,
11894            }
11895        }
11896    }
11897
11898    impl Vp8EncoderOptions {
11899        /// The defaults (see the table on the type).
11900        pub fn new() -> Self {
11901            Self::default()
11902        }
11903
11904        /// Set `effort`.
11905        #[must_use]
11906        pub fn with_effort(mut self, v: EncodeEffort) -> Self {
11907            self.effort = v;
11908            self
11909        }
11910
11911        /// Set `threads`.
11912        #[must_use]
11913        pub fn with_threads(mut self, v: usize) -> Self {
11914            self.threads = v;
11915            self
11916        }
11917
11918        /// Set `qindex`.
11919        #[must_use]
11920        pub fn with_qindex(mut self, v: u8) -> Self {
11921            self.qindex = v;
11922            self
11923        }
11924
11925        /// Set `quality`.
11926        #[must_use]
11927        pub fn with_quality(mut self, v: Option<f32>) -> Self {
11928            self.quality = v;
11929            self
11930        }
11931
11932        /// Set `loop_filter_level`.
11933        #[must_use]
11934        pub fn with_loop_filter_level(mut self, v: u8) -> Self {
11935            self.loop_filter_level = v;
11936            self
11937        }
11938
11939        /// Set `auto_loop_filter`.
11940        #[must_use]
11941        pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
11942            self.auto_loop_filter = v;
11943            self
11944        }
11945
11946        /// Set `partitions`.
11947        #[must_use]
11948        pub fn with_partitions(mut self, v: u8) -> Self {
11949            self.partitions = v;
11950            self
11951        }
11952    }
11953
11954    impl oxideav_core::CodecOptionsStruct for Vp8EncoderOptions {
11955        const SCHEMA: &'static [oxideav_core::OptionField] = &[
11956            oxideav_core::OptionField {
11957                name: "effort",
11958                kind: oxideav_core::OptionKind::U32,
11959                default: oxideav_core::OptionValue::U32(3),
11960                help: "mode-search effort: 0 fastest, 1 fast, 2 balanced, 3 thorough",
11961            },
11962            oxideav_core::OptionField {
11963                name: "threads",
11964                kind: oxideav_core::OptionKind::U32,
11965                default: oxideav_core::OptionValue::U32(0),
11966                help: "thread budget (0 = follow the execution context)",
11967            },
11968            oxideav_core::OptionField {
11969                name: "qindex",
11970                kind: oxideav_core::OptionKind::U32,
11971                default: oxideav_core::OptionValue::U32(32),
11972                help: "quantiser index 0..=127 (lower = better)",
11973            },
11974            oxideav_core::OptionField {
11975                name: "quality",
11976                kind: oxideav_core::OptionKind::F32,
11977                default: oxideav_core::OptionValue::F32(-1.0),
11978                help: "quality 0..=100 (overrides qindex; negative = unset)",
11979            },
11980            oxideav_core::OptionField {
11981                name: "loop_filter_level",
11982                kind: oxideav_core::OptionKind::U32,
11983                default: oxideav_core::OptionValue::U32(0),
11984                help: "loop filter level 0..=63",
11985            },
11986            oxideav_core::OptionField {
11987                name: "auto_loop_filter",
11988                kind: oxideav_core::OptionKind::Bool,
11989                default: oxideav_core::OptionValue::Bool(false),
11990                help: "choose the loop filter level per frame",
11991            },
11992            oxideav_core::OptionField {
11993                name: "partitions",
11994                kind: oxideav_core::OptionKind::U32,
11995                default: oxideav_core::OptionValue::U32(1),
11996                help: "token partition count: 1, 2, 4 or 8",
11997            },
11998        ];
11999
12000        fn apply(&mut self, key: &str, value: &oxideav_core::OptionValue) -> Result<()> {
12001            let small = |v: u32, max: u32, what: &str| {
12002                if v > max {
12003                    Err(Error::invalid(format!(
12004                        "vp8 encoder: option '{what}' out of range (0..={max}), got {v}"
12005                    )))
12006                } else {
12007                    Ok(v as u8)
12008                }
12009            };
12010            match key {
12011                "effort" => self.effort = EncodeEffort::from_level(small(value.as_u32()?, 3, key)?),
12012                "threads" => self.threads = value.as_u32()? as usize,
12013                "qindex" => self.qindex = small(value.as_u32()?, 127, key)?,
12014                "quality" => {
12015                    let q = value.as_f32()?;
12016                    self.quality = (q >= 0.0).then_some(q);
12017                }
12018                "loop_filter_level" => self.loop_filter_level = small(value.as_u32()?, 63, key)?,
12019                "auto_loop_filter" => self.auto_loop_filter = value.as_bool()?,
12020                "partitions" => {
12021                    let n = value.as_u32()?;
12022                    if !matches!(n, 1 | 2 | 4 | 8) {
12023                        return Err(Error::invalid(format!(
12024                            "vp8 encoder: option 'partitions' must be 1, 2, 4 or 8, got {n}"
12025                        )));
12026                    }
12027                    self.partitions = n as u8;
12028                }
12029                other => {
12030                    return Err(Error::invalid(format!(
12031                        "vp8 encoder: unknown option '{other}'"
12032                    )));
12033                }
12034            }
12035            Ok(())
12036        }
12037    }
12038
12039    /// Build the zero-latency key-frame encoder from typed
12040    /// [`Vp8EncoderOptions`] — the direct twin of the registered factory.
12041    /// `Vp8EncoderOptions::default()` gives the same encoder as
12042    /// [`make_encoder`].
12043    pub fn make_encoder_with_options(
12044        params: &CodecParameters,
12045        options: &Vp8EncoderOptions,
12046    ) -> Result<Box<dyn Encoder>> {
12047        let (width, height, pixel_format) = validate_video_params(params)?;
12048        if options.qindex > 127 {
12049            return Err(Error::invalid(
12050                "vp8 encoder: qindex out of range (must be 0..=127)",
12051            ));
12052        }
12053        if options.loop_filter_level > 63 {
12054            return Err(Error::invalid(
12055                "vp8 encoder: loop_filter_level out of range (must be 0..=63)",
12056            ));
12057        }
12058        if !matches!(options.partitions, 1 | 2 | 4 | 8) {
12059            return Err(Error::invalid(
12060                "vp8 encoder: partitions must be 1, 2, 4 or 8",
12061            ));
12062        }
12063        let mut keyframe = KeyframeParams::default()
12064            .with_y_ac_qi(options.qindex)
12065            .with_loop_filter_level(options.loop_filter_level)
12066            .with_nbr_of_dct_partitions(options.partitions);
12067        if let Some(quality) = options.quality {
12068            keyframe.y_ac_qi = super::quality_to_qindex(quality);
12069            keyframe.trellis_strength = super::quality_to_trellis_strength(quality);
12070        }
12071        let mut encoder = build_frame_encoder_typed(
12072            params,
12073            width,
12074            height,
12075            pixel_format,
12076            keyframe,
12077            options.auto_loop_filter,
12078        );
12079        encoder.effort = options.effort;
12080        encoder.option_threads = options.threads;
12081        Ok(Box::new(encoder))
12082    }
12083
12084    /// The registry's encoder factory: parse `params.options` (strictly —
12085    /// an unknown key or a malformed value is an error) into
12086    /// [`Vp8EncoderOptions`] and build the key-frame encoder from it. An
12087    /// empty bag gives the same encoder as [`make_encoder`].
12088    pub fn make_encoder_from_param_options(params: &CodecParameters) -> Result<Box<dyn Encoder>> {
12089        let options = oxideav_core::parse_options::<Vp8EncoderOptions>(&params.options)?;
12090        make_encoder_with_options(params, &options)
12091    }
12092
12093    /// Build a framework-side VP8 encoder bound to `params` with all
12094    /// defaults: `y_ac_qi = 32`, no loop filter, 1 DCT partition,
12095    /// normal filter. Equivalent to
12096    /// `make_encoder_with_qindex(params, 32)`.
12097    ///
12098    /// `params` must declare a positive `width` and `height`;
12099    /// `pixel_format` defaults to [`PixelFormat::Yuv420P`] when absent
12100    /// and is the only format the encoder currently accepts.
12101    pub fn make_encoder(params: &CodecParameters) -> Result<Box<dyn Encoder>> {
12102        make_encoder_with_qindex(params, KeyframeParams::default().y_ac_qi)
12103    }
12104
12105    /// Build a framework-side VP8 encoder with the WebP-canonical
12106    /// `0.0..=100.0` `quality` (higher = better) translated into a
12107    /// `y_ac_qi` via [`super::quality_to_qindex`] **and** a coherent §13
12108    /// trellis aggressiveness via [`super::quality_to_trellis_strength`]:
12109    /// a high-quality request keeps the conservative
12110    /// [`super::TrellisStrength::DEFAULT`] trade while a low-quality
12111    /// request also lets the trellis shave coefficient bits harder, so the
12112    /// single quality dial tunes both the quantiser and the trellis.
12113    ///
12114    /// Like [`make_encoder`] / [`make_encoder_with_qindex`], this is a
12115    /// **zero-latency single-frame door**: every `send_frame` emits one
12116    /// key frame packet immediately (the still-image contract the
12117    /// RIFF-VP8 image consumers rely on). The lagged inter-stream
12118    /// semantics live on the [`super::make_encoder_with_config`] path.
12119    pub fn make_encoder_with_quality(
12120        params: &CodecParameters,
12121        quality: f32,
12122    ) -> Result<Box<dyn Encoder>> {
12123        let (width, height, pixel_format) = validate_video_params(params)?;
12124        let keyframe = KeyframeParams {
12125            y_ac_qi: super::quality_to_qindex(quality),
12126            trellis_strength: super::quality_to_trellis_strength(quality),
12127            ..KeyframeParams::default()
12128        };
12129        build_frame_encoder(params, width, height, pixel_format, keyframe, false)
12130    }
12131
12132    /// Shared `CodecParameters` validation for every factory entry:
12133    /// positive dimensions inside the §9.1 14-bit fields, Yuv420P only.
12134    fn validate_video_params(params: &CodecParameters) -> Result<(u32, u32, PixelFormat)> {
12135        let width = params
12136            .width
12137            .ok_or_else(|| Error::invalid("vp8 encoder: missing width"))?;
12138        let height = params
12139            .height
12140            .ok_or_else(|| Error::invalid("vp8 encoder: missing height"))?;
12141        if width == 0 || height == 0 {
12142            return Err(Error::invalid(
12143                "vp8 encoder: width and height must be positive",
12144            ));
12145        }
12146        if width > 0x3FFF || height > 0x3FFF {
12147            return Err(Error::invalid(
12148                "vp8 encoder: width/height exceed VP8 14-bit field (max 16383)",
12149            ));
12150        }
12151        let pixel_format = params.pixel_format.unwrap_or(PixelFormat::Yuv420P);
12152        if pixel_format != PixelFormat::Yuv420P {
12153            return Err(Error::unsupported(
12154                "vp8 encoder: only PixelFormat::Yuv420P is supported",
12155            ));
12156        }
12157        Ok((width, height, pixel_format))
12158    }
12159
12160    /// Build a framework-side VP8 encoder with an explicit VP8 §9.6
12161    /// `y_ac_qi` quantiser index (`0..=127`, lower = better).
12162    pub fn make_encoder_with_qindex(
12163        params: &CodecParameters,
12164        qindex: u8,
12165    ) -> Result<Box<dyn Encoder>> {
12166        let (width, height, pixel_format) = validate_video_params(params)?;
12167        if qindex > 127 {
12168            return Err(Error::invalid(
12169                "vp8 encoder: qindex out of range (must be 0..=127)",
12170            ));
12171        }
12172        let keyframe = KeyframeParams {
12173            y_ac_qi: qindex,
12174            ..KeyframeParams::default()
12175        };
12176        build_frame_encoder(params, width, height, pixel_format, keyframe, false)
12177    }
12178
12179    /// Build a framework-side **lagged inter-stream** VP8 encoder from a
12180    /// full [`super::Vp8EncoderConfig`] — the round-387 upgrade that
12181    /// finally makes the `Box<dyn Encoder>` adapter consume the config's
12182    /// stream-level knobs instead of re-keying every frame:
12183    ///
12184    /// * `qindex` / `lf_level` / `trellis_strength` — per-frame encode
12185    ///   parameters (as before);
12186    /// * `auto_loop_filter` — RD-selected §9.4 level / sharpness per
12187    ///   emitted frame (`lf_level` ignored when set);
12188    /// * `alt_ref_interval` — lookahead group size: each completed group
12189    ///   ships one invisible ARNR anchor followed by its visible
12190    ///   multi-reference P-frames. `0` disables anchors (group size 1 —
12191    ///   zero lag, K/P streaming with immediate packet availability);
12192    /// * `lookahead_window` — caps the group size;
12193    /// * `golden_interval` — key-frame cadence in source frames (`0`
12194    ///   keys only frame 0); scene cuts force additional keys.
12195    ///
12196    /// The returned encoder follows the standard lagged
12197    /// [`Encoder`] protocol: `send_frame` may buffer (`receive_packet`
12198    /// surfaces [`Error::NeedMore`] while a lookahead group is
12199    /// filling), `flush` drains the tail group, and the stream emits
12200    /// **more packets than source frames** (invisible anchor packets
12201    /// carry `pts = None` and `flags.keyframe = false`; a muxer stores
12202    /// them in decode order, a player never displays them). Like
12203    /// [`super::Vp8Encoder::encode_sequence`], the §13.4 fitted
12204    /// token-prob-update emission and the §11 intra-within-inter picker
12205    /// are enabled on every frame (never-grow byte guards; the cost is
12206    /// a second encode pass per frame).
12207    pub(crate) fn make_encoder_from_config(
12208        params: &CodecParameters,
12209        config: super::Vp8EncoderConfig,
12210    ) -> Result<Box<dyn Encoder>> {
12211        let (width, height, pixel_format) = validate_video_params(params)?;
12212        if config.qindex > 127 {
12213            return Err(Error::invalid(
12214                "vp8 encoder: qindex out of range (must be 0..=127)",
12215            ));
12216        }
12217        if config.lf_level > 63 {
12218            return Err(Error::invalid(
12219                "vp8 encoder: lf_level out of range (must be 0..=63)",
12220            ));
12221        }
12222
12223        let mut output_params = params.clone();
12224        output_params.media_type = MediaType::Video;
12225        output_params.codec_id = CodecId::new(VP8_CODEC_ID);
12226        output_params.width = Some(width);
12227        output_params.height = Some(height);
12228        output_params.pixel_format = Some(pixel_format);
12229        let time_base = params
12230            .frame_rate
12231            .map_or(TimeBase::new(1, 90_000), |r| TimeBase::new(r.den, r.num));
12232
12233        // Same knob mapping as `Vp8Encoder::encode_sequence`.
12234        let window = if config.alt_ref_interval == 0 {
12235            1
12236        } else {
12237            config.alt_ref_interval.min(config.lookahead_window.max(1)) as usize
12238        };
12239        let stream_config = crate::stream::AltrefStreamConfig {
12240            params: KeyframeParams {
12241                y_ac_qi: config.qindex,
12242                loop_filter_level: config.lf_level,
12243                trellis_strength: config.trellis_strength,
12244                nbr_of_dct_partitions: config.stream_partitions(),
12245                ..KeyframeParams::default()
12246            },
12247            keyframe_interval: u64::from(config.golden_interval),
12248            altref_window: window,
12249            auto_loop_filter: config.auto_loop_filter,
12250            fitted_token_prob_updates: true,
12251            intra_pick: true,
12252            effort: config.effort,
12253            threads: config.threads,
12254            inter_effort: config.inter_effort,
12255            target_bitrate_bps: config.target_bitrate_bps,
12256            frame_rate: params
12257                .frame_rate
12258                .filter(|r| r.num > 0 && r.den > 0)
12259                .map_or(config.frame_rate, |r| r.num as f64 / r.den as f64),
12260            ..crate::stream::AltrefStreamConfig::default()
12261        };
12262        let stream = crate::stream::Vp8AltrefStreamEncoder::new(stream_config)
12263            .expect("window is clamped to >= 1 above");
12264
12265        Ok(Box::new(Vp8LaggedEncoder {
12266            output_params,
12267            width,
12268            height,
12269            stream_config,
12270            stream,
12271            time_base,
12272            pts_queue: VecDeque::new(),
12273            pending: VecDeque::new(),
12274            eof: false,
12275        }))
12276    }
12277
12278    /// Lagged [`oxideav_core::Encoder`] adapter around the auto-altref
12279    /// stream driver ([`crate::stream::Vp8AltrefStreamEncoder`]) — the
12280    /// framework face of the round-384 GOLDEN/ALTREF subsystem.
12281    ///
12282    /// Protocol: `send_frame` buffers source pictures into lookahead
12283    /// groups (returning `Ok(())` immediately); `receive_packet` pops
12284    /// finished packets or surfaces [`Error::NeedMore`] while the group
12285    /// is filling; `flush` drains the tail group and arms the final
12286    /// [`Error::Eof`]. Visible packets carry their source frame's `pts`
12287    /// (in push order — the driver emits visible packets in source
12288    /// order); invisible anchor packets carry `pts = None`. Only key
12289    /// frames set `flags.keyframe`.
12290    pub(crate) struct Vp8LaggedEncoder {
12291        output_params: CodecParameters,
12292        width: u32,
12293        height: u32,
12294        /// The configuration `stream` was built from — re-used to start
12295        /// a fresh stream (opening with a key frame) when a
12296        /// [`Frame::StreamParams`] event changes the input size.
12297        stream_config: crate::stream::AltrefStreamConfig,
12298        stream: crate::stream::Vp8AltrefStreamEncoder,
12299        time_base: TimeBase,
12300        /// pts of pushed source frames not yet emitted as visible
12301        /// packets (front = oldest). Visible packets pop in order.
12302        pts_queue: VecDeque<Option<i64>>,
12303        pending: VecDeque<Packet>,
12304        eof: bool,
12305    }
12306
12307    impl std::fmt::Debug for Vp8LaggedEncoder {
12308        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12309            f.debug_struct("Vp8LaggedEncoder")
12310                .field("width", &self.width)
12311                .field("height", &self.height)
12312                .field("buffered", &self.stream.buffered())
12313                .field("pending", &self.pending.len())
12314                .field("eof", &self.eof)
12315                .finish()
12316        }
12317    }
12318
12319    impl Vp8LaggedEncoder {
12320        /// Convert a batch of stream packets into framework [`Packet`]s,
12321        /// consuming the pts queue for visible ones.
12322        fn enqueue(&mut self, packets: Vec<crate::stream::AltrefStreamPacket>) {
12323            for p in packets {
12324                let is_key = p.kind == crate::stream::AltrefPacketKind::Key;
12325                let pts = match p.source_index {
12326                    Some(_) => self.pts_queue.pop_front().flatten(),
12327                    None => None,
12328                };
12329                let mut pkt = Packet::new(0, self.time_base, p.bytes);
12330                pkt.pts = pts;
12331                pkt.dts = pts;
12332                pkt.flags.keyframe = is_key;
12333                self.pending.push_back(pkt);
12334            }
12335        }
12336    }
12337
12338    impl Encoder for Vp8LaggedEncoder {
12339        fn codec_id(&self) -> &CodecId {
12340            &self.output_params.codec_id
12341        }
12342
12343        fn output_params(&self) -> &CodecParameters {
12344            &self.output_params
12345        }
12346
12347        fn send_frame(&mut self, frame: &Frame) -> Result<()> {
12348            if self.eof {
12349                return Err(Error::invalid(
12350                    "vp8 encoder: send_frame after flush (encoder is drained)",
12351                ));
12352            }
12353            let v = match frame {
12354                Frame::Video(v) => v,
12355                Frame::StreamParams(p) => {
12356                    let (width, height) = reconfigure_target(p, self.width, self.height)?;
12357                    if (width, height) != (self.width, self.height) {
12358                        // Close the current lookahead group(s) at the old
12359                        // size, then open a fresh stream: its first frame
12360                        // is a §9.1 key frame carrying the new size.
12361                        let emitted = self
12362                            .stream
12363                            .finish()
12364                            .map_err(|e| Error::invalid(e.to_string()))?;
12365                        self.enqueue(emitted);
12366                        self.stream =
12367                            crate::stream::Vp8AltrefStreamEncoder::new(self.stream_config)
12368                                .expect("the config already built a stream");
12369                        self.width = width;
12370                        self.height = height;
12371                        self.output_params.width = Some(width);
12372                        self.output_params.height = Some(height);
12373                    }
12374                    return Ok(());
12375                }
12376                _ => return Err(Error::invalid("vp8 encoder: video frames only")),
12377            };
12378            let (y, u, vv) = packed_planes_from_video_frame(v, self.width, self.height)?;
12379            let src = I420Frame::packed(self.width, self.height, &y, &u, &vv);
12380            self.pts_queue.push_back(v.pts);
12381            let emitted = self
12382                .stream
12383                .push_frame(&src)
12384                .map_err(|e| Error::invalid(e.to_string()))?;
12385            self.enqueue(emitted);
12386            Ok(())
12387        }
12388
12389        fn receive_packet(&mut self) -> Result<Packet> {
12390            if let Some(p) = self.pending.pop_front() {
12391                Ok(p)
12392            } else if self.eof {
12393                Err(Error::Eof)
12394            } else {
12395                Err(Error::NeedMore)
12396            }
12397        }
12398
12399        fn flush(&mut self) -> Result<()> {
12400            if !self.eof {
12401                let emitted = self
12402                    .stream
12403                    .finish()
12404                    .map_err(|e| Error::invalid(e.to_string()))?;
12405                self.enqueue(emitted);
12406                self.eof = true;
12407            }
12408            Ok(())
12409        }
12410
12411        /// Adopt the announced thread budget for the key frames unless
12412        /// the configuration named one itself (`threads > 1`). The bytes
12413        /// do not depend on it.
12414        fn set_execution_context(&mut self, ctx: &oxideav_core::ExecutionContext) {
12415            if self.stream_config.threads <= 1 {
12416                self.stream_config.threads = ctx.threads;
12417                self.stream.set_threads(ctx.threads);
12418            }
12419        }
12420    }
12421
12422    /// Shared constructor for the framework-side keyframe encoder adapter.
12423    /// `auto_lf` routes each frame through the §9.4 RD loop-filter selector
12424    /// ([`encode_keyframe_auto_loop_filter`]) when set.
12425    pub(crate) fn build_frame_encoder(
12426        params: &CodecParameters,
12427        width: u32,
12428        height: u32,
12429        pixel_format: PixelFormat,
12430        keyframe: KeyframeParams,
12431        auto_lf: bool,
12432    ) -> Result<Box<dyn Encoder>> {
12433        Ok(Box::new(build_frame_encoder_typed(
12434            params,
12435            width,
12436            height,
12437            pixel_format,
12438            keyframe,
12439            auto_lf,
12440        )))
12441    }
12442
12443    fn build_frame_encoder_typed(
12444        params: &CodecParameters,
12445        width: u32,
12446        height: u32,
12447        pixel_format: PixelFormat,
12448        keyframe: KeyframeParams,
12449        auto_lf: bool,
12450    ) -> Vp8FrameEncoder {
12451        let mut output_params = params.clone();
12452        output_params.media_type = MediaType::Video;
12453        output_params.codec_id = CodecId::new(VP8_CODEC_ID);
12454        output_params.width = Some(width);
12455        output_params.height = Some(height);
12456        output_params.pixel_format = Some(pixel_format);
12457
12458        let time_base = params
12459            .frame_rate
12460            .map_or(TimeBase::new(1, 90_000), |r| TimeBase::new(r.den, r.num));
12461
12462        Vp8FrameEncoder {
12463            output_params,
12464            width,
12465            height,
12466            keyframe,
12467            auto_lf,
12468            effort: EncodeEffort::Thorough,
12469            option_threads: 0,
12470            context_threads: 1,
12471            time_base,
12472            pending: VecDeque::new(),
12473            eof: false,
12474        }
12475    }
12476
12477    /// Zero-latency [`oxideav_core::Encoder`] adapter around the
12478    /// direct-API [`encode_keyframe`] driver. One source
12479    /// [`Frame::Video`] produces one keyframe [`Packet`] immediately —
12480    /// the still-image contract behind [`make_encoder`] /
12481    /// [`make_encoder_with_qindex`] / [`make_encoder_with_quality`].
12482    /// The inter-stream / lagged semantics live on
12483    /// [`Vp8LaggedEncoder`] via [`super::make_encoder_with_config`].
12484    pub(crate) struct Vp8FrameEncoder {
12485        output_params: CodecParameters,
12486        width: u32,
12487        height: u32,
12488        keyframe: KeyframeParams,
12489        /// §9.4 RD loop-filter auto-selection (per
12490        /// [`Vp8EncoderConfig::auto_loop_filter`]).
12491        auto_lf: bool,
12492        /// Mode-search effort ([`Vp8EncoderOptions::effort`]).
12493        effort: EncodeEffort,
12494        /// Explicit thread budget from the options (`0` = none given).
12495        option_threads: usize,
12496        /// Thread budget announced through `set_execution_context`
12497        /// (`1` until one is).
12498        context_threads: usize,
12499        time_base: TimeBase,
12500        pending: VecDeque<Packet>,
12501        eof: bool,
12502    }
12503
12504    impl Vp8FrameEncoder {
12505        /// The per-frame speed options: the explicit `threads` option if
12506        /// one was given, else the announced execution-context budget.
12507        fn keyframe_options(&self) -> KeyframeEncodeOptions {
12508            let threads = if self.option_threads > 0 {
12509                self.option_threads
12510            } else {
12511                self.context_threads
12512            };
12513            KeyframeEncodeOptions::exhaustive()
12514                .with_effort(self.effort)
12515                .with_threads(threads)
12516                .with_auto_loop_filter(self.auto_lf)
12517        }
12518    }
12519
12520    impl std::fmt::Debug for Vp8FrameEncoder {
12521        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12522            f.debug_struct("Vp8FrameEncoder")
12523                .field("width", &self.width)
12524                .field("height", &self.height)
12525                .field("y_ac_qi", &self.keyframe.y_ac_qi)
12526                .field("pending", &self.pending.len())
12527                .field("eof", &self.eof)
12528                .finish()
12529        }
12530    }
12531
12532    impl Encoder for Vp8FrameEncoder {
12533        fn codec_id(&self) -> &CodecId {
12534            &self.output_params.codec_id
12535        }
12536
12537        fn output_params(&self) -> &CodecParameters {
12538            &self.output_params
12539        }
12540
12541        fn send_frame(&mut self, frame: &Frame) -> Result<()> {
12542            let v = match frame {
12543                Frame::Video(v) => v,
12544                Frame::StreamParams(p) => {
12545                    // Every packet of this adapter is a key frame, so a
12546                    // new size takes effect cleanly on the next frame.
12547                    let (width, height) = reconfigure_target(p, self.width, self.height)?;
12548                    self.width = width;
12549                    self.height = height;
12550                    self.output_params.width = Some(width);
12551                    self.output_params.height = Some(height);
12552                    return Ok(());
12553                }
12554                _ => return Err(Error::invalid("vp8 encoder: video frames only")),
12555            };
12556            let bytes = encode_video_frame(
12557                v,
12558                self.width,
12559                self.height,
12560                &self.keyframe,
12561                &self.keyframe_options(),
12562            )?;
12563            let mut pkt = Packet::new(0, self.time_base, bytes);
12564            pkt.pts = v.pts;
12565            pkt.dts = v.pts;
12566            pkt.flags.keyframe = true;
12567            self.pending.push_back(pkt);
12568            Ok(())
12569        }
12570
12571        fn receive_packet(&mut self) -> Result<Packet> {
12572            if let Some(p) = self.pending.pop_front() {
12573                Ok(p)
12574            } else if self.eof {
12575                Err(Error::Eof)
12576            } else {
12577                Err(Error::NeedMore)
12578            }
12579        }
12580
12581        fn flush(&mut self) -> Result<()> {
12582            self.eof = true;
12583            Ok(())
12584        }
12585
12586        /// Record the announced thread budget; it applies unless the
12587        /// `threads` option named one. The bytes do not depend on it.
12588        fn set_execution_context(&mut self, ctx: &oxideav_core::ExecutionContext) {
12589            self.context_threads = ctx.threads;
12590        }
12591    }
12592
12593    /// Resolve a [`Frame::StreamParams`] event into the new input size.
12594    ///
12595    /// VP8 re-states the frame size on every §9.1 key frame, so a size
12596    /// change is accepted (the adapters re-key on it); anything the
12597    /// encoder cannot follow — a non-video description, a pixel format
12598    /// other than [`PixelFormat::Yuv420P`], a size outside the §9.1
12599    /// 14-bit fields — is [`Error::Unsupported`]. Fields the event leaves
12600    /// `None` keep their current value.
12601    fn reconfigure_target(params: &CodecParameters, width: u32, height: u32) -> Result<(u32, u32)> {
12602        if params.media_type != MediaType::Video {
12603            return Err(Error::unsupported(
12604                "vp8 encoder: stream-params event does not describe video",
12605            ));
12606        }
12607        if params
12608            .pixel_format
12609            .is_some_and(|pf| pf != PixelFormat::Yuv420P)
12610        {
12611            return Err(Error::unsupported(
12612                "vp8 encoder: cannot switch away from PixelFormat::Yuv420P mid-stream",
12613            ));
12614        }
12615        let width = params.width.unwrap_or(width);
12616        let height = params.height.unwrap_or(height);
12617        if width == 0 || height == 0 || width > 0x3FFF || height > 0x3FFF {
12618            return Err(Error::unsupported(
12619                "vp8 encoder: stream-params size outside the §9.1 14-bit range (1..=16383)",
12620            ));
12621        }
12622        Ok((width, height))
12623    }
12624
12625    /// Pull the three I420 planes out of `frame` as tightly-packed
12626    /// buffers (validating the layout the encoder needs). Shared by the
12627    /// zero-latency keyframe adapter and the lagged stream adapter.
12628    fn packed_planes_from_video_frame(
12629        frame: &VideoFrame,
12630        width: u32,
12631        height: u32,
12632    ) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
12633        if frame.planes.len() < 3 {
12634            return Err(Error::invalid(
12635                "vp8 encoder: VideoFrame must carry 3 planes (Y/U/V)",
12636            ));
12637        }
12638        let w = width as usize;
12639        let h = height as usize;
12640        let uvw = w.div_ceil(2);
12641        let uvh = h.div_ceil(2);
12642
12643        let y_plane = &frame.planes[0];
12644        let u_plane = &frame.planes[1];
12645        let v_plane = &frame.planes[2];
12646
12647        // Per-plane geometry validation. Two hostile shapes must be
12648        // rejected here rather than detonating in the row repack below:
12649        // a stride narrower than the row width (whose total buffer
12650        // length can still satisfy a naive `stride * rows` check while
12651        // the *last* row read `off .. off + row_w` runs past the end),
12652        // and a stride so large that `stride * rows` wraps `usize`.
12653        // The length requirement is the exact repack footprint —
12654        // `stride * (rows - 1) + row_w` — computed with checked
12655        // arithmetic so overflow is a clean `Err`.
12656        fn validate_plane(
12657            plane: &oxideav_core::frame::VideoPlane,
12658            row_w: usize,
12659            rows: usize,
12660            name: &str,
12661        ) -> Result<()> {
12662            if rows == 0 {
12663                return Ok(());
12664            }
12665            if plane.stride < row_w {
12666                return Err(Error::invalid(format!(
12667                    "vp8 encoder: {name} plane stride {} narrower than row width {row_w}",
12668                    plane.stride
12669                )));
12670            }
12671            let needed = plane
12672                .stride
12673                .checked_mul(rows - 1)
12674                .and_then(|n| n.checked_add(row_w))
12675                .ok_or_else(|| {
12676                    Error::invalid(format!(
12677                        "vp8 encoder: {name} plane stride {} x {rows} rows overflows",
12678                        plane.stride
12679                    ))
12680                })?;
12681            if plane.data.len() < needed {
12682                return Err(Error::invalid(format!(
12683                    "vp8 encoder: {name} plane buffer {} bytes, needs {needed} \
12684                     (stride {}, {rows} rows of {row_w})",
12685                    plane.data.len(),
12686                    plane.stride
12687                )));
12688            }
12689            Ok(())
12690        }
12691        validate_plane(y_plane, w, h, "Y")?;
12692        validate_plane(u_plane, uvw, uvh, "U")?;
12693        validate_plane(v_plane, uvw, uvh, "V")?;
12694
12695        // The direct-API I420Frame requires tightly-packed planes
12696        // (stride == width). Always repack here so the borrow lifetimes
12697        // stay simple; zero-copy is a future optimisation when the
12698        // supplied frame already matches.
12699        Ok((
12700            repack_plane(&y_plane.data, y_plane.stride, w, h),
12701            repack_plane(&u_plane.data, u_plane.stride, uvw, uvh),
12702            repack_plane(&v_plane.data, v_plane.stride, uvw, uvh),
12703        ))
12704    }
12705
12706    /// Pull the three I420 planes out of `frame` (validating the layout
12707    /// the encoder needs), then drive [`encode_keyframe`] with them.
12708    fn encode_video_frame(
12709        frame: &VideoFrame,
12710        width: u32,
12711        height: u32,
12712        keyframe: &KeyframeParams,
12713        options: &KeyframeEncodeOptions,
12714    ) -> Result<Vec<u8>> {
12715        let (y_packed, u_packed, v_packed) = packed_planes_from_video_frame(frame, width, height)?;
12716        let src = I420Frame::packed(width, height, &y_packed, &u_packed, &v_packed);
12717        encode_keyframe_with_options(&src, keyframe, options)
12718            .map_err(|e| Error::invalid(e.to_string()))
12719    }
12720
12721    fn repack_plane(data: &[u8], stride: usize, w: usize, h: usize) -> Vec<u8> {
12722        let mut out = Vec::with_capacity(w * h);
12723        for r in 0..h {
12724            let off = r * stride;
12725            out.extend_from_slice(&data[off..off + w]);
12726        }
12727        out
12728    }
12729}
12730
12731#[cfg(feature = "registry")]
12732pub use factory::{
12733    Vp8EncoderOptions, make_encoder, make_encoder_from_param_options, make_encoder_with_options,
12734    make_encoder_with_qindex, make_encoder_with_quality,
12735};
12736
12737// ───────────────────── 0.1.13 public-surface compatibility ─────────────────────
12738//
12739// The crates.io `oxideav-vp8 0.1.13` release exposed a wider encoder
12740// surface than the post-orphan-rebuild master. This block restores the
12741// public *shape* (struct fields, enum variants, function signatures,
12742// constants) so historical consumers keep building. The bodies of the
12743// two-pass-encoder family stub to [`Vp8Error::Unsupported`] per the
12744// Tier-3 caveat from the round-167 widen — the rate-control algorithm
12745// is intentionally future work; this round locks the symbol surface.
12746//
12747// All items here are reachable under `default-features = false` unless
12748// explicitly gated on `registry`.
12749
12750/// Loop-filter routing strategy — historical 0.1.13 enum re-exposed
12751/// here. The current encoder always emits the §15 normal filter; this
12752/// enum is preserved on the surface so historical configs keep
12753/// compiling.
12754#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12755#[non_exhaustive]
12756pub enum LoopFilterMode {
12757    /// Pick `Normal` for `lf_level < SIMPLE` thresholds, `Simple`
12758    /// otherwise. Default in 0.1.13.
12759    #[default]
12760    Auto,
12761    /// Always use the §15.3 normal filter.
12762    Normal,
12763    /// Always use the §15.2 simple filter.
12764    Simple,
12765}
12766
12767/// Per-frame complexity hint produced by [`first_pass_analyze`] and
12768/// consumed by [`Vp8TwoPassEncoder`]. The 0.1.13 release used this as
12769/// the carrier for the first-pass → second-pass rate-control hand-off.
12770#[derive(Debug, Clone, Copy, PartialEq, Default)]
12771#[non_exhaustive]
12772pub struct FrameComplexity {
12773    /// Source-frame index inside the GOP.
12774    pub frame_index: u32,
12775    /// Estimated bits-per-MB for the source frame (the spec-side
12776    /// "intra cost" surrogate; higher = harder to compress).
12777    pub bits_per_mb: f32,
12778    /// True when the first-pass detected a scene cut between this
12779    /// frame and the previous one.
12780    pub scene_cut: bool,
12781}
12782
12783impl FrameComplexity {
12784    /// Set `frame_index`.
12785    #[must_use]
12786    pub fn with_frame_index(mut self, v: u32) -> Self {
12787        self.frame_index = v;
12788        self
12789    }
12790
12791    /// Set `bits_per_mb`.
12792    #[must_use]
12793    pub fn with_bits_per_mb(mut self, v: f32) -> Self {
12794        self.bits_per_mb = v;
12795        self
12796    }
12797
12798    /// Set `scene_cut`.
12799    #[must_use]
12800    pub fn with_scene_cut(mut self, v: bool) -> Self {
12801        self.scene_cut = v;
12802        self
12803    }
12804}
12805
12806/// Encoder statistics — emitted by every `encode` call so downstream
12807/// muxers can keep running rate / quality counters.
12808#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
12809#[non_exhaustive]
12810pub struct Vp8EncoderStats {
12811    /// Number of frames the encoder has produced so far.
12812    pub frames_encoded: u64,
12813    /// Total emitted byte count across all frames.
12814    pub bytes_emitted: u64,
12815    /// Number of key frames emitted so far.
12816    pub keyframes_emitted: u64,
12817}
12818
12819impl Vp8EncoderStats {
12820    /// Set `frames_encoded`.
12821    #[must_use]
12822    pub fn with_frames_encoded(mut self, v: u64) -> Self {
12823        self.frames_encoded = v;
12824        self
12825    }
12826
12827    /// Set `bytes_emitted`.
12828    #[must_use]
12829    pub fn with_bytes_emitted(mut self, v: u64) -> Self {
12830        self.bytes_emitted = v;
12831        self
12832    }
12833
12834    /// Set `keyframes_emitted`.
12835    #[must_use]
12836    pub fn with_keyframes_emitted(mut self, v: u64) -> Self {
12837        self.keyframes_emitted = v;
12838        self
12839    }
12840}
12841
12842/// Encoder configuration knobs — the 0.1.13 public struct.
12843///
12844/// Each field has a documented default constant (e.g.
12845/// [`DEFAULT_QINDEX`], [`DEFAULT_GOLDEN_INTERVAL`]) so callers can
12846/// override only the knobs they care about. The current encoder honours
12847/// `qindex` and `lf_level` directly; the higher-level knobs (lookahead,
12848/// scene-cut detection, segment-aware QP) are persisted on the struct
12849/// for forward-compat but not yet exercised by the encode body.
12850#[derive(Debug, Clone, Copy, PartialEq)]
12851#[non_exhaustive]
12852pub struct Vp8EncoderConfig {
12853    /// Base `y_ac_qi` quantiser index (§9.6, `0..=127`).
12854    pub qindex: u8,
12855    /// Loop-filter level (`0..=63`).
12856    pub lf_level: u8,
12857    /// Loop-filter routing mode.
12858    pub lf_mode: LoopFilterMode,
12859    /// Golden-frame refresh interval in frames.
12860    pub golden_interval: u32,
12861    /// Alt-ref refresh interval in frames.
12862    pub alt_ref_interval: u32,
12863    /// Lookahead window in frames (first-pass / scene-cut buffer).
12864    pub lookahead_window: u32,
12865    /// One-pass rate control target of the lagged stream paths in bits
12866    /// per second, or 0 (the default) for a constant quantiser: the
12867    /// stream starts at `qindex` and then adapts the quantiser frame by
12868    /// frame (see `AltrefStreamConfig::target_bitrate_bps`).
12869    pub target_bitrate_bps: u32,
12870    /// When `true`, the §9.4 `loop_filter_level` / `sharpness_level` are
12871    /// chosen per frame by the RD selector
12872    /// ([`select_filter_params`]) rather than taken from
12873    /// [`lf_level`](Self::lf_level): the encoder picks the pair minimising
12874    /// post-§15 reconstruction SSD against the source. Defaults to `false`
12875    /// (the historical fixed-`lf_level` behaviour). RFC 6386 is silent on
12876    /// the choice, so this is a clean-room encoder-quality knob.
12877    pub auto_loop_filter: bool,
12878    /// §13 trellis coefficient-RDO aggressiveness — the clean-room
12879    /// quality/size dial threaded onto both the keyframe and inter residual
12880    /// emit (see [`KeyframeParams::trellis_strength`]).
12881    /// [`TrellisStrength::DEFAULT`] reproduces the calibrated trade; higher
12882    /// trades PSNR for smaller output, [`TrellisStrength::OFF`] reverts to
12883    /// plain round-quantisation.
12884    pub trellis_strength: TrellisStrength,
12885    /// Mode-search effort of the key frames this configuration encodes
12886    /// (see [`EncodeEffort`]); inter frames follow
12887    /// [`inter_effort`](Self::inter_effort). Default
12888    /// [`EncodeEffort::Thorough`] — the historical key-frame bytes.
12889    pub effort: EncodeEffort,
12890    /// Thread budget for each frame's macroblock-row wavefront, key and
12891    /// inter frames alike (`0` / `1` = serial, the default). Never
12892    /// changes the bytes.
12893    pub threads: usize,
12894    /// Mode-search effort of the stream's **inter frames** (the lagged
12895    /// stream paths: [`Vp8Encoder::encode_sequence`] and
12896    /// `make_encoder_with_config`). Defaults to
12897    /// [`EncodeEffort::Balanced`].
12898    pub inter_effort: EncodeEffort,
12899    /// §9.5 token partition count (1 / 2 / 4 / 8) of every frame of the
12900    /// lagged stream paths; any other value is treated as 1. More
12901    /// partitions let a decoder parse tokens on several threads.
12902    pub partitions: u8,
12903    /// Frames per second [`target_bitrate_bps`](Self::target_bitrate_bps)
12904    /// is spread over on [`Vp8Encoder::encode_sequence`] (default 30).
12905    /// The registry encoder uses the stream's own frame rate when the
12906    /// codec parameters carry one.
12907    pub frame_rate: f64,
12908}
12909
12910impl Vp8EncoderConfig {
12911    /// Set `effort`.
12912    #[must_use]
12913    pub fn with_effort(mut self, v: EncodeEffort) -> Self {
12914        self.effort = v;
12915        self
12916    }
12917
12918    /// Set `threads`.
12919    #[must_use]
12920    pub fn with_threads(mut self, v: usize) -> Self {
12921        self.threads = v;
12922        self
12923    }
12924
12925    /// Set `inter_effort`.
12926    #[must_use]
12927    pub fn with_inter_effort(mut self, v: EncodeEffort) -> Self {
12928        self.inter_effort = v;
12929        self
12930    }
12931
12932    /// Set `partitions`.
12933    #[must_use]
12934    pub fn with_partitions(mut self, v: u8) -> Self {
12935        self.partitions = v;
12936        self
12937    }
12938
12939    /// Set `frame_rate`.
12940    #[must_use]
12941    pub fn with_frame_rate(mut self, v: f64) -> Self {
12942        self.frame_rate = v;
12943        self
12944    }
12945
12946    /// The §9.5 partition count the lagged stream paths encode with.
12947    fn stream_partitions(&self) -> u8 {
12948        match self.partitions {
12949            2 | 4 | 8 => self.partitions,
12950            _ => 1,
12951        }
12952    }
12953
12954    /// The key-frame speed options this configuration implies.
12955    fn keyframe_options(&self) -> KeyframeEncodeOptions {
12956        KeyframeEncodeOptions::exhaustive()
12957            .with_effort(self.effort)
12958            .with_threads(self.threads)
12959            .with_auto_loop_filter(self.auto_loop_filter)
12960    }
12961
12962    /// Set `qindex`.
12963    #[must_use]
12964    pub fn with_qindex(mut self, v: u8) -> Self {
12965        self.qindex = v;
12966        self
12967    }
12968
12969    /// Set `lf_level`.
12970    #[must_use]
12971    pub fn with_lf_level(mut self, v: u8) -> Self {
12972        self.lf_level = v;
12973        self
12974    }
12975
12976    /// Set `lf_mode`.
12977    #[must_use]
12978    pub fn with_lf_mode(mut self, v: LoopFilterMode) -> Self {
12979        self.lf_mode = v;
12980        self
12981    }
12982
12983    /// Set `golden_interval`.
12984    #[must_use]
12985    pub fn with_golden_interval(mut self, v: u32) -> Self {
12986        self.golden_interval = v;
12987        self
12988    }
12989
12990    /// Set `alt_ref_interval`.
12991    #[must_use]
12992    pub fn with_alt_ref_interval(mut self, v: u32) -> Self {
12993        self.alt_ref_interval = v;
12994        self
12995    }
12996
12997    /// Set `lookahead_window`.
12998    #[must_use]
12999    pub fn with_lookahead_window(mut self, v: u32) -> Self {
13000        self.lookahead_window = v;
13001        self
13002    }
13003
13004    /// Set `target_bitrate_bps`.
13005    #[must_use]
13006    pub fn with_target_bitrate_bps(mut self, v: u32) -> Self {
13007        self.target_bitrate_bps = v;
13008        self
13009    }
13010
13011    /// Set `auto_loop_filter`.
13012    #[must_use]
13013    pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
13014        self.auto_loop_filter = v;
13015        self
13016    }
13017
13018    /// Set `trellis_strength`.
13019    #[must_use]
13020    pub fn with_trellis_strength(mut self, v: TrellisStrength) -> Self {
13021        self.trellis_strength = v;
13022        self
13023    }
13024}
13025
13026impl Default for Vp8EncoderConfig {
13027    fn default() -> Self {
13028        Self {
13029            qindex: DEFAULT_QINDEX,
13030            lf_level: 0,
13031            lf_mode: LoopFilterMode::Auto,
13032            golden_interval: DEFAULT_GOLDEN_INTERVAL,
13033            alt_ref_interval: DEFAULT_ALT_REF_INTERVAL,
13034            lookahead_window: DEFAULT_LOOKAHEAD_WINDOW,
13035            target_bitrate_bps: 0,
13036            auto_loop_filter: false,
13037            trellis_strength: TrellisStrength::DEFAULT,
13038            effort: EncodeEffort::Thorough,
13039            threads: 1,
13040            inter_effort: EncodeEffort::Balanced,
13041            partitions: 1,
13042            frame_rate: 30.0,
13043        }
13044    }
13045}
13046
13047/// Direct-API typed encoder — historical 0.1.13 single-pass entry
13048/// point. Wraps the current encoder's [`KeyframeParams`] /
13049/// [`encode_keyframe`] driver under a single struct so downstream
13050/// consumers that wrote `Vp8Encoder::new(cfg).encode_keyframe(...)`
13051/// keep building.
13052#[derive(Debug, Clone)]
13053pub struct Vp8Encoder {
13054    config: Vp8EncoderConfig,
13055    stats: Vp8EncoderStats,
13056}
13057
13058impl Vp8Encoder {
13059    /// Build a fresh encoder with the supplied config.
13060    pub fn new(config: Vp8EncoderConfig) -> Self {
13061        Self {
13062            config,
13063            stats: Vp8EncoderStats::default(),
13064        }
13065    }
13066
13067    /// Encoder configuration (immutable handle).
13068    pub fn config(&self) -> &Vp8EncoderConfig {
13069        &self.config
13070    }
13071
13072    /// Running encoder statistics.
13073    pub fn stats(&self) -> &Vp8EncoderStats {
13074        &self.stats
13075    }
13076
13077    /// Encode `frame` as a VP8 key frame; returns the on-the-wire
13078    /// bytes. Delegates to the current crate's [`encode_keyframe`]
13079    /// driver using the encoder's [`Vp8EncoderConfig`] for the §9.6
13080    /// quant index and the §9.4 loop-filter level. When
13081    /// [`auto_loop_filter`](Vp8EncoderConfig::auto_loop_filter) is set the
13082    /// §9.4 level / sharpness are RD-selected per frame
13083    /// ([`encode_keyframe_auto_loop_filter`]) and `config.lf_level` is
13084    /// ignored.
13085    pub fn encode_keyframe(&mut self, frame: &I420Frame<'_>) -> crate::error::Result<Vec<u8>> {
13086        let params = KeyframeParams {
13087            y_ac_qi: self.config.qindex,
13088            loop_filter_level: self.config.lf_level,
13089            trellis_strength: self.config.trellis_strength,
13090            ..KeyframeParams::default()
13091        };
13092        let bytes = encode_keyframe_with_options(frame, &params, &self.config.keyframe_options())
13093            .map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?;
13094        self.stats.frames_encoded += 1;
13095        self.stats.keyframes_emitted += 1;
13096        self.stats.bytes_emitted += bytes.len() as u64;
13097        Ok(bytes)
13098    }
13099
13100    /// Encode a whole source sequence as an **auto-altref inter
13101    /// stream** — the round-384 batch front door that finally consumes
13102    /// the config's stream-level knobs:
13103    ///
13104    /// * [`alt_ref_interval`](Vp8EncoderConfig::alt_ref_interval) —
13105    ///   the lookahead group size: every completed group ships one
13106    ///   invisible ARNR anchor (§9.1 `show_frame = 0`, §9.7
13107    ///   `refresh_alternate_frame = 1`) followed by the group's visible
13108    ///   multi-reference P-frames. `0` disables anchors (plain
13109    ///   streaming, group size 1).
13110    /// * [`lookahead_window`](Vp8EncoderConfig::lookahead_window) —
13111    ///   caps the group size (the encoder never buffers more source
13112    ///   frames than this).
13113    /// * [`golden_interval`](Vp8EncoderConfig::golden_interval) — used
13114    ///   as the **key-frame cadence** of the sequence (`0` keys only
13115    ///   frame 0); scene cuts additionally force keys via the stream
13116    ///   driver's default MAD detector.
13117    /// * `qindex` / `lf_level` / `trellis_strength` apply to every
13118    ///   frame, exactly as on [`Self::encode_keyframe`].
13119    ///
13120    /// Returns the full packet list in decode order — **more packets
13121    /// than source frames** (one invisible anchor per group; see
13122    /// [`crate::stream::AltrefStreamPacket`]). Feed them to
13123    /// [`crate::state::Vp8DecoderState::decode_frame`] in order; a
13124    /// player drops packets whose
13125    /// [`is_visible()`](crate::stream::AltrefStreamPacket::is_visible)
13126    /// is `false`.
13127    ///
13128    /// [`auto_loop_filter`](Vp8EncoderConfig::auto_loop_filter) applies
13129    /// per emitted frame (key frames, anchors, and P-frames each get an
13130    /// RD-selected §9.4 level / sharpness; `lf_level` is ignored when
13131    /// it is set). As the offline batch front door, this path
13132    /// additionally enables the §13.4 fitted `token_prob_update()`
13133    /// in-header emission and the §11 intra-within-inter picker on
13134    /// every frame — both quality/density features with a never-grow
13135    /// byte guard, paid for with extra encode passes an offline batch
13136    /// caller accepts. A caller that wants the round-384 single-pass
13137    /// wire drives [`crate::stream::Vp8AltrefStreamEncoder`] directly
13138    /// with those toggles off.
13139    pub fn encode_sequence(
13140        &mut self,
13141        frames: &[I420Frame<'_>],
13142    ) -> crate::error::Result<Vec<crate::stream::AltrefStreamPacket>> {
13143        let window = if self.config.alt_ref_interval == 0 {
13144            1
13145        } else {
13146            self.config
13147                .alt_ref_interval
13148                .min(self.config.lookahead_window.max(1)) as usize
13149        };
13150        let config = crate::stream::AltrefStreamConfig {
13151            params: KeyframeParams {
13152                y_ac_qi: self.config.qindex,
13153                loop_filter_level: self.config.lf_level,
13154                trellis_strength: self.config.trellis_strength,
13155                nbr_of_dct_partitions: self.config.stream_partitions(),
13156                ..KeyframeParams::default()
13157            },
13158            keyframe_interval: u64::from(self.config.golden_interval),
13159            altref_window: window,
13160            auto_loop_filter: self.config.auto_loop_filter,
13161            fitted_token_prob_updates: true,
13162            intra_pick: true,
13163            effort: self.config.effort,
13164            threads: self.config.threads,
13165            inter_effort: self.config.inter_effort,
13166            target_bitrate_bps: self.config.target_bitrate_bps,
13167            frame_rate: self.config.frame_rate,
13168            ..crate::stream::AltrefStreamConfig::default()
13169        };
13170        let mut enc = crate::stream::Vp8AltrefStreamEncoder::new(config)
13171            .expect("window is clamped to >= 1 above");
13172        let mut packets = Vec::new();
13173        for frame in frames {
13174            packets.extend(
13175                enc.push_frame(frame)
13176                    .map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?,
13177            );
13178        }
13179        packets.extend(
13180            enc.finish()
13181                .map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?,
13182        );
13183        for p in &packets {
13184            self.stats.frames_encoded += 1;
13185            self.stats.bytes_emitted += p.bytes.len() as u64;
13186            if p.kind == crate::stream::AltrefPacketKind::Key {
13187                self.stats.keyframes_emitted += 1;
13188            }
13189        }
13190        Ok(packets)
13191    }
13192}
13193
13194/// Two-pass encoder configuration.
13195///
13196/// The two-pass rate-control algorithm uses [`base`](Self::base) as the
13197/// **target** single-pass configuration: `base.qindex` is the per-GOP
13198/// average qindex the second pass aims at, and complexity-driven deltas
13199/// distribute around it (heavier frames → lower qindex / higher quality,
13200/// lighter frames → higher qindex / smaller bytes).
13201///
13202/// [`target_bitrate_bps`](Self::target_bitrate_bps) and
13203/// [`overshoot_ratio`](Self::overshoot_ratio) are persisted on the
13204/// config for downstream callers but are **advisory** in the current
13205/// implementation: the second pass is a complexity-aware constant-quality
13206/// scheduler, not a strict bitrate-constrained CBR loop, so they do not
13207/// alter the emitted bytes today. A future round may use them to clamp
13208/// the per-frame qindex within a bitrate envelope.
13209#[derive(Debug, Clone, Copy, PartialEq)]
13210#[non_exhaustive]
13211pub struct Vp8TwoPassConfig {
13212    /// Underlying single-pass config used as the second-pass baseline.
13213    pub base: Vp8EncoderConfig,
13214    /// Target average bitrate in bits/sec. When non-zero **and** a frame
13215    /// rate is set, the second pass solves for a per-GOP base qindex that
13216    /// makes the predicted byte total meet this budget (see struct docs).
13217    /// `0` keeps the historical complexity-aware constant-quality
13218    /// scheduler centred on `base.qindex`.
13219    pub target_bitrate_bps: u32,
13220    /// Maximum permitted bitrate-overshoot ratio (e.g. `1.2`). The
13221    /// bitrate solver treats `target_bitrate_bps × overshoot_ratio` as
13222    /// the hard per-GOP byte ceiling it must not exceed.
13223    pub overshoot_ratio: f32,
13224    /// Frame-rate numerator (frames per `fps_den` seconds). Used with
13225    /// [`target_bitrate_bps`](Self::target_bitrate_bps) to convert the
13226    /// bits/sec budget into a per-GOP byte budget. `0` disables the
13227    /// bitrate solver (the bitrate budget is undefined without a rate).
13228    pub fps_num: u32,
13229    /// Frame-rate denominator. `0` is treated as `1`.
13230    pub fps_den: u32,
13231    /// When `true`, each second-pass frame's §9.4 `loop_filter_level` is
13232    /// chosen by the RD selector ([`select_filter_level`]) rather than
13233    /// taken from `base.lf_level`: the encoder picks, per frame, the level
13234    /// that minimises post-§15 reconstruction SSD against the source. The
13235    /// chosen level reaches the wire, so decoder lockstep holds. Defaults
13236    /// to `false` (the historical fixed-`base.lf_level` behaviour). RFC
13237    /// 6386 is silent on the level choice, so this is a clean-room
13238    /// encoder-quality knob.
13239    pub auto_loop_filter: bool,
13240}
13241
13242impl Vp8TwoPassConfig {
13243    /// Set `base`.
13244    #[must_use]
13245    pub fn with_base(mut self, v: Vp8EncoderConfig) -> Self {
13246        self.base = v;
13247        self
13248    }
13249
13250    /// Set `target_bitrate_bps`.
13251    #[must_use]
13252    pub fn with_target_bitrate_bps(mut self, v: u32) -> Self {
13253        self.target_bitrate_bps = v;
13254        self
13255    }
13256
13257    /// Set `overshoot_ratio`.
13258    #[must_use]
13259    pub fn with_overshoot_ratio(mut self, v: f32) -> Self {
13260        self.overshoot_ratio = v;
13261        self
13262    }
13263
13264    /// Set `fps_num`.
13265    #[must_use]
13266    pub fn with_fps_num(mut self, v: u32) -> Self {
13267        self.fps_num = v;
13268        self
13269    }
13270
13271    /// Set `fps_den`.
13272    #[must_use]
13273    pub fn with_fps_den(mut self, v: u32) -> Self {
13274        self.fps_den = v;
13275        self
13276    }
13277
13278    /// Set `auto_loop_filter`.
13279    #[must_use]
13280    pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
13281        self.auto_loop_filter = v;
13282        self
13283    }
13284}
13285
13286impl Default for Vp8TwoPassConfig {
13287    fn default() -> Self {
13288        Self {
13289            base: Vp8EncoderConfig::default(),
13290            target_bitrate_bps: 0,
13291            overshoot_ratio: 1.2,
13292            fps_num: 0,
13293            fps_den: 1,
13294            auto_loop_filter: false,
13295        }
13296    }
13297}
13298
13299impl Vp8TwoPassConfig {
13300    /// Frames-per-second as an `f32`, or `None` when no rate is set
13301    /// (`fps_num == 0`). `fps_den == 0` is read as `1`.
13302    pub fn fps(&self) -> Option<f32> {
13303        if self.fps_num == 0 {
13304            None
13305        } else {
13306            Some(self.fps_num as f32 / self.fps_den.max(1) as f32)
13307        }
13308    }
13309
13310    /// True when the bitrate solver is active: a positive target bitrate
13311    /// **and** a usable frame rate are both present. When `false` the
13312    /// second pass stays on the complexity-aware constant-quality
13313    /// schedule centred on [`base.qindex`](Vp8EncoderConfig::qindex).
13314    pub fn bitrate_targeted(&self) -> bool {
13315        self.target_bitrate_bps > 0 && self.fps().is_some()
13316    }
13317}
13318
13319/// Two-pass encoder driver.
13320///
13321/// # Algorithm (clean-room, RFC 6386 §9.6 + in-tree primitives only)
13322///
13323/// RFC 6386 is intentionally silent on rate-control — the algorithm is
13324/// the encoder's choice. This implementation runs in one of two modes,
13325/// selected by [`Vp8TwoPassConfig::bitrate_targeted`]:
13326///
13327/// * **Constant-quality** (no bitrate target): a complexity-aware
13328///   scheduler centred on `config.base.qindex` (steps 1–3 below).
13329/// * **Bitrate-targeted** (`target_bitrate_bps > 0` **and** a frame
13330///   rate set): [`Self::first_pass_analyze`] solves the GOP base qindex
13331///   that fits the budget ([`solve_base_qindex_for_budget`]) and caches
13332///   a per-frame byte allotment. Each [`Self::encode_frame`] then
13333///   re-centres the complexity delta on the solved base and adds a
13334///   closed-loop feedback term proportional to the accumulated rate
13335///   debt (bytes emitted so far minus bytes allotted), so the stream
13336///   self-corrects toward the target. The feedback gain /clamp are
13337///   [`RATE_FEEDBACK_QSTEP_PER_FRAME`] / [`RATE_FEEDBACK_MAX_QSTEP`].
13338///
13339/// The complexity-aware scheduler (both modes share it) is built from a
13340/// single linear pass over the luma plane:
13341///
13342/// 1. **First pass** ([`first_pass_analyze`] / the free fn of the same
13343///    name): for each input frame, compute a lightweight cost surrogate
13344///    from per-pixel luma arithmetic:
13345///    * `mad`  — mean absolute deviation vs the previous frame's luma
13346///      (motion proxy; first frame uses `mad = 0`).
13347///    * `var`  — luma variance vs the per-frame mean (spatial activity
13348///      proxy).
13349///    * `bits_per_mb` (the surrogate) ≈ `α·log2(1+mad) + β·log2(1+var)`,
13350///      multiplied by 100 and clamped non-negative.  A pure-flat frame
13351///      lands near 0; a noise-saturated moving frame lands near 1000.
13352///    * Scene cut: declared when `mad * 1024 / (prev_var + 1)` exceeds
13353///      [`DEFAULT_SCENE_CUT_THRESHOLD`] **and** `mad >=
13354///      SCENE_CUT_ABS_FLOOR / 1024`.
13355///
13356/// 2. **Second pass** ([`two_pass_qindices`] / the free fn of the same
13357///    name): distribute per-frame `qindex` around `config.base.qindex`
13358///    so heavier frames get **lower** qindex (better quality, more
13359///    bytes) and lighter frames get **higher** qindex (lower quality,
13360///    fewer bytes):
13361///    * `mean = mean(bits_per_mb)` across the GOP.
13362///    * `delta = clamp((cost - mean) / max(mean, 1.0) * range, -range, range)`
13363///      where `range = DEFAULT_AQ_QINDEX_RANGE`.
13364///    * `qindex = clamp(base + round(delta), 0, 127)` per RFC 6386 §9.6.
13365///    * Scene cuts subtract an additional [`DEFAULT_SCENE_CUT_QUANT_BOOST`]
13366///      to give those frames extra quality.
13367///
13368/// 3. **Encode pass** ([`Self::encode_frame`]): for each input frame,
13369///    look up its per-frame qindex, build a [`KeyframeParams`] with
13370///    that `y_ac_qi`, and drive the in-tree key/P encoders against the
13371///    reference [`KeyframePlanes`] stashed inside the driver.  The
13372///    first call always emits a key frame; subsequent calls emit P
13373///    frames against the previous reconstruction.
13374///
13375/// The per-frame `qindex` is sourced purely from the supplied
13376/// `complexity` and the `global_mean_cost` cached during the most
13377/// recent [`Self::first_pass_analyze`] call.  A caller that bypasses
13378/// `first_pass_analyze` falls back to a no-delta schedule (every
13379/// frame gets `config.base.qindex`).
13380#[derive(Debug, Clone)]
13381pub struct Vp8TwoPassEncoder {
13382    config: Vp8TwoPassConfig,
13383    /// Mean of `bits_per_mb` across the last [`Self::first_pass_analyze`]
13384    /// call.  `None` until first_pass_analyze runs; in that case
13385    /// [`Self::encode_frame`] falls back to `config.base.qindex` (no
13386    /// per-frame delta).
13387    global_mean_cost: Option<f32>,
13388    /// Most-recent reconstruction kept as the `LAST` reference for the
13389    /// next P-frame encode.  Cleared until the first key frame lands.
13390    last_reconstruction: Option<crate::frame::KeyframePlanes>,
13391    /// Number of frames emitted so far in this stream — determines
13392    /// keyframe vs P-frame and is used by the `golden_interval` /
13393    /// `alt_ref_interval` scheduler (not yet wired into the §9.7
13394    /// refresh ladder; today every P-frame uses
13395    /// [`RefreshControls::default`]).
13396    frame_count: u64,
13397    /// Frame index of the most recent emitted key frame.  Anchors the
13398    /// `golden_interval` / scene-cut keyframe scheduler.
13399    last_keyframe_index: Option<u64>,
13400    /// Base qindex the [`solve_base_qindex_for_budget`] solver chose for
13401    /// this GOP, cached during [`Self::first_pass_analyze`] when the
13402    /// config is bitrate-targeted.  `None` keeps the encoder on the
13403    /// constant-quality schedule centred on `config.base.qindex`.
13404    solved_base_qindex: Option<u8>,
13405    /// Per-frame byte allotment under the bitrate target (= GOP byte
13406    /// budget ÷ frame count), cached alongside `solved_base_qindex`.
13407    /// Drives the closed-loop feedback term: a frame that overspends
13408    /// this allotment pushes subsequent frames' qindex up, and vice
13409    /// versa.
13410    frame_byte_budget: Option<u64>,
13411    /// Running rate debt in bytes: `Σ(emitted − allotment)` across the
13412    /// frames coded so far.  Positive ⇒ the stream is over budget so
13413    /// later frames must use a coarser quantiser; negative ⇒ under
13414    /// budget so quality can be spent.  Only updated on the
13415    /// bitrate-targeted path.
13416    rate_debt_bytes: i64,
13417}
13418
13419impl Vp8TwoPassEncoder {
13420    /// Build a fresh two-pass encoder.
13421    ///
13422    /// The encoder starts with no first-pass state and no reference
13423    /// reconstruction — call [`Self::first_pass_analyze`] before
13424    /// [`Self::encode_frame`] to populate the rate-control mean.
13425    pub fn new(config: Vp8TwoPassConfig) -> Self {
13426        Self {
13427            config,
13428            global_mean_cost: None,
13429            last_reconstruction: None,
13430            frame_count: 0,
13431            last_keyframe_index: None,
13432            solved_base_qindex: None,
13433            frame_byte_budget: None,
13434            rate_debt_bytes: 0,
13435        }
13436    }
13437
13438    /// Two-pass config (immutable handle).
13439    pub fn config(&self) -> &Vp8TwoPassConfig {
13440        &self.config
13441    }
13442
13443    /// First-pass analysis entry — returns the per-frame
13444    /// [`FrameComplexity`] vector **and** caches the GOP-mean cost on
13445    /// `self` so the subsequent [`Self::encode_frame`] calls can pick
13446    /// per-frame qindex deltas relative to it.
13447    ///
13448    /// Delegates to the free function [`first_pass_analyze`] for the
13449    /// core arithmetic; this method exists so a streaming consumer
13450    /// can keep the analysis state on the encoder handle rather than
13451    /// threading the mean by hand.
13452    pub fn first_pass_analyze(
13453        &mut self,
13454        frames: &[I420Frame<'_>],
13455    ) -> crate::error::Result<Vec<FrameComplexity>> {
13456        let stats = first_pass_analyze(frames, &self.config)?;
13457        self.global_mean_cost = Some(mean_complexity_cost(&stats));
13458        // If a bitrate target is set, solve the GOP base qindex now and
13459        // cache the per-frame byte allotment so the second-pass encode
13460        // loop can correct over/undershoot frame-by-frame.  Reset any
13461        // debt carried from a previous analysis.
13462        self.rate_debt_bytes = 0;
13463        if self.config.bitrate_targeted() && !stats.is_empty() {
13464            let (w, h) = frames
13465                .first()
13466                .map(|f| (f.width, f.height))
13467                .unwrap_or((0, 0));
13468            self.solved_base_qindex =
13469                Some(solve_base_qindex_for_budget(&self.config, &stats, w, h));
13470            self.frame_byte_budget =
13471                gop_byte_budget(&self.config, stats.len()).map(|b| b / stats.len() as u64);
13472        } else {
13473            self.solved_base_qindex = None;
13474            self.frame_byte_budget = None;
13475        }
13476        Ok(stats)
13477    }
13478
13479    /// Second-pass encode of one frame, picking the qindex from the
13480    /// first-pass complexity report.
13481    ///
13482    /// The first call always emits a key frame; subsequent calls emit
13483    /// a P-frame against the previous reconstruction.  The complexity
13484    /// report's `scene_cut` flag forces a key frame even mid-stream.
13485    /// Returns the raw VP8 bitstream bytes for the frame.
13486    pub fn encode_frame(
13487        &mut self,
13488        frame: &I420Frame<'_>,
13489        complexity: FrameComplexity,
13490    ) -> crate::error::Result<Vec<u8>> {
13491        let qindex = self.qindex_for(complexity);
13492        let params = KeyframeParams {
13493            y_ac_qi: qindex,
13494            loop_filter_level: self.config.base.lf_level,
13495            trellis_strength: self.config.base.trellis_strength,
13496            ..KeyframeParams::default()
13497        };
13498
13499        // Schedule key vs P frame.  Force-keyframe conditions:
13500        //   * No prior reference (first call or right after a complexity
13501        //     report that demanded a key frame).
13502        //   * Scene cut flagged in the supplied complexity.
13503        //   * Golden interval elapsed since the last keyframe (acts as
13504        //     a max-GOP guard so a long P-chain doesn't accumulate
13505        //     drift).
13506        let force_key = self.last_reconstruction.is_none()
13507            || complexity.scene_cut
13508            || self
13509                .last_keyframe_index
13510                .map(|anchor| {
13511                    self.frame_count.saturating_sub(anchor)
13512                        >= self.config.base.golden_interval.max(1) as u64
13513                })
13514                .unwrap_or(false);
13515
13516        // §9.4 auto loop-filter: when enabled, the per-frame
13517        // `loop_filter_level` is the RD selector's choice rather than
13518        // `base.lf_level`. The auto entry points write the chosen level to
13519        // the wire so decoder lockstep holds either way.
13520        let auto_lf = self.config.auto_loop_filter;
13521        let (bytes, planes) = if force_key {
13522            encode_keyframe_with_reconstruction_and_options(
13523                frame,
13524                &params,
13525                &self
13526                    .config
13527                    .base
13528                    .keyframe_options()
13529                    .with_auto_loop_filter(auto_lf),
13530            )
13531            .map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?
13532        } else {
13533            let reference = self
13534                .last_reconstruction
13535                .as_ref()
13536                .expect("force_key=false implies a reference exists");
13537            if auto_lf {
13538                encode_p_frame_multi_ref_auto_loop_filter(frame, reference, None, None, &params)
13539            } else {
13540                encode_p_frame_multi_ref(frame, reference, None, None, &params)
13541            }
13542            .map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?
13543        };
13544
13545        self.last_reconstruction = Some(planes);
13546        if force_key {
13547            self.last_keyframe_index = Some(self.frame_count);
13548        }
13549        // Closed-loop accounting: fold this frame's over/undershoot vs
13550        // its allotment into the running debt so the next frame's
13551        // `qindex_for` can correct it.  Only meaningful on the
13552        // bitrate-targeted path (frame_byte_budget is `None` otherwise).
13553        if let Some(budget) = self.frame_byte_budget {
13554            let spent = bytes.len() as i64;
13555            self.rate_debt_bytes = self.rate_debt_bytes.saturating_add(spent - budget as i64);
13556        }
13557        self.frame_count += 1;
13558        Ok(bytes)
13559    }
13560
13561    /// Current accumulated rate debt in bytes (positive ⇒ over budget).
13562    /// Exposed so a streaming caller can observe how the closed-loop
13563    /// bitrate controller is tracking the target.  Always `0` on the
13564    /// constant-quality (no bitrate target) path.
13565    pub fn rate_debt_bytes(&self) -> i64 {
13566        self.rate_debt_bytes
13567    }
13568
13569    /// Resolve the per-frame qindex from the cached first-pass mean
13570    /// (falling back to `config.base.qindex` when first_pass_analyze
13571    /// hasn't been called).  Centralised so the [`Self::encode_frame`]
13572    /// path and the public [`two_pass_qindex_for_frame`] free function
13573    /// agree on the formula.
13574    ///
13575    /// On the bitrate-targeted path the base qindex is the solver's
13576    /// choice (cached during [`Self::first_pass_analyze`]) plus a
13577    /// closed-loop feedback term proportional to the accumulated
13578    /// [`Self::rate_debt_bytes`]: a stream that has overspent its
13579    /// allotment so far nudges this frame's qindex up (coarser, cheaper)
13580    /// and an under-budget stream nudges it down (finer, higher
13581    /// quality).  Without a bitrate target the behaviour is unchanged.
13582    fn qindex_for(&self, complexity: FrameComplexity) -> u8 {
13583        // Constant-quality (no bitrate target): unchanged historical path.
13584        let Some(solved_base) = self.solved_base_qindex else {
13585            return match self.global_mean_cost {
13586                Some(mean) => qindex_from_complexity(&self.config, complexity, mean),
13587                None => qindex_from_complexity(&self.config, complexity, complexity.bits_per_mb),
13588            };
13589        };
13590        // Bitrate-targeted: re-centre the complexity delta on the solved
13591        // base, then add the feedback correction.
13592        let mut cfg = self.config;
13593        cfg.base.qindex = solved_base;
13594        let mean = self.global_mean_cost.unwrap_or(complexity.bits_per_mb);
13595        let centred = qindex_from_complexity(&cfg, complexity, mean) as i32;
13596        let correction = self.rate_feedback_delta();
13597        (centred + correction).clamp(0, 127) as u8
13598    }
13599
13600    /// Closed-loop feedback delta (in qindex units) from the running
13601    /// rate debt.  Scales the accumulated over/undershoot by the
13602    /// per-frame byte allotment: roughly one qindex step per
13603    /// [`RATE_FEEDBACK_BYTES_PER_QSTEP`] fraction of an allotment of
13604    /// debt, clamped to ±[`RATE_FEEDBACK_MAX_QSTEP`] so a single noisy
13605    /// frame can't slam the quantiser to an extreme.  Returns `0` when
13606    /// no per-frame budget is known.
13607    fn rate_feedback_delta(&self) -> i32 {
13608        let Some(budget) = self.frame_byte_budget else {
13609            return 0;
13610        };
13611        if budget == 0 {
13612            return 0;
13613        }
13614        // debt as a multiple of one frame's allotment.
13615        let debt_frames = self.rate_debt_bytes as f32 / budget as f32;
13616        let raw = (debt_frames * RATE_FEEDBACK_QSTEP_PER_FRAME as f32).round() as i32;
13617        raw.clamp(-RATE_FEEDBACK_MAX_QSTEP, RATE_FEEDBACK_MAX_QSTEP)
13618    }
13619}
13620
13621/// Free-function first-pass analysis — historical 0.1.13 entry point.
13622///
13623/// Walks `frames` end-to-end and produces one [`FrameComplexity`] per
13624/// input.  The cost surrogate is documented on [`Vp8TwoPassEncoder`]:
13625/// a lightweight log-MAD + log-variance combination on the 8-bit luma
13626/// plane.  Pure RFC 6386 §9.6-qindex-range math; no transform, no
13627/// entropy coding, no reference-encoder consultation.
13628///
13629/// Returns an empty `Vec` for an empty input slice.  Caller-supplied
13630/// frame dimensions are honoured frame-by-frame (varying dimensions
13631/// across the slice are allowed — only the per-frame stats use the
13632/// dimensions; no cross-frame pixel arithmetic crosses dimension
13633/// boundaries).
13634pub fn first_pass_analyze(
13635    frames: &[I420Frame<'_>],
13636    _config: &Vp8TwoPassConfig,
13637) -> crate::error::Result<Vec<FrameComplexity>> {
13638    let mut out = Vec::with_capacity(frames.len());
13639    let mut prev_luma_sample: Option<(Vec<u8>, u32, u32)> = None;
13640    let mut prev_variance: f32 = 0.0;
13641    for (idx, frame) in frames.iter().enumerate() {
13642        let (_mean, variance) = luma_mean_and_variance(frame);
13643        let mad = match &prev_luma_sample {
13644            Some((prev, pw, ph)) if *pw == frame.width && *ph == frame.height => {
13645                luma_mad(frame, prev)
13646            }
13647            _ => 0.0,
13648        };
13649        // Cost surrogate: scale-invariant log combination so a flat
13650        // frame lands near zero and a textured / fast-motion frame
13651        // lands at a few hundred.  α / β picked so a frame with
13652        // mad=10, var=200 lands around 100 bits/MB (matches the
13653        // ballpark "expected" per-MB cost at the default qindex).
13654        let cost = 30.0 * (1.0 + mad).log2() + 25.0 * (1.0 + variance).log2();
13655        let cost = cost.max(0.0);
13656        // Scene-cut decision: the §9.4 / §20.6 spec is silent; the
13657        // surrogate compares mad-vs-prev-variance against the
13658        // `DEFAULT_SCENE_CUT_THRESHOLD` knob, gated by the
13659        // `SCENE_CUT_ABS_FLOOR` minimum so a static scene with tiny
13660        // numerical noise doesn't false-positive.
13661        let scene_cut = if idx == 0 {
13662            false
13663        } else {
13664            let ratio = (mad * 1024.0) / (prev_variance + 1.0);
13665            ratio >= DEFAULT_SCENE_CUT_THRESHOLD as f32
13666                && (mad * 1024.0) >= SCENE_CUT_ABS_FLOOR as f32
13667        };
13668        out.push(FrameComplexity {
13669            frame_index: idx as u32,
13670            bits_per_mb: cost,
13671            scene_cut,
13672        });
13673        // Snapshot the luma plane for the next iteration's MAD calc.
13674        // We copy because the borrow of `frame.y` doesn't survive the
13675        // next loop iteration.
13676        let plane_len = (frame.height as usize) * frame.y_stride;
13677        let mut buf = vec![0u8; plane_len];
13678        let take = plane_len.min(frame.y.len());
13679        buf[..take].copy_from_slice(&frame.y[..take]);
13680        prev_luma_sample = Some((buf, frame.width, frame.height));
13681        prev_variance = variance;
13682    }
13683    Ok(out)
13684}
13685
13686/// Returns the second-pass qindex the encoder would select for a
13687/// particular frame, given just the per-frame [`FrameComplexity`].
13688///
13689/// This is the **stateless** variant: it has no access to a GOP-mean,
13690/// so it treats `complexity.bits_per_mb` as both the per-frame cost
13691/// *and* the reference mean — which collapses the rate-control delta
13692/// to zero for every non-scene-cut frame.  Useful when a caller only
13693/// has one frame's worth of data; for a full GOP the schedule
13694/// produced by [`two_pass_qindices`] (which uses the actual mean)
13695/// is what [`Vp8TwoPassEncoder::encode_frame`] consumes.
13696///
13697/// Scene-cut frames receive a [`DEFAULT_SCENE_CUT_QUANT_BOOST`]-sized
13698/// qindex *reduction* (better quality) on top of the baseline.
13699///
13700/// Returns `Err(Vp8Error::InvalidData)` if `config.base.qindex` is
13701/// outside the RFC 6386 §9.6 `0..=127` range.
13702pub fn two_pass_qindex_for_frame(
13703    config: &Vp8TwoPassConfig,
13704    complexity: FrameComplexity,
13705) -> crate::error::Result<u8> {
13706    if config.base.qindex > 127 {
13707        return Err(crate::error::Vp8Error::invalid(format!(
13708            "vp8 two-pass: config.base.qindex={} out of RFC 6386 §9.6 range 0..=127",
13709            config.base.qindex
13710        )));
13711    }
13712    Ok(qindex_from_complexity(
13713        config,
13714        complexity,
13715        complexity.bits_per_mb,
13716    ))
13717}
13718
13719/// Returns the full second-pass qindex schedule for a GOP.
13720///
13721/// Computes the GOP mean from `complexities` and emits one
13722/// `0..=127` qindex per entry per the algorithm documented on
13723/// [`Vp8TwoPassEncoder`].  An empty input yields an empty schedule.
13724///
13725/// Returns `Err(Vp8Error::InvalidData)` if `config.base.qindex` is
13726/// outside `0..=127`.
13727pub fn two_pass_qindices(
13728    config: &Vp8TwoPassConfig,
13729    complexities: &[FrameComplexity],
13730) -> crate::error::Result<Vec<u8>> {
13731    if config.base.qindex > 127 {
13732        return Err(crate::error::Vp8Error::invalid(format!(
13733            "vp8 two-pass: config.base.qindex={} out of RFC 6386 §9.6 range 0..=127",
13734            config.base.qindex
13735        )));
13736    }
13737    if complexities.is_empty() {
13738        return Ok(Vec::new());
13739    }
13740    let mean = mean_complexity_cost(complexities);
13741    Ok(complexities
13742        .iter()
13743        .map(|c| qindex_from_complexity(config, *c, mean))
13744        .collect())
13745}
13746
13747/// Build a two-pass encoder from a [`Vp8TwoPassConfig`].  Convenience
13748/// historical-0.1.13 factory; equivalent to
13749/// [`Vp8TwoPassEncoder::new`].
13750pub fn make_two_pass_encoder(config: Vp8TwoPassConfig) -> Vp8TwoPassEncoder {
13751    Vp8TwoPassEncoder::new(config)
13752}
13753
13754// ─────────────── bitrate-budget solver (clean-room) ───────────────
13755//
13756// RFC 6386 fixes the §9.6 qindex ladder but is silent on how an
13757// encoder hits a bitrate. The solver below turns a bits/sec target
13758// into a per-GOP byte budget and bisects the §9.6 qindex range for
13759// the *lowest* base qindex (= highest quality) whose predicted byte
13760// total still fits the budget. Prediction is the in-tree bit-cost
13761// model ([`estimate_frame_bytes`]); no reference encoder is read.
13762
13763/// The per-GOP byte budget implied by a bitrate target and frame rate.
13764///
13765/// `bytes = (target_bitrate_bps / 8) × (frame_count / fps)`. Returns
13766/// `None` when the config has no usable bitrate / frame-rate pair
13767/// (i.e. [`Vp8TwoPassConfig::bitrate_targeted`] is `false`) or when
13768/// `frame_count == 0`.
13769pub fn gop_byte_budget(config: &Vp8TwoPassConfig, frame_count: usize) -> Option<u64> {
13770    if frame_count == 0 {
13771        return None;
13772    }
13773    // `fps()` only yields `Some` when `fps_num != 0`, so the rate is
13774    // always strictly positive and finite here.
13775    let fps = config.fps()?;
13776    if config.target_bitrate_bps == 0 {
13777        return None;
13778    }
13779    let bytes_per_sec = config.target_bitrate_bps as f64 / 8.0;
13780    let gop_seconds = frame_count as f64 / fps as f64;
13781    Some((bytes_per_sec * gop_seconds).floor() as u64)
13782}
13783
13784/// Predicted total encoded bytes for a GOP if every frame were coded
13785/// at the same `base_qindex` (before per-frame AQ redistribution).
13786///
13787/// Sums [`estimate_frame_bytes`] over each frame's complexity at
13788/// `base_qindex`. All frames are assumed to share `width × height`.
13789fn predict_gop_bytes_at_qindex(
13790    complexities: &[FrameComplexity],
13791    width: u32,
13792    height: u32,
13793    base_qindex: i32,
13794) -> u64 {
13795    complexities.iter().fold(0u64, |acc, c| {
13796        acc.saturating_add(estimate_frame_bytes(
13797            c.bits_per_mb,
13798            base_qindex,
13799            width,
13800            height,
13801        ))
13802    })
13803}
13804
13805/// Solve for the GOP base qindex that meets `config`'s bitrate budget.
13806///
13807/// Returns the **lowest** §9.6 qindex (best quality) whose predicted
13808/// byte total — summed over `complexities` at that single qindex via
13809/// the in-tree bit-cost model — stays within
13810/// `target_bitrate_bps × overshoot_ratio`. If even qindex 127 (the
13811/// coarsest quantiser) overshoots, returns 127; if even qindex 0 fits,
13812/// returns 0.
13813///
13814/// Returns `config.base.qindex` unchanged when
13815/// [`Vp8TwoPassConfig::bitrate_targeted`] is `false` (no bitrate
13816/// solving requested) or the GOP is empty.
13817///
13818/// The search is a monotone bisection: predicted bytes decrease as the
13819/// qindex rises (coarser quantiser ⇒ fewer tokens), so the smallest
13820/// qindex meeting the ceiling is found in `log2(128) ≤ 7` model
13821/// evaluations of the GOP.
13822pub fn solve_base_qindex_for_budget(
13823    config: &Vp8TwoPassConfig,
13824    complexities: &[FrameComplexity],
13825    width: u32,
13826    height: u32,
13827) -> u8 {
13828    if !config.bitrate_targeted() || complexities.is_empty() {
13829        return config.base.qindex.min(127);
13830    }
13831    let budget = match gop_byte_budget(config, complexities.len()) {
13832        Some(b) => b,
13833        None => return config.base.qindex.min(127),
13834    };
13835    // Hard ceiling = budget × overshoot. overshoot_ratio < 1.0 is
13836    // nonsensical (would forbid even hitting the target); clamp to 1.0.
13837    let ceiling = {
13838        let r = config.overshoot_ratio.max(1.0) as f64;
13839        (budget as f64 * r) as u64
13840    };
13841    // predicted(qindex) is monotone non-increasing in qindex. Find the
13842    // smallest qindex whose predicted total ≤ ceiling.
13843    let fits = |qi: i32| predict_gop_bytes_at_qindex(complexities, width, height, qi) <= ceiling;
13844    // Coarsest quantiser still overshoots ⇒ nothing we can do, cap at 127.
13845    if !fits(127) {
13846        return 127;
13847    }
13848    // Finest quantiser already fits ⇒ spend all the quality.
13849    if fits(0) {
13850        return 0;
13851    }
13852    // Bisect for the boundary: lo never fits, hi always fits.
13853    let mut lo = 0i32; // !fits(lo) holds (fits(0) was false above)
13854    let mut hi = 127i32; // fits(hi) holds
13855    while hi - lo > 1 {
13856        let mid = (lo + hi) / 2;
13857        if fits(mid) {
13858            hi = mid;
13859        } else {
13860            lo = mid;
13861        }
13862    }
13863    hi as u8
13864}
13865
13866/// Full second-pass qindex schedule under a bitrate target.
13867///
13868/// First solves the GOP base qindex via
13869/// [`solve_base_qindex_for_budget`], then redistributes per-frame
13870/// qindex around *that* solved base using the same complexity-aware
13871/// delta as [`two_pass_qindices`] (heavier frames → lower qindex). The
13872/// result is a schedule whose **mean** tracks the bitrate budget while
13873/// individual frames still flex with complexity.
13874///
13875/// When the config is not bitrate-targeted this is identical to
13876/// [`two_pass_qindices`] (the base qindex stays `config.base.qindex`).
13877///
13878/// Returns `Err(Vp8Error::InvalidData)` if `config.base.qindex` is
13879/// outside `0..=127`.
13880pub fn two_pass_qindices_for_bitrate(
13881    config: &Vp8TwoPassConfig,
13882    complexities: &[FrameComplexity],
13883    width: u32,
13884    height: u32,
13885) -> crate::error::Result<Vec<u8>> {
13886    if config.base.qindex > 127 {
13887        return Err(crate::error::Vp8Error::invalid(format!(
13888            "vp8 two-pass: config.base.qindex={} out of RFC 6386 §9.6 range 0..=127",
13889            config.base.qindex
13890        )));
13891    }
13892    if complexities.is_empty() {
13893        return Ok(Vec::new());
13894    }
13895    let solved_base = solve_base_qindex_for_budget(config, complexities, width, height);
13896    // Re-centre the delta math on the solved base by cloning the config
13897    // with base.qindex replaced. The per-frame delta + scene-cut boost
13898    // are unchanged.
13899    let mut solved_config = *config;
13900    solved_config.base.qindex = solved_base;
13901    let mean = mean_complexity_cost(complexities);
13902    Ok(complexities
13903        .iter()
13904        .map(|c| qindex_from_complexity(&solved_config, *c, mean))
13905        .collect())
13906}
13907
13908// ──────────────────── two-pass helpers (private) ────────────────────
13909
13910/// Mean cost across a per-frame complexity vector — empty input maps
13911/// to `0.0` so the caller's downstream division-by-mean falls back to
13912/// the fallback path.
13913fn mean_complexity_cost(stats: &[FrameComplexity]) -> f32 {
13914    if stats.is_empty() {
13915        0.0
13916    } else {
13917        let sum: f32 = stats.iter().map(|c| c.bits_per_mb).sum();
13918        sum / stats.len() as f32
13919    }
13920}
13921
13922// ─────────────────── bit-cost model (clean-room) ───────────────────
13923//
13924// RFC 6386 is silent on rate control by design (§9.6 only fixes the
13925// quantiser ladder; the encoder chooses how to spend bits). The
13926// closed-loop bitrate target below needs a way to predict, *before*
13927// entropy-coding a frame, roughly how many bits it will cost at a
13928// candidate qindex. The model is built only from the in-tree
13929// complexity surrogate plus the §20.4 AC quantiser ladder; no
13930// reference encoder is consulted.
13931//
13932// Shape: encoded frame bits fall as the quantiser step grows (coarser
13933// quant → more coefficients quantise to zero → fewer tokens). The
13934// §20.4 `ac_qlookup` step at qindex 0 is 4 and at qindex 127 is 284 —
13935// a ~71× span. We model the per-MB bit cost as the first-pass
13936// `bits_per_mb` surrogate divided by a power of the AC step, so a
13937// flat frame stays cheap at every qindex and a busy frame's cost
13938// collapses as the quantiser coarsens.
13939
13940/// Exponent γ on the AC quantiser step in the bit-cost model
13941/// (fixed-point ×256). A γ near 1.0 makes predicted bits roughly
13942/// inversely proportional to the quantiser step. `RATE_MODEL_GAMMA_X256
13943/// / 256.0` is the effective exponent.
13944pub const RATE_MODEL_GAMMA_X256: i32 = 200;
13945
13946/// Closed-loop feedback gain: qindex steps applied per one full
13947/// frame-allotment of accumulated rate debt. A gain of 4 means a
13948/// stream that is one whole frame's worth of bytes over budget nudges
13949/// the next frame's qindex up by 4 (coarser / cheaper). Kept modest so
13950/// the loop settles rather than oscillates.
13951pub const RATE_FEEDBACK_QSTEP_PER_FRAME: i32 = 4;
13952
13953/// Clamp on the per-frame closed-loop feedback correction (qindex
13954/// units), so a single pathological frame's debt can't slam the
13955/// quantiser to an extreme in one step.
13956pub const RATE_FEEDBACK_MAX_QSTEP: i32 = 24;
13957
13958/// Per-MB additive floor (in bits) the bit-cost model charges every
13959/// macroblock regardless of quantiser — mode bits, the always-present
13960/// per-MB header tokens, and the residual the quantiser can never
13961/// drive fully to zero. Keeps the model from predicting a literally
13962/// zero-bit frame at the coarsest quantiser.
13963pub const RATE_MODEL_MB_FLOOR_BITS: f32 = 6.0;
13964
13965/// Reference AC quantiser step the surrogate was calibrated against.
13966/// `first_pass_analyze`'s `bits_per_mb` is tuned (§ its rustdoc) so a
13967/// `mad=10, var=200` frame lands near 100 — read as "≈100 bits/MB at
13968/// the default qindex". The §20.4 AC step at [`DEFAULT_QINDEX`] (50)
13969/// is the divisor that makes the model reproduce that reading, so the
13970/// surrogate value *is* the predicted bits/MB at the reference step.
13971const RATE_MODEL_REF_QINDEX: usize = DEFAULT_QINDEX as usize;
13972
13973/// The §20.4 AC quantiser step for a clamped qindex.
13974#[inline]
13975fn ac_step_for_qindex(qindex: i32) -> f32 {
13976    crate::inverse_transform::AC_QLOOKUP[crate::inverse_transform::clamp_qindex(qindex)] as f32
13977}
13978
13979/// Predict the encoded **bits per macroblock** for a frame of the
13980/// given complexity at a candidate `qindex`.
13981///
13982/// Clean-room model (see the module comment above): the first-pass
13983/// `bits_per_mb` surrogate is the predicted cost at
13984/// [`RATE_MODEL_REF_QINDEX`]; scaling to another qindex multiplies by
13985/// `(ref_step / step) ^ γ`, then a per-MB floor is added so the
13986/// coarsest quantiser still charges header / mode bits.
13987pub fn estimate_bits_per_mb(complexity: f32, qindex: i32) -> f32 {
13988    let gamma = RATE_MODEL_GAMMA_X256 as f32 / 256.0;
13989    let ref_step = ac_step_for_qindex(RATE_MODEL_REF_QINDEX as i32);
13990    let step = ac_step_for_qindex(qindex);
13991    // `complexity` is the surrogate's reading at the reference step;
13992    // a coarser (larger) step than the reference scales the cost down.
13993    let scaled = complexity.max(0.0) * (ref_step / step).powf(gamma);
13994    scaled + RATE_MODEL_MB_FLOOR_BITS
13995}
13996
13997/// Predict the encoded **byte** count for one whole frame at `qindex`.
13998///
13999/// Multiplies [`estimate_bits_per_mb`] by the macroblock count implied
14000/// by `width × height` (16×16 MBs, partial MBs rounded up per §2), then
14001/// converts to bytes (÷8, rounded up).
14002pub fn estimate_frame_bytes(complexity: f32, qindex: i32, width: u32, height: u32) -> u64 {
14003    let mb_cols = (width as u64).div_ceil(16);
14004    let mb_rows = (height as u64).div_ceil(16);
14005    let mb_count = mb_cols.saturating_mul(mb_rows);
14006    let bits_per_mb = estimate_bits_per_mb(complexity, qindex);
14007    let total_bits = (bits_per_mb.max(0.0) as f64) * (mb_count as f64);
14008    (total_bits / 8.0).ceil() as u64
14009}
14010
14011/// Mean luma value and variance for one frame.  Single linear pass
14012/// over `frame.y` honouring `frame.y_stride`.
14013fn luma_mean_and_variance(frame: &I420Frame<'_>) -> (f32, f32) {
14014    let w = frame.width as usize;
14015    let h = frame.height as usize;
14016    if w == 0 || h == 0 {
14017        return (0.0, 0.0);
14018    }
14019    let stride = frame.y_stride.max(w);
14020    let mut sum: u64 = 0;
14021    let mut sumsq: u64 = 0;
14022    let mut count: u64 = 0;
14023    for r in 0..h {
14024        let row_off = r * stride;
14025        // The luma slice may be sized for fewer rows than `h` (the
14026        // I420Frame::packed builder enforces tight packing but defensive
14027        // callers may pass shorter slices); clamp at the slice length.
14028        if row_off >= frame.y.len() {
14029            break;
14030        }
14031        let row_end = (row_off + w).min(frame.y.len());
14032        for &px in &frame.y[row_off..row_end] {
14033            sum += px as u64;
14034            sumsq += (px as u64) * (px as u64);
14035            count += 1;
14036        }
14037    }
14038    if count == 0 {
14039        return (0.0, 0.0);
14040    }
14041    let count_f = count as f32;
14042    let mean = sum as f32 / count_f;
14043    // var = E[X²] - E[X]² (one-pass formula; numerically OK for u8
14044    // pixel values where the dynamic range is bounded).
14045    let var = (sumsq as f32 / count_f) - (mean * mean);
14046    (mean, var.max(0.0))
14047}
14048
14049/// Mean absolute deviation of `frame.y` vs the supplied previous
14050/// luma plane (assumed identical layout).
14051fn luma_mad(frame: &I420Frame<'_>, prev: &[u8]) -> f32 {
14052    let w = frame.width as usize;
14053    let h = frame.height as usize;
14054    if w == 0 || h == 0 {
14055        return 0.0;
14056    }
14057    let stride = frame.y_stride.max(w);
14058    let mut sum: u64 = 0;
14059    let mut count: u64 = 0;
14060    for r in 0..h {
14061        let row_off = r * stride;
14062        if row_off >= frame.y.len() || row_off >= prev.len() {
14063            break;
14064        }
14065        let row_end = (row_off + w).min(frame.y.len()).min(prev.len());
14066        let cur = &frame.y[row_off..row_end];
14067        let pre = &prev[row_off..row_end];
14068        for (a, b) in cur.iter().zip(pre.iter()) {
14069            sum += (*a as i32 - *b as i32).unsigned_abs() as u64;
14070            count += 1;
14071        }
14072    }
14073    if count == 0 {
14074        0.0
14075    } else {
14076        sum as f32 / count as f32
14077    }
14078}
14079
14080/// Compute the per-frame qindex from a complexity record and a
14081/// reference mean cost.  Higher-than-mean cost ⇒ negative delta ⇒
14082/// lower qindex (better quality).  The delta is clamped to the
14083/// configured [`DEFAULT_AQ_QINDEX_RANGE`] either side of
14084/// `config.base.qindex`, then to the RFC 6386 §9.6 `0..=127` range.
14085/// Scene cuts add a [`DEFAULT_SCENE_CUT_QUANT_BOOST`] quality
14086/// boost (subtraction).
14087fn qindex_from_complexity(
14088    config: &Vp8TwoPassConfig,
14089    complexity: FrameComplexity,
14090    reference_mean: f32,
14091) -> u8 {
14092    let base = config.base.qindex as i32;
14093    let range = DEFAULT_AQ_QINDEX_RANGE.max(0);
14094    let delta = if reference_mean > 1.0 {
14095        let normed = (complexity.bits_per_mb - reference_mean) / reference_mean;
14096        // Negate: higher cost ⇒ lower qindex.
14097        let raw = -(normed * range as f32);
14098        raw.round() as i32
14099    } else {
14100        0
14101    };
14102    let mut qindex = base + delta.clamp(-range, range);
14103    if complexity.scene_cut {
14104        qindex -= DEFAULT_SCENE_CUT_QUANT_BOOST;
14105    }
14106    qindex.clamp(0, 127) as u8
14107}
14108
14109/// Framework-side factory that takes a full [`Vp8EncoderConfig`]
14110/// (rather than just a qindex). Honours `qindex`, the §9.4 `lf_level`,
14111/// and the [`auto_loop_filter`](Vp8EncoderConfig::auto_loop_filter)
14112/// RD-selection switch; when the latter is set the §9.4 level / sharpness
14113/// are chosen per frame and `lf_level` is ignored.
14114#[cfg(feature = "registry")]
14115pub fn make_encoder_with_config(
14116    params: &oxideav_core::CodecParameters,
14117    config: Vp8EncoderConfig,
14118) -> oxideav_core::Result<Box<dyn oxideav_core::Encoder>> {
14119    factory::make_encoder_from_config(params, config)
14120}
14121
14122/// Build a [`Vp8Encoder`] (the typed direct-API handle) from a
14123/// [`Vp8EncoderConfig`]. The "typed" variant returns the concrete
14124/// struct rather than a `Box<dyn Encoder>`; reachable under
14125/// `--no-default-features`.
14126pub fn make_encoder_typed_with_config(config: Vp8EncoderConfig) -> Vp8Encoder {
14127    Vp8Encoder::new(config)
14128}
14129
14130// ─────────────── 0.1.13 encoder constants — type / ballpark defaults ───────────────
14131//
14132// The 0.1.13 release shipped a long list of tuning constants. The
14133// numeric values below match the documented defaults from the
14134// per-version rustdoc (where available) or use the documented
14135// "ballpark" the spec calls out. They are public so historical
14136// consumers can pattern-match against them; the encoder itself does
14137// not consume every entry yet.
14138
14139/// Default `y_ac_qi` (§9.6) for the single-pass encoder.
14140pub const DEFAULT_QINDEX: u8 = 50;
14141/// Max value the adaptive-QP range may add to the base qindex.
14142pub const AQ_QINDEX_RANGE_MAX: i32 = 16;
14143/// Default adaptive-QP qindex range (±delta around the base qindex).
14144pub const DEFAULT_AQ_QINDEX_RANGE: i32 = 8;
14145/// Per-segment adaptive-QP variance thresholds (4 segments — VP8 §10).
14146pub const DEFAULT_ADAPTIVE_SEGMENT_THRESHOLDS: [u32; 4] = [80, 320, 1_280, 5_120];
14147/// Default alt-ref refresh interval in frames.
14148pub const DEFAULT_ALT_REF_INTERVAL: u32 = 16;
14149/// Default golden-frame refresh interval in frames.
14150pub const DEFAULT_GOLDEN_INTERVAL: u32 = 8;
14151/// Default chroma-aware spatial chroma weight (fixed-point ×256).
14152pub const DEFAULT_CHROMA_AWARE_SPATIAL_CHROMA_WEIGHT_X256: i32 = 96;
14153/// Default chroma-aware spatial luma weight (fixed-point ×256).
14154pub const DEFAULT_CHROMA_AWARE_SPATIAL_LUMA_WEIGHT_X256: i32 = 160;
14155/// Default maximum iteration count for the joint R44+R49 picker.
14156pub const DEFAULT_JOINT_R44R49_PICKER_MAX_ITERS: u32 = 4;
14157/// Hard cap on the joint R44+R49 picker iteration count.
14158pub const JOINT_R44R49_PICKER_MAX_ITERS_MAX: u32 = 16;
14159/// Default convergence threshold for the k-means segmentation pass
14160/// (centroid drift below which the loop terminates, x256).
14161pub const DEFAULT_KMEANS_CONVERGENCE_THRESHOLD: i32 = 8;
14162/// Default k-means spatial-alpha weight (fixed-point ×256).
14163pub const DEFAULT_KMEANS_SPATIAL_ALPHA_X256: i32 = 128;
14164/// Hard cap on the k-means spatial-segmentation iteration count.
14165pub const KMEANS_SPATIAL_MAX_ITERS: u32 = 32;
14166/// Default long-ref lambda scale (×256).
14167pub const DEFAULT_LAMBDA_LONG_REF_SCALE_X256: i32 = 256;
14168/// Default RD lambda scale (×256). 256 ≡ 1.0.
14169pub const LAMBDA_SCALE_DEFAULT: i32 = 256;
14170/// Default lookahead window in frames (first-pass / scene-cut buffer).
14171pub const DEFAULT_LOOKAHEAD_WINDOW: u32 = 16;
14172/// Non-local-means filter `h²` parameter default.
14173pub const DEFAULT_NLM_H2: i32 = 100;
14174/// Default psy-RD strength (fixed-point, ballpark "moderate").
14175pub const DEFAULT_PSY_RD_STRENGTH: i32 = 30;
14176/// Default boost-frame count when a scene cut is detected.
14177pub const DEFAULT_SCENE_CUT_BOOST_FRAMES: u32 = 2;
14178/// Default qindex boost (subtraction) on a scene-cut keyframe.
14179pub const DEFAULT_SCENE_CUT_QUANT_BOOST: i32 = 8;
14180/// Default scene-cut decision threshold (variance × frame ratio).
14181pub const DEFAULT_SCENE_CUT_THRESHOLD: i32 = 4_096;
14182/// Default segment-aware loop-filter deltas (4 segments — §10).
14183pub const DEFAULT_SEGMENT_LF_DELTAS: [i8; 4] = [0, 0, 0, 0];
14184/// Default segment-aware quant deltas (4 segments — §10).
14185pub const DEFAULT_SEGMENT_QUANT_DELTAS: [i8; 4] = [0, 0, 0, 0];
14186/// Default maximum simple-filter loop-filter level.
14187pub const DEFAULT_SIMPLE_LF_MAX_LEVEL: u8 = 32;
14188/// Default number of spatial loop-filter column bands.
14189pub const DEFAULT_SPATIAL_LF_N_COL_BANDS: u32 = 4;
14190/// Default number of spatial loop-filter row bands.
14191pub const DEFAULT_SPATIAL_LF_N_ROW_BANDS: u32 = 4;
14192/// Default number of refinement passes for the SPLITMV joint picker.
14193pub const DEFAULT_SPLIT_MV_JOINT_REFINE_PASSES: u32 = 2;
14194/// Hard cap on the SPLITMV joint-refine pass count.
14195pub const SPLIT_MV_JOINT_REFINE_PASSES_MAX: u32 = 8;
14196/// Variance threshold above which an intra block forces B_PRED in a
14197/// P-frame.
14198pub const INTRA_IN_P_BPRED_VARIANCE_THRESHOLD: i32 = 256;
14199/// QP sensitivity scaling (×8) used by the §10 segment-aware QP search.
14200pub const QP_SENSITIVITY_X8: i32 = 8;
14201/// Absolute floor on the scene-cut metric below which a cut is never
14202/// declared.
14203pub const SCENE_CUT_ABS_FLOOR: i32 = 32;
14204/// Per-segment variance thresholds the adaptive-QP / scene-segmenter
14205/// uses (4 segments).
14206pub const SEGMENT_VARIANCE_THRESHOLDS: [u32; 4] = [64, 256, 1_024, 4_096];
14207
14208// ─────────────────────────────────── tests ────────────────────────────────────
14209
14210#[cfg(test)]
14211mod tests {
14212    use super::*;
14213
14214    /// The r441 DC-only / all-zero shortcut in [`reconstruct_block_4x4`]
14215    /// must be byte-for-byte the general dequant → §14.4 IDCT → §14.5
14216    /// add-clamp chain, including the dequant multiply's `i16`
14217    /// truncation (the shortcut reads the truncated DC exactly as the
14218    /// transform would) and the clamp at both rails.
14219    #[test]
14220    fn reconstruct_block_4x4_dc_only_matches_general() {
14221        let mut st = 0x5EED_0441u32;
14222        let mut next = move || {
14223            st = st.wrapping_mul(1_103_515_245).wrapping_add(12345);
14224            (st >> 16) as i32
14225        };
14226        for case in 0..4096 {
14227            let mut pred = [0u8; 16];
14228            for p in pred.iter_mut() {
14229                *p = (next() & 0xFF) as u8;
14230            }
14231            let (dc, ac) = (4 + (next() % 280) as i16, 4 + (next() % 280) as i16);
14232            let mut quant = [0i16; 16];
14233            // Regimes: all-zero, small DC, huge DC (i16-truncation edge),
14234            // and (as a control) a genuinely general block.
14235            match case % 4 {
14236                0 => {}
14237                1 => quant[0] = (next() % 9 - 4) as i16,
14238                2 => quant[0] = (next() % 60_000 - 30_000) as i16,
14239                _ => {
14240                    for c in quant.iter_mut() {
14241                        *c = (next() % 41 - 20) as i16;
14242                    }
14243                }
14244            }
14245            // Reference: the pre-shortcut chain, verbatim.
14246            let mut dq = quant;
14247            dq[0] = (dq[0] as i32 * dc as i32) as i16;
14248            for c in dq.iter_mut().skip(1) {
14249                *c = (*c as i32 * ac as i32) as i16;
14250            }
14251            let mut residue = [0i16; 16];
14252            inverse_dct_4x4(&dq, &mut residue);
14253            let mut want = [0u8; 16];
14254            add_residue_4x4(&pred, &residue, &mut want);
14255
14256            let got = reconstruct_block_4x4(&pred, &quant, dc, ac);
14257            assert_eq!(want, got, "case {case} dc {dc} ac {ac} quant {quant:?}");
14258        }
14259    }
14260
14261    /// The pre-round-441 §13 trellis, retained verbatim as the byte-level
14262    /// reference for the per-frame rate-table + sub-threshold-early-exit
14263    /// rewrite. It prices every candidate through the direct
14264    /// [`super::coeff_token_bits`] / [`super::eob_token_bits`] calls and
14265    /// never takes the all-zero shortcut, so
14266    /// `trellis_lut_and_early_exit_match_reference` below can pin the
14267    /// shipped fast paths against it level-for-level.
14268    #[allow(clippy::needless_range_loop)]
14269    fn trellis_quantize_block_reference(
14270        block: &mut [i16; 16],
14271        spec: super::TrellisBlockSpec,
14272        coeff_probs: &super::CoeffProbs,
14273        lambda: f64,
14274    ) {
14275        let super::TrellisBlockSpec {
14276            dc,
14277            ac,
14278            first_coeff,
14279            entry_ctx3,
14280            plane,
14281        } = spec;
14282        // `lambda` is the **effective** coefficient-level price the caller has
14283        // already scaled down from the mode-decision multiplier (coefficient
14284        // RDO spends `lambda` far more effectively than the mode-granular
14285        // picker — it can drop one trailing coefficient rather than a whole
14286        // mode — so the raw mode lambda over-trades quality for rate). The
14287        // scale is resolved by [`MbRdCtx::trellis_lambda`] from the
14288        // [`TrellisStrength`] knob; this entry consumes the resolved value
14289        // directly so callers can dial the rate/quality trade per stream.
14290
14291        // Baseline rounding for the lossless / no-trade path.
14292        if lambda <= 0.0 {
14293            super::enc_quantize_block_range(block, dc, ac, first_coeff);
14294            return;
14295        }
14296
14297        // Scan-order view of the unquantised coefficients + per-position step.
14298        let mut scan_x = [0i32; 16];
14299        let mut step = [0i32; 16];
14300        for k in 0..16 {
14301            scan_x[k] = block[crate::dct_tokens::ZIGZAG[k]] as i32;
14302            step[k] = if k == 0 { dc as i32 } else { ac as i32 };
14303        }
14304
14305        let norms = &*super::IDCT_BASIS_NORM_SQ;
14306
14307        // Distortion of coding scan position `k` at absolute level `m`
14308        // (transform-domain squared error scaled by the basis norm). `m` is a
14309        // magnitude (≥ 0); the dequantised coefficient carries `scan_x[k]`'s
14310        // sign, so the error is computed on absolute magnitudes.
14311        let dist = |k: usize, m: i64| -> f64 {
14312            let q = step[k] as i64;
14313            let recon = m * q;
14314            let err = (scan_x[k] as i64).abs() - recon;
14315            norms[k] * (err * err) as f64
14316        };
14317
14318        // Suffix distortion of *dropping* every position k..16 to level 0 —
14319        // the distortion the §13.3 implicit/explicit EOB tail pays for the
14320        // coefficients past the last coded one. `suffix_zero_dist[k]` =
14321        // Σ_{j=k}^{15} dist(j, 0). Without this, terminating early would hide
14322        // the energy of the dropped tail and the trellis would zero
14323        // everything. `suffix_zero_dist[16] = 0`.
14324        let mut suffix_zero_dist = [0f64; 17];
14325        for k in (first_coeff..16).rev() {
14326            suffix_zero_dist[k] = suffix_zero_dist[k + 1] + dist(k, 0);
14327        }
14328
14329        // Forward Viterbi. State = carried `ctx3 ∈ {0,1,2}`. `cells[k]` holds
14330        // the best survivor *ending at* scan position `k` with each carried
14331        // context, where "ending" means position `k` holds the last coded
14332        // (possibly non-zero) coefficient so far. We also separately track the
14333        // running all-zero-prefix cost so a block can terminate with EOB at
14334        // `first_coeff` (entirely zero) for free of trailing-token bits.
14335        //
14336        // `prev[ctx]` is the best (cost, level, prev_ctx, prev_was_zero) to
14337        // arrive at the *current* position carrying `ctx`.
14338        const INF: f64 = f64::INFINITY;
14339
14340        // survivor reaching position `k` with carried ctx — initialised at the
14341        // virtual "before first_coeff" boundary: a single state carrying
14342        // `entry_ctx3`, cost 0, prev_was_zero = false (the first token may emit
14343        // EOB).
14344        #[derive(Clone, Copy)]
14345        struct Surv {
14346            cost: f64,
14347            prev_was_zero: bool,
14348            // back-pointer chain stored in `choice` below
14349        }
14350        let mut surv = [Surv {
14351            cost: INF,
14352            prev_was_zero: false,
14353        }; 3];
14354        surv[entry_ctx3] = Surv {
14355            cost: 0.0,
14356            prev_was_zero: false,
14357        };
14358
14359        // Decision record per (position, carried-ctx): the level chosen at this
14360        // position and which predecessor ctx it came from, for traceback.
14361        let mut choice = [[super::TrellisCell {
14362            cost: INF,
14363            level: 0,
14364            prev_ctx: 0,
14365        }; 3]; 16];
14366
14367        // Best terminating survivor: code positions first..=t, then EOB after
14368        // t (if t+1 < 16) or implicit EOB. `best_end_pos = first_coeff - 1`
14369        // (sentinel `usize::MAX` meaning "all zero") seeds the all-zero block.
14370        let mut best_term_cost = {
14371            // All-zero block: EOB token at `first_coeff` against the entry ctx,
14372            // plus the distortion of dropping every coefficient to zero.
14373            let mut c = INF;
14374            let s = &surv[entry_ctx3];
14375            if s.cost < INF {
14376                c = s.cost
14377                    + lambda * super::eob_token_bits(coeff_probs, plane, first_coeff, entry_ctx3)
14378                    + suffix_zero_dist[first_coeff];
14379            }
14380            c
14381        };
14382        let mut best_term_pos: i32 = -1; // -1 ⇒ all-zero
14383        let mut best_term_ctx = entry_ctx3;
14384
14385        for k in first_coeff..16 {
14386            let m_round = {
14387                let q = step[k] as i64;
14388                // round-half-away-from-zero magnitude
14389                let num = scan_x[k].unsigned_abs() as i64;
14390                (num + q / 2) / q
14391            };
14392            // Candidate magnitudes: round and round-1 (≥0), deduplicated, plus
14393            // a forced 0 so a non-trivial coefficient can still be dropped.
14394            let mut cands = [0i64; 3];
14395            let mut ncand = 0usize;
14396            for cand in [m_round, m_round - 1, 0] {
14397                if cand >= 0 && !cands[..ncand].contains(&cand) {
14398                    cands[ncand] = cand;
14399                    ncand += 1;
14400                }
14401            }
14402
14403            let mut next = [Surv {
14404                cost: INF,
14405                prev_was_zero: false,
14406            }; 3];
14407            let mut next_choice = [super::TrellisCell {
14408                cost: INF,
14409                level: 0,
14410                prev_ctx: 0,
14411            }; 3];
14412
14413            for (in_ctx, &s) in surv.iter().enumerate() {
14414                if s.cost >= INF {
14415                    continue;
14416                }
14417                for &m in &cands[..ncand] {
14418                    let abs = m as u16;
14419                    let d = dist(k, m);
14420                    let r = super::coeff_token_bits(
14421                        coeff_probs,
14422                        plane,
14423                        k,
14424                        in_ctx,
14425                        s.prev_was_zero,
14426                        abs,
14427                    );
14428                    let cost = s.cost + d + lambda * r;
14429                    let out_ctx = super::level_ctx3(abs);
14430                    if cost < next[out_ctx].cost {
14431                        next[out_ctx] = Surv {
14432                            cost,
14433                            prev_was_zero: abs == 0,
14434                        };
14435                        next_choice[out_ctx] = super::TrellisCell {
14436                            cost,
14437                            level: abs,
14438                            prev_ctx: in_ctx,
14439                        };
14440                    }
14441                }
14442            }
14443
14444            choice[k] = next_choice;
14445
14446            // Consider terminating *after* position k: position k must hold a
14447            // non-zero coefficient to be a meaningful last-coded slot (a zero
14448            // last slot is dominated by terminating one position earlier). The
14449            // EOB after position k lands at k+1 (if any) against k's out-ctx;
14450            // at k = 15 the implicit EOB costs nothing.
14451            for (out_ctx, &cell) in next_choice.iter().enumerate() {
14452                if cell.cost >= INF || cell.level == 0 {
14453                    continue;
14454                }
14455                // `cell.cost` covers coding first..=k; add the EOB token (if
14456                // any remain) plus the distortion of dropping positions k+1..16.
14457                let term_cost = if k + 1 < 16 {
14458                    cell.cost
14459                        + lambda * super::eob_token_bits(coeff_probs, plane, k + 1, out_ctx)
14460                        + suffix_zero_dist[k + 1]
14461                } else {
14462                    cell.cost // implicit EOB after the last coefficient
14463                };
14464                if term_cost < best_term_cost {
14465                    best_term_cost = term_cost;
14466                    best_term_pos = k as i32;
14467                    best_term_ctx = out_ctx;
14468                }
14469            }
14470
14471            surv = next;
14472        }
14473
14474        // Traceback from the best terminating position, writing scan-order
14475        // levels then permuting back to raster.
14476        let mut scan_levels = [0i32; 16];
14477        if best_term_pos >= 0 {
14478            let mut k = best_term_pos as usize;
14479            let mut ctx = best_term_ctx;
14480            loop {
14481                let cell = choice[k][ctx];
14482                let lvl = cell.level as i32;
14483                let signed = if scan_x[k] < 0 { -lvl } else { lvl };
14484                scan_levels[k] = signed;
14485                if k == first_coeff {
14486                    break;
14487                }
14488                ctx = cell.prev_ctx;
14489                k -= 1;
14490            }
14491        }
14492
14493        // Permute scan levels back into the raster `block`.
14494        for v in block.iter_mut() {
14495            *v = 0;
14496        }
14497        for (k, &lvl) in scan_levels.iter().enumerate() {
14498            block[crate::dct_tokens::ZIGZAG[k]] = lvl as i16;
14499        }
14500    }
14501    use crate::bool_decoder::BoolDecoder;
14502    use crate::coded_header::Vp8CodedHeader;
14503    use crate::decode_vp8;
14504    use crate::frame_header::Vp8FrameHeader;
14505
14506    /// [`TrellisRateTables::level_rate`] is bit-for-bit
14507    /// [`coeff_token_bits`] over the whole §13.2 alphabet.
14508    #[test]
14509    fn level_rate_matches_coeff_token_bits() {
14510        let probs = &crate::DEFAULT_COEFF_PROBS;
14511        let tables = TrellisRateTables::for_probs(probs);
14512        for plane in 0..4 {
14513            for (i, &band) in COEFF_BANDS.iter().enumerate() {
14514                for ctx3 in 0..3 {
14515                    for pwz in [false, true] {
14516                        for level in 0u32..=2114 {
14517                            let want = coeff_token_bits(probs, plane, i, ctx3, pwz, level as u16);
14518                            let got = TrellisRateTables::level_rate(
14519                                &tables.small[plane][band],
14520                                &tables.cat_path[plane][band],
14521                                ctx3,
14522                                pwz,
14523                                level,
14524                            );
14525                            assert_eq!(want.to_bits(), got.to_bits());
14526                        }
14527                    }
14528                }
14529            }
14530        }
14531    }
14532
14533    /// The one-step renormalisation in [`BoolEncoder::write_bool`]
14534    /// produces the same byte stream and the same final state as the
14535    /// §7.3 one-bit-at-a-time loop, over skewed, balanced and extreme
14536    /// probabilities and long runs of either bit (carry chains).
14537    #[test]
14538    fn write_bool_matches_bitwise_listing() {
14539        fn write_bool_bitwise(enc: &mut BoolEncoder, prob: u8, value: bool) {
14540            let split = 1 + (((enc.range - 1) * prob as u32) >> 8);
14541            if value {
14542                enc.bottom = enc.bottom.wrapping_add(split);
14543                enc.range -= split;
14544            } else {
14545                enc.range = split;
14546            }
14547            while enc.range < 128 {
14548                enc.range <<= 1;
14549                if (enc.bottom >> 31) & 1 == 1 {
14550                    add_one_to_output(&mut enc.out);
14551                }
14552                enc.bottom <<= 1;
14553                enc.bit_count -= 1;
14554                if enc.bit_count == 0 {
14555                    enc.out.push((enc.bottom >> 24) as u8);
14556                    enc.bottom &= (1 << 24) - 1;
14557                    enc.bit_count = 8;
14558                }
14559            }
14560        }
14561        let mut lcg = 0x0BAD_5EEDu32;
14562        let mut next = move || {
14563            lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
14564            lcg >> 8
14565        };
14566        for regime in 0..8 {
14567            let mut fast = BoolEncoder::new();
14568            let mut slow = BoolEncoder::new();
14569            for n in 0..300_000u32 {
14570                let r = next();
14571                let (prob, value) = match regime {
14572                    0 => ((r & 0xFF) as u8, r & 0x100 != 0),
14573                    1 => (128, r & 1 != 0),
14574                    2 => (1, r & 0xFF00 != 0),
14575                    3 => (255, r & 0xFF00 == 0),
14576                    4 => (1, true),
14577                    5 => (255, n % 97 == 0),
14578                    6 => ((r & 0xFF) as u8, true),
14579                    _ => (2 + (r & 3) as u8, r & 0x700 != 0),
14580                };
14581                fast.write_bool(prob, value);
14582                write_bool_bitwise(&mut slow, prob, value);
14583                assert_eq!(
14584                    (fast.range, fast.bottom, fast.bit_count),
14585                    (slow.range, slow.bottom, slow.bit_count),
14586                    "regime {regime} symbol {n}"
14587                );
14588            }
14589            assert_eq!(fast.out, slow.out, "regime {regime}");
14590            assert_eq!(fast.finish(), slow.finish(), "regime {regime}");
14591        }
14592    }
14593
14594    /// The pre-summed ranking estimate stays within rounding of the
14595    /// reference estimate — far inside the margin [`RD_TIE_GUARD`]
14596    /// assumes.
14597    #[test]
14598    fn presummed_estimate_tracks_reference_estimate() {
14599        let probs = &crate::DEFAULT_COEFF_PROBS;
14600        let tables = TrellisRateTables::for_probs(probs);
14601        let mut lcg = 0x0DDB_A11Du32;
14602        let mut next = move || {
14603            lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
14604            (lcg >> 16) as i32
14605        };
14606        let mut worst = 0f64;
14607        for case in 0..40_000 {
14608            let mut coeffs = [0i16; 16];
14609            for (k, c) in coeffs.iter_mut().enumerate() {
14610                *c = match case % 4 {
14611                    0 => (next() % 3 - 1) as i16,
14612                    1 => ((next() % 9 == 0) as i32 * (next() % 41 - 20)) as i16,
14613                    2 => ((next() % 4229 - 2114) / (1 + k as i32)) as i16,
14614                    _ => (next() % 4229 - 2114) as i16,
14615                };
14616            }
14617            for block_type in [
14618                BlockType::Y2,
14619                BlockType::YAfterY2,
14620                BlockType::YNoY2,
14621                BlockType::UV,
14622            ] {
14623                let (above, left) = (case % 2 == 0, case % 3 == 0);
14624                let reference = estimate_block_bits(block_type, probs, above, left, &coeffs);
14625                let ranking =
14626                    estimate_block_bits_presummed(&tables, block_type, above, left, &coeffs);
14627                worst = worst.max((reference - ranking).abs());
14628            }
14629        }
14630        assert!(worst < 1e-9, "pre-summed estimate drifted by {worst} bits");
14631    }
14632
14633    #[test]
14634    fn decisive_minimum_takes_the_first_minimum_and_flags_close_calls() {
14635        assert_eq!(decisive_minimum(&[5.0, 3.0, 9.0]), (1, true));
14636        assert_eq!(decisive_minimum(&[3.0, 3.0, 9.0]), (0, false));
14637        assert_eq!(
14638            decisive_minimum(&[3.0 + RD_TIE_GUARD / 2.0, 3.0, 9.0]),
14639            (1, false)
14640        );
14641        assert_eq!(
14642            decisive_minimum(&[3.0 + RD_TIE_GUARD * 2.0, 3.0]),
14643            (1, true)
14644        );
14645        assert_eq!(decisive_minimum(&[7.0]), (0, true));
14646    }
14647
14648    /// The guarded ranking search picks exactly what the reference
14649    /// search picks: whole frames encode to the same bytes with every
14650    /// decision forced through the reference costs.
14651    #[test]
14652    fn ranked_search_matches_reference_search() {
14653        let (w, h) = (112usize, 80usize);
14654        // Structured picture: ramps, a flat block, edges and grain, so
14655        // whole-block and `B_PRED` macroblocks, identical-prediction
14656        // sub-blocks and near-ties all occur.
14657        let mut lcg = 0x7E57_F00Du32;
14658        let mut y = vec![0u8; w * h];
14659        for row in 0..h {
14660            for col in 0..w {
14661                lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
14662                let grain = ((lcg >> 24) % 7) as i32 - 3;
14663                let mut v = (col * 2 + row) as i32 % 256;
14664                if (32..64).contains(&col) && (16..48).contains(&row) {
14665                    v = 90;
14666                } else if col > 70 {
14667                    v = if (col / 6 + row / 9) % 2 == 0 {
14668                        40
14669                    } else {
14670                        210
14671                    } + grain;
14672                } else if row > 56 {
14673                    v += grain * 6;
14674                }
14675                y[row * w + col] = v.clamp(0, 255) as u8;
14676            }
14677        }
14678        let u: Vec<u8> = (0..(w / 2) * (h / 2))
14679            .map(|i| (100 + (i % 37)) as u8)
14680            .collect();
14681        let v: Vec<u8> = (0..(w / 2) * (h / 2))
14682            .map(|i| (150 - (i % 23)) as u8)
14683            .collect();
14684        let frame = I420Frame::packed(w as u32, h as u32, &y, &u, &v);
14685        for qi in [0u8, 6, 20, 45, 90, 127] {
14686            for strength in [0.0, 1.0, 3.0] {
14687                let params = KeyframeParams::default()
14688                    .with_y_ac_qi(qi)
14689                    .with_trellis_strength(TrellisStrength::new(strength));
14690                let ranked = encode_keyframe(&frame, &params).unwrap();
14691                FORCE_REFERENCE_SEARCH.with(|f| f.set(true));
14692                let reference = encode_keyframe(&frame, &params);
14693                FORCE_REFERENCE_SEARCH.with(|f| f.set(false));
14694                assert_eq!(ranked, reference.unwrap(), "qi {qi} strength {strength}");
14695            }
14696        }
14697    }
14698
14699    /// The reciprocal-multiply level rounding equals the plain division
14700    /// for every magnitude a 16-bit coefficient can take at every tabled
14701    /// quantiser step (and on the division fallback above the table).
14702    #[test]
14703    fn rounded_level_matches_division() {
14704        for q in 1u32..1100 {
14705            for magnitude in 0u32..=32768 {
14706                let want = (magnitude + q / 2) / q;
14707                assert_eq!(
14708                    rounded_level(magnitude, q),
14709                    want,
14710                    "magnitude {magnitude} q {q}"
14711                );
14712            }
14713        }
14714    }
14715
14716    /// The step-table estimator returns the bit-identical `f64` the
14717    /// direct per-step walk does, across block types, neighbour contexts,
14718    /// probability tables and coefficient shapes (empty, sparse, dense,
14719    /// full to position 15, cat-token magnitudes).
14720    #[test]
14721    fn estimate_block_bits_tabled_matches_direct() {
14722        let mut perturbed = crate::DEFAULT_COEFF_PROBS;
14723        let mut st = 0x1357_9BDFu32;
14724        for prob in perturbed.iter_mut().flatten().flatten().flatten() {
14725            st = st.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
14726            *prob = ((st >> 24) as u8).max(1);
14727        }
14728        let mut lcg = 0xDEAD_BEEFu32;
14729        let mut next = move || {
14730            lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
14731            (lcg >> 16) as i32
14732        };
14733        let mut cases = 0usize;
14734        for probs in [&crate::DEFAULT_COEFF_PROBS, &perturbed] {
14735            let tables = TrellisRateTables::for_probs(probs);
14736            for block_type in [
14737                BlockType::Y2,
14738                BlockType::YAfterY2,
14739                BlockType::YNoY2,
14740                BlockType::UV,
14741            ] {
14742                for shape in 0..6 {
14743                    for _ in 0..200 {
14744                        let mut coeffs = [0i16; 16];
14745                        for (k, c) in coeffs.iter_mut().enumerate() {
14746                            let v = match shape {
14747                                0 => 0,
14748                                1 => (next() % 8 == 0) as i32 * (next() % 3 - 1),
14749                                2 => next() % 5 - 2,
14750                                3 => next() % 2 * 2 - 1,
14751                                4 => (next() % 4200 - 2100) / (1 + k as i32),
14752                                _ => (next() % 3 == 0) as i32 * (next() % 140 - 70),
14753                            };
14754                            *c = v as i16;
14755                        }
14756                        for above in [false, true] {
14757                            for left in [false, true] {
14758                                let want =
14759                                    estimate_block_bits(block_type, probs, above, left, &coeffs);
14760                                let got = estimate_block_bits_tabled(
14761                                    &tables, block_type, above, left, &coeffs,
14762                                );
14763                                assert_eq!(
14764                                    want.to_bits(),
14765                                    got.to_bits(),
14766                                    "{block_type:?} above {above} left {left} {coeffs:?}"
14767                                );
14768                                cases += 1;
14769                            }
14770                        }
14771                    }
14772                }
14773            }
14774        }
14775        assert!(cases > 30_000);
14776    }
14777
14778    /// Every point of the per-frame [`TrellisRateTables`] domain must be
14779    /// **bit-for-bit** the value the direct reference rate call returns —
14780    /// under the §13.5 default table AND a deterministically perturbed
14781    /// non-uniform table (a wrong band/context/level slot would change the
14782    /// f64, not alias into it). Together with
14783    /// `trellis_lut_and_early_exit_match_reference` this pins the r441
14784    /// lookup path: identical rates ⇒ identical Viterbi costs ⇒ identical
14785    /// chosen levels ⇒ identical emitted bytes.
14786    #[test]
14787    fn trellis_rate_tables_match_direct_calls() {
14788        let mut perturbed = crate::DEFAULT_COEFF_PROBS;
14789        let mut st = 0x1357_9BDFu32;
14790        for plane in perturbed.iter_mut() {
14791            for band in plane.iter_mut() {
14792                for ctx in band.iter_mut() {
14793                    for prob in ctx.iter_mut() {
14794                        st = st.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
14795                        *prob = ((st >> 24) as u8).max(1);
14796                    }
14797                }
14798            }
14799        }
14800        for probs in [&crate::DEFAULT_COEFF_PROBS, &perturbed] {
14801            let t = TrellisRateTables::for_probs(probs);
14802            for plane in 0..4 {
14803                for (i, &band) in COEFF_BANDS.iter().enumerate() {
14804                    for ctx3 in 0..3 {
14805                        assert_eq!(
14806                            t.eob[plane][band][ctx3].to_bits(),
14807                            eob_token_bits(probs, plane, i, ctx3).to_bits(),
14808                            "eob: plane {plane} pos {i} ctx {ctx3}"
14809                        );
14810                        for (pwz, small) in t.small[plane][band][ctx3].iter().enumerate() {
14811                            for abs in 0..=TRELLIS_SMALL_LEVEL_MAX {
14812                                assert_eq!(
14813                                    small[abs as usize].to_bits(),
14814                                    coeff_token_bits(probs, plane, i, ctx3, pwz == 1, abs)
14815                                        .to_bits(),
14816                                    "plane {plane} pos {i} ctx {ctx3} pwz {pwz} abs {abs}"
14817                                );
14818                            }
14819                        }
14820                    }
14821                }
14822            }
14823        }
14824    }
14825
14826    /// The shipped trellis (per-frame rate LUT + sub-threshold early
14827    /// exit) must produce **level-for-level identical** output to the
14828    /// retained pre-r441 reference implementation — with and without the
14829    /// tables — across block types, entry contexts, quantisers, lambdas,
14830    /// probability tables, and residual magnitudes from far-sub-threshold
14831    /// (the early-exit path) through cat-token territory (the `abs > 4`
14832    /// direct-call fallback).
14833    #[test]
14834    fn trellis_lut_and_early_exit_match_reference() {
14835        let mut perturbed = crate::DEFAULT_COEFF_PROBS;
14836        let mut st = 0xA5A5_1234u32;
14837        for plane in perturbed.iter_mut() {
14838            for band in plane.iter_mut() {
14839                for ctx in band.iter_mut() {
14840                    for prob in ctx.iter_mut() {
14841                        st = st.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
14842                        *prob = ((st >> 24) as u8).max(1);
14843                    }
14844                }
14845            }
14846        }
14847
14848        let block_specs = [
14849            (BlockType::Y2, 0usize),
14850            (BlockType::YAfterY2, 0),
14851            (BlockType::YNoY2, 1),
14852            (BlockType::UV, 2),
14853        ];
14854
14855        let mut cases = 0usize;
14856        for probs in [&crate::DEFAULT_COEFF_PROBS, &perturbed] {
14857            let tables = TrellisRateTables::for_probs(probs);
14858            for qi in [8i32, 40, 100] {
14859                let factors =
14860                    crate::dequant::MbDequantFactors::from_base_and_deltas(qi, 0, 0, 0, 0, 0);
14861                let base_lambda = rd_lambda(&factors) * TRELLIS_LAMBDA_SCALE;
14862                for (block_type, entry_ctx3) in block_specs {
14863                    let (dc, ac) = match block_type {
14864                        BlockType::Y2 => (factors.y2_dc, factors.y2_ac),
14865                        BlockType::UV => (factors.uv_dc, factors.uv_ac),
14866                        _ => (factors.y1_dc, factors.y1_ac),
14867                    };
14868                    let spec = TrellisBlockSpec {
14869                        dc,
14870                        ac,
14871                        first_coeff: block_type.first_coeff(),
14872                        entry_ctx3,
14873                        plane: block_type.plane_index(),
14874                    };
14875                    // Magnitude regimes: far sub-threshold (all-zero early
14876                    // exit), around-threshold, working range, cat-token
14877                    // range (levels > 4 hit the direct-call fallback).
14878                    for (scale, offset) in [
14879                        (1i32, 0i32),
14880                        (ac as i32, 0),
14881                        (ac as i32 * 3, 8),
14882                        (ac as i32 * 24, 64),
14883                    ] {
14884                        for seed in 0u32..12 {
14885                            let mut lcg = 0xC0FF_EE00u32
14886                                .wrapping_add(seed)
14887                                .wrapping_mul(2_891_336_453);
14888                            let mut next = move || {
14889                                lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
14890                                (lcg >> 16) as i32
14891                            };
14892                            let mut base = [0i16; 16];
14893                            for (k, c) in base.iter_mut().enumerate() {
14894                                // Roughly zig-zag-decaying magnitudes with
14895                                // both signs, like real DCT output.
14896                                let mag = (next() % (scale + offset + 1)) / (1 + k as i32 / 4);
14897                                let sign = if next() % 2 == 0 { 1 } else { -1 };
14898                                *c = (sign * mag).clamp(-2048, 2047) as i16;
14899                            }
14900                            for lambda in [base_lambda * 0.25, base_lambda, base_lambda * 6.0] {
14901                                let mut want = base;
14902                                trellis_quantize_block_reference(&mut want, spec, probs, lambda);
14903                                let mut got_direct = base;
14904                                trellis_quantize_block(&mut got_direct, spec, probs, None, lambda);
14905                                let mut got_lut = base;
14906                                trellis_quantize_block(
14907                                    &mut got_lut,
14908                                    spec,
14909                                    probs,
14910                                    Some(&tables),
14911                                    lambda,
14912                                );
14913                                assert_eq!(
14914                                    want, got_direct,
14915                                    "direct path drifted: qi {qi} type {block_type:?} scale {scale} seed {seed} lambda {lambda}"
14916                                );
14917                                assert_eq!(
14918                                    want, got_lut,
14919                                    "LUT path drifted: qi {qi} type {block_type:?} scale {scale} seed {seed} lambda {lambda}"
14920                                );
14921                                cases += 1;
14922                            }
14923                        }
14924                    }
14925                }
14926            }
14927        }
14928        assert!(cases >= 3000, "stress matrix shrank: {cases} cases");
14929    }
14930
14931    /// Re-read a §9.3 `update_segmentation()` block from raw bits the
14932    /// same way the decoder's `parse_update_segmentation` does, so a
14933    /// `write_update_segmentation` round-trip can be asserted without
14934    /// reaching the private parser. Mirrors the §19.2 table layout
14935    /// verbatim (the writer is the only thing under test).
14936    #[derive(Debug, PartialEq, Eq)]
14937    struct DecodedSegLayer {
14938        feature_absolute: bool,
14939        update_map: bool,
14940        quant: [Option<i16>; 4],
14941        lf: [Option<i16>; 4],
14942        probs: [Option<u8>; 3],
14943    }
14944
14945    fn read_update_segmentation_for_test(dec: &mut BoolDecoder<'_>) -> DecodedSegLayer {
14946        // The caller has already consumed segmentation_enabled = 1.
14947        let update_map = dec.read_bool(128).unwrap();
14948        let update_feature = dec.read_bool(128).unwrap();
14949        let mut feature_absolute = false;
14950        let mut quant: [Option<i16>; 4] = [None; 4];
14951        let mut lf: [Option<i16>; 4] = [None; 4];
14952        if update_feature {
14953            feature_absolute = dec.read_bool(128).unwrap();
14954            for slot in &mut quant {
14955                if dec.read_bool(128).unwrap() {
14956                    let mag = dec.read_literal(7).unwrap() as i16;
14957                    let sign = dec.read_bool(128).unwrap();
14958                    *slot = Some(if sign { -mag } else { mag });
14959                }
14960            }
14961            for slot in &mut lf {
14962                if dec.read_bool(128).unwrap() {
14963                    let mag = dec.read_literal(6).unwrap() as i16;
14964                    let sign = dec.read_bool(128).unwrap();
14965                    *slot = Some(if sign { -mag } else { mag });
14966                }
14967            }
14968        }
14969        let mut probs: [Option<u8>; 3] = [None; 3];
14970        if update_map {
14971            for slot in &mut probs {
14972                if dec.read_bool(128).unwrap() {
14973                    *slot = Some(dec.read_literal(8).unwrap() as u8);
14974                }
14975            }
14976        }
14977        DecodedSegLayer {
14978            feature_absolute,
14979            update_map,
14980            quant,
14981            lf,
14982            probs,
14983        }
14984    }
14985
14986    /// `write_update_segmentation` lays the §9.3 sub-block out so the
14987    /// decoder's reader recovers every field: the map-update flag, the
14988    /// delta/absolute feature mode, the four signed quantizer deltas, the
14989    /// four signed loop-filter deltas, and the three tree probabilities,
14990    /// including the `None` (flag-not-set) slots.
14991    #[test]
14992    fn update_segmentation_writer_round_trips_full_layer() {
14993        let layer = UpdateSegmentationLayer {
14994            update_mb_segmentation_map: true,
14995            feature_mode_absolute: false,
14996            quantizer: [Some(-12), None, Some(40), Some(-1)],
14997            loop_filter: [None, Some(7), None, Some(-3)],
14998            segment_prob: [Some(200), None, Some(31)],
14999        };
15000        let mut enc = BoolEncoder::new();
15001        write_update_segmentation(&mut enc, &layer);
15002        let buf = enc.finish();
15003
15004        let mut dec = BoolDecoder::init(&buf).unwrap();
15005        // segmentation_enabled = 1 written first.
15006        assert!(dec.read_bool(128).unwrap());
15007        let got = read_update_segmentation_for_test(&mut dec);
15008        assert_eq!(got.feature_absolute, layer.feature_mode_absolute);
15009        assert_eq!(got.update_map, layer.update_mb_segmentation_map);
15010        assert_eq!(got.quant, layer.quantizer);
15011        assert_eq!(got.lf, layer.loop_filter);
15012        assert_eq!(got.probs, layer.segment_prob);
15013    }
15014
15015    /// Absolute feature mode + no map update: `update_segment_feature_data`
15016    /// is still set (a feature is carried), but the `segment_prob` block is
15017    /// absent. Exercises the absolute-mode flag and the map-off branch.
15018    #[test]
15019    fn update_segmentation_writer_absolute_no_map_update() {
15020        let layer = UpdateSegmentationLayer {
15021            update_mb_segmentation_map: false,
15022            feature_mode_absolute: true,
15023            quantizer: [Some(20), Some(35), Some(60), Some(90)],
15024            loop_filter: [None; 4],
15025            segment_prob: [None; 3],
15026        };
15027        let mut enc = BoolEncoder::new();
15028        write_update_segmentation(&mut enc, &layer);
15029        let buf = enc.finish();
15030
15031        let mut dec = BoolDecoder::init(&buf).unwrap();
15032        assert!(dec.read_bool(128).unwrap());
15033        let got = read_update_segmentation_for_test(&mut dec);
15034        assert!(got.feature_absolute);
15035        assert!(!got.update_map);
15036        assert_eq!(got.quant, layer.quantizer);
15037        assert_eq!(got.lf, [None; 4]);
15038        assert_eq!(got.probs, [None; 3]);
15039    }
15040
15041    /// Map-update with no feature data: `update_segment_feature_data` codes
15042    /// 0 (no quantizer / loop-filter deltas), but the three tree
15043    /// probabilities are still written.
15044    #[test]
15045    fn update_segmentation_writer_map_only_no_features() {
15046        let layer = UpdateSegmentationLayer {
15047            update_mb_segmentation_map: true,
15048            feature_mode_absolute: false,
15049            quantizer: [None; 4],
15050            loop_filter: [None; 4],
15051            segment_prob: [Some(255), Some(128), Some(1)],
15052        };
15053        let mut enc = BoolEncoder::new();
15054        write_update_segmentation(&mut enc, &layer);
15055        let buf = enc.finish();
15056
15057        let mut dec = BoolDecoder::init(&buf).unwrap();
15058        assert!(dec.read_bool(128).unwrap());
15059        let got = read_update_segmentation_for_test(&mut dec);
15060        assert!(got.update_map);
15061        assert_eq!(got.quant, [None; 4]);
15062        assert_eq!(got.lf, [None; 4]);
15063        assert_eq!(got.probs, layer.segment_prob);
15064    }
15065
15066    /// Equivalence proof for the round-277 compile-time
15067    /// `PARTITION_GROUP_TABLE`: for each of the four §16.4 partitions,
15068    /// the precomputed groups must be exactly what a direct walk of the
15069    /// §20.13 `MV_PARTITIONS` row produces — the right group count
15070    /// (2 / 2 / 4 / 16), every sub-block in the group whose id the
15071    /// table assigns it, raster-ascending member order (so `group[0]`
15072    /// is the §16.4 anchor), and all 16 sub-blocks covered exactly
15073    /// once.
15074    #[test]
15075    fn partition_group_table_matches_mv_partitions() {
15076        use crate::near_mv::{MV_PARTITIONS, MvPartition, partition_id};
15077        for (p, expected_groups) in [
15078            (MvPartition::TopBottom, 2usize),
15079            (MvPartition::LeftRight, 2),
15080            (MvPartition::Quarters, 4),
15081            (MvPartition::Mv16, 16),
15082        ] {
15083            let groups = partition_groups(p);
15084            assert_eq!(groups.num_groups, expected_groups, "{p:?} group count");
15085            let table = &MV_PARTITIONS[partition_id(p)];
15086            let mut seen = [false; 16];
15087            for g in 0..groups.num_groups {
15088                let members = groups.group(g);
15089                assert!(!members.is_empty(), "{p:?} group {g} empty");
15090                let mut prev: Option<usize> = None;
15091                for &b in members {
15092                    assert_eq!(
15093                        table[b] as usize, g,
15094                        "{p:?} sub-block {b} listed under group {g}"
15095                    );
15096                    assert!(!seen[b], "{p:?} sub-block {b} listed twice");
15097                    seen[b] = true;
15098                    if let Some(prev) = prev {
15099                        assert!(prev < b, "{p:?} group {g} not raster-ascending");
15100                    }
15101                    prev = Some(b);
15102                }
15103            }
15104            assert!(seen.iter().all(|&s| s), "{p:?} does not cover all 16");
15105        }
15106    }
15107
15108    /// Equivalence proof for the round-281 fused
15109    /// [`group_sad_at_whole_mv`] fast path: for every §16.4 partition
15110    /// shape, every group, and a candidate sweep spanning in-bounds and
15111    /// border-straddling whole-pixel MVs (in all four directions), the
15112    /// fused row-window SAD must equal the pre-round-281 per-member
15113    /// assembly (`fetch_block_whole_pixel` + `extract_src_subblock_4x4`
15114    /// + `sub_block_sad_4x4`) bit-for-bit.
15115    #[test]
15116    fn group_sad_fused_fast_path_matches_per_subblock_fetch() {
15117        use crate::motion_vector::Mv;
15118        use crate::near_mv::MvPartition;
15119
15120        // 48×48 plane = 3×3 MBs; MB(0,0) and MB(2,2) reach the plane
15121        // corners so the extreme candidates straddle every border.
15122        let width = 48usize;
15123        let height = 48usize;
15124        let mut plane = vec![0u8; width * height];
15125        for y in 0..height {
15126            for x in 0..width {
15127                plane[y * width + x] = ((x * 11 + y * 17) % 251) as u8;
15128            }
15129        }
15130        let luma = crate::motion_search::LumaRef {
15131            plane: &plane,
15132            stride: width,
15133            width,
15134            height,
15135        };
15136        let mut src_y = [0u8; 256];
15137        for (i, slot) in src_y.iter_mut().enumerate() {
15138            *slot = ((i * 3 + 41) % 249) as u8;
15139        }
15140
15141        let per_subblock_reference =
15142            |mb_col: usize, mb_row: usize, group_subblocks: &[usize], mv: Mv| -> u32 {
15143                let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
15144                let mut sad: u32 = 0;
15145                for &b in group_subblocks {
15146                    let patch = crate::motion_comp::fetch_block_whole_pixel(
15147                        luma.plane,
15148                        luma.stride,
15149                        luma.width,
15150                        luma.height,
15151                        mb_col * 16 + (b & 3) * 4,
15152                        mb_row * 16 + (b >> 2) * 4,
15153                        mv_eighth,
15154                    );
15155                    let src_sb = extract_src_subblock_4x4(&src_y, b);
15156                    sad += sub_block_sad_4x4(&src_sb, &patch);
15157                }
15158                sad
15159            };
15160
15161        let candidates: [Mv; 11] = [
15162            Mv { row: 0, col: 0 },
15163            Mv { row: 4, col: -4 },
15164            Mv { row: -8, col: 12 },
15165            Mv { row: 16, col: 16 },
15166            Mv { row: -16, col: -16 },
15167            Mv { row: 64, col: -64 },
15168            Mv { row: -1020, col: 0 },
15169            Mv { row: 0, col: -1020 },
15170            Mv { row: 1020, col: 0 },
15171            Mv { row: 0, col: 1020 },
15172            Mv {
15173                row: -1020,
15174                col: 1020,
15175            },
15176        ];
15177
15178        for p in [
15179            MvPartition::TopBottom,
15180            MvPartition::LeftRight,
15181            MvPartition::Quarters,
15182            MvPartition::Mv16,
15183        ] {
15184            let groups = partition_groups(p);
15185            for (mb_col, mb_row) in [(0usize, 0usize), (1, 1), (2, 2)] {
15186                for g in 0..groups.num_groups {
15187                    let members = groups.group(g);
15188                    for mv in candidates {
15189                        let expected = per_subblock_reference(mb_col, mb_row, members, mv);
15190                        let got = group_sad_at_whole_mv(luma, mb_col, mb_row, &src_y, members, mv);
15191                        assert_eq!(
15192                            got, expected,
15193                            "fused group SAD diverged: {p:?} group {g} \
15194                             MB({mb_col},{mb_row}) mv={mv:?}"
15195                        );
15196                    }
15197                }
15198            }
15199        }
15200    }
15201
15202    /// Every §20.13 partition group must be an exact rectangle: each
15203    /// member lies inside the precomputed [`GroupShape`] and the member
15204    /// count equals the shape's sub-block area — the contract the
15205    /// r451 row-merged [`group_sad_at_whole_mv_shaped`] fast path
15206    /// relies on.
15207    #[test]
15208    fn partition_group_shapes_are_exact_rectangles() {
15209        use crate::near_mv::MvPartition;
15210        for p in [
15211            MvPartition::TopBottom,
15212            MvPartition::LeftRight,
15213            MvPartition::Quarters,
15214            MvPartition::Mv16,
15215        ] {
15216            let groups = partition_groups(p);
15217            for g in 0..groups.num_groups {
15218                let shape = groups.shape(g);
15219                let members = groups.group(g);
15220                assert_eq!(
15221                    members.len() * 16,
15222                    shape.w_px * shape.h_px,
15223                    "{p:?} group {g}: members must tile the shape"
15224                );
15225                for &b in members {
15226                    let (r0, c0) = ((b >> 2) * 4, (b & 3) * 4);
15227                    assert!(
15228                        r0 >= shape.row0
15229                            && r0 + 4 <= shape.row0 + shape.h_px
15230                            && c0 >= shape.col0
15231                            && c0 + 4 <= shape.col0 + shape.w_px,
15232                        "{p:?} group {g}: member {b} outside shape {shape:?}"
15233                    );
15234                }
15235            }
15236        }
15237    }
15238
15239    /// Equivalence proof for the r451 row-merged shaped group SAD: for
15240    /// every §16.4 partition shape, every group (with its precomputed
15241    /// rectangle), and a candidate sweep spanning in-bounds and
15242    /// border-straddling whole-pixel MVs, the shaped evaluator must
15243    /// equal the per-member assembly (`fetch_block_whole_pixel` +
15244    /// `extract_src_subblock_4x4` + `sub_block_sad_4x4`) bit-for-bit.
15245    #[test]
15246    fn group_sad_shaped_matches_per_subblock_fetch() {
15247        use crate::motion_vector::Mv;
15248        use crate::near_mv::MvPartition;
15249
15250        let width = 48usize;
15251        let height = 48usize;
15252        let mut plane = vec![0u8; width * height];
15253        for y in 0..height {
15254            for x in 0..width {
15255                plane[y * width + x] = ((x * 11 + y * 17) % 251) as u8;
15256            }
15257        }
15258        let luma = crate::motion_search::LumaRef {
15259            plane: &plane,
15260            stride: width,
15261            width,
15262            height,
15263        };
15264        let mut src_y = [0u8; 256];
15265        for (i, slot) in src_y.iter_mut().enumerate() {
15266            *slot = ((i * 3 + 41) % 249) as u8;
15267        }
15268
15269        let per_subblock_reference =
15270            |mb_col: usize, mb_row: usize, group_subblocks: &[usize], mv: Mv| -> u32 {
15271                let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
15272                let mut sad: u32 = 0;
15273                for &b in group_subblocks {
15274                    let patch = crate::motion_comp::fetch_block_whole_pixel(
15275                        luma.plane,
15276                        luma.stride,
15277                        luma.width,
15278                        luma.height,
15279                        mb_col * 16 + (b & 3) * 4,
15280                        mb_row * 16 + (b >> 2) * 4,
15281                        mv_eighth,
15282                    );
15283                    let src_sb = extract_src_subblock_4x4(&src_y, b);
15284                    sad += sub_block_sad_4x4(&src_sb, &patch);
15285                }
15286                sad
15287            };
15288
15289        let candidates: [Mv; 9] = [
15290            Mv { row: 0, col: 0 },
15291            Mv { row: 4, col: -4 },
15292            Mv { row: -8, col: 12 },
15293            Mv { row: 16, col: 16 },
15294            Mv { row: -16, col: -16 },
15295            Mv { row: 64, col: -64 },
15296            Mv { row: -1020, col: 0 },
15297            Mv { row: 0, col: 1020 },
15298            Mv {
15299                row: -1020,
15300                col: 1020,
15301            },
15302        ];
15303
15304        for p in [
15305            MvPartition::TopBottom,
15306            MvPartition::LeftRight,
15307            MvPartition::Quarters,
15308            MvPartition::Mv16,
15309        ] {
15310            let groups = partition_groups(p);
15311            for (mb_col, mb_row) in [(0usize, 0usize), (1, 1), (2, 2)] {
15312                for g in 0..groups.num_groups {
15313                    let members = groups.group(g);
15314                    let shape = groups.shape(g);
15315                    for mv in candidates {
15316                        let expected = per_subblock_reference(mb_col, mb_row, members, mv);
15317                        let got = group_sad_at_whole_mv_shaped(
15318                            luma, mb_col, mb_row, &src_y, members, shape, mv,
15319                        );
15320                        assert_eq!(got, expected, "{p:?} group {g} mv {mv:?}");
15321                    }
15322                }
15323            }
15324        }
15325    }
15326
15327    /// Equivalence proof for the precomputed `TOKEN_BIT_PATHS` table:
15328    /// for every reachable `(start_index, token)` combination, the
15329    /// table's stored `(prob_index, bit)` sequence must equal the result
15330    /// of running the §13.2 tree descent on `ENC_COEFF_TREE` directly.
15331    /// Also asserts the one unreachable cell (`start_index = 2`,
15332    /// `token = Eob`) stays a length-0 tombstone — the §13.2 "previous
15333    /// coefficient was DCT_0 → skip Eob branch" invariant — so any
15334    /// future call to it will trip the in-function `debug_assert`.
15335    #[test]
15336    fn token_bit_path_table_matches_tree_descent() {
15337        // Reference descent — duplicates the original recursive walk
15338        // before round 204 precomputed it into TOKEN_BIT_PATHS.
15339        fn reference_descent(i: i8, target: i8, path: &mut Vec<(usize, bool)>) -> bool {
15340            for &bit in &[false, true] {
15341                let child = ENC_COEFF_TREE[i as usize + bit as usize];
15342                if child <= 0 {
15343                    if -child == target {
15344                        path.push(((i as usize) >> 1, bit));
15345                        return true;
15346                    }
15347                } else {
15348                    path.push(((i as usize) >> 1, bit));
15349                    if reference_descent(child, target, path) {
15350                        return true;
15351                    }
15352                    path.pop();
15353                }
15354            }
15355            false
15356        }
15357
15358        let tokens = [
15359            DctToken::Dct0,
15360            DctToken::Dct1,
15361            DctToken::Dct2,
15362            DctToken::Dct3,
15363            DctToken::Dct4,
15364            DctToken::Cat1,
15365            DctToken::Cat2,
15366            DctToken::Cat3,
15367            DctToken::Cat4,
15368            DctToken::Cat5,
15369            DctToken::Cat6,
15370            DctToken::Eob,
15371        ];
15372
15373        for &start in &[0i8, 2i8] {
15374            for &token in &tokens {
15375                let mut reference = Vec::new();
15376                let reachable = reference_descent(start, token as i8, &mut reference);
15377
15378                // The single unreachable cell.
15379                if !reachable {
15380                    assert_eq!(
15381                        (start, token),
15382                        (2i8, DctToken::Eob),
15383                        "unexpected unreachable (start, token) = ({start}, {token:?})"
15384                    );
15385                    let slot = 1usize;
15386                    let (_, len) = &TOKEN_BIT_PATHS[slot][token as usize];
15387                    assert_eq!(*len, 0, "(start=2, Eob) must remain a length-0 tombstone");
15388                    continue;
15389                }
15390
15391                let table = token_to_bit_path(token, start);
15392                assert_eq!(
15393                    table.len(),
15394                    reference.len(),
15395                    "path-length mismatch for (start={start}, token={token:?})"
15396                );
15397                for (k, &(ref_i, ref_bit)) in reference.iter().enumerate() {
15398                    assert_eq!(
15399                        table[k].prob_index as usize, ref_i,
15400                        "prob_index mismatch at step {k} of (start={start}, token={token:?})"
15401                    );
15402                    assert_eq!(
15403                        table[k].bit, ref_bit,
15404                        "bit mismatch at step {k} of (start={start}, token={token:?})"
15405                    );
15406                }
15407            }
15408        }
15409
15410        // Width contract: no path should ever exceed the static buffer.
15411        const { assert!(TOKEN_BIT_PATH_MAX_LEN >= 7) };
15412        for (slot, paths) in TOKEN_BIT_PATHS.iter().enumerate() {
15413            for (token, (_, len)) in paths.iter().enumerate() {
15414                assert!(
15415                    (*len as usize) <= TOKEN_BIT_PATH_MAX_LEN,
15416                    "path length {} > buffer capacity {} at slot={slot} token={token}",
15417                    *len,
15418                    TOKEN_BIT_PATH_MAX_LEN
15419                );
15420            }
15421        }
15422    }
15423
15424    /// Sanity check on the local `COEFF_UPDATE_PROBS` table — the
15425    /// 1056-entry flat walk should be non-zero and the last entry should
15426    /// equal `[3][7][2][10]` of the nested form. Catches a transcription
15427    /// typo or a flattening-loop off-by-one.
15428    #[test]
15429    fn coeff_update_probs_flat_walk_is_consistent() {
15430        let s: u32 = COEFF_UPDATE_PROBS_FLAT.iter().map(|&p| p as u32).sum();
15431        assert!(s > 0);
15432        assert_eq!(
15433            COEFF_UPDATE_PROBS_FLAT[3 * 8 * 3 * 11 + 7 * 3 * 11 + 2 * 11 + 10],
15434            COEFF_UPDATE_PROBS[3][7][2][10]
15435        );
15436    }
15437
15438    /// Anchor the §13.4 `token_prob_update()` walk-order byte-
15439    /// equivalence between [`write_no_token_prob_updates`] and
15440    /// [`write_token_prob_updates`]-handed-all-`None` against the
15441    /// **actual** §13.4 `coeff_update_probs[4][8][3][11]` spec table
15442    /// (RFC 6386 §13.4 page 69), not a flat `[128u8; 1056]` placeholder.
15443    ///
15444    /// Why both writers should agree on every byte when the §13.4 flag
15445    /// is `false` everywhere:
15446    ///
15447    /// * Both writers walk the same `(i=0..4, j=0..8, k=0..3, t=0..11)`
15448    ///   four-nested-`do/while` order from RFC 6386 §13.4.
15449    /// * Both writers consult `flag_probs[i*8*3*11 + j*3*11 + k*11 + t]`
15450    ///   when emitting the per-position "is this slot replaced?" bit.
15451    /// * On the all-`None` path, `write_token_prob_updates` emits
15452    ///   `write_bool(p, false)` at every position and never follows up
15453    ///   with an `L(8)`; `write_no_token_prob_updates` emits the same
15454    ///   `write_bool(p, false)` at the same `p`. With the bool encoder
15455    ///   being deterministic on `(state, prob, bit)` triples, the byte
15456    ///   streams MUST be identical.
15457    ///
15458    /// The existing external test
15459    /// (`tests/encoder_token_prob_updates.rs::write_token_prob_updates_all_none_matches_no_update_writer`)
15460    /// validates this with a flat `[128u8; 1056]`, which means the bool
15461    /// encoder's range / split machinery never exercises the rare
15462    /// extreme-probability splits the §13.4 table actually contains
15463    /// (the table has entries as low as `5` and as high as `255`). This
15464    /// in-crate test closes that gap by exercising the byte equivalence
15465    /// against the real §13.4 flag table — if a future refactor of
15466    /// either writer subtly diverges (e.g. one switches to `write_bit`
15467    /// at a hard-coded probability, or skips a slot when the flag
15468    /// probability is `0` / `255`), the [128;1056] placeholder test
15469    /// might still pass while this one would catch the regression.
15470    #[test]
15471    fn write_no_token_prob_updates_matches_all_none_against_spec_flag_probs() {
15472        let no_updates: crate::coded_header::TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
15473
15474        let mut a = BoolEncoder::new();
15475        write_no_token_prob_updates(&mut a, &COEFF_UPDATE_PROBS_FLAT);
15476        let bytes_a = a.finish();
15477
15478        let mut b = BoolEncoder::new();
15479        write_token_prob_updates(&mut b, &no_updates, &COEFF_UPDATE_PROBS_FLAT);
15480        let bytes_b = b.finish();
15481
15482        assert_eq!(
15483            bytes_a, bytes_b,
15484            "writers must agree on the all-None §13.4 payload under \
15485             the real coeff_update_probs[4][8][3][11] table — any \
15486             divergence here means the §13.4 four-nested walk order \
15487             or the per-position probability lookup has drifted \
15488             between the two writers."
15489        );
15490
15491        // Bit-count sanity: both writers emit exactly 1056 bool bits
15492        // and no L(8) payload on the all-None path, so the output must
15493        // be non-empty (the bool encoder always flushes at least one
15494        // partial byte at `finish()`).
15495        assert!(
15496            !bytes_a.is_empty(),
15497            "all-None §13.4 payload must still emit at least one byte"
15498        );
15499    }
15500
15501    /// Anchor the encoder-side §17.2 `MV_UPDATE_PROBS_FLAT` 38-entry
15502    /// flat table against the canonical 2×19 spec table held in
15503    /// [`crate::coded_header`] (`MV_UPDATE_PROBS`, transcribed from
15504    /// RFC 6386 §17.2 `vp8_mv_update_probs[2]`).
15505    ///
15506    /// The encoder's `mv_prob_update()` writer (called inline by
15507    /// every inter-frame entry-point — see the
15508    /// `for ctx in MV_UPDATE_PROBS_FLAT.iter()` loop around the §17.2
15509    /// no-update flag emission) walks a flat 38-entry copy of the
15510    /// table. The decoder (`parse_mv_prob_update`) reads each `F`
15511    /// flag at `MV_UPDATE_PROBS[i][j]`. If the two transcriptions
15512    /// ever drift — a typo, a row/column swap, or an off-by-one in
15513    /// the flat walk — the encoder would emit `write_bool(p1, false)`
15514    /// at one probability while the decoder consumed `read_bool(p2)`
15515    /// at a different one, silently producing a bool-coder range that
15516    /// looks valid but means a wholly different bitstream to a
15517    /// third-party reference reader. CI would catch it on the
15518    /// self-roundtrip, but only after a real encode runs; this anchor
15519    /// catches the divergence at lib-test time on the *constants*.
15520    ///
15521    /// The walk order is row-major `(component=0..2, position=0..19)`,
15522    /// matching the encoder's flat layout (rows concatenated) and the
15523    /// decoder's `for i in 0..2 { for j in 0..MV_PROB_COUNT { ... } }`
15524    /// double-loop. Sanity-checks the flat length too — `MV_PROB_COUNT`
15525    /// could be re-defined and silently shrink the spec table without
15526    /// the encoder's `[u8; 38]` literal noticing.
15527    #[test]
15528    fn mv_update_probs_flat_matches_spec_table() {
15529        use crate::coded_header::{MV_PROB_COUNT, MV_UPDATE_PROBS};
15530
15531        assert_eq!(
15532            MV_UPDATE_PROBS_FLAT.len(),
15533            2 * MV_PROB_COUNT,
15534            "MV_UPDATE_PROBS_FLAT length must match 2 × MV_PROB_COUNT \
15535             (RFC 6386 §17.2 two MV_CONTEXTs × 19 positions)"
15536        );
15537
15538        for i in 0..2 {
15539            for j in 0..MV_PROB_COUNT {
15540                let flat = MV_UPDATE_PROBS_FLAT[i * MV_PROB_COUNT + j];
15541                let spec = MV_UPDATE_PROBS[i][j];
15542                assert_eq!(
15543                    flat, spec,
15544                    "encoder-side MV_UPDATE_PROBS_FLAT[{i}*{MV_PROB_COUNT}+{j}] \
15545                     ({flat}) diverges from the §17.2 spec table \
15546                     MV_UPDATE_PROBS[{i}][{j}] ({spec}) the decoder reads at"
15547                );
15548            }
15549        }
15550    }
15551
15552    /// Anchor the encoder-side §13.2 `ENC_PCAT1..ENC_PCAT6` extra-bits
15553    /// probability lists and `ENC_CAT_BASE` category-base offsets against
15554    /// the literal §13.2 spec listing transcribed inline from
15555    /// RFC 6386 §13.2 (the `Pcat1..Pcat6` arrays at the `DCTextra`
15556    /// definition, and `categoryBase[6]` immediately preceding the
15557    /// `vp8_dct_value_cost` cost table).
15558    ///
15559    /// The encoder consults these six lists in `cat_extras()` to drive
15560    /// `DCTextra`'s per-bit `read_bool(d, *p)` (decoder side); the
15561    /// encoder mirror is the per-bit `write_bool(p, bit)` walk that
15562    /// emits the `(v - categoryBase[c])` residual MSB-first against the
15563    /// same `Pcat` probability sequence. If a `Pcat` byte or a
15564    /// `CAT_BASE` offset drifts here — a typo, a transposed pair, a
15565    /// dropped trailing zero swept into the slice — the encoder would
15566    /// emit a bit at `p1` while a third-party reference reader consumed
15567    /// the same bit at `p2`, silently producing a bool-coder range that
15568    /// looks valid but means a *different* residual integer to the
15569    /// reader. CI's self-roundtrip would still pass (encoder + decoder
15570    /// drift together), but `ffmpeg -c:v vp8` would diverge on the
15571    /// first cat-token. This anchor catches the divergence at
15572    /// lib-test time on the *constants*, before any real frame
15573    /// encode runs.
15574    ///
15575    /// Spec source (verbatim from RFC 6386 §13.2):
15576    ///
15577    /// ```text
15578    ///     const Prob Pcat1[] = { 159, 0};
15579    ///     const Prob Pcat2[] = { 165, 145, 0};
15580    ///     const Prob Pcat3[] = { 173, 148, 140, 0};
15581    ///     const Prob Pcat4[] = { 176, 155, 140, 135, 0};
15582    ///     const Prob Pcat5[] = { 180, 157, 141, 134, 130, 0};
15583    ///     const Prob Pcat6[] =
15584    ///         { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0};
15585    ///     ...
15586    ///     int categoryBase[6] = { 5, 7, 11, 19, 35, 67 };
15587    /// ```
15588    ///
15589    /// The encoder's local copies drop the `0` terminator (the encoder
15590    /// walks a known-length slice instead of testing `*p` at the loop
15591    /// edge), so the byte-equal comparison runs against the
15592    /// terminator-stripped prefix of each spec list.
15593    #[test]
15594    fn enc_pcat_and_cat_base_match_spec_listing() {
15595        // RFC 6386 §13.2 — Pcat1..Pcat6 with trailing `0` terminator
15596        // stripped (encoder walks a fixed-length slice).
15597        const SPEC_PCAT1: &[u8] = &[159];
15598        const SPEC_PCAT2: &[u8] = &[165, 145];
15599        const SPEC_PCAT3: &[u8] = &[173, 148, 140];
15600        const SPEC_PCAT4: &[u8] = &[176, 155, 140, 135];
15601        const SPEC_PCAT5: &[u8] = &[180, 157, 141, 134, 130];
15602        const SPEC_PCAT6: &[u8] = &[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129];
15603        // RFC 6386 §13.2 — categoryBase[6].
15604        const SPEC_CAT_BASE: [u16; 6] = [5, 7, 11, 19, 35, 67];
15605
15606        // Length sanity — the encoder's six Pcat slices must match
15607        // the spec list lengths (1, 2, 3, 4, 5, 11 extra bits for
15608        // cat1..cat6 respectively; the cat6 range spans 67..=2114
15609        // = 2048 values requiring 11 bits, the rest follow the
15610        // geometric `(2^n - 1) + base` pattern).
15611        let enc_lists: [(&[u8], &[u8], &str, usize); 6] = [
15612            (ENC_PCAT1, SPEC_PCAT1, "Pcat1", 1),
15613            (ENC_PCAT2, SPEC_PCAT2, "Pcat2", 2),
15614            (ENC_PCAT3, SPEC_PCAT3, "Pcat3", 3),
15615            (ENC_PCAT4, SPEC_PCAT4, "Pcat4", 4),
15616            (ENC_PCAT5, SPEC_PCAT5, "Pcat5", 5),
15617            (ENC_PCAT6, SPEC_PCAT6, "Pcat6", 11),
15618        ];
15619        for (enc_list, spec_list, name, expected_len) in enc_lists.iter() {
15620            assert_eq!(
15621                enc_list.len(),
15622                *expected_len,
15623                "encoder-side {name} carries {} probs but §13.2 \
15624                 emits exactly {expected_len} extra bits",
15625                enc_list.len()
15626            );
15627            assert_eq!(
15628                enc_list.len(),
15629                spec_list.len(),
15630                "encoder-side {name} length ({}) diverges from §13.2 \
15631                 spec list length ({})",
15632                enc_list.len(),
15633                spec_list.len()
15634            );
15635            for (k, (&enc_p, &spec_p)) in enc_list.iter().zip(spec_list.iter()).enumerate() {
15636                assert_eq!(
15637                    enc_p, spec_p,
15638                    "encoder-side {name}[{k}] ({enc_p}) diverges from \
15639                     §13.2 spec listing {name}[{k}] ({spec_p}) — the \
15640                     decoder's DCTextra() reads each cat-residual bit \
15641                     at this probability"
15642                );
15643            }
15644        }
15645
15646        // CAT_BASE — the §13.2 `categoryBase[6]` offsets used by
15647        // `cat_extras()` to add to the decoded residual `v`.
15648        assert_eq!(
15649            ENC_CAT_BASE.len(),
15650            SPEC_CAT_BASE.len(),
15651            "encoder-side ENC_CAT_BASE length ({}) diverges from \
15652             §13.2 categoryBase[6] ({})",
15653            ENC_CAT_BASE.len(),
15654            SPEC_CAT_BASE.len()
15655        );
15656        for k in 0..ENC_CAT_BASE.len() {
15657            assert_eq!(
15658                ENC_CAT_BASE[k],
15659                SPEC_CAT_BASE[k],
15660                "encoder-side ENC_CAT_BASE[{k}] ({}) diverges from \
15661                 §13.2 spec categoryBase[{k}] ({}) — the decoder adds \
15662                 this offset to the cat{}-residual",
15663                ENC_CAT_BASE[k],
15664                SPEC_CAT_BASE[k],
15665                k + 1
15666            );
15667        }
15668
15669        // Cross-check `cat_extras()` returns the same `(base, list)`
15670        // pair the encoder's per-cat-token writer consumes — catches
15671        // a future drift where the match-arm order desyncs from the
15672        // table index. The `expected_bits` field carries the §13.2
15673        // extra-bits count for each cat (1, 2, 3, 4, 5, 11).
15674        let cat_token_pairs: [(DctToken, usize, usize); 6] = [
15675            (DctToken::Cat1, 0, 1),
15676            (DctToken::Cat2, 1, 2),
15677            (DctToken::Cat3, 2, 3),
15678            (DctToken::Cat4, 3, 4),
15679            (DctToken::Cat5, 4, 5),
15680            (DctToken::Cat6, 5, 11),
15681        ];
15682        for (tok, expected_idx, expected_bits) in cat_token_pairs.iter() {
15683            let (base, list) = cat_extras(*tok).expect("cat-token must carry extras");
15684            assert_eq!(
15685                base, ENC_CAT_BASE[*expected_idx],
15686                "cat_extras({tok:?}) returned base {base} but \
15687                 §13.2 categoryBase[{expected_idx}] is {}",
15688                ENC_CAT_BASE[*expected_idx]
15689            );
15690            assert_eq!(
15691                list.len(),
15692                *expected_bits,
15693                "cat_extras({tok:?}) returned a Pcat list of len {} \
15694                 but §13.2 emits exactly {expected_bits} extra bits",
15695                list.len()
15696            );
15697        }
15698
15699        // Non-cat tokens (Dct0..Dct4, Eob) must not advertise extras —
15700        // any future regression that started returning `Some(...)` for
15701        // them would lead to bogus tail bits in the bitstream.
15702        for tok in [
15703            DctToken::Eob,
15704            DctToken::Dct0,
15705            DctToken::Dct1,
15706            DctToken::Dct2,
15707            DctToken::Dct3,
15708            DctToken::Dct4,
15709        ] {
15710            assert!(
15711                cat_extras(tok).is_none(),
15712                "cat_extras({tok:?}) must be None — §13.2 reserves \
15713                 the trailing `DCTextra` walk for cat1..cat6 only"
15714            );
15715        }
15716    }
15717
15718    /// The §11 mode-layer writer must produce a first partition the
15719    /// decoder's `parse_key_frame_macroblock_modes` reads back to the
15720    /// exact `MacroblockModes` the encoder chose — including the §11.3
15721    /// cross-macroblock `B_PRED` sub-block context evolution. We encode a
15722    /// small synthetic frame, re-parse the control partition, and compare
15723    /// the recovered modes to the encoder's own (recomputed here by the
15724    /// same per-MB picker the driver uses).
15725    #[test]
15726    fn mode_layer_roundtrips_through_decoder_parser() {
15727        // A 32×32 frame (2×2 macroblocks) with a structured gradient so
15728        // the picker exercises more than one luma / chroma mode.
15729        let (w, h) = (32u32, 32u32);
15730        let cw = w.div_ceil(2) as usize;
15731        let ch = h.div_ceil(2) as usize;
15732        let mut y = vec![0u8; (w * h) as usize];
15733        for r in 0..h as usize {
15734            for c in 0..w as usize {
15735                y[r * w as usize + c] = ((r * 8 + c * 8) & 0xff) as u8;
15736            }
15737        }
15738        let u = vec![110u8; cw * ch];
15739        let v = vec![140u8; cw * ch];
15740        let frame = I420Frame::packed(w, h, &y, &u, &v);
15741        let params = KeyframeParams {
15742            y_ac_qi: 32,
15743            loop_filter_level: 0,
15744            sharpness_level: 0,
15745            nbr_of_dct_partitions: 1,
15746            filter_type: false,
15747            trellis_strength: TrellisStrength::DEFAULT,
15748        };
15749        let bytes = encode_keyframe(&frame, &params).expect("encode");
15750
15751        // Re-parse the control partition exactly as the decoder does.
15752        let header = Vp8FrameHeader::parse(&bytes).unwrap();
15753        let off = header.header_bytes_consumed;
15754        let size = header.first_partition_size as usize;
15755        let first = &bytes[off..off + size];
15756        let (coded, mut dec) = Vp8CodedHeader::parse_with_decoder(first, true).unwrap();
15757        let parsed =
15758            crate::macroblock::parse_key_frame_macroblock_modes(&mut dec, &coded, 2, 2).unwrap();
15759        assert_eq!(parsed.len(), 4);
15760
15761        // Recompute the encoder's own chosen modes by replaying the
15762        // raster driver's per-MB pick against the reconstructed planes —
15763        // the simplest oracle is to decode the frame and confirm it
15764        // succeeds (which it does in the integration test); here we
15765        // assert structural invariants the parser must satisfy.
15766        for mb in &parsed {
15767            // A B_PRED MB must carry sixteen sub-block modes; a
15768            // whole-block MB must carry none.
15769            assert_eq!(
15770                mb.subblock_modes.is_some(),
15771                mb.y_mode == IntraYMode::B,
15772                "subblock_modes presence must track B_PRED"
15773            );
15774        }
15775
15776        // End-to-end: the frame decodes without error and the modes the
15777        // decoder used are byte-identical to what we re-parsed (the
15778        // decoder runs the same parser internally).
15779        let decoded = decode_vp8(&bytes).expect("decode");
15780        assert_eq!(decoded.width, w);
15781        assert_eq!(decoded.height, h);
15782    }
15783
15784    /// Build a 64×64 structured-but-natural I420 test frame: a smooth
15785    /// luma gradient with a low-amplitude pseudo-random texture overlay,
15786    /// and gently varying chroma. Returns `(y, u, v)` tightly packed.
15787    /// Shared by the RD validation tests.
15788    fn natural_test_frame_64x64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
15789        let (w, h) = (64usize, 64usize);
15790        let (cw, ch) = (32usize, 32usize);
15791        let mut y = vec![0u8; w * h];
15792        let mut state: u32 = 0x1234_5678;
15793        let mut next = || {
15794            state = state.wrapping_mul(1_103_515_245).wrapping_add(12345);
15795            (state >> 16) & 0x1f
15796        };
15797        for r in 0..h {
15798            for c in 0..w {
15799                let base = 40 + (r + c) * 2;
15800                let tex = next() as usize;
15801                y[r * w + c] = (base + tex).min(235) as u8;
15802            }
15803        }
15804        let mut u = vec![0u8; cw * ch];
15805        let mut v = vec![0u8; cw * ch];
15806        for r in 0..ch {
15807            for c in 0..cw {
15808                u[r * cw + c] = (100 + r) as u8;
15809                v[r * cw + c] = (150 - c) as u8;
15810            }
15811        }
15812        (y, u, v)
15813    }
15814
15815    /// Decode a VP8 keyframe and return the luma-plane PSNR against the
15816    /// source. The decoder returns a visible-cropped, tightly-packed luma
15817    /// plane, so the comparison is direct.
15818    fn keyframe_luma_psnr(bytes: &[u8], src_y: &[u8], w: usize, h: usize) -> f64 {
15819        let decoded = decode_vp8(bytes).expect("decode");
15820        psnr(&src_y[..w * h], &decoded.y[..w * h])
15821    }
15822
15823    /// The rate-distortion mode picker must keep the self-decode PSNR high
15824    /// on a natural keyframe while producing a valid, decodable stream.
15825    /// This is the floor the RD trade must never fall below: the picker
15826    /// may shave bits, but the reconstruction quality stays well above
15827    /// 30 dB at a mid quantiser.
15828    #[test]
15829    fn rd_keyframe_holds_psnr_floor_on_natural_frame() {
15830        let (w, h) = (64u32, 64u32);
15831        let (y, u, v) = natural_test_frame_64x64();
15832        let frame = I420Frame::packed(w, h, &y, &u, &v);
15833        for qi in [16u8, 32, 48] {
15834            let params = KeyframeParams {
15835                y_ac_qi: qi,
15836                loop_filter_level: 0,
15837                sharpness_level: 0,
15838                nbr_of_dct_partitions: 1,
15839                filter_type: false,
15840                trellis_strength: TrellisStrength::DEFAULT,
15841            };
15842            let bytes = encode_keyframe(&frame, &params).expect("encode");
15843            let p = keyframe_luma_psnr(&bytes, &y, w as usize, h as usize);
15844            assert!(
15845                p >= 30.0,
15846                "RD keyframe luma PSNR {p:.2} dB < 30 dB floor at qi={qi}"
15847            );
15848        }
15849    }
15850
15851    /// The §14.4 inverse-DCT basis-norm distortion model the trellis uses
15852    /// must track the actual pixel-domain reconstruction SSD: summing
15853    /// `norm_k · (x_k − level_k·q)^2` over the scan positions reproduces
15854    /// `block_ssd(reconstruct, src)` to within the IDCT's sub-LSB rounding.
15855    #[test]
15856    fn trellis_basis_norm_distortion_tracks_pixel_ssd() {
15857        // The §14.4 IDCT basis vectors are near-equal-energy (≈ 0.25 each).
15858        let norms = &*super::IDCT_BASIS_NORM_SQ;
15859        for &n in norms.iter() {
15860            assert!((0.24..0.26).contains(&n), "basis norm {n} out of range");
15861        }
15862        // A handful of synthetic residual blocks; predicted (model) SSD
15863        // must closely track the true reconstruction SSD.
15864        for seed in 0u32..8 {
15865            let mut st = 0x1357u32.wrapping_add(seed.wrapping_mul(0x9E3D));
15866            let mut next = || {
15867                st = st.wrapping_mul(1_103_515_245).wrapping_add(12345);
15868                (st >> 16) as i32
15869            };
15870            let pred = [128u8; 16];
15871            let mut src = [0u8; 16];
15872            for s in src.iter_mut() {
15873                *s = (128 + (next() % 60) - 30).clamp(0, 255) as u8;
15874            }
15875            let mut residual = [0i16; 16];
15876            for k in 0..16 {
15877                residual[k] = src[k] as i16 - pred[k] as i16;
15878            }
15879            let mut coeffs = [0i16; 16];
15880            super::forward_dct_4x4(&residual, &mut coeffs);
15881            let (dc, ac) = (16i16, 18i16);
15882            let mut q = coeffs;
15883            super::enc_quantize_block(&mut q, dc, ac);
15884            let recon = super::reconstruct_block_4x4(&pred, &q, dc, ac);
15885            let actual = super::block_ssd(&recon, &src) as f64;
15886
15887            let scan_x = super::raster_to_scan(&coeffs);
15888            let scan_q = super::raster_to_scan(&q);
15889            let mut model = 0.0f64;
15890            for k in 0..16 {
15891                let step = if k == 0 { dc } else { ac } as i64;
15892                let err = (scan_x[k] as i64).abs() - (scan_q[k] as i64).abs() * step;
15893                model += norms[k] * (err * err) as f64;
15894            }
15895            // Within 8 SSD-units or 25 % — the gap is the IDCT's `+4 >> 3`
15896            // rounding, which never exceeds a fraction of an LSB per pixel.
15897            let tol = (actual * 0.25).max(8.0);
15898            assert!(
15899                (model - actual).abs() <= tol,
15900                "seed {seed}: model SSD {model:.1} vs actual {actual:.1} (tol {tol:.1})"
15901            );
15902        }
15903    }
15904
15905    /// Trellis output must round-trip byte-exact through the §13.3 token
15906    /// encoder + decoder, and never raise the Lagrangian `J = D + λ·R`
15907    /// above plain round-quantisation (it is, by construction, the RD
15908    /// minimiser over its candidate set).
15909    #[test]
15910    fn trellis_round_trips_and_never_raises_rd_cost() {
15911        let probs = crate::DEFAULT_COEFF_PROBS;
15912        let factors = crate::dequant::MbDequantFactors::from_base_and_deltas(40, 0, 0, 0, 0, 0);
15913        let lambda = super::rd_lambda(&factors) * super::TRELLIS_LAMBDA_SCALE;
15914        let (dc, ac) = (factors.uv_dc, factors.uv_ac);
15915
15916        for seed in 0u32..32 {
15917            let mut st = 0xBEEFu32.wrapping_add(seed.wrapping_mul(0x9E3D));
15918            let mut next = || {
15919                st = st.wrapping_mul(1_103_515_245).wrapping_add(12345);
15920                (st >> 15) as i32
15921            };
15922            let pred = [128u8; 16];
15923            let mut src = [0u8; 16];
15924            for s in src.iter_mut() {
15925                *s = (128 + (next() % 90) - 45).clamp(0, 255) as u8;
15926            }
15927            let mut residual = [0i16; 16];
15928            for k in 0..16 {
15929                residual[k] = src[k] as i16 - pred[k] as i16;
15930            }
15931            let mut base = [0i16; 16];
15932            super::forward_dct_4x4(&residual, &mut base);
15933
15934            // Cost helper: J = D + λ·R, where D is the **basis-norm model**
15935            // distortion the trellis actually optimises (transform-domain
15936            // squared error scaled by the §14.4 IDCT basis norms), and R is
15937            // the §13.3 token bits. The trellis is the exact RD minimiser
15938            // over this model, so it can never raise this J above plain
15939            // round-quantisation. (Against the true pixel SSD the trellis
15940            // is near-optimal but not provably ≤, since the model differs
15941            // from the pixel domain by the IDCT's sub-LSB rounding — see
15942            // `trellis_basis_norm_distortion_tracks_pixel_ssd`.)
15943            let norms = &*super::IDCT_BASIS_NORM_SQ;
15944            let cost = |quant: &[i16; 16]| -> f64 {
15945                let scan_q = super::raster_to_scan(quant);
15946                let scan_x = super::raster_to_scan(&base);
15947                let mut d = 0.0f64;
15948                for k in 0..16 {
15949                    let step = if k == 0 { dc } else { ac } as i64;
15950                    let err = (scan_x[k] as i64).abs() - (scan_q[k] as i64).abs() * step;
15951                    d += norms[k] * (err * err) as f64;
15952                }
15953                let r = super::estimate_block_bits(BlockType::UV, &probs, false, false, &scan_q);
15954                d + lambda * r
15955            };
15956
15957            let mut plain = base;
15958            super::enc_quantize_block(&mut plain, dc, ac);
15959
15960            let mut trel = base;
15961            super::trellis_quantize_block(
15962                &mut trel,
15963                super::TrellisBlockSpec {
15964                    dc,
15965                    ac,
15966                    first_coeff: BlockType::UV.first_coeff(),
15967                    entry_ctx3: 0,
15968                    plane: BlockType::UV.plane_index(),
15969                },
15970                &probs,
15971                None,
15972                // `trellis_quantize_block` now consumes the **effective**
15973                // (already-scaled) coefficient lambda — the same `lambda`
15974                // the cost helper above prices J against.
15975                lambda,
15976            );
15977
15978            // (1) RD non-regression — the trellis cost is ≤ plain rounding.
15979            let (cp, ct) = (cost(&plain), cost(&trel));
15980            assert!(
15981                ct <= cp + 1e-6,
15982                "seed {seed}: trellis J {ct:.2} > plain J {cp:.2}"
15983            );
15984
15985            // (2) Byte-exact §13.3 round-trip of the trellis levels (in
15986            //     scan order, the layout `encode_coeff_block` consumes).
15987            let scan = super::raster_to_scan(&trel);
15988            let recovered = encode_then_decode_block(BlockType::UV, &scan, false, false);
15989            assert_eq!(
15990                recovered, scan,
15991                "seed {seed}: trellis block did not round-trip through §13.3"
15992            );
15993        }
15994    }
15995
15996    /// The rate-distortion picker must not regress against the prior
15997    /// SAD-only picker: at a fixed quantiser it produces a **smaller**
15998    /// stream while holding equal-or-better self-decode PSNR. The
15999    /// SAD-baseline numbers below were captured from the r135 picker on
16000    /// this exact frame (`natural_test_frame_64x64`); the RD picker beats
16001    /// them on both byte count and PSNR at every quantiser, so we assert
16002    /// the RD output never exceeds the SAD byte count and never drops
16003    /// below the SAD PSNR. This pins the RD trade as a strict improvement.
16004    #[test]
16005    fn rd_beats_sad_baseline_size_and_quality() {
16006        // (qi, SAD bytes, SAD luma PSNR) measured on the r135 SAD picker.
16007        let sad_baseline: [(u8, usize, f64); 5] = [
16008            (16, 1467, 39.293),
16009            (24, 1192, 36.777),
16010            (32, 1003, 34.561),
16011            (48, 731, 31.742),
16012            (64, 383, 29.921),
16013        ];
16014        let (w, h) = (64u32, 64u32);
16015        let (y, u, v) = natural_test_frame_64x64();
16016        let frame = I420Frame::packed(w, h, &y, &u, &v);
16017        for (qi, sad_bytes, sad_psnr) in sad_baseline {
16018            let params = KeyframeParams {
16019                y_ac_qi: qi,
16020                loop_filter_level: 0,
16021                sharpness_level: 0,
16022                nbr_of_dct_partitions: 1,
16023                filter_type: false,
16024                trellis_strength: TrellisStrength::DEFAULT,
16025            };
16026            let bytes = encode_keyframe(&frame, &params).expect("encode");
16027            let p = keyframe_luma_psnr(&bytes, &y, w as usize, h as usize);
16028            assert!(
16029                bytes.len() <= sad_bytes,
16030                "RD stream at qi={qi} ({} B) must not exceed the SAD baseline ({sad_bytes} B)",
16031                bytes.len()
16032            );
16033            assert!(
16034                p >= sad_psnr - 0.05,
16035                "RD PSNR at qi={qi} ({p:.3} dB) must hold the SAD baseline ({sad_psnr:.3} dB)"
16036            );
16037        }
16038    }
16039
16040    /// The §13 [`TrellisStrength`] knob is monotone in the rate/quality
16041    /// trade: dialing it up never *grows* the keyframe and dialing it to
16042    /// [`TrellisStrength::OFF`] reproduces the pre-trellis (plain-rounding)
16043    /// bytes — which are the largest of the three, since the trellis only
16044    /// ever shaves bits. Every strength must still decode, and the
16045    /// calibrated [`TrellisStrength::DEFAULT`] must match the historical
16046    /// `rd_beats_sad_baseline` byte ceiling exactly (the knob is a strict
16047    /// superset of the previously-fixed `0.04` scale).
16048    #[test]
16049    fn trellis_strength_knob_is_monotone_and_round_trips() {
16050        let (w, h) = (64u32, 64u32);
16051        let (y, u, v) = natural_test_frame_64x64();
16052        let frame = I420Frame::packed(w, h, &y, &u, &v);
16053        // Same fixed-quantiser working points the SAD-baseline test pins.
16054        for qi in [16u8, 24, 32, 48, 64] {
16055            let mk = |s: TrellisStrength| KeyframeParams {
16056                y_ac_qi: qi,
16057                loop_filter_level: 0,
16058                sharpness_level: 0,
16059                nbr_of_dct_partitions: 1,
16060                filter_type: false,
16061                trellis_strength: s,
16062            };
16063            let off = encode_keyframe(&frame, &mk(TrellisStrength::OFF)).expect("off");
16064            let def = encode_keyframe(&frame, &mk(TrellisStrength::DEFAULT)).expect("default");
16065            // A strength well above the default trades more aggressively.
16066            let hot = encode_keyframe(&frame, &mk(TrellisStrength::new(4.0))).expect("hot");
16067
16068            // OFF = plain rounding = the largest stream; the default trims
16069            // it; the hot setting trims at least as much as the default.
16070            assert!(
16071                def.len() <= off.len(),
16072                "qi={qi}: DEFAULT trellis ({} B) must not exceed OFF ({} B)",
16073                def.len(),
16074                off.len()
16075            );
16076            assert!(
16077                hot.len() <= def.len(),
16078                "qi={qi}: strength 4.0 ({} B) must not exceed DEFAULT ({} B)",
16079                hot.len(),
16080                def.len()
16081            );
16082
16083            // Every strength decodes cleanly through the crate's own decoder
16084            // (encoder↔decoder pixel lockstep holds at every setting).
16085            for bytes in [&off, &def, &hot] {
16086                let dec = crate::decode_vp8(bytes).expect("decode at this strength");
16087                assert_eq!(dec.y.len(), w as usize * h as usize);
16088            }
16089
16090            // The hot setting must actually move the wire at the mid/low
16091            // quantisers VP8 keyframes operate at (a knob that never changes
16092            // anything would be a silent no-op).
16093            if qi <= 48 {
16094                assert!(
16095                    hot.len() < off.len(),
16096                    "qi={qi}: strength 4.0 ({} B) should beat OFF ({} B)",
16097                    hot.len(),
16098                    off.len()
16099                );
16100            }
16101        }
16102
16103        // `new` clamps out-of-range / NaN inputs into the documented band.
16104        assert_eq!(TrellisStrength::new(-1.0).get(), 0.0);
16105        assert_eq!(TrellisStrength::new(1000.0).get(), TrellisStrength::MAX);
16106        assert_eq!(TrellisStrength::new(f64::NAN), TrellisStrength::DEFAULT);
16107    }
16108
16109    /// `quality_to_trellis_strength` pairs the quality dial with the §13
16110    /// trellis: visually-lossless requests stay at `DEFAULT`, lower quality
16111    /// ramps the strength up monotonically toward `4.0`, and `NaN` is the
16112    /// conservative default.
16113    #[test]
16114    fn quality_to_trellis_strength_ramps_monotonically() {
16115        // High quality holds the default (no PSNR sacrifice).
16116        assert_eq!(quality_to_trellis_strength(100.0), TrellisStrength::DEFAULT);
16117        assert_eq!(quality_to_trellis_strength(90.0), TrellisStrength::DEFAULT);
16118        // Above-100 / below-0 clamp like the qindex mapping.
16119        assert_eq!(quality_to_trellis_strength(150.0), TrellisStrength::DEFAULT);
16120        // Bottom of the range hits the strong operating point.
16121        assert!((quality_to_trellis_strength(0.0).get() - 4.0).abs() < 1e-6);
16122        // NaN is the conservative default.
16123        assert_eq!(
16124            quality_to_trellis_strength(f32::NAN),
16125            TrellisStrength::DEFAULT
16126        );
16127
16128        // Monotone in quality: lower quality ⇒ greater-or-equal strength.
16129        // Walk q from 100 down to 0; each step's strength must not drop.
16130        let mut prev = 0.0f64;
16131        for q in (0..=100).rev() {
16132            let s = quality_to_trellis_strength(q as f32).get();
16133            assert!(
16134                s >= prev - 1e-9,
16135                "strength must not fall as quality falls (q={q}: {s} < {prev})"
16136            );
16137            prev = s;
16138        }
16139    }
16140
16141    /// The §7.3 boolean encoder and the §7.3 boolean decoder in this
16142    /// crate are inverses on a randomised flag sequence at randomised
16143    /// probabilities.
16144    #[test]
16145    fn bool_encoder_decoder_round_trip_pseudo_random_sequence() {
16146        // Linear-feedback PRNG so the sequence is reproducible.
16147        let mut state: u32 = 0xCAFE_F00D;
16148        let mut next = || {
16149            state = state.wrapping_mul(1_103_515_245).wrapping_add(12345);
16150            state
16151        };
16152        let mut bools: Vec<(u8, bool)> = Vec::with_capacity(1024);
16153        for _ in 0..1024 {
16154            let p = ((next() >> 16) as u8).max(1);
16155            let v = (next() & 1) != 0;
16156            bools.push((p, v));
16157        }
16158
16159        let mut enc = BoolEncoder::new();
16160        for (p, v) in &bools {
16161            enc.write_bool(*p, *v);
16162        }
16163        let bytes = enc.finish();
16164        assert!(bytes.len() >= 4);
16165
16166        let mut dec = BoolDecoder::init(&bytes).expect("encoder always emits ≥ 2 bytes");
16167        for (p, v) in &bools {
16168            assert_eq!(dec.read_bool(*p).expect("partition underrun"), *v);
16169        }
16170    }
16171
16172    /// `write_literal` / `write_signed_literal` round-trip through
16173    /// `BoolDecoder::read_literal` / a manual sign-bit pair.
16174    #[test]
16175    fn write_literal_round_trips_through_read_literal() {
16176        let mut enc = BoolEncoder::new();
16177        // Unsigned MSB-first.
16178        enc.write_literal(0xA5, 8);
16179        // Six-bit value.
16180        enc.write_literal(42, 6);
16181        // Signed: -5 magnitude=5 over 4 bits, sign=1.
16182        enc.write_signed_literal(-5, 4);
16183        // Signed positive: +7 magnitude=7 over 4 bits, sign=0.
16184        enc.write_signed_literal(7, 4);
16185        let bytes = enc.finish();
16186        let mut dec = BoolDecoder::init(&bytes).unwrap();
16187        assert_eq!(dec.read_literal(8).unwrap(), 0xA5);
16188        assert_eq!(dec.read_literal(6).unwrap(), 42);
16189        // -5: read 4 bits magnitude, then sign.
16190        assert_eq!(dec.read_literal(4).unwrap(), 5);
16191        assert!(dec.read_bool(128).unwrap()); // sign=1 → negative
16192        assert_eq!(dec.read_literal(4).unwrap(), 7);
16193        assert!(!dec.read_bool(128).unwrap());
16194    }
16195
16196    /// §9.1 frame-tag writer round-trips through
16197    /// [`Vp8FrameHeader::parse`] on a key frame with a non-trivial
16198    /// dimension + non-trivial first-partition size.
16199    #[test]
16200    fn frame_tag_round_trips_through_parser_key_frame() {
16201        let mut buf: Vec<u8> = Vec::new();
16202        let bytes_written = write_frame_tag(
16203            &mut buf,
16204            true,     // key frame
16205            0,        // version
16206            true,     // show_frame
16207            0x1_2345, // first_partition_size
16208            640,
16209            480,
16210            ScaleCode::None,
16211            ScaleCode::None,
16212        )
16213        .unwrap();
16214        assert_eq!(bytes_written, 10);
16215        assert_eq!(buf.len(), 10);
16216        // Start code is at offset 3..6 — required by §9.1.
16217        assert_eq!(&buf[3..6], &KEY_FRAME_START_CODE);
16218        let hdr = Vp8FrameHeader::parse(&buf).unwrap();
16219        assert!(hdr.key_frame);
16220        assert_eq!(hdr.version, 0);
16221        assert!(hdr.show_frame);
16222        assert_eq!(hdr.first_partition_size, 0x1_2345);
16223        assert_eq!(hdr.width, Some(640));
16224        assert_eq!(hdr.height, Some(480));
16225    }
16226
16227    /// `patch_first_partition_size` preserves the surrounding bits
16228    /// (frame_type / version / show_frame).
16229    #[test]
16230    fn patch_first_partition_size_preserves_neighbouring_bits() {
16231        let mut buf: Vec<u8> = Vec::new();
16232        write_frame_tag(
16233            &mut buf,
16234            true,
16235            5,    // version=5
16236            true, // show=1
16237            0,    // start at zero
16238            16,
16239            16,
16240            ScaleCode::None,
16241            ScaleCode::None,
16242        )
16243        .unwrap();
16244        patch_first_partition_size(&mut buf[..3], 1234).unwrap();
16245        let hdr = Vp8FrameHeader::parse(&buf).unwrap();
16246        assert_eq!(hdr.version, 5);
16247        assert!(hdr.show_frame);
16248        assert!(hdr.key_frame);
16249        assert_eq!(hdr.first_partition_size, 1234);
16250    }
16251
16252    /// `set_show_frame_bit` flips exactly the §9.1 bit-4 and preserves
16253    /// every neighbouring tag field (frame_type / version /
16254    /// first_partition_size) plus every byte after the tag.
16255    #[test]
16256    fn set_show_frame_bit_flips_only_bit_4() {
16257        let mut buf: Vec<u8> = Vec::new();
16258        write_frame_tag(
16259            &mut buf,
16260            false, // inter frame
16261            3,     // version=3
16262            true,  // show=1
16263            0x5_4321,
16264            16,
16265            16,
16266            ScaleCode::None,
16267            ScaleCode::None,
16268        )
16269        .unwrap();
16270        buf.extend_from_slice(&[0xAA, 0x55, 0xF0]); // fake payload
16271        let visible = buf.clone();
16272
16273        set_show_frame_bit(&mut buf, false);
16274        let hdr = Vp8FrameHeader::parse(&buf).unwrap();
16275        assert!(!hdr.key_frame);
16276        assert_eq!(hdr.version, 3);
16277        assert!(!hdr.show_frame);
16278        assert_eq!(hdr.first_partition_size, 0x5_4321);
16279        // Only byte 0 differs, and only in bit 4.
16280        assert_eq!(buf[0] ^ visible[0], 0x10);
16281        assert_eq!(&buf[1..], &visible[1..]);
16282
16283        // Round-trip back to visible restores the original bytes.
16284        set_show_frame_bit(&mut buf, true);
16285        assert_eq!(buf, visible);
16286    }
16287
16288    /// Dimensions outside the 14-bit field are rejected.
16289    #[test]
16290    fn rejects_oversize_dimensions() {
16291        let mut buf = Vec::new();
16292        let err = write_frame_tag(
16293            &mut buf,
16294            true,
16295            0,
16296            true,
16297            0,
16298            0x4000, // > 0x3FFF
16299            16,
16300            ScaleCode::None,
16301            ScaleCode::None,
16302        )
16303        .unwrap_err();
16304        assert!(matches!(err, EncodeError::InvalidDimensions { .. }));
16305    }
16306
16307    /// Loop-filter / sharpness validation.
16308    #[test]
16309    fn rejects_out_of_range_loop_filter_inputs() {
16310        let mut enc = BoolEncoder::new();
16311        assert!(matches!(
16312            write_loop_filter(&mut enc, false, 64, 0, false),
16313            Err(EncodeError::LoopFilterLevelOutOfRange { value: 64 })
16314        ));
16315        let mut enc = BoolEncoder::new();
16316        assert!(matches!(
16317            write_loop_filter(&mut enc, false, 0, 8, false),
16318            Err(EncodeError::SharpnessLevelOutOfRange { value: 8 })
16319        ));
16320    }
16321
16322    #[test]
16323    fn rejects_illegal_partition_count() {
16324        let mut enc = BoolEncoder::new();
16325        assert!(matches!(
16326            write_token_partition_count(&mut enc, 3),
16327            Err(EncodeError::InvalidDctPartitionCount { value: 3 })
16328        ));
16329    }
16330
16331    #[test]
16332    fn rejects_oversize_quant_index() {
16333        let mut enc = BoolEncoder::new();
16334        assert!(matches!(
16335            write_quant_indices(&mut enc, 128, None, None, None, None, None),
16336            Err(EncodeError::QuantIndexOutOfRange { value: 128 })
16337        ));
16338    }
16339
16340    /// End-to-end: a silent 16×16 keyframe round-trips through the
16341    /// crate's own decoder.
16342    #[test]
16343    fn silent_keyframe_16x16_round_trips_through_own_decoder() {
16344        let bytes = encode_silent_keyframe(SilentKeyframeParams::new(16, 16))
16345            .expect("encoder should produce a valid frame");
16346        let decoded = decode_vp8(&bytes).expect("own decoder must accept emitted frame");
16347        assert_eq!(decoded.width, 16);
16348        assert_eq!(decoded.height, 16);
16349        assert_eq!(decoded.y.len(), 16 * 16);
16350        assert_eq!(decoded.u.len(), 8 * 8);
16351        assert_eq!(decoded.v.len(), 8 * 8);
16352    }
16353
16354    /// The §9.x writer subroutines compose into a parse-able coded
16355    /// header. We strip the frame tag + key-frame extension and ask
16356    /// [`Vp8CodedHeader::parse`] to walk our boolean-coded first
16357    /// partition. Confirms the §9.2 / §9.3 / §9.4 / §9.5 / §9.6 /
16358    /// §9.7 layout is byte-correct.
16359    #[test]
16360    fn silent_keyframe_first_partition_round_trips_through_coded_header_parser() {
16361        let bytes = encode_silent_keyframe(SilentKeyframeParams::new(64, 64)).unwrap();
16362        let hdr = Vp8FrameHeader::parse(&bytes).unwrap();
16363        let off = hdr.header_bytes_consumed;
16364        let sz = hdr.first_partition_size as usize;
16365        let partition = &bytes[off..off + sz];
16366        let coded = Vp8CodedHeader::parse(partition, true).unwrap();
16367        assert_eq!(coded.color_space, Some(false));
16368        assert_eq!(coded.clamping_type, Some(false));
16369        assert!(!coded.segmentation_enabled);
16370        assert!(!coded.filter_type);
16371        assert_eq!(coded.loop_filter_level, 0);
16372        assert_eq!(coded.sharpness_level, 0);
16373        assert!(!coded.mb_lf_adjustments.loop_filter_adj_enable);
16374        assert_eq!(coded.log2_nbr_of_dct_partitions, 0);
16375        assert_eq!(coded.nbr_of_dct_partitions, 1);
16376        assert_eq!(coded.quant_indices.y_ac_qi, 0);
16377        assert_eq!(coded.quant_indices.y_dc_delta, None);
16378        assert!(coded.refresh_entropy_probs);
16379        assert!(coded.mb_no_skip_coeff);
16380        assert_eq!(coded.prob_skip_false, Some(1));
16381    }
16382
16383    /// Round-trip across all four legal DCT partition counts so the
16384    /// §9.5 size-table writer is exercised. 64×64 → 4 MB rows, big
16385    /// enough to actually route through every partition.
16386    #[test]
16387    fn silent_keyframe_round_trips_at_all_partition_counts() {
16388        for &count in &[1u8, 2, 4, 8] {
16389            let mut params = SilentKeyframeParams::new(64, 64);
16390            params.nbr_of_dct_partitions = count;
16391            let bytes = encode_silent_keyframe(params)
16392                .unwrap_or_else(|e| panic!("encoder failed at count={count}: {e}"));
16393            let decoded = decode_vp8(&bytes)
16394                .unwrap_or_else(|e| panic!("decoder failed at count={count}: {e}"));
16395            assert_eq!(decoded.width, 64);
16396            assert_eq!(decoded.height, 64);
16397        }
16398    }
16399
16400    /// Various non-square dimensions round-trip through the decoder.
16401    /// Exercises the macroblock-loop count for `mb_rows != mb_cols`
16402    /// and the visible-crop logic (32×24 has only one MB row of
16403    /// trailing "excess" pixels).
16404    #[test]
16405    fn silent_keyframe_non_square_dimensions_round_trip() {
16406        let cases = [(16u32, 16u32), (32, 32), (48, 16), (16, 48), (32, 24)];
16407        for (w, h) in cases {
16408            let bytes = encode_silent_keyframe(SilentKeyframeParams::new(w, h))
16409                .unwrap_or_else(|e| panic!("encoder failed at {w}x{h}: {e}"));
16410            let decoded =
16411                decode_vp8(&bytes).unwrap_or_else(|e| panic!("decoder failed at {w}x{h}: {e}"));
16412            assert_eq!(decoded.width, w);
16413            assert_eq!(decoded.height, h);
16414        }
16415    }
16416
16417    /// The historical `make_silent_keyframe_encoder()` factory reaches
16418    /// the same byte sequence as the direct
16419    /// `encode_silent_keyframe(SilentKeyframeParams::new(...))` call.
16420    #[test]
16421    fn make_silent_keyframe_encoder_produces_same_bytes_as_top_level_function() {
16422        let enc = make_silent_keyframe_encoder();
16423        let from_factory = enc.encode_keyframe(&[], 32, 32).unwrap();
16424        let from_direct = encode_silent_keyframe(SilentKeyframeParams::new(32, 32)).unwrap();
16425        assert_eq!(from_factory, from_direct);
16426    }
16427
16428    /// Bit-budget guard: the silent-keyframe path emits the smallest
16429    /// possible 16×16 frame the §9.x layout admits — frame tag (10) +
16430    /// first partition (small, dominated by 1056 token-update "no"
16431    /// bits at high prob) + 1 DCT partition (4-byte flush). The exact
16432    /// number is implementation-determined; we just lock the order
16433    /// of magnitude to detect a future-round regression that
16434    /// accidentally bloats the partition.
16435    #[test]
16436    fn silent_keyframe_size_is_small() {
16437        let bytes = encode_silent_keyframe(SilentKeyframeParams::new(16, 16)).unwrap();
16438        // Empirically ~ 30-40 bytes for a 16×16 silent keyframe. A
16439        // generous upper bound that still catches accidental growth
16440        // (e.g. forgetting the §13.4 update-probs table and using a
16441        // flat 128 would push past 200 bytes).
16442        assert!(
16443            bytes.len() < 100,
16444            "silent 16×16 keyframe ballooned to {} bytes",
16445            bytes.len()
16446        );
16447        // Lower-bounded by the 10-byte key-frame header + 4-byte
16448        // first-partition flush + 4-byte DCT-partition flush.
16449        assert!(bytes.len() >= 10 + 4 + 4);
16450    }
16451
16452    // ───────── Phase 2 §13 token-encoder round-trip tests ─────────
16453
16454    use crate::dct_tokens::{DEFAULT_COEFF_PROBS, decode_block};
16455
16456    /// Encode one block with `encode_coeff_block`, then decode the
16457    /// emitted bytes with `decode_block`. Returns the recovered
16458    /// `[i16; 16]`. Used as the central round-trip helper for the
16459    /// Phase 2 token-encoder tests below.
16460    fn encode_then_decode_block(
16461        block_type: BlockType,
16462        coeffs: &[i16; 16],
16463        above_has_nonzero: bool,
16464        left_has_nonzero: bool,
16465    ) -> [i16; 16] {
16466        let mut enc = BoolEncoder::new();
16467        let nonzeros = encode_coeff_block(
16468            &mut enc,
16469            block_type,
16470            &DEFAULT_COEFF_PROBS,
16471            above_has_nonzero,
16472            left_has_nonzero,
16473            coeffs,
16474        )
16475        .expect("encode_coeff_block should accept in-range coefficients");
16476        // The non-zero count returned by the encoder must equal the
16477        // population-count of non-zero entries in the input (modulo
16478        // the first_coeff skip slot, which is unread on either side).
16479        let first = block_type.first_coeff();
16480        let expected_nz = coeffs
16481            .iter()
16482            .enumerate()
16483            .filter(|&(i, &v)| i >= first && v != 0)
16484            .count();
16485        assert_eq!(nonzeros, expected_nz, "non-zero count mismatch");
16486        let bytes = enc.finish();
16487
16488        let mut dec = BoolDecoder::init(&bytes).expect("encoder emits ≥ 2 bytes");
16489        let mut recovered = [0i16; 16];
16490        let nz = decode_block(
16491            &mut dec,
16492            block_type,
16493            &DEFAULT_COEFF_PROBS,
16494            above_has_nonzero,
16495            left_has_nonzero,
16496            &mut recovered,
16497        )
16498        .expect("decode_block should consume the encoded byte stream");
16499        assert_eq!(nz, expected_nz);
16500        recovered
16501    }
16502
16503    /// Token classifier — exercises the full §13.2 alphabet.
16504    #[test]
16505    fn classify_coeff_token_covers_full_alphabet() {
16506        assert_eq!(classify_coeff_token(0), DctToken::Dct0);
16507        assert_eq!(classify_coeff_token(1), DctToken::Dct1);
16508        assert_eq!(classify_coeff_token(2), DctToken::Dct2);
16509        assert_eq!(classify_coeff_token(3), DctToken::Dct3);
16510        assert_eq!(classify_coeff_token(4), DctToken::Dct4);
16511        // Cat1: 5..=6
16512        assert_eq!(classify_coeff_token(5), DctToken::Cat1);
16513        assert_eq!(classify_coeff_token(6), DctToken::Cat1);
16514        // Cat2: 7..=10
16515        assert_eq!(classify_coeff_token(7), DctToken::Cat2);
16516        assert_eq!(classify_coeff_token(10), DctToken::Cat2);
16517        // Cat3: 11..=18
16518        assert_eq!(classify_coeff_token(11), DctToken::Cat3);
16519        assert_eq!(classify_coeff_token(18), DctToken::Cat3);
16520        // Cat4: 19..=34
16521        assert_eq!(classify_coeff_token(19), DctToken::Cat4);
16522        assert_eq!(classify_coeff_token(34), DctToken::Cat4);
16523        // Cat5: 35..=66
16524        assert_eq!(classify_coeff_token(35), DctToken::Cat5);
16525        assert_eq!(classify_coeff_token(66), DctToken::Cat5);
16526        // Cat6: 67..=2114
16527        assert_eq!(classify_coeff_token(67), DctToken::Cat6);
16528        assert_eq!(classify_coeff_token(2114), DctToken::Cat6);
16529    }
16530
16531    /// All-zero block — every plane / first_coeff combination should
16532    /// round-trip a 16-entry all-zero coefficient vector exactly. The
16533    /// encoder emits a single immediate EOB token at position
16534    /// `first_coeff`; the decoder leaves the rest at zero.
16535    #[test]
16536    fn encode_coeff_block_all_zero_round_trips() {
16537        let coeffs = [0i16; 16];
16538        for &bt in &[
16539            BlockType::YAfterY2,
16540            BlockType::Y2,
16541            BlockType::UV,
16542            BlockType::YNoY2,
16543        ] {
16544            let recovered = encode_then_decode_block(bt, &coeffs, false, false);
16545            assert_eq!(recovered, coeffs, "all-zero round-trip failed for {bt:?}");
16546        }
16547    }
16548
16549    /// A single non-zero coefficient at every position round-trips
16550    /// for every plane type. Exercises the `last_non_zero` EOB
16551    /// placement, the §13.2 leaf walk for each of the small literal
16552    /// tokens, and the universal sign bit.
16553    #[test]
16554    fn encode_coeff_block_single_nonzero_at_each_position() {
16555        for &bt in &[BlockType::Y2, BlockType::UV, BlockType::YNoY2] {
16556            let first = bt.first_coeff();
16557            for pos in first..16 {
16558                for &value in &[1i16, -1, 2, -3, 4, -4] {
16559                    let mut coeffs = [0i16; 16];
16560                    coeffs[pos] = value;
16561                    let recovered = encode_then_decode_block(bt, &coeffs, false, false);
16562                    assert_eq!(
16563                        recovered, coeffs,
16564                        "single-nonzero round-trip failed at {bt:?} pos={pos} value={value}"
16565                    );
16566                }
16567            }
16568        }
16569        // YAfterY2 separately, because coeffs[0] is ignored (DC lives
16570        // in the Y2 block) — only positions 1..16 are meaningful.
16571        let bt = BlockType::YAfterY2;
16572        for pos in 1..16 {
16573            let mut coeffs = [0i16; 16];
16574            coeffs[pos] = 3;
16575            let recovered = encode_then_decode_block(bt, &coeffs, false, false);
16576            assert_eq!(
16577                recovered, coeffs,
16578                "single-nonzero round-trip failed at YAfterY2 pos={pos}"
16579            );
16580        }
16581    }
16582
16583    /// Each `Cat1..Cat6` token exercises a different extra-bits
16584    /// probability list (§13.2 `Pcat1..Pcat6`). This test pins one
16585    /// value inside every cat range — verified by encode + decode at
16586    /// the coefficient layer.
16587    #[test]
16588    fn encode_coeff_block_each_cat_range_round_trips() {
16589        // (value, category index) pairs spanning every Pcat list.
16590        let cases: &[i16] = &[
16591            5, 6, // Cat1
16592            7, 8, 10, // Cat2
16593            11, 15, 18, // Cat3
16594            19, 27, 34, // Cat4
16595            35, 50, 66, // Cat5
16596            67, 200, 1000, 2114, // Cat6
16597        ];
16598        for &v in cases {
16599            for &sign in &[1i16, -1] {
16600                let mut coeffs = [0i16; 16];
16601                // Place at position 3 — well inside all planes' visit
16602                // range and inside band-1 to avoid the all-128
16603                // pathological first-plane band-0 row.
16604                coeffs[3] = v * sign;
16605                let recovered = encode_then_decode_block(BlockType::UV, &coeffs, true, false);
16606                assert_eq!(
16607                    recovered, coeffs,
16608                    "cat-range round-trip failed for value {v}*{sign}"
16609                );
16610            }
16611        }
16612    }
16613
16614    /// A fully-populated 16-entry block (every position non-zero) —
16615    /// exercises the §13.2 "implicit EOB after the last coefficient"
16616    /// rule, where the encoder omits the explicit `Eob` token because
16617    /// there is nothing past position 15. Decoder must still recover
16618    /// the full vector.
16619    #[test]
16620    fn encode_coeff_block_fully_populated_block_round_trips_with_implicit_eob() {
16621        let mut coeffs = [0i16; 16];
16622        // Mix of magnitudes covering every token bucket; sign
16623        // alternates so the universal sign bit gets exercised.
16624        let values = [1, -2, 3, -4, 5, -7, 11, -19, 35, -67, 1, -1, 2, -3, 4, -5];
16625        coeffs.copy_from_slice(&values);
16626        // YNoY2 reads all 16 positions; perfect for the "no implicit
16627        // EOB slot wasted" path.
16628        let recovered = encode_then_decode_block(BlockType::YNoY2, &coeffs, false, false);
16629        assert_eq!(recovered, coeffs);
16630    }
16631
16632    /// Sparse pattern with interior zeros — exercises the §13.2
16633    /// "previous coefficient was DCT_0" branch that bypasses the EOB
16634    /// tree edge. The pattern `[3, 0, 0, 5, 0, 0, 0, 2, 0, …]`
16635    /// transitions through `Dct0` multiple times so the encoder's
16636    /// `prev_was_zero` tracking is exercised.
16637    #[test]
16638    fn encode_coeff_block_interior_zeros_round_trip() {
16639        let mut coeffs = [0i16; 16];
16640        coeffs[0] = 3;
16641        coeffs[3] = 5;
16642        coeffs[7] = 2;
16643        coeffs[12] = -8;
16644        let recovered = encode_then_decode_block(BlockType::Y2, &coeffs, false, false);
16645        assert_eq!(recovered, coeffs);
16646    }
16647
16648    /// Neighbour-predictor combinations seed `ctx3` for the first
16649    /// coefficient — exercising the §13.3 page 65 rule. All four
16650    /// (above × left) combinations must produce a self-consistent
16651    /// byte stream the matching `decode_block` call recovers.
16652    #[test]
16653    fn encode_coeff_block_neighbour_predictor_combinations() {
16654        let coeffs = {
16655            let mut c = [0i16; 16];
16656            c[0] = 4;
16657            c[1] = -1;
16658            c[5] = 2;
16659            c
16660        };
16661        for above in &[false, true] {
16662            for left in &[false, true] {
16663                let recovered = encode_then_decode_block(BlockType::YNoY2, &coeffs, *above, *left);
16664                assert_eq!(
16665                    recovered, coeffs,
16666                    "neighbour predictor combination ({above}, {left}) failed"
16667                );
16668            }
16669        }
16670    }
16671
16672    /// Out-of-range coefficient is rejected. The §13.2 alphabet caps
16673    /// at 67 + 2047 = 2114; anything larger surfaces as
16674    /// `CoefficientOutOfRange`.
16675    #[test]
16676    fn encode_coeff_block_rejects_out_of_range_coefficient() {
16677        let mut coeffs = [0i16; 16];
16678        coeffs[2] = 2115;
16679        let mut enc = BoolEncoder::new();
16680        let err = encode_coeff_block(
16681            &mut enc,
16682            BlockType::YNoY2,
16683            &DEFAULT_COEFF_PROBS,
16684            false,
16685            false,
16686            &coeffs,
16687        )
16688        .unwrap_err();
16689        assert!(matches!(
16690            err,
16691            TokenEncodeError::CoefficientOutOfRange {
16692                index: 2,
16693                value: 2115
16694            }
16695        ));
16696    }
16697
16698    /// `TokenEncoder` wrapper produces the same byte stream as the
16699    /// free-function path. Locks the wrapper's stateful API to the
16700    /// stateless one — any future refactor that splits one and not
16701    /// the other will trip this immediately.
16702    #[test]
16703    fn token_encoder_wrapper_matches_free_function_bytes() {
16704        let mut coeffs = [0i16; 16];
16705        coeffs[0] = 2;
16706        coeffs[4] = -7;
16707        coeffs[9] = 15;
16708
16709        let mut free_enc = BoolEncoder::new();
16710        encode_coeff_block(
16711            &mut free_enc,
16712            BlockType::YNoY2,
16713            &DEFAULT_COEFF_PROBS,
16714            false,
16715            false,
16716            &coeffs,
16717        )
16718        .unwrap();
16719        let free_bytes = free_enc.finish();
16720
16721        let mut wrapper = TokenEncoder::new(DEFAULT_COEFF_PROBS);
16722        wrapper
16723            .encode_block(BlockType::YNoY2, false, false, &coeffs)
16724            .unwrap();
16725        let wrapper_bytes = wrapper.finish();
16726
16727        assert_eq!(free_bytes, wrapper_bytes);
16728    }
16729
16730    /// Pseudo-random sweep — encode 64 random blocks at randomised
16731    /// quant magnitudes, decode them back, assert byte-identical at
16732    /// the coefficient layer. Catches an algorithmic regression that
16733    /// individual-case tests above might miss.
16734    #[test]
16735    fn encode_coeff_block_pseudo_random_sweep_round_trips() {
16736        let mut state: u32 = 0xDEAD_BEEF;
16737        let mut next = || {
16738            state = state.wrapping_mul(1_103_515_245).wrapping_add(12345);
16739            state
16740        };
16741
16742        for trial in 0..64 {
16743            let bt = match trial % 4 {
16744                0 => BlockType::YAfterY2,
16745                1 => BlockType::Y2,
16746                2 => BlockType::UV,
16747                _ => BlockType::YNoY2,
16748            };
16749            let first = bt.first_coeff();
16750            let mut coeffs = [0i16; 16];
16751            // Sparse fill — at most ~half the positions populated, so
16752            // both the "implicit EOB at 16" and "explicit EOB partway
16753            // through" branches get exercised.
16754            for (i, c) in coeffs.iter_mut().enumerate().skip(first) {
16755                let r = next();
16756                // Roughly 1 in 4 positions populated; fewer at high
16757                // index (so EOB usually triggers before the end).
16758                if (r & 0x3) != 0 || i > 10 {
16759                    continue;
16760                }
16761                // Magnitude up to 100 — exercises Dct1..Dct4 + Cat1..Cat5.
16762                let mag = ((r >> 8) % 100) as i16;
16763                let sign = if (r >> 16) & 1 == 0 { 1 } else { -1 };
16764                *c = mag * sign;
16765            }
16766            let above = (next() & 1) != 0;
16767            let left = (next() & 1) != 0;
16768            let recovered = encode_then_decode_block(bt, &coeffs, above, left);
16769            assert_eq!(
16770                recovered, coeffs,
16771                "pseudo-random round-trip failed at trial {trial}, bt={bt:?}, above={above}, left={left}"
16772            );
16773        }
16774    }
16775
16776    // ───────── Phase 2 per-MB block-set encoder roundtrip tests ─────────
16777
16778    use crate::dct_tokens::decode_mb_coeffs;
16779    use crate::dequant::MbDequantFactors;
16780    use crate::macroblock::{IntraBmode, IntraUvMode, IntraYMode};
16781    use crate::reconstruct::{MbNeighbors, decode_keyframe_mb_bpred, decode_keyframe_mb_non_bpred};
16782
16783    /// Encode a flat-color MB through `encode_mb_block_set`, decode the
16784    /// bytes back through the mode-aware helper (off-frame neighbours may
16785    /// favour B_PRED), dequantize, and run the §14.2 reconstruction —
16786    /// the recovered luma / chroma planes must be within ≤ 1 LSB of the
16787    /// input.
16788    #[test]
16789    fn mb_block_set_roundtrip_flat_color_recovers_within_one_lsb() {
16790        // Pick a uniform pixel value off 128 so the residual is
16791        // non-zero and the §14 chain actually exercises the DC path
16792        // (rather than every block being all-zero, which is the
16793        // trivial success case).
16794        for &pixel in &[100u8, 110, 128, 140, 160, 200] {
16795            let pixels = MbPixels {
16796                y: [pixel; 256],
16797                u: [pixel; 64],
16798                v: [pixel; 64],
16799            };
16800
16801            // yac_qi = 0 is the lossless flat-block case
16802            // (`DC_QLOOKUP[0] = AC_QLOOKUP[0] = 4`). Decode through the
16803            // mode-aware helper: with off-frame neighbours the picker may
16804            // legitimately choose B_PRED (the evolving sub-block
16805            // neighbours converge on the flat value better than the
16806            // off-frame whole-block fills), so the decode must follow the
16807            // picked mode's has_y2 / reconstruction path. The helper also
16808            // asserts the §13.3 byte-layer roundtrip (raw == coeffs).
16809            let (_y_mode, _uv, _sub, y_plane, u_plane, v_plane) =
16810                encode_decode_bpred_aware(&pixels, &MbNeighbors::default(), 0);
16811
16812            // Verify every reconstructed pixel is within ≤ 1 LSB of the
16813            // input across all three planes. At yac_qi = 0 the chain is
16814            // bit-exact for a flat block (per the existing per-block
16815            // roundtrip test); the bound leaves room for §14.5
16816            // clamp / rounding on extreme inputs.
16817            for (i, &recon) in y_plane.iter().enumerate() {
16818                assert!(
16819                    (recon as i32 - pixel as i32).abs() <= 1,
16820                    "pixel {pixel}: y recon[{i}] = {recon} differs by > 1 LSB"
16821                );
16822            }
16823            for (i, &recon) in u_plane.iter().enumerate() {
16824                assert!(
16825                    (recon as i32 - pixel as i32).abs() <= 1,
16826                    "pixel {pixel}: u recon[{i}] = {recon} differs by > 1 LSB"
16827                );
16828            }
16829            for (i, &recon) in v_plane.iter().enumerate() {
16830                assert!(
16831                    (recon as i32 - pixel as i32).abs() <= 1,
16832                    "pixel {pixel}: v recon[{i}] = {recon} differs by > 1 LSB"
16833                );
16834            }
16835        }
16836    }
16837
16838    /// A constant 128-pixel macroblock has zero residual — every block
16839    /// after FDCT / FWHT is all-zero, which means every encoded block
16840    /// is a single immediate EOB token and the predictor contexts
16841    /// remain at their default (no non-zero coefficients anywhere).
16842    #[test]
16843    fn mb_block_set_constant_128_emits_all_eob_blocks() {
16844        let pixels = MbPixels {
16845            y: [128u8; 256],
16846            u: [128u8; 64],
16847            v: [128u8; 64],
16848        };
16849        let encoded =
16850            encode_mb_block_set(&pixels, 0, &DEFAULT_COEFF_PROBS).expect("encode_mb_block_set");
16851        assert_eq!(
16852            encoded.nonzero_block_count, 0,
16853            "constant 128 MB must produce zero non-zero blocks"
16854        );
16855        // A flat 128 block is the one value where DC_PRED's top-left 128
16856        // fill matches the source exactly (SAD 0) while V/H/TM carry the
16857        // 127/129 off-frame defaults — so the picker must choose DC.
16858        assert_eq!(encoded.y_mode, IntraYMode::Dc);
16859        assert_eq!(encoded.uv_mode, IntraUvMode::Dc);
16860        // Round-trip through the decoder to confirm the bytes are
16861        // structurally valid (the bool encoder always writes ≥ 4 bytes
16862        // even on an empty stream — the §7.3 flush tail).
16863        let mut dec = BoolDecoder::init(&encoded.bytes).expect("encoder emits ≥ 2 bytes");
16864        let mut above = MbEntropyCtx::default();
16865        let mut left = MbEntropyCtx::default();
16866        let recovered = decode_mb_coeffs(
16867            &mut dec,
16868            true,
16869            false,
16870            &DEFAULT_COEFF_PROBS,
16871            &mut above,
16872            &mut left,
16873        )
16874        .expect("decode_mb_coeffs");
16875        assert_eq!(recovered.y2, [0i16; 16]);
16876        assert!(recovered.y.iter().all(|b| *b == [0i16; 16]));
16877        assert!(recovered.u.iter().all(|b| *b == [0i16; 16]));
16878        assert!(recovered.v.iter().all(|b| *b == [0i16; 16]));
16879    }
16880
16881    /// A non-zero MB at a non-trivial quantizer must still recover
16882    /// within ≤ 1 LSB on a flat colour input — the round-131 §14
16883    /// per-block roundtrip proved the chain holds at `yac_qi = 32`,
16884    /// and the per-MB walk doesn't perturb that bound for a flat MB.
16885    #[test]
16886    fn mb_block_set_roundtrip_flat_color_at_q16_holds_within_2_lsb() {
16887        let pixels = MbPixels {
16888            y: [160u8; 256],
16889            u: [120u8; 64],
16890            v: [140u8; 64],
16891        };
16892        // Mode-aware decode (off-frame neighbours may favour B_PRED); the
16893        // helper asserts the byte-layer roundtrip internally.
16894        let (_y_mode, _uv, _sub, y_plane, _u_plane, _v_plane) =
16895            encode_decode_bpred_aware(&pixels, &MbNeighbors::default(), 16);
16896
16897        // At yac_qi = 16 the §14 chain holds to ≤ 2 LSB on a flat
16898        // block (the WHT + DCT round-trip introduces at most a small
16899        // round-off from the `*155/100` Y2 AC scaling, but flat blocks
16900        // have zero AC so this collapses to the DC-only path which is
16901        // bit-exact up to the IWHT's `(x+3)>>3` rounding — i.e. ≤ 1
16902        // LSB; the ≤ 2 bound is defensive).
16903        for (i, &recon) in y_plane.iter().enumerate() {
16904            assert!(
16905                (recon as i32 - 160i32).abs() <= 2,
16906                "yac_qi=16 flat 160: recon[{i}] = {recon} differs by > 2 LSB"
16907            );
16908        }
16909    }
16910
16911    // ───────── Phase 3 whole-block intra mode-pick tests ─────────
16912
16913    /// Mean-squared-error → PSNR in dB between a source plane and its
16914    /// reconstruction. Returns `f64::INFINITY` for a bit-exact match.
16915    fn psnr(src: &[u8], recon: &[u8]) -> f64 {
16916        assert_eq!(src.len(), recon.len());
16917        let mse: f64 = src
16918            .iter()
16919            .zip(recon.iter())
16920            .map(|(&s, &r)| {
16921                let d = s as f64 - r as f64;
16922                d * d
16923            })
16924            .sum::<f64>()
16925            / src.len() as f64;
16926        if mse == 0.0 {
16927            f64::INFINITY
16928        } else {
16929            10.0 * (255.0f64 * 255.0 / mse).log10()
16930        }
16931    }
16932
16933    /// Encode `pixels` against `neighbors`, decode the bytes back, run
16934    /// the §14.2 reconstruction orchestrator against the **same**
16935    /// neighbours + the picked modes, and return
16936    /// `(y_mode, uv_mode, reconstructed planes)`.
16937    fn encode_decode_with_neighbors(
16938        pixels: &MbPixels,
16939        neighbors: &MbNeighbors,
16940        yac_qi: u8,
16941    ) -> (IntraYMode, IntraUvMode, Vec<u8>, Vec<u8>, Vec<u8>) {
16942        let encoded =
16943            encode_mb_block_set_with_neighbors(pixels, neighbors, yac_qi, &DEFAULT_COEFF_PROBS)
16944                .expect("encode_mb_block_set_with_neighbors");
16945
16946        let mut dec = BoolDecoder::init(&encoded.bytes).expect("encoder emits ≥ 2 bytes");
16947        let mut above = MbEntropyCtx::default();
16948        let mut left = MbEntropyCtx::default();
16949        let mut raw = decode_mb_coeffs(
16950            &mut dec,
16951            true,
16952            false,
16953            &DEFAULT_COEFF_PROBS,
16954            &mut above,
16955            &mut left,
16956        )
16957        .expect("decode_mb_coeffs");
16958        assert_eq!(raw, encoded.coeffs, "byte-layer roundtrip mismatch");
16959
16960        let factors = MbDequantFactors::from_base_and_deltas(yac_qi as i32, 0, 0, 0, 0, 0);
16961        factors.dequantize(&mut raw);
16962
16963        let recon = decode_keyframe_mb_non_bpred(
16964            encoded.y_mode,
16965            encoded.uv_mode,
16966            false,
16967            neighbors,
16968            &raw.y2,
16969            &raw.y,
16970            &raw.u,
16971            &raw.v,
16972        )
16973        .expect("decode_keyframe_mb_non_bpred");
16974
16975        (
16976            encoded.y_mode,
16977            encoded.uv_mode,
16978            recon.y.to_vec(),
16979            recon.u.to_vec(),
16980            recon.v.to_vec(),
16981        )
16982    }
16983
16984    /// Encode `pixels` against `neighbors`, decode the bytes back, and
16985    /// run the reconstruction orchestrator that matches the picked luma
16986    /// mode — `decode_keyframe_mb_bpred` (no Y2) when `y_mode == B`, or
16987    /// `decode_keyframe_mb_non_bpred` (with Y2) otherwise. Returns the
16988    /// picked modes (luma, chroma, optional 16 sub-modes) plus the
16989    /// reconstructed planes. This is the §11.3 / §12.3 superset of
16990    /// [`encode_decode_with_neighbors`] used by the B_PRED tests.
16991    #[allow(clippy::type_complexity)]
16992    fn encode_decode_bpred_aware(
16993        pixels: &MbPixels,
16994        neighbors: &MbNeighbors,
16995        yac_qi: u8,
16996    ) -> (
16997        IntraYMode,
16998        IntraUvMode,
16999        Option<[IntraBmode; 16]>,
17000        Vec<u8>,
17001        Vec<u8>,
17002        Vec<u8>,
17003    ) {
17004        let encoded =
17005            encode_mb_block_set_with_neighbors(pixels, neighbors, yac_qi, &DEFAULT_COEFF_PROBS)
17006                .expect("encode_mb_block_set_with_neighbors");
17007
17008        let is_bpred = encoded.y_mode == IntraYMode::B;
17009        // A B_PRED macroblock has no Y2 block, so `decode_mb_coeffs`
17010        // must be told `has_y2 = false` to route the Y plane through the
17011        // YNoY2 token plane and skip block 24.
17012        let has_y2 = !is_bpred;
17013
17014        let mut dec = BoolDecoder::init(&encoded.bytes).expect("encoder emits ≥ 2 bytes");
17015        let mut above = MbEntropyCtx::default();
17016        let mut left = MbEntropyCtx::default();
17017        let mut raw = decode_mb_coeffs(
17018            &mut dec,
17019            has_y2,
17020            false,
17021            &DEFAULT_COEFF_PROBS,
17022            &mut above,
17023            &mut left,
17024        )
17025        .expect("decode_mb_coeffs");
17026        assert_eq!(raw, encoded.coeffs, "byte-layer roundtrip mismatch");
17027
17028        let factors = MbDequantFactors::from_base_and_deltas(yac_qi as i32, 0, 0, 0, 0, 0);
17029        factors.dequantize(&mut raw);
17030
17031        let recon = if is_bpred {
17032            decode_keyframe_mb_bpred(
17033                encoded.b_subblock_modes.as_ref(),
17034                encoded.uv_mode,
17035                false,
17036                neighbors,
17037                &raw.y,
17038                &raw.u,
17039                &raw.v,
17040            )
17041            .expect("decode_keyframe_mb_bpred")
17042        } else {
17043            decode_keyframe_mb_non_bpred(
17044                encoded.y_mode,
17045                encoded.uv_mode,
17046                false,
17047                neighbors,
17048                &raw.y2,
17049                &raw.y,
17050                &raw.u,
17051                &raw.v,
17052            )
17053            .expect("decode_keyframe_mb_non_bpred")
17054        };
17055
17056        (
17057            encoded.y_mode,
17058            encoded.uv_mode,
17059            encoded.b_subblock_modes,
17060            recon.y.to_vec(),
17061            recon.u.to_vec(),
17062            recon.v.to_vec(),
17063        )
17064    }
17065
17066    // ───────── §11.3 / §12.3 B_PRED luma mode-pick tests ─────────
17067
17068    /// A flat MB (every luma pixel equal) sitting in a flat region —
17069    /// i.e. with neighbour strips equal to the same constant — is
17070    /// reproduced **exactly** (SSD 0) by the whole-block V / H / DC
17071    /// modes. The B_PRED pass can at best tie that SSD 0 distortion but
17072    /// costs more rate (the §11.2 B_PRED mode flag plus sixteen sub-block
17073    /// mode signals), so the RD decision (B_PRED wins only on a strictly
17074    /// lower `J = SSD + lambda * R`) keeps the macroblock on a whole-block
17075    /// luma mode (`y_mode != B`) and carries no sub-modes. (With
17076    /// *off-frame* neighbours a flat MB legitimately favours B_PRED,
17077    /// because the off-frame whole-block fills disagree with the interior
17078    /// while the evolving sub-block neighbours converge on the true
17079    /// constant — so the realistic flat-region case uses matching
17080    /// neighbours, which is how flat areas appear mid-frame.)
17081    #[test]
17082    fn flat_mb_keeps_whole_block_luma_mode() {
17083        let pixels = MbPixels {
17084            y: [120u8; 256],
17085            u: [120u8; 64],
17086            v: [120u8; 64],
17087        };
17088        // Matching flat reconstructed-neighbour strips (a flat region).
17089        let neighbors = MbNeighbors {
17090            y_above: Some([120u8; 16]),
17091            y_left: Some([120u8; 16]),
17092            y_topleft: Some(120),
17093            y_above_right: Some([120u8; 4]),
17094            u_above: Some([120u8; 8]),
17095            u_left: Some([120u8; 8]),
17096            u_topleft: Some(120),
17097            v_above: Some([120u8; 8]),
17098            v_left: Some([120u8; 8]),
17099            v_topleft: Some(120),
17100        };
17101
17102        let (y_mode, _uv, sub, ry, _ru, _rv) = encode_decode_bpred_aware(&pixels, &neighbors, 8);
17103
17104        assert_ne!(
17105            y_mode,
17106            IntraYMode::B,
17107            "a flat MB must NOT flip to B_PRED — a whole-block mode reproduces it exactly"
17108        );
17109        assert!(
17110            sub.is_none(),
17111            "whole-block luma decision must carry no sub-block modes"
17112        );
17113        // Sanity: it still reconstructs the flat value at high PSNR.
17114        let p_y = psnr(&pixels.y, &ry);
17115        assert!(p_y >= 30.0, "flat luma PSNR {p_y:.2} dB < 30 dB");
17116    }
17117
17118    /// A macroblock built from per-4×4-sub-block diagonal structure —
17119    /// each 4×4 sub-block a 45° gradient that no single whole-block
17120    /// 16×16 mode can follow — must flip the top-level luma decision to
17121    /// `B_PRED`. The picked sub-modes drive the decoder's per-sub-block
17122    /// walk and the reconstruction must clear ≥ 30 dB. This is the
17123    /// black-box validation for the round's B_PRED pass.
17124    #[test]
17125    fn diagonal_subblock_mb_picks_bpred_and_decodes_above_30db() {
17126        // Build a 16×16 luma plane whose every 4×4 sub-block carries a
17127        // strong diagonal gradient: pixel value depends on (row + col)
17128        // within the sub-block, repeating per sub-block so the global
17129        // plane has 16 independent diagonal tiles. A whole-block V / H /
17130        // DC / TM prediction smears across the tile boundaries; the
17131        // per-sub-block B_PRED diagonal modes (B_LD / B_RD / …) fit each
17132        // tile far better, so total B_PRED SAD beats every whole-block
17133        // mode.
17134        let mut y = [0u8; 256];
17135        for r in 0..16usize {
17136            for c in 0..16usize {
17137                // Local coordinates inside the 4×4 sub-block.
17138                let lr = r % 4;
17139                let lc = c % 4;
17140                // Diagonal ramp 30..=240 across the sub-block's
17141                // anti-diagonal; alternate the slope direction per
17142                // sub-block so neighbouring tiles differ.
17143                let sb = (r / 4) * 4 + (c / 4);
17144                let d = if sb % 2 == 0 { lr + lc } else { 6 - (lr + lc) };
17145                y[r * 16 + c] = (30 + d * 35) as u8;
17146            }
17147        }
17148        // Flat chroma — chroma always uses a whole-block mode regardless.
17149        let pixels = MbPixels {
17150            y,
17151            u: [128u8; 64],
17152            v: [128u8; 64],
17153        };
17154        let neighbors = MbNeighbors::default();
17155
17156        let (y_mode, _uv, sub, ry, _ru, _rv) = encode_decode_bpred_aware(&pixels, &neighbors, 4);
17157
17158        assert_eq!(
17159            y_mode,
17160            IntraYMode::B,
17161            "a per-4×4-sub-block-structured MB must pick B_PRED"
17162        );
17163        let sub = sub.expect("B_PRED MB must carry sixteen sub-block modes");
17164        assert_eq!(sub.len(), 16);
17165
17166        let p_y = psnr(&pixels.y, &ry);
17167        assert!(
17168            p_y >= 30.0,
17169            "B_PRED luma reconstruction PSNR {p_y:.2} dB < 30 dB"
17170        );
17171    }
17172
17173    /// The encoder's in-place neighbour evolution must match the
17174    /// decoder's: the bytes a B_PRED MB emits, fed back through
17175    /// `decode_keyframe_mb_bpred` with the **same** sub-modes and
17176    /// neighbours, must reconstruct the exact pixels the encoder's
17177    /// internal working buffer held. We check this indirectly via the
17178    /// byte-layer roundtrip assertion in the helper (raw == coeffs) plus
17179    /// a tighter PSNR floor at a low quantiser on the same diagonal MB.
17180    ///
17181    /// The MB is a per-sub-block diagonal pattern that no single
17182    /// whole-block mode can predict; at a *low but non-zero* quantiser the
17183    /// rate-distortion picker flips it to B_PRED (the per-sub-block
17184    /// prediction shaves enough distortion to repay the extra mode bits).
17185    /// At `yac_qi = 0` the chain is near-lossless, so the distortion of
17186    /// every candidate collapses toward zero and the picker prefers the
17187    /// cheaper-rate whole-block path — which is why this test exercises
17188    /// the realistic low-q (`yac_qi = 8`) regime rather than `q = 0`.
17189    #[test]
17190    fn bpred_neighbour_evolution_roundtrips_at_low_q() {
17191        let mut y = [0u8; 256];
17192        for r in 0..16usize {
17193            for c in 0..16usize {
17194                let lr = r % 4;
17195                let lc = c % 4;
17196                let sb = (r / 4) * 4 + (c / 4);
17197                let d = if sb % 2 == 0 { lr + lc } else { 6 - (lr + lc) };
17198                y[r * 16 + c] = (30 + d * 35) as u8;
17199            }
17200        }
17201        let pixels = MbPixels {
17202            y,
17203            u: [128u8; 64],
17204            v: [128u8; 64],
17205        };
17206        let neighbors = MbNeighbors::default();
17207
17208        // At yac_qi = 8 the §14 chain is near-lossless and the RD picker
17209        // selects B_PRED; the reconstruction should clear a high PSNR
17210        // floor (the helper also asserts the byte-layer roundtrip).
17211        let (y_mode, _uv, sub, ry, _ru, _rv) = encode_decode_bpred_aware(&pixels, &neighbors, 8);
17212        assert_eq!(y_mode, IntraYMode::B);
17213        assert!(sub.is_some());
17214        let p_y = psnr(&pixels.y, &ry);
17215        assert!(
17216            p_y >= 40.0,
17217            "B_PRED luma PSNR at q8 {p_y:.2} dB < 40 dB — neighbour evolution likely diverged"
17218        );
17219    }
17220
17221    /// A macroblock whose pixels are constant down each column but vary
17222    /// across columns is reproduced exactly by V_PRED from the above
17223    /// row. With a genuine reconstructed-neighbour `above` strip that
17224    /// equals the column pattern, the SAD picker must choose `V` for
17225    /// luma and the residual must reconstruct at high PSNR.
17226    #[test]
17227    fn mode_pick_chooses_v_pred_for_column_constant_mb() {
17228        // Column c value: a ramp 40..=190 across the 16 columns. Every
17229        // row of the MB is identical to this row, so the bottom row of
17230        // the (notional) above neighbour equals it too.
17231        let mut y_row = [0u8; 16];
17232        for (c, slot) in y_row.iter_mut().enumerate() {
17233            *slot = (40 + c * 10) as u8;
17234        }
17235        let mut u_row = [0u8; 8];
17236        let mut v_row = [0u8; 8];
17237        for c in 0..8 {
17238            u_row[c] = (50 + c * 12) as u8;
17239            v_row[c] = (200 - c * 12) as u8;
17240        }
17241
17242        let mut y = [0u8; 256];
17243        for r in 0..16 {
17244            y[r * 16..r * 16 + 16].copy_from_slice(&y_row);
17245        }
17246        let mut u = [0u8; 64];
17247        let mut v = [0u8; 64];
17248        for r in 0..8 {
17249            u[r * 8..r * 8 + 8].copy_from_slice(&u_row);
17250            v[r * 8..r * 8 + 8].copy_from_slice(&v_row);
17251        }
17252        let pixels = MbPixels { y, u, v };
17253
17254        let neighbors = MbNeighbors {
17255            y_above: Some(y_row),
17256            u_above: Some(u_row),
17257            v_above: Some(v_row),
17258            ..MbNeighbors::default()
17259        };
17260
17261        let (y_mode, uv_mode, ry, ru, rv) = encode_decode_with_neighbors(&pixels, &neighbors, 8);
17262
17263        assert_eq!(
17264            y_mode,
17265            IntraYMode::V,
17266            "column-constant MB must pick V_PRED for luma"
17267        );
17268        assert_eq!(
17269            uv_mode,
17270            IntraUvMode::V,
17271            "column-constant MB must pick V_PRED for chroma"
17272        );
17273
17274        let p_y = psnr(&pixels.y, &ry);
17275        let p_u = psnr(&pixels.u, &ru);
17276        let p_v = psnr(&pixels.v, &rv);
17277        assert!(p_y >= 30.0, "V_PRED luma PSNR {p_y:.2} dB < 30 dB");
17278        assert!(p_u >= 30.0, "V_PRED U PSNR {p_u:.2} dB < 30 dB");
17279        assert!(p_v >= 30.0, "V_PRED V PSNR {p_v:.2} dB < 30 dB");
17280    }
17281
17282    /// A macroblock whose pixels are constant across each row but vary
17283    /// down the rows is reproduced exactly by H_PRED from the left
17284    /// column. The SAD picker must choose `H` and reconstruct at high
17285    /// PSNR.
17286    #[test]
17287    fn mode_pick_chooses_h_pred_for_row_constant_mb() {
17288        let mut y_col = [0u8; 16];
17289        for (r, slot) in y_col.iter_mut().enumerate() {
17290            *slot = (200 - r * 10) as u8;
17291        }
17292        let mut u_col = [0u8; 8];
17293        let mut v_col = [0u8; 8];
17294        for r in 0..8 {
17295            u_col[r] = (60 + r * 14) as u8;
17296            v_col[r] = (190 - r * 14) as u8;
17297        }
17298
17299        let mut y = [0u8; 256];
17300        for r in 0..16 {
17301            for c in 0..16 {
17302                y[r * 16 + c] = y_col[r];
17303            }
17304        }
17305        let mut u = [0u8; 64];
17306        let mut v = [0u8; 64];
17307        for r in 0..8 {
17308            for c in 0..8 {
17309                u[r * 8 + c] = u_col[r];
17310                v[r * 8 + c] = v_col[r];
17311            }
17312        }
17313        let pixels = MbPixels { y, u, v };
17314
17315        let neighbors = MbNeighbors {
17316            y_left: Some(y_col),
17317            u_left: Some(u_col),
17318            v_left: Some(v_col),
17319            ..MbNeighbors::default()
17320        };
17321
17322        let (y_mode, uv_mode, ry, ru, rv) = encode_decode_with_neighbors(&pixels, &neighbors, 8);
17323
17324        assert_eq!(
17325            y_mode,
17326            IntraYMode::H,
17327            "row-constant MB must pick H_PRED for luma"
17328        );
17329        assert_eq!(
17330            uv_mode,
17331            IntraUvMode::H,
17332            "row-constant MB must pick H_PRED for chroma"
17333        );
17334
17335        let p_y = psnr(&pixels.y, &ry);
17336        let p_u = psnr(&pixels.u, &ru);
17337        let p_v = psnr(&pixels.v, &rv);
17338        assert!(p_y >= 30.0, "H_PRED luma PSNR {p_y:.2} dB < 30 dB");
17339        assert!(p_u >= 30.0, "H_PRED U PSNR {p_u:.2} dB < 30 dB");
17340        assert!(p_v >= 30.0, "H_PRED V PSNR {p_v:.2} dB < 30 dB");
17341    }
17342
17343    /// TM_PRED propagates a gradient seeded by the above row, the left
17344    /// column, and the corner: `X_ij = clamp(L_i + A_j - P)`. A planar
17345    /// ramp `base + i + j` is exactly the shape TM reconstructs, so a MB
17346    /// built from that surface (with matching neighbour strips) must let
17347    /// the picker beat the flat fallbacks with TM and reconstruct at
17348    /// high PSNR.
17349    #[test]
17350    fn mode_pick_chooses_tm_pred_for_planar_ramp_mb() {
17351        let corner: i32 = 100;
17352        // Above row A_j = corner + (j+1); left column L_i = corner + (i+1).
17353        let mut a = [0u8; 16];
17354        let mut l = [0u8; 16];
17355        for k in 0..16 {
17356            a[k] = (corner + k as i32 + 1) as u8;
17357            l[k] = (corner + k as i32 + 1) as u8;
17358        }
17359        let mut ua = [0u8; 8];
17360        let mut ul = [0u8; 8];
17361        let mut va = [0u8; 8];
17362        let mut vl = [0u8; 8];
17363        for k in 0..8 {
17364            ua[k] = (corner + k as i32 + 1) as u8;
17365            ul[k] = (corner + k as i32 + 1) as u8;
17366            va[k] = (corner + k as i32 + 1) as u8;
17367            vl[k] = (corner + k as i32 + 1) as u8;
17368        }
17369
17370        // Source surface = clamp(L_i + A_j - P) — what TM predicts.
17371        let mut y = [0u8; 256];
17372        for i in 0..16 {
17373            for j in 0..16 {
17374                y[i * 16 + j] = (l[i] as i32 + a[j] as i32 - corner).clamp(0, 255) as u8;
17375            }
17376        }
17377        let mut u = [0u8; 64];
17378        let mut v = [0u8; 64];
17379        for i in 0..8 {
17380            for j in 0..8 {
17381                u[i * 8 + j] = (ul[i] as i32 + ua[j] as i32 - corner).clamp(0, 255) as u8;
17382                v[i * 8 + j] = (vl[i] as i32 + va[j] as i32 - corner).clamp(0, 255) as u8;
17383            }
17384        }
17385        let pixels = MbPixels { y, u, v };
17386
17387        let neighbors = MbNeighbors {
17388            y_above: Some(a),
17389            y_left: Some(l),
17390            y_topleft: Some(corner as u8),
17391            u_above: Some(ua),
17392            u_left: Some(ul),
17393            u_topleft: Some(corner as u8),
17394            v_above: Some(va),
17395            v_left: Some(vl),
17396            v_topleft: Some(corner as u8),
17397            ..MbNeighbors::default()
17398        };
17399
17400        let (y_mode, _uv_mode, ry, _ru, _rv) = encode_decode_with_neighbors(&pixels, &neighbors, 8);
17401
17402        assert_eq!(
17403            y_mode,
17404            IntraYMode::Tm,
17405            "planar-ramp MB must pick TM_PRED for luma"
17406        );
17407        let p_y = psnr(&pixels.y, &ry);
17408        assert!(p_y >= 30.0, "TM_PRED luma PSNR {p_y:.2} dB < 30 dB");
17409    }
17410
17411    /// The standalone `encode_mb_block_set` (off-frame neighbours)
17412    /// reduces to the same picker over the §12 defaults: it must still
17413    /// roundtrip a textured MB through the decoder's isolated-MB path
17414    /// (`decode_keyframe` on a 1×1 frame) at ≥ 30 dB.
17415    #[test]
17416    fn isolated_mb_textured_roundtrips_above_30db() {
17417        // A mild diagonal texture around mid-grey — no neighbour helps,
17418        // so the picker lands on whichever default is closest, but the
17419        // residual still carries the texture and must reconstruct well.
17420        let mut y = [0u8; 256];
17421        for i in 0..16 {
17422            for j in 0..16 {
17423                y[i * 16 + j] = (120 + ((i + j) % 8) * 2) as u8;
17424            }
17425        }
17426        let mut u = [0u8; 64];
17427        let mut v = [0u8; 64];
17428        for i in 0..8 {
17429            for j in 0..8 {
17430                u[i * 8 + j] = (124 + ((i + j) % 4) * 2) as u8;
17431                v[i * 8 + j] = (132 - ((i + j) % 4) * 2) as u8;
17432            }
17433        }
17434        let pixels = MbPixels { y, u, v };
17435
17436        // Mode-aware decode: a diagonal texture with off-frame neighbours
17437        // may pick B_PRED for luma; either way the residual must
17438        // reconstruct the texture above the PSNR floor.
17439        let (_y_mode, _uv, _sub, ry, ru, rv) =
17440            encode_decode_bpred_aware(&pixels, &MbNeighbors::default(), 8);
17441
17442        let p_y = psnr(&pixels.y, &ry);
17443        let p_u = psnr(&pixels.u, &ru);
17444        let p_v = psnr(&pixels.v, &rv);
17445        assert!(p_y >= 30.0, "isolated luma PSNR {p_y:.2} dB < 30 dB");
17446        assert!(p_u >= 30.0, "isolated U PSNR {p_u:.2} dB < 30 dB");
17447        assert!(p_v >= 30.0, "isolated V PSNR {p_v:.2} dB < 30 dB");
17448    }
17449
17450    /// Round 161 — `pick_intra_mb_all` must score every §11.2 × §11.4
17451    /// whole-block intra candidate and return the J-best `(y_mode,
17452    /// uv_mode)`. Three crafted MBs exercise the non-DC modes:
17453    ///
17454    ///   * Vertical-stripe MB (rows identical to the above row) — the
17455    ///     §12 V_PRED prediction is exact, so `(V, V)` should win.
17456    ///   * Horizontal-stripe MB (columns identical to the left column)
17457    ///     — H_PRED prediction is exact, so `(H, H)` should win.
17458    ///   * Planar-ramp MB (`base + i + j`) — TM_PRED prediction is exact,
17459    ///     so `(Tm, Tm)` should win.
17460    ///
17461    /// All three contrast with the round-160 DC-only picker, which would
17462    /// have returned `(Dc, Dc)` on every input regardless of content.
17463    /// Neighbour edges are supplied so the V / H / TM kernels predict
17464    /// from the genuine neighbour content (not the §12 off-frame
17465    /// default-fill 127/129).
17466    #[test]
17467    fn pick_intra_mb_all_selects_v_h_tm_for_structured_sources() {
17468        use crate::dequant::MbDequantFactors;
17469        use crate::macroblock::{IntraUvMode, IntraYMode};
17470        use crate::reconstruct::MbNeighbors;
17471
17472        // Fixed mid-quality quantiser keeps the §14 floor low so the
17473        // residual stays small enough for the matched mode's SAD to win.
17474        let factors = MbDequantFactors::from_base_and_deltas(32, 0, 0, 0, 0, 0);
17475        let lambda = rd_lambda(&factors);
17476
17477        // Above strip: vertically-monotonic; left strip: monotonic; corner
17478        // value matches both ends — used by TM_PRED.
17479        let above_y: [u8; 16] = core::array::from_fn(|j| (40 + j * 8) as u8);
17480        let left_y: [u8; 16] = core::array::from_fn(|i| (40 + i * 8) as u8);
17481        let above_uv: [u8; 8] = core::array::from_fn(|j| (60 + j * 4) as u8);
17482        let left_uv: [u8; 8] = core::array::from_fn(|i| (60 + i * 4) as u8);
17483        let corner_y: u8 = 40;
17484        let corner_uv: u8 = 60;
17485
17486        let make_neighbors = || MbNeighbors {
17487            y_above: Some(above_y),
17488            y_left: Some(left_y),
17489            y_above_right: Some([above_y[15]; 4]),
17490            y_topleft: Some(corner_y),
17491            u_above: Some(above_uv),
17492            u_left: Some(left_uv),
17493            u_topleft: Some(corner_uv),
17494            v_above: Some(above_uv),
17495            v_left: Some(left_uv),
17496            v_topleft: Some(corner_uv),
17497        };
17498
17499        // ---- Vertical-stripe source: every row equals the above row.
17500        //      V_PRED predicts the above row directly, residual = 0.
17501        let mut y_vstripe = [0u8; 256];
17502        for r in 0..16 {
17503            for c in 0..16 {
17504                y_vstripe[r * 16 + c] = above_y[c];
17505            }
17506        }
17507        let mut uv_vstripe = [0u8; 64];
17508        for r in 0..8 {
17509            for c in 0..8 {
17510                uv_vstripe[r * 8 + c] = above_uv[c];
17511            }
17512        }
17513        let pixels_v = MbPixels {
17514            y: y_vstripe,
17515            u: uv_vstripe,
17516            v: uv_vstripe,
17517        };
17518        let pick_v = pick_intra_mb_all(
17519            &pixels_v,
17520            &make_neighbors(),
17521            &factors,
17522            lambda,
17523            None,
17524            None,
17525            TrellisStrength::DEFAULT,
17526        );
17527        assert_eq!(
17528            pick_v.y_mode,
17529            IntraYMode::V,
17530            "vertical-stripe source should pick V_PRED for Y, got {:?}",
17531            pick_v.y_mode
17532        );
17533        // The picker's distortion model is Y-SAD only (matches the
17534        // inter picker for cross-candidate apples-to-apples comparison),
17535        // so the chroma mode is chosen purely on §11.4 tree-bit cost
17536        // unless the chroma rate-distortion adapts the Y SAD via the
17537        // recon path. DC has the cheapest leaf bit cost in the §11.4
17538        // IF_UV_MODE_TREE, so DC is a legitimate winner when Y dominates.
17539        // Assert the chroma pick is a valid §11.4 leaf.
17540        assert!(matches!(
17541            pick_v.uv_mode,
17542            IntraUvMode::Dc | IntraUvMode::V | IntraUvMode::H | IntraUvMode::Tm
17543        ));
17544
17545        // ---- Horizontal-stripe source: every column equals the left
17546        //      column. H_PRED predicts the left column directly,
17547        //      residual = 0.
17548        let mut y_hstripe = [0u8; 256];
17549        for r in 0..16 {
17550            for c in 0..16 {
17551                y_hstripe[r * 16 + c] = left_y[r];
17552            }
17553        }
17554        let mut uv_hstripe = [0u8; 64];
17555        for r in 0..8 {
17556            for c in 0..8 {
17557                uv_hstripe[r * 8 + c] = left_uv[r];
17558            }
17559        }
17560        let pixels_h = MbPixels {
17561            y: y_hstripe,
17562            u: uv_hstripe,
17563            v: uv_hstripe,
17564        };
17565        let pick_h = pick_intra_mb_all(
17566            &pixels_h,
17567            &make_neighbors(),
17568            &factors,
17569            lambda,
17570            None,
17571            None,
17572            TrellisStrength::DEFAULT,
17573        );
17574        assert_eq!(
17575            pick_h.y_mode,
17576            IntraYMode::H,
17577            "horizontal-stripe source should pick H_PRED for Y, got {:?}",
17578            pick_h.y_mode
17579        );
17580        assert!(matches!(
17581            pick_h.uv_mode,
17582            IntraUvMode::Dc | IntraUvMode::V | IntraUvMode::H | IntraUvMode::Tm
17583        ));
17584
17585        // ---- Planar-ramp source. TM_PRED reconstructs the canonical
17586        //      planar surface `clamp(L_i + A_j - P)` from the
17587        //      neighbours; with above / left = `40 + 8k` and corner = 40,
17588        //      the surface is `40 + 8 * (r + c)` over the 16×16 grid.
17589        //      Clamp to u8 (last few cells saturate near 255).
17590        let mut y_tm = [0u8; 256];
17591        for r in 0..16 {
17592            for c in 0..16 {
17593                let v = (corner_y as i32) + 8 * (r as i32 + c as i32) - 40;
17594                // The TM formula is `clamp(L_i + A_j - P)` with
17595                //   L_i = corner_y + 8 * (i+1) = 40 + 8 * (i+1)
17596                //   A_j = corner_y + 8 * (j+1) = 40 + 8 * (j+1)
17597                //   P   = corner_y             = 40
17598                // ⇒ surface = 40 + 8*(i+1) + 8*(j+1) - 40 = 8*(i+j+2).
17599                let surface = 8 * (r as i32 + c as i32 + 2);
17600                let _ = v; // commented for clarity; we use `surface`.
17601                y_tm[r * 16 + c] = surface.clamp(0, 255) as u8;
17602            }
17603        }
17604        let mut uv_tm = [0u8; 64];
17605        for r in 0..8 {
17606            for c in 0..8 {
17607                // Chroma uses corner_uv = 60, above/left = 60 + 4*(k+1).
17608                let surface = 4 * (r as i32 + c as i32) + 2 * 4 + (corner_uv as i32);
17609                // = 4*(r+c) + 8 + 60 = 4*(r+c) + 68. Equivalent to
17610                // L_i + A_j - P with the same algebra.
17611                uv_tm[r * 8 + c] = surface.clamp(0, 255) as u8;
17612            }
17613        }
17614        let pixels_tm = MbPixels {
17615            y: y_tm,
17616            u: uv_tm,
17617            v: uv_tm,
17618        };
17619        let pick_tm = pick_intra_mb_all(
17620            &pixels_tm,
17621            &make_neighbors(),
17622            &factors,
17623            lambda,
17624            None,
17625            None,
17626            TrellisStrength::DEFAULT,
17627        );
17628        assert_eq!(
17629            pick_tm.y_mode,
17630            IntraYMode::Tm,
17631            "planar-ramp source should pick TM_PRED for Y, got {:?}",
17632            pick_tm.y_mode
17633        );
17634        // Chroma may legitimately tie at TM or fall to V/H/DC depending
17635        // on the ramp slope vs the §11.4 mode-tree-bit cost trade. The
17636        // luma TM_PRED selection is the load-bearing assertion (it
17637        // would have been impossible under the r160 DC-only picker);
17638        // the chroma assertion is a smoke check that the pick is a
17639        // valid §11.4 leaf.
17640        assert!(matches!(
17641            pick_tm.uv_mode,
17642            IntraUvMode::Dc | IntraUvMode::V | IntraUvMode::H | IntraUvMode::Tm
17643        ));
17644
17645        // ---- Sanity: a flat-grey source still rounds to DC_PRED (the
17646        //      round-160 behaviour); strict-< tie-break to first-tried
17647        //      ⇒ (Dc, Dc).
17648        let flat_y = [128u8; 256];
17649        let flat_uv = [128u8; 64];
17650        let pixels_flat = MbPixels {
17651            y: flat_y,
17652            u: flat_uv,
17653            v: flat_uv,
17654        };
17655        let pick_flat = pick_intra_mb_all(
17656            &pixels_flat,
17657            &MbNeighbors::default(),
17658            &factors,
17659            lambda,
17660            None,
17661            None,
17662            TrellisStrength::DEFAULT,
17663        );
17664        assert_eq!(
17665            pick_flat.y_mode,
17666            IntraYMode::Dc,
17667            "flat-grey source with off-frame neighbours should still pick DC_PRED for Y"
17668        );
17669        assert_eq!(
17670            pick_flat.uv_mode,
17671            IntraUvMode::Dc,
17672            "flat-grey source should pick DC_PRED for UV"
17673        );
17674    }
17675
17676    // ─────────────── bit-cost model (rate control) ───────────────
17677
17678    #[test]
17679    fn estimate_bits_per_mb_falls_as_qindex_rises() {
17680        // The whole point of the model: at a fixed complexity, raising
17681        // the qindex (coarser quantiser) must lower the predicted bits.
17682        let complexity = 200.0;
17683        let lo = estimate_bits_per_mb(complexity, 10);
17684        let mid = estimate_bits_per_mb(complexity, 50);
17685        let hi = estimate_bits_per_mb(complexity, 110);
17686        assert!(
17687            lo > mid && mid > hi,
17688            "bits/MB must fall as qindex rises: qi10={lo} qi50={mid} qi110={hi}"
17689        );
17690    }
17691
17692    #[test]
17693    fn estimate_bits_per_mb_rises_with_complexity() {
17694        // At a fixed qindex, a busier frame must cost more bits.
17695        let qi = 40;
17696        let flat = estimate_bits_per_mb(10.0, qi);
17697        let busy = estimate_bits_per_mb(800.0, qi);
17698        assert!(
17699            busy > flat,
17700            "busier frame must cost more bits at the same qindex: flat={flat} busy={busy}"
17701        );
17702    }
17703
17704    #[test]
17705    fn estimate_bits_per_mb_reproduces_surrogate_at_reference_qindex() {
17706        // By construction the surrogate value is the predicted bits/MB
17707        // at the reference qindex (plus the per-MB floor): the scaling
17708        // factor collapses to 1.0 when step == ref_step.
17709        let complexity = 137.0;
17710        let predicted = estimate_bits_per_mb(complexity, RATE_MODEL_REF_QINDEX as i32);
17711        assert!(
17712            (predicted - (complexity + RATE_MODEL_MB_FLOOR_BITS)).abs() < 1e-3,
17713            "at the reference qindex the model must reproduce the surrogate + floor, got {predicted}"
17714        );
17715    }
17716
17717    #[test]
17718    fn estimate_bits_per_mb_keeps_the_floor_at_coarsest_quant() {
17719        // Even at qindex 127 a zero-complexity frame still charges the
17720        // per-MB floor (header / mode bits never vanish).
17721        let predicted = estimate_bits_per_mb(0.0, 127);
17722        assert!(
17723            (predicted - RATE_MODEL_MB_FLOOR_BITS).abs() < 1e-3,
17724            "zero-complexity frame at qi127 must charge exactly the floor, got {predicted}"
17725        );
17726    }
17727
17728    #[test]
17729    fn estimate_frame_bytes_scales_with_macroblock_count() {
17730        // A 4× larger frame (2× each dimension) has 4× the MBs and so
17731        // ≈4× the predicted bytes at the same complexity / qindex.
17732        let small = estimate_frame_bytes(150.0, 40, 32, 32); // 2×2 MBs
17733        let big = estimate_frame_bytes(150.0, 40, 64, 64); // 4×4 MBs
17734        assert!(
17735            big >= small.saturating_mul(3),
17736            "4× the MBs must predict roughly 4× the bytes: small={small} big={big}"
17737        );
17738    }
17739
17740    #[test]
17741    fn estimate_frame_bytes_rounds_partial_macroblocks_up() {
17742        // A 17×17 frame spans 2×2 MBs (one full + partials) — same MB
17743        // count as 32×32, so the predicted byte count must match.
17744        let partial = estimate_frame_bytes(100.0, 40, 17, 17);
17745        let full = estimate_frame_bytes(100.0, 40, 32, 32);
17746        assert_eq!(
17747            partial, full,
17748            "17×17 and 32×32 both span 2×2 MBs — byte estimate must match"
17749        );
17750    }
17751
17752    #[test]
17753    fn estimate_frame_bytes_zero_dimensions_is_zero() {
17754        assert_eq!(estimate_frame_bytes(500.0, 40, 0, 64), 0);
17755        assert_eq!(estimate_frame_bytes(500.0, 40, 64, 0), 0);
17756    }
17757
17758    // ─────────────── bitrate-budget solver ───────────────
17759
17760    fn busy_clip(n: usize) -> Vec<FrameComplexity> {
17761        (0..n)
17762            .map(|i| FrameComplexity {
17763                frame_index: i as u32,
17764                bits_per_mb: 600.0,
17765                scene_cut: false,
17766            })
17767            .collect()
17768    }
17769
17770    #[test]
17771    fn gop_byte_budget_tracks_bitrate_and_rate() {
17772        let mut config = Vp8TwoPassConfig {
17773            target_bitrate_bps: 8_000_000, // 1 MB/s
17774            fps_num: 30,
17775            fps_den: 1,
17776            ..Vp8TwoPassConfig::default()
17777        };
17778        // 30 frames at 30fps == 1 second == 1 MB.
17779        let b = gop_byte_budget(&config, 30).expect("budget defined");
17780        assert_eq!(b, 1_000_000);
17781        // Half the frames ⇒ half the budget.
17782        let b2 = gop_byte_budget(&config, 15).expect("budget defined");
17783        assert_eq!(b2, 500_000);
17784        // No rate ⇒ no budget.
17785        config.fps_num = 0;
17786        assert!(gop_byte_budget(&config, 30).is_none());
17787    }
17788
17789    #[test]
17790    fn solver_returns_base_when_not_bitrate_targeted() {
17791        // No target bitrate ⇒ solver is a no-op, returns base qindex.
17792        let config = Vp8TwoPassConfig {
17793            base: Vp8EncoderConfig {
17794                qindex: 44,
17795                ..Vp8EncoderConfig::default()
17796            },
17797            ..Vp8TwoPassConfig::default()
17798        };
17799        let qi = solve_base_qindex_for_budget(&config, &busy_clip(10), 176, 144);
17800        assert_eq!(qi, 44);
17801    }
17802
17803    #[test]
17804    fn solver_raises_qindex_under_a_tight_budget() {
17805        // A deliberately starved bitrate must drive the solved base
17806        // qindex high (coarse quantiser) to fit the budget.
17807        let config = Vp8TwoPassConfig {
17808            target_bitrate_bps: 8_000, // 1 kB/s — very tight for QCIF busy
17809            fps_num: 30,
17810            fps_den: 1,
17811            ..Vp8TwoPassConfig::default()
17812        };
17813        let qi = solve_base_qindex_for_budget(&config, &busy_clip(30), 176, 144);
17814        assert!(
17815            qi > Vp8EncoderConfig::default().qindex,
17816            "tight budget must raise the base qindex above the default, got {qi}"
17817        );
17818    }
17819
17820    #[test]
17821    fn solver_lowers_qindex_under_a_generous_budget() {
17822        // A very generous bitrate must drive the solved base qindex to
17823        // the finest quantiser (best quality).
17824        let config = Vp8TwoPassConfig {
17825            target_bitrate_bps: 800_000_000, // absurdly high
17826            fps_num: 30,
17827            fps_den: 1,
17828            ..Vp8TwoPassConfig::default()
17829        };
17830        let qi = solve_base_qindex_for_budget(&config, &busy_clip(30), 176, 144);
17831        assert_eq!(qi, 0, "generous budget must spend all quality (qindex 0)");
17832    }
17833
17834    #[test]
17835    fn solver_is_monotone_in_budget() {
17836        // Loosening the budget must never raise the solved qindex.
17837        let base = Vp8TwoPassConfig {
17838            fps_num: 30,
17839            fps_den: 1,
17840            ..Vp8TwoPassConfig::default()
17841        };
17842        let clip = busy_clip(30);
17843        let mut prev = 128i32;
17844        for &bps in &[8_000u32, 40_000, 200_000, 1_000_000, 5_000_000] {
17845            let config = Vp8TwoPassConfig {
17846                target_bitrate_bps: bps,
17847                ..base
17848            };
17849            let qi = solve_base_qindex_for_budget(&config, &clip, 176, 144) as i32;
17850            assert!(
17851                qi <= prev,
17852                "a larger budget ({bps} bps) must not raise the solved qindex: {qi} > {prev}"
17853            );
17854            prev = qi;
17855        }
17856    }
17857
17858    #[test]
17859    fn solver_respects_predicted_ceiling() {
17860        // The predicted byte total at the solved qindex must stay under
17861        // the budget × overshoot ceiling (the solver's contract).
17862        let config = Vp8TwoPassConfig {
17863            target_bitrate_bps: 100_000,
17864            overshoot_ratio: 1.2,
17865            fps_num: 30,
17866            fps_den: 1,
17867            ..Vp8TwoPassConfig::default()
17868        };
17869        let clip = busy_clip(30);
17870        let qi = solve_base_qindex_for_budget(&config, &clip, 176, 144) as i32;
17871        let budget = gop_byte_budget(&config, clip.len()).unwrap();
17872        let ceiling = (budget as f64 * 1.2) as u64;
17873        let predicted = predict_gop_bytes_at_qindex(&clip, 176, 144, qi);
17874        // Either we fit the ceiling, or we are already pinned at the
17875        // coarsest quantiser (127) and physically cannot do better.
17876        assert!(
17877            predicted <= ceiling || qi == 127,
17878            "predicted {predicted} must fit ceiling {ceiling} unless pinned at qi127 (qi={qi})"
17879        );
17880    }
17881
17882    #[test]
17883    fn two_pass_qindices_for_bitrate_recenters_schedule() {
17884        // Under a tight budget the per-frame schedule must re-centre on
17885        // the solved (higher) base, not on config.base.qindex.
17886        let config = Vp8TwoPassConfig {
17887            base: Vp8EncoderConfig {
17888                qindex: 30,
17889                ..Vp8EncoderConfig::default()
17890            },
17891            target_bitrate_bps: 8_000,
17892            fps_num: 30,
17893            fps_den: 1,
17894            ..Vp8TwoPassConfig::default()
17895        };
17896        // Vary complexity so the schedule isn't flat.
17897        let clip: Vec<_> = (0..6)
17898            .map(|i| FrameComplexity {
17899                frame_index: i,
17900                bits_per_mb: 200.0 + i as f32 * 200.0,
17901                scene_cut: false,
17902            })
17903            .collect();
17904        let sched = two_pass_qindices_for_bitrate(&config, &clip, 176, 144).unwrap();
17905        assert_eq!(sched.len(), clip.len());
17906        let mean_qi: f32 = sched.iter().map(|&q| q as f32).sum::<f32>() / sched.len() as f32;
17907        assert!(
17908            mean_qi > config.base.qindex as f32,
17909            "tight budget must raise the schedule mean above the configured base: \
17910             mean={mean_qi} base={}",
17911            config.base.qindex
17912        );
17913        for &q in &sched {
17914            assert!(q <= 127);
17915        }
17916    }
17917
17918    #[test]
17919    fn two_pass_qindices_for_bitrate_matches_cq_when_untargeted() {
17920        // With no bitrate target the bitrate schedule must equal the
17921        // plain complexity-aware schedule.
17922        let config = Vp8TwoPassConfig::default();
17923        let clip: Vec<_> = (0..5)
17924            .map(|i| FrameComplexity {
17925                frame_index: i,
17926                bits_per_mb: 100.0 + i as f32 * 50.0,
17927                scene_cut: false,
17928            })
17929            .collect();
17930        let cq = two_pass_qindices(&config, &clip).unwrap();
17931        let br = two_pass_qindices_for_bitrate(&config, &clip, 176, 144).unwrap();
17932        assert_eq!(
17933            cq, br,
17934            "untargeted bitrate schedule must equal the CQ schedule"
17935        );
17936    }
17937
17938    #[test]
17939    fn rate_feedback_delta_sign_and_clamp() {
17940        let config = Vp8TwoPassConfig {
17941            target_bitrate_bps: 100_000,
17942            fps_num: 30,
17943            fps_den: 1,
17944            ..Vp8TwoPassConfig::default()
17945        };
17946        let mut enc = Vp8TwoPassEncoder::new(config);
17947        // No budget cached yet ⇒ no feedback.
17948        assert_eq!(enc.rate_feedback_delta(), 0);
17949
17950        enc.frame_byte_budget = Some(1000);
17951        // Over budget by one full frame allotment ⇒ +gain.
17952        enc.rate_debt_bytes = 1000;
17953        assert_eq!(enc.rate_feedback_delta(), RATE_FEEDBACK_QSTEP_PER_FRAME);
17954        // Under budget by one allotment ⇒ −gain.
17955        enc.rate_debt_bytes = -1000;
17956        assert_eq!(enc.rate_feedback_delta(), -RATE_FEEDBACK_QSTEP_PER_FRAME);
17957        // Huge debt ⇒ clamped at the max step.
17958        enc.rate_debt_bytes = 1_000_000;
17959        assert_eq!(enc.rate_feedback_delta(), RATE_FEEDBACK_MAX_QSTEP);
17960        enc.rate_debt_bytes = -1_000_000;
17961        assert_eq!(enc.rate_feedback_delta(), -RATE_FEEDBACK_MAX_QSTEP);
17962    }
17963
17964    #[test]
17965    fn two_pass_qindices_for_bitrate_empty_and_bad_base() {
17966        let config = Vp8TwoPassConfig::default();
17967        assert!(
17968            two_pass_qindices_for_bitrate(&config, &[], 176, 144)
17969                .unwrap()
17970                .is_empty()
17971        );
17972        let bad = Vp8TwoPassConfig {
17973            base: Vp8EncoderConfig {
17974                qindex: 200,
17975                ..Vp8EncoderConfig::default()
17976            },
17977            ..Vp8TwoPassConfig::default()
17978        };
17979        assert!(two_pass_qindices_for_bitrate(&bad, &busy_clip(3), 176, 144).is_err());
17980    }
17981
17982    #[test]
17983    fn treed_bits_cached_matches_dfs_walk() {
17984        // The RD scorers price mode bits through the precomputed
17985        // per-tree path tables; every priced value must be f64
17986        // bit-for-bit the DFS-walk `treed_bits` sum, for every leaf of
17987        // every table and under both the real probability tables and a
17988        // synthetic non-uniform lookup (so a wrong prob_index would
17989        // change the sum, not alias into it).
17990        fn check<const N: usize>(
17991            tree: &'static [i8],
17992            paths: &[TreedLeafPath; N],
17993            real_probs: &'static [u8],
17994        ) {
17995            let synthetic = |i: usize| -> u8 { (37 * i + 11) as u8 };
17996            for leaf in 0..N as u8 {
17997                for lookup in [
17998                    Box::new(|i: usize| real_probs[i]) as Box<dyn Fn(usize) -> u8>,
17999                    Box::new(synthetic),
18000                ] {
18001                    let reference = treed_bits(tree, &lookup, leaf);
18002                    let cached = treed_bits_cached(paths, &lookup, leaf);
18003                    assert_eq!(
18004                        cached.to_bits(),
18005                        reference.to_bits(),
18006                        "tree {tree:?} leaf {leaf}"
18007                    );
18008                }
18009            }
18010        }
18011        check(&KF_YMODE_TREE, &KF_YMODE_PATHS, &KF_YMODE_PROB);
18012        check(&UV_MODE_TREE, &UV_MODE_PATHS, &KF_UV_MODE_PROB);
18013        check(&BMODE_TREE, &BMODE_PATHS, &KF_BMODE_PROB[0][0]);
18014        check(&IF_YMODE_TREE, &IF_YMODE_PATHS, &IF_YMODE_PROB_DEFAULTS);
18015        // The chroma table is shared between keyframe and interframe
18016        // pricing; cover the interframe probabilities too.
18017        check(&UV_MODE_TREE, &UV_MODE_PATHS, &IF_UV_MODE_PROB_DEFAULTS);
18018    }
18019
18020    #[test]
18021    fn write_literal_fast_matches_generic_loop() {
18022        // The register-local fixed-prob-128 `write_literal` must be
18023        // state-for-state the generic `num_bits x write_bool(128)` loop:
18024        // identical emitted bytes AND identical (range, bottom,
18025        // bit_count) after every literal, across the full width spread
18026        // (including width 0) and enough volume to exercise the carry
18027        // scan and the byte-emit cadence.
18028        let mut fast = BoolEncoder::new();
18029        let mut generic = BoolEncoder::new();
18030        let mut x: u32 = 0x1234_5678;
18031        for step in 0..4096u32 {
18032            // xorshift32 value stream.
18033            x ^= x << 13;
18034            x ^= x >> 17;
18035            x ^= x << 5;
18036            let num_bits = step % 33; // 0..=32
18037            let value = if num_bits == 32 {
18038                x
18039            } else {
18040                x & ((1u32 << num_bits) - 1)
18041            };
18042            fast.write_literal(value, num_bits);
18043            let mut i = num_bits;
18044            while i > 0 {
18045                i -= 1;
18046                generic.write_bool(128, ((value >> i) & 1) != 0);
18047            }
18048            assert_eq!(fast.range, generic.range, "range diverged at step {step}");
18049            assert_eq!(
18050                fast.bottom, generic.bottom,
18051                "bottom diverged at step {step}"
18052            );
18053            assert_eq!(
18054                fast.bit_count, generic.bit_count,
18055                "bit_count diverged at step {step}"
18056            );
18057            assert_eq!(fast.out, generic.out, "bytes diverged at step {step}");
18058        }
18059        assert_eq!(fast.finish(), generic.finish());
18060    }
18061}