Skip to main content

oxideav_vp8/
reconstruct.rs

1//! Per-macroblock reconstruction orchestration (RFC 6386 §14.2).
2//!
3//! This module is the glue that ties together the bitstream pieces
4//! already landed in earlier rounds:
5//!
6//! * §13 token decode (`dct_tokens` / `decode_block`) → caller produces
7//!   raw 4×4 sub-block coefficient arrays;
8//! * §14.1 dequantization (`inverse_transform::dequant_block`) → caller
9//!   multiplies each sub-block's coefficients by the DC / AC factors;
10//! * §14.3 inverse WHT (`inverse_transform::inverse_wht_4x4`) → applied
11//!   here when the Y2 block is present;
12//! * §14.4 inverse DCT (`inverse_transform::inverse_dct_4x4`) → applied
13//!   here per Y / U / V sub-block;
14//! * §11 mode decode (`macroblock::parse_key_frame_macroblock_modes`)
15//!   selects which §12 intra-prediction kernel applies;
16//! * §12 intra-prediction kernels (`intra_predict::predict_y16x16` /
17//!   `predict_uv8x8`) → applied here;
18//! * §14.5 summation (`inverse_transform::add_residue_4x4`) → applied
19//!   here to fold the per-sub-block residue back into the predicted
20//!   pixels.
21//!
22//! ## Scope (single-MB orchestrator)
23//!
24//! [`decode_keyframe_mb_non_bpred`] reconstructs one macroblock whose
25//! 16×16 luma mode is one of the four §12.3-16×16 modes
26//! ([`IntraYMode::Dc`] / [`IntraYMode::V`] / [`IntraYMode::H`] /
27//! [`IntraYMode::Tm`]). It does **not** drive `B_PRED` macroblocks.
28//!
29//! [`decode_keyframe_mb_bpred`] is the companion entry point for the
30//! `B_PRED` luma mode (§11.3 / §12.3). Unlike the 16×16 modes, a
31//! `B_PRED` macroblock predicts each of its sixteen 4×4 luma sub-blocks
32//! independently, and — critically — each sub-block's prediction reads
33//! the **already-reconstructed** pixels (prediction + residue) of the
34//! sub-blocks above and to its left. The orchestrator therefore cannot
35//! predict the whole plane first and add residue afterward; it must
36//! interleave predict → inverse-DCT → add-residue **per sub-block** in
37//! raster order so that each sub-block's reconstructed pixels are
38//! visible as the next sub-block's neighbours (this mirrors the §20.14
39//! reference decoder's in-place `b_pred()` loop). The chroma planes of a
40//! `B_PRED` macroblock still use one of the four 8×8 §12.2 modes, so
41//! that part of the recipe is identical to the non-`B_PRED` path.
42//!
43//! Neither orchestrator walks the raster of macroblocks across a frame;
44//! that walker sits on top of these primitives and is the next layer up.
45//!
46//! ### §12.3 per-sub-block neighbour evolution
47//!
48//! The working luma buffer is a `B_PRED`-private macroblock-sized array
49//! with a one-pixel top border row and a one-pixel left border column
50//! (so each sub-block can read `above` / `left` / the top-left pixel `P`
51//! at constant stride), plus a four-pixel "above-right extension" tacked
52//! onto the right end of the border row. Each sub-block's `above` is the
53//! 8-pixel strip in the row immediately above it (the four pixels
54//! directly above plus the four above-and-to-the-right), `left` is the
55//! 4-pixel column immediately to its left, and `P` is the pixel at
56//! `(-1, -1)` relative to the sub-block. After [`predict_b4x4`] writes
57//! the prediction, the sub-block's residue is inverse-DCT'd and added
58//! in place, so the next sub-block in raster order sees reconstructed
59//! pixels.
60//!
61//! ### §12.3 right-edge "above-right" fixup
62//!
63//! Because whole macroblocks are reconstructed in raster order, the
64//! four pixels above-and-to-the-right of sub-blocks 7, 11, and 15 have
65//! not been built when those sub-blocks are predicted. Per §12.3 page
66//! 55 all four right-edge sub-blocks (3, 7, 11, 15) instead share the
67//! four pixels above-and-to-the-right of sub-block 3 — frame positions
68//! `(-1, 16)..=(-1, 19)`. The orchestrator copies those four pixels
69//! down into the border slots above sub-blocks 7, 11, and 15 (the
70//! `copy_down` step of the reference decoder) before the sub-block walk
71//! begins. The caller supplies the four `(-1, 16)..=(-1, 19)` values in
72//! [`MbNeighbors::y_above_right`]; on the top macroblock row they are
73//! 127, and for the rightmost macroblock in a non-top row they are the
74//! value at `(-1, 15)` (the caller computes that clamp).
75//!
76//! ## Inputs
77//!
78//! The caller supplies pre-dequantized 16-bit coefficient arrays for
79//! the 25th (Y2) block, the sixteen Y sub-blocks, and the eight chroma
80//! sub-blocks. The dequant step is the caller's responsibility for
81//! two reasons:
82//!
83//! 1. Y1 dequant factors (`Y1DequantFactors`) are already exposed by
84//!    [`inverse_transform`]; pulling them in here would force a choice
85//!    on the caller about quantiser-index plumbing that the §14.2
86//!    orchestration step itself does not care about.
87//! 2. The Y2 / chroma dequant scaling and clamping that RFC 6386 §14.1
88//!    defers to the reference decoder `dixie.c` source is currently a
89//!    documented spec gap (filed against `docs/video/vp8/`) — keeping
90//!    that gap **out** of this orchestrator's signature means this
91//!    module lands today without depending on the gap being filled.
92//!    When the gap is filled, a follow-up convenience entry point that
93//!    accepts raw tokens + a quantiser-index bundle can wrap this
94//!    function.
95//!
96//! The caller also supplies the neighbouring pixel context that the
97//! §12 kernels read (the 16-pixel `above` / `left` strips and the
98//! top-left pixel for Y, the 8-pixel pair for each chroma plane).
99//!
100//! ## §14.2 procedure (transcribed)
101//!
102//! 1. If the Y2 block exists (Y mode ≠ `B_PRED` and ≠ `SPLITMV`):
103//!    inverse-WHT the Y2 coefficients and seed each Y sub-block's
104//!    coefficient 0 with the matching WHT-output element. This is the
105//!    §14.2 first-paragraph rule: *"the element of the result at row
106//!    `i`, column `j` is used as the 0th coefficient of the Y subblock
107//!    at position `(i, j)`, that is, the Y subblock whose index is
108//!    `(i * 4) + j`."*
109//! 2. Inverse-DCT all sixteen Y sub-blocks and all eight chroma
110//!    sub-blocks (§14.2 second paragraph: *"All 24 of these inversions
111//!    are independent of each other."*)
112//! 3. Apply the §12 intra-prediction kernel selected by the §11 mode
113//!    record, producing the prediction buffer.
114//! 4. Sum the prediction and the residue with `clamp255` (§14.5).
115//!
116//! ## `mb_skip_coeff`
117//!
118//! When the §11 mode record's `mb_skip_coeff` is true, the entire
119//! residue is zero by definition — token decode is skipped, the Y2
120//! block is absent, and the reconstructed pixels equal the prediction
121//! exactly. This orchestrator honours that short-circuit and avoids
122//! the wasted WHT / DCT / summation cycles for skip MBs.
123
124use crate::intra_predict::{
125    DEFAULT_ABOVE_PIXEL, DEFAULT_LEFT_PIXEL, predict_b4x4, predict_uv8x8, predict_y16x16,
126};
127use crate::inverse_transform::{add_residue_4x4, inverse_dct_4x4, inverse_wht_4x4};
128use crate::macroblock::{IntraBmode, IntraUvMode, IntraYMode};
129
130/// Pixel context surrounding a macroblock, supplying the neighbours
131/// the §12 intra-prediction kernels read.
132///
133/// All fields are `Option`: `None` means the corresponding strip lies
134/// off the top / left edge of the frame and the §12 kernels' default
135/// substitution rules apply (the kernels fill from
136/// [`crate::intra_predict::DEFAULT_ABOVE_PIXEL`] / `DEFAULT_LEFT_PIXEL`
137/// / `DEFAULT_TOPLEFT_DC` as the spec specifies).
138#[derive(Debug, Clone, Copy, Default)]
139pub struct MbNeighbors {
140    /// Sixteen luma pixels immediately above the MB (row `-1`,
141    /// columns `0..=15`).
142    pub y_above: Option<[u8; 16]>,
143    /// Sixteen luma pixels immediately to the left of the MB
144    /// (column `-1`, rows `0..=15`).
145    pub y_left: Option<[u8; 16]>,
146    /// The four luma pixels above-and-to-the-right of the macroblock
147    /// (frame positions `(-1, 16)..=(-1, 19)`), used only by the
148    /// `B_PRED` path's §12.3 right-edge sub-blocks (3, 7, 11, 15).
149    ///
150    /// `None` means the macroblock is on the top row of the frame, in
151    /// which case §12.3 page 55 fixes all four extra pixels at 127
152    /// ([`crate::intra_predict::DEFAULT_ABOVE_PIXEL`]). When `Some`, the
153    /// caller has already applied the rightmost-macroblock clamp (all
154    /// four equal to the `(-1, 15)` pixel) where it applies; this
155    /// orchestrator copies the four values verbatim into the working
156    /// buffer. The 16×16 luma modes never read this field.
157    pub y_above_right: Option<[u8; 4]>,
158    /// Luma pixel at `(-1, -1)`. Only `TM_PRED` reads it; the
159    /// §12 kernels substitute [`crate::intra_predict::DEFAULT_TOPLEFT_DC`]
160    /// when `None`.
161    pub y_topleft: Option<u8>,
162    /// Eight chroma-U pixels immediately above the MB.
163    pub u_above: Option<[u8; 8]>,
164    /// Eight chroma-U pixels immediately to the left of the MB.
165    pub u_left: Option<[u8; 8]>,
166    /// Chroma-U pixel at `(-1, -1)`.
167    pub u_topleft: Option<u8>,
168    /// Eight chroma-V pixels immediately above the MB.
169    pub v_above: Option<[u8; 8]>,
170    /// Eight chroma-V pixels immediately to the left of the MB.
171    pub v_left: Option<[u8; 8]>,
172    /// Chroma-V pixel at `(-1, -1)`.
173    pub v_topleft: Option<u8>,
174}
175
176/// Reconstructed pixel output for one macroblock.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub struct ReconstructedMb {
179    /// 16×16 luma pixels in row-major (raster) order.
180    pub y: [u8; 256],
181    /// 8×8 U chroma pixels in row-major order.
182    pub u: [u8; 64],
183    /// 8×8 V chroma pixels in row-major order.
184    pub v: [u8; 64],
185}
186
187impl Default for ReconstructedMb {
188    fn default() -> Self {
189        ReconstructedMb {
190            y: [0u8; 256],
191            u: [0u8; 64],
192            v: [0u8; 64],
193        }
194    }
195}
196
197/// Errors surfaced by the reconstruction orchestrator.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199#[non_exhaustive]
200pub enum ReconstructError {
201    /// [`decode_keyframe_mb_non_bpred`] was called with
202    /// `y_mode == IntraYMode::B`. The 16×16 orchestrator handles only
203    /// the four 16×16 luma modes (`DC_PRED` / `V_PRED` / `H_PRED` /
204    /// `TM_PRED`); `B_PRED` macroblocks go through
205    /// [`decode_keyframe_mb_bpred`] instead, which drives the
206    /// per-sub-block neighbour-evolution walk §12.3 specifies.
207    BPredNotSupported,
208    /// [`decode_keyframe_mb_bpred`] was called for a macroblock whose
209    /// `subblock_modes` record is absent. A `B_PRED` macroblock always
210    /// carries sixteen decoded 4×4 sub-block modes (§11.3); a missing
211    /// record means the caller routed a non-`B_PRED` macroblock here by
212    /// mistake.
213    MissingSubblockModes,
214}
215
216impl core::fmt::Display for ReconstructError {
217    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
218        match self {
219            ReconstructError::BPredNotSupported => f.write_str(
220                "vp8 reconstruct: B_PRED MBs require the per-sub-block intra walker — \
221                 use decode_keyframe_mb_bpred, not decode_keyframe_mb_non_bpred",
222            ),
223            ReconstructError::MissingSubblockModes => f.write_str(
224                "vp8 reconstruct: decode_keyframe_mb_bpred needs sixteen 4x4 sub-block \
225                 modes; the supplied record has none (non-B_PRED MB routed here?)",
226            ),
227        }
228    }
229}
230
231impl std::error::Error for ReconstructError {}
232
233/// Copy a 4×4 block at sub-block position `(by, bx)` (in 4-pixel
234/// units) out of a row-major plane of stride `plane_stride` pixels.
235#[inline]
236fn extract_4x4(plane: &[u8], plane_stride: usize, by: usize, bx: usize) -> [u8; 16] {
237    let mut out = [0u8; 16];
238    let y0 = by * 4;
239    let x0 = bx * 4;
240    for r in 0..4 {
241        let src = (y0 + r) * plane_stride + x0;
242        let dst = r * 4;
243        out[dst..dst + 4].copy_from_slice(&plane[src..src + 4]);
244    }
245    out
246}
247
248/// Splat a 4×4 block back into a row-major plane.
249#[inline]
250fn insert_4x4(plane: &mut [u8], plane_stride: usize, by: usize, bx: usize, src: &[u8; 16]) {
251    let y0 = by * 4;
252    let x0 = bx * 4;
253    for r in 0..4 {
254        let dst = (y0 + r) * plane_stride + x0;
255        let s = r * 4;
256        plane[dst..dst + 4].copy_from_slice(&src[s..s + 4]);
257    }
258}
259
260/// Reconstruct one macroblock whose Y mode is one of the four 16×16
261/// modes (`DC_PRED` / `V_PRED` / `H_PRED` / `TM_PRED`), per RFC 6386
262/// §14.2.
263///
264/// # Inputs
265///
266/// * `y_mode` — the §11.2 16×16 luma intra mode. Must not be
267///   [`IntraYMode::B`]; passing it returns
268///   [`ReconstructError::BPredNotSupported`].
269/// * `uv_mode` — the §11.4 8×8 chroma intra mode (always one of four
270///   variants; chroma never has a `B_PRED` analogue).
271/// * `mb_skip_coeff` — the §11.1 skip flag. When `true`, the entire
272///   residue is zero and the four coefficient arrays are ignored; the
273///   reconstructed pixels equal the prediction.
274/// * `neighbors` — the surrounding pixel context the §12 kernels read
275///   (see [`MbNeighbors`]).
276/// * `y2_coeffs_dequant` — the dequantized Y2 (25th-block) WHT
277///   coefficients in row-major order. Inverse-WHT is applied here and
278///   each element of the result seeds the DC of one Y sub-block per
279///   §14.2.
280/// * `y_coeffs_dequant` — the sixteen dequantized Y sub-block DCT
281///   coefficient arrays in raster sub-block order (sub-block index
282///   `i * 4 + j` for row `i`, column `j` of the 4×4 sub-block grid).
283///   The DC slot of each entry is overwritten with the WHT result
284///   before the inverse DCT is applied.
285/// * `u_coeffs_dequant` / `v_coeffs_dequant` — the eight chroma
286///   sub-block coefficient arrays, four U then four V, in raster
287///   sub-block order (`i * 2 + j` for the 2×2 chroma grid).
288///
289/// # Output
290///
291/// A fully reconstructed macroblock — the predictor-plus-residue sum
292/// with `clamp255` saturation, before loop filtering.
293#[allow(clippy::too_many_arguments)] // each parameter is a distinct §14.2 input;
294// bundling them into a struct would obscure the spec mapping.
295pub fn decode_keyframe_mb_non_bpred(
296    y_mode: IntraYMode,
297    uv_mode: IntraUvMode,
298    mb_skip_coeff: bool,
299    neighbors: &MbNeighbors,
300    y2_coeffs_dequant: &[i16; 16],
301    y_coeffs_dequant: &[[i16; 16]; 16],
302    u_coeffs_dequant: &[[i16; 16]; 4],
303    v_coeffs_dequant: &[[i16; 16]; 4],
304) -> Result<ReconstructedMb, ReconstructError> {
305    if y_mode == IntraYMode::B {
306        return Err(ReconstructError::BPredNotSupported);
307    }
308
309    let mut out = ReconstructedMb::default();
310
311    // Step 3 (done first because we always need it, even on skip MBs):
312    // intra prediction into the output buffers.
313    //
314    // The corner pixel (-1, -1) is read only by TM_PRED. A `None` here
315    // means the corner is off the top frame edge (the frame walker
316    // supplies `Some(129)` for the left-frame-edge corner and the genuine
317    // reconstructed pixel for interior macroblocks), so it defaults to the
318    // §12 `DEFAULT_ABOVE_PIXEL` (127) — the value §20.14 `fixup_above`
319    // assigns the off-top corner.
320    let topleft_y = neighbors.y_topleft.unwrap_or(DEFAULT_ABOVE_PIXEL);
321    predict_y16x16(
322        &mut out.y,
323        y_mode,
324        neighbors.y_above.as_ref(),
325        neighbors.y_left.as_ref(),
326        topleft_y,
327    )
328    // predict_y16x16 returns Option<()> only to distinguish the B_PRED
329    // case; we've rejected B above, so this is always Some.
330    .expect("y_mode rejected B_PRED at function entry");
331
332    let topleft_u = neighbors.u_topleft.unwrap_or(DEFAULT_ABOVE_PIXEL);
333    predict_uv8x8(
334        &mut out.u,
335        uv_mode,
336        neighbors.u_above.as_ref(),
337        neighbors.u_left.as_ref(),
338        topleft_u,
339    );
340    let topleft_v = neighbors.v_topleft.unwrap_or(DEFAULT_ABOVE_PIXEL);
341    predict_uv8x8(
342        &mut out.v,
343        uv_mode,
344        neighbors.v_above.as_ref(),
345        neighbors.v_left.as_ref(),
346        topleft_v,
347    );
348
349    if mb_skip_coeff {
350        // §11.1: skip flag → zero residue → reconstructed pixels equal
351        // prediction. No transform work needed; out already holds the
352        // prediction.
353        return Ok(out);
354    }
355
356    // Step 1 (§14.2 first paragraph): if Y2 exists, inverse-WHT and
357    // seed each Y sub-block's DC. For all four 16×16 modes the Y2
358    // block exists (it's absent only for B_PRED and SPLITMV).
359    let mut y2_residue = [0i16; 16];
360    inverse_wht_4x4(y2_coeffs_dequant, &mut y2_residue);
361
362    // Copy the Y coefficients so we can splice in the WHT seeds without
363    // mutating the caller's input.
364    let mut y_coeffs = *y_coeffs_dequant;
365    for i in 0..4 {
366        for j in 0..4 {
367            // §14.2: y2_residue[i*4+j] seeds Y sub-block (i,j)'s
368            // coefficient 0.
369            y_coeffs[i * 4 + j][0] = y2_residue[i * 4 + j];
370        }
371    }
372
373    // Step 2 (§14.2 second paragraph): inverse-DCT all 16 Y +
374    // 8 chroma sub-blocks. Step 4 (§14.5): add to prediction with
375    // clamp255 and store back into the output buffer.
376    for i in 0..4 {
377        for j in 0..4 {
378            let idx = i * 4 + j;
379            let mut residue = [0i16; 16];
380            inverse_dct_4x4(&y_coeffs[idx], &mut residue);
381            let pred = extract_4x4(&out.y, 16, i, j);
382            let mut summed = [0u8; 16];
383            add_residue_4x4(&pred, &residue, &mut summed);
384            insert_4x4(&mut out.y, 16, i, j, &summed);
385        }
386    }
387    for i in 0..2 {
388        for j in 0..2 {
389            let idx = i * 2 + j;
390            let mut residue = [0i16; 16];
391            inverse_dct_4x4(&u_coeffs_dequant[idx], &mut residue);
392            let pred = extract_4x4(&out.u, 8, i, j);
393            let mut summed = [0u8; 16];
394            add_residue_4x4(&pred, &residue, &mut summed);
395            insert_4x4(&mut out.u, 8, i, j, &summed);
396
397            let mut residue = [0i16; 16];
398            inverse_dct_4x4(&v_coeffs_dequant[idx], &mut residue);
399            let pred = extract_4x4(&out.v, 8, i, j);
400            let mut summed = [0u8; 16];
401            add_residue_4x4(&pred, &residue, &mut summed);
402            insert_4x4(&mut out.v, 8, i, j, &summed);
403        }
404    }
405
406    Ok(out)
407}
408
409// ===========================================================================
410// §11.3 / §12.3 B_PRED macroblock reconstruction
411// ===========================================================================
412
413/// Stride (pixels per row) of the `B_PRED` working luma buffer.
414///
415/// Layout per row: `[ left-border (1) | 16 reconstruction columns |
416/// above-right extension (4) ]` = 21 columns. The four-pixel extension
417/// lets the §12.3 right-edge sub-blocks (3, 7, 11, 15) read their
418/// shared above-and-to-the-right pixels at a constant stride.
419const BPRED_STRIDE: usize = 1 + 16 + 4;
420
421/// Number of rows in the `B_PRED` working luma buffer: one top-border
422/// row plus the sixteen reconstruction rows.
423const BPRED_ROWS: usize = 1 + 16;
424
425/// Flat index of the working buffer's reconstruction origin `(0, 0)`
426/// — i.e. one row down (past the top border) and one column right
427/// (past the left border).
428const BPRED_ORIGIN: usize = BPRED_STRIDE + 1;
429
430/// Reconstruct one macroblock whose Y mode is `B_PRED` (RFC 6386 §11.3
431/// / §12.3), driving the sixteen 4×4 luma sub-blocks with the
432/// per-sub-block neighbour evolution the spec requires.
433///
434/// The chroma planes use the 8×8 §12.2 mode in `uv_mode`, identically
435/// to [`decode_keyframe_mb_non_bpred`]; only the luma plane differs.
436///
437/// # Inputs
438///
439/// * `subblock_modes` — the sixteen §11.3 4×4 luma sub-block modes in
440///   raster order (sub-block index `i * 4 + j` for row `i`, column `j`).
441///   This is the `MacroblockModes::subblock_modes` field; it must be
442///   `Some` for a `B_PRED` macroblock.
443/// * `uv_mode` — the §11.4 8×8 chroma intra mode.
444/// * `mb_skip_coeff` — the §11.1 skip flag. When `true` the residue is
445///   zero: each sub-block's reconstructed pixels equal its prediction,
446///   and the neighbour evolution still proceeds (a sub-block's `above` /
447///   `left` are then its neighbours' *predictions*, which is the correct
448///   reconstructed value when the residue is zero).
449/// * `neighbors` — the surrounding pixel context (see [`MbNeighbors`]).
450///   `B_PRED` reads `y_above`, `y_left`, `y_topleft`, the chroma fields,
451///   and additionally [`MbNeighbors::y_above_right`].
452/// * `y_coeffs_dequant` — the sixteen dequantized Y sub-block DCT
453///   coefficient arrays in raster sub-block order. Unlike the 16×16
454///   path, **no WHT seeding is applied**: §13 / §14.2 specify that a
455///   `B_PRED` macroblock has no Y2 block and the 0th coefficient of each
456///   Y sub-block is part of that sub-block's own residue. The caller
457///   supplies the coefficients verbatim.
458/// * `u_coeffs_dequant` / `v_coeffs_dequant` — the eight chroma
459///   sub-block coefficient arrays, four U then four V, in raster order.
460///
461/// # Output
462///
463/// A fully reconstructed macroblock (predictor + residue, `clamp255`),
464/// before loop filtering.
465#[allow(clippy::too_many_arguments)] // each parameter is a distinct §12.3 / §14.2 input.
466pub fn decode_keyframe_mb_bpred(
467    subblock_modes: Option<&[IntraBmode; 16]>,
468    uv_mode: IntraUvMode,
469    mb_skip_coeff: bool,
470    neighbors: &MbNeighbors,
471    y_coeffs_dequant: &[[i16; 16]; 16],
472    u_coeffs_dequant: &[[i16; 16]; 4],
473    v_coeffs_dequant: &[[i16; 16]; 4],
474) -> Result<ReconstructedMb, ReconstructError> {
475    let modes = subblock_modes.ok_or(ReconstructError::MissingSubblockModes)?;
476
477    let mut out = ReconstructedMb::default();
478
479    // ----- Luma (§12.3 B_PRED): per-sub-block walk -----------------
480    let mut buf = build_bpred_work_buffer(neighbors);
481
482    for i in 0..4 {
483        for j in 0..4 {
484            let idx = i * 4 + j;
485            // Top-left pixel of this sub-block inside the working buffer.
486            let sb_base = BPRED_ORIGIN + (i * 4) * BPRED_STRIDE + (j * 4);
487
488            // Gather the §12.3 neighbour inputs from the (evolving)
489            // working buffer:
490            //   above[0..4] = the four pixels directly above the
491            //                 sub-block (row -1, cols 0..3);
492            //   above[4..8] = the four pixels above-and-to-the-right
493            //                 (row -1, cols 4..7);
494            //   left[0..4]  = the four pixels in the column to the left
495            //                 (rows 0..3, col -1);
496            //   p           = the pixel at (-1, -1).
497            let above_base = sb_base - BPRED_STRIDE; // row -1, col 0
498            let mut above = [0u8; 8];
499            above.copy_from_slice(&buf[above_base..above_base + 8]);
500            let mut left = [0u8; 4];
501            for (r, slot) in left.iter_mut().enumerate() {
502                *slot = buf[sb_base + r * BPRED_STRIDE - 1];
503            }
504            let p = buf[above_base - 1];
505
506            // Predict this sub-block into a scratch 4×4.
507            let mut pred = [0u8; 16];
508            predict_b4x4(&mut pred, modes[idx], &above, &left, p);
509
510            // §14.5: add the residue (zero when skipping) to the
511            // prediction, then write the reconstructed sub-block back
512            // into the working buffer so it becomes a neighbour for the
513            // sub-blocks below / to its right.
514            let mut recon = [0u8; 16];
515            if mb_skip_coeff {
516                recon = pred;
517            } else {
518                let mut residue = [0i16; 16];
519                inverse_dct_4x4(&y_coeffs_dequant[idx], &mut residue);
520                add_residue_4x4(&pred, &residue, &mut recon);
521            }
522            for r in 0..4 {
523                let dst = sb_base + r * BPRED_STRIDE;
524                buf[dst..dst + 4].copy_from_slice(&recon[r * 4..r * 4 + 4]);
525            }
526        }
527    }
528
529    // Copy the reconstructed 16×16 luma area out of the working buffer
530    // into the contiguous output plane.
531    for r in 0..16 {
532        let src = BPRED_ORIGIN + r * BPRED_STRIDE;
533        out.y[r * 16..r * 16 + 16].copy_from_slice(&buf[src..src + 16]);
534    }
535
536    // ----- Chroma (§12.2): identical to the non-B_PRED path --------
537    // Off-frame chroma top-left defaults to DEFAULT_ABOVE_PIXEL (127), the
538    // RFC 6386 §12.2 above-row default — matching the non-B_PRED path above
539    // and the encoder. Only TM_PRED reads this corner; defaulting to 0 here
540    // diverged U/V on top-row B_PRED MBs while luma stayed byte-identical.
541    let topleft_u = neighbors.u_topleft.unwrap_or(DEFAULT_ABOVE_PIXEL);
542    predict_uv8x8(
543        &mut out.u,
544        uv_mode,
545        neighbors.u_above.as_ref(),
546        neighbors.u_left.as_ref(),
547        topleft_u,
548    );
549    let topleft_v = neighbors.v_topleft.unwrap_or(DEFAULT_ABOVE_PIXEL);
550    predict_uv8x8(
551        &mut out.v,
552        uv_mode,
553        neighbors.v_above.as_ref(),
554        neighbors.v_left.as_ref(),
555        topleft_v,
556    );
557
558    if !mb_skip_coeff {
559        for i in 0..2 {
560            for j in 0..2 {
561                let idx = i * 2 + j;
562                let mut residue = [0i16; 16];
563                inverse_dct_4x4(&u_coeffs_dequant[idx], &mut residue);
564                let pred = extract_4x4(&out.u, 8, i, j);
565                let mut summed = [0u8; 16];
566                add_residue_4x4(&pred, &residue, &mut summed);
567                insert_4x4(&mut out.u, 8, i, j, &summed);
568
569                let mut residue = [0i16; 16];
570                inverse_dct_4x4(&v_coeffs_dequant[idx], &mut residue);
571                let pred = extract_4x4(&out.v, 8, i, j);
572                let mut summed = [0u8; 16];
573                add_residue_4x4(&pred, &residue, &mut summed);
574                insert_4x4(&mut out.v, 8, i, j, &summed);
575            }
576        }
577    }
578
579    Ok(out)
580}
581
582/// Build the `B_PRED` working luma buffer with its border row / column
583/// pre-filled from the macroblock's neighbours, and apply the §12.3
584/// right-edge "above-right" fixup (the reference decoder's `copy_down`).
585///
586/// The returned buffer is [`BPRED_ROWS`] rows of [`BPRED_STRIDE`] pixels.
587/// The reconstruction area (`out.y` equivalent) lives at flat offset
588/// [`BPRED_ORIGIN`] with the buffer stride.
589fn build_bpred_work_buffer(neighbors: &MbNeighbors) -> [u8; BPRED_ROWS * BPRED_STRIDE] {
590    let mut buf = [0u8; BPRED_ROWS * BPRED_STRIDE];
591
592    // --- Top border row (buffer row 0) -----------------------------
593    // Columns of the border row, in buffer coordinates:
594    //   col 0          → the (-1, -1) top-left pixel P;
595    //   cols 1..=16    → the 16 above pixels (-1, 0)..=(-1, 15);
596    //   cols 17..=20   → the 4 above-right pixels (-1, 16)..=(-1, 19).
597    let above = neighbors.y_above.unwrap_or([DEFAULT_ABOVE_PIXEL; 16]);
598    // §12 / reference `fixup_above`: when the row above is off-frame the
599    // whole above row *and* the (-1, -1) corner are 127. The frame
600    // walker (the layer above this orchestrator) is responsible for
601    // populating `y_topleft` with the genuine reconstructed corner pixel
602    // when one exists — including the 129 the left-frame-edge corner
603    // takes per `fixup_left`. A `None` here means off-top-edge → 127.
604    let topleft = neighbors.y_topleft.unwrap_or(DEFAULT_ABOVE_PIXEL);
605    buf[0] = topleft;
606    buf[1..17].copy_from_slice(&above);
607    // Above-right extension. When `y_above_right` is None (top MB row)
608    // §12.3 fixes the four pixels at 127.
609    let above_right = neighbors.y_above_right.unwrap_or([DEFAULT_ABOVE_PIXEL; 4]);
610    buf[17..21].copy_from_slice(&above_right);
611
612    // --- Left border column (buffer rows 1..=16, col 0) ------------
613    // §12: left neighbours are 129 (DEFAULT_LEFT_PIXEL) when the MB is
614    // on the left column of the frame.
615    let left = neighbors.y_left.unwrap_or([DEFAULT_LEFT_PIXEL; 16]);
616    for (r, &v) in left.iter().enumerate() {
617        buf[(r + 1) * BPRED_STRIDE] = v;
618    }
619
620    // --- §12.3 right-edge fixup (reference `copy_down`) ------------
621    // The four pixels above-and-to-the-right of sub-block 3 (border row,
622    // cols 17..=20) are copied into the four border slots that sit
623    // immediately above sub-blocks 7, 11, and 15 — i.e. the rows above
624    // sub-block rows 1, 2, 3 at reconstruction columns 16..=19. Those
625    // rows are reconstruction rows 3, 7, 11 (zero-based), which map to
626    // buffer rows 4, 8, 12, columns BPRED_ORIGIN-column-wise at recon
627    // cols 16..=19 → buffer cols (1 + 16)..=(1 + 19) = 17..=20.
628    let extra = [buf[17], buf[18], buf[19], buf[20]];
629    for &recon_row_above in &[3usize, 7, 11] {
630        // Sub-blocks 7/11/15 begin at reconstruction rows 4/8/12; their
631        // "above" border lives at reconstruction row 3/7/11.
632        let buf_row = 1 + recon_row_above; // +1 for the top border row.
633        let base = buf_row * BPRED_STRIDE + 17; // recon col 16 → buf col 17.
634        buf[base..base + 4].copy_from_slice(&extra);
635    }
636
637    buf
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643    use crate::intra_predict::DEFAULT_TOPLEFT_DC;
644
645    /// Convenience type alias for the four coefficient bundles
646    /// `zero_coeffs` returns (Y2, sixteen Y, four U, four V).
647    type CoeffBundle = ([i16; 16], [[i16; 16]; 16], [[i16; 16]; 4], [[i16; 16]; 4]);
648
649    /// All-zero coefficients in every block.
650    fn zero_coeffs() -> CoeffBundle {
651        (
652            [0i16; 16],
653            [[0i16; 16]; 16],
654            [[0i16; 16]; 4],
655            [[0i16; 16]; 4],
656        )
657    }
658
659    #[test]
660    fn bpred_yields_error() {
661        let (y2, y, u, v) = zero_coeffs();
662        let res = decode_keyframe_mb_non_bpred(
663            IntraYMode::B,
664            IntraUvMode::Dc,
665            false,
666            &MbNeighbors::default(),
667            &y2,
668            &y,
669            &u,
670            &v,
671        );
672        assert_eq!(res, Err(ReconstructError::BPredNotSupported));
673    }
674
675    #[test]
676    fn skip_mb_equals_prediction_dc_mode_top_left_corner() {
677        // A top-left corner MB with skip=true and DC_PRED in both
678        // planes. Per §12.2 page 53, DC_PRED with no neighbours uses
679        // 128 for both Y and chroma (DEFAULT_TOPLEFT_DC). With skip=
680        // true the residue is zero, so every reconstructed pixel must
681        // be 128.
682        let (y2, y, u, v) = zero_coeffs();
683        let out = decode_keyframe_mb_non_bpred(
684            IntraYMode::Dc,
685            IntraUvMode::Dc,
686            true,
687            &MbNeighbors::default(),
688            &y2,
689            &y,
690            &u,
691            &v,
692        )
693        .expect("non-bpred path");
694        assert!(out.y.iter().all(|&p| p == DEFAULT_TOPLEFT_DC));
695        assert!(out.u.iter().all(|&p| p == DEFAULT_TOPLEFT_DC));
696        assert!(out.v.iter().all(|&p| p == DEFAULT_TOPLEFT_DC));
697    }
698
699    #[test]
700    fn skip_mb_matches_standalone_intra_predict_v_mode() {
701        // V_PRED in luma + V_PRED in chroma with known `above` strips.
702        // skip=true → output must match a standalone predict_*_v call.
703        let y_above = [50u8; 16];
704        let u_above = [60u8; 8];
705        let v_above = [70u8; 8];
706
707        let neighbors = MbNeighbors {
708            y_above: Some(y_above),
709            u_above: Some(u_above),
710            v_above: Some(v_above),
711            ..MbNeighbors::default()
712        };
713        let (y2, y, u, v) = zero_coeffs();
714        let out = decode_keyframe_mb_non_bpred(
715            IntraYMode::V,
716            IntraUvMode::V,
717            true,
718            &neighbors,
719            &y2,
720            &y,
721            &u,
722            &v,
723        )
724        .expect("non-bpred path");
725
726        let mut expect_y = [0u8; 256];
727        predict_y16x16(&mut expect_y, IntraYMode::V, Some(&y_above), None, 0).unwrap();
728        let mut expect_u = [0u8; 64];
729        predict_uv8x8(&mut expect_u, IntraUvMode::V, Some(&u_above), None, 0);
730        let mut expect_v = [0u8; 64];
731        predict_uv8x8(&mut expect_v, IntraUvMode::V, Some(&v_above), None, 0);
732
733        assert_eq!(out.y, expect_y);
734        assert_eq!(out.u, expect_u);
735        assert_eq!(out.v, expect_v);
736    }
737
738    #[test]
739    fn zero_residue_non_skip_also_equals_prediction() {
740        // With skip=false but all coefficients zero, the WHT and the
741        // sixteen DCT inversions all yield zero residues, so the
742        // reconstructed pixels still equal the prediction — but this
743        // time the §14.2 orchestration path is exercised (all the
744        // transforms run, all the adds run; they just contribute 0).
745        let y_above = [80u8; 16];
746        let y_left = [90u8; 16];
747        let u_above = [100u8; 8];
748        let u_left = [110u8; 8];
749        let v_above = [120u8; 8];
750        let v_left = [130u8; 8];
751        let neighbors = MbNeighbors {
752            y_above: Some(y_above),
753            y_left: Some(y_left),
754            y_topleft: Some(85),
755            u_above: Some(u_above),
756            u_left: Some(u_left),
757            u_topleft: Some(105),
758            v_above: Some(v_above),
759            v_left: Some(v_left),
760            v_topleft: Some(125),
761            ..MbNeighbors::default()
762        };
763        let (y2, y, u, v) = zero_coeffs();
764        let out_skip = decode_keyframe_mb_non_bpred(
765            IntraYMode::Tm,
766            IntraUvMode::Tm,
767            true,
768            &neighbors,
769            &y2,
770            &y,
771            &u,
772            &v,
773        )
774        .unwrap();
775        let out_run = decode_keyframe_mb_non_bpred(
776            IntraYMode::Tm,
777            IntraUvMode::Tm,
778            false,
779            &neighbors,
780            &y2,
781            &y,
782            &u,
783            &v,
784        )
785        .unwrap();
786        assert_eq!(out_skip.y, out_run.y);
787        assert_eq!(out_skip.u, out_run.u);
788        assert_eq!(out_skip.v, out_run.v);
789    }
790
791    #[test]
792    fn y2_dc_only_seeds_y_subblock_dc_and_lifts_pixels() {
793        // Put a single non-zero DC in Y2 and verify the §14.2 seeding
794        // contract: the WHT of an all-zero-except-DC=8 block is the
795        // flat array `[1, 1, 1, 1, ..., 1]` (16 ones) — see the
796        // existing `wht_dc_only_matches_general_path` test in
797        // inverse_transform.rs. Each of the sixteen Y sub-blocks then
798        // gets coefficient[0] = 1 spliced in. The inverse DCT of an
799        // all-zero-except-DC=1 4×4 block is, per §14.4's two-pass
800        // arithmetic with `(x + 4) >> 3` rounding, all zero (1*8 = 8,
801        // (8+4)>>3 = 1, then again (1+4)>>3 = 0 — actually let's not
802        // rely on a hand derivation here; we verify it empirically).
803        let mut y2 = [0i16; 16];
804        y2[0] = 8;
805        let (_, y, u, v) = zero_coeffs();
806
807        // Top-left corner MB with DC_PRED everywhere — every prediction
808        // pixel = 128, all chroma residue = 0.
809        let out = decode_keyframe_mb_non_bpred(
810            IntraYMode::Dc,
811            IntraUvMode::Dc,
812            false,
813            &MbNeighbors::default(),
814            &y2,
815            &y,
816            &u,
817            &v,
818        )
819        .unwrap();
820
821        // Empirically derive the expected per-pixel residue: WHT
822        // distributes DC=8 as `1` into every Y sub-block's slot 0,
823        // then inverse_dct_4x4 with input[0]=1 (and the rest zero) is
824        // computed and added to the 128 prediction.
825        let mut seed = [0i16; 16];
826        seed[0] = 1;
827        let mut residue4x4 = [0i16; 16];
828        inverse_dct_4x4(&seed, &mut residue4x4);
829        let pred4x4 = [DEFAULT_TOPLEFT_DC; 16];
830        let mut expect_sub = [0u8; 16];
831        add_residue_4x4(&pred4x4, &residue4x4, &mut expect_sub);
832
833        // Every Y sub-block must equal `expect_sub` since they all see
834        // the same prediction value (128) and the same WHT-seed (1).
835        for i in 0..4 {
836            for j in 0..4 {
837                let got = extract_4x4(&out.y, 16, i, j);
838                assert_eq!(
839                    got, expect_sub,
840                    "sub-block ({i},{j}) mismatch — y2 DC distribution broken"
841                );
842            }
843        }
844
845        // Chroma residue was zero everywhere → chroma equals prediction.
846        assert!(out.u.iter().all(|&p| p == DEFAULT_TOPLEFT_DC));
847        assert!(out.v.iter().all(|&p| p == DEFAULT_TOPLEFT_DC));
848    }
849
850    #[test]
851    fn y2_off_diagonal_seeds_distinct_subblocks_per_142_index_rule() {
852        // Drive a Y2 input that, after the inverse WHT, produces a
853        // distinguishable residue at row 0 column 0 versus row 1
854        // column 0 versus row 0 column 1. Per §14.2 these distinct
855        // values must seed sub-block (0,0), sub-block (1,0)=index 4
856        // and sub-block (0,1)=index 1 respectively — proving the
857        // `i * 4 + j` index rule.
858        //
859        // From the existing `wht_hand_derived_two_value_input` test
860        // in inverse_transform.rs, with input[0]=8 and input[4]=8:
861        //   WHT output = [2,2,2,2, 2,2,2,2, 0,0,0,0, 0,0,0,0]
862        // So sub-blocks (0,0)/(0,1)/(0,2)/(0,3) and (1,0)/(1,1)/(1,2)
863        // /(1,3) get DC seed 2, while (2,*)/(3,*) get DC seed 0.
864        let mut y2 = [0i16; 16];
865        y2[0] = 8;
866        y2[4] = 8;
867        let (_, y, u, v) = zero_coeffs();
868
869        let out = decode_keyframe_mb_non_bpred(
870            IntraYMode::Dc,
871            IntraUvMode::Dc,
872            false,
873            &MbNeighbors::default(),
874            &y2,
875            &y,
876            &u,
877            &v,
878        )
879        .unwrap();
880
881        let mut seed_lit = [0i16; 16];
882        seed_lit[0] = 2;
883        let mut residue_lit = [0i16; 16];
884        inverse_dct_4x4(&seed_lit, &mut residue_lit);
885        let pred = [DEFAULT_TOPLEFT_DC; 16];
886        let mut expect_lit = [0u8; 16];
887        add_residue_4x4(&pred, &residue_lit, &mut expect_lit);
888
889        let mut seed_zero = [0i16; 16];
890        seed_zero[0] = 0;
891        let mut residue_zero = [0i16; 16];
892        inverse_dct_4x4(&seed_zero, &mut residue_zero);
893        let mut expect_zero = [0u8; 16];
894        add_residue_4x4(&pred, &residue_zero, &mut expect_zero);
895
896        // Rows 0..2 are "lit" (DC=2); rows 2..4 are "zero" (DC=0).
897        for i in 0..4 {
898            for j in 0..4 {
899                let got = extract_4x4(&out.y, 16, i, j);
900                let expected = if i < 2 { expect_lit } else { expect_zero };
901                assert_eq!(
902                    got, expected,
903                    "sub-block ({i},{j}) wrong — i*4+j index rule violated"
904                );
905            }
906        }
907    }
908
909    #[test]
910    fn neighbour_defaults_drive_v_mode_when_above_absent() {
911        // V_PRED with no `above` neighbour: §12 substitutes
912        // DEFAULT_ABOVE_PIXEL = 127. Verify the orchestrator forwards
913        // the substitution by checking the luma output equals 127
914        // everywhere (skip MB, zero residue).
915        let (y2, y, u, v) = zero_coeffs();
916        let out = decode_keyframe_mb_non_bpred(
917            IntraYMode::V,
918            IntraUvMode::V,
919            true,
920            &MbNeighbors::default(),
921            &y2,
922            &y,
923            &u,
924            &v,
925        )
926        .unwrap();
927        assert!(out.y.iter().all(|&p| p == DEFAULT_ABOVE_PIXEL));
928        assert!(out.u.iter().all(|&p| p == DEFAULT_ABOVE_PIXEL));
929    }
930
931    #[test]
932    fn neighbour_defaults_drive_h_mode_when_left_absent() {
933        let (y2, y, u, v) = zero_coeffs();
934        let out = decode_keyframe_mb_non_bpred(
935            IntraYMode::H,
936            IntraUvMode::H,
937            true,
938            &MbNeighbors::default(),
939            &y2,
940            &y,
941            &u,
942            &v,
943        )
944        .unwrap();
945        assert!(out.y.iter().all(|&p| p == DEFAULT_LEFT_PIXEL));
946        assert!(out.v.iter().all(|&p| p == DEFAULT_LEFT_PIXEL));
947    }
948
949    #[test]
950    fn residue_summation_saturates_high_per_145() {
951        // Drive an MB where the Y residue plus a normal-range V_PRED
952        // prediction overflows past 255, and verify the §14.5
953        // clamp255 step is applied (instead of wrapping at u8).
954        //
955        // §14.2 overwrites every Y sub-block's coefficient[0] with
956        // the Y2 WHT result, so we drive the saturation through Y2.
957        // A Y2 input of `[8000, 0, ...]` produces a WHT output that
958        // distributes large values into every Y sub-block's DC; the
959        // per-sub-block inverse DCT then yields per-pixel residues
960        // well over +1000.
961        let mut y2 = [0i16; 16];
962        y2[0] = 8000;
963        let y = [[0i16; 16]; 16];
964        let (_, _, u, v) = zero_coeffs();
965
966        let y_above = [200u8; 16];
967        let neighbors = MbNeighbors {
968            y_above: Some(y_above),
969            ..MbNeighbors::default()
970        };
971        let out = decode_keyframe_mb_non_bpred(
972            IntraYMode::V,
973            IntraUvMode::Dc,
974            false,
975            &neighbors,
976            &y2,
977            &y,
978            &u,
979            &v,
980        )
981        .unwrap();
982
983        // Every luma pixel must clamp to 255 (residue + 200 ≫ 255 in
984        // every sub-block) — proves clamp255 is wired into the
985        // summation step rather than wrapping at u8.
986        assert!(
987            out.y.iter().all(|&p| p == 255),
988            "expected 255 saturation everywhere in Y plane; got first pixel {}",
989            out.y[0]
990        );
991    }
992
993    #[test]
994    fn residue_summation_saturates_low_per_145() {
995        // Symmetric to the high-saturation test: negative Y2 input,
996        // small prediction, every pixel must clamp to 0.
997        let mut y2 = [0i16; 16];
998        y2[0] = -8000;
999        let y = [[0i16; 16]; 16];
1000        let (_, _, u, v) = zero_coeffs();
1001
1002        let y_above = [40u8; 16];
1003        let neighbors = MbNeighbors {
1004            y_above: Some(y_above),
1005            ..MbNeighbors::default()
1006        };
1007        let out = decode_keyframe_mb_non_bpred(
1008            IntraYMode::V,
1009            IntraUvMode::Dc,
1010            false,
1011            &neighbors,
1012            &y2,
1013            &y,
1014            &u,
1015            &v,
1016        )
1017        .unwrap();
1018
1019        assert!(
1020            out.y.iter().all(|&p| p == 0),
1021            "expected 0 saturation everywhere in Y plane; got first pixel {}",
1022            out.y[0]
1023        );
1024    }
1025
1026    #[test]
1027    fn extract_and_insert_4x4_roundtrip() {
1028        // Tiny helper test: extract + insert is a no-op (modulo unrelated
1029        // bytes), guarding against an off-by-one in the orchestrator's
1030        // address math.
1031        let mut plane = [0u8; 256];
1032        for (i, slot) in plane.iter_mut().enumerate() {
1033            *slot = i as u8;
1034        }
1035        // Save sub-block (2,1) (rows 8..12, cols 4..8).
1036        let got = extract_4x4(&plane, 16, 2, 1);
1037        // Expected: row r, col c → byte at (8+r)*16 + (4+c).
1038        for r in 0..4 {
1039            for c in 0..4 {
1040                assert_eq!(got[r * 4 + c], ((8 + r) * 16 + (4 + c)) as u8);
1041            }
1042        }
1043        // Zero it out, then re-insert and verify the plane is restored.
1044        let zeros = [0u8; 16];
1045        insert_4x4(&mut plane, 16, 2, 1, &zeros);
1046        for r in 0..4 {
1047            for c in 0..4 {
1048                assert_eq!(plane[(8 + r) * 16 + (4 + c)], 0);
1049            }
1050        }
1051        insert_4x4(&mut plane, 16, 2, 1, &got);
1052        for r in 0..4 {
1053            for c in 0..4 {
1054                assert_eq!(
1055                    plane[(8 + r) * 16 + (4 + c)],
1056                    ((8 + r) * 16 + (4 + c)) as u8
1057                );
1058            }
1059        }
1060        // And bytes outside the patched sub-block are untouched.
1061        assert_eq!(plane[0], 0);
1062        assert_eq!(plane[255], 255);
1063    }
1064
1065    // -------------------------------------------------------------------
1066    // §11.3 / §12.3 B_PRED reconstruction
1067    // -------------------------------------------------------------------
1068
1069    /// Coefficient bundle for the B_PRED entry (no Y2 block).
1070    type BpredCoeffs = ([[i16; 16]; 16], [[i16; 16]; 4], [[i16; 16]; 4]);
1071
1072    fn zero_bpred_coeffs() -> BpredCoeffs {
1073        ([[0i16; 16]; 16], [[0i16; 16]; 4], [[0i16; 16]; 4])
1074    }
1075
1076    /// All sixteen sub-blocks set to `mode`.
1077    fn all_modes(mode: IntraBmode) -> [IntraBmode; 16] {
1078        [mode; 16]
1079    }
1080
1081    /// Pull a 4×4 luma sub-block (sub-block index `i*4+j`) out of an
1082    /// `out.y` 16×16 plane.
1083    fn y_subblock(out: &ReconstructedMb, i: usize, j: usize) -> [u8; 16] {
1084        extract_4x4(&out.y, 16, i, j)
1085    }
1086
1087    #[test]
1088    fn bpred_missing_subblock_modes_errors() {
1089        let (y, u, v) = zero_bpred_coeffs();
1090        let res = decode_keyframe_mb_bpred(
1091            None,
1092            IntraUvMode::Dc,
1093            false,
1094            &MbNeighbors::default(),
1095            &y,
1096            &u,
1097            &v,
1098        );
1099        assert_eq!(res, Err(ReconstructError::MissingSubblockModes));
1100    }
1101
1102    #[test]
1103    fn bpred_dc_top_left_corner_is_128_everywhere() {
1104        // Top-left corner MB, all sub-blocks B_DC_PRED, skip=true.
1105        // For the (0,0) sub-block: above = 127 (off-frame), left = 129
1106        // (off-frame) → DC = (4*127 + 4*129 + 4) >> 3 = 1028 >> 3 = 128.
1107        // Once that sub-block reconstructs to flat-128, every other
1108        // sub-block sees only 128 / 127 / 129 neighbours and likewise
1109        // settles to a flat value. The whole-plane result is therefore
1110        // a constant; we assert it is 128 (the corner sub-block value)
1111        // and uniform.
1112        let (y, u, v) = zero_bpred_coeffs();
1113        let out = decode_keyframe_mb_bpred(
1114            Some(&all_modes(IntraBmode::Dc)),
1115            IntraUvMode::Dc,
1116            true,
1117            &MbNeighbors::default(),
1118            &y,
1119            &u,
1120            &v,
1121        )
1122        .unwrap();
1123        // Corner sub-block (0,0) is exactly 128.
1124        assert!(y_subblock(&out, 0, 0).iter().all(|&p| p == 128));
1125        // Chroma top-left corner with DC mode also fills 128.
1126        assert!(out.u.iter().all(|&p| p == DEFAULT_TOPLEFT_DC));
1127        assert!(out.v.iter().all(|&p| p == DEFAULT_TOPLEFT_DC));
1128    }
1129
1130    #[test]
1131    fn bpred_skip_matches_standalone_per_subblock_kernels() {
1132        // Drive an interior-style MB with full neighbours and skip=true
1133        // for several distinct sub-modes, then independently replay the
1134        // §12.3 kernel for the *first* sub-block (which reads only the
1135        // supplied border, not any evolved neighbour) and confirm the
1136        // orchestrator's (0,0) sub-block matches byte-for-byte. This
1137        // proves the orchestrator wires the border into predict_b4x4
1138        // correctly for each mode.
1139        let y_above: [u8; 16] = core::array::from_fn(|i| (20 + i * 3) as u8);
1140        let y_left: [u8; 16] = core::array::from_fn(|i| (200 - i * 5) as u8);
1141        let y_above_right = [80u8, 90, 100, 110];
1142        let topleft = 64u8;
1143        let neighbors = MbNeighbors {
1144            y_above: Some(y_above),
1145            y_left: Some(y_left),
1146            y_topleft: Some(topleft),
1147            y_above_right: Some(y_above_right),
1148            ..MbNeighbors::default()
1149        };
1150        let (y, u, v) = zero_bpred_coeffs();
1151
1152        for mode in [
1153            IntraBmode::Dc,
1154            IntraBmode::Tm,
1155            IntraBmode::Ve,
1156            IntraBmode::He,
1157            IntraBmode::Ld,
1158            IntraBmode::Rd,
1159            IntraBmode::Vr,
1160            IntraBmode::Vl,
1161            IntraBmode::Hd,
1162            IntraBmode::Hu,
1163        ] {
1164            let out = decode_keyframe_mb_bpred(
1165                Some(&all_modes(mode)),
1166                IntraUvMode::Dc,
1167                true,
1168                &neighbors,
1169                &y,
1170                &u,
1171                &v,
1172            )
1173            .unwrap();
1174
1175            // Standalone replay for sub-block (0,0): its above strip is
1176            // y_above[0..4] followed by y_above[4..8]; its left is
1177            // y_left[0..4]; its P is the MB top-left corner.
1178            let mut above = [0u8; 8];
1179            above.copy_from_slice(&y_above[0..8]);
1180            let left = [y_left[0], y_left[1], y_left[2], y_left[3]];
1181            let mut want = [0u8; 16];
1182            predict_b4x4(&mut want, mode, &above, &left, topleft);
1183
1184            assert_eq!(
1185                y_subblock(&out, 0, 0),
1186                want,
1187                "mode {mode:?} sub-block (0,0) mismatch vs standalone kernel"
1188            );
1189        }
1190    }
1191
1192    #[test]
1193    fn bpred_neighbour_evolution_left_propagates() {
1194        // Sub-block (0,1) must read its `left` column from the
1195        // already-reconstructed sub-block (0,0), not from the MB-level
1196        // y_left border. We exercise that by giving sub-block (0,0) a
1197        // non-zero residue (so its reconstructed right column differs
1198        // from any border default) and using B_HE_PRED for sub-block
1199        // (0,1), which copies a smoothed version of its `left` column
1200        // across each row. If the orchestrator failed to feed (0,0)'s
1201        // reconstructed pixels in as (0,1)'s `left`, the result would
1202        // not depend on (0,0)'s residue.
1203        let neighbors = MbNeighbors {
1204            y_above: Some([100u8; 16]),
1205            y_left: Some([100u8; 16]),
1206            y_topleft: Some(100),
1207            y_above_right: Some([100u8; 4]),
1208            ..MbNeighbors::default()
1209        };
1210
1211        // Two runs: identical except sub-block (0,0)'s residue.
1212        let modes = {
1213            let mut m = all_modes(IntraBmode::Dc);
1214            m[1] = IntraBmode::He; // sub-block (0,1)
1215            m
1216        };
1217
1218        let (mut y_a, u, v) = zero_bpred_coeffs();
1219        let out_flat = decode_keyframe_mb_bpred(
1220            Some(&modes),
1221            IntraUvMode::Dc,
1222            false,
1223            &neighbors,
1224            &y_a,
1225            &u,
1226            &v,
1227        )
1228        .unwrap();
1229
1230        // Give sub-block (0,0) a large positive DC so its reconstructed
1231        // right column climbs well above 100.
1232        y_a[0][0] = 400;
1233        let out_lifted = decode_keyframe_mb_bpred(
1234            Some(&modes),
1235            IntraUvMode::Dc,
1236            false,
1237            &neighbors,
1238            &y_a,
1239            &u,
1240            &v,
1241        )
1242        .unwrap();
1243
1244        let flat_01 = y_subblock(&out_flat, 0, 1);
1245        let lifted_01 = y_subblock(&out_lifted, 0, 1);
1246        assert_ne!(
1247            flat_01, lifted_01,
1248            "sub-block (0,1) did not respond to sub-block (0,0)'s residue — \
1249             left-neighbour evolution is broken"
1250        );
1251    }
1252
1253    #[test]
1254    fn bpred_neighbour_evolution_above_propagates() {
1255        // Symmetric to the left-propagation test: sub-block (1,0) reads
1256        // its `above` strip from the reconstructed sub-block (0,0). Use
1257        // B_VE_PRED for (1,0) (copies a smoothed above row down every
1258        // row) and perturb (0,0)'s residue.
1259        let neighbors = MbNeighbors {
1260            y_above: Some([100u8; 16]),
1261            y_left: Some([100u8; 16]),
1262            y_topleft: Some(100),
1263            y_above_right: Some([100u8; 4]),
1264            ..MbNeighbors::default()
1265        };
1266        let modes = {
1267            let mut m = all_modes(IntraBmode::Dc);
1268            m[4] = IntraBmode::Ve; // sub-block (1,0)
1269            m
1270        };
1271
1272        let (mut y_a, u, v) = zero_bpred_coeffs();
1273        let out_flat = decode_keyframe_mb_bpred(
1274            Some(&modes),
1275            IntraUvMode::Dc,
1276            false,
1277            &neighbors,
1278            &y_a,
1279            &u,
1280            &v,
1281        )
1282        .unwrap();
1283
1284        y_a[0][0] = 400;
1285        let out_lifted = decode_keyframe_mb_bpred(
1286            Some(&modes),
1287            IntraUvMode::Dc,
1288            false,
1289            &neighbors,
1290            &y_a,
1291            &u,
1292            &v,
1293        )
1294        .unwrap();
1295
1296        assert_ne!(
1297            y_subblock(&out_flat, 1, 0),
1298            y_subblock(&out_lifted, 1, 0),
1299            "sub-block (1,0) did not respond to sub-block (0,0)'s residue — \
1300             above-neighbour evolution is broken"
1301        );
1302    }
1303
1304    #[test]
1305    fn bpred_right_edge_above_right_fixup() {
1306        // §12.3: sub-blocks 7, 11, 15 share sub-block 3's above-right
1307        // pixels (frame (-1,16)..=(-1,19)). With B_LD_PRED (which reads
1308        // above[4..8], the above-right strip) on those sub-blocks, the
1309        // result must depend on y_above_right. We run twice with two
1310        // different y_above_right values and require the bottom-right
1311        // sub-blocks to differ. Sub-block 3 (top-right) reads the same
1312        // pixels directly, so it must differ too.
1313        let mk = |ar: [u8; 4]| MbNeighbors {
1314            y_above: Some([100u8; 16]),
1315            y_left: Some([100u8; 16]),
1316            y_topleft: Some(100),
1317            y_above_right: Some(ar),
1318            ..MbNeighbors::default()
1319        };
1320        let modes = all_modes(IntraBmode::Ld);
1321        let (y, u, v) = zero_bpred_coeffs();
1322
1323        let out_a = decode_keyframe_mb_bpred(
1324            Some(&modes),
1325            IntraUvMode::Dc,
1326            true,
1327            &mk([10, 10, 10, 10]),
1328            &y,
1329            &u,
1330            &v,
1331        )
1332        .unwrap();
1333        let out_b = decode_keyframe_mb_bpred(
1334            Some(&modes),
1335            IntraUvMode::Dc,
1336            true,
1337            &mk([240, 240, 240, 240]),
1338            &y,
1339            &u,
1340            &v,
1341        )
1342        .unwrap();
1343
1344        // Sub-block 3 (row 0, col 3) reads above-right directly.
1345        assert_ne!(
1346            y_subblock(&out_a, 0, 3),
1347            y_subblock(&out_b, 0, 3),
1348            "sub-block 3 ignored y_above_right"
1349        );
1350        // Sub-block 7 (row 1, col 3) gets the copied-down above-right.
1351        assert_ne!(
1352            y_subblock(&out_a, 1, 3),
1353            y_subblock(&out_b, 1, 3),
1354            "sub-block 7 did not receive the copy_down above-right fixup"
1355        );
1356        // Sub-block 15 (row 3, col 3).
1357        assert_ne!(
1358            y_subblock(&out_a, 3, 3),
1359            y_subblock(&out_b, 3, 3),
1360            "sub-block 15 did not receive the copy_down above-right fixup"
1361        );
1362    }
1363
1364    #[test]
1365    fn bpred_top_row_above_right_defaults_to_127() {
1366        // On the top MB row (y_above and y_above_right both None) the
1367        // four above-right pixels must be 127. With B_LD_PRED on the
1368        // right-edge sub-blocks, supplying y_above_right=None should be
1369        // identical to supplying Some([127; 4]) with the same above.
1370        let modes = all_modes(IntraBmode::Ld);
1371        let (y, u, v) = zero_bpred_coeffs();
1372
1373        // Both: above off-frame (→127), left present.
1374        let n_none = MbNeighbors {
1375            y_left: Some([90u8; 16]),
1376            ..MbNeighbors::default()
1377        };
1378        let n_explicit = MbNeighbors {
1379            y_left: Some([90u8; 16]),
1380            y_above: Some([DEFAULT_ABOVE_PIXEL; 16]),
1381            y_above_right: Some([DEFAULT_ABOVE_PIXEL; 4]),
1382            y_topleft: Some(DEFAULT_ABOVE_PIXEL),
1383            ..MbNeighbors::default()
1384        };
1385
1386        let out_none =
1387            decode_keyframe_mb_bpred(Some(&modes), IntraUvMode::Dc, true, &n_none, &y, &u, &v)
1388                .unwrap();
1389        let out_explicit =
1390            decode_keyframe_mb_bpred(Some(&modes), IntraUvMode::Dc, true, &n_explicit, &y, &u, &v)
1391                .unwrap();
1392        assert_eq!(
1393            out_none.y, out_explicit.y,
1394            "top-row default-127 above-right path diverged from explicit Some([127;4])"
1395        );
1396    }
1397
1398    #[test]
1399    fn bpred_full_mb_reconstruction_mixed_modes() {
1400        // A full B_PRED macroblock with a mix of sub-block modes, full
1401        // neighbours, and non-trivial residue in every Y sub-block,
1402        // plus chroma residue. This exercises the complete §12.3 walk
1403        // (predict → idct → add → evolve) end-to-end. We assert two
1404        // invariants that any correct implementation must satisfy:
1405        //  1. With skip=false but all-zero coefficients, the result
1406        //     equals the skip=true (prediction-only) result.
1407        //  2. Adding a constant positive DC to every Y sub-block raises
1408        //     the plane (no panic, monotone non-decrease at the (0,0)
1409        //     corner) — a smoke test that residue folds in per sub-block.
1410        let neighbors = MbNeighbors {
1411            y_above: Some(core::array::from_fn(|i| (30 + i * 4) as u8)),
1412            y_left: Some(core::array::from_fn(|i| (40 + i * 3) as u8)),
1413            y_topleft: Some(50),
1414            y_above_right: Some([60, 70, 80, 90]),
1415            u_above: Some([120u8; 8]),
1416            u_left: Some([130u8; 8]),
1417            u_topleft: Some(125),
1418            v_above: Some([140u8; 8]),
1419            v_left: Some([150u8; 8]),
1420            v_topleft: Some(145),
1421        };
1422        let modes = [
1423            IntraBmode::Dc,
1424            IntraBmode::Tm,
1425            IntraBmode::Ve,
1426            IntraBmode::He,
1427            IntraBmode::Ld,
1428            IntraBmode::Rd,
1429            IntraBmode::Vr,
1430            IntraBmode::Vl,
1431            IntraBmode::Hd,
1432            IntraBmode::Hu,
1433            IntraBmode::Dc,
1434            IntraBmode::Tm,
1435            IntraBmode::Ve,
1436            IntraBmode::He,
1437            IntraBmode::Ld,
1438            IntraBmode::Rd,
1439        ];
1440
1441        // Invariant 1: zero residue, skip vs run agree.
1442        let (y0, u0, v0) = zero_bpred_coeffs();
1443        let out_skip = decode_keyframe_mb_bpred(
1444            Some(&modes),
1445            IntraUvMode::Tm,
1446            true,
1447            &neighbors,
1448            &y0,
1449            &u0,
1450            &v0,
1451        )
1452        .unwrap();
1453        let out_run = decode_keyframe_mb_bpred(
1454            Some(&modes),
1455            IntraUvMode::Tm,
1456            false,
1457            &neighbors,
1458            &y0,
1459            &u0,
1460            &v0,
1461        )
1462        .unwrap();
1463        assert_eq!(out_skip.y, out_run.y, "zero-residue Y skip != run");
1464        assert_eq!(out_skip.u, out_run.u, "zero-residue U skip != run");
1465        assert_eq!(out_skip.v, out_run.v, "zero-residue V skip != run");
1466
1467        // Invariant 2: a positive DC in every Y sub-block lifts the
1468        // (0,0) corner pixel relative to the prediction-only run.
1469        let mut y_lift = [[0i16; 16]; 16];
1470        for sb in y_lift.iter_mut() {
1471            sb[0] = 80; // positive DC seed → positive flat-ish residue.
1472        }
1473        let out_lift = decode_keyframe_mb_bpred(
1474            Some(&modes),
1475            IntraUvMode::Tm,
1476            false,
1477            &neighbors,
1478            &y_lift,
1479            &u0,
1480            &v0,
1481        )
1482        .unwrap();
1483        assert!(
1484            out_lift.y[0] >= out_skip.y[0],
1485            "positive Y DC did not lift the (0,0) corner: {} < {}",
1486            out_lift.y[0],
1487            out_skip.y[0]
1488        );
1489        // And the chroma planes (zero residue) are unchanged from skip.
1490        assert_eq!(out_lift.u, out_skip.u);
1491        assert_eq!(out_lift.v, out_skip.v);
1492    }
1493
1494    #[test]
1495    fn bpred_chroma_uses_8x8_mode_independent_of_luma() {
1496        // The chroma path of a B_PRED MB is the ordinary 8×8 §12.2 mode.
1497        // Verify it matches a standalone predict_uv8x8 call (skip MB).
1498        let u_above = [55u8; 8];
1499        let v_above = [66u8; 8];
1500        let neighbors = MbNeighbors {
1501            y_above: Some([100u8; 16]),
1502            y_left: Some([100u8; 16]),
1503            y_topleft: Some(100),
1504            y_above_right: Some([100u8; 4]),
1505            u_above: Some(u_above),
1506            v_above: Some(v_above),
1507            ..MbNeighbors::default()
1508        };
1509        let (y, u, v) = zero_bpred_coeffs();
1510        let out = decode_keyframe_mb_bpred(
1511            Some(&all_modes(IntraBmode::Dc)),
1512            IntraUvMode::V,
1513            true,
1514            &neighbors,
1515            &y,
1516            &u,
1517            &v,
1518        )
1519        .unwrap();
1520
1521        let mut want_u = [0u8; 64];
1522        predict_uv8x8(&mut want_u, IntraUvMode::V, Some(&u_above), None, 0);
1523        let mut want_v = [0u8; 64];
1524        predict_uv8x8(&mut want_v, IntraUvMode::V, Some(&v_above), None, 0);
1525        assert_eq!(out.u, want_u);
1526        assert_eq!(out.v, want_v);
1527    }
1528
1529    #[test]
1530    fn bpred_top_row_chroma_topleft_defaults_to_127() {
1531        // Regression (issue #23): on a top-row B_PRED MB the off-frame
1532        // chroma top-left must default to DEFAULT_ABOVE_PIXEL (127), the
1533        // RFC 6386 §12.2 above-row default — the same value the non-B_PRED
1534        // path and the encoder use. TM_PRED is the only 8×8 chroma mode that
1535        // reads the corner, so it exposes the divergence: defaulting to 0
1536        // (the prior bug) silently corrupted U/V on top-row MBs while luma
1537        // stayed byte-identical (pink/green smearing).
1538        let u_above = [55u8; 8];
1539        let u_left = [70u8; 8];
1540        let v_above = [66u8; 8];
1541        let v_left = [80u8; 8];
1542        let neighbors = MbNeighbors {
1543            y_above: Some([100u8; 16]),
1544            y_left: Some([100u8; 16]),
1545            y_topleft: Some(100),
1546            y_above_right: Some([100u8; 4]),
1547            u_above: Some(u_above),
1548            u_left: Some(u_left),
1549            v_above: Some(v_above),
1550            v_left: Some(v_left),
1551            // u_topleft / v_topleft deliberately None: this is the top row.
1552            ..MbNeighbors::default()
1553        };
1554        let (y, u, v) = zero_bpred_coeffs();
1555        let out = decode_keyframe_mb_bpred(
1556            Some(&all_modes(IntraBmode::Dc)),
1557            IntraUvMode::Tm,
1558            true,
1559            &neighbors,
1560            &y,
1561            &u,
1562            &v,
1563        )
1564        .unwrap();
1565
1566        // Must match a standalone TM_PRED with corner = 127 ...
1567        let mut want_u = [0u8; 64];
1568        predict_uv8x8(
1569            &mut want_u,
1570            IntraUvMode::Tm,
1571            Some(&u_above),
1572            Some(&u_left),
1573            DEFAULT_ABOVE_PIXEL,
1574        );
1575        let mut want_v = [0u8; 64];
1576        predict_uv8x8(
1577            &mut want_v,
1578            IntraUvMode::Tm,
1579            Some(&v_above),
1580            Some(&v_left),
1581            DEFAULT_ABOVE_PIXEL,
1582        );
1583        assert_eq!(out.u, want_u);
1584        assert_eq!(out.v, want_v);
1585
1586        // ... and must NOT match the prior corner-0 behaviour (locks the fix).
1587        let mut bug_u = [0u8; 64];
1588        predict_uv8x8(
1589            &mut bug_u,
1590            IntraUvMode::Tm,
1591            Some(&u_above),
1592            Some(&u_left),
1593            0,
1594        );
1595        assert_ne!(out.u, bug_u);
1596    }
1597}