forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mc.rs1297 lines, 49.7 KiBHistoryRawDownload
1//! Motion-compensation inter predictors: reference border extension, 6-tap
2//! luma prediction, bilinear chroma prediction, and the UMV-border motion
3//! vector clamps.
4//!
5//! Normative source: [RFC 6386] §18.3 (sub-pixel interpolation, two
6//! separable 1-D passes, each sample `clamp255((a + 64) >> 7)`). The loop
7//! structure, intermediate widths and the border clamps follow the libvpx
8//! reference implementation (`vp8/common/filter.c`, `vp8/common/
9//! reconinter.c`, `vp8/common/extend.c`) sample-for-sample; the per-pass
10//! 0..=255 clamping of the 6-tap intermediate is mandated by the RFC's
11//! `interp()` and is what the integer test vectors below pin down.
12//!
13//! Reference planes arrive already border-extended by [`extend_plane`]
14//! (edge replication, `border` = 32 like libvpx's `VP8BORDERINPIXELS`);
15//! `src` starts at the first byte of the bordered buffer (top-left border
16//! corner) and visible pixel `(px, py)` therefore lives at
17//! `src[(py + border) * stride + (px + border)]`.
18//!
19//! Motion vectors are `(row, col)` pairs in eighth-pel units (`i16`), and
20//! the C arithmetic right shifts / two's-complement `& 7` phase extraction
21//! are reproduced exactly (`i32 >> 3` and `& 7` on negatives).
22//!
23//! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386
24use archmage::SimdToken;
25use multiversion::target::match_target;
26
27/// `VP8_FILTER_WEIGHT` (filter.c): tap weights sum to this, DC passes.
28const VP8_FILTER_WEIGHT: i32 = 128;
29/// `VP8_FILTER_SHIFT` (filter.c): normalize the 7-bit-precision result.
30const VP8_FILTER_SHIFT: i32 = 7;
31
32/// `vp8_sub_pel_filters[8][6]` (filter.c), indexed by the 0..8 sub-pel phase.
33const SUB_PEL_FILTERS: [[i32; 6]; 8] = [
34 [0, 0, 128, 0, 0, 0], // degenerate whole-pel (RFC 6386 §18.3 "filters[0]")
35 [0, -6, 123, 12, -1, 0],
36 [2, -11, 108, 36, -8, 1],
37 [0, -9, 93, 50, -6, 0],
38 [3, -16, 77, 77, -16, 3],
39 [0, -6, 50, 93, -9, 0],
40 [1, -8, 36, 108, -11, 2],
41 [0, -1, 12, 123, -6, 0],
42];
43
44/// `vp8_bilinear_filters[8][2]` (filter.c); chroma prediction is always
45/// bilinear (RFC 6386 §19.2).
46const BILINEAR_FILTERS: [[i32; 2]; 8] = [
47 [128, 0],
48 [112, 16],
49 [96, 32],
50 [80, 48],
51 [64, 64],
52 [48, 80],
53 [32, 96],
54 [16, 112],
55];
56
57#[inline]
58fn clamp255(v: i32) -> i32 {
59 v.clamp(0, 255)
60}
61
62/// Extends the visible `vis_w` x `vis_h` region of `plane` into the `border`
63/// ring on all four sides by edge replication: every out-of-image sample
64/// becomes the nearest in-image sample.
65///
66/// Port of `copy_and_extend_plane` (extend.c) with `et = el = eb = er =
67/// border` and `interleave_step = 1`, in place: first the left/right border
68/// of every visible row is filled from the row's first/last column, then the
69/// (already side-extended) top and bottom rows are copied into the top and
70/// bottom borders — which gives the corners their corner pixels, matching
71/// the C exactly.
72pub(crate) fn extend_plane(plane: &mut [u8], stride: usize, vis_w: usize, vis_h: usize, border: usize) {
73 debug_assert!(vis_w >= 1 && vis_h >= 1);
74 debug_assert!(stride >= border * 2 + vis_w);
75
76 let line = border + vis_w + border;
77
78 // extend.c: "copy the left and right most columns out".
79 for r in 0..vis_h {
80 let base = (border + r) * stride + border;
81 let first = plane[base];
82 let last = plane[base + vis_w - 1];
83 plane[base - border..base].fill(first);
84 plane[base + vis_w..base + vis_w + border].fill(last);
85 }
86
87 // extend.c: "Now copy the top and bottom lines into each line of the
88 // respective borders" — src rows are the already side-extended lines.
89 let top = border * stride;
90 let bottom = (border + vis_h - 1) * stride;
91 for i in 0..border {
92 plane.copy_within(top..top + line, (border - 1 - i) * stride);
93 plane.copy_within(bottom..bottom + line, (border + vis_h + i) * stride);
94 }
95}
96
97/// Luma predictor for one `bw` x `bh` block (`bw`,`bh` in 4..=16, multiples
98/// of 4) whose visible-image top-left pixel is `(x, y)`.
99///
100/// Semantics of `vp8_build_inter_predictors_b` /
101/// `vp8_build_inter16x16_predictors_mby` + `vp8_sixtap_predict*` (reconinter.c,
102/// filter.c): full-pel start `(x + (mv.1 >> 3), y + (mv.0 >> 3))`, phases
103/// `fx = mv.1 & 7`, `fy = mv.0 & 7`; a whole-pel MV is a plain copy,
104/// otherwise the separable 6-tap filter runs horizontally into an `i32`
105/// intermediate — clamped to 0..=255 per pass like libvpx's `int` `FData` —
106/// then vertically, both passes computing `(dot + 64) >> 7` and clamping.
107///
108/// When `need_clamp` is set, the MV is first passed through
109/// [`clamp_mv_to_umv_border`].
110// mirrors the argument list of the C predictor it ports
111#[allow(clippy::too_many_arguments)]
112pub(crate) fn predict_luma(
113 src: &[u8],
114 stride: usize,
115 border: usize,
116 vis_w: usize,
117 vis_h: usize,
118 x: usize,
119 y: usize,
120 mv: (i16, i16),
121 need_clamp: bool,
122 dst: &mut [u8],
123 dst_stride: usize,
124 bw: usize,
125 bh: usize,
126 bilinear: bool,
127) {
128 debug_assert!((4..=16).contains(&bw) && bw.is_multiple_of(4));
129 debug_assert!((4..=16).contains(&bh) && bh.is_multiple_of(4));
130
131 let mut mv = (i32::from(mv.0), i32::from(mv.1));
132 if need_clamp {
133 clamp_mv_to_umv_border(&mut mv, x >> 4, y >> 4, vis_w, vis_h);
134 }
135
136 let fx = (mv.1 & 7) as usize;
137 let fy = (mv.0 & 7) as usize;
138 let sx = border as i32 + x as i32 + (mv.1 >> 3);
139 let sy = border as i32 + y as i32 + (mv.0 >> 3);
140 // The libvpx clamp keeps a conforming read inside the border; an
141 // unclamped split MV may not, so the origin is brought back in range.
142 let (sx, sy) = clamp_read_origin(sx, sy, stride, vis_h + 2 * border, bw, bh);
143
144 if bilinear {
145 bilinear_block(src, stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
146 } else {
147 sixtap_block(src, stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
148 }
149}
150
151/// Six-tap separable sub-pel predictor (libvpx vp8_sixtap_predict*,
152/// filter.c). `(sx, sy)` is the full-pel block origin in the bordered
153/// reference, `(fx, fy)` the sub-pel phases 0..7 (0 = copy).
154///
155/// Both passes share one clamped intermediate buffer: the first pass is
156/// clamped to 0..=255 per pass (libvpx `clamp_pixel`), so it is stored as
157/// `u8` at a fixed 16-lane stride. The AVX2 kernels always compute all 16
158/// lanes of an intermediate row (reads stay inside the 32-px border for
159/// every block shape) and the vertical pass discards the tail lanes with
160/// its `bw`-byte store; the scalar reference only fills the first `bw`.
161// mirrors the argument list of the C predictor it ports
162#[allow(clippy::too_many_arguments)]
163fn sixtap_block(
164 src: &[u8],
165 stride: usize,
166 sx: usize,
167 sy: usize,
168 fx: usize,
169 fy: usize,
170 dst: &mut [u8],
171 dst_stride: usize,
172 bw: usize,
173 bh: usize,
174) {
175 if fx == 0 && fy == 0 {
176 // reconinter.c build_inter_predictors_b / vp8_copy_mem*.
177 for r in 0..bh {
178 let s = (sy + r) * stride + sx;
179 dst[r * dst_stride..r * dst_stride + bw].copy_from_slice(&src[s..s + bw]);
180 }
181 return;
182 }
183
184 sixtap_2d(src, stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
185}
186
187/// Both separable passes of [`sixtap_block`] for a fractional phase.
188///
189/// Runtime dispatch is done by `multiversion`: the AVX2 clone runs the
190/// [`simd`] kernels, the baseline clone runs the scalar reference. The
191/// AVX2 pass reads 21 bytes per row, which a 4-wide block at the far edge
192/// of the clamp can push past the buffer; those blocks take the exact-width
193/// scalar path even in the AVX2 clone.
194// mirrors the argument list of the C predictor it ports
195#[allow(clippy::too_many_arguments)]
196#[multiversion::multiversion(targets("x86_64+avx2"))]
197fn sixtap_2d(
198 src: &[u8],
199 stride: usize,
200 sx: usize,
201 sy: usize,
202 fx: usize,
203 fy: usize,
204 dst: &mut [u8],
205 dst_stride: usize,
206 bw: usize,
207 bh: usize,
208) {
209 let hf = &SUB_PEL_FILTERS[fx];
210 let vf = &SUB_PEL_FILTERS[fy];
211 let rows = bh + 5;
212 let mut tmp = [0u8; 21 * 16]; // C: int FData[21 * 24], clamped to u8
213
214 match_target! {
215 "x86_64+avx2" => {
216 if let Some(t) = archmage::X64V3Token::summon() {
217 if (sy + rows - 2) * stride + sx + 19 <= src.len() {
218 simd::sixtap_h(t, src, stride, sx, sy, hf, &mut tmp, rows);
219 simd::sixtap_v(t, &tmp, vf, dst, dst_stride, bw, bh);
220 return;
221 }
222 }
223 }
224 _ => {}
225 }
226
227 sixtap_h_scalar(src, stride, sx, sy, hf, &mut tmp, bw, rows);
228 sixtap_v_scalar(&tmp, vf, dst, dst_stride, bw, bh);
229}
230
231/// Scalar first pass of [`sixtap_block`] (filter.c
232/// `filter_block2d_first_pass` on `src - 2*stride`): `rows` = `bh + 5`
233/// horizontal lines, each sample `(dot + 64) >> 7` clamped to 0..=255.
234/// Phase 0 is the exact identity (`(p * 128 + 64) >> 7 == p`), so the
235/// uniform loop reproduces the C for every phase combination.
236// mirrors the argument list of the C predictor it ports
237#[allow(clippy::too_many_arguments)]
238fn sixtap_h_scalar(
239 src: &[u8],
240 stride: usize,
241 sx: usize,
242 sy: usize,
243 hf: &[i32; 6],
244 tmp: &mut [u8; 21 * 16],
245 bw: usize,
246 rows: usize,
247) {
248 for i in 0..rows {
249 let row = (sy + i - 2) * stride + sx - 2;
250 for j in 0..bw {
251 let p = row + j;
252 let acc = i32::from(src[p]) * hf[0]
253 + i32::from(src[p + 1]) * hf[1]
254 + i32::from(src[p + 2]) * hf[2]
255 + i32::from(src[p + 3]) * hf[3]
256 + i32::from(src[p + 4]) * hf[4]
257 + i32::from(src[p + 5]) * hf[5]
258 + (VP8_FILTER_WEIGHT >> 1); /* Rounding */
259 tmp[i * 16 + j] = clamp255(acc >> VP8_FILTER_SHIFT) as u8;
260 }
261 }
262}
263
264/// Scalar second pass of [`sixtap_block`] (filter.c
265/// `filter_block2d_second_pass` on `FData + 2*bw`): taps read the
266/// intermediate rows `r .. r + 5` at the fixed 16-lane stride.
267fn sixtap_v_scalar(
268 tmp: &[u8; 21 * 16],
269 vf: &[i32; 6],
270 dst: &mut [u8],
271 dst_stride: usize,
272 bw: usize,
273 bh: usize,
274) {
275 for r in 0..bh {
276 for c in 0..bw {
277 let acc = i32::from(tmp[r * 16 + c]) * vf[0]
278 + i32::from(tmp[(r + 1) * 16 + c]) * vf[1]
279 + i32::from(tmp[(r + 2) * 16 + c]) * vf[2]
280 + i32::from(tmp[(r + 3) * 16 + c]) * vf[3]
281 + i32::from(tmp[(r + 4) * 16 + c]) * vf[4]
282 + i32::from(tmp[(r + 5) * 16 + c]) * vf[5]
283 + (VP8_FILTER_WEIGHT >> 1); /* Rounding */
284 dst[r * dst_stride + c] = clamp255(acc >> VP8_FILTER_SHIFT) as u8;
285 }
286 }
287}
288
289/// Explicit `std::arch::x86_64` kernels for the six-tap and bilinear
290/// passes (the 18% of a decode the profile pins on `sixtap_block` and its
291/// chroma siblings). Nothing here is spec logic: each kernel is the scalar
292/// function's arithmetic lane-parallel, with the same rounding, the same
293/// truncation points and the same clamps -- the equivalence tests run
294/// every kernel against its scalar reference over all shapes, phases and
295/// worst-case input bytes.
296///
297/// The kernels are safe functions. Their only precondition is AVX2, which
298/// the `X64V3Token` argument proves; the token comes only from `summon()`,
299/// which checks the CPU at runtime, so [`sixtap_2d`] and [`bilinear_2d`]
300/// pass it only when AVX2 is present. Loads and stores go through `bytemuck`
301/// on slices, so every access is bounds-checked.
302///
303/// Exactness notes shared by the six-tap kernels:
304/// - `_mm*_madd_epi16` multiplies *pairs of samples* by a packed tap pair
305/// and accumulates in `i32`; every product is exact (widened samples
306/// are 0..=255, `|byte * tap| <= 255 * 128 < 2^15`) and the six-product
307/// sum is exact in `i32` (`|dot + 64| <= 255 * 160 + 64 < 2^23`).
308/// - The even/odd column split exists because `madd` pairs *adjacent*
309/// samples: the even accumulator's `madd` lane m is output `2m`, the
310/// odd one output `2m+1` (load offset +1 shifts the sample window).
311/// - `packs_epi32`'s `i32 -> i16` saturation can never fire: after
312/// `(dot + 64) >> 7` the range is `[-76, 319]`.
313/// - `packus_epi16`'s `u8` saturation *is* filter.c's `clamp_pixel`:
314/// values below 0 saturate to 0, above 255 to 255, the rest unchanged.
315#[cfg(target_arch = "x86_64")]
316mod simd {
317 use super::{VP8_FILTER_SHIFT, VP8_FILTER_WEIGHT};
318 use archmage::{X64V3Token, arcane};
319 use std::arch::x86_64::*;
320
321 /// Tap pair `[t0, t1]` packed into one `i32`, the operand shape
322 /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))`
323 /// is `s[2j] * t0 + s[2j+1] * t1` (ec-av1 `mc::simd::tap_pairs`).
324 #[inline]
325 fn tap_pair(a: i32, b: i32) -> i32 {
326 (b << 16) | (a as u16 as i32)
327 }
328
329 /// 16 bytes from the front of `s` (the `loadu_si128` of the kernels).
330 #[inline(always)]
331 fn ld16(s: &[u8]) -> __m128i {
332 bytemuck::pod_read_unaligned(&s[..16])
333 }
334
335 /// The low 8 bytes of `s` in the low half of a register, the high half
336 /// zero. Only `_mm_cvtepu8_epi16` consumers read it, and those take the
337 /// low 8 bytes, so this matches the 16-byte load the C-shaped code
338 /// used without reading past the 8 bytes that matter.
339 #[inline(always)]
340 fn ld8(s: &[u8]) -> __m128i {
341 let mut b = [0u8; 16];
342 b[..8].copy_from_slice(&s[..8]);
343 bytemuck::cast(b)
344 }
345
346 /// Stores all 16 bytes of `v` at the front of `d`.
347 #[inline(always)]
348 fn st16(d: &mut [u8], v: __m128i) {
349 let b: [u8; 16] = bytemuck::cast(v);
350 d[..16].copy_from_slice(&b);
351 }
352
353 /// Stores the low 8 bytes of `v` at the front of `d`.
354 #[inline(always)]
355 fn st8(d: &mut [u8], v: __m128i) {
356 let b: [u8; 16] = bytemuck::cast(v);
357 d[..8].copy_from_slice(&b[..8]);
358 }
359
360 /// Stores the low 4 bytes of `v` at the front of `d`.
361 #[inline(always)]
362 fn st4(d: &mut [u8], v: __m128i) {
363 let b: [u8; 16] = bytemuck::cast(v);
364 d[..4].copy_from_slice(&b[..4]);
365 }
366
367 /// Six-tap first pass, all 16 lanes of every intermediate row (see
368 /// [`sixtap_2d`] for the layout).
369 ///
370 /// The caller guarantees that for every `i < rows`, the 21 bytes
371 /// starting at `(sy + i - 2) * stride + sx - 2` are in `src` (with
372 /// `sx, sy >= 2`); the slice indexing below enforces it.
373 #[arcane]
374 pub(super) fn sixtap_h(
375 _t: X64V3Token,
376 src: &[u8],
377 stride: usize,
378 sx: usize,
379 sy: usize,
380 hf: &[i32; 6],
381 tmp: &mut [u8; 21 * 16],
382 rows: usize,
383 ) {
384 debug_assert!(sx >= 2 && sy >= 2);
385 let tv = [
386 _mm256_set1_epi32(tap_pair(hf[0], hf[1])),
387 _mm256_set1_epi32(tap_pair(hf[2], hf[3])),
388 _mm256_set1_epi32(tap_pair(hf[4], hf[5])),
389 ];
390 let rnd = _mm256_set1_epi32(VP8_FILTER_WEIGHT >> 1);
391 for i in 0..rows {
392 let base = (sy + i - 2) * stride + sx - 2;
393 let win = &src[base..base + 21];
394 // `cvtepu8_epi16` of the 16-byte window at byte offset `2k`
395 // puts each even output's tap pair in one `madd` lane pair:
396 // `e` accumulates outputs 0,2,..,14, `o` (window +1 byte)
397 // outputs 1,3,..,15.
398 let mut e = _mm256_setzero_si256();
399 let mut o = _mm256_setzero_si256();
400 // tap loop walks the vector taps and the source offsets together
401 #[allow(clippy::needless_range_loop)]
402 for k in 0..3 {
403 let se = _mm256_cvtepu8_epi16(ld16(&win[2 * k..]));
404 e = _mm256_add_epi32(e, _mm256_madd_epi16(se, tv[k]));
405 let so = _mm256_cvtepu8_epi16(ld16(&win[2 * k + 1..]));
406 o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k]));
407 }
408 e = _mm256_srai_epi32(_mm256_add_epi32(e, rnd), VP8_FILTER_SHIFT);
409 o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), VP8_FILTER_SHIFT);
410 // `unpacklo/hi` + `packs` interleave even/odd outputs back in
411 // order (0..8 in the low 128-bit half, 8..16 in the high
412 // half), then `packus` narrows both halves in sequence -- its
413 // `u8` saturation is filter.c's `clamp_pixel` itself.
414 let lo = _mm256_unpacklo_epi32(e, o);
415 let hi = _mm256_unpackhi_epi32(e, o);
416 let i16 = _mm256_packs_epi32(lo, hi);
417 let u8 = _mm_packus_epi16(
418 _mm256_castsi256_si128(i16),
419 _mm256_extracti128_si256::<1>(i16),
420 );
421 st16(&mut tmp[i * 16..], u8);
422 }
423 }
424
425 /// Six-tap second pass: `bh` output rows of `bw` (4/8/16) samples from
426 /// the 16-lane-strided intermediate. `dst` must hold `bh` rows of `bw`
427 /// bytes at `dst_stride` (slice indexing enforces it); `bw` is 4, 8 or 16.
428 #[arcane]
429 pub(super) fn sixtap_v(
430 _t: X64V3Token,
431 tmp: &[u8; 21 * 16],
432 vf: &[i32; 6],
433 dst: &mut [u8],
434 dst_stride: usize,
435 bw: usize,
436 bh: usize,
437 ) {
438 debug_assert!(matches!(bw, 4 | 8 | 16));
439 let tv = [
440 _mm256_set1_epi32(tap_pair(vf[0], vf[1])),
441 _mm256_set1_epi32(tap_pair(vf[2], vf[3])),
442 _mm256_set1_epi32(tap_pair(vf[4], vf[5])),
443 ];
444 let rnd = _mm256_set1_epi32(VP8_FILTER_WEIGHT >> 1);
445 for r in 0..bh {
446 // Rows `r + 2k` / `r + 2k + 1` widened to samples, interleaved
447 // by `unpack_epi16` so one `madd` covers two taps of every
448 // output; `lo` holds even columns, `hi` odd ones (one run per
449 // 128-bit lane).
450 let mut lo = _mm256_setzero_si256();
451 let mut hi = _mm256_setzero_si256();
452 // tap loop walks the vector taps and the source offsets together
453 #[allow(clippy::needless_range_loop)]
454 for k in 0..3 {
455 let a = _mm256_cvtepu8_epi16(ld16(&tmp[(r + 2 * k) * 16..]));
456 let b = _mm256_cvtepu8_epi16(ld16(&tmp[(r + 2 * k + 1) * 16..]));
457 lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv[k]));
458 hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv[k]));
459 }
460 lo = _mm256_srai_epi32(_mm256_add_epi32(lo, rnd), VP8_FILTER_SHIFT);
461 hi = _mm256_srai_epi32(_mm256_add_epi32(hi, rnd), VP8_FILTER_SHIFT);
462 // `packs` reorders to outputs 0..8 | 8..16 across the two
463 // 128-bit halves, in column order.
464 let i16 = _mm256_packs_epi32(lo, hi);
465 let u8 = _mm_packus_epi16(
466 _mm256_castsi256_si128(i16),
467 _mm256_extracti128_si256::<1>(i16),
468 );
469 let row = &mut dst[r * dst_stride..];
470 match bw {
471 16 => st16(row, u8),
472 8 => st8(row, u8),
473 4 => st4(row, u8),
474 _ => unreachable!("bw is 4, 8 or 16"),
475 }
476 }
477 }
478
479 /// Bilinear first pass, 8 output columns per step (`bw` is 4, 8 or
480 /// 16; `bw = 16` runs the loop twice). The `i16` accumulator is exact:
481 /// taps are non-negative and sum to 128, so every product and the sum
482 /// stay `<= 255 * 128 + 64 < 2^15` -- this *is* the C's `unsigned
483 /// short` intermediate, narrowed at a provably-in-range point.
484 ///
485 /// The caller guarantees that for every `i < rows`, the 17 bytes
486 /// starting at `(sy + i) * stride + sx` are in `src`; the slice
487 /// indexing below enforces it.
488 #[arcane]
489 pub(super) fn bilinear_h(
490 _t: X64V3Token,
491 src: &[u8],
492 stride: usize,
493 sx: usize,
494 sy: usize,
495 hf: &[i32; 2],
496 tmp: &mut [u8; 17 * 16],
497 rows: usize,
498 ) {
499 let f0 = _mm_set1_epi16(hf[0] as i16);
500 let f1 = _mm_set1_epi16(hf[1] as i16);
501 let rnd = _mm_set1_epi16((VP8_FILTER_WEIGHT / 2) as i16);
502 for i in 0..rows {
503 let row = &src[(sy + i) * stride + sx..];
504 for c in (0..16).step_by(8) {
505 // Lane j pairs the samples `j` and `j + 1` (tap `[0]` on
506 // the window at `c`, tap `[1]` shifted by one byte).
507 let a = _mm_cvtepu8_epi16(ld8(&row[c..]));
508 let b = _mm_cvtepu8_epi16(ld8(&row[c + 1..]));
509 let acc = _mm_add_epi16(
510 _mm_add_epi16(_mm_mullo_epi16(a, f0), _mm_mullo_epi16(b, f1)),
511 rnd,
512 );
513 let u8 = _mm_packus_epi16(_mm_srai_epi16::<VP8_FILTER_SHIFT>(acc), acc);
514 st8(&mut tmp[i * 16 + c..], u8);
515 }
516 }
517 }
518
519 /// Bilinear second pass: rows `r` / `r + 1` of the intermediate, same
520 /// exact-`i16` shape as [`bilinear_h`]. `dst` must hold `bh` rows of
521 /// `bw` bytes at `dst_stride` (slice indexing enforces it); `bw` is
522 /// 4, 8 or 16.
523 #[arcane]
524 pub(super) fn bilinear_v(
525 _t: X64V3Token,
526 tmp: &[u8; 17 * 16],
527 vf: &[i32; 2],
528 dst: &mut [u8],
529 dst_stride: usize,
530 bw: usize,
531 bh: usize,
532 ) {
533 debug_assert!(matches!(bw, 4 | 8 | 16));
534 let f0 = _mm_set1_epi16(vf[0] as i16);
535 let f1 = _mm_set1_epi16(vf[1] as i16);
536 let rnd = _mm_set1_epi16((VP8_FILTER_WEIGHT / 2) as i16);
537 for r in 0..bh {
538 let drow = &mut dst[r * dst_stride..];
539 for c in (0..bw).step_by(8) {
540 let a = _mm_cvtepu8_epi16(ld8(&tmp[r * 16 + c..]));
541 let b = _mm_cvtepu8_epi16(ld8(&tmp[(r + 1) * 16 + c..]));
542 let acc = _mm_add_epi16(
543 _mm_add_epi16(_mm_mullo_epi16(a, f0), _mm_mullo_epi16(b, f1)),
544 rnd,
545 );
546 let u8 = _mm_packus_epi16(_mm_srai_epi16::<VP8_FILTER_SHIFT>(acc), acc);
547 match bw - c {
548 8 | 16 => st8(&mut drow[c..], u8),
549 _ => st4(&mut drow[c..], u8),
550 }
551 }
552 }
553 }
554}
555
556/// Two-tap bilinear separable predictor (libvpx vp8_bilinear_predict*,
557/// filter.c). The dot products are provably in 0..=255 (taps are
558/// non-negative and sum to 128 over 0..=255 inputs), which is why libvpx's
559/// bilinear passes store `unsigned short` intermediates and skip the
560/// clamp: the intermediate is stored as `u8` at a fixed 16-lane stride
561/// (representation-only change, same argument as [`sixtap_block`]).
562// mirrors the argument list of the C predictor it ports
563#[allow(clippy::too_many_arguments)]
564fn bilinear_block(
565 src: &[u8],
566 stride: usize,
567 sx: usize,
568 sy: usize,
569 fx: usize,
570 fy: usize,
571 dst: &mut [u8],
572 dst_stride: usize,
573 bw: usize,
574 bh: usize,
575) {
576 if fx == 0 && fy == 0 {
577 for r in 0..bh {
578 let s = (sy + r) * stride + sx;
579 dst[r * dst_stride..r * dst_stride + bw].copy_from_slice(&src[s..s + bw]);
580 }
581 return;
582 }
583
584 bilinear_2d(src, stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
585}
586
587/// Both separable passes of [`bilinear_block`] for a fractional phase.
588/// Dispatched like [`sixtap_2d`]: the AVX2 clone runs the [`simd`] kernels
589/// when the read window fits in `src`, the baseline clone the scalar path.
590// mirrors the argument list of the C predictor it ports
591#[allow(clippy::too_many_arguments)]
592#[multiversion::multiversion(targets("x86_64+avx2"))]
593fn bilinear_2d(
594 src: &[u8],
595 stride: usize,
596 sx: usize,
597 sy: usize,
598 fx: usize,
599 fy: usize,
600 dst: &mut [u8],
601 dst_stride: usize,
602 bw: usize,
603 bh: usize,
604) {
605 let hf = &BILINEAR_FILTERS[fx];
606 let vf = &BILINEAR_FILTERS[fy];
607 let rows = bh + 1;
608 let mut tmp = [0u8; 17 * 16]; // C: unsigned short FData[17 * 16], <= 255
609
610 match_target! {
611 "x86_64+avx2" => {
612 if let Some(t) = archmage::X64V3Token::summon() {
613 if (sy + rows - 1) * stride + sx + 16 < src.len() {
614 simd::bilinear_h(t, src, stride, sx, sy, hf, &mut tmp, rows);
615 simd::bilinear_v(t, &tmp, vf, dst, dst_stride, bw, bh);
616 return;
617 }
618 }
619 }
620 _ => {}
621 }
622
623 bilinear_h_scalar(src, stride, sx, sy, hf, &mut tmp, bw, rows);
624 bilinear_v_scalar(&tmp, vf, dst, dst_stride, bw, bh);
625}
626
627/// Scalar first pass of [`bilinear_block`] (filter.c
628/// `filter_block2d_bil_first_pass`): `bh + 1` rows, taps `[0]` and `[1]`.
629/// Phase 0 is the exact identity, as in [`sixtap_h_scalar`].
630// mirrors the argument list of the C predictor it ports
631#[allow(clippy::too_many_arguments)]
632fn bilinear_h_scalar(
633 src: &[u8],
634 stride: usize,
635 sx: usize,
636 sy: usize,
637 hf: &[i32; 2],
638 tmp: &mut [u8; 17 * 16],
639 bw: usize,
640 rows: usize,
641) {
642 for i in 0..rows {
643 let row = (sy + i) * stride + sx;
644 for j in 0..bw {
645 let p = row + j;
646 let acc = i32::from(src[p]) * hf[0] + i32::from(src[p + 1]) * hf[1]
647 + (VP8_FILTER_WEIGHT / 2); /* Rounding */
648 tmp[i * 16 + j] = (acc >> VP8_FILTER_SHIFT) as u8;
649 }
650 }
651}
652
653/// Scalar second pass of [`bilinear_block`] (filter.c
654/// `filter_block2d_bil_second_pass`): taps `[0]` and `[1]` read rows
655/// `r` / `r + 1` of the intermediate at the fixed 16-lane stride.
656fn bilinear_v_scalar(
657 tmp: &[u8; 17 * 16],
658 vf: &[i32; 2],
659 dst: &mut [u8],
660 dst_stride: usize,
661 bw: usize,
662 bh: usize,
663) {
664 for r in 0..bh {
665 for c in 0..bw {
666 let acc = i32::from(tmp[r * 16 + c]) * vf[0]
667 + i32::from(tmp[(r + 1) * 16 + c]) * vf[1]
668 + (VP8_FILTER_WEIGHT / 2); /* Rounding */
669 dst[r * dst_stride + c] = (acc >> VP8_FILTER_SHIFT) as u8;
670 }
671 }
672}
673
674/// Chroma predictor for one `bw` x `bh` block whose visible-image top-left
675/// chroma pixel is `(x, y)`.
676///
677/// `mv` is the chroma MV in eighth-CHROMA-pel units (the caller derives it
678/// from luma per libvpx: round-half-away-from-zero division by 2 (whole MB)
679/// or sum-then-divide-by-8 (SPLITMV), `& fullpixel_mask`).
680///
681/// The interpolation filter is the FRAME's MC filter, exactly like luma:
682/// `vp8_setup_version` picks six-tap for version 0 (and reserved 4-7) and
683/// bilinear for versions 1-3 (decodeframe.c:851-860 assigns BOTH
684/// `subpixel_predict` and `subpixel_predict8x8` from that one switch, and
685/// reconinter.c uses them for the chroma predicts). `bilinear` is that
686/// per-frame selection.
687///
688/// When `need_clamp` is set, the MV is first passed through
689/// [`clamp_uvmv_to_umv_border`].
690// mirrors the argument list of the C predictor it ports
691#[allow(clippy::too_many_arguments)]
692pub(crate) fn predict_chroma(
693 src: &[u8],
694 uv_stride: usize,
695 border: usize,
696 vis_w: usize,
697 vis_h: usize,
698 x: usize,
699 y: usize,
700 mv: (i16, i16),
701 need_clamp: bool,
702 dst: &mut [u8],
703 dst_stride: usize,
704 bw: usize,
705 bh: usize,
706 bilinear: bool,
707) {
708 debug_assert!((2..=16).contains(&bw) && bw.is_multiple_of(2));
709 debug_assert!((2..=16).contains(&bh) && bh.is_multiple_of(2));
710
711 let mut mv = (i32::from(mv.0), i32::from(mv.1));
712 if need_clamp {
713 // A right/bottom chroma quadrant starts at x == vis_w; it still
714 // lives in the last MB, so clamp the derived MB index.
715 let mb_cols = (vis_w + 15) >> 4;
716 let mb_rows = (vis_h + 15) >> 4;
717 let mbc = (x >> 3).min(mb_cols - 1);
718 let mbr = (y >> 3).min(mb_rows - 1);
719 clamp_uvmv_to_umv_border(&mut mv, mbc, mbr, vis_w, vis_h);
720 }
721
722 let fx = (mv.1 & 7) as usize;
723 let fy = (mv.0 & 7) as usize;
724 let sx = border as i32 + x as i32 + (mv.1 >> 3);
725 let sy = border as i32 + y as i32 + (mv.0 >> 3);
726 // Chroma planes hold vis_h / 2 visible rows (`vis_*` are luma sizes).
727 let (sx, sy) = clamp_read_origin(sx, sy, uv_stride, vis_h / 2 + 2 * border, bw, bh);
728
729 if bilinear {
730 bilinear_block(src, uv_stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
731 } else {
732 sixtap_block(src, uv_stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
733 }
734}
735
736/// Keeps a `bw` x `bh` reference read inside a bordered plane of `stride`
737/// columns and `total_rows` rows, `(sx, sy)` being the block origin.
738///
739/// The 6-tap filter reads 2 samples before and 3 after the origin, so the
740/// origin must lie in `2..=stride - bw - 3` (and likewise for rows); one
741/// extra sample of slack is kept. Conforming streams are always in range.
742/// A block whose origin lies outside the border is clamped to the nearest
743/// in-range origin. Every sample it reads is then border replication, so the
744/// prediction equals the unclamped one, and the read stays in bounds.
745fn clamp_read_origin(
746 sx: i32,
747 sy: i32,
748 stride: usize,
749 total_rows: usize,
750 bw: usize,
751 bh: usize,
752) -> (usize, usize) {
753 let max_x = stride.saturating_sub(bw + 4).max(2) as i32;
754 let max_y = total_rows.saturating_sub(bh + 4).max(2) as i32;
755 (sx.clamp(2, max_x) as usize, sy.clamp(2, max_y) as usize)
756}
757
758/// The macroblock-level UMV border edges in eighth-pel units, exactly the
759/// decoder's `xd->mb_to_{left,right,top,bottom}_edge` (decodeframe.c:503-532):
760///
761/// ```c
762/// xd->mb_to_top_edge = -((mb_row * 16) << 3);
763/// xd->mb_to_bottom_edge = ((mb_rows - 1 - mb_row) * 16) << 3;
764/// xd->mb_to_left_edge = -((mb_col * 16) << 3);
765/// xd->mb_to_right_edge = ((mb_cols - 1 - mb_col) * 16) << 3;
766/// ```
767///
768/// with `mb_rows`/`mb_cols` the full (partial MB inclusive) MB counts of the
769/// visible frame. Returns `(left, right, top, bottom)`.
770fn mb_edges(mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) -> (i32, i32, i32, i32) {
771 let mb_cols = (vis_w + 15) >> 4;
772 let mb_rows = (vis_h + 15) >> 4;
773 debug_assert!(mb_col < mb_cols && mb_row < mb_rows);
774 let left = -(((mb_col * 16) as i32) << 3);
775 let right = (((mb_cols - 1 - mb_col) * 16) as i32) << 3;
776 let top = -(((mb_row * 16) as i32) << 3);
777 let bottom = (((mb_rows - 1 - mb_row) * 16) as i32) << 3;
778 (left, right, top, bottom)
779}
780
781/// Port of `clamp_mv_to_umv_border` (reconinter.c:257-278), luma MV in
782/// eighth-pel units:
783///
784/// ```c
785/// if (mv->col < (xd->mb_to_left_edge - (19 << 3))) {
786/// mv->col = xd->mb_to_left_edge - (16 << 3);
787/// } else if (mv->col > xd->mb_to_right_edge + (18 << 3)) {
788/// mv->col = xd->mb_to_right_edge + (16 << 3);
789/// }
790/// /* same for row with top/bottom edges */
791/// ```
792///
793/// 19 px slack toward left/top (16 px + 3 taps right of the central pixel),
794/// 18 px toward right/bottom (16 px + 2 taps left of it); the clamp anchor
795/// is 16 px inside the border. `mb_col`/`mb_row` locate the block's
796/// macroblock; libvpx clamps with these MB-level edges for whole-MB MVs and,
797/// when `need_to_clamp_mvs` is set, for each SPLITMV subblock MV too
798/// (reconinter.c:370-375, 397-400).
799fn clamp_mv_to_umv_border(mv: &mut (i32, i32), mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) {
800 let (left, right, top, bottom) = mb_edges(mb_col, mb_row, vis_w, vis_h);
801 if mv.1 < left - (19 << 3) {
802 mv.1 = left - (16 << 3);
803 } else if mv.1 > right + (18 << 3) {
804 mv.1 = right + (16 << 3);
805 }
806
807 if mv.0 < top - (19 << 3) {
808 mv.0 = top - (16 << 3);
809 } else if mv.0 > bottom + (18 << 3) {
810 mv.0 = bottom + (16 << 3);
811 }
812}
813
814/// Port of `clamp_uvmv_to_umv_border` (reconinter.c:281-295), chroma MV in
815/// eighth-CHROMA-pel units. The comparison doubles the chroma MV back into
816/// luma eighth-pel units (`2 * mv->col`, the "different divisor": the
817/// chroma border reach is half the luma one) and the clamp target is the
818/// luma anchor halved:
819///
820/// ```c
821/// mv->col = (2 * mv->col < (xd->mb_to_left_edge - (19 << 3)))
822/// ? (xd->mb_to_left_edge - (16 << 3)) >> 1
823/// : mv->col;
824/// mv->col = (2 * mv->col > xd->mb_to_right_edge + (18 << 3))
825/// ? (xd->mb_to_right_edge + (16 << 3)) >> 1
826/// : mv->col;
827/// /* same for row */
828/// ```
829///
830/// The C applies the two ternaries in sequence (right check sees the
831/// left-clamped value, which cannot trip it); the sequential `if`s here are
832/// that verbatim. `(left - (16 << 3))` is a multiple of 256 so `>> 1` is
833/// exact. Callers must re-apply this clamp AFTER full-pel rounding of a
834/// derived chroma MV: rounding to full-pel can move the MV outside the
835/// border tap window even though the luma MV was already clamped
836/// (reconinter.c:336-339 — the 16x16 path clamps the chroma MV
837/// unconditionally for exactly this reason).
838fn clamp_uvmv_to_umv_border(mv: &mut (i32, i32), mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) {
839 let (left, right, top, bottom) = mb_edges(mb_col, mb_row, vis_w, vis_h);
840
841 if 2 * mv.1 < left - (19 << 3) {
842 mv.1 = (left - (16 << 3)) >> 1;
843 }
844 if 2 * mv.1 > right + (18 << 3) {
845 mv.1 = (right + (16 << 3)) >> 1;
846 }
847
848 if 2 * mv.0 < top - (19 << 3) {
849 mv.0 = (top - (16 << 3)) >> 1;
850 }
851 if 2 * mv.0 > bottom + (18 << 3) {
852 mv.0 = (bottom + (16 << 3)) >> 1;
853 }
854}
855
856#[cfg(test)]
857mod tests {
858 use super::*;
859
860 /// Deterministic plane fill shared by every test (LCG, same sequence in
861 /// the hand-computed literals below).
862 fn lcg_plane(seed: u32, len: usize) -> Vec<u8> {
863 let mut out = vec![0u8; len];
864 let mut s = seed;
865 for b in out.iter_mut() {
866 s = s.wrapping_mul(1664525).wrapping_add(1013904223);
867 *b = (s >> 16) as u8;
868 }
869 out
870 }
871
872 const BORDER: usize = 32;
873 const STRIDE: usize = 104; // 40 visible + 2 * 32 border
874 const VIS_W: usize = 40; // 3 MB columns, last one partial
875 const VIS_H: usize = 36; // 3 MB rows, last one partial
876 const ROWS: usize = VIS_H + 2 * BORDER;
877
878 fn plane() -> Vec<u8> {
879 lcg_plane(0x1234, STRIDE * ROWS)
880 }
881
882 /// Reads visible-image pixel (`vx`, `vy`) out of a bordered plane.
883 fn vis(plane: &[u8], vx: usize, vy: usize) -> u8 {
884 plane[(vy + BORDER) * STRIDE + (vx + BORDER)]
885 }
886
887 #[test]
888 fn extend_plane_replicates_edges_and_corners() {
889 let mut p = plane();
890 // Distinct visible values, sentinel everywhere else.
891 for r in 0..VIS_H {
892 for c in 0..VIS_W {
893 p[(BORDER + r) * STRIDE + BORDER + c] = ((r * 7 + c * 3) % 251 + 4) as u8;
894 }
895 }
896 p[..BORDER * STRIDE].fill(0xEE);
897 p[(BORDER + VIS_H) * STRIDE..].fill(0xEE);
898 for r in 0..VIS_H {
899 let row = &mut p[(BORDER + r) * STRIDE..(BORDER + r) * STRIDE + STRIDE];
900 row[..BORDER].fill(0xEE);
901 row[BORDER + VIS_W..].fill(0xEE);
902 }
903
904 extend_plane(&mut p, STRIDE, VIS_W, VIS_H, BORDER);
905
906 // Every sample of the bordered plane equals the nearest in-image sample.
907 for r in 0..ROWS {
908 for c in 0..STRIDE {
909 let vr = r.saturating_sub(BORDER).min(VIS_H - 1);
910 let vc = c.saturating_sub(BORDER).min(VIS_W - 1);
911 assert_eq!(p[r * STRIDE + c], vis(&p, vc, vr), "sample ({r},{c})");
912 }
913 }
914 // Explicit corners (worst case of the rule above).
915 assert_eq!(p[0], vis(&p, 0, 0)); // top-left
916 assert_eq!(p[line_len() - 1], vis(&p, VIS_W - 1, 0)); // top-right
917 assert_eq!(p[(ROWS - 1) * STRIDE], vis(&p, 0, VIS_H - 1)); // bottom-left
918 assert_eq!(
919 p[ROWS * STRIDE - 1],
920 vis(&p, VIS_W - 1, VIS_H - 1) // bottom-right
921 );
922 // The visible region itself is untouched.
923 for r in 0..VIS_H {
924 for c in 0..VIS_W {
925 assert_eq!(
926 p[(BORDER + r) * STRIDE + BORDER + c],
927 ((r * 7 + c * 3) % 251 + 4) as u8
928 );
929 }
930 }
931 }
932
933 fn line_len() -> usize {
934 BORDER + VIS_W + BORDER
935 }
936
937 #[test]
938 fn integer_mv_predict_is_a_plain_copy() {
939 let p = plane();
940 let mut dst = [0u8; 16 * 16];
941
942 // Whole-pel luma MV (row=16, col=-8) → full-pel offset (x-1, y+2).
943 // mv.0 is the row component, mv.1 the column component. x=y=8 keeps
944 // every read inside the visible region of the unextended plane.
945 predict_luma(
946 &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (16, -8), false, &mut dst, 16, 16, 16,
947 false);
948 for r in 0..16 {
949 for c in 0..16 {
950 assert_eq!(dst[r * 16 + c], vis(&p, 8 - 1 + c, 8 + 2 + r), "({r},{c})");
951 }
952 }
953
954 // Zero MV → identity copy.
955 predict_luma(
956 &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (0, 0), false, &mut dst, 16, 16, 16,
957 false);
958 for r in 0..16 {
959 for c in 0..16 {
960 assert_eq!(dst[r * 16 + c], vis(&p, 8 + c, 8 + r), "({r},{c})");
961 }
962 }
963
964 // Chroma copy path, whole-pel chroma MV (row=-16, col=+8)
965 // → full-pel offset (x+1, y-2).
966 let mut dst8 = [0u8; 8 * 8];
967 predict_chroma(
968 &p, STRIDE, BORDER, VIS_W, VIS_H, 4, 4, (-16, 8), false, &mut dst8, 8, 8, 8,
969 false);
970 for r in 0..8 {
971 for c in 0..8 {
972 assert_eq!(dst8[r * 8 + c], vis(&p, 4 + 1 + c, 4 - 2 + r), "({r},{c})");
973 }
974 }
975 }
976
977 #[test]
978 fn sixtap_pure_horizontal_matches_hand_computed_values() {
979 let p = plane();
980 let mut dst = [0u8; 4 * 4];
981
982 // mv = (0, 4): full-pel start (16, 12), fx = 4, fy = 0.
983 predict_luma(
984 &p, STRIDE, BORDER, VIS_W, VIS_H, 16, 12, (0, 4), false, &mut dst, 4, 4, 4, false,
985 );
986
987 // Hand-computed from vp8_sub_pel_filters[4] = { 3, -16, 77, 77, -16, 3 }
988 // and vp8_sub_pel_filters[0] = { 0, 0, 128, 0, 0, 0 } (vertical is the
989 // exact identity over the clamped horizontal intermediate).
990 // out[0][0]: taps are visible pixels (12, 14..19) = [183, 106, 2, 87, 75, 198]:
991 // 183*3 - 106*16 + 2*77 + 87*77 - 75*16 + 198*3 + 64 = 5164
992 // 5164 >> 7 = 40, already in 0..=255.
993 // out[1][2]: taps (13, 17..22) = [153, 188, 219, 13, 86, 194]:
994 // 153*3 - 188*16 + 219*77 + 13*77 - 86*16 + 194*3 + 64 = 14585
995 // 14585 >> 7 = 113.
996 assert_eq!(dst[0], 40);
997 assert_eq!(dst[6], 113);
998
999 // Full block against the tap-table reference formula.
1000 for r in 0..4 {
1001 for c in 0..4 {
1002 let taps: Vec<i32> = (0..6)
1003 .map(|k| i32::from(vis(&p, 16 + c - 2 + k as usize, 12 + r)))
1004 .collect();
1005 let acc: i32 = taps
1006 .iter()
1007 .zip(SUB_PEL_FILTERS[4])
1008 .map(|(t, f)| t * f)
1009 .sum::<i32>()
1010 + 64;
1011 assert_eq!(
1012 dst[r * 4 + c],
1013 (acc >> 7).clamp(0, 255) as u8,
1014 "out[{r}][{c}] taps={taps:?} acc={acc}"
1015 );
1016 }
1017 }
1018 }
1019
1020 #[test]
1021 fn sixtap_combined_phase_16x16_matches_hand_computed_values() {
1022 let p = plane();
1023 let mut dst = [0u8; 16 * 16];
1024
1025 // mv = (14, 18): full-pel start (10, 9), fx = 2, fy = 6.
1026 predict_luma(
1027 &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (14, 18), false, &mut dst, 16, 16, 16, false,
1028 );
1029
1030 // vp8_sub_pel_filters[2] = { 2, -11, 108, 36, -8, 1 }, each
1031 // intermediate clamped to 0..=255 (e.g. tmp[3][10] taps
1032 // [75, 190, 18, 15, 104, 40], raw dot -184, -184 >> 7 = -2, clamped 0);
1033 // vertical pass with vp8_sub_pel_filters[6] = { 1, -8, 36, 108, -11, 2 }.
1034 //
1035 // out[0][0]: horizontal taps are visible pixels (7, 8..13), giving the
1036 // post-clamp intermediate column h_tmp = [41, 186, 229, 210, 95, 185]:
1037 // 41*1 - 186*8 + 229*36 + 210*108 - 95*11 + 185*2 + 64 = 28866
1038 // 28866 >> 7 = 225, already in 0..=255.
1039 //
1040 // out[5][9]: horizontal taps are visible pixels (11, 15..20),
1041 // h_tmp = [205, 8, 14, 189, 108, 4]:
1042 // 205*1 - 8*8 + 14*36 + 189*108 - 108*11 + 4*2 + 64 = 19941
1043 // 19941 >> 7 = 155.
1044 assert_eq!(dst[0], 225);
1045 assert_eq!(dst[5 * 16 + 9], 155);
1046
1047 // Full block against the two-pass reference formula.
1048 let mut tmp = [0i32; 21 * 16];
1049 for i in 0..21 {
1050 for j in 0..16 {
1051 let acc: i32 = (0..6)
1052 .map(|k| i32::from(vis(&p, 10 - 2 + j + k, 9 - 2 + i)))
1053 .zip(SUB_PEL_FILTERS[2])
1054 .map(|(t, f)| t * f)
1055 .sum::<i32>()
1056 + 64;
1057 tmp[i * 16 + j] = (acc >> 7).clamp(0, 255);
1058 }
1059 }
1060 for r in 0..16 {
1061 for c in 0..16 {
1062 let acc: i32 = (0..6)
1063 .map(|k| tmp[(r + k) * 16 + c])
1064 .zip(SUB_PEL_FILTERS[6])
1065 .map(|(t, f)| t * f)
1066 .sum::<i32>()
1067 + 64;
1068 assert_eq!(
1069 dst[r * 16 + c],
1070 (acc >> 7).clamp(0, 255) as u8,
1071 "out[{r}][{c}]"
1072 );
1073 }
1074 }
1075 }
1076
1077 #[test]
1078 fn bilinear_chroma_matches_hand_computed_values() {
1079 let p = plane();
1080 let mut dst = [0u8; 8 * 8];
1081
1082 // mv = (11, 5): full-pel start (4, 7), fx = 5, fy = 3.
1083 predict_chroma(
1084 &p, STRIDE, BORDER, VIS_W, VIS_H, 4, 6, (11, 5), false, &mut dst, 8, 8, 8, true,
1085 );
1086
1087 // Horizontal taps { 48, 80 } (phase 5), vertical { 80, 48 } (phase 3),
1088 // both passes (dot + 64) >> 7, no clamp (provably in range).
1089 //
1090 // out[0][0]: tmp[0][0] = (160*48 + 96*80 + 64) >> 7 = 120 from visible
1091 // pixels (4,7),(5,7); tmp[1][0] = (107*48 + 42*80 + 64) >> 7 = 66
1092 // from (4,8),(5,8).
1093 // 120*80 + 66*48 + 64 = 12832, 12832 >> 7 = 100.
1094 // out[3][7]: tmp[3][7] = 84, tmp[4][7] = 189;
1095 // 84*80 + 189*48 + 64 = 15856, 15856 >> 7 = 123.
1096 assert_eq!(dst[0], 100);
1097 assert_eq!(dst[3 * 8 + 7], 123);
1098
1099 // Full block against the two-pass reference formula.
1100 let mut tmp = [0u16; 9 * 8];
1101 for i in 0..9 {
1102 for j in 0..8 {
1103 tmp[i * 8 + j] = ((i32::from(vis(&p, 4 + j, 7 + i)) * 48
1104 + i32::from(vis(&p, 4 + j + 1, 7 + i)) * 80
1105 + 64)
1106 >> 7) as u16;
1107 }
1108 }
1109 for r in 0..8 {
1110 for c in 0..8 {
1111 let acc = i32::from(tmp[r * 8 + c]) * 80 + i32::from(tmp[(r + 1) * 8 + c]) * 48 + 64;
1112 assert_eq!(dst[r * 8 + c], (acc >> 7) as u8, "out[{r}][{c}]");
1113 }
1114 }
1115 }
1116
1117 #[test]
1118 fn umv_border_clamps_match_libvpx_arithmetic() {
1119 let p = plane();
1120 let mut a = [0u8; 16 * 16];
1121 let mut b = [0u8; 16 * 16];
1122
1123 // Single-MB frame (vis 16x16): mb_to_left_edge = mb_to_top_edge = 0,
1124 // mb_to_right_edge = mb_to_bottom_edge = 0.
1125 //
1126 // Luma: mv (-1000, -1000) < 0 - 152 → both components set to -128
1127 // (left - (16 << 3)); prediction must equal an explicit (-128, -128).
1128 predict_luma(
1129 &p, STRIDE, BORDER, 16, 16, 0, 0, (-1000, -1000), true, &mut a, 16, 16, 16,
1130 false);
1131 predict_luma(
1132 &p, STRIDE, BORDER, 16, 16, 0, 0, (-128, -128), false, &mut b, 16, 16, 16,
1133 false);
1134 assert_eq!(a, b);
1135
1136 // Strict threshold: (-152, -152) is NOT clamped (condition is strict
1137 // `<`), (-153, -153) IS clamped to (-128, -128).
1138 predict_luma(
1139 &p, STRIDE, BORDER, 16, 16, 0, 0, (-152, -152), true, &mut a, 16, 16, 16,
1140 false);
1141 predict_luma(
1142 &p, STRIDE, BORDER, 16, 16, 0, 0, (-152, -152), false, &mut b, 16, 16, 16,
1143 false);
1144 assert_eq!(a, b);
1145 predict_luma(
1146 &p, STRIDE, BORDER, 16, 16, 0, 0, (-153, -153), true, &mut a, 16, 16, 16,
1147 false);
1148 predict_luma(
1149 &p, STRIDE, BORDER, 16, 16, 0, 0, (-128, -128), false, &mut b, 16, 16, 16,
1150 false);
1151 assert_eq!(a, b);
1152
1153 // Right/bottom: mv (4000, 4000) > 0 + 144 → set to +128.
1154 predict_luma(
1155 &p, STRIDE, BORDER, 16, 16, 0, 0, (4000, 4000), true, &mut a, 16, 16, 16,
1156 false);
1157 predict_luma(
1158 &p, STRIDE, BORDER, 16, 16, 0, 0, (128, 128), false, &mut b, 16, 16, 16,
1159 false);
1160 assert_eq!(a, b);
1161
1162 // Chroma: 2 * (-2000) < -152 → (-128 >> 1) = -64 per component.
1163 let mut ca = [0u8; 8 * 8];
1164 let mut cb = [0u8; 8 * 8];
1165 predict_chroma(
1166 &p, STRIDE, BORDER, 8, 8, 0, 0, (-2000, -2000), true, &mut ca, 8, 8, 8,
1167 false);
1168 predict_chroma(
1169 &p, STRIDE, BORDER, 8, 8, 0, 0, (-64, -64), false, &mut cb, 8, 8, 8,
1170 false);
1171 assert_eq!(ca, cb);
1172
1173 // Chroma right/bottom: 2 * 2000 > 144 → (128 >> 1) = 64.
1174 predict_chroma(
1175 &p, STRIDE, BORDER, 8, 8, 0, 0, (2000, 2000), true, &mut ca, 8, 8, 8,
1176 false);
1177 predict_chroma(
1178 &p, STRIDE, BORDER, 8, 8, 0, 0, (64, 64), false, &mut cb, 8, 8, 8,
1179 false);
1180 assert_eq!(ca, cb);
1181
1182 // An in-range MV with need_clamp=true must pass through untouched.
1183 predict_luma(
1184 &p, STRIDE, BORDER, 16, 16, 0, 0, (10, -10), true, &mut a, 16, 16, 16, false,
1185 );
1186 predict_luma(
1187 &p, STRIDE, BORDER, 16, 16, 0, 0, (10, -10), false, &mut b, 16, 16, 16, false,
1188 );
1189 assert_eq!(a, b);
1190 }
1191
1192 /// Fills a bordered plane with a 0x00/0xFF checkerboard: maximizes the
1193 /// six-tap dot products' excursions in both directions (negative taps
1194 /// over 0xFF while positive taps sit on 0x00 and vice versa), so the
1195 /// clamp/saturation paths of both implementations are exercised.
1196 fn checkerboard_plane() -> Vec<u8> {
1197 let mut out = vec![0u8; STRIDE * ROWS];
1198 for r in 0..ROWS {
1199 for c in 0..STRIDE {
1200 out[r * STRIDE + c] = if (r + c) & 1 == 0 { 0xFF } else { 0x00 };
1201 }
1202 }
1203 out
1204 }
1205
1206 /// The dispatched six-tap predictor must be lane-for-lane identical to
1207 /// the scalar reference (the libvpx transcription) on every block shape,
1208 /// every phase pair, at both a central and a right/bottom-edge origin
1209 /// where the wide loads reach furthest into the border. On an AVX2 host
1210 /// the dispatch runs the AVX2 kernels; this compares them to the scalar
1211 /// path.
1212 #[test]
1213 fn dispatched_sixtap_matches_the_scalar_reference_everywhere() {
1214 let planes = [plane(), checkerboard_plane()];
1215 let origins = [
1216 (BORDER + 2, BORDER + 3),
1217 (BORDER + VIS_W - 16, BORDER + VIS_H - 16),
1218 ];
1219 for p in &planes {
1220 for &(sx, sy) in &origins {
1221 for bw in [4usize, 8, 16] {
1222 for bh in [4usize, 8, 16] {
1223 // test sweeps every filter phase pair; indexes the filter table
1224 #[allow(clippy::needless_range_loop)]
1225 for fx in 0..8usize {
1226 // test sweeps every filter phase pair; indexes the filter table
1227 #[allow(clippy::needless_range_loop)]
1228 for fy in 0..8usize {
1229 if fx == 0 && fy == 0 {
1230 continue; // whole-pel copy, shared path
1231 }
1232 let mut want = [0u8; 16 * 16];
1233 let mut got = [0u8; 16 * 16];
1234 let mut tmp = [0u8; 21 * 16];
1235 sixtap_h_scalar(
1236 p, STRIDE, sx, sy, &SUB_PEL_FILTERS[fx], &mut tmp, bw, bh + 5,
1237 );
1238 sixtap_v_scalar(&tmp, &SUB_PEL_FILTERS[fy], &mut want, 16, bw, bh);
1239 sixtap_block(p, STRIDE, sx, sy, fx, fy, &mut got, 16, bw, bh);
1240 let n = bh * 16;
1241 assert_eq!(
1242 &got[..n],
1243 &want[..n],
1244 "sixtap bw={bw} bh={bh} fx={fx} fy={fy} origin=({sx},{sy})"
1245 );
1246 }
1247 }
1248 }
1249 }
1250 }
1251 }
1252 }
1253
1254 /// Same gate for the bilinear predictor.
1255 #[test]
1256 fn dispatched_bilinear_matches_the_scalar_reference_everywhere() {
1257 let planes = [plane(), checkerboard_plane()];
1258 let origins = [
1259 (BORDER + 2, BORDER + 3),
1260 (BORDER + VIS_W - 16, BORDER + VIS_H - 16),
1261 ];
1262 for p in &planes {
1263 for &(sx, sy) in &origins {
1264 for bw in [4usize, 8, 16] {
1265 for bh in [4usize, 8, 16] {
1266 // test sweeps every filter phase pair; indexes the filter table
1267 #[allow(clippy::needless_range_loop)]
1268 for fx in 0..8usize {
1269 // test sweeps every filter phase pair; indexes the filter table
1270 #[allow(clippy::needless_range_loop)]
1271 for fy in 0..8usize {
1272 if fx == 0 && fy == 0 {
1273 continue;
1274 }
1275 let mut want = [0u8; 16 * 16];
1276 let mut got = [0u8; 16 * 16];
1277 let mut tmp = [0u8; 17 * 16];
1278 bilinear_h_scalar(
1279 p, STRIDE, sx, sy, &BILINEAR_FILTERS[fx], &mut tmp, bw, bh + 1,
1280 );
1281 bilinear_v_scalar(&tmp, &BILINEAR_FILTERS[fy], &mut want, 16, bw, bh);
1282 bilinear_block(p, STRIDE, sx, sy, fx, fy, &mut got, 16, bw, bh);
1283 for r in 0..bh {
1284 assert_eq!(
1285 got[r * 16..r * 16 + bw],
1286 want[r * 16..r * 16 + bw],
1287 "bilinear bw={bw} bh={bh} fx={fx} fy={fy} origin=({sx},{sy}) row={r}"
1288 );
1289 }
1290 }
1291 }
1292 }
1293 }
1294 }
1295 }
1296 }
1297}