Skip to main content

oxideav_vp8/
motion_comp.rs

1//! Interframe motion compensation — RFC 6386 §16.2 reference selection,
2//! §18.1 motion-vector adjustment, §18.2 whole-pixel prediction, and
3//! §18.3 sub-pixel (sixtap / bilinear) interpolation.
4//!
5//! This module is the first inter-frame *prediction* slice: it consumes
6//! the §17 motion vectors decoded by [`crate::motion_vector`] and turns a
7//! reference frame plus a per-macroblock motion vector into a predicted
8//! macroblock, then folds in the §14 dequantized residual to complete
9//! inter-MB reconstruction. It sits one layer below the §16.3
10//! near/nearest/best census (which produces the actual per-MB vector a
11//! NEWMV offset is added to) and the §16.4 SPLITMV walk; those choose
12//! *which* vector applies, this applies it.
13//!
14//! ## Scope — whole-pixel + sub-pixel motion compensation
15//!
16//! VP8 motion vectors carry a fractional (sub-pixel) part. After the
17//! §18.1 adjustments, each component's low three bits (`& 7`) are an
18//! eighth-pixel forward displacement:
19//!
20//! * **Whole-pixel** (`mx | my == 0`): §18.3 page 115 "the prediction
21//!   subblock is simply copied". This is the `filter_block` special case
22//!   in the §20.14 reference decoder, where `filter_block` returns the
23//!   reference pointer unchanged.
24//! * **Sub-pixel** (either fraction non-zero): §18.3 synthesises the
25//!   missing samples via a horizontal then a vertical one-dimensional
26//!   six-tap convolution ([`sixtap_2d`]). The tap set is chosen by the
27//!   frame-tag version — `version == 0` uses the bicubic
28//!   [`SIXTAP_FILTERS`], any other version uses the [`BILINEAR_FILTERS`]
29//!   (§20.14 `subpixel_filters` assignment). Both luma and chroma share
30//!   the version-selected set.
31//!
32//! Concretely this module provides:
33//!
34//! * [`RefFrame`] + [`select_ref_frame`] — the §16.2 `prob_last` /
35//!   `prob_gf` reference-frame selector.
36//! * [`ReferencePlanes`] — a borrow of one reference frame's I420 planes
37//!   for prediction fetch.
38//! * [`stored_luma_mv`] / [`chroma_mv`] / [`apply_full_pixel`] — the
39//!   §18.1 motion-vector adjustments (stored-luma doubling, the chroma
40//!   `avg()` averaging, and the version-3 full-pel truncation).
41//! * [`whole_pixel_fraction_is_zero`] — the §18.3 whole-pixel test
42//!   applied to an already-§18.1-adjusted (eighth-pixel) vector.
43//! * [`SIXTAP_FILTERS`] / [`BILINEAR_FILTERS`] / [`FilterSet`] /
44//!   [`filter_set_for_version`] — the §18.3 filter tables and the §20.14
45//!   version→tap-set selector.
46//! * [`interp`] / [`sixtap_horiz`] / [`sixtap_vert`] / [`sixtap_2d`] —
47//!   the §18.3 / §20.14 one-dimensional convolution primitives.
48//! * [`fetch_block_whole_pixel`] — the §20.14 `build_mc_border`
49//!   edge-replicated 4×4 block fetch, specialised to whole-pixel offsets
50//!   (no six-tap support pixels needed).
51//! * [`fetch_block_halo`] — the §20.14 `build_mc_border` 9×9 halo fetch
52//!   (the 4×4 block plus the two-before / three-after support pixels the
53//!   six-tap convolution needs in each dimension).
54//! * [`filter_block_4x4`] — the §20.14 `filter_block`: whole-pixel copy
55//!   or [`sixtap_2d`] sub-pixel synthesis for one 4×4 sub-block.
56//! * [`predict_inter_mb`] — the §18.2 whole-MB prediction buffer for a
57//!   non-SPLITMV macroblock (one vector for all sixteen Y sub-blocks, the
58//!   averaged chroma vector for the eight chroma sub-blocks), routing each
59//!   sub-block through whole-pixel copy or sub-pixel interpolation.
60//! * [`reconstruct_inter_mb`] — prediction + §14 dequantized residual,
61//!   producing a [`ReconstructedMb`].
62//!
63//! The whole-pixel-only [`predict_inter_mb_whole_pixel`] /
64//! [`reconstruct_inter_mb_whole_pixel`] entry points are retained for
65//! callers that only ever pass whole-pixel vectors; they refuse a
66//! sub-pixel vector with [`MotionCompError::SubPixelNotSupported`]. New
67//! callers should prefer [`predict_inter_mb`] / [`reconstruct_inter_mb`].
68//!
69//! ## What is deferred (next inter-prediction rounds)
70//!
71//! * §16.4 SPLITMV (per-sub-block vectors): this round handles the four
72//!   whole-MB inter modes (`mv_nearest` / `mv_near` / `mv_zero` /
73//!   `mv_new`), all of which apply one vector to the whole MB.
74//! * §16.3 `vp8_find_near_mvs` census: this module takes the *resolved*
75//!   per-MB vector as an input; deriving it from neighbours is a separate
76//!   slice.
77
78use crate::bool_decoder::{BoolDecoder, BoolDecoderError};
79use crate::inverse_transform::{clamp255, inverse_dct_4x4_add_into, inverse_wht_4x4};
80use crate::motion_vector::Mv;
81use crate::reconstruct::ReconstructedMb;
82
83/// The reference frame a macroblock predicts from — RFC 6386 §16.2.
84///
85/// On an interframe, after the intra/inter discriminator selects
86/// inter-prediction, a `Bool(prob_last)` then (conditionally) a
87/// `Bool(prob_gf)` choose between the three stored reference frames.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub enum RefFrame {
90    /// The previous (last) decoded frame — `prob_last` reads 0.
91    Last,
92    /// The golden frame — `prob_last` reads 1, `prob_gf` reads 0.
93    Golden,
94    /// The altref frame — `prob_last` reads 1, `prob_gf` reads 1.
95    AltRef,
96}
97
98/// Select the reference frame for an inter-predicted macroblock — RFC
99/// 6386 §16.2.
100///
101/// "The next datum is then another bool, `B(prob_last)`, selecting the
102/// reference frame. If 0, the reference frame is the previous frame (the
103/// last frame); if 1, another bool (`prob_gf`) selects the reference
104/// frame between the golden frame (0) and the altref frame (1)."
105///
106/// `prob_last` and `prob_gf` come from field J of the frame header (the
107/// §9.10 `prob_last` / `prob_gf` already parsed by [`crate::coded_header`]).
108pub fn select_ref_frame(
109    dec: &mut BoolDecoder<'_>,
110    prob_last: u8,
111    prob_gf: u8,
112) -> Result<RefFrame, BoolDecoderError> {
113    if !dec.read_bool(prob_last)? {
114        Ok(RefFrame::Last)
115    } else if !dec.read_bool(prob_gf)? {
116        Ok(RefFrame::Golden)
117    } else {
118        Ok(RefFrame::AltRef)
119    }
120}
121
122/// A borrow of one reference frame's reconstructed I420 planes, in the
123/// whole-macroblock layout produced by [`crate::frame::KeyframePlanes`].
124///
125/// The planes are sized to whole macroblocks: the luma plane is
126/// `mb_cols * 16` wide by `mb_rows * 16` tall, each chroma plane half
127/// that in both dimensions. The §18.2 prediction fetch reads from these
128/// planes with the §20.14 `build_mc_border` edge replication when a
129/// motion vector points outside the plane.
130#[derive(Debug, Clone, Copy)]
131pub struct ReferencePlanes<'a> {
132    /// Luma plane, row-major, `y_stride * (mb_rows * 16)` bytes.
133    pub y: &'a [u8],
134    /// U chroma plane, row-major, `uv_stride * (mb_rows * 8)` bytes.
135    pub u: &'a [u8],
136    /// V chroma plane, same dimensions as [`ReferencePlanes::u`].
137    pub v: &'a [u8],
138    /// Luma plane stride (= `mb_cols * 16`).
139    pub y_stride: usize,
140    /// Chroma plane stride (= `mb_cols * 8`).
141    pub uv_stride: usize,
142    /// Number of macroblock columns.
143    pub mb_cols: usize,
144    /// Number of macroblock rows.
145    pub mb_rows: usize,
146}
147
148/// Errors surfaced by the motion-compensation layer.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150#[non_exhaustive]
151pub enum MotionCompError {
152    /// The §18.1-adjusted motion vector has a non-zero fractional part,
153    /// so §18.3 sub-pixel interpolation is required. Returned only by the
154    /// whole-pixel-only entry points
155    /// ([`predict_inter_mb_whole_pixel`] /
156    /// [`reconstruct_inter_mb_whole_pixel`]); the full
157    /// [`predict_inter_mb`] / [`reconstruct_inter_mb`] path handles
158    /// sub-pixel vectors directly and never returns this.
159    SubPixelNotSupported,
160}
161
162impl core::fmt::Display for MotionCompError {
163    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
164        match self {
165            MotionCompError::SubPixelNotSupported => f.write_str(
166                "vp8 motion-comp: sub-pixel interpolation (§18.3) not yet implemented; \
167                 only whole-pixel motion vectors are supported this round",
168            ),
169        }
170    }
171}
172
173impl std::error::Error for MotionCompError {}
174
175/// Apply the §18.1 stored-luma doubling to a decoded luma motion vector.
176///
177/// RFC 6386 §18.1: "the synthetic pixel calculation ... uses [1/8-pixel]
178/// resolution for the luma subblocks as well. In accordance, the stored
179/// luma motion vectors are all doubled, each component of each luma
180/// vector becoming an even integer in the range -2046 to +2046,
181/// inclusive."
182///
183/// The §17 decode produces quarter-pixel luma components; doubling moves
184/// them to the eighth-pixel resolution chroma uses, so a single
185/// fractional-extraction rule (`& 7`) serves both planes.
186#[inline]
187pub fn stored_luma_mv(mv: Mv) -> Mv {
188    Mv {
189        row: mv.row.wrapping_mul(2),
190        col: mv.col.wrapping_mul(2),
191    }
192}
193
194/// The §18.1 `avg()` four-vector averaging primitive (one component).
195///
196/// RFC 6386 §18.1:
197///
198/// ```text
199/// int avg(int c1, int c2, int c3, int c4) {
200///     int s = c1 + c2 + c3 + c4;
201///     return s >= 0 ? (s + 4) >> 3 : -((-s + 4) >> 3);
202/// }
203/// ```
204///
205/// The shift divides by 8 (not 4) because chroma pixels have twice the
206/// diameter of luma pixels; the negative-number handling is explicit
207/// because C right shifts of negatives are not well-defined.
208#[inline]
209fn avg(c1: i32, c2: i32, c3: i32, c4: i32) -> i32 {
210    let s = c1 + c2 + c3 + c4;
211    if s >= 0 {
212        (s + 4) >> 3
213    } else {
214        -((-s + 4) >> 3)
215    }
216}
217
218/// Compute the chroma motion vector for a whole (non-SPLITMV)
219/// macroblock — RFC 6386 §18.1.
220///
221/// For a whole-MB vector all sixteen luma sub-blocks share `luma_mv`
222/// (already §18.1-doubled to eighth-pixel resolution), so each chroma
223/// vector is `avg(v, v, v, v)` of that one vector. The §20.14 reference
224/// decoder writes this as the closed form
225/// `(c + 1 + (c >> 31) * 2) / 2` per component, which equals
226/// `avg(c, c, c, c)`; we use [`avg`] directly so the single §18.1
227/// primitive backs both the whole-MB and (future) SPLITMV chroma paths.
228///
229/// `luma_mv` must already be the §18.1 stored (doubled) luma vector —
230/// see [`stored_luma_mv`].
231#[inline]
232pub fn chroma_mv(luma_mv: Mv) -> Mv {
233    let row = luma_mv.row as i32;
234    let col = luma_mv.col as i32;
235    Mv {
236        row: avg(row, row, row, row) as i16,
237        col: avg(col, col, col, col) as i16,
238    }
239}
240
241/// Truncate the fractional part of a vector for the version-3 full-pel
242/// chroma profile — RFC 6386 §18.1.
243///
244/// "if the version number in the frame tag specifies only full-pel
245/// chroma motion vectors, then the fractional parts of both components
246/// of the vector are truncated to zero":
247///
248/// ```text
249/// x = x & (~7);
250/// y = y & (~7);
251/// ```
252///
253/// Applied to an eighth-pixel-resolution vector (the §18.1 stored luma
254/// vector or the [`chroma_mv`] average).
255#[inline]
256pub fn apply_full_pixel(mv: Mv) -> Mv {
257    Mv {
258        row: mv.row & !7,
259        col: mv.col & !7,
260    }
261}
262
263/// Test whether an already-§18.1-adjusted (eighth-pixel) vector has a
264/// zero fractional part — i.e. it is a whole-pixel vector and §18.3 page
265/// 115 "the prediction subblock is simply copied" applies.
266///
267/// This mirrors the §20.14 `filter_block` test `mx = mv.x & 7;
268/// my = mv.y & 7; if (mx | my) interpolate; else copy`.
269#[inline]
270pub fn whole_pixel_fraction_is_zero(mv: Mv) -> bool {
271    (mv.row & 7) == 0 && (mv.col & 7) == 0
272}
273
274/// The §18.3 bicubic ("six-tap") interpolation filter table, indexed by
275/// the eighth-pixel fractional displacement (0..=7).
276///
277/// RFC 6386 §18.3 `filters[8][6]` (= the §20.14 `sixtap_filters`):
278///
279/// ```text
280/// const int filters [8] [6] = {        /* indexed by displacement */
281///     { 0,  0,  128,    0,   0,  0 },  /* degenerate whole-pixel */
282///     { 0, -6,  123,   12,  -1,  0 },  /* 1/8 */
283///     { 2, -11, 108,   36,  -8,  1 },  /* 1/4 */
284///     { 0, -9,   93,   50,  -6,  0 },  /* 3/8 */
285///     { 3, -16,  77,   77, -16,  3 },  /* 1/2 is symmetric */
286///     { 0, -6,   50,   93,  -9,  0 },  /* 5/8 = reverse of 3/8 */
287///     { 1, -8,   36,  108, -11,  2 },  /* 3/4 = reverse of 1/4 */
288///     { 0, -1,   12,  123,  -6,  0 }   /* 7/8 = reverse of 1/8 */
289/// };
290/// ```
291///
292/// "Filter taps taken to 7-bit precision. Because DC is always passed,
293/// taps always sum to 128."
294pub static SIXTAP_FILTERS: [[i32; 6]; 8] = [
295    [0, 0, 128, 0, 0, 0],
296    [0, -6, 123, 12, -1, 0],
297    [2, -11, 108, 36, -8, 1],
298    [0, -9, 93, 50, -6, 0],
299    [3, -16, 77, 77, -16, 3],
300    [0, -6, 50, 93, -9, 0],
301    [1, -8, 36, 108, -11, 2],
302    [0, -1, 12, 123, -6, 0],
303];
304
305/// The §18.3 bilinear interpolation filter table, indexed by the
306/// eighth-pixel fractional displacement (0..=7).
307///
308/// RFC 6386 §18.3 `BilinearFilters[8][6]` (= the §20.14
309/// `bilinear_filters`):
310///
311/// ```text
312/// const int BilinearFilters[8][6] =
313/// {
314///     { 0, 0, 128,   0, 0, 0 },
315///     { 0, 0, 112,  16, 0, 0 },
316///     { 0, 0,  96,  32, 0, 0 },
317///     { 0, 0,  80,  48, 0, 0 },
318///     { 0, 0,  64,  64, 0, 0 },
319///     { 0, 0,  48,  80, 0, 0 },
320///     { 0, 0,  32,  96, 0, 0 },
321///     { 0, 0,  16, 112, 0, 0 }
322/// };
323/// ```
324///
325/// Only the centre two taps are non-zero, so the bilinear filter never
326/// reaches the outer support pixels; the convolution machinery is shared
327/// with the six-tap path regardless.
328pub static BILINEAR_FILTERS: [[i32; 6]; 8] = [
329    [0, 0, 128, 0, 0, 0],
330    [0, 0, 112, 16, 0, 0],
331    [0, 0, 96, 32, 0, 0],
332    [0, 0, 80, 48, 0, 0],
333    [0, 0, 64, 64, 0, 0],
334    [0, 0, 48, 80, 0, 0],
335    [0, 0, 32, 96, 0, 0],
336    [0, 0, 16, 112, 0, 0],
337];
338
339/// Which §18.3 tap set a frame uses, selected by the frame-tag version.
340///
341/// RFC 6386 §20.14 `setup_subpixel_filters`:
342/// `if (version) subpixel_filters = bilinear_filters; else
343/// subpixel_filters = sixtap_filters;`. Both luma and chroma share the
344/// frame's one set.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346pub enum FilterSet {
347    /// The bicubic six-tap set ([`SIXTAP_FILTERS`]) — frame-tag
348    /// `version == 0`.
349    Sixtap,
350    /// The bilinear set ([`BILINEAR_FILTERS`]) — frame-tag `version != 0`.
351    Bilinear,
352}
353
354impl FilterSet {
355    /// The 8×6 tap table backing this filter set.
356    #[inline]
357    pub fn taps(self) -> &'static [[i32; 6]; 8] {
358        match self {
359            FilterSet::Sixtap => &SIXTAP_FILTERS,
360            FilterSet::Bilinear => &BILINEAR_FILTERS,
361        }
362    }
363}
364
365/// Select the §18.3 interpolation filter set for a frame-tag version —
366/// RFC 6386 §20.14.
367///
368/// `version == 0` → bicubic six-tap; any other version → bilinear.
369#[inline]
370pub fn filter_set_for_version(version: u8) -> FilterSet {
371    if version == 0 {
372        FilterSet::Sixtap
373    } else {
374        FilterSet::Bilinear
375    }
376}
377
378/// One-dimensional synthesis of a single interpolated sample — RFC 6386
379/// §18.3 `interp`.
380///
381/// ```text
382/// Pixel interp(const int fil[6], const Pixel *p, const int s) {
383///     int32 a = 0; int i = 0;
384///     p -= s + s;                 /* move back two positions */
385///     do { a += *p * fil[i]; p += s; } while (++i < 6);
386///     return clamp255((a + 64) >> 7);
387/// }
388/// ```
389///
390/// `support` holds the six contributing source samples in increasing
391/// position order — i.e. `[p[-2s], p[-1s], p[0], p[+1s], p[+2s],
392/// p[+3s]]` — so the caller folds the stride `s` into the gather and
393/// this primitive is a pure six-tap dot product with `(a + 64) >> 7`
394/// rounding and a final `clamp255`.
395#[inline]
396pub fn interp(filter: &[i32; 6], support: &[u8; 6]) -> u8 {
397    let mut a = 0i32;
398    for i in 0..6 {
399        a += support[i] as i32 * filter[i];
400    }
401    clamp255((a + 64) >> 7)
402}
403
404/// Horizontal six-tap convolution — RFC 6386 §20.14 `sixtap_horiz`.
405///
406/// Reads `rows` rows of `cols` output samples from `reference` (a plane
407/// of stride `ref_stride`), with the convolution origin at each output
408/// column; each output sample uses the six horizontal neighbours
409/// `reference[c-2 ..= c+3]`. Writes into `output` at stride `out_stride`.
410/// The intermediate is an 8-bit value: `clamp255((sum + 64) >> 7)`, so
411/// negative partial sums are clamped to 0 exactly as in the reference
412/// decoder (the intermediate buffer there is `unsigned char`).
413///
414/// `ref0` is the index in `reference` of output column 0, row 0 (the
415/// convolution origin); the function reads `reference[ref0 - 2 ..]`.
416#[allow(clippy::too_many_arguments)] // mirrors the §20.14 sixtap_horiz signature.
417fn sixtap_horiz(
418    output: &mut [u8],
419    out_stride: usize,
420    reference: &[u8],
421    ref_stride: usize,
422    ref0: usize,
423    cols: usize,
424    rows: usize,
425    filter: &[i32; 6],
426) {
427    for r in 0..rows {
428        let row_base = ref0 + r * ref_stride;
429        for c in 0..cols {
430            let mut support = [0u8; 6];
431            for (k, s) in support.iter_mut().enumerate() {
432                // taps span reference[c-2 ..= c+3].
433                *s = reference[row_base + c + k - 2];
434            }
435            output[r * out_stride + c] = interp(filter, &support);
436        }
437    }
438}
439
440/// Vertical six-tap convolution — RFC 6386 §20.14 `sixtap_vert`.
441///
442/// The vertical counterpart of [`sixtap_horiz`]: each output sample uses
443/// the six vertical neighbours `reference[(r-2 ..= r+3) * ref_stride]`.
444/// Operates on the horizontally-filtered intermediate produced by
445/// [`sixtap_horiz`].
446#[allow(clippy::too_many_arguments)] // mirrors the §20.14 sixtap_vert signature.
447fn sixtap_vert(
448    output: &mut [u8],
449    out_stride: usize,
450    reference: &[u8],
451    ref_stride: usize,
452    ref0: usize,
453    cols: usize,
454    rows: usize,
455    filter: &[i32; 6],
456) {
457    for r in 0..rows {
458        for c in 0..cols {
459            let col_base = ref0 + r * ref_stride + c;
460            let mut support = [0u8; 6];
461            for (k, s) in support.iter_mut().enumerate() {
462                // taps span reference[(r-2 ..= r+3) * ref_stride].
463                *s = reference[col_base + (k * ref_stride) - 2 * ref_stride];
464            }
465            output[r * out_stride + c] = interp(filter, &support);
466        }
467    }
468}
469
470/// How one §18.3 tap row is evaluated over whole sample runs.
471///
472/// With `P` the sum of the non-negative taps' products plus the rounding
473/// 64 and `M` the magnitude of the negative taps' products, the §20.14
474/// output sample is `clamp255((P − M) >> 7)`: `0` when `P < M`, else
475/// `min(255, (P − M) >> 7)` — exactly `min(255, P.saturating_sub(M) >> 7)`.
476/// Tap rows with the §18.3 sign pattern (taps 0, 2, 3, 5 ≥ 0, taps 1 and
477/// 4 ≤ 0) whose `P` and `M` cannot overflow 16 bits are evaluated that
478/// way in `u16` (twice the lanes per vector of the plain `i32` sum); any
479/// other row takes the `i32` sum. The plan is resolved once per block so
480/// the per-run loops carry no decisions.
481#[derive(Debug, Clone, Copy)]
482pub(crate) enum TapPlan {
483    /// Sign-split `u16` form with taps 0 and 5 zero (the even
484    /// eighth-pixel positions and the bilinear set): tap magnitudes.
485    Inner([u16; 6]),
486    /// Sign-split `u16` form with all six taps: tap magnitudes.
487    Full([u16; 6]),
488    /// Plain `i32` sums.
489    Wide([i32; 6]),
490}
491
492impl TapPlan {
493    pub(crate) fn new(taps: &[i32; 6]) -> Self {
494        let split_signs = taps[0] >= 0
495            && taps[2] >= 0
496            && taps[3] >= 0
497            && taps[5] >= 0
498            && taps[1] <= 0
499            && taps[4] <= 0
500            && (taps[0] + taps[2] + taps[3] + taps[5]) * 255 + 64 <= u16::MAX as i32
501            && -(taps[1] + taps[4]) * 255 <= u16::MAX as i32;
502        if !split_signs {
503            return TapPlan::Wide(*taps);
504        }
505        let magnitudes = taps.map(|t| t.unsigned_abs() as u16);
506        if taps[0] == 0 && taps[5] == 0 {
507            TapPlan::Inner(magnitudes)
508        } else {
509            TapPlan::Full(magnitudes)
510        }
511    }
512
513    /// One filter pass over a run of `N` adjacent output samples:
514    /// `out[i] = interp(taps, [src[i], src[i + step], …, src[i + 5·step]])`.
515    /// `step = 1` is a horizontal pass over one row (`src` starts two
516    /// samples left of output sample 0); `step = stride` is a vertical
517    /// pass over one output row (`src` starts two rows above it).
518    #[inline(always)]
519    pub(crate) fn run<const N: usize>(&self, src: &[u8], step: usize) -> [u8; N] {
520        match self {
521            TapPlan::Inner(m) => run_split::<N, false>(src, step, m),
522            TapPlan::Full(m) => run_split::<N, true>(src, step, m),
523            TapPlan::Wide(taps) => run_wide::<N>(src, step, taps),
524        }
525    }
526}
527
528/// The run of `N` samples `step·k` past the start of `src`.
529#[inline(always)]
530fn tap_run<const N: usize>(src: &[u8], step: usize, k: usize) -> &[u8; N] {
531    src[k * step..k * step + N]
532        .try_into()
533        .expect("run of N samples")
534}
535
536/// [`TapPlan::run`] in the sign-split `u16` form; `OUTER` includes taps
537/// 0 and 5.
538#[inline(always)]
539fn run_split<const N: usize, const OUTER: bool>(src: &[u8], step: usize, m: &[u16; 6]) -> [u8; N] {
540    let (s1, s2, s3, s4) = (
541        tap_run::<N>(src, step, 1),
542        tap_run::<N>(src, step, 2),
543        tap_run::<N>(src, step, 3),
544        tap_run::<N>(src, step, 4),
545    );
546    let mut out = [0u8; N];
547    if OUTER {
548        let (s0, s5) = (tap_run::<N>(src, step, 0), tap_run::<N>(src, step, 5));
549        for i in 0..N {
550            let plus = 64
551                + s0[i] as u16 * m[0]
552                + s2[i] as u16 * m[2]
553                + s3[i] as u16 * m[3]
554                + s5[i] as u16 * m[5];
555            let minus = s1[i] as u16 * m[1] + s4[i] as u16 * m[4];
556            out[i] = (plus.saturating_sub(minus) >> 7).min(255) as u8;
557        }
558    } else {
559        for i in 0..N {
560            let plus = 64 + s2[i] as u16 * m[2] + s3[i] as u16 * m[3];
561            let minus = s1[i] as u16 * m[1] + s4[i] as u16 * m[4];
562            out[i] = (plus.saturating_sub(minus) >> 7).min(255) as u8;
563        }
564    }
565    out
566}
567
568/// [`TapPlan::run`] as plain `i32` sums.
569#[inline(always)]
570fn run_wide<const N: usize>(src: &[u8], step: usize, taps: &[i32; 6]) -> [u8; N] {
571    let mut acc = [0i32; N];
572    for (k, &tap) in taps.iter().enumerate() {
573        let run = tap_run::<N>(src, step, k);
574        for i in 0..N {
575            acc[i] += run[i] as i32 * tap;
576        }
577    }
578    let mut out = [0u8; N];
579    for i in 0..N {
580        out[i] = clamp255((acc[i] + 64) >> 7);
581    }
582    out
583}
584
585/// One §20.14 filter pass over a run of `N` adjacent output samples —
586/// [`TapPlan::run`] for a caller that filters a single run. Equals
587/// [`interp`] sample for sample (`sixtap_run_matches_interp`).
588#[cfg(test)]
589fn sixtap_run<const N: usize>(src: &[u8], step: usize, taps: &[i32; 6]) -> [u8; N] {
590    TapPlan::new(taps).run::<N>(src, step)
591}
592
593/// The two-pass §20.14 convolution of one `OW×OW` block from its
594/// `(OW+5)×(OW+5)` halo, each pass as whole-row runs ([`TapPlan`]) — the
595/// stable-build kernel behind [`sixtap_mb_luma`] when neither pass is
596/// the identity (measured: about half the instructions of the reference
597/// listing at 16 samples per run, but more at 8 and 4, so the chroma and
598/// sub-block forms keep the listing for their two-pass case). Byte-exact
599/// with the reference listing (`sixtap_mb_luma_scalar`), which the
600/// dispatcher stress tests compare it against.
601#[cfg_attr(feature = "simd", allow(dead_code))] // simd builds use the portable-simd kernels.
602#[inline]
603fn sixtap_block_runs<const HW: usize, const OW: usize, const HN: usize, const ON: usize>(
604    halo: &[u8; HN],
605    mx: usize,
606    my: usize,
607    filters: &[[i32; 6]; 8],
608) -> [u8; ON] {
609    debug_assert_eq!(HW, OW + 5);
610    debug_assert_eq!(HN, HW * HW);
611    debug_assert_eq!(ON, OW * OW);
612    // Horizontal pass: HW rows of OW samples (the block rows plus the
613    // two above / three below the vertical pass reads), 8-bit, stride OW.
614    let mut temp = [[0u8; OW]; HW];
615    filter_rows(&mut temp, &TapPlan::new(&filters[mx]), halo, HW, 1);
616    let mut out = [[0u8; OW]; OW];
617    filter_rows(
618        &mut out,
619        &TapPlan::new(&filters[my]),
620        temp.as_flattened(),
621        OW,
622        OW,
623    );
624    let mut flat = [0u8; ON];
625    flat.copy_from_slice(out.as_flattened());
626    flat
627}
628
629/// Fill `rows` with one filter pass: row `r` is the run starting at
630/// `src[r · stride]`, taps `step` apart. The plan is matched once, so
631/// each arm is a plain loop of runs.
632#[inline(always)]
633fn filter_rows<const N: usize>(
634    rows: &mut [[u8; N]],
635    plan: &TapPlan,
636    src: &[u8],
637    stride: usize,
638    step: usize,
639) {
640    match plan {
641        TapPlan::Inner(m) => {
642            for (r, row) in rows.iter_mut().enumerate() {
643                *row = run_split::<N, false>(&src[r * stride..], step, m);
644            }
645        }
646        TapPlan::Full(m) => {
647            for (r, row) in rows.iter_mut().enumerate() {
648                *row = run_split::<N, true>(&src[r * stride..], step, m);
649            }
650        }
651        TapPlan::Wide(taps) => {
652            for (r, row) in rows.iter_mut().enumerate() {
653                *row = run_wide::<N>(&src[r * stride..], step, taps);
654            }
655        }
656    }
657}
658
659/// Two-dimensional six-tap interpolation of a 4×4 sub-block — RFC 6386
660/// §20.14 `sixtap_2d`.
661///
662/// ```text
663/// sixtap_horiz(temp, 16, reference - 2*stride, stride, cols, rows + 5,
664///              filters[mx]);
665/// sixtap_vert(output, output_stride, temp + 2*16, 16, cols, rows,
666///             filters[my]);
667/// ```
668///
669/// `halo` is the 9×9 edge-replicated source region from
670/// [`fetch_block_halo`]: row-major, stride 9, with the 4×4 block origin
671/// at `halo[(2,2)]`. The horizontal pass synthesises a 4-wide × 9-tall
672/// intermediate (the block rows plus the two-above / three-below support
673/// the vertical pass needs); the vertical pass then synthesises the final
674/// 4×4. `(mx, my)` are the eighth-pixel fractions (`mv & 7`); `filters`
675/// is the version-selected tap set.
676///
677/// Dispatch: SIMD path on nightly + `simd`, scalar otherwise. The SIMD
678/// path is byte-exact against the scalar listing on every test fixture
679/// (`sixtap_2d_simd_matches_scalar_on_stress_inputs`).
680pub fn sixtap_2d(halo: &[u8; 81], mx: usize, my: usize, filters: &[[i32; 6]; 8]) -> [u8; 16] {
681    #[cfg(feature = "simd")]
682    {
683        sixtap_2d_simd(halo, mx, my, filters)
684    }
685    #[cfg(not(feature = "simd"))]
686    {
687        sixtap_identity_elide::<9, 4, 81, 16>(halo, mx, my, filters)
688            .unwrap_or_else(|| sixtap_2d_scalar(halo, mx, my, filters))
689    }
690}
691
692/// Scalar §20.14 `sixtap_2d` — the two-pass [`sixtap_horiz`] /
693/// [`sixtap_vert`] composition written as the spec listing.
694///
695/// The public [`sixtap_2d`] dispatches here on stable builds (and on
696/// nightly without the `simd` feature); the `simd` feature swaps in
697/// [`sixtap_2d_simd`], which is itself byte-exact against this
698/// implementation (`sixtap_2d_simd_matches_scalar_on_stress_inputs`).
699#[allow(dead_code)] // Used by `sixtap_2d` only on the !simd path.
700fn sixtap_2d_scalar(halo: &[u8; 81], mx: usize, my: usize, filters: &[[i32; 6]; 8]) -> [u8; 16] {
701    // Horizontal pass: 9 rows (the 4 block rows + 2 above + 3 below) ×
702    // 4 cols. Intermediate is 8-bit (clamped), stride 4.
703    //
704    // halo stride is 9; the block origin is at (2, 2). sixtap_horiz reads
705    // from "reference - 2*stride" with cols=4, rows=9 — i.e. starting at
706    // halo row 0, and each output column c reads halo[col-2 ..= col+3]
707    // relative to block-origin column 2. So ref0 = 2 (block-origin column
708    // within the halo), and the first row read is halo row 0 (the function
709    // adds no vertical offset; rows iterate 0..9 from ref0's row).
710    let mut temp = [0u8; 9 * 4];
711    sixtap_horiz(
712        &mut temp,
713        4,
714        halo,
715        9,
716        /* ref0 = */ 2, // block-origin column; row 0 of the 9-row span
717        4,
718        9,
719        &filters[mx],
720    );
721
722    // Vertical pass: 4 rows × 4 cols, reading the intermediate at "temp +
723    // 2*stride" — i.e. block-origin row 2 within the 9-row intermediate.
724    let mut out = [0u8; 16];
725    sixtap_vert(
726        &mut out,
727        4,
728        &temp,
729        4,
730        /* ref0 = */ 2 * 4, // block-origin row 2, column 0
731        4,
732        4,
733        &filters[my],
734    );
735    out
736}
737
738/// SIMD §18.3 / §20.14 `sixtap_2d` — `core::simd::Simd<i32, 4>` row
739/// rewrite of [`sixtap_2d_scalar`].
740///
741/// Both §20.14 passes produce rows of exactly four output samples (the
742/// 4×4 sub-block geometry), and within a row the four §18.3 `interp`
743/// dot products are independent — only the support window slides by one
744/// sample per output column. Each output row is therefore computed as
745/// one four-lane vector: for tap `k` the four lanes' support samples
746/// are a contiguous source run (`halo[r*9 + k ..][..4]`), so the six
747/// taps become six widen-multiply-accumulates of four lanes each in
748/// place of 24 scalar multiply-accumulates per row. The horizontal
749/// pass's clamped intermediate stays resident in `i32` vectors — every
750/// lane is already in `0..=255` after the lane-wise clamp, so the
751/// vertical pass reads the exact same sample values the scalar
752/// listing's 8-bit `temp` buffer would hold, without a narrow-to-u8 /
753/// widen-from-u8 round trip.
754///
755/// Lane type: the accumulator must be `i32`, not `i16`. The §18.3
756/// six-tap dot product `a = Σ fil[i] * p[i]` over `u8` support spans
757/// `[-32·255, 160·255] = [-8160, 40800]` (the ½-displacement row
758/// `{3, -16, 77, 77, -16, 3}` has positive-tap sum 160 and
759/// negative-tap sum −32), and `a + 64` reaches 40864 — past
760/// `i16::MAX`. `i32` lanes reproduce the scalar `i32` arithmetic
761/// exactly: the `(a + 64) >> 7` lane shift is the same sign-propagating
762/// arithmetic shift, `simd_clamp(0, 255)` is the lane-wise §14.5
763/// `clamp255`, and the post-clamp `cast::<u8>()` of a value already in
764/// `0..=255` equals the scalar `as u8`. Byte-exactness against
765/// [`sixtap_2d_scalar`] is enforced on every fixture by
766/// `sixtap_2d_simd_matches_scalar_on_stress_inputs`.
767#[cfg(feature = "simd")]
768#[inline]
769fn sixtap_2d_simd(halo: &[u8; 81], mx: usize, my: usize, filters: &[[i32; 6]; 8]) -> [u8; 16] {
770    use core::simd::Simd;
771    use core::simd::cmp::SimdOrd;
772    use core::simd::num::{SimdInt, SimdUint};
773
774    let zero = Simd::<i32, 4>::splat(0);
775    let max = Simd::<i32, 4>::splat(255);
776    let seven = Simd::<i32, 4>::splat(7);
777
778    // Horizontal pass: 9 rows (the 4 block rows + 2 above + 3 below) ×
779    // 4 cols — exactly the scalar `sixtap_horiz(temp, 4, halo, 9, ref0 =
780    // 2, 4, 9, filters[mx])` call. With the halo's block origin at
781    // column 2, output column c's tap-k support sample is
782    // halo[r*9 + c + k], so the four lanes of tap k are the contiguous
783    // run halo[r*9 + k .. r*9 + k + 4].
784    let fh = &filters[mx];
785    let fh_v: [Simd<i32, 4>; 6] = core::array::from_fn(|k| Simd::splat(fh[k]));
786    let mut temp = [Simd::<i32, 4>::splat(0); 9];
787    for (r, trow) in temp.iter_mut().enumerate() {
788        let row = &halo[r * 9..r * 9 + 9];
789        // §18.3 interp: a = Σ fil[k] * support[k]; seed with the +64
790        // rounding term so the shift below is the spec's (a + 64) >> 7.
791        let mut acc = Simd::<i32, 4>::splat(64);
792        for (k, tap) in fh_v.iter().enumerate() {
793            let support: Simd<i32, 4> = Simd::<u8, 4>::from_slice(&row[k..k + 4]).cast::<i32>();
794            acc += support * tap;
795        }
796        *trow = (acc >> seven).simd_clamp(zero, max);
797    }
798
799    // Vertical pass: 4 rows × 4 cols reading the intermediate at block-
800    // origin row 2 — the scalar `sixtap_vert(out, 4, temp, 4, ref0 = 8,
801    // 4, 4, filters[my])` call. Output row r's tap-k support row is
802    // temp row r + k (= ref0/4 + r + k - 2), already a four-lane vector.
803    let fv = &filters[my];
804    let fv_v: [Simd<i32, 4>; 6] = core::array::from_fn(|k| Simd::splat(fv[k]));
805    let mut out = [0u8; 16];
806    for r in 0..4 {
807        let mut acc = Simd::<i32, 4>::splat(64);
808        for (k, tap) in fv_v.iter().enumerate() {
809            acc += temp[r + k] * tap;
810        }
811        let res = (acc >> seven).simd_clamp(zero, max);
812        out[r * 4..r * 4 + 4].copy_from_slice(&res.cast::<u8>().to_array());
813    }
814    out
815}
816
817/// Fetch the 21×21 edge-replicated halo a whole-macroblock six-tap luma
818/// interpolation needs — RFC 6386 §20.14 `build_mc_border`, MB-scale.
819///
820/// All sixteen luma sub-blocks of a non-SPLITMV macroblock share one
821/// motion vector (§18.1), so the six-tap support of the whole 16×16 luma
822/// block is one contiguous `(16 + 5) × (16 + 5) = 21×21` region — the
823/// 16×16 block plus the two-before / three-after support pixels in each
824/// dimension. This is the MB-scale analogue of the per-sub-block
825/// [`fetch_block_halo`]: it covers source positions
826/// `[src_y0 - 2, src_y0 + 18] × [src_x0 - 2, src_x0 + 18]` (where
827/// `(src_x0, src_y0) = (mb_x, mb_y) + (mv >> 3)` is the integer-offset MB
828/// origin), clamping any out-of-plane read to the nearest edge pixel.
829/// The result is row-major with stride 21; the 16×16 block origin sits at
830/// `halo[(2, 2)]`, matching [`sixtap_mb_luma`]'s expectation.
831///
832/// Fetching one 21×21 region once and convolving it whole replaces the
833/// sixteen overlapping 9×9 [`fetch_block_halo`] fetches the per-sub-block
834/// path would issue, amortising the border / gather setup across the
835/// whole MB (the round-269 BENCHMARKS candidate "MB-scale §18.3
836/// batching").
837pub fn fetch_luma_mb_halo(
838    plane: &[u8],
839    stride: usize,
840    w: usize,
841    h: usize,
842    mb_x: usize,
843    mb_y: usize,
844    mv: Mv,
845) -> [u8; 21 * 21] {
846    let off_x = (mv.col >> 3) as isize;
847    let off_y = (mv.row >> 3) as isize;
848    // The halo origin is two pixels above/left of the integer MB origin
849    // (the first six-tap support pixel).
850    let src_x0 = mb_x as isize + off_x - 2;
851    let src_y0 = mb_y as isize + off_y - 2;
852
853    let w_i = w as isize;
854    let h_i = h as isize;
855    let mut out = [0u8; 21 * 21];
856
857    // Fast path mirroring [`fetch_block_halo`]: when the 21×21 halo lands
858    // strictly inside the plane (the dominant case for inter-MBs that
859    // don't touch the picture border), each output row is a contiguous
860    // 21-byte slice of the reference plane — no per-pixel `.clamp()`. The
861    // fallback below is bit-identical for halos that straddle the border.
862    if src_x0 >= 0 && src_y0 >= 0 && src_x0 + 21 <= w_i && src_y0 + 21 <= h_i {
863        let x0 = src_x0 as usize;
864        let y0 = src_y0 as usize;
865        for r in 0..21 {
866            let row_start = (y0 + r) * stride + x0;
867            out[r * 21..r * 21 + 21].copy_from_slice(&plane[row_start..row_start + 21]);
868        }
869        return out;
870    }
871
872    for r in 0..21 {
873        let sy = (src_y0 + r as isize).clamp(0, h_i - 1);
874        for c in 0..21 {
875            let sx = (src_x0 + c as isize).clamp(0, w_i - 1);
876            out[r * 21 + c] = plane[sy as usize * stride + sx as usize];
877        }
878    }
879    out
880}
881
882/// Two-dimensional six-tap interpolation of a whole 16×16 luma block —
883/// the MB-scale analogue of [`sixtap_2d`], RFC 6386 §18.3 / §20.14.
884///
885/// `halo` is the 21×21 edge-replicated source region from
886/// [`fetch_luma_mb_halo`]: row-major, stride 21, with the 16×16 block
887/// origin at `halo[(2, 2)]`. The horizontal pass synthesises a
888/// 16-wide × 21-tall intermediate (the 16 block rows plus the two-above /
889/// three-below support the vertical pass needs); the vertical pass then
890/// synthesises the final 16×16. `(mx, my)` are the eighth-pixel fractions
891/// (`mv & 7`); `filters` is the version-selected tap set.
892///
893/// This is byte-exact with applying [`sixtap_2d`] to each of the sixteen
894/// 4×4 sub-blocks separately: the §18.3 `interp` dot product is the same
895/// per output sample regardless of how the support is tiled, and the
896/// horizontal-pass intermediate is clamped identically (the §20.14
897/// `temp` buffer is 8-bit per sample). The win is fetching + convolving
898/// one 21×21 region instead of sixteen overlapping 9×9 regions.
899///
900/// Dispatch: SIMD path on nightly + `simd`, scalar otherwise — same shape
901/// as [`sixtap_2d`].
902pub fn sixtap_mb_luma(
903    halo: &[u8; 21 * 21],
904    mx: usize,
905    my: usize,
906    filters: &[[i32; 6]; 8],
907) -> [u8; 256] {
908    #[cfg(feature = "simd")]
909    {
910        sixtap_mb_luma_simd(halo, mx, my, filters)
911    }
912    #[cfg(not(feature = "simd"))]
913    {
914        sixtap_identity_elide::<21, 16, { 21 * 21 }, 256>(halo, mx, my, filters)
915            .unwrap_or_else(|| sixtap_block_runs::<21, 16, { 21 * 21 }, 256>(halo, mx, my, filters))
916    }
917}
918
919/// The §18.3 whole-pixel filter row `{0, 0, 128, 0, 0, 0}` — the one tap
920/// set for which a §20.14 convolution pass is the exact identity:
921/// `clamp255((128·p + 64) >> 7) = clamp255(p) = p` for every 8-bit
922/// sample `p` (both [`SIXTAP_FILTERS`]`[0]` and [`BILINEAR_FILTERS`]`[0]`
923/// are this row — §18.3 assigns the whole-pixel position no filtering in
924/// either set).
925#[cfg_attr(feature = "simd", allow(dead_code))] // simd builds route around the scalar elide.
926const IDENTITY_TAPS: [i32; 6] = [0, 0, 128, 0, 0, 0];
927
928/// Identity-pass elision for the scalar §20.14 two-pass six-tap
929/// convolution over one `OW×OW` block with its
930/// `HW×HW = (OW+5)×(OW+5)` edge-replicated halo (block origin at
931/// `halo[(2, 2)]`) — the shared fast-path gate in front of the
932/// stable-build [`sixtap_2d`] / [`sixtap_mb_luma`] /
933/// [`sixtap_mb_chroma`] scalar listings.
934///
935/// A §20.14 pass whose tap row equals [`IDENTITY_TAPS`] computes
936/// `clamp255((128·p + 64) >> 7)`, which is exactly `p` for every
937/// `p ∈ 0..=255` — the pass changes no sample. When one pass is the
938/// identity this runs **only the other pass**, as the identical
939/// [`sixtap_horiz`] / [`sixtap_vert`] reference listing reading the
940/// halo directly (the elided pass's output *is* its input); when both
941/// are, the block is the plain halo core copy. Any other tap pair
942/// returns `None` and the caller runs the unmodified two-pass listing.
943/// The gate compares the resolved tap *values*, not the fraction index,
944/// so a caller-supplied table without an identity row is unaffected
945/// (`sixtap_identity_elide_gates_on_tap_values`).
946///
947/// This fires constantly in the §17 sub-pixel refinement searches —
948/// half the probed candidates around a whole-pixel center have one
949/// whole-pixel component — and on every decoded inter MB whose MV has
950/// exactly one whole-pixel axis.
951///
952/// Byte-equivalence across all 64 `(mx, my)` fraction pairs × both
953/// shipped filter sets × the stress-halo matrix is pinned by the
954/// dispatcher-driven `sixtap_2d_simd_matches_scalar_on_stress_inputs` /
955/// `sixtap_mb_luma_simd_matches_scalar_on_stress_inputs` /
956/// `sixtap_mb_chroma_simd_matches_scalar_on_stress_inputs` tests (the
957/// scalar side of those comparisons is the retained un-elided listing).
958#[cfg_attr(feature = "simd", allow(dead_code))] // simd builds route around the scalar elide.
959#[inline]
960fn sixtap_identity_elide<const HW: usize, const OW: usize, const HN: usize, const ON: usize>(
961    halo: &[u8; HN],
962    mx: usize,
963    my: usize,
964    filters: &[[i32; 6]; 8],
965) -> Option<[u8; ON]> {
966    debug_assert_eq!(HW, OW + 5);
967    debug_assert_eq!(HN, HW * HW);
968    debug_assert_eq!(ON, OW * OW);
969
970    let ident_h = filters[mx] == IDENTITY_TAPS;
971    let ident_v = filters[my] == IDENTITY_TAPS;
972    if !ident_h && !ident_v {
973        return None;
974    }
975    let mut out = [0u8; ON];
976
977    if ident_h && ident_v {
978        // Both passes are the identity: the output is the OW×OW core of
979        // the halo at block origin (2, 2).
980        for r in 0..OW {
981            let base = (r + 2) * HW + 2;
982            out[r * OW..r * OW + OW].copy_from_slice(&halo[base..base + OW]);
983        }
984    } else if ident_h {
985        // Horizontal pass is the identity: its §20.14 intermediate
986        // equals the halo samples, so run the vertical §18.3 dot
987        // product directly over the halo at block-origin column 2
988        // (output row r, tap k reads halo row r + k — the same rows the
989        // intermediate would hold), one run per output row.
990        let mut rows = [[0u8; OW]; OW];
991        filter_rows(&mut rows, &TapPlan::new(&filters[my]), &halo[2..], HW, HW);
992        out.copy_from_slice(rows.as_flattened());
993    } else {
994        // Vertical pass is the identity: the output rows are the
995        // horizontal §18.3 dot product over halo rows 2..2+OW.
996        let mut rows = [[0u8; OW]; OW];
997        filter_rows(
998            &mut rows,
999            &TapPlan::new(&filters[mx]),
1000            &halo[2 * HW..],
1001            HW,
1002            1,
1003        );
1004        out.copy_from_slice(rows.as_flattened());
1005    }
1006    Some(out)
1007}
1008
1009/// Scalar MB-scale §20.14 `sixtap_2d` over a 16×16 luma block.
1010///
1011/// Horizontal pass: 21 rows × 16 cols, each output sample the §18.3
1012/// `interp` of the six horizontal support samples `halo[r*21 + c ..][..6]`
1013/// (block origin at halo column 2, so output column c reads
1014/// `halo[r*21 + c+2-2 ..= c+2+3]`). Intermediate clamped to 8-bit, stride
1015/// 16. Vertical pass: 16 rows × 16 cols reading the intermediate at block
1016/// origin row 2 (`temp` rows `r ..= r+5`).
1017#[allow(dead_code)] // Used by `sixtap_mb_luma` only on the !simd path.
1018fn sixtap_mb_luma_scalar(
1019    halo: &[u8; 21 * 21],
1020    mx: usize,
1021    my: usize,
1022    filters: &[[i32; 6]; 8],
1023) -> [u8; 256] {
1024    let fh = &filters[mx];
1025    let fv = &filters[my];
1026
1027    // Horizontal pass: 21 rows of 16 output samples.
1028    let mut temp = [0u8; 21 * 16];
1029    for r in 0..21 {
1030        let row_base = r * 21;
1031        for c in 0..16 {
1032            let mut support = [0u8; 6];
1033            for (k, s) in support.iter_mut().enumerate() {
1034                // Block origin is column 2; output column c reads
1035                // halo[c+2-2 ..= c+2+3] = halo[c ..= c+5].
1036                *s = halo[row_base + c + k];
1037            }
1038            temp[r * 16 + c] = interp(fh, &support);
1039        }
1040    }
1041
1042    // Vertical pass: 16 rows of 16 output samples, reading the
1043    // intermediate at block origin row 2.
1044    let mut out = [0u8; 256];
1045    for r in 0..16 {
1046        for c in 0..16 {
1047            let mut support = [0u8; 6];
1048            for (k, s) in support.iter_mut().enumerate() {
1049                // Block origin row is 2; output row r reads temp rows
1050                // r+2-2 ..= r+2+3 = r ..= r+5.
1051                *s = temp[(r + k) * 16 + c];
1052            }
1053            out[r * 16 + c] = interp(fv, &support);
1054        }
1055    }
1056    out
1057}
1058
1059/// SIMD MB-scale §18.3 / §20.14 `sixtap_2d` over a 16×16 luma block —
1060/// `core::simd::Simd<i32, 16>` row rewrite of [`sixtap_mb_luma_scalar`].
1061///
1062/// Each of the 21 horizontal-pass rows produces sixteen output samples
1063/// whose four §18.3 `interp` dot products are independent — only the
1064/// support window slides by one sample per output column. The whole row
1065/// is computed as one sixteen-lane vector: for tap `k` the sixteen lanes'
1066/// support samples are the contiguous source run `halo[r*21 + k ..][..16]`,
1067/// so the six taps become six widen-multiply-accumulates of sixteen lanes
1068/// each in place of 96 scalar multiply-accumulates per row. The
1069/// horizontal pass's clamped intermediate stays resident in `i32` vectors
1070/// (every lane already in `0..=255` after the lane-wise clamp), so the
1071/// vertical pass — sixteen output rows, each one sixteen-lane vector
1072/// summing six intermediate rows under the vertical taps — runs with zero
1073/// loads.
1074///
1075/// Lane type: the accumulator must be `i32`, not `i16`, for the same
1076/// reason as [`sixtap_2d_simd`]: the §18.3 six-tap dot product over `u8`
1077/// support spans `[-8160, 40800]` (the ½-displacement row sums positive
1078/// taps to 160), past `i16::MAX`. The `i32` lanes reproduce the scalar
1079/// `i32` arithmetic exactly. Byte-exactness against
1080/// [`sixtap_mb_luma_scalar`] (and, transitively, the per-sub-block
1081/// [`sixtap_2d`]) is enforced by
1082/// `sixtap_mb_luma_simd_matches_scalar_on_stress_inputs` /
1083/// `sixtap_mb_luma_matches_per_subblock_path`.
1084#[cfg(feature = "simd")]
1085#[inline]
1086fn sixtap_mb_luma_simd(
1087    halo: &[u8; 21 * 21],
1088    mx: usize,
1089    my: usize,
1090    filters: &[[i32; 6]; 8],
1091) -> [u8; 256] {
1092    use core::simd::Simd;
1093    use core::simd::cmp::SimdOrd;
1094    use core::simd::num::{SimdInt, SimdUint};
1095
1096    let zero = Simd::<i32, 16>::splat(0);
1097    let max = Simd::<i32, 16>::splat(255);
1098    let seven = Simd::<i32, 16>::splat(7);
1099
1100    // Horizontal pass: 21 rows × 16 cols. Output column c's tap-k support
1101    // sample is halo[r*21 + c + k] (block origin at column 2), so the
1102    // sixteen lanes of tap k are the contiguous run
1103    // halo[r*21 + k .. r*21 + k + 16].
1104    let fh = &filters[mx];
1105    let fh_v: [Simd<i32, 16>; 6] = core::array::from_fn(|k| Simd::splat(fh[k]));
1106    let mut temp = [Simd::<i32, 16>::splat(0); 21];
1107    for (r, trow) in temp.iter_mut().enumerate() {
1108        let row = &halo[r * 21..r * 21 + 21];
1109        let mut acc = Simd::<i32, 16>::splat(64);
1110        for (k, tap) in fh_v.iter().enumerate() {
1111            let support: Simd<i32, 16> = Simd::<u8, 16>::from_slice(&row[k..k + 16]).cast::<i32>();
1112            acc += support * tap;
1113        }
1114        *trow = (acc >> seven).simd_clamp(zero, max);
1115    }
1116
1117    // Vertical pass: 16 rows × 16 cols reading the intermediate at block
1118    // origin row 2. Output row r's tap-k support row is temp row r + k
1119    // (= ref0 + r + k - 2 with ref0 = 2), already a sixteen-lane vector.
1120    let fv = &filters[my];
1121    let fv_v: [Simd<i32, 16>; 6] = core::array::from_fn(|k| Simd::splat(fv[k]));
1122    let mut out = [0u8; 256];
1123    for r in 0..16 {
1124        let mut acc = Simd::<i32, 16>::splat(64);
1125        for (k, tap) in fv_v.iter().enumerate() {
1126            acc += temp[r + k] * tap;
1127        }
1128        let res = (acc >> seven).simd_clamp(zero, max);
1129        out[r * 16..r * 16 + 16].copy_from_slice(&res.cast::<u8>().to_array());
1130    }
1131    out
1132}
1133
1134/// Fetch the 13×13 edge-replicated halo a whole-macroblock six-tap chroma
1135/// interpolation needs — RFC 6386 §20.14 `build_mc_border`, MB-scale.
1136///
1137/// The four chroma sub-blocks of a non-SPLITMV macroblock share one §18.1
1138/// averaged motion vector ([`chroma_mv`]), so the six-tap support of the
1139/// whole 8×8 chroma block is one contiguous `(8 + 5) × (8 + 5) = 13×13`
1140/// region — the 8×8 block plus the two-before / three-after support pixels
1141/// in each dimension. This is the chroma analogue of the 16×16-luma
1142/// [`fetch_luma_mb_halo`]: it covers source positions
1143/// `[src_y0 - 2, src_y0 + 10] × [src_x0 - 2, src_x0 + 10]` (where
1144/// `(src_x0, src_y0) = (mb_x, mb_y) + (mv >> 3)` is the integer-offset
1145/// chroma-MB origin), clamping any out-of-plane read to the nearest edge
1146/// pixel. The result is row-major with stride 13; the 8×8 block origin sits
1147/// at `halo[(2, 2)]`, matching [`sixtap_mb_chroma`]'s expectation.
1148///
1149/// Fetching one 13×13 region once and convolving it whole replaces the
1150/// four overlapping 9×9 [`fetch_block_halo`] fetches the per-sub-block
1151/// chroma path would issue (the round-270 BENCHMARKS candidate "MB-scale
1152/// §18.3 chroma batching").
1153pub fn fetch_chroma_mb_halo(
1154    plane: &[u8],
1155    stride: usize,
1156    w: usize,
1157    h: usize,
1158    mb_x: usize,
1159    mb_y: usize,
1160    mv: Mv,
1161) -> [u8; 13 * 13] {
1162    let off_x = (mv.col >> 3) as isize;
1163    let off_y = (mv.row >> 3) as isize;
1164    // The halo origin is two pixels above/left of the integer chroma-MB
1165    // origin (the first six-tap support pixel).
1166    let src_x0 = mb_x as isize + off_x - 2;
1167    let src_y0 = mb_y as isize + off_y - 2;
1168
1169    let w_i = w as isize;
1170    let h_i = h as isize;
1171    let mut out = [0u8; 13 * 13];
1172
1173    // Fast path mirroring [`fetch_luma_mb_halo`]: when the 13×13 halo lands
1174    // strictly inside the plane (the dominant case for inter-MBs that don't
1175    // touch the picture border), each output row is a contiguous 13-byte
1176    // slice of the reference plane — no per-pixel `.clamp()`. The fallback
1177    // below is bit-identical for halos that straddle the border.
1178    if src_x0 >= 0 && src_y0 >= 0 && src_x0 + 13 <= w_i && src_y0 + 13 <= h_i {
1179        let x0 = src_x0 as usize;
1180        let y0 = src_y0 as usize;
1181        for r in 0..13 {
1182            let row_start = (y0 + r) * stride + x0;
1183            out[r * 13..r * 13 + 13].copy_from_slice(&plane[row_start..row_start + 13]);
1184        }
1185        return out;
1186    }
1187
1188    for r in 0..13 {
1189        let sy = (src_y0 + r as isize).clamp(0, h_i - 1);
1190        for c in 0..13 {
1191            let sx = (src_x0 + c as isize).clamp(0, w_i - 1);
1192            out[r * 13 + c] = plane[sy as usize * stride + sx as usize];
1193        }
1194    }
1195    out
1196}
1197
1198/// Two-dimensional six-tap interpolation of a whole 8×8 chroma block — the
1199/// chroma analogue of [`sixtap_mb_luma`], RFC 6386 §18.3 / §20.14.
1200///
1201/// `halo` is the 13×13 edge-replicated source region from
1202/// [`fetch_chroma_mb_halo`]: row-major, stride 13, with the 8×8 block
1203/// origin at `halo[(2, 2)]`. The horizontal pass synthesises a
1204/// 8-wide × 13-tall intermediate (the 8 block rows plus the two-above /
1205/// three-below support the vertical pass needs); the vertical pass then
1206/// synthesises the final 8×8. `(mx, my)` are the eighth-pixel fractions
1207/// (`mv & 7`); `filters` is the version-selected tap set.
1208///
1209/// This is byte-exact with applying [`sixtap_2d`] to each of the four 4×4
1210/// sub-blocks separately: the §18.3 `interp` dot product is the same per
1211/// output sample regardless of how the support is tiled, and the
1212/// horizontal-pass intermediate is clamped identically (the §20.14 `temp`
1213/// buffer is 8-bit per sample). The win is fetching + convolving one 13×13
1214/// region instead of four overlapping 9×9 regions.
1215///
1216/// Dispatch: SIMD path on nightly + `simd`, scalar otherwise — same shape
1217/// as [`sixtap_mb_luma`].
1218pub fn sixtap_mb_chroma(
1219    halo: &[u8; 13 * 13],
1220    mx: usize,
1221    my: usize,
1222    filters: &[[i32; 6]; 8],
1223) -> [u8; 64] {
1224    #[cfg(feature = "simd")]
1225    {
1226        sixtap_mb_chroma_simd(halo, mx, my, filters)
1227    }
1228    #[cfg(not(feature = "simd"))]
1229    {
1230        sixtap_identity_elide::<13, 8, { 13 * 13 }, 64>(halo, mx, my, filters)
1231            .unwrap_or_else(|| sixtap_mb_chroma_scalar(halo, mx, my, filters))
1232    }
1233}
1234
1235/// Differential probe for the fuzz harness: run the §18.3 / §20.14 4×4
1236/// sub-pixel synthesis through BOTH [`sixtap_2d_scalar`] and
1237/// [`sixtap_2d_simd`] and return `(scalar, simd)` so the caller can assert
1238/// byte-equality. Same argument contract as [`sixtap_2d`]
1239/// (`mx`, `my` ∈ 0..8).
1240///
1241/// Only compiled under the `simd` feature (without it there is exactly one
1242/// implementation and nothing to compare). Behaviour-neutral: nothing in
1243/// the decode or encode pipeline calls this — it exists so the
1244/// `decode_stream_token_descent` fuzz target can turn any scalar/SIMD
1245/// divergence on attacker-shaped inputs into a finding.
1246#[cfg(feature = "simd")]
1247#[doc(hidden)]
1248pub fn sixtap_2d_parity_pair(
1249    halo: &[u8; 81],
1250    mx: usize,
1251    my: usize,
1252    filters: &[[i32; 6]; 8],
1253) -> ([u8; 16], [u8; 16]) {
1254    (
1255        sixtap_2d_scalar(halo, mx, my, filters),
1256        sixtap_2d_simd(halo, mx, my, filters),
1257    )
1258}
1259
1260/// Differential probe for the fuzz harness: run the MB-scale §18.3 /
1261/// §20.14 luma synthesis through BOTH [`sixtap_mb_luma_scalar`] and
1262/// [`sixtap_mb_luma_simd`] and return `(scalar, simd)` so the caller can
1263/// assert byte-equality. Same argument contract as [`sixtap_mb_luma`].
1264///
1265/// Only compiled under the `simd` feature; behaviour-neutral (see
1266/// [`sixtap_2d_parity_pair`]).
1267#[cfg(feature = "simd")]
1268#[doc(hidden)]
1269pub fn sixtap_mb_luma_parity_pair(
1270    halo: &[u8; 21 * 21],
1271    mx: usize,
1272    my: usize,
1273    filters: &[[i32; 6]; 8],
1274) -> ([u8; 256], [u8; 256]) {
1275    (
1276        sixtap_mb_luma_scalar(halo, mx, my, filters),
1277        sixtap_mb_luma_simd(halo, mx, my, filters),
1278    )
1279}
1280
1281/// Differential probe for the fuzz harness: run the MB-scale §18.3 /
1282/// §20.14 chroma synthesis through BOTH [`sixtap_mb_chroma_scalar`] and
1283/// [`sixtap_mb_chroma_simd`] and return `(scalar, simd)` so the caller can
1284/// assert byte-equality. Same argument contract as [`sixtap_mb_chroma`].
1285///
1286/// Only compiled under the `simd` feature; behaviour-neutral (see
1287/// [`sixtap_2d_parity_pair`]).
1288#[cfg(feature = "simd")]
1289#[doc(hidden)]
1290pub fn sixtap_mb_chroma_parity_pair(
1291    halo: &[u8; 13 * 13],
1292    mx: usize,
1293    my: usize,
1294    filters: &[[i32; 6]; 8],
1295) -> ([u8; 64], [u8; 64]) {
1296    (
1297        sixtap_mb_chroma_scalar(halo, mx, my, filters),
1298        sixtap_mb_chroma_simd(halo, mx, my, filters),
1299    )
1300}
1301
1302/// Scalar MB-scale §20.14 `sixtap_2d` over an 8×8 chroma block.
1303///
1304/// Horizontal pass: 13 rows × 8 cols, each output sample the §18.3 `interp`
1305/// of the six horizontal support samples `halo[r*13 + c ..][..6]` (block
1306/// origin at halo column 2, so output column c reads
1307/// `halo[r*13 + c+2-2 ..= c+2+3]`). Intermediate clamped to 8-bit, stride
1308/// 8. Vertical pass: 8 rows × 8 cols reading the intermediate at block
1309/// origin row 2 (`temp` rows `r ..= r+5`).
1310#[allow(dead_code)] // Used by `sixtap_mb_chroma` only on the !simd path.
1311fn sixtap_mb_chroma_scalar(
1312    halo: &[u8; 13 * 13],
1313    mx: usize,
1314    my: usize,
1315    filters: &[[i32; 6]; 8],
1316) -> [u8; 64] {
1317    let fh = &filters[mx];
1318    let fv = &filters[my];
1319
1320    // Horizontal pass: 13 rows of 8 output samples.
1321    let mut temp = [0u8; 13 * 8];
1322    for r in 0..13 {
1323        let row_base = r * 13;
1324        for c in 0..8 {
1325            let mut support = [0u8; 6];
1326            for (k, s) in support.iter_mut().enumerate() {
1327                // Block origin is column 2; output column c reads
1328                // halo[c+2-2 ..= c+2+3] = halo[c ..= c+5].
1329                *s = halo[row_base + c + k];
1330            }
1331            temp[r * 8 + c] = interp(fh, &support);
1332        }
1333    }
1334
1335    // Vertical pass: 8 rows of 8 output samples, reading the intermediate
1336    // at block origin row 2.
1337    let mut out = [0u8; 64];
1338    for r in 0..8 {
1339        for c in 0..8 {
1340            let mut support = [0u8; 6];
1341            for (k, s) in support.iter_mut().enumerate() {
1342                // Block origin row is 2; output row r reads temp rows
1343                // r+2-2 ..= r+2+3 = r ..= r+5.
1344                *s = temp[(r + k) * 8 + c];
1345            }
1346            out[r * 8 + c] = interp(fv, &support);
1347        }
1348    }
1349    out
1350}
1351
1352/// SIMD MB-scale §18.3 / §20.14 `sixtap_2d` over an 8×8 chroma block —
1353/// `core::simd::Simd<i32, 8>` row rewrite of [`sixtap_mb_chroma_scalar`].
1354///
1355/// Each of the 13 horizontal-pass rows produces eight output samples whose
1356/// §18.3 `interp` dot products are independent — only the support window
1357/// slides by one sample per output column. The whole row is computed as
1358/// one eight-lane vector: for tap `k` the eight lanes' support samples are
1359/// the contiguous source run `halo[r*13 + k ..][..8]`, so the six taps
1360/// become six widen-multiply-accumulates of eight lanes each in place of 48
1361/// scalar multiply-accumulates per row. The horizontal pass's clamped
1362/// intermediate stays resident in `i32` vectors (every lane already in
1363/// `0..=255` after the lane-wise clamp), so the vertical pass — eight
1364/// output rows, each one eight-lane vector summing six intermediate rows
1365/// under the vertical taps — runs with zero loads.
1366///
1367/// Lane type: the accumulator must be `i32`, not `i16`, for the same reason
1368/// as [`sixtap_2d_simd`] / [`sixtap_mb_luma_simd`]: the §18.3 six-tap dot
1369/// product over `u8` support spans `[-8160, 40800]` (the ½-displacement row
1370/// sums positive taps to 160), past `i16::MAX`. The `i32` lanes reproduce
1371/// the scalar `i32` arithmetic exactly. Byte-exactness against
1372/// [`sixtap_mb_chroma_scalar`] (and, transitively, the per-sub-block
1373/// [`sixtap_2d`]) is enforced by
1374/// `sixtap_mb_chroma_simd_matches_scalar_on_stress_inputs` /
1375/// `sixtap_mb_chroma_matches_per_subblock_path`.
1376#[cfg(feature = "simd")]
1377#[inline]
1378fn sixtap_mb_chroma_simd(
1379    halo: &[u8; 13 * 13],
1380    mx: usize,
1381    my: usize,
1382    filters: &[[i32; 6]; 8],
1383) -> [u8; 64] {
1384    use core::simd::Simd;
1385    use core::simd::cmp::SimdOrd;
1386    use core::simd::num::{SimdInt, SimdUint};
1387
1388    let zero = Simd::<i32, 8>::splat(0);
1389    let max = Simd::<i32, 8>::splat(255);
1390    let seven = Simd::<i32, 8>::splat(7);
1391
1392    // Horizontal pass: 13 rows × 8 cols. Output column c's tap-k support
1393    // sample is halo[r*13 + c + k] (block origin at column 2), so the eight
1394    // lanes of tap k are the contiguous run halo[r*13 + k .. r*13 + k + 8].
1395    let fh = &filters[mx];
1396    let fh_v: [Simd<i32, 8>; 6] = core::array::from_fn(|k| Simd::splat(fh[k]));
1397    let mut temp = [Simd::<i32, 8>::splat(0); 13];
1398    for (r, trow) in temp.iter_mut().enumerate() {
1399        let row = &halo[r * 13..r * 13 + 13];
1400        let mut acc = Simd::<i32, 8>::splat(64);
1401        for (k, tap) in fh_v.iter().enumerate() {
1402            let support: Simd<i32, 8> = Simd::<u8, 8>::from_slice(&row[k..k + 8]).cast::<i32>();
1403            acc += support * tap;
1404        }
1405        *trow = (acc >> seven).simd_clamp(zero, max);
1406    }
1407
1408    // Vertical pass: 8 rows × 8 cols reading the intermediate at block
1409    // origin row 2. Output row r's tap-k support row is temp row r + k
1410    // (= ref0 + r + k - 2 with ref0 = 2), already an eight-lane vector.
1411    let fv = &filters[my];
1412    let fv_v: [Simd<i32, 8>; 6] = core::array::from_fn(|k| Simd::splat(fv[k]));
1413    let mut out = [0u8; 64];
1414    for r in 0..8 {
1415        let mut acc = Simd::<i32, 8>::splat(64);
1416        for (k, tap) in fv_v.iter().enumerate() {
1417            acc += temp[r + k] * tap;
1418        }
1419        let res = (acc >> seven).simd_clamp(zero, max);
1420        out[r * 8..r * 8 + 8].copy_from_slice(&res.cast::<u8>().to_array());
1421    }
1422    out
1423}
1424
1425/// Fetch a 4×4 whole-pixel prediction block from a reference plane with
1426/// the §20.14 `build_mc_border` edge-replication rule.
1427///
1428/// `mv` is the §18.1-adjusted (eighth-pixel) vector for this sub-block;
1429/// its fractional part must be zero (whole-pixel — see
1430/// [`whole_pixel_fraction_is_zero`]). The integer pixel offset is
1431/// `mv >> 3` per component (sign-propagating right shift, §18.2 "rounding
1432/// up or left by right-shifting each component 3 bits with sign
1433/// propagation").
1434///
1435/// `(blk_x, blk_y)` is the sub-block's top-left position in the plane in
1436/// pixels (before the motion offset). `plane` / `stride` describe the
1437/// reference plane; `w` / `h` are its width / height in pixels. Pixels
1438/// the source position would read outside `[0, w) × [0, h)` are clamped
1439/// to the nearest edge pixel — the whole-pixel specialisation of
1440/// `build_mc_border` (which, for an integer fetch, just replicates the
1441/// border row / column).
1442pub fn fetch_block_whole_pixel(
1443    plane: &[u8],
1444    stride: usize,
1445    w: usize,
1446    h: usize,
1447    blk_x: usize,
1448    blk_y: usize,
1449    mv: Mv,
1450) -> [u8; 16] {
1451    // §18.2: integer pixel offset is the eighth-pixel vector shifted
1452    // right 3 with sign propagation.
1453    let off_x = (mv.col >> 3) as isize;
1454    let off_y = (mv.row >> 3) as isize;
1455    let src_x0 = blk_x as isize + off_x;
1456    let src_y0 = blk_y as isize + off_y;
1457
1458    let w_i = w as isize;
1459    let h_i = h as isize;
1460    let mut out = [0u8; 16];
1461
1462    // Round-170 fast path: when all 16 source positions land strictly
1463    // inside the plane, no per-pixel `.clamp()` or bounds checks are
1464    // needed and each output row is a contiguous 4-byte slice of the
1465    // reference. This is the common case mid-frame; the edge-replication
1466    // fallback below stays bit-identical to the slow path for MBs that
1467    // straddle the picture border. (§20.14 `build_mc_border` semantics
1468    // are preserved — only the in-bounds branch is specialised.)
1469    if src_x0 >= 0 && src_y0 >= 0 && src_x0 + 4 <= w_i && src_y0 + 4 <= h_i {
1470        let x0 = src_x0 as usize;
1471        let y0 = src_y0 as usize;
1472        for r in 0..4 {
1473            let row_start = (y0 + r) * stride + x0;
1474            out[r * 4..r * 4 + 4].copy_from_slice(&plane[row_start..row_start + 4]);
1475        }
1476        return out;
1477    }
1478
1479    for r in 0..4 {
1480        // §20.14 build_mc_border: rows past the top / bottom edge read
1481        // the first / last in-bounds row (edge replication).
1482        let sy = (src_y0 + r as isize).clamp(0, h_i - 1);
1483        for c in 0..4 {
1484            // Columns past the left / right edge read the first / last
1485            // in-bounds column.
1486            let sx = (src_x0 + c as isize).clamp(0, w_i - 1);
1487            out[r * 4 + c] = plane[sy as usize * stride + sx as usize];
1488        }
1489    }
1490    out
1491}
1492
1493/// Fetch the whole 16×16 luma block of a non-SPLITMV inter MB under a
1494/// *whole-pixel* motion vector — the MB-scale analogue of
1495/// [`fetch_block_whole_pixel`], RFC 6386 §18.2 / §20.14 `build_mc_border`.
1496///
1497/// All sixteen luma sub-blocks of a non-SPLITMV MB share one motion vector
1498/// (§18.1); when that vector is whole-pixel (`mv & 7 == 0` per component)
1499/// the §18.3 prediction is "simply copied" — no convolution. The whole
1500/// 16×16 block is then one contiguous source region at integer offset
1501/// `(mb_x, mb_y) + (mv >> 3)`, so it can be fetched in one pass instead of
1502/// sixteen overlapping 4×4 [`fetch_block_whole_pixel`] calls (the
1503/// round-271 BENCHMARKS candidate "whole-pixel non-SPLITMV MB batching" —
1504/// pure gather amortisation, no convolution).
1505///
1506/// `(mb_x, mb_y)` is the MB's top-left luma position in pixels (before the
1507/// motion offset); `w` / `h` are the reference plane's pixel dimensions.
1508/// Source positions outside `[0, w) × [0, h)` replicate the nearest edge
1509/// pixel, exactly as [`fetch_block_whole_pixel`] does per 4×4 sub-block —
1510/// the §20.14 `build_mc_border` row / column replication. The result is
1511/// row-major with stride 16, matching the `out.y` layout
1512/// [`predict_inter_mb`] writes.
1513pub fn fetch_luma_mb_whole_pixel(
1514    plane: &[u8],
1515    stride: usize,
1516    w: usize,
1517    h: usize,
1518    mb_x: usize,
1519    mb_y: usize,
1520    mv: Mv,
1521) -> [u8; 256] {
1522    // §18.2: integer pixel offset is the eighth-pixel vector shifted right
1523    // 3 with sign propagation.
1524    let off_x = (mv.col >> 3) as isize;
1525    let off_y = (mv.row >> 3) as isize;
1526    let src_x0 = mb_x as isize + off_x;
1527    let src_y0 = mb_y as isize + off_y;
1528
1529    let w_i = w as isize;
1530    let h_i = h as isize;
1531    let mut out = [0u8; 256];
1532
1533    // Fast path mirroring [`fetch_block_whole_pixel`]: when all 16×16
1534    // source positions land strictly inside the plane (the dominant case
1535    // mid-frame), each output row is a contiguous 16-byte slice of the
1536    // reference. The fallback below is bit-identical for MBs that straddle
1537    // the picture border (§20.14 `build_mc_border` semantics preserved).
1538    if src_x0 >= 0 && src_y0 >= 0 && src_x0 + 16 <= w_i && src_y0 + 16 <= h_i {
1539        let x0 = src_x0 as usize;
1540        let y0 = src_y0 as usize;
1541        for r in 0..16 {
1542            let row_start = (y0 + r) * stride + x0;
1543            out[r * 16..r * 16 + 16].copy_from_slice(&plane[row_start..row_start + 16]);
1544        }
1545        return out;
1546    }
1547
1548    for r in 0..16 {
1549        // §20.14 build_mc_border: rows past the top / bottom edge read the
1550        // first / last in-bounds row (edge replication).
1551        let sy = (src_y0 + r as isize).clamp(0, h_i - 1) as usize;
1552        for c in 0..16 {
1553            // Columns past the left / right edge read the first / last
1554            // in-bounds column.
1555            let sx = (src_x0 + c as isize).clamp(0, w_i - 1) as usize;
1556            out[r * 16 + c] = plane[sy * stride + sx];
1557        }
1558    }
1559    out
1560}
1561
1562/// Fetch the whole 8×8 chroma block of a non-SPLITMV inter MB under a
1563/// *whole-pixel* (averaged) motion vector — the chroma analogue of
1564/// [`fetch_luma_mb_whole_pixel`], RFC 6386 §18.2 / §20.14
1565/// `build_mc_border`.
1566///
1567/// The four chroma sub-blocks of a non-SPLITMV MB share one §18.1 averaged
1568/// vector ([`chroma_mv`]); when that vector is whole-pixel the whole 8×8
1569/// block is one contiguous source region at integer offset
1570/// `(mb_x, mb_y) + (mv >> 3)`, fetched in one pass instead of four
1571/// overlapping 4×4 [`fetch_block_whole_pixel`] calls per plane.
1572///
1573/// `(mb_x, mb_y)` is the chroma-MB top-left position in pixels; `w` / `h`
1574/// are the chroma plane's pixel dimensions. Out-of-plane reads replicate
1575/// the nearest edge pixel. The result is row-major with stride 8, matching
1576/// the `out.u` / `out.v` layout [`predict_inter_mb`] writes.
1577pub fn fetch_chroma_mb_whole_pixel(
1578    plane: &[u8],
1579    stride: usize,
1580    w: usize,
1581    h: usize,
1582    mb_x: usize,
1583    mb_y: usize,
1584    mv: Mv,
1585) -> [u8; 64] {
1586    let off_x = (mv.col >> 3) as isize;
1587    let off_y = (mv.row >> 3) as isize;
1588    let src_x0 = mb_x as isize + off_x;
1589    let src_y0 = mb_y as isize + off_y;
1590
1591    let w_i = w as isize;
1592    let h_i = h as isize;
1593    let mut out = [0u8; 64];
1594
1595    if src_x0 >= 0 && src_y0 >= 0 && src_x0 + 8 <= w_i && src_y0 + 8 <= h_i {
1596        let x0 = src_x0 as usize;
1597        let y0 = src_y0 as usize;
1598        for r in 0..8 {
1599            let row_start = (y0 + r) * stride + x0;
1600            out[r * 8..r * 8 + 8].copy_from_slice(&plane[row_start..row_start + 8]);
1601        }
1602        return out;
1603    }
1604
1605    for r in 0..8 {
1606        let sy = (src_y0 + r as isize).clamp(0, h_i - 1) as usize;
1607        for c in 0..8 {
1608            let sx = (src_x0 + c as isize).clamp(0, w_i - 1) as usize;
1609            out[r * 8 + c] = plane[sy * stride + sx];
1610        }
1611    }
1612    out
1613}
1614
1615/// Fetch the 9×9 edge-replicated halo a six-tap 4×4 interpolation needs —
1616/// RFC 6386 §20.14 `build_mc_border` / `recon_1_edge_block`.
1617///
1618/// The six-tap convolution of a 4×4 sub-block references two pixels
1619/// before and three pixels after the block in each dimension, so the
1620/// source support is a `(4+5) × (4+5) = 9×9` region. This fetch
1621/// reproduces the §20.14 `build_mc_border` emulated block: it covers
1622/// source positions `[src_y0 - 2, src_y0 + 6] × [src_x0 - 2, src_x0 + 6]`
1623/// (where `(src_x0, src_y0) = (blk_x, blk_y) + (mv >> 3)` is the
1624/// integer-offset block origin), clamping any out-of-plane read to the
1625/// nearest edge pixel. The result is row-major with stride 9; the 4×4
1626/// block origin sits at `halo[(2, 2)]`, matching [`sixtap_2d`]'s
1627/// expectation.
1628///
1629/// For an in-bounds fetch this is just a 9×9 window; the clamp makes the
1630/// edge case identical to `build_mc_border`'s row/column replication,
1631/// which is the whole-pixel [`fetch_block_whole_pixel`] rule extended to
1632/// the support halo.
1633pub fn fetch_block_halo(
1634    plane: &[u8],
1635    stride: usize,
1636    w: usize,
1637    h: usize,
1638    blk_x: usize,
1639    blk_y: usize,
1640    mv: Mv,
1641) -> [u8; 81] {
1642    let off_x = (mv.col >> 3) as isize;
1643    let off_y = (mv.row >> 3) as isize;
1644    // The halo origin is two pixels above/left of the integer block
1645    // origin (the first six-tap support pixel).
1646    let src_x0 = blk_x as isize + off_x - 2;
1647    let src_y0 = blk_y as isize + off_y - 2;
1648
1649    let w_i = w as isize;
1650    let h_i = h as isize;
1651    let mut out = [0u8; 81];
1652
1653    // Round-170 fast path: when the 9×9 halo lands strictly inside the
1654    // plane (the dominant case for inter-MBs that don't touch the
1655    // picture border), each output row is a contiguous 9-byte slice of
1656    // the reference plane — no `.clamp()` per pixel, no per-byte bound
1657    // checks. The fallback below is bit-identical for halos that
1658    // straddle the border.
1659    if src_x0 >= 0 && src_y0 >= 0 && src_x0 + 9 <= w_i && src_y0 + 9 <= h_i {
1660        let x0 = src_x0 as usize;
1661        let y0 = src_y0 as usize;
1662        for r in 0..9 {
1663            let row_start = (y0 + r) * stride + x0;
1664            out[r * 9..r * 9 + 9].copy_from_slice(&plane[row_start..row_start + 9]);
1665        }
1666        return out;
1667    }
1668
1669    for r in 0..9 {
1670        let sy = (src_y0 + r as isize).clamp(0, h_i - 1);
1671        for c in 0..9 {
1672            let sx = (src_x0 + c as isize).clamp(0, w_i - 1);
1673            out[r * 9 + c] = plane[sy as usize * stride + sx as usize];
1674        }
1675    }
1676    out
1677}
1678
1679/// Predict one 4×4 sub-block — RFC 6386 §20.14 `filter_block`.
1680///
1681/// Mirrors the reference decoder's `filter_block`: extract the
1682/// eighth-pixel fractions `mx = mv.col & 7`, `my = mv.row & 7`. If both
1683/// are zero the prediction is the whole-pixel copy
1684/// ([`fetch_block_whole_pixel`]); otherwise it is the [`sixtap_2d`]
1685/// horizontal-then-vertical convolution of the [`fetch_block_halo`]
1686/// support region under the version-selected `filters`.
1687///
1688/// `mv` is the §18.1-adjusted (eighth-pixel) vector for this plane;
1689/// `(blk_x, blk_y)` is the sub-block's top-left position in the plane in
1690/// pixels (before the motion offset); `w` / `h` are the plane's pixel
1691/// dimensions.
1692#[allow(clippy::too_many_arguments)] // mirrors the §20.14 filter_block call shape.
1693pub fn filter_block_4x4(
1694    plane: &[u8],
1695    stride: usize,
1696    w: usize,
1697    h: usize,
1698    blk_x: usize,
1699    blk_y: usize,
1700    mv: Mv,
1701    filters: &[[i32; 6]; 8],
1702) -> [u8; 16] {
1703    let mx = (mv.col & 7) as usize;
1704    let my = (mv.row & 7) as usize;
1705    if mx == 0 && my == 0 {
1706        // Whole-pixel: the §18.3 "prediction subblock is simply copied".
1707        fetch_block_whole_pixel(plane, stride, w, h, blk_x, blk_y, mv)
1708    } else {
1709        let halo = fetch_block_halo(plane, stride, w, h, blk_x, blk_y, mv);
1710        sixtap_2d(&halo, mx, my, filters)
1711    }
1712}
1713
1714/// Predict one 4×4 sub-block and write it directly into a destination
1715/// raster — the strided-write companion of [`filter_block_4x4`].
1716///
1717/// [`filter_block_4x4`] returns a fixed `[u8; 16]` block that the caller
1718/// then re-copies row-by-row into a strided macroblock buffer (`out.y` /
1719/// `out.u` / `out.v`). For the per-sub-block SPLITMV path (sixteen luma plus
1720/// eight chroma calls per MB, RFC 6386 §16.4) every sub-block pays that
1721/// `[u8; 16]` scratch plus the four-row second copy. This entry point
1722/// folds the synthesis and the write into one pass:
1723///
1724/// * **Whole-pixel** (`mv & 7 == 0`, the §18.3 "simply copied" case): the
1725///   in-bounds fast path copies each source row straight into `dst` at
1726///   `(dst_x, dst_y)` — no `[u8; 16]` round trip. The border-straddle
1727///   fallback is the §20.14 `build_mc_border` per-pixel edge replication,
1728///   bit-identical to [`fetch_block_whole_pixel`]'s slow path.
1729/// * **Sub-pixel**: delegates the pixel computation to [`filter_block_4x4`]
1730///   unchanged (so the `sixtap_2d` SIMD dispatch and its byte-exactness
1731///   proof carry verbatim) and writes the returned block strided in one
1732///   place.
1733///
1734/// `dst` is the destination plane, `dst_stride` its row stride, and
1735/// `(dst_x, dst_y)` the sub-block's top-left position within it. The
1736/// remaining arguments match [`filter_block_4x4`]. Byte-exact against
1737/// "[`filter_block_4x4`] then a four-row strided copy" on every input
1738/// (`filter_block_4x4_into_matches_filter_block_4x4`).
1739#[allow(clippy::too_many_arguments)] // mirrors filter_block_4x4 plus the destination triple.
1740pub fn filter_block_4x4_into(
1741    dst: &mut [u8],
1742    dst_stride: usize,
1743    dst_x: usize,
1744    dst_y: usize,
1745    plane: &[u8],
1746    stride: usize,
1747    w: usize,
1748    h: usize,
1749    blk_x: usize,
1750    blk_y: usize,
1751    mv: Mv,
1752    filters: &[[i32; 6]; 8],
1753) {
1754    let mx = (mv.col & 7) as usize;
1755    let my = (mv.row & 7) as usize;
1756    if mx == 0 && my == 0 {
1757        // §18.3 whole-pixel: the prediction sub-block is the source region
1758        // at integer offset `(blk_x, blk_y) + (mv >> 3)`, copied directly
1759        // into `dst` without the intermediate `[u8; 16]` block.
1760        let off_x = (mv.col >> 3) as isize;
1761        let off_y = (mv.row >> 3) as isize;
1762        let src_x0 = blk_x as isize + off_x;
1763        let src_y0 = blk_y as isize + off_y;
1764        let w_i = w as isize;
1765        let h_i = h as isize;
1766
1767        if src_x0 >= 0 && src_y0 >= 0 && src_x0 + 4 <= w_i && src_y0 + 4 <= h_i {
1768            // Fast path: each source row is a contiguous 4-byte run copied
1769            // straight into the destination row.
1770            let x0 = src_x0 as usize;
1771            let y0 = src_y0 as usize;
1772            for r in 0..4 {
1773                let src = (y0 + r) * stride + x0;
1774                let d = (dst_y + r) * dst_stride + dst_x;
1775                dst[d..d + 4].copy_from_slice(&plane[src..src + 4]);
1776            }
1777        } else {
1778            // §20.14 build_mc_border edge replication, bit-identical to
1779            // `fetch_block_whole_pixel`'s slow path.
1780            for r in 0..4 {
1781                let sy = (src_y0 + r as isize).clamp(0, h_i - 1) as usize;
1782                let d = (dst_y + r) * dst_stride + dst_x;
1783                for c in 0..4 {
1784                    let sx = (src_x0 + c as isize).clamp(0, w_i - 1) as usize;
1785                    dst[d + c] = plane[sy * stride + sx];
1786                }
1787            }
1788        }
1789    } else {
1790        // Sub-pixel: reuse the exact `filter_block_4x4` synthesis (SIMD
1791        // dispatch + byte-exactness preserved), write the result strided.
1792        let blk = filter_block_4x4(plane, stride, w, h, blk_x, blk_y, mv, filters);
1793        for r in 0..4 {
1794            let d = (dst_y + r) * dst_stride + dst_x;
1795            dst[d..d + 4].copy_from_slice(&blk[r * 4..r * 4 + 4]);
1796        }
1797    }
1798}
1799
1800/// Build the §18.2 whole-pixel prediction buffer for a non-SPLITMV
1801/// inter-predicted macroblock.
1802///
1803/// The same `luma_mv` (raw §17-decoded, quarter-pixel) applies to all
1804/// sixteen Y sub-blocks; the chroma vector is the §18.1 average of that
1805/// one vector. `full_pixel` is the version-3 full-pel-chroma flag
1806/// (`frame_hdr.version == 3`).
1807///
1808/// Returns the predicted macroblock (no residue) as a
1809/// [`ReconstructedMb`], or [`MotionCompError::SubPixelNotSupported`] if
1810/// the §18.1-adjusted luma or chroma vector has a non-zero fractional
1811/// part (sub-pixel interpolation is a future round).
1812///
1813/// `(mb_col, mb_row)` is the macroblock position; the reference planes
1814/// supply the dimensions.
1815pub fn predict_inter_mb_whole_pixel(
1816    reference: &ReferencePlanes<'_>,
1817    mb_col: usize,
1818    mb_row: usize,
1819    luma_mv: Mv,
1820    full_pixel: bool,
1821) -> Result<ReconstructedMb, MotionCompError> {
1822    // §18.1: double the quarter-pixel luma vector to eighth-pixel
1823    // resolution.
1824    let mut ymv = stored_luma_mv(luma_mv);
1825    // §18.1 chroma averaging (avg() of the single repeated vector).
1826    let mut uvmv = chroma_mv(ymv);
1827    if full_pixel {
1828        // §18.1 version-3 full-pel-chroma truncation.
1829        ymv = apply_full_pixel(ymv);
1830        uvmv = apply_full_pixel(uvmv);
1831    }
1832
1833    // §18.3 whole-pixel gate: both fractions must be zero.
1834    if !whole_pixel_fraction_is_zero(ymv) || !whole_pixel_fraction_is_zero(uvmv) {
1835        return Err(MotionCompError::SubPixelNotSupported);
1836    }
1837
1838    let lw = reference.mb_cols * 16;
1839    let lh = reference.mb_rows * 16;
1840    let cw = reference.mb_cols * 8;
1841    let ch = reference.mb_rows * 8;
1842
1843    let mut out = ReconstructedMb::default();
1844
1845    // Luma: sixteen 4×4 sub-blocks, each fetched with the same ymv.
1846    let y_x0 = mb_col * 16;
1847    let y_y0 = mb_row * 16;
1848    for sb in 0..4 {
1849        for sc in 0..4 {
1850            let blk = fetch_block_whole_pixel(
1851                reference.y,
1852                reference.y_stride,
1853                lw,
1854                lh,
1855                y_x0 + sc * 4,
1856                y_y0 + sb * 4,
1857                ymv,
1858            );
1859            // Write into the 16×16 row-major output.
1860            for r in 0..4 {
1861                let dst = (sb * 4 + r) * 16 + sc * 4;
1862                out.y[dst..dst + 4].copy_from_slice(&blk[r * 4..r * 4 + 4]);
1863            }
1864        }
1865    }
1866
1867    // Chroma: four 4×4 sub-blocks per plane, each fetched with uvmv.
1868    let uv_x0 = mb_col * 8;
1869    let uv_y0 = mb_row * 8;
1870    for sb in 0..2 {
1871        for sc in 0..2 {
1872            let ublk = fetch_block_whole_pixel(
1873                reference.u,
1874                reference.uv_stride,
1875                cw,
1876                ch,
1877                uv_x0 + sc * 4,
1878                uv_y0 + sb * 4,
1879                uvmv,
1880            );
1881            let vblk = fetch_block_whole_pixel(
1882                reference.v,
1883                reference.uv_stride,
1884                cw,
1885                ch,
1886                uv_x0 + sc * 4,
1887                uv_y0 + sb * 4,
1888                uvmv,
1889            );
1890            for r in 0..4 {
1891                let dst = (sb * 4 + r) * 8 + sc * 4;
1892                out.u[dst..dst + 4].copy_from_slice(&ublk[r * 4..r * 4 + 4]);
1893                out.v[dst..dst + 4].copy_from_slice(&vblk[r * 4..r * 4 + 4]);
1894            }
1895        }
1896    }
1897
1898    Ok(out)
1899}
1900
1901/// Reconstruct one whole-pixel inter-predicted (non-SPLITMV)
1902/// macroblock — RFC 6386 §16.2 / §18 prediction + §14 residue.
1903///
1904/// This is the inter analogue of [`crate::reconstruct::decode_keyframe_mb_non_bpred`]:
1905///
1906/// 1. Build the §18.2 whole-pixel prediction buffer
1907///    ([`predict_inter_mb_whole_pixel`]).
1908/// 2. If `mb_skip_coeff`, the residue is zero and the prediction is the
1909///    reconstruction (§11.1 skip short-circuit).
1910/// 3. Otherwise inverse-WHT the Y2 block (an inter non-SPLITMV MB has a
1911///    Y2 block, §14.2), seed each Y sub-block DC, inverse-DCT all 24
1912///    sub-blocks, and add the residue with `clamp255` (§14.5).
1913///
1914/// The coefficient arrays are pre-dequantized (the caller's
1915/// responsibility, matching the keyframe path).
1916///
1917/// Returns [`MotionCompError::SubPixelNotSupported`] when the vector is
1918/// not whole-pixel.
1919#[allow(clippy::too_many_arguments)] // each parameter is a distinct §14.2/§18 input.
1920pub fn reconstruct_inter_mb_whole_pixel(
1921    reference: &ReferencePlanes<'_>,
1922    mb_col: usize,
1923    mb_row: usize,
1924    luma_mv: Mv,
1925    full_pixel: bool,
1926    mb_skip_coeff: bool,
1927    y2_coeffs_dequant: &[i16; 16],
1928    y_coeffs_dequant: &[[i16; 16]; 16],
1929    u_coeffs_dequant: &[[i16; 16]; 4],
1930    v_coeffs_dequant: &[[i16; 16]; 4],
1931) -> Result<ReconstructedMb, MotionCompError> {
1932    let mut out = predict_inter_mb_whole_pixel(reference, mb_col, mb_row, luma_mv, full_pixel)?;
1933
1934    if mb_skip_coeff {
1935        return Ok(out);
1936    }
1937
1938    // §14.2: inverse-WHT Y2 and seed each Y sub-block's DC.
1939    let mut y2_residue = [0i16; 16];
1940    inverse_wht_4x4(y2_coeffs_dequant, &mut y2_residue);
1941    let mut y_coeffs = *y_coeffs_dequant;
1942    for i in 0..4 {
1943        for j in 0..4 {
1944            y_coeffs[i * 4 + j][0] = y2_residue[i * 4 + j];
1945        }
1946    }
1947
1948    // Luma: §14.4 inverse-DCT fused with the §14.5 add-clamp into the
1949    // stride-16 prediction raster (round 286), matching the
1950    // [`reconstruct_inter_mb`] path. Bit-identical to the prior
1951    // inverse_dct_4x4 → extract/add/insert sequence.
1952    for i in 0..4 {
1953        for j in 0..4 {
1954            let idx = i * 4 + j;
1955            inverse_dct_4x4_add_into(&y_coeffs[idx], &mut out.y, 16, i, j);
1956        }
1957    }
1958
1959    // Chroma: same fused IDCT + add-clamp, U then V, stride 8.
1960    for i in 0..2 {
1961        for j in 0..2 {
1962            let idx = i * 2 + j;
1963            inverse_dct_4x4_add_into(&u_coeffs_dequant[idx], &mut out.u, 8, i, j);
1964            inverse_dct_4x4_add_into(&v_coeffs_dequant[idx], &mut out.v, 8, i, j);
1965        }
1966    }
1967
1968    Ok(out)
1969}
1970
1971/// Build the §18.2 prediction buffer for a non-SPLITMV inter-predicted
1972/// macroblock, with §18.3 sub-pixel interpolation — RFC 6386 §18.
1973///
1974/// The full prediction path: the same `luma_mv` (raw §17-decoded,
1975/// quarter-pixel) applies to all sixteen Y sub-blocks; the chroma vector
1976/// is the §18.1 average of that one vector. Each sub-block is routed
1977/// through [`filter_block_4x4`], which copies whole-pixel sub-blocks and
1978/// six-tap-interpolates sub-pixel sub-blocks under `filters`.
1979///
1980/// `full_pixel` is the version-3 full-pel-chroma flag
1981/// (`frame_hdr.version == 3`); `filters` is the §20.14 version-selected
1982/// tap set (use [`filter_set_for_version`] then [`FilterSet::taps`]).
1983///
1984/// `(mb_col, mb_row)` is the macroblock position; the reference planes
1985/// supply the dimensions.
1986pub fn predict_inter_mb(
1987    reference: &ReferencePlanes<'_>,
1988    mb_col: usize,
1989    mb_row: usize,
1990    luma_mv: Mv,
1991    full_pixel: bool,
1992    filters: &[[i32; 6]; 8],
1993) -> ReconstructedMb {
1994    // §18.1: double the quarter-pixel luma vector to eighth-pixel
1995    // resolution.
1996    let mut ymv = stored_luma_mv(luma_mv);
1997    // §18.1 chroma averaging (avg() of the single repeated vector).
1998    let mut uvmv = chroma_mv(ymv);
1999    if full_pixel {
2000        // §18.1 version-3 full-pel-chroma truncation.
2001        ymv = apply_full_pixel(ymv);
2002        uvmv = apply_full_pixel(uvmv);
2003    }
2004
2005    let lw = reference.mb_cols * 16;
2006    let lh = reference.mb_rows * 16;
2007    let cw = reference.mb_cols * 8;
2008    let ch = reference.mb_rows * 8;
2009
2010    let mut out = ReconstructedMb::default();
2011
2012    // Luma: all sixteen 4×4 sub-blocks share `ymv` (§18.1), so a
2013    // sub-pixel vector is interpolated as one whole-MB §18.3 pass off a
2014    // single 21×21 halo ([`sixtap_mb_luma`]) — byte-exact with sixteen
2015    // separate [`filter_block_4x4`] / [`sixtap_2d`] calls but amortising
2016    // the fetch + setup. A whole-pixel vector keeps the per-sub-block
2017    // copy fast path (`filter_block_4x4` → `fetch_block_whole_pixel`).
2018    let y_x0 = mb_col * 16;
2019    let y_y0 = mb_row * 16;
2020    let mx = (ymv.col & 7) as usize;
2021    let my = (ymv.row & 7) as usize;
2022    if mx == 0 && my == 0 {
2023        // Whole-pixel: the whole 16×16 luma block is one contiguous source
2024        // region (all sixteen sub-blocks share `ymv`, §18.1), fetched in
2025        // one pass ([`fetch_luma_mb_whole_pixel`]) instead of sixteen 4×4
2026        // [`fetch_block_whole_pixel`] copies — byte-identical, amortising
2027        // the per-sub-block gather setup.
2028        out.y = fetch_luma_mb_whole_pixel(reference.y, reference.y_stride, lw, lh, y_x0, y_y0, ymv);
2029    } else {
2030        let halo = fetch_luma_mb_halo(reference.y, reference.y_stride, lw, lh, y_x0, y_y0, ymv);
2031        out.y = sixtap_mb_luma(&halo, mx, my, filters);
2032    }
2033
2034    // Chroma: the four 4×4 sub-blocks per plane share `uvmv` (§18.1), so a
2035    // sub-pixel vector is interpolated as one whole-MB §18.3 pass off a
2036    // single 13×13 halo ([`sixtap_mb_chroma`]) — byte-exact with four
2037    // separate [`filter_block_4x4`] / [`sixtap_2d`] calls but amortising
2038    // the fetch + setup, the chroma analogue of the luma MB-batched path
2039    // above. A whole-pixel vector keeps the per-sub-block copy fast path.
2040    let uv_x0 = mb_col * 8;
2041    let uv_y0 = mb_row * 8;
2042    let cmx = (uvmv.col & 7) as usize;
2043    let cmy = (uvmv.row & 7) as usize;
2044    if cmx == 0 && cmy == 0 {
2045        // Whole-pixel chroma: each 8×8 plane is one contiguous source
2046        // region (all four sub-blocks share `uvmv`, §18.1), fetched in one
2047        // pass per plane ([`fetch_chroma_mb_whole_pixel`]) instead of four
2048        // 4×4 [`fetch_block_whole_pixel`] copies — the chroma analogue of
2049        // the luma whole-pixel batch above.
2050        out.u = fetch_chroma_mb_whole_pixel(
2051            reference.u,
2052            reference.uv_stride,
2053            cw,
2054            ch,
2055            uv_x0,
2056            uv_y0,
2057            uvmv,
2058        );
2059        out.v = fetch_chroma_mb_whole_pixel(
2060            reference.v,
2061            reference.uv_stride,
2062            cw,
2063            ch,
2064            uv_x0,
2065            uv_y0,
2066            uvmv,
2067        );
2068    } else {
2069        let uhalo =
2070            fetch_chroma_mb_halo(reference.u, reference.uv_stride, cw, ch, uv_x0, uv_y0, uvmv);
2071        let vhalo =
2072            fetch_chroma_mb_halo(reference.v, reference.uv_stride, cw, ch, uv_x0, uv_y0, uvmv);
2073        out.u = sixtap_mb_chroma(&uhalo, cmx, cmy, filters);
2074        out.v = sixtap_mb_chroma(&vhalo, cmx, cmy, filters);
2075    }
2076
2077    out
2078}
2079
2080/// Reconstruct one inter-predicted (non-SPLITMV) macroblock with §18.3
2081/// sub-pixel interpolation — RFC 6386 §16.2 / §18 prediction + §14
2082/// residue.
2083///
2084/// The full-resolution analogue of [`reconstruct_inter_mb_whole_pixel`]:
2085///
2086/// 1. Build the §18.2/§18.3 prediction buffer ([`predict_inter_mb`],
2087///    whole-pixel copy or six-tap interpolation per sub-block).
2088/// 2. If `mb_skip_coeff`, the residue is zero and the prediction is the
2089///    reconstruction (§11.1 skip short-circuit).
2090/// 3. Otherwise inverse-WHT the Y2 block (an inter non-SPLITMV MB has a
2091///    Y2 block, §14.2), seed each Y sub-block DC, inverse-DCT all 24
2092///    sub-blocks, and add the residue with `clamp255` (§14.5).
2093///
2094/// `filters` is the §20.14 version-selected tap set. The coefficient
2095/// arrays are pre-dequantized (the caller's responsibility, matching the
2096/// keyframe path).
2097#[allow(clippy::too_many_arguments)] // each parameter is a distinct §14.2/§18 input.
2098pub fn reconstruct_inter_mb(
2099    reference: &ReferencePlanes<'_>,
2100    mb_col: usize,
2101    mb_row: usize,
2102    luma_mv: Mv,
2103    full_pixel: bool,
2104    filters: &[[i32; 6]; 8],
2105    mb_skip_coeff: bool,
2106    y2_coeffs_dequant: &[i16; 16],
2107    y_coeffs_dequant: &[[i16; 16]; 16],
2108    u_coeffs_dequant: &[[i16; 16]; 4],
2109    v_coeffs_dequant: &[[i16; 16]; 4],
2110) -> ReconstructedMb {
2111    let mut out = predict_inter_mb(reference, mb_col, mb_row, luma_mv, full_pixel, filters);
2112
2113    if mb_skip_coeff {
2114        return out;
2115    }
2116
2117    // §14.2: inverse-WHT Y2 and seed each Y sub-block's DC.
2118    let mut y2_residue = [0i16; 16];
2119    inverse_wht_4x4(y2_coeffs_dequant, &mut y2_residue);
2120    let mut y_coeffs = *y_coeffs_dequant;
2121    for i in 0..4 {
2122        for j in 0..4 {
2123            y_coeffs[i * 4 + j][0] = y2_residue[i * 4 + j];
2124        }
2125    }
2126
2127    // Luma: §14.4 inverse-DCT fused with the §14.5 add-clamp written
2128    // straight into the stride-16 prediction raster (round 286). The
2129    // fused helper replaces the prior inverse_dct_4x4 → extract_4x4 →
2130    // add_residue_4x4 → insert_4x4 four-buffer round-trip; output is
2131    // bit-identical (the transform arithmetic and per-pixel clamp are
2132    // unchanged). See `BENCHMARKS.md` round 286.
2133    for i in 0..4 {
2134        for j in 0..4 {
2135            let idx = i * 4 + j;
2136            inverse_dct_4x4_add_into(&y_coeffs[idx], &mut out.y, 16, i, j);
2137        }
2138    }
2139
2140    // Chroma: same fused IDCT + add-clamp, U then V, stride 8.
2141    for i in 0..2 {
2142        for j in 0..2 {
2143            let idx = i * 2 + j;
2144            inverse_dct_4x4_add_into(&u_coeffs_dequant[idx], &mut out.u, 8, i, j);
2145            inverse_dct_4x4_add_into(&v_coeffs_dequant[idx], &mut out.v, 8, i, j);
2146        }
2147    }
2148
2149    out
2150}
2151
2152// ───────────────────────── §16.4 / §18 SPLITMV ─────────────────────────────
2153
2154/// The §18.1 chroma sub-block index of luma sub-block `b` (`0..=15`) —
2155/// RFC 6386 §18.1, the §20.11 expression `(b>>1&1) + (b>>2&2)`.
2156///
2157/// Maps the sixteen Y sub-blocks onto the four chroma sub-blocks (each
2158/// chroma sub-block covers four luma sub-blocks); the closed form expands
2159/// to the §18.1 enumeration `{0,1,4,5}→0`, `{2,3,6,7}→1`, `{8,9,12,13}→2`,
2160/// `{10,11,14,15}→3`.
2161#[inline]
2162pub fn chroma_idx_for_luma_subblock(b: usize) -> usize {
2163    ((b >> 1) & 1) + ((b >> 2) & 2)
2164}
2165
2166/// Derive the four §18.1 chroma sub-block motion vectors from the sixteen
2167/// SPLITMV per-luma-sub-block vectors — RFC 6386 §18.1 `avg(...)`.
2168///
2169/// Per §18.1 each chroma sub-block's vector is the four-vector average of
2170/// the four luma sub-blocks occupying the same visible area; the §20.14
2171/// `avg()` primitive (also used by [`chroma_mv`] for the whole-MB case)
2172/// performs the divide-by-8 + sign-aware rounding. `split_luma_mvs` are
2173/// the raw quarter-pixel per-sub-block vectors (the SPLITMV decode output);
2174/// the result is in eighth-pixel units already (matching `chroma_mv`).
2175pub fn split_chroma_mvs(split_luma_mvs: &[Mv; 16]) -> [Mv; 4] {
2176    // Sum the (doubled) luma components per chroma slot.
2177    let mut sum_row = [0i32; 4];
2178    let mut sum_col = [0i32; 4];
2179    for (b, mv) in split_luma_mvs.iter().enumerate() {
2180        let c = chroma_idx_for_luma_subblock(b);
2181        // §18.1 "stored luma motion vectors are all doubled": the §20.11
2182        // chroma loop sums the *doubled* vectors before the avg(). We mimic
2183        // by stacking 4 copies of the stored-luma value into the §18.1 avg.
2184        let r = (mv.row as i32).wrapping_mul(2);
2185        let cc = (mv.col as i32).wrapping_mul(2);
2186        sum_row[c] = sum_row[c].wrapping_add(r);
2187        sum_col[c] = sum_col[c].wrapping_add(cc);
2188    }
2189    let mut out = [Mv::default(); 4];
2190    for c in 0..4 {
2191        let s_r = sum_row[c];
2192        let s_c = sum_col[c];
2193        // §18.1 avg(): sign-aware divide-by-8 with rounding adjustment.
2194        let row = if s_r >= 0 {
2195            (s_r + 4) >> 3
2196        } else {
2197            -((-s_r + 4) >> 3)
2198        };
2199        let col = if s_c >= 0 {
2200            (s_c + 4) >> 3
2201        } else {
2202            -((-s_c + 4) >> 3)
2203        };
2204        out[c] = Mv {
2205            row: row as i16,
2206            col: col as i16,
2207        };
2208    }
2209    out
2210}
2211
2212/// Build the §18.2/§18.3 prediction buffer for a SPLITMV inter-predicted
2213/// macroblock — RFC 6386 §16.4 / §18.
2214///
2215/// Sixteen luma sub-blocks, each interpolated under *its own* quarter-pixel
2216/// vector (after the §18.1 doubling); four chroma sub-blocks per plane,
2217/// each interpolated under the §18.1 four-vector average of the
2218/// corresponding luma group ([`split_chroma_mvs`]).
2219///
2220/// Unlike [`predict_inter_mb`], no §18.1 secondary clamp is applied —
2221/// §18.1 page 114 "secondary clamping is not performed for SPLITMV
2222/// macroblocks, meaning any subblock's motion vector ... may point outside
2223/// the clamping zone."
2224///
2225/// `full_pixel` is the version-3 full-pel-chroma flag; `filters` is the
2226/// §20.14 version-selected tap set; `split_luma_mvs` is the
2227/// [`crate::near_mv::SplitMvResult::split_mvs`] field.
2228pub fn predict_split_mv(
2229    reference: &ReferencePlanes<'_>,
2230    mb_col: usize,
2231    mb_row: usize,
2232    split_luma_mvs: &[Mv; 16],
2233    full_pixel: bool,
2234    filters: &[[i32; 6]; 8],
2235) -> ReconstructedMb {
2236    let lw = reference.mb_cols * 16;
2237    let lh = reference.mb_rows * 16;
2238    let cw = reference.mb_cols * 8;
2239    let ch = reference.mb_rows * 8;
2240
2241    let mut out = ReconstructedMb::default();
2242
2243    // Luma: each 4×4 sub-block under its own §18.1-doubled vector. The
2244    // sixteen vectors are distinct (SPLITMV), so the MB-scale shared-halo
2245    // batch ([`sixtap_mb_luma`], rounds 270–272) does not apply. The
2246    // per-sub-block synthesis builds a contiguous `[u8; 16]` block and
2247    // copies it four contiguous rows at a time into `out.y`: a round-274
2248    // bench (`motion_comp_subpel_luma/splitmv_predict_*`) measured this
2249    // scratch-then-copy form ~23 % FASTER than a strided-write variant
2250    // (`filter_block_4x4_into`) that writes each sub-block directly into the
2251    // stride-16 raster — the contiguous block lets the compiler vectorise
2252    // the per-row writes where the scattered strided writes can't. See
2253    // `BENCHMARKS.md` round-274 for the A/B.
2254    let y_x0 = mb_col * 16;
2255    let y_y0 = mb_row * 16;
2256    for sb in 0..4 {
2257        for sc in 0..4 {
2258            let b = sb * 4 + sc;
2259            let mut ymv = stored_luma_mv(split_luma_mvs[b]);
2260            if full_pixel {
2261                ymv = apply_full_pixel(ymv);
2262            }
2263            let blk = filter_block_4x4(
2264                reference.y,
2265                reference.y_stride,
2266                lw,
2267                lh,
2268                y_x0 + sc * 4,
2269                y_y0 + sb * 4,
2270                ymv,
2271                filters,
2272            );
2273            for r in 0..4 {
2274                let dst = (sb * 4 + r) * 16 + sc * 4;
2275                out.y[dst..dst + 4].copy_from_slice(&blk[r * 4..r * 4 + 4]);
2276            }
2277        }
2278    }
2279
2280    // Chroma: the four §18.1 averaged vectors, one per chroma sub-block.
2281    let chroma = split_chroma_mvs(split_luma_mvs);
2282    let uv_x0 = mb_col * 8;
2283    let uv_y0 = mb_row * 8;
2284    for sb in 0..2 {
2285        for sc in 0..2 {
2286            let c = sb * 2 + sc;
2287            let mut uvmv = chroma[c];
2288            if full_pixel {
2289                uvmv = apply_full_pixel(uvmv);
2290            }
2291            let ublk = filter_block_4x4(
2292                reference.u,
2293                reference.uv_stride,
2294                cw,
2295                ch,
2296                uv_x0 + sc * 4,
2297                uv_y0 + sb * 4,
2298                uvmv,
2299                filters,
2300            );
2301            let vblk = filter_block_4x4(
2302                reference.v,
2303                reference.uv_stride,
2304                cw,
2305                ch,
2306                uv_x0 + sc * 4,
2307                uv_y0 + sb * 4,
2308                uvmv,
2309                filters,
2310            );
2311            for r in 0..4 {
2312                let dst = (sb * 4 + r) * 8 + sc * 4;
2313                out.u[dst..dst + 4].copy_from_slice(&ublk[r * 4..r * 4 + 4]);
2314                out.v[dst..dst + 4].copy_from_slice(&vblk[r * 4..r * 4 + 4]);
2315            }
2316        }
2317    }
2318
2319    out
2320}
2321
2322/// Reconstruct one SPLITMV macroblock — RFC 6386 §16.4 / §18 prediction +
2323/// §14 residue.
2324///
2325/// SPLITMV macroblocks have no Y2 block (§14.2 "for ... `SPLITMV`, the
2326/// 0th Y coefficients are part of the residue signal"), so each Y
2327/// sub-block's full 16 coefficients go straight through the inverse DCT
2328/// (no WHT seeding).
2329///
2330/// 1. Build the §18.2/§18.3 prediction buffer ([`predict_split_mv`]).
2331/// 2. If `mb_skip_coeff`, the residue is zero and the prediction is the
2332///    reconstruction (§11.1 skip short-circuit).
2333/// 3. Otherwise inverse-DCT each of the 16 Y + 4 U + 4 V sub-blocks and
2334///    add the residue with `clamp255`.
2335///
2336/// `filters` is the §20.14 version-selected tap set. The coefficient
2337/// arrays are pre-dequantized (caller's responsibility, matching
2338/// [`reconstruct_inter_mb`]).
2339#[allow(clippy::too_many_arguments)] // each parameter is a distinct §14.2/§16.4 input.
2340pub fn reconstruct_split_mv_mb(
2341    reference: &ReferencePlanes<'_>,
2342    mb_col: usize,
2343    mb_row: usize,
2344    split_luma_mvs: &[Mv; 16],
2345    full_pixel: bool,
2346    filters: &[[i32; 6]; 8],
2347    mb_skip_coeff: bool,
2348    y_coeffs_dequant: &[[i16; 16]; 16],
2349    u_coeffs_dequant: &[[i16; 16]; 4],
2350    v_coeffs_dequant: &[[i16; 16]; 4],
2351) -> ReconstructedMb {
2352    let mut out = predict_split_mv(
2353        reference,
2354        mb_col,
2355        mb_row,
2356        split_luma_mvs,
2357        full_pixel,
2358        filters,
2359    );
2360
2361    if mb_skip_coeff {
2362        return out;
2363    }
2364
2365    // Luma: §14.4 inverse-DCT fused with the §14.5 add-clamp into the
2366    // stride-16 prediction raster (round 286; no Y2 for SPLITMV).
2367    // Bit-identical to the prior extract/add/insert sequence.
2368    for i in 0..4 {
2369        for j in 0..4 {
2370            let idx = i * 4 + j;
2371            inverse_dct_4x4_add_into(&y_coeffs_dequant[idx], &mut out.y, 16, i, j);
2372        }
2373    }
2374
2375    // Chroma: same fused IDCT + add-clamp, U then V, stride 8.
2376    for i in 0..2 {
2377        for j in 0..2 {
2378            let idx = i * 2 + j;
2379            inverse_dct_4x4_add_into(&u_coeffs_dequant[idx], &mut out.u, 8, i, j);
2380            inverse_dct_4x4_add_into(&v_coeffs_dequant[idx], &mut out.v, 8, i, j);
2381        }
2382    }
2383
2384    out
2385}
2386
2387#[cfg(test)]
2388mod tests {
2389    use super::*;
2390    use crate::inverse_transform::inverse_dct_4x4;
2391
2392    /// Minimal test-side VP8 boolean encoder, mirroring the proven
2393    /// encoder in `motion_vector::tests` / `bool_decoder::tests`. Used to
2394    /// build bitstreams the §16.2 reference selector decodes back.
2395    struct BoolEncoder {
2396        out: Vec<u8>,
2397        range: u32,
2398        bottom: u32,
2399        bit_count: i32,
2400    }
2401
2402    impl BoolEncoder {
2403        fn new() -> Self {
2404            BoolEncoder {
2405                out: Vec::new(),
2406                range: 255,
2407                bottom: 0,
2408                bit_count: 24,
2409            }
2410        }
2411
2412        fn write_bool(&mut self, prob: u8, val: bool) {
2413            let split = 1 + (((self.range - 1) * prob as u32) >> 8);
2414            if val {
2415                self.bottom = self.bottom.wrapping_add(split);
2416                self.range -= split;
2417            } else {
2418                self.range = split;
2419            }
2420            while self.range < 128 {
2421                self.range <<= 1;
2422                if (self.bottom >> 31) & 1 == 1 {
2423                    let mut i = self.out.len();
2424                    while i > 0 {
2425                        i -= 1;
2426                        if self.out[i] == 255 {
2427                            self.out[i] = 0;
2428                        } else {
2429                            self.out[i] = self.out[i].wrapping_add(1);
2430                            break;
2431                        }
2432                    }
2433                }
2434                self.bottom <<= 1;
2435                self.bit_count -= 1;
2436                if self.bit_count == 0 {
2437                    let byte = (self.bottom >> 24) as u8;
2438                    self.out.push(byte);
2439                    self.bottom &= (1 << 24) - 1;
2440                    self.bit_count = 8;
2441                }
2442            }
2443        }
2444
2445        fn finish(mut self) -> Vec<u8> {
2446            let c = self.bit_count;
2447            let v = self.bottom;
2448            if v & (1u32 << (32 - c)) != 0 {
2449                let mut i = self.out.len();
2450                while i > 0 {
2451                    i -= 1;
2452                    if self.out[i] == 255 {
2453                        self.out[i] = 0;
2454                    } else {
2455                        self.out[i] = self.out[i].wrapping_add(1);
2456                        break;
2457                    }
2458                }
2459            }
2460            let mut v = v;
2461            v <<= c & 7;
2462            let mut c_shift = c >> 3;
2463            while c_shift > 0 {
2464                v <<= 8;
2465                c_shift -= 1;
2466            }
2467            for _ in 0..4 {
2468                self.out.push((v >> 24) as u8);
2469                v <<= 8;
2470            }
2471            while self.out.len() < 2 {
2472                self.out.push(0);
2473            }
2474            self.out
2475        }
2476    }
2477
2478    // ----- §16.2 reference frame selection ---------------------------
2479
2480    #[test]
2481    fn ref_frame_last_reads_single_zero() {
2482        // prob_last bit 0 → Last; prob_gf is never read.
2483        let mut enc = BoolEncoder::new();
2484        enc.write_bool(128, false); // prob_last = 0
2485        let bytes = enc.finish();
2486        let mut dec = BoolDecoder::init(&bytes).unwrap();
2487        assert_eq!(
2488            select_ref_frame(&mut dec, 128, 128).unwrap(),
2489            RefFrame::Last
2490        );
2491    }
2492
2493    #[test]
2494    fn ref_frame_golden_reads_one_then_zero() {
2495        let mut enc = BoolEncoder::new();
2496        enc.write_bool(128, true); // prob_last = 1
2497        enc.write_bool(128, false); // prob_gf = 0 → Golden
2498        let bytes = enc.finish();
2499        let mut dec = BoolDecoder::init(&bytes).unwrap();
2500        assert_eq!(
2501            select_ref_frame(&mut dec, 128, 128).unwrap(),
2502            RefFrame::Golden
2503        );
2504    }
2505
2506    #[test]
2507    fn ref_frame_altref_reads_one_then_one() {
2508        let mut enc = BoolEncoder::new();
2509        enc.write_bool(128, true); // prob_last = 1
2510        enc.write_bool(128, true); // prob_gf = 1 → AltRef
2511        let bytes = enc.finish();
2512        let mut dec = BoolDecoder::init(&bytes).unwrap();
2513        assert_eq!(
2514            select_ref_frame(&mut dec, 128, 128).unwrap(),
2515            RefFrame::AltRef
2516        );
2517    }
2518
2519    #[test]
2520    fn ref_frame_uses_distinct_probs() {
2521        // Encode Golden against asymmetric probs; decode with the same
2522        // probs must recover Golden. This proves prob_last and prob_gf
2523        // are wired to the right read order.
2524        let mut enc = BoolEncoder::new();
2525        enc.write_bool(30, true); // prob_last = 30
2526        enc.write_bool(200, false); // prob_gf = 200
2527        let bytes = enc.finish();
2528        let mut dec = BoolDecoder::init(&bytes).unwrap();
2529        assert_eq!(
2530            select_ref_frame(&mut dec, 30, 200).unwrap(),
2531            RefFrame::Golden
2532        );
2533    }
2534
2535    // ----- §18.1 motion-vector adjustments ---------------------------
2536
2537    #[test]
2538    fn stored_luma_doubles_each_component() {
2539        // §18.1: quarter-pixel luma vector doubled to eighth-pixel.
2540        assert_eq!(
2541            stored_luma_mv(Mv { row: 3, col: -5 }),
2542            Mv { row: 6, col: -10 }
2543        );
2544        // Extremes: ±1023 quarter-pel → ±2046 eighth-pel (the §18.1
2545        // stated range).
2546        assert_eq!(
2547            stored_luma_mv(Mv {
2548                row: 1023,
2549                col: -1023
2550            }),
2551            Mv {
2552                row: 2046,
2553                col: -2046
2554            }
2555        );
2556    }
2557
2558    #[test]
2559    fn avg_matches_spec_formula() {
2560        // Positive rounding: (s + 4) >> 3.
2561        assert_eq!(avg(8, 8, 8, 8), (32 + 4) >> 3); // = 4
2562        assert_eq!(avg(1, 1, 1, 1), (4 + 4) >> 3); // = 1
2563        assert_eq!(avg(0, 0, 0, 0), 0);
2564        // Negative rounding: -((-s + 4) >> 3) — symmetric to positive.
2565        assert_eq!(avg(-8, -8, -8, -8), -((32 + 4) >> 3)); // = -4
2566        assert_eq!(avg(-1, -1, -1, -1), -((4 + 4) >> 3)); // = -1
2567        // Mixed sign, sum exactly zero.
2568        assert_eq!(avg(5, -5, 3, -3), 0);
2569    }
2570
2571    #[test]
2572    fn chroma_mv_of_repeated_vector_is_quarter() {
2573        // For a whole-MB vector, chroma_mv = avg(v,v,v,v). With the
2574        // eighth-pixel doubled luma vector v=6, avg(6,6,6,6) = (24+4)>>3
2575        // = 3.
2576        let ymv = stored_luma_mv(Mv { row: 3, col: -5 }); // (6, -10)
2577        let uvmv = chroma_mv(ymv);
2578        assert_eq!(uvmv.row, ((6 * 4 + 4) >> 3) as i16); // 3
2579        assert_eq!(uvmv.col, -(((10 * 4 + 4) >> 3) as i16)); // -5
2580    }
2581
2582    #[test]
2583    fn chroma_mv_matches_reference_closed_form() {
2584        // §20.14 writes the whole-MB chroma vector as
2585        // (c + 1 + (c >> 31) * 2) / 2 per component. Cross-check our
2586        // avg()-based chroma_mv against that closed form across a spread
2587        // of eighth-pixel luma components.
2588        fn ref_form(c: i32) -> i32 {
2589            (c + 1 + (c >> 31) * 2) / 2
2590        }
2591        for &c in &[0i32, 2, 6, 10, 14, 100, -2, -6, -10, -14, -100, 2046, -2046] {
2592            let mv = Mv {
2593                row: c as i16,
2594                col: c as i16,
2595            };
2596            let got = chroma_mv(mv);
2597            assert_eq!(got.row as i32, ref_form(c), "row c={c}");
2598            assert_eq!(got.col as i32, ref_form(c), "col c={c}");
2599        }
2600    }
2601
2602    #[test]
2603    fn full_pixel_truncation_clears_low_three_bits() {
2604        // §18.1 version-3: x &= ~7, y &= ~7.
2605        assert_eq!(
2606            apply_full_pixel(Mv { row: 13, col: 9 }),
2607            Mv { row: 8, col: 8 }
2608        );
2609        assert_eq!(
2610            apply_full_pixel(Mv { row: 16, col: 24 }),
2611            Mv { row: 16, col: 24 }
2612        );
2613        // Negative two's-complement & ~7 rounds toward negative infinity.
2614        assert_eq!(apply_full_pixel(Mv { row: -1, col: -9 }).row, -8);
2615        assert_eq!(apply_full_pixel(Mv { row: -1, col: -9 }).col, -16);
2616    }
2617
2618    #[test]
2619    fn whole_pixel_test_detects_fraction() {
2620        assert!(whole_pixel_fraction_is_zero(Mv { row: 16, col: -8 }));
2621        assert!(whole_pixel_fraction_is_zero(Mv { row: 0, col: 0 }));
2622        assert!(!whole_pixel_fraction_is_zero(Mv { row: 1, col: 0 }));
2623        assert!(!whole_pixel_fraction_is_zero(Mv { row: 0, col: 3 }));
2624        assert!(!whole_pixel_fraction_is_zero(Mv { row: -1, col: 0 }));
2625    }
2626
2627    // ----- §20.14 build_mc_border whole-pixel fetch ------------------
2628
2629    /// A 8×8 single-plane ramp where pixel (r, c) = r * 8 + c.
2630    fn ramp_plane(w: usize, h: usize) -> Vec<u8> {
2631        (0..w * h).map(|i| (i % 256) as u8).collect()
2632    }
2633
2634    #[test]
2635    fn fetch_zero_mv_copies_in_place() {
2636        let w = 8;
2637        let h = 8;
2638        let plane = ramp_plane(w, h);
2639        // Sub-block at (0,0), zero vector → the top-left 4×4.
2640        let blk = fetch_block_whole_pixel(&plane, w, w, h, 0, 0, Mv { row: 0, col: 0 });
2641        let mut expect = [0u8; 16];
2642        for r in 0..4 {
2643            for c in 0..4 {
2644                expect[r * 4 + c] = plane[r * w + c];
2645            }
2646        }
2647        assert_eq!(blk, expect);
2648    }
2649
2650    #[test]
2651    fn fetch_whole_pixel_offset_shifts_origin() {
2652        let w = 8;
2653        let h = 8;
2654        let plane = ramp_plane(w, h);
2655        // Eighth-pixel vector (8, 16) → integer offset (1, 2): origin
2656        // moves down 1 row, right 2 cols.
2657        let blk = fetch_block_whole_pixel(&plane, w, w, h, 0, 0, Mv { row: 8, col: 16 });
2658        let mut expect = [0u8; 16];
2659        for r in 0..4 {
2660            for c in 0..4 {
2661                expect[r * 4 + c] = plane[(1 + r) * w + (2 + c)];
2662            }
2663        }
2664        assert_eq!(blk, expect);
2665    }
2666
2667    #[test]
2668    fn fetch_left_edge_replicates_first_column() {
2669        let w = 8;
2670        let h = 8;
2671        let plane = ramp_plane(w, h);
2672        // Negative col offset large enough to push all 4 columns past
2673        // the left edge: every fetched pixel is column 0 of its row.
2674        // mv.col = -64 → off_x = -8; sub-block at x=0 → src_x0 = -8,
2675        // all columns clamp to 0.
2676        let blk = fetch_block_whole_pixel(&plane, w, w, h, 0, 0, Mv { row: 0, col: -64 });
2677        for r in 0..4 {
2678            for c in 0..4 {
2679                assert_eq!(blk[r * 4 + c], plane[r * w], "row {r} col {c}");
2680            }
2681        }
2682    }
2683
2684    #[test]
2685    fn fetch_top_edge_replicates_first_row() {
2686        let w = 8;
2687        let h = 8;
2688        let plane = ramp_plane(w, h);
2689        // mv.row = -64 → off_y = -8; all rows clamp to row 0.
2690        let blk = fetch_block_whole_pixel(&plane, w, w, h, 0, 0, Mv { row: -64, col: 0 });
2691        for r in 0..4 {
2692            for c in 0..4 {
2693                assert_eq!(blk[r * 4 + c], plane[c], "row {r} col {c}");
2694            }
2695        }
2696    }
2697
2698    #[test]
2699    fn fetch_bottom_right_corner_replicates() {
2700        let w = 8;
2701        let h = 8;
2702        let plane = ramp_plane(w, h);
2703        // Push the fetch fully past the bottom-right corner: every pixel
2704        // becomes the (h-1, w-1) corner pixel.
2705        let blk = fetch_block_whole_pixel(&plane, w, w, h, 4, 4, Mv { row: 64, col: 64 });
2706        let corner = plane[(h - 1) * w + (w - 1)];
2707        for px in blk {
2708            assert_eq!(px, corner);
2709        }
2710    }
2711
2712    // ----- §18.2 whole-MB prediction ---------------------------------
2713
2714    /// Build a reference frame whose planes are filled with a deterministic
2715    /// per-position value, big enough for a 2×2 macroblock grid.
2716    fn build_reference(mb_cols: usize, mb_rows: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2717        let lw = mb_cols * 16;
2718        let lh = mb_rows * 16;
2719        let cw = mb_cols * 8;
2720        let ch = mb_rows * 8;
2721        let y = (0..lw * lh).map(|i| (i % 251) as u8).collect();
2722        let u = (0..cw * ch).map(|i| ((i * 3 + 1) % 251) as u8).collect();
2723        let v = (0..cw * ch).map(|i| ((i * 7 + 2) % 251) as u8).collect();
2724        (y, u, v)
2725    }
2726
2727    #[test]
2728    fn predict_zero_mv_copies_corresponding_mb() {
2729        // A zero motion vector predicts the current MB from the matching
2730        // MB in the reference frame (mv_zero, §16.3).
2731        let (y, u, v) = build_reference(2, 2);
2732        let reference = ReferencePlanes {
2733            y: &y,
2734            u: &u,
2735            v: &v,
2736            y_stride: 32,
2737            uv_stride: 16,
2738            mb_cols: 2,
2739            mb_rows: 2,
2740        };
2741        // Predict MB (1, 1) with a zero vector.
2742        let pred =
2743            predict_inter_mb_whole_pixel(&reference, 1, 1, Mv { row: 0, col: 0 }, false).unwrap();
2744
2745        // The luma block must equal reference MB (1,1) verbatim.
2746        for r in 0..16 {
2747            for c in 0..16 {
2748                let ref_px = y[(16 + r) * 32 + (16 + c)];
2749                assert_eq!(pred.y[r * 16 + c], ref_px, "luma ({r},{c})");
2750            }
2751        }
2752        for r in 0..8 {
2753            for c in 0..8 {
2754                let ru = u[(8 + r) * 16 + (8 + c)];
2755                let rv = v[(8 + r) * 16 + (8 + c)];
2756                assert_eq!(pred.u[r * 8 + c], ru, "u ({r},{c})");
2757                assert_eq!(pred.v[r * 8 + c], rv, "v ({r},{c})");
2758            }
2759        }
2760    }
2761
2762    #[test]
2763    fn predict_whole_pixel_offset_shifts_source() {
2764        // Pick a luma vector whose §18.1-doubled value AND its chroma
2765        // average are both whole-pixel, so the prediction is a pure copy
2766        // with a non-trivial integer offset (no §18.3 interpolation).
2767        //
2768        // luma quarter-pel (8, 16) → doubled (16, 32): both eighth-pel
2769        // fractions zero → luma integer offset (16>>3, 32>>3) = (2, 4).
2770        // chroma row avg(16,16,16,16) = (64+4)>>3 = 8 → fraction zero →
2771        // chroma row offset 8>>3 = 1; chroma col avg(32..) = (128+4)>>3 =
2772        // 16 → fraction zero → chroma col offset 16>>3 = 2. So both
2773        // planes copy in place at shifted origins. Use a 3×3 grid so the
2774        // shifted reads stay in-bounds and predict the centre MB (1,1).
2775        let (y, u, v) = build_reference(3, 3);
2776        let reference = ReferencePlanes {
2777            y: &y,
2778            u: &u,
2779            v: &v,
2780            y_stride: 48,
2781            uv_stride: 24,
2782            mb_cols: 3,
2783            mb_rows: 3,
2784        };
2785        let mv = Mv { row: 8, col: 16 };
2786        let pred = predict_inter_mb_whole_pixel(&reference, 1, 1, mv, false).unwrap();
2787
2788        // Luma: MB (1,1) origin (16, 16) + offset (2, 4).
2789        for r in 0..16 {
2790            for c in 0..16 {
2791                let ref_px = y[(16 + 2 + r) * 48 + (16 + 4 + c)];
2792                assert_eq!(pred.y[r * 16 + c], ref_px, "luma ({r},{c})");
2793            }
2794        }
2795        // Chroma: MB (1,1) origin (8, 8) + offset (1, 2).
2796        for r in 0..8 {
2797            for c in 0..8 {
2798                let ru = u[(8 + 1 + r) * 24 + (8 + 2 + c)];
2799                let rv = v[(8 + 1 + r) * 24 + (8 + 2 + c)];
2800                assert_eq!(pred.u[r * 8 + c], ru, "u ({r},{c})");
2801                assert_eq!(pred.v[r * 8 + c], rv, "v ({r},{c})");
2802            }
2803        }
2804    }
2805
2806    #[test]
2807    fn predict_sub_pixel_vector_rejected() {
2808        // A vector whose doubled luma fraction is non-zero must be
2809        // refused (sub-pel interpolation is a future round). row=1
2810        // quarter-pel → 2 eighth-pel → fraction 2, non-zero.
2811        let (y, u, v) = build_reference(1, 1);
2812        let reference = ReferencePlanes {
2813            y: &y,
2814            u: &u,
2815            v: &v,
2816            y_stride: 16,
2817            uv_stride: 8,
2818            mb_cols: 1,
2819            mb_rows: 1,
2820        };
2821        assert_eq!(
2822            predict_inter_mb_whole_pixel(&reference, 0, 0, Mv { row: 1, col: 0 }, false),
2823            Err(MotionCompError::SubPixelNotSupported)
2824        );
2825    }
2826
2827    #[test]
2828    fn predict_chroma_sub_pixel_vector_rejected() {
2829        // A luma vector that is whole-pixel but whose chroma average is
2830        // sub-pixel must also be refused. luma quarter-pel (2, 0) →
2831        // doubled (4, 0): luma fraction 4 — non-zero, so it's already
2832        // refused at luma. Use (4, 0) quarter → doubled (8, 0): luma
2833        // whole-pixel; chroma avg(8..)=4 → fraction 4, sub-pixel.
2834        let (y, u, v) = build_reference(1, 1);
2835        let reference = ReferencePlanes {
2836            y: &y,
2837            u: &u,
2838            v: &v,
2839            y_stride: 16,
2840            uv_stride: 8,
2841            mb_cols: 1,
2842            mb_rows: 1,
2843        };
2844        assert_eq!(
2845            predict_inter_mb_whole_pixel(&reference, 0, 0, Mv { row: 4, col: 0 }, false),
2846            Err(MotionCompError::SubPixelNotSupported)
2847        );
2848    }
2849
2850    #[test]
2851    fn predict_full_pixel_version_truncates_to_whole() {
2852        // With full_pixel set, a vector that would be chroma-sub-pixel is
2853        // truncated to whole-pixel and accepted. luma quarter (4, 0) →
2854        // doubled (8, 0); chroma avg(8..) = 4 (sub-pixel); full_pixel
2855        // truncates both to whole-pixel → (8&~7, 0) = (8, 0) luma,
2856        // (4&~7, 0) = (0, 0) chroma. Accepted.
2857        //
2858        // Use a 2×2 grid and predict MB (0,0) so the luma row-1 offset
2859        // stays in-bounds; cross-check luma against the same
2860        // edge-clamped fetch the implementation uses, so the test is
2861        // robust to any boundary behaviour.
2862        let (y, u, v) = build_reference(2, 2);
2863        let reference = ReferencePlanes {
2864            y: &y,
2865            u: &u,
2866            v: &v,
2867            y_stride: 32,
2868            uv_stride: 16,
2869            mb_cols: 2,
2870            mb_rows: 2,
2871        };
2872        let pred =
2873            predict_inter_mb_whole_pixel(&reference, 0, 0, Mv { row: 4, col: 0 }, true).unwrap();
2874        // Luma offset (8>>3, 0) = (1, 0): row shifted down by 1. Compare
2875        // against fetch_block_whole_pixel for each 4×4 sub-block.
2876        for sb in 0..4 {
2877            for sc in 0..4 {
2878                let blk =
2879                    fetch_block_whole_pixel(&y, 32, 32, 32, sc * 4, sb * 4, Mv { row: 8, col: 0 });
2880                for r in 0..4 {
2881                    for c in 0..4 {
2882                        let pr = sb * 4 + r;
2883                        let pc = sc * 4 + c;
2884                        assert_eq!(pred.y[pr * 16 + pc], blk[r * 4 + c], "luma ({pr},{pc})");
2885                    }
2886                }
2887            }
2888        }
2889        // Chroma offset (0, 0): copied in place from MB (0,0).
2890        for r in 0..8 {
2891            for c in 0..8 {
2892                assert_eq!(pred.u[r * 8 + c], u[r * 16 + c], "u ({r},{c})");
2893            }
2894        }
2895    }
2896
2897    // ----- §16.2 / §18 / §14 inter reconstruction --------------------
2898
2899    #[test]
2900    fn reconstruct_skip_equals_prediction() {
2901        // mb_skip_coeff → zero residue → reconstruction == prediction.
2902        let (y, u, v) = build_reference(2, 2);
2903        let reference = ReferencePlanes {
2904            y: &y,
2905            u: &u,
2906            v: &v,
2907            y_stride: 32,
2908            uv_stride: 16,
2909            mb_cols: 2,
2910            mb_rows: 2,
2911        };
2912        let mv = Mv { row: 0, col: 0 };
2913        let pred = predict_inter_mb_whole_pixel(&reference, 1, 0, mv, false).unwrap();
2914        let recon = reconstruct_inter_mb_whole_pixel(
2915            &reference,
2916            1,
2917            0,
2918            mv,
2919            false,
2920            true, // skip
2921            &[0i16; 16],
2922            &[[0i16; 16]; 16],
2923            &[[0i16; 16]; 4],
2924            &[[0i16; 16]; 4],
2925        )
2926        .unwrap();
2927        assert_eq!(recon, pred);
2928    }
2929
2930    #[test]
2931    fn reconstruct_adds_dc_residue() {
2932        // A pure Y2 DC term lifts every Y sub-block's DC uniformly; the
2933        // reconstruction must equal prediction + a constant on luma.
2934        let (y, u, v) = build_reference(1, 1);
2935        let reference = ReferencePlanes {
2936            y: &y,
2937            u: &u,
2938            v: &v,
2939            y_stride: 16,
2940            uv_stride: 8,
2941            mb_cols: 1,
2942            mb_rows: 1,
2943        };
2944        let mv = Mv { row: 0, col: 0 };
2945        let pred = predict_inter_mb_whole_pixel(&reference, 0, 0, mv, false).unwrap();
2946
2947        // A Y2 block with a single DC term. The inverse WHT of a
2948        // DC-only block distributes (dc + 3) >> 3 to every output; that
2949        // becomes each Y sub-block's DC, and the inverse DCT of a
2950        // DC-only block distributes (dc + 4) >> 3 to every pixel.
2951        let mut y2 = [0i16; 16];
2952        y2[0] = 64; // WHT: each sub-block DC = (64 + 3) >> 3 ... see below
2953        let recon = reconstruct_inter_mb_whole_pixel(
2954            &reference,
2955            0,
2956            0,
2957            mv,
2958            false,
2959            false,
2960            &y2,
2961            &[[0i16; 16]; 16],
2962            &[[0i16; 16]; 4],
2963            &[[0i16; 16]; 4],
2964        )
2965        .unwrap();
2966
2967        // Compute the expected luma delta independently via the same
2968        // public transform primitives.
2969        let mut y2_residue = [0i16; 16];
2970        inverse_wht_4x4(&y2, &mut y2_residue);
2971        // Every Y sub-block gets DC = y2_residue[idx]; with a single DC
2972        // input the WHT spreads it evenly, so all sixteen are equal.
2973        let sub_dc = y2_residue[0];
2974        let mut residue = [0i16; 16];
2975        let mut coeffs = [0i16; 16];
2976        coeffs[0] = sub_dc;
2977        inverse_dct_4x4(&coeffs, &mut residue);
2978        let delta = residue[0];
2979
2980        // Chroma has no residue → equals prediction.
2981        assert_eq!(recon.u, pred.u);
2982        assert_eq!(recon.v, pred.v);
2983        // Luma: each pixel is clamp255(pred + delta).
2984        for i in 0..256 {
2985            let expect = (pred.y[i] as i32 + delta as i32).clamp(0, 255) as u8;
2986            assert_eq!(recon.y[i], expect, "luma px {i}");
2987        }
2988        // Sanity: the residue is genuinely non-zero so this isn't a
2989        // trivial pass.
2990        assert_ne!(delta, 0);
2991    }
2992
2993    #[test]
2994    fn reconstruct_sub_pixel_vector_rejected() {
2995        let (y, u, v) = build_reference(1, 1);
2996        let reference = ReferencePlanes {
2997            y: &y,
2998            u: &u,
2999            v: &v,
3000            y_stride: 16,
3001            uv_stride: 8,
3002            mb_cols: 1,
3003            mb_rows: 1,
3004        };
3005        assert_eq!(
3006            reconstruct_inter_mb_whole_pixel(
3007                &reference,
3008                0,
3009                0,
3010                Mv { row: 1, col: 0 },
3011                false,
3012                true,
3013                &[0i16; 16],
3014                &[[0i16; 16]; 16],
3015                &[[0i16; 16]; 4],
3016                &[[0i16; 16]; 4],
3017            ),
3018            Err(MotionCompError::SubPixelNotSupported)
3019        );
3020    }
3021
3022    // ----- §18.3 sub-pixel interpolation -----------------------------
3023
3024    #[test]
3025    fn filter_tables_match_spec_values() {
3026        // §18.3 / §20.14: spot-check the documented rows.
3027        assert_eq!(SIXTAP_FILTERS[0], [0, 0, 128, 0, 0, 0]);
3028        assert_eq!(SIXTAP_FILTERS[1], [0, -6, 123, 12, -1, 0]);
3029        assert_eq!(SIXTAP_FILTERS[2], [2, -11, 108, 36, -8, 1]);
3030        assert_eq!(SIXTAP_FILTERS[4], [3, -16, 77, 77, -16, 3]);
3031        assert_eq!(SIXTAP_FILTERS[7], [0, -1, 12, 123, -6, 0]);
3032        assert_eq!(BILINEAR_FILTERS[0], [0, 0, 128, 0, 0, 0]);
3033        assert_eq!(BILINEAR_FILTERS[4], [0, 0, 64, 64, 0, 0]);
3034        assert_eq!(BILINEAR_FILTERS[7], [0, 0, 16, 112, 0, 0]);
3035    }
3036
3037    #[test]
3038    fn filter_taps_always_sum_to_128() {
3039        // §18.3: "Because DC is always passed, taps always sum to 128."
3040        for f in SIXTAP_FILTERS.iter() {
3041            assert_eq!(f.iter().sum::<i32>(), 128);
3042        }
3043        for f in BILINEAR_FILTERS.iter() {
3044            assert_eq!(f.iter().sum::<i32>(), 128);
3045        }
3046    }
3047
3048    #[test]
3049    fn bilinear_uses_only_centre_two_taps() {
3050        // The bilinear filter never reaches the outer support pixels.
3051        for f in BILINEAR_FILTERS.iter() {
3052            assert_eq!(f[0], 0);
3053            assert_eq!(f[1], 0);
3054            assert_eq!(f[4], 0);
3055            assert_eq!(f[5], 0);
3056        }
3057    }
3058
3059    #[test]
3060    fn filter_set_selected_by_version() {
3061        // §20.14: version 0 → six-tap; non-zero → bilinear.
3062        assert_eq!(filter_set_for_version(0), FilterSet::Sixtap);
3063        assert_eq!(filter_set_for_version(1), FilterSet::Bilinear);
3064        assert_eq!(filter_set_for_version(2), FilterSet::Bilinear);
3065        assert_eq!(filter_set_for_version(3), FilterSet::Bilinear);
3066        assert!(core::ptr::eq(
3067            FilterSet::Sixtap.taps(),
3068            &SIXTAP_FILTERS as &[[i32; 6]; 8]
3069        ));
3070        assert!(core::ptr::eq(
3071            FilterSet::Bilinear.taps(),
3072            &BILINEAR_FILTERS as &[[i32; 6]; 8]
3073        ));
3074    }
3075
3076    #[test]
3077    fn interp_matches_spec_formula() {
3078        // §18.3 interp: clamp255((sum_i support[i]*fil[i] + 64) >> 7).
3079        // Whole-pixel filter (index 0) passes the centre tap unchanged.
3080        let support = [10u8, 20, 30, 40, 50, 60];
3081        assert_eq!(interp(&SIXTAP_FILTERS[0], &support), 30);
3082        // 1/2 symmetric filter, computed by hand:
3083        // 3*10 -16*20 +77*30 +77*40 -16*50 +3*60
3084        // = 30 -320 +2310 +3080 -800 +180 = 4480; (4480+64)>>7 = 35.
3085        assert_eq!(interp(&SIXTAP_FILTERS[4], &support), 35);
3086        // Constant support → DC passes (taps sum 128): (128*K+64)>>7 = K.
3087        let flat = [200u8; 6];
3088        for f in SIXTAP_FILTERS.iter() {
3089            assert_eq!(interp(f, &flat), 200);
3090        }
3091        // clamp255 floor: a strongly negative partial sum clamps to 0.
3092        // filter index 2 has negative taps -11 and -8; drive the negative
3093        // taps high and the positive taps to 0.
3094        let neg = [0u8, 255, 0, 0, 255, 0];
3095        // 2*0 -11*255 +108*0 +36*0 -8*255 +1*0 = -4845; +64 = -4781;
3096        // >>7 (arithmetic) = -38 → clamp255 → 0.
3097        assert_eq!(interp(&SIXTAP_FILTERS[2], &neg), 0);
3098    }
3099
3100    /// Independent §18.3 `interp` over a slice with explicit stride —
3101    /// a literal transcription of the spec-prose code block, used to
3102    /// cross-check [`sixtap_2d`].
3103    fn ref_interp(fil: &[i32; 6], p: &[u8], origin: isize, s: isize) -> u8 {
3104        let mut a = 0i32;
3105        let mut idx = origin - s - s; // "move back two positions"
3106        for &tap in fil.iter() {
3107            a += p[idx as usize] as i32 * tap;
3108            idx += s;
3109        }
3110        ((a + 64) >> 7).clamp(0, 255) as u8
3111    }
3112
3113    /// Independent §18.3 Hinterp + Vinterp over the same 9×9 halo
3114    /// [`sixtap_2d`] consumes, reproducing the spec prose verbatim:
3115    /// horizontal pass producing 9 rows of 4, vertical pass producing
3116    /// the final 4×4. The halo block origin is at (2, 2), stride 9.
3117    fn ref_sixtap_2d(halo: &[u8; 81], mx: usize, my: usize, filters: &[[i32; 6]; 8]) -> [u8; 16] {
3118        let hfil = &filters[mx];
3119        let vfil = &filters[my];
3120        // Hinterp: temp[9][4]. Spec advances p by the vertical stride per
3121        // row, starting at the subblock origin. interp moves back two
3122        // positions, so the support spans rows [origin-? n/a here] — for
3123        // the horizontal pass the step is 1 (within a row) and we read
3124        // rows [block_origin_row .. +8]. The halo's row 2 is the block
3125        // origin row; Hinterp's row r corresponds to halo row r (the
3126        // §20.14 sixtap_horiz starts at reference - 2*stride = halo row
3127        // 0, producing 9 rows). To match that, iterate halo rows 0..9.
3128        let mut temp = [[0u8; 4]; 9];
3129        for (r, trow) in temp.iter_mut().enumerate() {
3130            for (c, t) in trow.iter_mut().enumerate() {
3131                // Row base in the halo: block-origin column is 2.
3132                let base = r * 9 + 2;
3133                *t = ref_interp(hfil, halo, (base + c) as isize, 1);
3134            }
3135        }
3136        // Vinterp: read temp at block-origin row (halo row 2 → temp row
3137        // 2) with vertical step = 4 (row width). Flatten temp to a
3138        // 9*4 row-major buffer.
3139        let mut flat = [0u8; 36];
3140        for r in 0..9 {
3141            for c in 0..4 {
3142                flat[r * 4 + c] = temp[r][c];
3143            }
3144        }
3145        let mut out = [0u8; 16];
3146        for r in 0..4 {
3147            for c in 0..4 {
3148                // Block-origin row within the 9-row intermediate is row 2.
3149                let base = (2 + r) * 4 + c;
3150                out[r * 4 + c] = ref_interp(vfil, &flat, base as isize, 4);
3151            }
3152        }
3153        out
3154    }
3155
3156    /// Pseudo-random 9×9 halo for cross-checking the convolution.
3157    fn rand_halo(seed: u64) -> [u8; 81] {
3158        let mut s = seed;
3159        let mut h = [0u8; 81];
3160        for px in h.iter_mut() {
3161            s = s
3162                .wrapping_mul(6364136223846793005)
3163                .wrapping_add(1442695040888963407);
3164            *px = (s >> 33) as u8;
3165        }
3166        h
3167    }
3168
3169    #[test]
3170    fn sixtap_2d_matches_independent_spec_reference() {
3171        // Cross-check the production sixtap_2d against a literal
3172        // transcription of §18.3 Hinterp/Vinterp over the same halo, for
3173        // every (mx, my) sub-pixel pair and both filter sets.
3174        for set in [&SIXTAP_FILTERS, &BILINEAR_FILTERS] {
3175            for seed in 0..3u64 {
3176                let halo = rand_halo(seed * 977 + 13);
3177                for mx in 0..8 {
3178                    for my in 0..8 {
3179                        let got = sixtap_2d(&halo, mx, my, set);
3180                        let want = ref_sixtap_2d(&halo, mx, my, set);
3181                        assert_eq!(got, want, "mx={mx} my={my} seed={seed}");
3182                    }
3183                }
3184            }
3185        }
3186    }
3187
3188    #[test]
3189    fn sixtap_2d_flat_halo_passes_dc() {
3190        // A constant source must interpolate to the same constant for any
3191        // fraction (taps sum to 128, DC preserved, no clamp).
3192        let halo = [137u8; 81];
3193        for mx in 0..8 {
3194            for my in 0..8 {
3195                let out = sixtap_2d(&halo, mx, my, &SIXTAP_FILTERS);
3196                assert!(out.iter().all(|&p| p == 137), "mx={mx} my={my}");
3197                let outb = sixtap_2d(&halo, mx, my, &BILINEAR_FILTERS);
3198                assert!(outb.iter().all(|&p| p == 137), "bilinear mx={mx} my={my}");
3199            }
3200        }
3201    }
3202
3203    #[test]
3204    fn sixtap_2d_whole_fraction_copies_block() {
3205        // (mx,my)=(0,0) is the degenerate whole-pixel filter: the centre
3206        // tap is 128 in both dimensions, so sixtap_2d copies the 4×4
3207        // block at the halo origin (rows/cols 2..6).
3208        let halo = rand_halo(42);
3209        let out = sixtap_2d(&halo, 0, 0, &SIXTAP_FILTERS);
3210        for r in 0..4 {
3211            for c in 0..4 {
3212                assert_eq!(out[r * 4 + c], halo[(2 + r) * 9 + (2 + c)], "({r},{c})");
3213            }
3214        }
3215    }
3216
3217    #[test]
3218    fn sixtap_2d_horizontal_only_known_values() {
3219        // my=0 (vertical filter is the centre-tap copy), so the result is
3220        // a pure horizontal convolution of the block-origin rows. Build a
3221        // horizontal ramp halo so the answer is easy to verify against
3222        // ref_interp directly.
3223        let mut halo = [0u8; 81];
3224        for r in 0..9 {
3225            for c in 0..9 {
3226                halo[r * 9 + c] = (c * 20) as u8; // 0,20,40,...,160
3227            }
3228        }
3229        let out = sixtap_2d(&halo, 2, 0, &SIXTAP_FILTERS); // mx=1/4
3230        for r in 0..4 {
3231            for c in 0..4 {
3232                let want = ref_interp(&SIXTAP_FILTERS[2], &halo, (r * 9 + 2 + c) as isize, 1);
3233                assert_eq!(out[r * 4 + c], want, "({r},{c})");
3234            }
3235        }
3236    }
3237
3238    // Round-269 dispatcher equivalence (scalar vs the public entry,
3239    // which is SIMD under nightly + `simd`). Mirrors the §14
3240    // `*_simd_matches_scalar_on_stress_inputs` pairs. On stable / no
3241    // `simd` feature this exercises the scalar-vs-scalar identity
3242    // (harmless); on nightly + `simd` it's the primary safety net:
3243    // `sixtap_2d` dispatches to `sixtap_2d_simd` and must be byte-exact
3244    // against `sixtap_2d_scalar` on every fixture.
3245
3246    #[test]
3247    fn sixtap_2d_simd_matches_scalar_on_stress_inputs() {
3248        // Structured halos: flat extremes, opposing ramps, alternating
3249        // extremes (the worst case for the clamp endpoints), plus
3250        // deterministic LCG halos — for every (mx, my) eighth-pixel
3251        // fraction pair and both §18.3 filter sets.
3252        let mut hramp = [0u8; 81];
3253        let mut vramp = [0u8; 81];
3254        let mut checker = [0u8; 81];
3255        for r in 0..9 {
3256            for c in 0..9 {
3257                hramp[r * 9 + c] = (c * 31) as u8;
3258                vramp[r * 9 + c] = (r * 31) as u8;
3259                checker[r * 9 + c] = if (r + c) % 2 == 0 { 255 } else { 0 };
3260            }
3261        }
3262        // All-floor, all-ceiling, the structured halos, then the LCG set.
3263        let mut halos: Vec<[u8; 81]> = vec![[0u8; 81], [255u8; 81], hramp, vramp, checker];
3264        for seed in 0..8u64 {
3265            halos.push(rand_halo(seed * 6661 + 7));
3266        }
3267
3268        for set in [&SIXTAP_FILTERS, &BILINEAR_FILTERS] {
3269            for (h, halo) in halos.iter().enumerate() {
3270                for mx in 0..8 {
3271                    for my in 0..8 {
3272                        let got = sixtap_2d(halo, mx, my, set);
3273                        let want = sixtap_2d_scalar(halo, mx, my, set);
3274                        assert_eq!(got, want, "halo={h} mx={mx} my={my}");
3275                    }
3276                }
3277            }
3278        }
3279    }
3280
3281    #[test]
3282    fn sixtap_2d_accumulator_extremes_match_scalar() {
3283        // The §18.3 dot product over the half-pel taps {3, -16, 77, 77,
3284        // -16, 3} spans [-32·255, 160·255] = [-8160, 40800] — past
3285        // i16::MAX, the reason the SIMD lanes are i32. Drive both
3286        // extremes through output column 0 (support columns c + k for
3287        // c = 0 are exactly k = 0..6): 255 on the positive-tap columns
3288        // {0, 2, 3, 5} maxes the sum (→ clamp ceiling), 255 on the
3289        // negative-tap columns {1, 4} alone mins it (→ clamp floor).
3290        let mut max_halo = [0u8; 81];
3291        let mut min_halo = [0u8; 81];
3292        for r in 0..9 {
3293            for c in 0..9 {
3294                let pos_tap = matches!(c % 6, 0 | 2 | 3 | 5);
3295                max_halo[r * 9 + c] = if pos_tap { 255 } else { 0 };
3296                min_halo[r * 9 + c] = if pos_tap { 0 } else { 255 };
3297            }
3298        }
3299        let got_max = sixtap_2d(&max_halo, 4, 4, &SIXTAP_FILTERS);
3300        assert_eq!(got_max, sixtap_2d_scalar(&max_halo, 4, 4, &SIXTAP_FILTERS));
3301        // Column 0 hits the positive overflow region: clamp255((40800 +
3302        // 64) >> 7) = 255 in the horizontal pass, then the constant-255
3303        // column interpolates to 255 (taps sum to 128).
3304        assert_eq!(got_max[0], 255);
3305
3306        let got_min = sixtap_2d(&min_halo, 4, 4, &SIXTAP_FILTERS);
3307        assert_eq!(got_min, sixtap_2d_scalar(&min_halo, 4, 4, &SIXTAP_FILTERS));
3308        // Column 0 hits the negative extreme: clamp255((-8160 + 64) >>
3309        // 7) = 0, then the constant-0 column stays 0.
3310        assert_eq!(got_min[0], 0);
3311    }
3312
3313    // ----- MB-scale §18.3 luma batching ------------------------------
3314
3315    /// Pseudo-random 21×21 halo for cross-checking the MB-scale
3316    /// convolution.
3317    fn rand_mb_halo(seed: u64) -> [u8; 21 * 21] {
3318        let mut s = seed;
3319        let mut h = [0u8; 21 * 21];
3320        for px in h.iter_mut() {
3321            s = s
3322                .wrapping_mul(6364136223846793005)
3323                .wrapping_add(1442695040888963407);
3324            *px = (s >> 33) as u8;
3325        }
3326        h
3327    }
3328
3329    #[test]
3330    fn sixtap_mb_luma_matches_per_subblock_path() {
3331        // The whole-MB §18.3 luma synthesis must be byte-identical to
3332        // running the per-sub-block sixtap_2d on each of the sixteen 4×4
3333        // sub-blocks of the same 16×16 block. Both consume the same
3334        // source samples and the same §18.3 interp dot product per output
3335        // pixel; only the tiling differs. Sweep every (mx, my) sub-pixel
3336        // fraction pair and both filter sets over deterministic halos.
3337        for set in [&SIXTAP_FILTERS, &BILINEAR_FILTERS] {
3338            for seed in 0..4u64 {
3339                let mb_halo = rand_mb_halo(seed * 4099 + 17);
3340                for mx in 0..8 {
3341                    for my in 0..8 {
3342                        let got = sixtap_mb_luma(&mb_halo, mx, my, set);
3343                        // Build the per-sub-block reference: each 4×4
3344                        // sub-block (sb, sc) extracts its own 9×9 halo
3345                        // from the 21×21 MB halo (the sub-block origin is
3346                        // at MB-halo position (2 + sb*4, 2 + sc*4); the
3347                        // 9×9 sub-halo starts two pixels up/left of that).
3348                        for sb in 0..4 {
3349                            for sc in 0..4 {
3350                                let mut sub = [0u8; 81];
3351                                for r in 0..9 {
3352                                    for c in 0..9 {
3353                                        // MB-halo position of this sub-halo
3354                                        // pixel: the sub-block origin in
3355                                        // the MB halo is (2 + sb*4, 2 +
3356                                        // sc*4); the sub-halo origin is two
3357                                        // up/left of that.
3358                                        let mr = sb * 4 + r;
3359                                        let mc = sc * 4 + c;
3360                                        sub[r * 9 + c] = mb_halo[mr * 21 + mc];
3361                                    }
3362                                }
3363                                let sub_out = sixtap_2d(&sub, mx, my, set);
3364                                for r in 0..4 {
3365                                    for c in 0..4 {
3366                                        let mr = sb * 4 + r;
3367                                        let mc = sc * 4 + c;
3368                                        assert_eq!(
3369                                            got[mr * 16 + mc],
3370                                            sub_out[r * 4 + c],
3371                                            "mx={mx} my={my} sb={sb} sc={sc} ({r},{c})"
3372                                        );
3373                                    }
3374                                }
3375                            }
3376                        }
3377                    }
3378                }
3379            }
3380        }
3381    }
3382
3383    #[test]
3384    fn sixtap_mb_luma_simd_matches_scalar_on_stress_inputs() {
3385        // Dispatcher (SIMD under nightly + `simd`) vs the scalar listing
3386        // on the MB-scale path — the §14 `*_simd_matches_scalar` shape,
3387        // MB-scale. Flat extremes, opposing ramps, alternating-extreme
3388        // checker (the worst case for the clamp endpoints) and a
3389        // deterministic LCG set, for every (mx, my) and both filter sets.
3390        let mut hramp = [0u8; 21 * 21];
3391        let mut vramp = [0u8; 21 * 21];
3392        let mut checker = [0u8; 21 * 21];
3393        for r in 0..21 {
3394            for c in 0..21 {
3395                hramp[r * 21 + c] = (c * 12) as u8;
3396                vramp[r * 21 + c] = (r * 12) as u8;
3397                checker[r * 21 + c] = if (r + c) % 2 == 0 { 255 } else { 0 };
3398            }
3399        }
3400        let mut halos: Vec<[u8; 21 * 21]> =
3401            vec![[0u8; 21 * 21], [255u8; 21 * 21], hramp, vramp, checker];
3402        for seed in 0..6u64 {
3403            halos.push(rand_mb_halo(seed * 7919 + 3));
3404        }
3405
3406        for set in [&SIXTAP_FILTERS, &BILINEAR_FILTERS] {
3407            for (h, halo) in halos.iter().enumerate() {
3408                for mx in 0..8 {
3409                    for my in 0..8 {
3410                        let got = sixtap_mb_luma(halo, mx, my, set);
3411                        let want = sixtap_mb_luma_scalar(halo, mx, my, set);
3412                        assert_eq!(got, want, "halo={h} mx={mx} my={my}");
3413                    }
3414                }
3415            }
3416        }
3417    }
3418
3419    #[test]
3420    fn fetch_luma_mb_halo_matches_subblock_halos_in_bounds() {
3421        // The 21×21 MB halo must contain every per-sub-block 9×9 halo as a
3422        // window: sub-block (sb, sc) at plane position (mb_x + sc*4,
3423        // mb_y + sb*4) under the same vector reads a 9×9 region whose
3424        // top-left is two pixels up/left of the sub-block origin, which in
3425        // the MB halo is position (sb*4, sc*4) (the MB halo origin is two
3426        // up/left of the MB origin).
3427        let w = 48;
3428        let h = 48;
3429        let plane = ramp_plane(w, h);
3430        let mv = Mv { row: 11, col: 19 }; // sub-pixel, integer offset (1, 2)
3431        let mb_x = 16;
3432        let mb_y = 16;
3433        let mb_halo = fetch_luma_mb_halo(&plane, w, w, h, mb_x, mb_y, mv);
3434        for sb in 0..4 {
3435            for sc in 0..4 {
3436                let sub = fetch_block_halo(&plane, w, w, h, mb_x + sc * 4, mb_y + sb * 4, mv);
3437                for r in 0..9 {
3438                    for c in 0..9 {
3439                        let mr = sb * 4 + r;
3440                        let mc = sc * 4 + c;
3441                        assert_eq!(
3442                            mb_halo[mr * 21 + mc],
3443                            sub[r * 9 + c],
3444                            "sb={sb} sc={sc} ({r},{c})"
3445                        );
3446                    }
3447                }
3448            }
3449        }
3450    }
3451
3452    #[test]
3453    fn fetch_luma_mb_halo_clamps_at_top_left_corner() {
3454        // MB at (0,0), zero mv: halo origin (-2,-2). Out-of-plane
3455        // rows/cols replicate the nearest edge (build_mc_border), and the
3456        // result must equal the per-pixel clamp formula.
3457        let w = 24;
3458        let h = 24;
3459        let plane = ramp_plane(w, h);
3460        let mb_halo = fetch_luma_mb_halo(&plane, w, w, h, 0, 0, Mv { row: 0, col: 0 });
3461        for r in 0..21 {
3462            for c in 0..21 {
3463                let sy = (r as isize - 2).clamp(0, h as isize - 1) as usize;
3464                let sx = (c as isize - 2).clamp(0, w as isize - 1) as usize;
3465                assert_eq!(mb_halo[r * 21 + c], plane[sy * w + sx], "({r},{c})");
3466            }
3467        }
3468    }
3469
3470    /// [`sixtap_run`] equals the §18.3 `interp` listing for every tap
3471    /// row of both shipped sets and for rows that take the plain-`i32`
3472    /// form (other sign patterns, sums past 16 bits), horizontally and
3473    /// vertically, on extreme and pseudo-random samples.
3474    #[test]
3475    fn sixtap_run_matches_interp() {
3476        let mut tap_rows: Vec<[i32; 6]> = Vec::new();
3477        tap_rows.extend_from_slice(&SIXTAP_FILTERS);
3478        tap_rows.extend_from_slice(&BILINEAR_FILTERS);
3479        tap_rows.extend_from_slice(&[
3480            [-3, 16, 77, 77, 16, -3],
3481            [0, -128, 255, 255, -128, 0],
3482            [5, -40, 200, 200, -40, 5],
3483            [1, 2, 3, 4, 5, 6],
3484            [0, 0, 0, 0, 0, 0],
3485        ]);
3486        const W: usize = 24;
3487        let mut lcg = 0x1234_5678u32;
3488        for case in 0..6 {
3489            let mut samples = [0u8; W * 6];
3490            for (n, s) in samples.iter_mut().enumerate() {
3491                lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
3492                *s = match case {
3493                    0 => 0,
3494                    1 => 255,
3495                    2 => [0, 255][n & 1],
3496                    3 => [255, 0][(n / W) & 1],
3497                    _ => (lcg >> 16) as u8,
3498                };
3499            }
3500            for taps in &tap_rows {
3501                // Horizontal: 16 outputs from one row.
3502                let got: [u8; 16] = sixtap_run(&samples, 1, taps);
3503                for (i, &g) in got.iter().enumerate() {
3504                    let support: [u8; 6] = core::array::from_fn(|k| samples[i + k]);
3505                    assert_eq!(g, interp(taps, &support), "horizontal {taps:?} case {case}");
3506                }
3507                // Vertical: 16 outputs from six rows.
3508                let got: [u8; 16] = sixtap_run(&samples, W, taps);
3509                for (i, &g) in got.iter().enumerate() {
3510                    let support: [u8; 6] = core::array::from_fn(|k| samples[i + k * W]);
3511                    assert_eq!(g, interp(taps, &support), "vertical {taps:?} case {case}");
3512                }
3513            }
3514        }
3515    }
3516
3517    #[test]
3518    fn sixtap_identity_elide_gates_on_tap_values() {
3519        // The identity-pass elision gates on the resolved tap VALUES,
3520        // not on the fraction index: a synthetic table whose index-0 row
3521        // is not `{0,0,128,0,0,0}` must never elide (every fraction pair
3522        // runs the unmodified two-pass listing), while the shipped
3523        // tables elide exactly the fraction pairs with a zero component
3524        // — and the elided result is sample-for-sample the two-pass
3525        // listing's output.
3526        let mut table = SIXTAP_FILTERS;
3527        table[0] = [1, 0, 127, 0, 0, 0]; // taps still sum to 128, not identity
3528        let halos: Vec<[u8; 21 * 21]> = (0..4).map(|s| rand_mb_halo(s * 131 + 17)).collect();
3529        for halo in &halos {
3530            for mx in 0..8 {
3531                for my in 0..8 {
3532                    assert!(
3533                        sixtap_identity_elide::<21, 16, { 21 * 21 }, 256>(halo, mx, my, &table)
3534                            .is_none(),
3535                        "non-identity table must never elide (mx={mx} my={my})"
3536                    );
3537                    for set in [&SIXTAP_FILTERS, &BILINEAR_FILTERS] {
3538                        let got =
3539                            sixtap_identity_elide::<21, 16, { 21 * 21 }, 256>(halo, mx, my, set);
3540                        assert_eq!(
3541                            got.is_some(),
3542                            mx == 0 || my == 0,
3543                            "shipped tables elide exactly the zero-fraction pairs"
3544                        );
3545                        if let Some(fast) = got {
3546                            let want = sixtap_mb_luma_scalar(halo, mx, my, set);
3547                            assert_eq!(fast, want, "mx={mx} my={my}");
3548                        }
3549                    }
3550                }
3551            }
3552        }
3553        // And the 4×4 / 8×8 geometries against their scalar listings.
3554        let halo4 = rand_halo(99);
3555        let mut halo8 = [0u8; 13 * 13];
3556        for (i, px) in halo8.iter_mut().enumerate() {
3557            let v = (i as u64).wrapping_mul(2654435761).wrapping_add(97);
3558            *px = (v >> 7) as u8;
3559        }
3560        for mx in 0..8 {
3561            for my in 0..8 {
3562                if let Some(fast) =
3563                    sixtap_identity_elide::<9, 4, 81, 16>(&halo4, mx, my, &SIXTAP_FILTERS)
3564                {
3565                    assert_eq!(
3566                        fast,
3567                        sixtap_2d_scalar(&halo4, mx, my, &SIXTAP_FILTERS),
3568                        "2d mx={mx} my={my}"
3569                    );
3570                }
3571                if let Some(fast) =
3572                    sixtap_identity_elide::<13, 8, { 13 * 13 }, 64>(&halo8, mx, my, &SIXTAP_FILTERS)
3573                {
3574                    assert_eq!(
3575                        fast,
3576                        sixtap_mb_chroma_scalar(&halo8, mx, my, &SIXTAP_FILTERS),
3577                        "chroma mx={mx} my={my}"
3578                    );
3579                }
3580            }
3581        }
3582    }
3583
3584    #[test]
3585    fn predict_inter_mb_sub_pixel_at_border_uses_mb_halo_clamp() {
3586        // Exercise the MB-scale path through the border-clamp fallback:
3587        // predict the corner MB (0,0) with a sub-pixel vector so the
3588        // 21×21 halo straddles the top-left edge. The whole-MB result
3589        // must still equal the per-sub-block filter_block_4x4 path (each
3590        // sub-block fetches its own clamped 9×9 halo), proving the MB-halo
3591        // clamp agrees with build_mc_border on a real prediction.
3592        let (y, u, v) = build_reference(2, 2);
3593        let reference = ReferencePlanes {
3594            y: &y,
3595            u: &u,
3596            v: &v,
3597            y_stride: 32,
3598            uv_stride: 16,
3599            mb_cols: 2,
3600            mb_rows: 2,
3601        };
3602        let luma_mv = Mv { row: 3, col: 5 }; // sub-pixel after §18.1
3603        let pred = predict_inter_mb(&reference, 0, 0, luma_mv, false, &SIXTAP_FILTERS);
3604
3605        let ymv = stored_luma_mv(luma_mv);
3606        for sb in 0..4 {
3607            for sc in 0..4 {
3608                let blk = filter_block_4x4(&y, 32, 32, 32, sc * 4, sb * 4, ymv, &SIXTAP_FILTERS);
3609                for r in 0..4 {
3610                    for c in 0..4 {
3611                        let pr = sb * 4 + r;
3612                        let pc = sc * 4 + c;
3613                        assert_eq!(pred.y[pr * 16 + pc], blk[r * 4 + c], "luma ({pr},{pc})");
3614                    }
3615                }
3616            }
3617        }
3618    }
3619
3620    // ----- MB-scale §18.3 chroma batching ----------------------------
3621
3622    /// Pseudo-random 13×13 halo for cross-checking the MB-scale chroma
3623    /// convolution.
3624    fn rand_chroma_mb_halo(seed: u64) -> [u8; 13 * 13] {
3625        let mut s = seed;
3626        let mut h = [0u8; 13 * 13];
3627        for px in h.iter_mut() {
3628            s = s
3629                .wrapping_mul(6364136223846793005)
3630                .wrapping_add(1442695040888963407);
3631            *px = (s >> 33) as u8;
3632        }
3633        h
3634    }
3635
3636    #[test]
3637    fn sixtap_mb_chroma_matches_per_subblock_path() {
3638        // The whole-MB §18.3 chroma synthesis must be byte-identical to
3639        // running the per-sub-block sixtap_2d on each of the four 4×4
3640        // sub-blocks of the same 8×8 block. Both consume the same source
3641        // samples and the same §18.3 interp dot product per output pixel;
3642        // only the tiling differs. Sweep every (mx, my) and both filter
3643        // sets over deterministic halos.
3644        for set in [&SIXTAP_FILTERS, &BILINEAR_FILTERS] {
3645            for seed in 0..4u64 {
3646                let mb_halo = rand_chroma_mb_halo(seed * 4099 + 17);
3647                for mx in 0..8 {
3648                    for my in 0..8 {
3649                        let got = sixtap_mb_chroma(&mb_halo, mx, my, set);
3650                        // Build the per-sub-block reference: each 4×4
3651                        // sub-block (sb, sc) extracts its own 9×9 halo from
3652                        // the 13×13 MB halo (the sub-block origin is at
3653                        // MB-halo position (2 + sb*4, 2 + sc*4); the 9×9
3654                        // sub-halo starts two pixels up/left of that, which
3655                        // is MB-halo position (sb*4, sc*4)).
3656                        for sb in 0..2 {
3657                            for sc in 0..2 {
3658                                let mut sub = [0u8; 81];
3659                                for r in 0..9 {
3660                                    for c in 0..9 {
3661                                        let mr = sb * 4 + r;
3662                                        let mc = sc * 4 + c;
3663                                        sub[r * 9 + c] = mb_halo[mr * 13 + mc];
3664                                    }
3665                                }
3666                                let sub_out = sixtap_2d(&sub, mx, my, set);
3667                                for r in 0..4 {
3668                                    for c in 0..4 {
3669                                        let mr = sb * 4 + r;
3670                                        let mc = sc * 4 + c;
3671                                        assert_eq!(
3672                                            got[mr * 8 + mc],
3673                                            sub_out[r * 4 + c],
3674                                            "mx={mx} my={my} sb={sb} sc={sc} ({r},{c})"
3675                                        );
3676                                    }
3677                                }
3678                            }
3679                        }
3680                    }
3681                }
3682            }
3683        }
3684    }
3685
3686    #[test]
3687    fn sixtap_mb_chroma_simd_matches_scalar_on_stress_inputs() {
3688        // Dispatcher (SIMD under nightly + `simd`) vs the scalar listing on
3689        // the MB-scale chroma path — the §14 `*_simd_matches_scalar` shape.
3690        // Flat extremes, opposing ramps, alternating-extreme checker (the
3691        // worst case for the clamp endpoints) and a deterministic LCG set,
3692        // for every (mx, my) and both filter sets.
3693        let mut hramp = [0u8; 13 * 13];
3694        let mut vramp = [0u8; 13 * 13];
3695        let mut checker = [0u8; 13 * 13];
3696        for r in 0..13 {
3697            for c in 0..13 {
3698                hramp[r * 13 + c] = (c * 20) as u8;
3699                vramp[r * 13 + c] = (r * 20) as u8;
3700                checker[r * 13 + c] = if (r + c) % 2 == 0 { 255 } else { 0 };
3701            }
3702        }
3703        let mut halos: Vec<[u8; 13 * 13]> =
3704            vec![[0u8; 13 * 13], [255u8; 13 * 13], hramp, vramp, checker];
3705        for seed in 0..6u64 {
3706            halos.push(rand_chroma_mb_halo(seed * 7919 + 3));
3707        }
3708
3709        for set in [&SIXTAP_FILTERS, &BILINEAR_FILTERS] {
3710            for (h, halo) in halos.iter().enumerate() {
3711                for mx in 0..8 {
3712                    for my in 0..8 {
3713                        let got = sixtap_mb_chroma(halo, mx, my, set);
3714                        let want = sixtap_mb_chroma_scalar(halo, mx, my, set);
3715                        assert_eq!(got, want, "halo={h} mx={mx} my={my}");
3716                    }
3717                }
3718            }
3719        }
3720    }
3721
3722    #[test]
3723    fn fetch_chroma_mb_halo_matches_subblock_halos_in_bounds() {
3724        // The 13×13 MB halo must contain every per-sub-block 9×9 chroma
3725        // halo as a window: sub-block (sb, sc) at plane position (mb_x +
3726        // sc*4, mb_y + sb*4) under the same vector reads a 9×9 region whose
3727        // top-left is two pixels up/left of the sub-block origin, which in
3728        // the MB halo is position (sb*4, sc*4).
3729        let w = 32;
3730        let h = 32;
3731        let plane = ramp_plane(w, h);
3732        let mv = Mv { row: 11, col: 19 }; // sub-pixel, integer offset (1, 2)
3733        let mb_x = 8;
3734        let mb_y = 8;
3735        let mb_halo = fetch_chroma_mb_halo(&plane, w, w, h, mb_x, mb_y, mv);
3736        for sb in 0..2 {
3737            for sc in 0..2 {
3738                let sub = fetch_block_halo(&plane, w, w, h, mb_x + sc * 4, mb_y + sb * 4, mv);
3739                for r in 0..9 {
3740                    for c in 0..9 {
3741                        let mr = sb * 4 + r;
3742                        let mc = sc * 4 + c;
3743                        assert_eq!(
3744                            mb_halo[mr * 13 + mc],
3745                            sub[r * 9 + c],
3746                            "sb={sb} sc={sc} ({r},{c})"
3747                        );
3748                    }
3749                }
3750            }
3751        }
3752    }
3753
3754    #[test]
3755    fn fetch_chroma_mb_halo_clamps_at_top_left_corner() {
3756        // Chroma MB at (0,0), zero mv: halo origin (-2,-2). Out-of-plane
3757        // rows/cols replicate the nearest edge (build_mc_border), and the
3758        // result must equal the per-pixel clamp formula.
3759        let w = 16;
3760        let h = 16;
3761        let plane = ramp_plane(w, h);
3762        let mb_halo = fetch_chroma_mb_halo(&plane, w, w, h, 0, 0, Mv { row: 0, col: 0 });
3763        for r in 0..13 {
3764            for c in 0..13 {
3765                let sy = (r as isize - 2).clamp(0, h as isize - 1) as usize;
3766                let sx = (c as isize - 2).clamp(0, w as isize - 1) as usize;
3767                assert_eq!(mb_halo[r * 13 + c], plane[sy * w + sx], "({r},{c})");
3768            }
3769        }
3770    }
3771
3772    #[test]
3773    fn predict_inter_mb_chroma_sub_pixel_matches_per_subblock_path() {
3774        // Exercise the MB-scale chroma path on a mid-plane MB with a
3775        // sub-pixel chroma vector: the whole-MB chroma result must equal the
3776        // per-sub-block filter_block_4x4 path (each chroma sub-block fetches
3777        // its own 9×9 halo). Pick a luma vector whose §18.1 chroma average
3778        // is sub-pixel.
3779        let (y, u, v) = build_reference(3, 3);
3780        let reference = ReferencePlanes {
3781            y: &y,
3782            u: &u,
3783            v: &v,
3784            y_stride: 48,
3785            uv_stride: 24,
3786            mb_cols: 3,
3787            mb_rows: 3,
3788        };
3789        let luma_mv = Mv { row: 5, col: 3 }; // sub-pixel chroma after §18.1
3790        let pred = predict_inter_mb(&reference, 1, 1, luma_mv, false, &SIXTAP_FILTERS);
3791
3792        let uvmv = chroma_mv(stored_luma_mv(luma_mv));
3793        assert!(
3794            !whole_pixel_fraction_is_zero(uvmv),
3795            "test wants sub-pixel chroma"
3796        );
3797        let uv_x0 = 8;
3798        let uv_y0 = 8;
3799        for sb in 0..2 {
3800            for sc in 0..2 {
3801                let ublk = filter_block_4x4(
3802                    &u,
3803                    24,
3804                    24,
3805                    24,
3806                    uv_x0 + sc * 4,
3807                    uv_y0 + sb * 4,
3808                    uvmv,
3809                    &SIXTAP_FILTERS,
3810                );
3811                let vblk = filter_block_4x4(
3812                    &v,
3813                    24,
3814                    24,
3815                    24,
3816                    uv_x0 + sc * 4,
3817                    uv_y0 + sb * 4,
3818                    uvmv,
3819                    &SIXTAP_FILTERS,
3820                );
3821                for r in 0..4 {
3822                    for c in 0..4 {
3823                        let pr = sb * 4 + r;
3824                        let pc = sc * 4 + c;
3825                        assert_eq!(pred.u[pr * 8 + pc], ublk[r * 4 + c], "u ({pr},{pc})");
3826                        assert_eq!(pred.v[pr * 8 + pc], vblk[r * 4 + c], "v ({pr},{pc})");
3827                    }
3828                }
3829            }
3830        }
3831    }
3832
3833    #[test]
3834    fn predict_inter_mb_chroma_sub_pixel_at_border_uses_mb_halo_clamp() {
3835        // The MB-scale chroma path through the border-clamp fallback:
3836        // predict the corner MB (0,0) with a sub-pixel chroma vector so the
3837        // 13×13 halo straddles the top-left edge. The whole-MB chroma result
3838        // must still equal the per-sub-block filter_block_4x4 path.
3839        let (y, u, v) = build_reference(2, 2);
3840        let reference = ReferencePlanes {
3841            y: &y,
3842            u: &u,
3843            v: &v,
3844            y_stride: 32,
3845            uv_stride: 16,
3846            mb_cols: 2,
3847            mb_rows: 2,
3848        };
3849        let luma_mv = Mv { row: 3, col: 5 }; // sub-pixel chroma after §18.1
3850        let pred = predict_inter_mb(&reference, 0, 0, luma_mv, false, &SIXTAP_FILTERS);
3851
3852        let uvmv = chroma_mv(stored_luma_mv(luma_mv));
3853        assert!(
3854            !whole_pixel_fraction_is_zero(uvmv),
3855            "test wants sub-pixel chroma"
3856        );
3857        for sb in 0..2 {
3858            for sc in 0..2 {
3859                let ublk = filter_block_4x4(&u, 16, 16, 16, sc * 4, sb * 4, uvmv, &SIXTAP_FILTERS);
3860                let vblk = filter_block_4x4(&v, 16, 16, 16, sc * 4, sb * 4, uvmv, &SIXTAP_FILTERS);
3861                for r in 0..4 {
3862                    for c in 0..4 {
3863                        let pr = sb * 4 + r;
3864                        let pc = sc * 4 + c;
3865                        assert_eq!(pred.u[pr * 8 + pc], ublk[r * 4 + c], "u ({pr},{pc})");
3866                        assert_eq!(pred.v[pr * 8 + pc], vblk[r * 4 + c], "v ({pr},{pc})");
3867                    }
3868                }
3869            }
3870        }
3871    }
3872
3873    // ----- §20.14 build_mc_border halo fetch -------------------------
3874
3875    #[test]
3876    fn halo_in_bounds_is_plain_window() {
3877        // A fetch well inside the plane is a 9×9 window starting two
3878        // pixels up/left of the integer block origin.
3879        let w = 16;
3880        let h = 16;
3881        let plane = ramp_plane(w, h);
3882        // mv (16, 8) → integer offset (16>>3, 8>>3) = (2, 1). Block at
3883        // (4, 4) → src origin (6, 5); halo origin (6-2, 5-2) = (4, 3).
3884        let halo = fetch_block_halo(&plane, w, w, h, 4, 4, Mv { row: 16, col: 8 });
3885        for r in 0..9 {
3886            for c in 0..9 {
3887                assert_eq!(halo[r * 9 + c], plane[(4 + r) * w + (3 + c)], "({r},{c})");
3888            }
3889        }
3890    }
3891
3892    #[test]
3893    fn halo_block_origin_at_2_2() {
3894        // The integer block origin must sit at halo[(2,2)].
3895        let w = 16;
3896        let h = 16;
3897        let plane = ramp_plane(w, h);
3898        // Zero mv, block at (4, 4): src origin (4, 4) → halo[(2,2)].
3899        let halo = fetch_block_halo(&plane, w, w, h, 4, 4, Mv { row: 0, col: 0 });
3900        assert_eq!(halo[2 * 9 + 2], plane[4 * w + 4]);
3901    }
3902
3903    #[test]
3904    fn halo_clamps_at_top_left_corner() {
3905        // Block at (0,0), zero mv: halo origin (-2,-2). All out-of-plane
3906        // rows/cols replicate the nearest edge — matching build_mc_border.
3907        let w = 8;
3908        let h = 8;
3909        let plane = ramp_plane(w, h);
3910        let halo = fetch_block_halo(&plane, w, w, h, 0, 0, Mv { row: 0, col: 0 });
3911        for r in 0..9 {
3912            for c in 0..9 {
3913                let sy = (r as isize - 2).clamp(0, h as isize - 1) as usize;
3914                let sx = (c as isize - 2).clamp(0, w as isize - 1) as usize;
3915                assert_eq!(halo[r * 9 + c], plane[sy * w + sx], "({r},{c})");
3916            }
3917        }
3918    }
3919
3920    // ----- §20.14 filter_block dispatch ------------------------------
3921
3922    #[test]
3923    fn filter_block_whole_pixel_copies() {
3924        // mx|my == 0 → filter_block_4x4 == fetch_block_whole_pixel.
3925        let w = 16;
3926        let h = 16;
3927        let plane = ramp_plane(w, h);
3928        let mv = Mv { row: 16, col: 8 }; // integer offset, no fraction
3929        let filt = filter_block_4x4(&plane, w, w, h, 4, 4, mv, &SIXTAP_FILTERS);
3930        let copy = fetch_block_whole_pixel(&plane, w, w, h, 4, 4, mv);
3931        assert_eq!(filt, copy);
3932    }
3933
3934    #[test]
3935    fn filter_block_sub_pixel_interpolates() {
3936        // A fractional mv routes through sixtap_2d on the fetched halo.
3937        let w = 16;
3938        let h = 16;
3939        let plane = ramp_plane(w, h);
3940        let mv = Mv { row: 10, col: 19 }; // my = 10&7 = 2, mx = 19&7 = 3
3941        let halo = fetch_block_halo(&plane, w, w, h, 4, 4, mv);
3942        let want = sixtap_2d(&halo, 3, 2, &SIXTAP_FILTERS);
3943        let got = filter_block_4x4(&plane, w, w, h, 4, 4, mv, &SIXTAP_FILTERS);
3944        assert_eq!(got, want);
3945    }
3946
3947    // ----- §18.2/§18.3 sub-pixel whole-MB prediction -----------------
3948
3949    #[test]
3950    fn predict_inter_mb_sub_pixel_matches_per_block() {
3951        // The whole-MB prediction must equal the per-sub-block
3952        // filter_block_4x4 applied with the §18.1-adjusted vectors.
3953        let (y, u, v) = build_reference(3, 3);
3954        let reference = ReferencePlanes {
3955            y: &y,
3956            u: &u,
3957            v: &v,
3958            y_stride: 48,
3959            uv_stride: 24,
3960            mb_cols: 3,
3961            mb_rows: 3,
3962        };
3963        // luma quarter-pel (3, 5) → doubled (6, 10): luma fractions
3964        // (6&7, 10&7) = (6, 2), sub-pixel. chroma avg(6..)=3, avg(10..)=5
3965        // → fractions (3, 5), also sub-pixel.
3966        let luma_mv = Mv { row: 3, col: 5 };
3967        let pred = predict_inter_mb(&reference, 1, 1, luma_mv, false, &SIXTAP_FILTERS);
3968
3969        let ymv = stored_luma_mv(luma_mv);
3970        let uvmv = chroma_mv(ymv);
3971        let lw = 48;
3972        let lh = 48;
3973        let cw = 24;
3974        let ch = 24;
3975        // Luma.
3976        for sb in 0..4 {
3977            for sc in 0..4 {
3978                let blk = filter_block_4x4(
3979                    &y,
3980                    48,
3981                    lw,
3982                    lh,
3983                    16 + sc * 4,
3984                    16 + sb * 4,
3985                    ymv,
3986                    &SIXTAP_FILTERS,
3987                );
3988                for r in 0..4 {
3989                    for c in 0..4 {
3990                        let pr = sb * 4 + r;
3991                        let pc = sc * 4 + c;
3992                        assert_eq!(pred.y[pr * 16 + pc], blk[r * 4 + c], "luma ({pr},{pc})");
3993                    }
3994                }
3995            }
3996        }
3997        // Chroma U.
3998        for sb in 0..2 {
3999            for sc in 0..2 {
4000                let blk = filter_block_4x4(
4001                    &u,
4002                    24,
4003                    cw,
4004                    ch,
4005                    8 + sc * 4,
4006                    8 + sb * 4,
4007                    uvmv,
4008                    &SIXTAP_FILTERS,
4009                );
4010                for r in 0..4 {
4011                    for c in 0..4 {
4012                        let pr = sb * 4 + r;
4013                        let pc = sc * 4 + c;
4014                        assert_eq!(pred.u[pr * 8 + pc], blk[r * 4 + c], "u ({pr},{pc})");
4015                    }
4016                }
4017            }
4018        }
4019    }
4020
4021    #[test]
4022    fn predict_inter_mb_whole_pixel_agrees_with_legacy() {
4023        // For a whole-pixel vector, predict_inter_mb must produce the
4024        // same buffer as the legacy whole-pixel-only entry point.
4025        let (y, u, v) = build_reference(3, 3);
4026        let reference = ReferencePlanes {
4027            y: &y,
4028            u: &u,
4029            v: &v,
4030            y_stride: 48,
4031            uv_stride: 24,
4032            mb_cols: 3,
4033            mb_rows: 3,
4034        };
4035        let mv = Mv { row: 8, col: 16 }; // whole-pixel after §18.1
4036        let full = predict_inter_mb(&reference, 1, 1, mv, false, &SIXTAP_FILTERS);
4037        let legacy = predict_inter_mb_whole_pixel(&reference, 1, 1, mv, false).unwrap();
4038        assert_eq!(full, legacy);
4039    }
4040
4041    #[test]
4042    fn predict_inter_mb_uses_selected_filter_set() {
4043        // Bilinear and six-tap give different results for the same
4044        // sub-pixel vector (the outer taps differ), so the prediction
4045        // must depend on the chosen set.
4046        let (y, u, v) = build_reference(3, 3);
4047        let reference = ReferencePlanes {
4048            y: &y,
4049            u: &u,
4050            v: &v,
4051            y_stride: 48,
4052            uv_stride: 24,
4053            mb_cols: 3,
4054            mb_rows: 3,
4055        };
4056        let luma_mv = Mv { row: 3, col: 5 };
4057        let six = predict_inter_mb(&reference, 1, 1, luma_mv, false, &SIXTAP_FILTERS);
4058        let bil = predict_inter_mb(&reference, 1, 1, luma_mv, false, &BILINEAR_FILTERS);
4059        assert_ne!(six.y, bil.y);
4060    }
4061
4062    #[test]
4063    fn reconstruct_inter_mb_skip_equals_prediction() {
4064        let (y, u, v) = build_reference(3, 3);
4065        let reference = ReferencePlanes {
4066            y: &y,
4067            u: &u,
4068            v: &v,
4069            y_stride: 48,
4070            uv_stride: 24,
4071            mb_cols: 3,
4072            mb_rows: 3,
4073        };
4074        let mv = Mv { row: 3, col: 5 }; // sub-pixel
4075        let pred = predict_inter_mb(&reference, 1, 1, mv, false, &SIXTAP_FILTERS);
4076        let recon = reconstruct_inter_mb(
4077            &reference,
4078            1,
4079            1,
4080            mv,
4081            false,
4082            &SIXTAP_FILTERS,
4083            true, // skip
4084            &[0i16; 16],
4085            &[[0i16; 16]; 16],
4086            &[[0i16; 16]; 4],
4087            &[[0i16; 16]; 4],
4088        );
4089        assert_eq!(recon, pred);
4090    }
4091
4092    #[test]
4093    fn reconstruct_inter_mb_sub_pixel_adds_dc_residue() {
4094        // Sub-pixel prediction + a pure Y2 DC term: luma lifts uniformly,
4095        // chroma equals prediction.
4096        let (y, u, v) = build_reference(3, 3);
4097        let reference = ReferencePlanes {
4098            y: &y,
4099            u: &u,
4100            v: &v,
4101            y_stride: 48,
4102            uv_stride: 24,
4103            mb_cols: 3,
4104            mb_rows: 3,
4105        };
4106        let mv = Mv { row: 3, col: 5 }; // sub-pixel
4107        let pred = predict_inter_mb(&reference, 1, 1, mv, false, &SIXTAP_FILTERS);
4108
4109        let mut y2 = [0i16; 16];
4110        y2[0] = 64;
4111        let recon = reconstruct_inter_mb(
4112            &reference,
4113            1,
4114            1,
4115            mv,
4116            false,
4117            &SIXTAP_FILTERS,
4118            false,
4119            &y2,
4120            &[[0i16; 16]; 16],
4121            &[[0i16; 16]; 4],
4122            &[[0i16; 16]; 4],
4123        );
4124
4125        // Independent luma delta via the public transforms.
4126        let mut y2_residue = [0i16; 16];
4127        inverse_wht_4x4(&y2, &mut y2_residue);
4128        let mut coeffs = [0i16; 16];
4129        coeffs[0] = y2_residue[0];
4130        let mut residue = [0i16; 16];
4131        inverse_dct_4x4(&coeffs, &mut residue);
4132        let delta = residue[0];
4133        assert_ne!(delta, 0);
4134
4135        assert_eq!(recon.u, pred.u);
4136        assert_eq!(recon.v, pred.v);
4137        for i in 0..256 {
4138            let expect = (pred.y[i] as i32 + delta as i32).clamp(0, 255) as u8;
4139            assert_eq!(recon.y[i], expect, "luma px {i}");
4140        }
4141    }
4142
4143    #[test]
4144    fn reconstruct_inter_mb_matches_legacy_for_whole_pixel() {
4145        // A whole-pixel vector through the full path must equal the
4146        // legacy whole-pixel reconstruction (filters are unused there).
4147        let (y, u, v) = build_reference(3, 3);
4148        let reference = ReferencePlanes {
4149            y: &y,
4150            u: &u,
4151            v: &v,
4152            y_stride: 48,
4153            uv_stride: 24,
4154            mb_cols: 3,
4155            mb_rows: 3,
4156        };
4157        let mv = Mv { row: 8, col: 16 };
4158        let mut y2 = [0i16; 16];
4159        y2[0] = 48;
4160        let mut ycoeffs = [[0i16; 16]; 16];
4161        ycoeffs[5][3] = 12;
4162        let ucoeffs = [[0i16; 16]; 4];
4163        let vcoeffs = [[0i16; 16]; 4];
4164        let full = reconstruct_inter_mb(
4165            &reference,
4166            1,
4167            1,
4168            mv,
4169            false,
4170            &SIXTAP_FILTERS,
4171            false,
4172            &y2,
4173            &ycoeffs,
4174            &ucoeffs,
4175            &vcoeffs,
4176        );
4177        let legacy = reconstruct_inter_mb_whole_pixel(
4178            &reference, 1, 1, mv, false, false, &y2, &ycoeffs, &ucoeffs, &vcoeffs,
4179        )
4180        .unwrap();
4181        assert_eq!(full, legacy);
4182    }
4183
4184    // ----- whole-pixel MB batching -----------------------------------
4185
4186    #[test]
4187    fn fetch_luma_mb_whole_pixel_matches_per_subblock_in_bounds() {
4188        // The whole 16×16 luma fetch must be byte-identical to assembling
4189        // it from sixteen 4×4 `fetch_block_whole_pixel` copies — both read
4190        // the same contiguous source region under the shared §18.1 vector.
4191        let w = 48;
4192        let h = 48;
4193        let plane = ramp_plane(w, h);
4194        let mb_x = 16;
4195        let mb_y = 16;
4196        // Whole-pixel vector: integer offset (1, 2), no fractional bits.
4197        let mv = Mv { row: 8, col: 16 };
4198        let mb = fetch_luma_mb_whole_pixel(&plane, w, w, h, mb_x, mb_y, mv);
4199        for sb in 0..4 {
4200            for sc in 0..4 {
4201                let blk =
4202                    fetch_block_whole_pixel(&plane, w, w, h, mb_x + sc * 4, mb_y + sb * 4, mv);
4203                for r in 0..4 {
4204                    for c in 0..4 {
4205                        let mr = sb * 4 + r;
4206                        let mc = sc * 4 + c;
4207                        assert_eq!(
4208                            mb[mr * 16 + mc],
4209                            blk[r * 4 + c],
4210                            "sb={sb} sc={sc} ({r},{c})"
4211                        );
4212                    }
4213                }
4214            }
4215        }
4216    }
4217
4218    #[test]
4219    fn fetch_chroma_mb_whole_pixel_matches_per_subblock_in_bounds() {
4220        // Chroma analogue: the whole 8×8 fetch == four 4×4
4221        // `fetch_block_whole_pixel` copies.
4222        let w = 32;
4223        let h = 32;
4224        let plane = ramp_plane(w, h);
4225        let mb_x = 8;
4226        let mb_y = 8;
4227        let mv = Mv { row: 16, col: 8 }; // whole-pixel, integer offset (2, 1)
4228        let mb = fetch_chroma_mb_whole_pixel(&plane, w, w, h, mb_x, mb_y, mv);
4229        for sb in 0..2 {
4230            for sc in 0..2 {
4231                let blk =
4232                    fetch_block_whole_pixel(&plane, w, w, h, mb_x + sc * 4, mb_y + sb * 4, mv);
4233                for r in 0..4 {
4234                    for c in 0..4 {
4235                        let mr = sb * 4 + r;
4236                        let mc = sc * 4 + c;
4237                        assert_eq!(mb[mr * 8 + mc], blk[r * 4 + c], "sb={sb} sc={sc} ({r},{c})");
4238                    }
4239                }
4240            }
4241        }
4242    }
4243
4244    #[test]
4245    fn fetch_luma_mb_whole_pixel_clamps_at_top_left_corner() {
4246        // MB at (0,0) with a vector that pushes the integer origin off the
4247        // top-left edge: every out-of-plane read must replicate the nearest
4248        // edge pixel (build_mc_border), matching the per-pixel clamp
4249        // formula and the per-sub-block `fetch_block_whole_pixel` fallback.
4250        let w = 24;
4251        let h = 24;
4252        let plane = ramp_plane(w, h);
4253        let mv = Mv { row: -32, col: -32 }; // integer offset (-4, -4)
4254        let mb = fetch_luma_mb_whole_pixel(&plane, w, w, h, 0, 0, mv);
4255        for r in 0..16 {
4256            for c in 0..16 {
4257                let sy = (r as isize - 4).clamp(0, h as isize - 1) as usize;
4258                let sx = (c as isize - 4).clamp(0, w as isize - 1) as usize;
4259                assert_eq!(mb[r * 16 + c], plane[sy * w + sx], "({r},{c})");
4260            }
4261        }
4262    }
4263
4264    #[test]
4265    fn fetch_chroma_mb_whole_pixel_clamps_at_bottom_right_corner() {
4266        // Chroma block whose integer origin pushes past the bottom-right
4267        // edge: out-of-plane rows / cols replicate the last in-bounds
4268        // row / col.
4269        let w = 16;
4270        let h = 16;
4271        let plane = ramp_plane(w, h);
4272        let mb_x = 8;
4273        let mb_y = 8;
4274        let mv = Mv { row: 32, col: 32 }; // integer offset (4, 4) → origin (12,12)
4275        let mb = fetch_chroma_mb_whole_pixel(&plane, w, w, h, mb_x, mb_y, mv);
4276        for r in 0..8 {
4277            for c in 0..8 {
4278                let sy = (mb_y as isize + 4 + r as isize).clamp(0, h as isize - 1) as usize;
4279                let sx = (mb_x as isize + 4 + c as isize).clamp(0, w as isize - 1) as usize;
4280                assert_eq!(mb[r * 8 + c], plane[sy * w + sx], "({r},{c})");
4281            }
4282        }
4283    }
4284
4285    #[test]
4286    fn predict_inter_mb_whole_pixel_at_border_uses_mb_batch_clamp() {
4287        // Exercise the batched whole-pixel path through the border-clamp
4288        // fallback: predict the corner MB (0,0) with a whole-pixel vector
4289        // that straddles the top-left edge. The whole-MB result must still
4290        // equal the per-sub-block `fetch_block_whole_pixel` assembly,
4291        // proving the batched fetch's clamp agrees with build_mc_border on
4292        // a real prediction.
4293        let (y, u, v) = build_reference(2, 2);
4294        let reference = ReferencePlanes {
4295            y: &y,
4296            u: &u,
4297            v: &v,
4298            y_stride: 32,
4299            uv_stride: 16,
4300            mb_cols: 2,
4301            mb_rows: 2,
4302        };
4303        // Whole-pixel vector pushing the integer origin off the top-left.
4304        let luma_mv = Mv { row: -16, col: -16 };
4305        let pred = predict_inter_mb(&reference, 0, 0, luma_mv, false, &SIXTAP_FILTERS);
4306
4307        let ymv = stored_luma_mv(luma_mv);
4308        for sb in 0..4 {
4309            for sc in 0..4 {
4310                let blk = fetch_block_whole_pixel(&y, 32, 32, 32, sc * 4, sb * 4, ymv);
4311                for r in 0..4 {
4312                    for c in 0..4 {
4313                        let pr = sb * 4 + r;
4314                        let pc = sc * 4 + c;
4315                        assert_eq!(pred.y[pr * 16 + pc], blk[r * 4 + c], "luma ({pr},{pc})");
4316                    }
4317                }
4318            }
4319        }
4320
4321        let uvmv = chroma_mv(ymv);
4322        for sb in 0..2 {
4323            for sc in 0..2 {
4324                let ublk = fetch_block_whole_pixel(&u, 16, 16, 16, sc * 4, sb * 4, uvmv);
4325                let vblk = fetch_block_whole_pixel(&v, 16, 16, 16, sc * 4, sb * 4, uvmv);
4326                for r in 0..4 {
4327                    for c in 0..4 {
4328                        let pr = sb * 4 + r;
4329                        let pc = sc * 4 + c;
4330                        assert_eq!(pred.u[pr * 8 + pc], ublk[r * 4 + c], "u ({pr},{pc})");
4331                        assert_eq!(pred.v[pr * 8 + pc], vblk[r * 4 + c], "v ({pr},{pc})");
4332                    }
4333                }
4334            }
4335        }
4336    }
4337
4338    // ----- §16.4 SPLITMV strided-write equivalence -------------------
4339
4340    #[test]
4341    fn filter_block_4x4_into_matches_filter_block_4x4() {
4342        // The strided-write entry point must produce, at the destination
4343        // sub-block, exactly the bytes [`filter_block_4x4`] returns — across
4344        // whole-pixel (copy) AND sub-pixel (six-tap) vectors, in-bounds and
4345        // at a border-straddling origin.
4346        let w = 48;
4347        let h = 48;
4348        let plane = ramp_plane(w, h);
4349        let filters = filter_set_for_version(0).taps();
4350        // (blk_x, blk_y, mv): whole-pixel in-bounds, sub-pixel in-bounds,
4351        // whole-pixel straddling the top-left corner, sub-pixel near the
4352        // bottom-right corner.
4353        let cases = [
4354            (20, 20, Mv { row: 16, col: 8 }),  // whole-pixel, offset (1, 2)
4355            (20, 20, Mv { row: 5, col: 3 }),   // sub-pixel (mx=3, my=5)
4356            (0, 0, Mv { row: -32, col: -32 }), // whole-pixel, clamps top-left
4357            (40, 40, Mv { row: 5, col: 3 }),   // sub-pixel near bottom-right
4358        ];
4359        for (blk_x, blk_y, mv) in cases {
4360            let expected = filter_block_4x4(&plane, w, w, h, blk_x, blk_y, mv, filters);
4361            // Write into a destination raster at a non-zero strided origin
4362            // to exercise the (dst_x, dst_y, dst_stride) arithmetic.
4363            let dst_stride = 16usize;
4364            let (dst_x, dst_y) = (8usize, 12usize);
4365            let mut dst = vec![0xABu8; dst_stride * 24];
4366            filter_block_4x4_into(
4367                &mut dst, dst_stride, dst_x, dst_y, &plane, w, w, h, blk_x, blk_y, mv, filters,
4368            );
4369            for r in 0..4 {
4370                for c in 0..4 {
4371                    let d = (dst_y + r) * dst_stride + dst_x + c;
4372                    assert_eq!(
4373                        dst[d],
4374                        expected[r * 4 + c],
4375                        "mv={mv:?} blk=({blk_x},{blk_y}) ({r},{c})"
4376                    );
4377                }
4378            }
4379            // Pixels outside the 4×4 footprint must be untouched.
4380            assert_eq!(dst[0], 0xAB, "out-of-footprint corruption for mv={mv:?}");
4381        }
4382    }
4383
4384    /// Assemble a SPLITMV prediction using the strided-write primitive
4385    /// [`filter_block_4x4_into`] — the alternative write strategy the
4386    /// round-274 bench measures against [`predict_split_mv`]'s shipped
4387    /// scratch-copy form. Used only to prove the two strategies agree
4388    /// byte-for-byte (the bench shows scratch-copy is the faster of the
4389    /// two, so the production path keeps it).
4390    fn predict_split_mv_via_strided_into(
4391        reference: &ReferencePlanes<'_>,
4392        mb_col: usize,
4393        mb_row: usize,
4394        split_luma_mvs: &[Mv; 16],
4395        full_pixel: bool,
4396        filters: &[[i32; 6]; 8],
4397    ) -> ReconstructedMb {
4398        let lw = reference.mb_cols * 16;
4399        let lh = reference.mb_rows * 16;
4400        let cw = reference.mb_cols * 8;
4401        let ch = reference.mb_rows * 8;
4402        let mut out = ReconstructedMb::default();
4403        let y_x0 = mb_col * 16;
4404        let y_y0 = mb_row * 16;
4405        for sb in 0..4 {
4406            for sc in 0..4 {
4407                let mut ymv = stored_luma_mv(split_luma_mvs[sb * 4 + sc]);
4408                if full_pixel {
4409                    ymv = apply_full_pixel(ymv);
4410                }
4411                filter_block_4x4_into(
4412                    &mut out.y,
4413                    16,
4414                    sc * 4,
4415                    sb * 4,
4416                    reference.y,
4417                    reference.y_stride,
4418                    lw,
4419                    lh,
4420                    y_x0 + sc * 4,
4421                    y_y0 + sb * 4,
4422                    ymv,
4423                    filters,
4424                );
4425            }
4426        }
4427        let chroma = split_chroma_mvs(split_luma_mvs);
4428        let uv_x0 = mb_col * 8;
4429        let uv_y0 = mb_row * 8;
4430        for sb in 0..2 {
4431            for sc in 0..2 {
4432                let mut uvmv = chroma[sb * 2 + sc];
4433                if full_pixel {
4434                    uvmv = apply_full_pixel(uvmv);
4435                }
4436                filter_block_4x4_into(
4437                    &mut out.u,
4438                    8,
4439                    sc * 4,
4440                    sb * 4,
4441                    reference.u,
4442                    reference.uv_stride,
4443                    cw,
4444                    ch,
4445                    uv_x0 + sc * 4,
4446                    uv_y0 + sb * 4,
4447                    uvmv,
4448                    filters,
4449                );
4450                filter_block_4x4_into(
4451                    &mut out.v,
4452                    8,
4453                    sc * 4,
4454                    sb * 4,
4455                    reference.v,
4456                    reference.uv_stride,
4457                    cw,
4458                    ch,
4459                    uv_x0 + sc * 4,
4460                    uv_y0 + sb * 4,
4461                    uvmv,
4462                    filters,
4463                );
4464            }
4465        }
4466        out
4467    }
4468
4469    #[test]
4470    fn strided_into_assembly_matches_predict_split_mv() {
4471        // Sixteen distinct luma vectors mixing whole-pixel and sub-pixel
4472        // fractions, assembled via `filter_block_4x4_into`, must equal the
4473        // shipped `predict_split_mv` (scratch-copy) output byte-for-byte at a
4474        // mid-grid MB (in-bounds) and the top-left corner MB
4475        // (border-straddle), under both `full_pixel` polarities.
4476        let (y, u, v) = build_reference(3, 3);
4477        let reference = ReferencePlanes {
4478            y: &y,
4479            u: &u,
4480            v: &v,
4481            y_stride: 48,
4482            uv_stride: 24,
4483            mb_cols: 3,
4484            mb_rows: 3,
4485        };
4486        let filters = filter_set_for_version(0).taps();
4487
4488        // Sixteen distinct vectors: alternate whole-pixel and sub-pixel
4489        // fractions and vary the integer offset per sub-block.
4490        let mut mvs = [Mv { row: 0, col: 0 }; 16];
4491        for (i, m) in mvs.iter_mut().enumerate() {
4492            let frac_r = if i % 2 == 0 { 0 } else { (i as i16 % 7) + 1 };
4493            let frac_c = if i % 3 == 0 { 0 } else { (i as i16 % 5) + 1 };
4494            *m = Mv {
4495                row: ((i as i16 % 3) - 1) * 8 + frac_r,
4496                col: ((i as i16 % 4) - 2) * 8 + frac_c,
4497            };
4498        }
4499
4500        for full_pixel in [false, true] {
4501            for (mb_col, mb_row) in [(1usize, 1usize), (0, 0)] {
4502                let got = predict_split_mv_via_strided_into(
4503                    &reference, mb_col, mb_row, &mvs, full_pixel, filters,
4504                );
4505                let want = predict_split_mv(&reference, mb_col, mb_row, &mvs, full_pixel, filters);
4506                assert_eq!(got.y, want.y, "luma MB ({mb_col},{mb_row}) fp={full_pixel}");
4507                assert_eq!(got.u, want.u, "U MB ({mb_col},{mb_row}) fp={full_pixel}");
4508                assert_eq!(got.v, want.v, "V MB ({mb_col},{mb_row}) fp={full_pixel}");
4509            }
4510        }
4511    }
4512}