forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

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