Skip to main content

oxideav_vp8/
loop_filter.rs

1//! VP8 loop filter per RFC 6386 §15.
2//!
3//! The loop filter is the last stage of frame reconstruction (§15 page
4//! 84): after the predictor and residue have been summed for every
5//! macroblock (§14), the filter is applied to the edges between adjacent
6//! macroblocks and the edges between adjacent subblocks, reducing the
7//! blocking artifacts that arise from the semi-independent coding of
8//! macroblocks and their subblocks. Because filtered output feeds the
9//! prediction of subsequent frames (§15 page 84, *"the results of loop
10//! filtering are used in the prediction of subsequent frames"*), a
11//! conforming decoder must reproduce it bit-for-bit.
12//!
13//! This module implements the parts of §15 that the RFC specifies
14//! **completely in its body**: the per-segment filtering arithmetic
15//! (§15.2 simple filter, §15.3 normal filter) and the derivation of the
16//! threshold/limit control parameters from `loop_filter_level` and
17//! `sharpness_level` (§15.4). Every filter routine operates on a single
18//! "segment" — the small run of pixels (length 2, 4, 6, or 8)
19//! symmetrically straddling one edge position — exactly as the spec's
20//! reference routines do, so the routines are agnostic to whether the
21//! edge is horizontal or vertical: the caller gathers the segment into
22//! a contiguous array and writes it back.
23//!
24//! # What is in scope (§15 body)
25//!
26//! * **§15.2 helpers** — the saturating clamp `c` (`clamp_s8`), the
27//!   signed/unsigned pixel conversions `u2s` / `s2u`, and the
28//!   `common_adjust` core adjustment shared by both filter types.
29//! * **§15.2 simple filter** — `simple_segment`, the 4-pixel filter
30//!   gated by an `edge_limit`. The spec notes the simple filter only
31//!   applies to luma edges; chroma edges are left unfiltered (§15.2
32//!   page 88).
33//! * **§15.3 normal filter** — the `filter_yes` enable test, the `hev`
34//!   high-edge-variance test, `subblock_filter` (the inter-subblock
35//!   variant), and `mb_filter` (the wider inter-macroblock variant
36//!   spelled `MBfilter` in the RFC).
37//! * **§15.4 control parameters** — [`LoopFilterParams::derive`], which
38//!   computes `interior_limit`, `hev_threshold`, `mbedge_limit`, and
39//!   `sub_bedge_limit` from a per-macroblock `loop_filter_level`, the
40//!   frame `sharpness_level`, and the key-frame flag.
41//!
42//! # §15.1 frame geometry (also in this module)
43//!
44//! * The §15.1 macroblock-by-macroblock filter *geometry* —
45//!   [`filter_frame`] walks the reconstructed [`crate::KeyframePlanes`]
46//!   in raster order, gathers the 16 luma / 8 chroma segments straddling
47//!   each of the four edges per macroblock, honours the order of the four
48//!   filtering steps, and applies the §15.1 page 86 skip rule (steps 2
49//!   and 4 skipped when the macroblock is neither `B_PRED` nor `SPLITMV`
50//!   and has no coded coefficient) plus the §15 page 84 level-0 whole-MB
51//!   skip. It calls the per-segment primitives above.
52//! * The §9.4 / §10 derivation of the per-macroblock `loop_filter_level`
53//!   itself — [`calculate_mb_filter_level`] implements the §20.6
54//!   `calculate_filter_parameters` body (segment override + the
55//!   reference-frame / prediction-mode deltas).
56//!   [`LoopFilterParams::derive`] still takes an already-resolved level
57//!   for callers wanting just the §15.4 limit derivation;
58//!   [`FrameFilterConfig::keyframe`] resolves the level inputs from a
59//!   [`crate::Vp8CodedHeader`].
60
61/// The §15.4 control parameters for one filtering pass over a
62/// macroblock, derived from a resolved (post-override) per-macroblock
63/// `loop_filter_level`, the frame-constant `sharpness_level`, and the
64/// key-frame flag.
65///
66/// All four fields are unsigned 8-bit limits as the spec defines them.
67/// The two edge limits differ for inter-macroblock vs. inter-subblock
68/// edges; `interior_limit` and `hev_threshold` are the same for all
69/// edge types within the macroblock.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct LoopFilterParams {
72    /// §15.4 `interior_limit` — limit on differences between adjacent
73    /// interior pixels of a segment (used only by the normal filter).
74    pub interior_limit: u8,
75    /// §15.4 `hev_threshold` — the high-edge-variance threshold (used
76    /// only by the normal filter).
77    pub hev_threshold: u8,
78    /// §15.4 `mbedge_limit` — the edge limit applied to inter-macroblock
79    /// edges (used by both filters).
80    pub mbedge_limit: u8,
81    /// §15.4 `sub_bedge_limit` — the edge limit applied to
82    /// inter-subblock edges (used by both filters).
83    pub sub_bedge_limit: u8,
84}
85
86impl LoopFilterParams {
87    /// Derive the §15.4 control parameters.
88    ///
89    /// `loop_filter_level` is the resolved per-macroblock level (§9.4 /
90    /// §10 overrides already applied by the caller), in the range
91    /// `0..=63`. `sharpness_level` is the frame-constant 3-bit value
92    /// (`0..=7`). `key_frame` selects the §15.4 page 96 key-frame vs.
93    /// interframe `hev_threshold` ladder.
94    ///
95    /// Note (§15 page 84): the caller must *skip* filtering entirely
96    /// when `loop_filter_level == 0`; this function still returns a
97    /// (degenerate) parameter set in that case rather than panicking, so
98    /// the skip decision stays the caller's responsibility.
99    pub fn derive(loop_filter_level: u8, sharpness_level: u8, key_frame: bool) -> Self {
100        // §15.4: interior_limit derivation.
101        let mut interior_limit = loop_filter_level;
102        if sharpness_level != 0 {
103            interior_limit >>= if sharpness_level > 4 { 2 } else { 1 };
104            let cap = 9u8.saturating_sub(sharpness_level);
105            if interior_limit > cap {
106                interior_limit = cap;
107            }
108        }
109        if interior_limit == 0 {
110            interior_limit = 1;
111        }
112
113        // §15.4: hev_threshold derivation (key frame vs. interframe).
114        let hev_threshold = if key_frame {
115            if loop_filter_level >= 40 {
116                2
117            } else if loop_filter_level >= 15 {
118                1
119            } else {
120                0
121            }
122        } else if loop_filter_level >= 40 {
123            3
124        } else if loop_filter_level >= 20 {
125            2
126        } else if loop_filter_level >= 15 {
127            1
128        } else {
129            0
130        };
131
132        // §15.4: edge limits. Both arithmetics are performed in a wider
133        // type and saturated into u8 — for the maximum legal inputs
134        // (`loop_filter_level = 63`, `interior_limit = 63`) the
135        // mbedge_limit reaches `(63 + 2) * 2 + 63 = 193`, well inside
136        // u8, but saturating is defensive against malformed levels.
137        let mbedge_limit =
138            (((loop_filter_level as u16 + 2) * 2) + interior_limit as u16).min(255) as u8;
139        let sub_bedge_limit =
140            ((loop_filter_level as u16 * 2) + interior_limit as u16).min(255) as u8;
141
142        LoopFilterParams {
143            interior_limit,
144            hev_threshold,
145            mbedge_limit,
146            sub_bedge_limit,
147        }
148    }
149}
150
151/// §15.2 `c` — clamp an integer to the signed 8-bit range
152/// `-128..=127`.
153///
154/// The spec's `int8 c(int v)` returns `v < -128 ? -128 : (v < 128 ? v :
155/// 127)`.
156#[inline]
157pub fn clamp_s8(v: i32) -> i8 {
158    if v < -128 {
159        -128
160    } else if v < 128 {
161        v as i8
162    } else {
163        127
164    }
165}
166
167/// §15.2 `u2s` — convert an unsigned pixel `0..=255` to a signed 8-bit
168/// number (`v - 128`), interpreted as `i8`.
169#[inline]
170pub fn u2s(v: u8) -> i8 {
171    (v as i16 - 128) as i8
172}
173
174/// §15.2 `s2u` — clamp a signed value with [`clamp_s8`], then convert
175/// back to an unsigned pixel by adding 128.
176#[inline]
177pub fn s2u(v: i32) -> u8 {
178    (clamp_s8(v) as i16 + 128) as u8
179}
180
181/// §15.2 `abs` for pixel differences (`-255..=255`).
182#[inline]
183fn abs_i(v: i32) -> i32 {
184    v.abs()
185}
186
187/// §15.2 `common_adjust` — the core edge adjustment shared by both
188/// filter types.
189///
190/// Operates in-place on a 4-pixel window `[p1, p0, q0, q1]` (indices
191/// `0..=3` of `seg`), where `p0`/`q0` straddle the edge. When
192/// `use_outer_taps` is true the outer taps `p1`/`q1` participate (a
193/// 4-tap filter); when false they do not (a 2-tap filter). Returns the
194/// signed adjustment `a` applied to `q0` (the subblock filter uses it).
195///
196/// The spec passes the four pixels as separate pointers `P1, P0, Q0,
197/// Q1`; here they are the first four entries of the shared segment
198/// buffer so the normal-filter routines can index further out.
199#[inline]
200pub fn common_adjust(use_outer_taps: bool, seg: &mut [u8], base: usize) -> i32 {
201    let p1 = u2s(seg[base]) as i32;
202    let p0 = u2s(seg[base + 1]) as i32;
203    let q0 = u2s(seg[base + 2]) as i32;
204    let q1 = u2s(seg[base + 3]) as i32;
205
206    // §15.2: a = c((use_outer_taps? c(p1 - q1) : 0) + 3*(q0 - p0)).
207    let outer = if use_outer_taps {
208        clamp_s8(p1 - q1) as i32
209    } else {
210        0
211    };
212    let a = clamp_s8(outer + 3 * (q0 - p0)) as i32;
213
214    // §15.2: b balances the rounding of a/8 when the fractional part is
215    // exactly 1/2; b = c(a + 3) >> 3.
216    let b = (clamp_s8(a + 3) as i32) >> 3;
217
218    // §15.2: a = c(a + 4) >> 3 — divide by 8 rounding up at the half.
219    let a = (clamp_s8(a + 4) as i32) >> 3;
220
221    // §15.2: Q0 = s2u(q0 - a); P0 = s2u(p0 + b).
222    seg[base + 2] = s2u(q0 - a);
223    seg[base + 1] = s2u(p0 + b);
224
225    a
226}
227
228/// §15.2 `simple_segment` — the simple loop filter applied to one
229/// 4-pixel window `[p1, p0, q0, q1]` at `seg[base..base + 4]`.
230///
231/// Does nothing if the §15.2 edge metric `abs(p0 - q0)*2 + abs(p1 -
232/// q1)/2` exceeds `edge_limit`; otherwise runs [`common_adjust`] with
233/// outer taps.
234#[inline]
235pub fn simple_segment(edge_limit: u8, seg: &mut [u8], base: usize) {
236    let p1 = seg[base] as i32;
237    let p0 = seg[base + 1] as i32;
238    let q0 = seg[base + 2] as i32;
239    let q1 = seg[base + 3] as i32;
240    if (abs_i(p0 - q0) * 2 + abs_i(p1 - q1) / 2) <= edge_limit as i32 {
241        common_adjust(true, seg, base);
242    }
243}
244
245/// §15.3 `filter_yes` — the normal-filter enable test over an 8-pixel
246/// segment `p3 p2 p1 p0 | q0 q1 q2 q3` (signed values).
247///
248/// Filtering proceeds only if the edge metric is within `e` AND every
249/// adjacent interior difference is within `i`.
250#[inline]
251#[allow(clippy::too_many_arguments)]
252fn filter_yes(
253    i: u8,
254    e: u8,
255    p3: i32,
256    p2: i32,
257    p1: i32,
258    p0: i32,
259    q0: i32,
260    q1: i32,
261    q2: i32,
262    q3: i32,
263) -> bool {
264    let i = i as i32;
265    let e = e as i32;
266    (abs_i(p0 - q0) * 2 + abs_i(p1 - q1) / 2) <= e
267        && abs_i(p3 - p2) <= i
268        && abs_i(p2 - p1) <= i
269        && abs_i(p1 - p0) <= i
270        && abs_i(q3 - q2) <= i
271        && abs_i(q2 - q1) <= i
272        && abs_i(q1 - q0) <= i
273}
274
275/// §15.3 `hev` — the high-edge-variance test over the 4 pixels nearest
276/// the edge (signed values).
277#[inline]
278fn hev(threshold: u8, p1: i32, p0: i32, q0: i32, q1: i32) -> bool {
279    let t = threshold as i32;
280    abs_i(p1 - p0) > t || abs_i(q1 - q0) > t
281}
282
283/// §15.3 `subblock_filter` — the normal inter-subblock filter over an
284/// 8-pixel segment `[p3, p2, p1, p0, q0, q1, q2, q3]` at
285/// `seg[base..base + 8]`.
286///
287/// If [`filter_yes`] passes, [`common_adjust`] is applied to the inner
288/// 4-pixel window with the outer taps gated by [`hev`]; when edge
289/// variance is *low* the two pixels one step in (`p1`, `q1`) are
290/// additionally adjusted by roughly half the edge adjustment.
291#[inline]
292pub fn subblock_filter(
293    hev_threshold: u8,
294    interior_limit: u8,
295    edge_limit: u8,
296    seg: &mut [u8],
297    base: usize,
298) {
299    let p3 = u2s(seg[base]) as i32;
300    let p2 = u2s(seg[base + 1]) as i32;
301    let p1 = u2s(seg[base + 2]) as i32;
302    let p0 = u2s(seg[base + 3]) as i32;
303    let q0 = u2s(seg[base + 4]) as i32;
304    let q1 = u2s(seg[base + 5]) as i32;
305    let q2 = u2s(seg[base + 6]) as i32;
306    let q3 = u2s(seg[base + 7]) as i32;
307
308    if filter_yes(interior_limit, edge_limit, p3, p2, p1, p0, q0, q1, q2, q3) {
309        let hv = hev(hev_threshold, p1, p0, q0, q1);
310        // common_adjust operates on the inner window p1 p0 q0 q1 =
311        // seg[base + 2 ..= base + 5].
312        let a = (common_adjust(hv, seg, base + 2) + 1) >> 1;
313        if !hv {
314            // §15.3: Q1 = s2u(q1 - a); P1 = s2u(p1 + a).
315            seg[base + 5] = s2u(q1 - a);
316            seg[base + 2] = s2u(p1 + a);
317        }
318    }
319}
320
321/// §15.3 `MBfilter` — the normal inter-macroblock filter over an
322/// 8-pixel segment `[p3, p2, p1, p0, q0, q1, q2, q3]` at
323/// `seg[base..base + 8]`.
324///
325/// If [`filter_yes`] passes and edge variance is *low*, the wider
326/// adjustment is applied: six pixels symmetric about the edge are
327/// modified with decaying magnitude (3/7, 2/7, 1/7 of the edge
328/// difference). If edge variance is *high*, the simple [`common_adjust`]
329/// (outer taps) is used instead.
330#[inline]
331pub fn mb_filter(
332    hev_threshold: u8,
333    interior_limit: u8,
334    edge_limit: u8,
335    seg: &mut [u8],
336    base: usize,
337) {
338    let p3 = u2s(seg[base]) as i32;
339    let p2 = u2s(seg[base + 1]) as i32;
340    let p1 = u2s(seg[base + 2]) as i32;
341    let p0 = u2s(seg[base + 3]) as i32;
342    let q0 = u2s(seg[base + 4]) as i32;
343    let q1 = u2s(seg[base + 5]) as i32;
344    let q2 = u2s(seg[base + 6]) as i32;
345    let q3 = u2s(seg[base + 7]) as i32;
346
347    if filter_yes(interior_limit, edge_limit, p3, p2, p1, p0, q0, q1, q2, q3) {
348        if !hev(hev_threshold, p1, p0, q0, q1) {
349            // §15.3: w = c(c(p1 - q1) + 3*(q0 - p0)).
350            let w = clamp_s8(clamp_s8(p1 - q1) as i32 + 3 * (q0 - p0)) as i32;
351
352            // §15.3: a = c((27*w + 63) >> 7); Q0 -= a; P0 += a.
353            let a = clamp_s8((27 * w + 63) >> 7) as i32;
354            seg[base + 4] = s2u(q0 - a);
355            seg[base + 3] = s2u(p0 + a);
356
357            // §15.3: a = c((18*w + 63) >> 7); Q1 -= a; P1 += a.
358            let a = clamp_s8((18 * w + 63) >> 7) as i32;
359            seg[base + 5] = s2u(q1 - a);
360            seg[base + 2] = s2u(p1 + a);
361
362            // §15.3: a = c((9*w + 63) >> 7); Q2 -= a; P2 += a.
363            let a = clamp_s8((9 * w + 63) >> 7) as i32;
364            seg[base + 6] = s2u(q2 - a);
365            seg[base + 1] = s2u(p2 + a);
366        } else {
367            // §15.3: if hev, do the simple filter on the inner window.
368            common_adjust(true, seg, base + 2);
369        }
370    }
371}
372
373// ===================================================================
374// §15.3 normal filter — whole edge run at once (stable toolchains)
375// ===================================================================
376//
377// The frame pass fires the §15.3 kernels once per pixel position along
378// a 16- or 8-pixel edge run, and those positions are independent: each
379// reads and writes only its own 8-tap window. [`normal_filter_run`]
380// therefore takes the whole run as eight tap arrays (`taps[k][n]` is tap
381// `k` of position `n`, already in the signed `u2s` domain) and evaluates
382// the listing's arithmetic for every position without a data-dependent
383// branch: both outcomes of the `filter_yes` / `hev` tests are computed
384// and the result is selected per position. Each position goes through
385// the same add / clamp / shift sequence [`mb_filter`] /
386// [`subblock_filter`] run for it, in 16-bit arithmetic (every
387// intermediate is bounded by `27·127 + 63`), so the selected output is
388// the scalar output bit for bit — `normal_filter_run_matches_scalar`
389// checks random and extreme windows across the parameter range. Written
390// over fixed-size arrays so the compiler can lay the positions out
391// across vector lanes.
392
393/// Saturate to the signed 8-bit range (the listing's `c()`), in 16-bit.
394#[cfg_attr(feature = "simd", allow(dead_code))]
395#[inline(always)]
396fn clamp_s8_i16(v: i16) -> i16 {
397    v.clamp(-128, 127)
398}
399
400/// Apply the §15.3 macroblock-edge (`mb_edge`) or sub-block-edge filter
401/// to `N` independent 8-tap windows held as signed tap arrays
402/// (`taps[0]` = `p3` … `taps[7]` = `q3`).
403// `n` walks one position across the eight parallel tap arrays.
404#[allow(clippy::needless_range_loop)]
405#[cfg_attr(feature = "simd", allow(dead_code))]
406#[inline(always)]
407fn normal_filter_run<const N: usize>(
408    taps: &mut [[i16; N]; 8],
409    hev_threshold: u8,
410    interior_limit: u8,
411    edge_limit: u8,
412    mb_edge: bool,
413) {
414    let (thresh, interior, edge) = (
415        hev_threshold as i16,
416        interior_limit as i16,
417        edge_limit as i16,
418    );
419    for n in 0..N {
420        let (p3, p2, p1, p0) = (taps[0][n], taps[1][n], taps[2][n], taps[3][n]);
421        let (q0, q1, q2, q3) = (taps[4][n], taps[5][n], taps[6][n], taps[7][n]);
422        let yes = (((p0 - q0).abs() * 2 + (p1 - q1).abs() / 2) <= edge)
423            & ((p3 - p2).abs() <= interior)
424            & ((p2 - p1).abs() <= interior)
425            & ((p1 - p0).abs() <= interior)
426            & ((q3 - q2).abs() <= interior)
427            & ((q2 - q1).abs() <= interior)
428            & ((q1 - q0).abs() <= interior);
429        let hev = ((p1 - p0).abs() > thresh) | ((q1 - q0).abs() > thresh);
430        // `c(c(p1 - q1) + 3*(q0 - p0))`: the macroblock filter's `w` and
431        // `common_adjust`'s `a` with the outer taps in use.
432        let outer = clamp_s8_i16(p1 - q1);
433        let step = 3 * (q0 - p0);
434        let with_outer = clamp_s8_i16(outer + step);
435        // `common_adjust`'s two rounded eighths of `a`.
436        let adjust = |a: i16| (clamp_s8_i16(a + 4) >> 3, clamp_s8_i16(a + 3) >> 3);
437        let (np2, np1, np0, nq0, nq1, nq2) = if mb_edge {
438            // No high edge variance: the three-tap-pair wide filter.
439            let w = with_outer;
440            let a0 = clamp_s8_i16((27 * w + 63) >> 7);
441            let a1 = clamp_s8_i16((18 * w + 63) >> 7);
442            let a2 = clamp_s8_i16((9 * w + 63) >> 7);
443            // High edge variance: `common_adjust(true)` on the inner pair.
444            let (a, b) = adjust(with_outer);
445            if hev {
446                (p2, p1, clamp_s8_i16(p0 + b), clamp_s8_i16(q0 - a), q1, q2)
447            } else {
448                (
449                    clamp_s8_i16(p2 + a2),
450                    clamp_s8_i16(p1 + a1),
451                    clamp_s8_i16(p0 + a0),
452                    clamp_s8_i16(q0 - a0),
453                    clamp_s8_i16(q1 - a1),
454                    clamp_s8_i16(q2 - a2),
455                )
456            }
457        } else {
458            // `common_adjust(hev)`: the outer taps count only under high
459            // edge variance; without it the outer pair moves by half.
460            let (a, b) = adjust(if hev { with_outer } else { clamp_s8_i16(step) });
461            let half = (a + 1) >> 1;
462            let (np1, nq1) = if hev {
463                (p1, q1)
464            } else {
465                (clamp_s8_i16(p1 + half), clamp_s8_i16(q1 - half))
466            };
467            (p2, np1, clamp_s8_i16(p0 + b), clamp_s8_i16(q0 - a), nq1, q2)
468        };
469        taps[1][n] = if yes { np2 } else { p2 };
470        taps[2][n] = if yes { np1 } else { p1 };
471        taps[3][n] = if yes { np0 } else { p0 };
472        taps[4][n] = if yes { nq0 } else { q0 };
473        taps[5][n] = if yes { nq1 } else { q1 };
474        taps[6][n] = if yes { nq2 } else { q2 };
475    }
476}
477
478/// [`filter_v_edge_normal`] for an `N`-row run through
479/// [`normal_filter_run`]: position `n` is row `y0 + n`, whose eight taps
480/// are the contiguous bytes `x - 4 .. x + 4`.
481// `n` walks one position across the eight parallel tap arrays.
482#[allow(clippy::needless_range_loop)]
483#[cfg(not(feature = "simd"))]
484#[inline(always)]
485fn filter_v_edge_normal_run<const N: usize>(
486    plane: &mut [u8],
487    stride: usize,
488    x: usize,
489    y0: usize,
490    params: &LoopFilterParams,
491    edge_limit: u8,
492    mb_edge: bool,
493) {
494    let mut taps = [[0i16; N]; 8];
495    for n in 0..N {
496        let row = (y0 + n) * stride + x - 4;
497        let window: &[u8; 8] = plane[row..row + 8].try_into().expect("8 taps");
498        for (k, tap) in taps.iter_mut().enumerate() {
499            tap[n] = window[k] as i16 - 128;
500        }
501    }
502    normal_filter_run(
503        &mut taps,
504        params.hev_threshold,
505        params.interior_limit,
506        edge_limit,
507        mb_edge,
508    );
509    for n in 0..N {
510        let row = (y0 + n) * stride + x - 4;
511        let window: &mut [u8; 8] = (&mut plane[row..row + 8]).try_into().expect("8 taps");
512        for k in 1..7 {
513            window[k] = (taps[k][n] + 128) as u8;
514        }
515    }
516}
517
518/// [`filter_h_edge_normal`] for an `N`-column run through
519/// [`normal_filter_run`]: tap `k` of every position is the contiguous
520/// run of `N` bytes on row `y - 4 + k`.
521// `n` walks one position across the eight parallel tap arrays.
522#[allow(clippy::needless_range_loop)]
523#[cfg(not(feature = "simd"))]
524#[inline(always)]
525fn filter_h_edge_normal_run<const N: usize>(
526    plane: &mut [u8],
527    stride: usize,
528    y: usize,
529    x0: usize,
530    params: &LoopFilterParams,
531    edge_limit: u8,
532    mb_edge: bool,
533) {
534    let mut taps = [[0i16; N]; 8];
535    for (k, tap) in taps.iter_mut().enumerate() {
536        let start = (y - 4 + k) * stride + x0;
537        let row: &[u8; N] = plane[start..start + N].try_into().expect("N columns");
538        for n in 0..N {
539            tap[n] = row[n] as i16 - 128;
540        }
541    }
542    normal_filter_run(
543        &mut taps,
544        params.hev_threshold,
545        params.interior_limit,
546        edge_limit,
547        mb_edge,
548    );
549    for (k, tap) in taps.iter().enumerate().take(7).skip(1) {
550        let start = (y - 4 + k) * stride + x0;
551        let row: &mut [u8; N] = (&mut plane[start..start + N])
552            .try_into()
553            .expect("N columns");
554        for n in 0..N {
555            row[n] = (tap[n] + 128) as u8;
556        }
557    }
558}
559
560// ===================================================================
561// §15.2 / §15.3 SIMD filter kernels (4 segments at once)
562// ===================================================================
563//
564// The §15 per-segment kernels above operate on one edge-straddling
565// pixel run at a time. The frame-geometry pass below fires them once
566// per row (vertical edge) or per column (horizontal edge) of a 16- or
567// 8-pixel edge run. Those rows / columns are fully independent: each
568// gathers its own 8-pixel window from a distinct stride row (vertical
569// edge) or distinct column (horizontal edge), and the §15.2 / §15.3
570// arithmetic on one window never reads another. That independence maps
571// directly onto a 4-lane `core::simd::Simd<i32, 4>` where lane `r`
572// holds segment `r`'s value at a given tap position.
573//
574// To stay byte-exact with the scalar kernels — which early-out per
575// segment when the §15.3 `filter_yes` gate (or the §15.2 edge metric)
576// fails — the SIMD path computes the filtered result for all four lanes
577// unconditionally and then, per lane, selects between the filtered and
578// the original pixel with a `Mask` derived from the same gate. Every
579// lane therefore performs the identical i32 add/clamp/shift sequence
580// the scalar code performs, so the selected output is bit-for-bit the
581// scalar output. No external SIMD layout reference was consulted; the
582// 4-lane layout follows directly from the §15.1 geometry (independent
583// rows / columns) and the §15.2 / §15.3 listings in RFC 6386.
584
585/// Lane-wise §15.2 saturating clamp `c` over a `Simd<i32, 4>` — the
586/// vector form of [`clamp_s8`]: clamp each lane to `-128..=127`.
587#[cfg(feature = "simd")]
588#[inline]
589fn clamp_s8_v(v: core::simd::Simd<i32, 4>) -> core::simd::Simd<i32, 4> {
590    use core::simd::Simd;
591    use core::simd::cmp::SimdOrd;
592    v.simd_clamp(Simd::splat(-128), Simd::splat(127))
593}
594
595/// Lane-wise absolute value over a `Simd<i32, 4>` (the vector form of
596/// [`abs_i`]).
597#[cfg(feature = "simd")]
598#[inline]
599fn abs_v(v: core::simd::Simd<i32, 4>) -> core::simd::Simd<i32, 4> {
600    use core::simd::num::SimdInt;
601    v.abs()
602}
603
604/// Lane-wise §15.2 `common_adjust` shared by both filter types, the
605/// 4-segment vector form of [`common_adjust`].
606///
607/// `p1..q1` are the four inner taps (each lane a distinct segment). The
608/// `q0` / `p0` lanes are updated in place to the filtered values and the
609/// returned `a` matches the scalar return (the subblock filter consumes
610/// it). Bit-for-bit identical to the scalar path on every lane.
611#[cfg(feature = "simd")]
612#[inline]
613fn common_adjust_v(
614    use_outer_taps: bool,
615    p1: core::simd::Simd<i32, 4>,
616    p0: &mut core::simd::Simd<i32, 4>,
617    q0: &mut core::simd::Simd<i32, 4>,
618    q1: core::simd::Simd<i32, 4>,
619) -> core::simd::Simd<i32, 4> {
620    use core::simd::Simd;
621    let outer = if use_outer_taps {
622        clamp_s8_v(p1 - q1)
623    } else {
624        Simd::splat(0)
625    };
626    let a = clamp_s8_v(outer + Simd::splat(3) * (*q0 - *p0));
627    // `b = c(a + 3) >> 3`; `a = c(a + 4) >> 3` — arithmetic right shift,
628    // matching the scalar `>> 3` on i32.
629    let b = clamp_s8_v(a + Simd::splat(3)) >> Simd::splat(3);
630    let a = clamp_s8_v(a + Simd::splat(4)) >> Simd::splat(3);
631    *q0 = clamp_s8_v(*q0 - a);
632    *p0 = clamp_s8_v(*p0 + b);
633    a
634}
635
636/// SIMD §15.3 normal-subblock filter over 4 segments at once — the
637/// 4-lane vector form of [`subblock_filter`].
638///
639/// `seg[k]` holds the four lanes' value at tap `k` (`p3..q3` for
640/// `k = 0..8`), each lane already converted to signed (`u2s`) i32. The
641/// filtered taps are written back into `seg` (still signed); the caller
642/// re-adds 128 (`s2u`) when storing. The §15.3 `filter_yes` gate and the
643/// `hev` test are evaluated per lane and used as `Mask`s to select
644/// between the filtered and the unfiltered value, so each lane is
645/// byte-exact with the scalar kernel.
646#[cfg(feature = "simd")]
647fn subblock_filter_v(
648    hev_threshold: u8,
649    interior_limit: u8,
650    edge_limit: u8,
651    seg: &mut [core::simd::Simd<i32, 4>; 8],
652) {
653    use core::simd::Select;
654    use core::simd::Simd;
655    use core::simd::cmp::SimdPartialOrd;
656
657    let i = Simd::splat(interior_limit as i32);
658    let e = Simd::splat(edge_limit as i32);
659    let t = Simd::splat(hev_threshold as i32);
660
661    let p3 = seg[0];
662    let p2 = seg[1];
663    let p1 = seg[2];
664    let p0 = seg[3];
665    let q0 = seg[4];
666    let q1 = seg[5];
667    let q2 = seg[6];
668    let q3 = seg[7];
669
670    // §15.3 `filter_yes`: edge metric within `e` AND every interior
671    // difference within `i` — evaluated lanewise.
672    let edge_metric = abs_v(p0 - q0) * Simd::splat(2) + abs_v(p1 - q1) / Simd::splat(2);
673    let do_filter = edge_metric.simd_le(e)
674        & abs_v(p3 - p2).simd_le(i)
675        & abs_v(p2 - p1).simd_le(i)
676        & abs_v(p1 - p0).simd_le(i)
677        & abs_v(q3 - q2).simd_le(i)
678        & abs_v(q2 - q1).simd_le(i)
679        & abs_v(q1 - q0).simd_le(i);
680
681    // §15.3 `hev`: |p1 - p0| > t || |q1 - q0| > t, lanewise.
682    let hv = abs_v(p1 - p0).simd_gt(t) | abs_v(q1 - q0).simd_gt(t);
683
684    // Apply `common_adjust` with outer taps gated by the per-lane hev:
685    // compute both the outer-tap and no-outer-tap result, then select.
686    let mut p0_outer = p0;
687    let mut q0_outer = q0;
688    let _ = common_adjust_v(true, p1, &mut p0_outer, &mut q0_outer, q1);
689    let mut p0_inner = p0;
690    let mut q0_inner = q0;
691    let a_inner = common_adjust_v(false, p1, &mut p0_inner, &mut q0_inner, q1);
692
693    let new_p0 = hv.select(p0_outer, p0_inner);
694    let new_q0 = hv.select(q0_outer, q0_inner);
695    // `a = (common_adjust(..) + 1) >> 1` — only the low-hev branch uses
696    // it (no-outer-taps adjust).
697    let a = (a_inner + Simd::splat(1)) >> Simd::splat(1);
698    // When hev is low, p1/q1 are additionally nudged by `a`.
699    let new_p1 = (!hv).select(clamp_s8_v(p1 + a), p1);
700    let new_q1 = (!hv).select(clamp_s8_v(q1 - a), q1);
701
702    // Select between filtered and original per the `filter_yes` gate.
703    seg[2] = do_filter.select(new_p1, p1);
704    seg[3] = do_filter.select(new_p0, p0);
705    seg[4] = do_filter.select(new_q0, q0);
706    seg[5] = do_filter.select(new_q1, q1);
707}
708
709/// SIMD §15.3 normal-macroblock filter over 4 segments at once — the
710/// 4-lane vector form of [`mb_filter`].
711///
712/// Same lane / mask discipline as [`subblock_filter_v`]: byte-exact with
713/// the scalar [`mb_filter`] on every lane.
714#[cfg(feature = "simd")]
715fn mb_filter_v(
716    hev_threshold: u8,
717    interior_limit: u8,
718    edge_limit: u8,
719    seg: &mut [core::simd::Simd<i32, 4>; 8],
720) {
721    use core::simd::Select;
722    use core::simd::Simd;
723    use core::simd::cmp::SimdPartialOrd;
724
725    let i = Simd::splat(interior_limit as i32);
726    let e = Simd::splat(edge_limit as i32);
727    let t = Simd::splat(hev_threshold as i32);
728
729    let p3 = seg[0];
730    let p2 = seg[1];
731    let p1 = seg[2];
732    let p0 = seg[3];
733    let q0 = seg[4];
734    let q1 = seg[5];
735    let q2 = seg[6];
736    let q3 = seg[7];
737
738    let edge_metric = abs_v(p0 - q0) * Simd::splat(2) + abs_v(p1 - q1) / Simd::splat(2);
739    let do_filter = edge_metric.simd_le(e)
740        & abs_v(p3 - p2).simd_le(i)
741        & abs_v(p2 - p1).simd_le(i)
742        & abs_v(p1 - p0).simd_le(i)
743        & abs_v(q3 - q2).simd_le(i)
744        & abs_v(q2 - q1).simd_le(i)
745        & abs_v(q1 - q0).simd_le(i);
746
747    let hv = abs_v(p1 - p0).simd_gt(t) | abs_v(q1 - q0).simd_gt(t);
748
749    // Low-hev wide branch: w = c(c(p1 - q1) + 3*(q0 - p0)).
750    let w = clamp_s8_v(clamp_s8_v(p1 - q1) + Simd::splat(3) * (q0 - p0));
751    // a0 = c((27*w + 63) >> 7): Q0 -= a0; P0 += a0.
752    let a0 = clamp_s8_v((Simd::splat(27) * w + Simd::splat(63)) >> Simd::splat(7));
753    let wide_q0 = s2u_signed_v(q0 - a0);
754    let wide_p0 = s2u_signed_v(p0 + a0);
755    // a1 = c((18*w + 63) >> 7): Q1 -= a1; P1 += a1.
756    let a1 = clamp_s8_v((Simd::splat(18) * w + Simd::splat(63)) >> Simd::splat(7));
757    let wide_q1 = s2u_signed_v(q1 - a1);
758    let wide_p1 = s2u_signed_v(p1 + a1);
759    // a2 = c((9*w + 63) >> 7): Q2 -= a2; P2 += a2.
760    let a2 = clamp_s8_v((Simd::splat(9) * w + Simd::splat(63)) >> Simd::splat(7));
761    let wide_q2 = s2u_signed_v(q2 - a2);
762    let wide_p2 = s2u_signed_v(p2 + a2);
763
764    // High-hev branch: common_adjust(outer taps) on the inner window.
765    let mut p0_hev = p0;
766    let mut q0_hev = q0;
767    common_adjust_v(true, p1, &mut p0_hev, &mut q0_hev, q1);
768
769    // Compose per the per-lane hev, then gate by `filter_yes`.
770    // p2/q2 only move in the low-hev branch.
771    let new_p2 = (!hv).select(wide_p2, p2);
772    let new_q2 = (!hv).select(wide_q2, q2);
773    let new_p1 = (!hv).select(wide_p1, p1);
774    let new_q1 = (!hv).select(wide_q1, q1);
775    let new_p0 = hv.select(p0_hev, wide_p0);
776    let new_q0 = hv.select(q0_hev, wide_q0);
777
778    seg[1] = do_filter.select(new_p2, p2);
779    seg[2] = do_filter.select(new_p1, p1);
780    seg[3] = do_filter.select(new_p0, p0);
781    seg[4] = do_filter.select(new_q0, q0);
782    seg[5] = do_filter.select(new_q1, q1);
783    seg[6] = do_filter.select(new_q2, q2);
784}
785
786/// Lane-wise §15.2 `s2u` that returns the *signed* clamped value
787/// (without the +128) for callers that keep the segment in signed space
788/// and add 128 only when storing — matches `clamp_s8` applied to the
789/// scalar `s2u` argument before its +128.
790#[cfg(feature = "simd")]
791#[inline]
792fn s2u_signed_v(v: core::simd::Simd<i32, 4>) -> core::simd::Simd<i32, 4> {
793    clamp_s8_v(v)
794}
795
796/// SIMD §15.2 simple filter over 4 segments at once — the 4-lane vector
797/// form of [`simple_segment`].
798///
799/// `p1..q1` are the four taps in *unsigned* space (the scalar simple
800/// filter reads the metric on unsigned pixels but adjusts in signed
801/// space via `common_adjust`). Returns the filtered `(p0, q0)` lanes in
802/// unsigned space. Byte-exact with the scalar [`simple_segment`].
803#[cfg(feature = "simd")]
804fn simple_segment_v(
805    edge_limit: u8,
806    p1: core::simd::Simd<i32, 4>,
807    p0: core::simd::Simd<i32, 4>,
808    q0: core::simd::Simd<i32, 4>,
809    q1: core::simd::Simd<i32, 4>,
810) -> (core::simd::Simd<i32, 4>, core::simd::Simd<i32, 4>) {
811    use core::simd::Select;
812    use core::simd::Simd;
813    use core::simd::cmp::SimdPartialOrd;
814
815    let limit = Simd::splat(edge_limit as i32);
816    // §15.2 edge metric on unsigned pixels.
817    let metric = abs_v(p0 - q0) * Simd::splat(2) + abs_v(p1 - q1) / Simd::splat(2);
818    let do_filter = metric.simd_le(limit);
819
820    // common_adjust runs in signed space (u2s = -128).
821    let bias = Simd::splat(128);
822    let p1s = p1 - bias;
823    let q1s = q1 - bias;
824    let mut p0s = p0 - bias;
825    let mut q0s = q0 - bias;
826    common_adjust_v(true, p1s, &mut p0s, &mut q0s, q1s);
827    let new_p0 = p0s + bias;
828    let new_q0 = q0s + bias;
829
830    (do_filter.select(new_p0, p0), do_filter.select(new_q0, q0))
831}
832
833// ===================================================================
834// §15.1 / §15.2 frame loop-filter geometry
835// ===================================================================
836//
837// This section implements the §15.1 "Filter Geometry and Overall
838// Procedure" — the per-frame pass that walks the reconstructed plane
839// buffers in raster-scan order and applies the §15.2 simple or §15.3
840// normal filter kernels above to the edges between adjacent macroblocks
841// and the edges between adjacent subblocks.
842//
843// The arithmetic that derives the per-macroblock filter level from the
844// base `loop_filter_level`, the §10 per-segment override, and the §9.4
845// reference / mode deltas is the §20.6 `calculate_filter_parameters`
846// body of the RFC's reference-decoder annex (`dixie.c`, part of RFC 6386
847// itself). The four-step per-macroblock edge iteration — left
848// inter-MB edge, three internal vertical subblock edges, top inter-MB
849// edge, three internal horizontal subblock edges, with chroma analogues
850// — is the §20.6 `filter_row_normal` / `filter_row_simple` geometry.
851//
852// `LoopFilterParams::derive` above already returns the §15.4 limits in
853// the form the kernels consume: its `mbedge_limit` / `sub_bedge_limit`
854// equal the `2 * E + I` disabling metric the §20.6 `normal_threshold`
855// (and the §20.6 simple `mb_limit` / `b_limit`) compute, so the
856// geometry pass passes those precomputed values straight into
857// `mb_filter` / `subblock_filter` / `simple_segment` as their
858// `edge_limit` argument.
859
860use crate::frame::{KeyframePlanes, MbCoeffs};
861use crate::macroblock::{IntraYMode, MacroblockModes};
862
863mod bands;
864
865/// Number of reference-frame loop-filter deltas (`MAX_REF_LF_DELTAS`,
866/// RFC 6386 §9.4) — one per reference-frame slot.
867pub const MAX_REF_LF_DELTAS: usize = 4;
868/// Number of prediction-mode loop-filter deltas (`MAX_MODE_LF_DELTAS`,
869/// RFC 6386 §9.4).
870pub const MAX_MODE_LF_DELTAS: usize = 4;
871/// Number of segments (`MAX_MB_SEGMENTS`, RFC 6386 §10).
872pub const MAX_MB_SEGMENTS: usize = 4;
873
874/// Frame-constant configuration controlling the §15 loop-filter pass.
875///
876/// Holds the resolved (post-header) state the §20.6
877/// `calculate_filter_parameters` body reads: the base
878/// `loop_filter_level` and `sharpness_level`, the §10 per-segment level
879/// override config, and the §9.4 reference / mode delta config. Build it
880/// with [`FrameFilterConfig::keyframe`] from a parsed
881/// [`crate::Vp8CodedHeader`], or construct directly for unit testing.
882///
883/// On a key frame every macroblock predicts from the current frame, so
884/// of the four §9.4 mode deltas only `mode_delta[0]` (the `B_PRED`
885/// delta) ever applies, and the reference delta is always the
886/// current-frame slot. The geometry pass below therefore models exactly
887/// those two contributions; the remaining inter-frame mode/reference
888/// deltas are reserved for the §16 inter-prediction round.
889#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
890#[non_exhaustive]
891pub struct FrameFilterConfig {
892    /// `filter_type` — `false` selects the §15.3 normal filter, `true`
893    /// the §15.2 simple filter.
894    pub simple: bool,
895    /// Whether the current frame is a key frame (selects the §15.4
896    /// key-frame `hev_threshold` ladder).
897    pub key_frame: bool,
898    /// Base frame `loop_filter_level` (`0..=63`, RFC 6386 §9.4).
899    pub loop_filter_level: u8,
900    /// Frame `sharpness_level` (`0..=7`, RFC 6386 §9.4).
901    pub sharpness_level: u8,
902    /// `segmentation_enabled` (RFC 6386 §9.3) — gates the §10
903    /// per-segment loop-filter override.
904    pub segmentation_enabled: bool,
905    /// `segment_feature_mode` (RFC 6386 §9.3 4.a): `true` = absolute
906    /// (the per-segment value *replaces* the base level), `false` =
907    /// delta (it is *added* to the base level). Only consulted when
908    /// `segmentation_enabled`.
909    pub segment_abs: bool,
910    /// The four §10 per-segment loop-filter levels (absolute values or
911    /// signed deltas per `segment_abs`). Only consulted when
912    /// `segmentation_enabled`.
913    pub segment_lf_level: [i16; MAX_MB_SEGMENTS],
914    /// `loop_filter_adj_enable` (RFC 6386 §9.4) — gates the per-MB
915    /// reference / mode delta adjustment.
916    pub delta_enabled: bool,
917    /// The reference-frame delta applied for the current (intra) frame —
918    /// `ref_delta[CURRENT_FRAME]` in §20.6. Only consulted when
919    /// `delta_enabled`.
920    pub ref_delta_current: i16,
921    /// The `B_PRED` mode delta — `mode_delta[0]` in §20.6. Only
922    /// consulted when `delta_enabled` and the macroblock is `B_PRED`.
923    pub bpred_mode_delta: i16,
924    /// The reference-frame delta applied to inter MBs predicting from
925    /// `LAST` — `ref_delta[LAST_FRAME]` in §20.6. Only consulted by
926    /// the interframe loop-filter path ([`filter_inter_frame`]).
927    pub ref_delta_last: i16,
928    /// The reference-frame delta applied to inter MBs predicting from
929    /// `GOLDEN` — `ref_delta[GOLDEN_FRAME]` in §20.6. Only consulted by
930    /// the interframe loop-filter path.
931    pub ref_delta_golden: i16,
932    /// The reference-frame delta applied to inter MBs predicting from
933    /// `ALTREF` — `ref_delta[ALTREF_FRAME]` in §20.6.
934    pub ref_delta_altref: i16,
935    /// The mode delta applied to inter MBs whose `y_mode` is `ZEROMV` —
936    /// `mode_delta[1]` in §20.6.
937    pub zero_mv_mode_delta: i16,
938    /// The mode delta applied to inter MBs whose `y_mode` is `NEARESTMV`,
939    /// `NEARMV`, or `NEWMV` — `mode_delta[2]` in §20.6.
940    pub other_mv_mode_delta: i16,
941    /// The mode delta applied to inter MBs whose `y_mode` is `SPLITMV` —
942    /// `mode_delta[3]` in §20.6.
943    pub split_mv_mode_delta: i16,
944}
945
946impl FrameFilterConfig {
947    /// Set `simple`.
948    #[must_use]
949    pub fn with_simple(mut self, v: bool) -> Self {
950        self.simple = v;
951        self
952    }
953
954    /// Set `key_frame`.
955    #[must_use]
956    pub fn with_key_frame(mut self, v: bool) -> Self {
957        self.key_frame = v;
958        self
959    }
960
961    /// Set `loop_filter_level`.
962    #[must_use]
963    pub fn with_loop_filter_level(mut self, v: u8) -> Self {
964        self.loop_filter_level = v;
965        self
966    }
967
968    /// Set `sharpness_level`.
969    #[must_use]
970    pub fn with_sharpness_level(mut self, v: u8) -> Self {
971        self.sharpness_level = v;
972        self
973    }
974
975    /// Set `segmentation_enabled`.
976    #[must_use]
977    pub fn with_segmentation_enabled(mut self, v: bool) -> Self {
978        self.segmentation_enabled = v;
979        self
980    }
981
982    /// Set `segment_abs`.
983    #[must_use]
984    pub fn with_segment_abs(mut self, v: bool) -> Self {
985        self.segment_abs = v;
986        self
987    }
988
989    /// Set `segment_lf_level`.
990    #[must_use]
991    pub fn with_segment_lf_level(mut self, v: [i16; MAX_MB_SEGMENTS]) -> Self {
992        self.segment_lf_level = v;
993        self
994    }
995
996    /// Set `delta_enabled`.
997    #[must_use]
998    pub fn with_delta_enabled(mut self, v: bool) -> Self {
999        self.delta_enabled = v;
1000        self
1001    }
1002
1003    /// Set `ref_delta_current`.
1004    #[must_use]
1005    pub fn with_ref_delta_current(mut self, v: i16) -> Self {
1006        self.ref_delta_current = v;
1007        self
1008    }
1009
1010    /// Set `bpred_mode_delta`.
1011    #[must_use]
1012    pub fn with_bpred_mode_delta(mut self, v: i16) -> Self {
1013        self.bpred_mode_delta = v;
1014        self
1015    }
1016
1017    /// Set `ref_delta_last`.
1018    #[must_use]
1019    pub fn with_ref_delta_last(mut self, v: i16) -> Self {
1020        self.ref_delta_last = v;
1021        self
1022    }
1023
1024    /// Set `ref_delta_golden`.
1025    #[must_use]
1026    pub fn with_ref_delta_golden(mut self, v: i16) -> Self {
1027        self.ref_delta_golden = v;
1028        self
1029    }
1030
1031    /// Set `ref_delta_altref`.
1032    #[must_use]
1033    pub fn with_ref_delta_altref(mut self, v: i16) -> Self {
1034        self.ref_delta_altref = v;
1035        self
1036    }
1037
1038    /// Set `zero_mv_mode_delta`.
1039    #[must_use]
1040    pub fn with_zero_mv_mode_delta(mut self, v: i16) -> Self {
1041        self.zero_mv_mode_delta = v;
1042        self
1043    }
1044
1045    /// Set `other_mv_mode_delta`.
1046    #[must_use]
1047    pub fn with_other_mv_mode_delta(mut self, v: i16) -> Self {
1048        self.other_mv_mode_delta = v;
1049        self
1050    }
1051
1052    /// Set `split_mv_mode_delta`.
1053    #[must_use]
1054    pub fn with_split_mv_mode_delta(mut self, v: i16) -> Self {
1055        self.split_mv_mode_delta = v;
1056        self
1057    }
1058}
1059
1060impl FrameFilterConfig {
1061    /// Build the key-frame configuration from a parsed boolean-coded
1062    /// frame header.
1063    ///
1064    /// Resolves the §10 per-segment loop-filter levels from the header's
1065    /// `update_segmentation.loop_filter_update` (a `None` entry means the
1066    /// segment carries level 0 — the §9.3 "value is 0" path) and the
1067    /// §9.4 reference / mode deltas from `mb_lf_adjustments`. Because a
1068    /// key frame has no prior persisted delta state (the §9.4 deltas are
1069    /// "updated for the current frame" and key frames begin a fresh
1070    /// sequence), a `None` update entry resolves to 0.
1071    ///
1072    /// The reference delta used is the current-frame slot
1073    /// (`ref_frame_delta_update[0]`, the `CURRENT_FRAME` reference per
1074    /// §20.6's `ref_delta[CURRENT_FRAME]`) and the only mode delta that
1075    /// applies on a key frame is the `B_PRED` slot
1076    /// (`mb_mode_delta_update[0]`, `mode_delta[0]` in §20.6).
1077    pub fn keyframe(header: &crate::Vp8CodedHeader) -> Self {
1078        let mut segment_lf_level = [0i16; MAX_MB_SEGMENTS];
1079        let mut segment_abs = false;
1080        if header.segmentation_enabled
1081            && let Some(seg) = header.update_segmentation
1082        {
1083            segment_abs = seg.segment_feature_mode_absolute;
1084            for (dst, src) in segment_lf_level
1085                .iter_mut()
1086                .zip(seg.loop_filter_update.iter())
1087            {
1088                *dst = src.unwrap_or(0);
1089            }
1090        }
1091
1092        let lf = &header.mb_lf_adjustments;
1093        let (ref_delta_current, bpred_mode_delta) = if lf.loop_filter_adj_enable {
1094            (
1095                lf.ref_frame_delta_update[0].unwrap_or(0),
1096                lf.mb_mode_delta_update[0].unwrap_or(0),
1097            )
1098        } else {
1099            (0, 0)
1100        };
1101
1102        FrameFilterConfig {
1103            simple: header.filter_type,
1104            key_frame: true,
1105            loop_filter_level: header.loop_filter_level,
1106            sharpness_level: header.sharpness_level,
1107            segmentation_enabled: header.segmentation_enabled,
1108            segment_abs,
1109            segment_lf_level,
1110            delta_enabled: lf.loop_filter_adj_enable,
1111            ref_delta_current,
1112            bpred_mode_delta,
1113            ref_delta_last: 0,
1114            ref_delta_golden: 0,
1115            ref_delta_altref: 0,
1116            zero_mv_mode_delta: 0,
1117            other_mv_mode_delta: 0,
1118            split_mv_mode_delta: 0,
1119        }
1120    }
1121
1122    /// Build the interframe configuration from a parsed boolean-coded
1123    /// frame header and the carried (across-frame) reference / mode delta
1124    /// state.
1125    ///
1126    /// Unlike [`FrameFilterConfig::keyframe`], the §9.4 deltas persist
1127    /// across frames per RFC 6386 §9.4: "the values from the previous
1128    /// frame are used, unless they are updated in the current header."
1129    /// The caller carries `carried_ref_deltas[4]` and `carried_mode_deltas[4]`
1130    /// across frames and asks this constructor to overlay the current
1131    /// frame's `mb_lf_adjustments` updates on top. The four `ref` indices
1132    /// are `{CURRENT=0, LAST=1, GOLDEN=2, ALTREF=3}` and the four `mode`
1133    /// indices are `{B_PRED=0, ZERO_MV=1, NEAREST/NEAR/NEW_MV=2, SPLIT_MV=3}`.
1134    pub fn interframe(
1135        header: &crate::Vp8CodedHeader,
1136        carried_ref_deltas: [i16; 4],
1137        carried_mode_deltas: [i16; 4],
1138    ) -> Self {
1139        let mut segment_lf_level = [0i16; MAX_MB_SEGMENTS];
1140        let mut segment_abs = false;
1141        if header.segmentation_enabled
1142            && let Some(seg) = header.update_segmentation
1143        {
1144            segment_abs = seg.segment_feature_mode_absolute;
1145            for (dst, src) in segment_lf_level
1146                .iter_mut()
1147                .zip(seg.loop_filter_update.iter())
1148            {
1149                *dst = src.unwrap_or(0);
1150            }
1151        }
1152
1153        let lf = &header.mb_lf_adjustments;
1154        let mut ref_deltas = carried_ref_deltas;
1155        let mut mode_deltas = carried_mode_deltas;
1156        if lf.loop_filter_adj_enable {
1157            for (i, slot) in ref_deltas.iter_mut().enumerate() {
1158                if let Some(v) = lf.ref_frame_delta_update[i] {
1159                    *slot = v;
1160                }
1161            }
1162            for (i, slot) in mode_deltas.iter_mut().enumerate() {
1163                if let Some(v) = lf.mb_mode_delta_update[i] {
1164                    *slot = v;
1165                }
1166            }
1167        }
1168
1169        FrameFilterConfig {
1170            simple: header.filter_type,
1171            key_frame: false,
1172            loop_filter_level: header.loop_filter_level,
1173            sharpness_level: header.sharpness_level,
1174            segmentation_enabled: header.segmentation_enabled,
1175            segment_abs,
1176            segment_lf_level,
1177            delta_enabled: lf.loop_filter_adj_enable,
1178            ref_delta_current: ref_deltas[0],
1179            bpred_mode_delta: mode_deltas[0],
1180            ref_delta_last: ref_deltas[1],
1181            ref_delta_golden: ref_deltas[2],
1182            ref_delta_altref: ref_deltas[3],
1183            zero_mv_mode_delta: mode_deltas[1],
1184            other_mv_mode_delta: mode_deltas[2],
1185            split_mv_mode_delta: mode_deltas[3],
1186        }
1187    }
1188
1189    /// Extract the four `[CURRENT, LAST, GOLDEN, ALTREF]` reference deltas
1190    /// from a resolved config, in the order the §20.6 `ref_delta[]` array
1191    /// uses. Used by the across-frame state to carry the deltas to the next
1192    /// frame's [`FrameFilterConfig::interframe`] call.
1193    pub fn ref_deltas(&self) -> [i16; 4] {
1194        [
1195            self.ref_delta_current,
1196            self.ref_delta_last,
1197            self.ref_delta_golden,
1198            self.ref_delta_altref,
1199        ]
1200    }
1201    /// Extract the four `[B_PRED, ZERO_MV, OTHER_MV, SPLIT_MV]` mode deltas.
1202    pub fn mode_deltas(&self) -> [i16; 4] {
1203        [
1204            self.bpred_mode_delta,
1205            self.zero_mv_mode_delta,
1206            self.other_mv_mode_delta,
1207            self.split_mv_mode_delta,
1208        ]
1209    }
1210}
1211
1212/// Resolve the per-macroblock loop-filter level per the §20.6
1213/// `calculate_filter_parameters` body: start from the frame base,
1214/// apply the §10 per-segment override (delta or absolute), clamp to
1215/// `0..=63`, apply the §9.4 reference + mode deltas, then clamp again.
1216///
1217/// `segment_id` is the macroblock's §10 segment (`None` resolves to
1218/// segment 0, the §10 default when the map was not updated). `y_mode`
1219/// selects the §9.4 `B_PRED` mode delta. Returns the resolved level in
1220/// `0..=63`; the caller skips filtering entirely when it is 0 (RFC 6386
1221/// §15 page 84).
1222pub fn calculate_mb_filter_level(
1223    config: &FrameFilterConfig,
1224    segment_id: Option<u8>,
1225    y_mode: IntraYMode,
1226) -> u8 {
1227    // §20.6: filter_level = loopfilter_hdr.level.
1228    let mut level = config.loop_filter_level as i32;
1229
1230    // §20.6 + §10: per-segment override.
1231    if config.segmentation_enabled {
1232        let seg = segment_id.unwrap_or(0) as usize;
1233        let seg = seg.min(MAX_MB_SEGMENTS - 1);
1234        if config.segment_abs {
1235            level = config.segment_lf_level[seg] as i32;
1236        } else {
1237            level += config.segment_lf_level[seg] as i32;
1238        }
1239    }
1240
1241    // §20.6: clamp to 0..=63 after the segment override.
1242    level = level.clamp(0, 63);
1243
1244    // §20.6 + §9.4: reference / mode deltas. On a key frame every MB is
1245    // CURRENT_FRAME, so the reference delta always applies and only the
1246    // B_PRED mode delta participates.
1247    if config.delta_enabled {
1248        level += config.ref_delta_current as i32;
1249        if y_mode == IntraYMode::B {
1250            level += config.bpred_mode_delta as i32;
1251        }
1252    }
1253
1254    // §20.6: clamp to 0..=63 after the deltas.
1255    level.clamp(0, 63) as u8
1256}
1257
1258/// Per-macroblock loop-filter level for an interframe — the §20.6
1259/// `calculate_filter_parameters` body with the full §9.4 reference + mode
1260/// delta branching:
1261///
1262/// * the reference delta is selected by the MB's `ref_frame` (intra =
1263///   `CURRENT_FRAME`, otherwise the LAST / GOLDEN / ALTREF the MB
1264///   predicted from);
1265/// * the mode delta is selected by `(ref_frame, y_mode)`: an intra MB
1266///   only gets the `mode_delta[0]` `B_PRED` contribution; an inter MB
1267///   picks among `mode_delta[1]` (ZEROMV), `mode_delta[3]` (SPLITMV), or
1268///   `mode_delta[2]` (everything else — NEAREST / NEAR / NEW).
1269///
1270/// The mode-bucket-from-y_mode mapping mirrors the [`InterMode`] mapping
1271/// that [`crate::state::Vp8DecoderState`] uses when writing per-MB modes
1272/// into the `modes` slice: SPLITMV macroblocks are recorded with
1273/// `y_mode = B_PRED` (so the §15.1 "filter internal edges" rule fires
1274/// the way the spec wants), other whole-MB inter MBs get
1275/// `y_mode = DC_PRED`. We therefore pass the original `InterMode` (or
1276/// `None` for intra) in here, separate from the `y_mode` the caller
1277/// recorded for the §15 geometry.
1278///
1279/// [`InterMode`]: crate::near_mv::InterMode
1280pub fn calculate_mb_filter_level_inter(
1281    config: &FrameFilterConfig,
1282    segment_id: Option<u8>,
1283    ref_frame: Option<crate::motion_comp::RefFrame>,
1284    inter_mode: Option<crate::near_mv::InterMode>,
1285    y_mode_for_bpred: IntraYMode,
1286) -> u8 {
1287    use crate::motion_comp::RefFrame as RF;
1288    use crate::near_mv::InterMode as IM;
1289
1290    let mut level = config.loop_filter_level as i32;
1291    if config.segmentation_enabled {
1292        let seg = segment_id.unwrap_or(0) as usize;
1293        let seg = seg.min(MAX_MB_SEGMENTS - 1);
1294        if config.segment_abs {
1295            level = config.segment_lf_level[seg] as i32;
1296        } else {
1297            level += config.segment_lf_level[seg] as i32;
1298        }
1299    }
1300    level = level.clamp(0, 63);
1301
1302    if config.delta_enabled {
1303        // §20.6 ref_delta lookup by reference frame.
1304        let ref_delta = match ref_frame {
1305            None => config.ref_delta_current,
1306            Some(RF::Last) => config.ref_delta_last,
1307            Some(RF::Golden) => config.ref_delta_golden,
1308            Some(RF::AltRef) => config.ref_delta_altref,
1309        };
1310        level += ref_delta as i32;
1311        // §20.6 mode_delta lookup. Intra → only B_PRED contributes.
1312        match (ref_frame, inter_mode) {
1313            (None, _) => {
1314                if y_mode_for_bpred == IntraYMode::B {
1315                    level += config.bpred_mode_delta as i32;
1316                }
1317            }
1318            (Some(_), Some(IM::Zero)) => {
1319                level += config.zero_mv_mode_delta as i32;
1320            }
1321            (Some(_), Some(IM::Split)) => {
1322                level += config.split_mv_mode_delta as i32;
1323            }
1324            (Some(_), _) => {
1325                level += config.other_mv_mode_delta as i32;
1326            }
1327        }
1328    }
1329
1330    level.clamp(0, 63) as u8
1331}
1332
1333/// Interframe analogue of [`filter_frame`]: walk the macroblocks in raster
1334/// order applying the §15 / §20.6 filter to each MB's edges, but use
1335/// [`calculate_mb_filter_level_inter`] for the per-MB level so each MB's
1336/// reference frame + inter mode is consulted (the keyframe path was
1337/// limited to the §9.4 CURRENT_FRAME / B_PRED slots).
1338///
1339/// `ref_frames[r]` carries the per-MB ref frame (`None` = intra) in the
1340/// same raster order as `modes` / `coeffs`. `inter_modes[r]` carries the
1341/// §16.2 [`InterMode`] for inter MBs (ignored for intra), in the same
1342/// order. Both must have length `mb_rows * mb_cols`.
1343pub fn filter_inter_frame(
1344    planes: &mut KeyframePlanes,
1345    modes: &[MacroblockModes],
1346    coeffs: &[MbCoeffs],
1347    ref_frames: &[Option<crate::motion_comp::RefFrame>],
1348    inter_modes: &[Option<crate::near_mv::InterMode>],
1349    config: &FrameFilterConfig,
1350) {
1351    // As in `filter_frame`: the §15.1 step-2/4 rule only needs the per-MB
1352    // `mb_has_coeffs` boolean. Collapse the bundles and dispatch to the
1353    // flag-driven core; the public `&[MbCoeffs]` signature is preserved.
1354    let has_coeffs: Vec<bool> = coeffs.iter().map(mb_has_coeffs).collect();
1355    filter_inter_frame_flags(planes, modes, &has_coeffs, ref_frames, inter_modes, config);
1356}
1357
1358/// Flag-driven core of [`filter_inter_frame`] — analogue of
1359/// [`filter_frame_flags`]. `has_coeffs[index]` must equal `mb_has_coeffs` of
1360/// the MB at raster `index`. Byte-for-byte identical to
1361/// [`filter_inter_frame`] (proved by
1362/// `tests::filter_inter_frame_flags_matches_coeffs`).
1363#[allow(clippy::too_many_arguments)]
1364pub(crate) fn filter_inter_frame_flags(
1365    planes: &mut KeyframePlanes,
1366    modes: &[MacroblockModes],
1367    has_coeffs: &[bool],
1368    ref_frames: &[Option<crate::motion_comp::RefFrame>],
1369    inter_modes: &[Option<crate::near_mv::InterMode>],
1370    config: &FrameFilterConfig,
1371) {
1372    let mb_cols = planes.mb_cols;
1373    let mb_rows = planes.mb_rows;
1374    if mb_cols == 0 || mb_rows == 0 {
1375        return;
1376    }
1377    let expected = mb_cols * mb_rows;
1378    if modes.len() != expected
1379        || has_coeffs.len() != expected
1380        || ref_frames.len() != expected
1381        || inter_modes.len() != expected
1382    {
1383        return;
1384    }
1385
1386    let ys = planes.y_stride;
1387    let cs = planes.uv_stride;
1388
1389    for mb_row in 0..mb_rows {
1390        for mb_col in 0..mb_cols {
1391            let index = mb_row * mb_cols + mb_col;
1392            let mb = &modes[index];
1393
1394            let level = calculate_mb_filter_level_inter(
1395                config,
1396                mb.segment_id,
1397                ref_frames[index],
1398                inter_modes[index],
1399                mb.y_mode,
1400            );
1401            if level == 0 {
1402                continue;
1403            }
1404            let params = LoopFilterParams::derive(level, config.sharpness_level, config.key_frame);
1405
1406            // §15.1 page 86 filter_subblocks rule mirrors the keyframe
1407            // pass: B_PRED / SPLITMV (we mapped SPLITMV → y_mode B_PRED
1408            // in the modes record) OR any coded coefficient.
1409            let filter_subblocks = mb.y_mode == IntraYMode::B || has_coeffs[index];
1410
1411            let y_x0 = mb_col * 16;
1412            let y_y0 = mb_row * 16;
1413            let uv_x0 = mb_col * 8;
1414            let uv_y0 = mb_row * 8;
1415
1416            if config.simple {
1417                if mb_col > 0 {
1418                    filter_v_edge_simple(&mut planes.y, ys, y_x0, y_y0, params.mbedge_limit);
1419                }
1420                if filter_subblocks {
1421                    for q in 1..4 {
1422                        filter_v_edge_simple(
1423                            &mut planes.y,
1424                            ys,
1425                            y_x0 + 4 * q,
1426                            y_y0,
1427                            params.sub_bedge_limit,
1428                        );
1429                    }
1430                }
1431                if mb_row > 0 {
1432                    filter_h_edge_simple(&mut planes.y, ys, y_y0, y_x0, params.mbedge_limit);
1433                }
1434                if filter_subblocks {
1435                    for q in 1..4 {
1436                        filter_h_edge_simple(
1437                            &mut planes.y,
1438                            ys,
1439                            y_y0 + 4 * q,
1440                            y_x0,
1441                            params.sub_bedge_limit,
1442                        );
1443                    }
1444                }
1445            } else {
1446                if mb_col > 0 {
1447                    filter_v_edge_normal(&mut planes.y, ys, y_x0, y_y0, 16, &params, true);
1448                    filter_v_edge_normal(&mut planes.u, cs, uv_x0, uv_y0, 8, &params, true);
1449                    filter_v_edge_normal(&mut planes.v, cs, uv_x0, uv_y0, 8, &params, true);
1450                }
1451                if filter_subblocks {
1452                    for q in 1..4 {
1453                        filter_v_edge_normal(
1454                            &mut planes.y,
1455                            ys,
1456                            y_x0 + 4 * q,
1457                            y_y0,
1458                            16,
1459                            &params,
1460                            false,
1461                        );
1462                    }
1463                    filter_v_edge_normal(&mut planes.u, cs, uv_x0 + 4, uv_y0, 8, &params, false);
1464                    filter_v_edge_normal(&mut planes.v, cs, uv_x0 + 4, uv_y0, 8, &params, false);
1465                }
1466                if mb_row > 0 {
1467                    filter_h_edge_normal(&mut planes.y, ys, y_y0, y_x0, 16, &params, true);
1468                    filter_h_edge_normal(&mut planes.u, cs, uv_y0, uv_x0, 8, &params, true);
1469                    filter_h_edge_normal(&mut planes.v, cs, uv_y0, uv_x0, 8, &params, true);
1470                }
1471                if filter_subblocks {
1472                    for q in 1..4 {
1473                        filter_h_edge_normal(
1474                            &mut planes.y,
1475                            ys,
1476                            y_y0 + 4 * q,
1477                            y_x0,
1478                            16,
1479                            &params,
1480                            false,
1481                        );
1482                    }
1483                    filter_h_edge_normal(&mut planes.u, cs, uv_y0 + 4, uv_x0, 8, &params, false);
1484                    filter_h_edge_normal(&mut planes.v, cs, uv_y0 + 4, uv_x0, 8, &params, false);
1485                }
1486            }
1487        }
1488    }
1489}
1490
1491/// Whether a macroblock has any coded (non-zero) DCT coefficient.
1492///
1493/// The §20.6 step-2 / step-4 skip rule (RFC 6386 §15.1 page 86) is
1494/// "neither `B_PRED` nor `SPLITMV` *and* no DCT coefficient coded for
1495/// the whole macroblock". The §20.6 annex notes this conditional is
1496/// "actually dependent on the number of coefficients decoded, not the
1497/// skip flag as coded in the bitstream" — so we examine the
1498/// dequantized coefficient bundle directly rather than trusting
1499/// `mb_skip_coeff`.
1500pub(crate) fn mb_has_coeffs(coeffs: &MbCoeffs) -> bool {
1501    coeffs.y2.iter().any(|&c| c != 0)
1502        || coeffs.y.iter().any(|b| b.iter().any(|&c| c != 0))
1503        || coeffs.u.iter().any(|b| b.iter().any(|&c| c != 0))
1504        || coeffs.v.iter().any(|b| b.iter().any(|&c| c != 0))
1505}
1506
1507/// Apply the normal §15.3 filter to one vertical edge of a plane.
1508///
1509/// `x` is the column at the edge (`p`-side is `x - 1`, `q`-side is `x`);
1510/// `y0` is the first row of the edge, `len` the number of rows (16 for
1511/// luma, 8 for chroma). `mb_edge` selects the wide [`mb_filter`] for
1512/// inter-macroblock edges vs. the [`subblock_filter`] for inter-subblock
1513/// edges.
1514#[allow(clippy::too_many_arguments)]
1515fn filter_v_edge_normal(
1516    plane: &mut [u8],
1517    stride: usize,
1518    x: usize,
1519    y0: usize,
1520    len: usize,
1521    params: &LoopFilterParams,
1522    mb_edge: bool,
1523) {
1524    let edge_limit = if mb_edge {
1525        params.mbedge_limit
1526    } else {
1527        params.sub_bedge_limit
1528    };
1529
1530    // SIMD fast path: process 4 independent rows at once. Vertical-edge
1531    // rows are fully independent (each gathers its window from a distinct
1532    // stride row), so 4 rows map onto one `Simd<i32, 4>` lane each. Both
1533    // §15.1 edge lengths (16 luma, 8 chroma) are multiples of 4.
1534    #[cfg(feature = "simd")]
1535    {
1536        if len % 4 == 0 {
1537            filter_v_edge_normal_simd(plane, stride, x, y0, len, params, edge_limit, mb_edge);
1538            return;
1539        }
1540    }
1541    // Whole-run path for the two run lengths the frame pass uses.
1542    #[cfg(not(feature = "simd"))]
1543    match len {
1544        16 => {
1545            return filter_v_edge_normal_run::<16>(
1546                plane, stride, x, y0, params, edge_limit, mb_edge,
1547            );
1548        }
1549        8 => {
1550            return filter_v_edge_normal_run::<8>(
1551                plane, stride, x, y0, params, edge_limit, mb_edge,
1552            );
1553        }
1554        _ => {}
1555    }
1556
1557    let mut seg = [0u8; 8];
1558    for r in 0..len {
1559        let row = (y0 + r) * stride;
1560        // Gather the 8-pixel segment p3 p2 p1 p0 | q0 q1 q2 q3 centred on
1561        // the vertical edge at column `x` (p-side is to the left).
1562        for (k, slot) in seg.iter_mut().enumerate() {
1563            *slot = plane[row + x - 4 + k];
1564        }
1565        if mb_edge {
1566            mb_filter(
1567                params.hev_threshold,
1568                params.interior_limit,
1569                edge_limit,
1570                &mut seg,
1571                0,
1572            );
1573        } else {
1574            subblock_filter(
1575                params.hev_threshold,
1576                params.interior_limit,
1577                edge_limit,
1578                &mut seg,
1579                0,
1580            );
1581        }
1582        for (k, &val) in seg.iter().enumerate() {
1583            plane[row + x - 4 + k] = val;
1584        }
1585    }
1586}
1587
1588/// SIMD vertical-edge normal filter — processes the `len` rows in groups
1589/// of 4 through [`subblock_filter_v`] / [`mb_filter_v`]. Byte-exact with
1590/// the scalar [`filter_v_edge_normal`] loop body.
1591#[cfg(feature = "simd")]
1592#[allow(clippy::too_many_arguments)]
1593fn filter_v_edge_normal_simd(
1594    plane: &mut [u8],
1595    stride: usize,
1596    x: usize,
1597    y0: usize,
1598    len: usize,
1599    params: &LoopFilterParams,
1600    edge_limit: u8,
1601    mb_edge: bool,
1602) {
1603    use core::simd::Simd;
1604    let bias = Simd::splat(128);
1605    let mut r = 0;
1606    while r < len {
1607        // Gather tap `k` across the 4 rows into one lane each, converting
1608        // to signed (`u2s` = -128) up front.
1609        let mut seg: [Simd<i32, 4>; 8] = [Simd::splat(0); 8];
1610        for (k, slot) in seg.iter_mut().enumerate() {
1611            let lanes: [i32; 4] = core::array::from_fn(|lane| {
1612                let row = (y0 + r + lane) * stride;
1613                plane[row + x - 4 + k] as i32 - 128
1614            });
1615            *slot = Simd::from_array(lanes);
1616        }
1617        if mb_edge {
1618            mb_filter_v(
1619                params.hev_threshold,
1620                params.interior_limit,
1621                edge_limit,
1622                &mut seg,
1623            );
1624        } else {
1625            subblock_filter_v(
1626                params.hev_threshold,
1627                params.interior_limit,
1628                edge_limit,
1629                &mut seg,
1630            );
1631        }
1632        // Scatter back, re-adding 128 (`s2u` reverse of the `u2s` above —
1633        // the kernels keep everything clamped within signed range).
1634        for (k, slot) in seg.iter().enumerate() {
1635            let out = (*slot + bias).to_array();
1636            for (lane, &val) in out.iter().enumerate() {
1637                let row = (y0 + r + lane) * stride;
1638                plane[row + x - 4 + k] = val as u8;
1639            }
1640        }
1641        r += 4;
1642    }
1643}
1644
1645/// Apply the normal §15.3 filter to one horizontal edge of a plane.
1646///
1647/// `y` is the row at the edge (`p`-side is `y - 1`, `q`-side is `y`);
1648/// `x0` is the first column, `len` the number of columns.
1649#[allow(clippy::too_many_arguments)]
1650fn filter_h_edge_normal(
1651    plane: &mut [u8],
1652    stride: usize,
1653    y: usize,
1654    x0: usize,
1655    len: usize,
1656    params: &LoopFilterParams,
1657    mb_edge: bool,
1658) {
1659    let edge_limit = if mb_edge {
1660        params.mbedge_limit
1661    } else {
1662        params.sub_bedge_limit
1663    };
1664
1665    // SIMD fast path: 4 independent columns at once (each gathers its
1666    // window from a distinct column). Both edge lengths are multiples
1667    // of 4.
1668    #[cfg(feature = "simd")]
1669    {
1670        if len % 4 == 0 {
1671            filter_h_edge_normal_simd(plane, stride, y, x0, len, params, edge_limit, mb_edge);
1672            return;
1673        }
1674    }
1675    // Whole-run path for the two run lengths the frame pass uses.
1676    #[cfg(not(feature = "simd"))]
1677    match len {
1678        16 => {
1679            return filter_h_edge_normal_run::<16>(
1680                plane, stride, y, x0, params, edge_limit, mb_edge,
1681            );
1682        }
1683        8 => {
1684            return filter_h_edge_normal_run::<8>(
1685                plane, stride, y, x0, params, edge_limit, mb_edge,
1686            );
1687        }
1688        _ => {}
1689    }
1690
1691    let mut seg = [0u8; 8];
1692    for c in 0..len {
1693        let col = x0 + c;
1694        // Gather the 8-pixel segment straddling the horizontal edge at
1695        // row `y` (p-side is above).
1696        for (k, slot) in seg.iter_mut().enumerate() {
1697            *slot = plane[(y - 4 + k) * stride + col];
1698        }
1699        if mb_edge {
1700            mb_filter(
1701                params.hev_threshold,
1702                params.interior_limit,
1703                edge_limit,
1704                &mut seg,
1705                0,
1706            );
1707        } else {
1708            subblock_filter(
1709                params.hev_threshold,
1710                params.interior_limit,
1711                edge_limit,
1712                &mut seg,
1713                0,
1714            );
1715        }
1716        for (k, &val) in seg.iter().enumerate() {
1717            plane[(y - 4 + k) * stride + col] = val;
1718        }
1719    }
1720}
1721
1722/// SIMD horizontal-edge normal filter — processes the `len` columns in
1723/// groups of 4. Byte-exact with the scalar [`filter_h_edge_normal`]
1724/// loop body.
1725#[cfg(feature = "simd")]
1726#[allow(clippy::too_many_arguments)]
1727fn filter_h_edge_normal_simd(
1728    plane: &mut [u8],
1729    stride: usize,
1730    y: usize,
1731    x0: usize,
1732    len: usize,
1733    params: &LoopFilterParams,
1734    edge_limit: u8,
1735    mb_edge: bool,
1736) {
1737    use core::simd::Simd;
1738    let bias = Simd::splat(128);
1739    let mut c = 0;
1740    while c < len {
1741        let mut seg: [Simd<i32, 4>; 8] = [Simd::splat(0); 8];
1742        for (k, slot) in seg.iter_mut().enumerate() {
1743            let base = (y - 4 + k) * stride + x0 + c;
1744            let lanes: [i32; 4] = core::array::from_fn(|lane| plane[base + lane] as i32 - 128);
1745            *slot = Simd::from_array(lanes);
1746        }
1747        if mb_edge {
1748            mb_filter_v(
1749                params.hev_threshold,
1750                params.interior_limit,
1751                edge_limit,
1752                &mut seg,
1753            );
1754        } else {
1755            subblock_filter_v(
1756                params.hev_threshold,
1757                params.interior_limit,
1758                edge_limit,
1759                &mut seg,
1760            );
1761        }
1762        for (k, slot) in seg.iter().enumerate() {
1763            let base = (y - 4 + k) * stride + x0 + c;
1764            let out = (*slot + bias).to_array();
1765            for (lane, &val) in out.iter().enumerate() {
1766                plane[base + lane] = val as u8;
1767            }
1768        }
1769        c += 4;
1770    }
1771}
1772
1773/// Apply the §15.2 simple filter to one vertical edge (luma only).
1774///
1775/// The simple filter examines a 4-pixel window `p1 p0 | q0 q1`; the
1776/// `edge_limit` is the precomputed `mbedge_limit` / `sub_bedge_limit`.
1777fn filter_v_edge_simple(plane: &mut [u8], stride: usize, x: usize, y0: usize, edge_limit: u8) {
1778    // SIMD fast path: 4 independent rows at once (16 rows = 4 groups).
1779    #[cfg(feature = "simd")]
1780    filter_v_edge_simple_simd(plane, stride, x, y0, edge_limit);
1781    #[cfg(not(feature = "simd"))]
1782    {
1783        let mut seg = [0u8; 4];
1784        for r in 0..16 {
1785            let row = (y0 + r) * stride;
1786            for (k, slot) in seg.iter_mut().enumerate() {
1787                *slot = plane[row + x - 2 + k];
1788            }
1789            simple_segment(edge_limit, &mut seg, 0);
1790            for (k, &val) in seg.iter().enumerate() {
1791                plane[row + x - 2 + k] = val;
1792            }
1793        }
1794    }
1795}
1796
1797/// SIMD vertical-edge simple filter — 4 rows per group through
1798/// [`simple_segment_v`]. Byte-exact with the scalar loop body.
1799#[cfg(feature = "simd")]
1800fn filter_v_edge_simple_simd(plane: &mut [u8], stride: usize, x: usize, y0: usize, edge_limit: u8) {
1801    use core::simd::Simd;
1802    let mut r = 0;
1803    while r < 16 {
1804        let gather = |off: usize| -> Simd<i32, 4> {
1805            Simd::from_array(core::array::from_fn(|lane| {
1806                plane[(y0 + r + lane) * stride + x - 2 + off] as i32
1807            }))
1808        };
1809        let (np0, nq0) = simple_segment_v(edge_limit, gather(0), gather(1), gather(2), gather(3));
1810        let np0 = np0.to_array();
1811        let nq0 = nq0.to_array();
1812        for lane in 0..4 {
1813            let row = (y0 + r + lane) * stride;
1814            plane[row + x - 1] = np0[lane] as u8;
1815            plane[row + x] = nq0[lane] as u8;
1816        }
1817        r += 4;
1818    }
1819}
1820
1821/// Apply the §15.2 simple filter to one horizontal edge (luma only).
1822fn filter_h_edge_simple(plane: &mut [u8], stride: usize, y: usize, x0: usize, edge_limit: u8) {
1823    // SIMD fast path: 4 independent columns at once (16 cols = 4 groups).
1824    #[cfg(feature = "simd")]
1825    filter_h_edge_simple_simd(plane, stride, y, x0, edge_limit);
1826    #[cfg(not(feature = "simd"))]
1827    {
1828        let mut seg = [0u8; 4];
1829        for c in 0..16 {
1830            let col = x0 + c;
1831            for (k, slot) in seg.iter_mut().enumerate() {
1832                *slot = plane[(y - 2 + k) * stride + col];
1833            }
1834            simple_segment(edge_limit, &mut seg, 0);
1835            for (k, &val) in seg.iter().enumerate() {
1836                plane[(y - 2 + k) * stride + col] = val;
1837            }
1838        }
1839    }
1840}
1841
1842/// SIMD horizontal-edge simple filter — 4 columns per group through
1843/// [`simple_segment_v`]. Byte-exact with the scalar loop body.
1844#[cfg(feature = "simd")]
1845fn filter_h_edge_simple_simd(plane: &mut [u8], stride: usize, y: usize, x0: usize, edge_limit: u8) {
1846    use core::simd::Simd;
1847    let mut c = 0;
1848    while c < 16 {
1849        let gather = |off: usize| -> Simd<i32, 4> {
1850            let base = (y - 2 + off) * stride + x0 + c;
1851            Simd::from_array(core::array::from_fn(|lane| plane[base + lane] as i32))
1852        };
1853        let (np0, nq0) = simple_segment_v(edge_limit, gather(0), gather(1), gather(2), gather(3));
1854        let np0 = np0.to_array();
1855        let nq0 = nq0.to_array();
1856        let p0_base = (y - 1) * stride + x0 + c;
1857        let q0_base = y * stride + x0 + c;
1858        for lane in 0..4 {
1859            plane[p0_base + lane] = np0[lane] as u8;
1860            plane[q0_base + lane] = nq0[lane] as u8;
1861        }
1862        c += 4;
1863    }
1864}
1865
1866/// Run the §15 loop filter over a reconstructed key frame in place.
1867///
1868/// This is the §15.1 frame-geometry pass: it walks the macroblocks of
1869/// `planes` in raster-scan order and, for each, applies the four §15.1
1870/// filtering steps using the kernels above —
1871///
1872/// 1. the left (vertical) inter-macroblock edge (skipped on the leftmost
1873///    column),
1874/// 2. the three internal vertical subblock edges,
1875/// 3. the top (horizontal) inter-macroblock edge (skipped on the topmost
1876///    row),
1877/// 4. the three internal horizontal subblock edges,
1878///
1879/// with the chroma analogues for the normal filter (the §15.2 simple
1880/// filter touches only luma). Steps 2 and 4 are skipped for a macroblock
1881/// whose coding mode is neither `B_PRED` nor `SPLITMV` *and* which has no
1882/// coded coefficient (RFC 6386 §15.1 page 86). The whole macroblock is
1883/// skipped when its resolved §20.6 filter level is 0 (RFC 6386 §15
1884/// page 84). `modes` and `coeffs` must each have `mb_cols * mb_rows`
1885/// entries in the same raster order as [`crate::decode_keyframe`].
1886///
1887/// The §20.6 ordering "must be respected" (RFC 6386 §15.1 page 86): many
1888/// pixels straddle two or more edges and are filtered more than once, so
1889/// the raster MB order and the within-MB step order are both load-bearing.
1890pub fn filter_frame(
1891    planes: &mut KeyframePlanes,
1892    modes: &[MacroblockModes],
1893    coeffs: &[MbCoeffs],
1894    config: &FrameFilterConfig,
1895) {
1896    // The §15.1 step-2/4 skip rule consults only `mb_has_coeffs` per MB, a
1897    // single boolean. Collapse the full coefficient bundles to that per-MB
1898    // flag and dispatch to the flag-driven body; the public `&[MbCoeffs]`
1899    // signature is preserved for callers that still hold the full bundles.
1900    let has_coeffs: Vec<bool> = coeffs.iter().map(mb_has_coeffs).collect();
1901    filter_frame_flags(planes, modes, &has_coeffs, config);
1902}
1903
1904/// Borrowed view of a source picture's three planes plus the §9.1 visible
1905/// window, for scoring a candidate loop-filter reconstruction against the
1906/// original.
1907///
1908/// The planes are the encoder's *source* I420 picture (not the
1909/// reconstruction). `y` is `y_stride`-strided and at least `height` rows;
1910/// `u` / `v` are `uv_stride`-strided and at least `(height + 1) / 2` rows.
1911/// Only the visible `width × height` (luma) / `⌈w/2⌉ × ⌈h/2⌉` (chroma)
1912/// window is scored — the macroblock-padding region the reconstruction
1913/// carries past the visible edge has no source counterpart and is excluded
1914/// from the distortion sum.
1915#[derive(Debug, Clone, Copy)]
1916pub struct SourcePlanes<'a> {
1917    /// Visible luma width in pixels (§9.1).
1918    pub width: usize,
1919    /// Visible luma height in pixels (§9.1).
1920    pub height: usize,
1921    /// Source luma plane, row-major, `y_stride`-strided.
1922    pub y: &'a [u8],
1923    /// Source U chroma plane, row-major, `uv_stride`-strided.
1924    pub u: &'a [u8],
1925    /// Source V chroma plane, row-major, `uv_stride`-strided.
1926    pub v: &'a [u8],
1927    /// Luma row stride in bytes (≥ `width`).
1928    pub y_stride: usize,
1929    /// Chroma row stride in bytes (≥ `⌈width/2⌉`).
1930    pub uv_stride: usize,
1931}
1932
1933/// Sum of squared differences between the visible window of a
1934/// reconstruction plane and the matching source plane.
1935///
1936/// `recon` is the macroblock-padded reconstruction plane (`recon_stride`);
1937/// `src` is the source plane (`src_stride`). Only the `w × h` visible
1938/// window is summed. Returned as `u64` so a full-frame luma sum of 8-bit
1939/// squared error (≤ `65025` per pixel) cannot overflow for any §9.1-legal
1940/// frame.
1941fn plane_visible_ssd(
1942    recon: &[u8],
1943    recon_stride: usize,
1944    src: &[u8],
1945    src_stride: usize,
1946    w: usize,
1947    h: usize,
1948) -> u64 {
1949    let mut ssd = 0u64;
1950    for r in 0..h {
1951        let recon_row = &recon[r * recon_stride..r * recon_stride + w];
1952        let src_row = &src[r * src_stride..r * src_stride + w];
1953        for (a, b) in recon_row.iter().zip(src_row.iter()) {
1954            let d = *a as i32 - *b as i32;
1955            ssd += (d * d) as u64;
1956        }
1957    }
1958    ssd
1959}
1960
1961/// Total Y+U+V visible-window SSD of a reconstruction against its source.
1962///
1963/// Sums [`plane_visible_ssd`] over the three planes; the chroma planes use
1964/// the §9.1-derived `⌈w/2⌉ × ⌈h/2⌉` window.
1965pub fn reconstruction_ssd(planes: &KeyframePlanes, src: &SourcePlanes<'_>) -> u64 {
1966    let cw = src.width.div_ceil(2);
1967    let ch = src.height.div_ceil(2);
1968    plane_visible_ssd(
1969        &planes.y,
1970        planes.y_stride,
1971        src.y,
1972        src.y_stride,
1973        src.width,
1974        src.height,
1975    ) + plane_visible_ssd(&planes.u, planes.uv_stride, src.u, src.uv_stride, cw, ch)
1976        + plane_visible_ssd(&planes.v, planes.uv_stride, src.v, src.uv_stride, cw, ch)
1977}
1978
1979/// Per-macroblock inter-frame side information the §15 filter consults to
1980/// derive each MB's effective level (the §9.4 reference / mode deltas).
1981/// Bundled so [`select_filter_level`] can score key-frame and inter-frame
1982/// reconstructions through one code path.
1983#[derive(Debug, Clone, Copy)]
1984pub struct InterFilterInfo<'a> {
1985    /// Per-MB reference frame (raster order). `None` ⇒ intra MB.
1986    pub ref_frames: &'a [Option<crate::motion_comp::RefFrame>],
1987    /// Per-MB inter prediction mode (raster order). `None` ⇒ intra MB.
1988    pub inter_modes: &'a [Option<crate::near_mv::InterMode>],
1989}
1990
1991/// RD-driven §9.4 `loop_filter_level` selection (clean-room; RFC 6386 is
1992/// silent on the encoder's level choice — §15 only *defines* the filter).
1993///
1994/// Given the **unfiltered** reconstruction `planes`, the per-MB `modes` /
1995/// `has_coeffs`, the encoder's `base` filter config (sharpness, filter
1996/// type, key/inter, segmentation + delta state) and the original `src`
1997/// picture, this searches the §9.4 level range `0..=63` for the level that
1998/// minimises the post-filter visible-window SSD against `src`, and returns
1999/// it.
2000///
2001/// The §15 filter is monotone-ish but not strictly convex in the level, so
2002/// rather than trust a pure descent we run a **coarse grid then a local
2003/// refine**: score levels `0, step, 2·step, …` then a `±(step-1)` window
2004/// around the grid winner. With the default `step = 4` that is at most
2005/// `⌈64/4⌉ + 7 ≈ 23` candidate evaluations instead of 64, and it is exact
2006/// whenever the SSD-vs-level curve is unimodal (the common case — too
2007/// little filtering leaves block edges, too much over-smooths real
2008/// detail). Each candidate clones the unfiltered planes (so the search is
2009/// side-effect free) and runs the real §15 pass, so the returned level is
2010/// exactly reproducible by [`filter_frame`] / [`filter_inter_frame`].
2011///
2012/// `inter` is `Some` for a P-frame (the per-MB reference / mode arrays the
2013/// inter filter consults) and `None` for a key frame. The returned level
2014/// is clamped to `0..=63`; level `0` (no filtering) is always a candidate
2015/// and wins when the source is already block-edge-free (e.g. a flat or
2016/// already-smooth frame), so the selector never *adds* distortion.
2017pub fn select_filter_level(
2018    planes: &KeyframePlanes,
2019    modes: &[MacroblockModes],
2020    has_coeffs: &[bool],
2021    base: &FrameFilterConfig,
2022    src: &SourcePlanes<'_>,
2023    inter: Option<&InterFilterInfo<'_>>,
2024) -> u8 {
2025    select_filter_params(planes, modes, has_coeffs, base, src, inter).0
2026}
2027
2028/// Joint RD-driven §9.4 `(loop_filter_level, sharpness_level)` selection
2029/// (clean-room; RFC 6386 is silent on the encoder's choice — §15 only
2030/// *defines* the filter).
2031///
2032/// Extends [`select_filter_level`] with the §15.4 `sharpness_level`
2033/// (`0..=7`), which scales down the interior-edge limit (a higher
2034/// sharpness filters interior sub-block edges less, preserving real
2035/// detail). The search is a **coordinate descent**: first pick the best
2036/// level at the base sharpness (coarse grid `step = 4` + `±3` refine — the
2037/// level dominates the distortion), then sweep all 8 sharpness values at
2038/// that level. Returns `(level, sharpness)`; when the chosen level is `0`
2039/// the sharpness is irrelevant (the §15 whole-frame skip runs) and the
2040/// base sharpness is returned unchanged.
2041///
2042/// Each candidate clones the unfiltered planes and runs the real §15 pass,
2043/// so the returned pair is exactly reproducible by [`filter_frame`] /
2044/// [`filter_inter_frame`]. `inter` is `Some` for a P-frame, `None` for a
2045/// key frame. Level `0` is always a candidate, so the selector never
2046/// *adds* distortion.
2047pub fn select_filter_params(
2048    planes: &KeyframePlanes,
2049    modes: &[MacroblockModes],
2050    has_coeffs: &[bool],
2051    base: &FrameFilterConfig,
2052    src: &SourcePlanes<'_>,
2053    inter: Option<&InterFilterInfo<'_>>,
2054) -> (u8, u8) {
2055    select_filter_params_threaded(planes, modes, has_coeffs, base, src, inter, 1)
2056}
2057
2058/// Post-filter visible-window SSD of one `(level, sharpness)` candidate:
2059/// clone the unfiltered planes, run the real §15 pass, measure. Level 0
2060/// short-circuits the §15 whole-frame skip (no clone, no filter) per §15
2061/// page 84 — sharpness is then a no-op.
2062fn score_filter_candidate(
2063    planes: &KeyframePlanes,
2064    modes: &[MacroblockModes],
2065    has_coeffs: &[bool],
2066    base: &FrameFilterConfig,
2067    src: &SourcePlanes<'_>,
2068    inter: Option<&InterFilterInfo<'_>>,
2069    (level, sharpness): (u8, u8),
2070) -> u64 {
2071    if level == 0 {
2072        return reconstruction_ssd(planes, src);
2073    }
2074    let mut cand = planes.clone();
2075    let cfg = FrameFilterConfig {
2076        loop_filter_level: level,
2077        sharpness_level: sharpness,
2078        ..*base
2079    };
2080    match inter {
2081        Some(info) => filter_inter_frame_flags(
2082            &mut cand,
2083            modes,
2084            has_coeffs,
2085            info.ref_frames,
2086            info.inter_modes,
2087            &cfg,
2088        ),
2089        None => filter_frame_flags(&mut cand, modes, has_coeffs, &cfg),
2090    }
2091    reconstruction_ssd(&cand, src)
2092}
2093
2094/// Evaluate `score` for every candidate on up to `threads` threads; the
2095/// results come back in candidate order, so a caller's first-minimum
2096/// choice does not depend on the budget.
2097fn score_candidates<C: Copy + Sync>(
2098    candidates: &[C],
2099    threads: usize,
2100    score: impl Fn(C) -> u64 + Sync,
2101) -> Vec<u64> {
2102    let workers = threads.clamp(1, candidates.len().max(1));
2103    if workers == 1 {
2104        return candidates.iter().map(|&c| score(c)).collect();
2105    }
2106    let next = std::sync::atomic::AtomicUsize::new(0);
2107    let results: Vec<std::sync::atomic::AtomicU64> = candidates
2108        .iter()
2109        .map(|_| std::sync::atomic::AtomicU64::new(0))
2110        .collect();
2111    let worker = || {
2112        loop {
2113            let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2114            let Some(&candidate) = candidates.get(i) else {
2115                break;
2116            };
2117            results[i].store(score(candidate), std::sync::atomic::Ordering::Release);
2118        }
2119    };
2120    std::thread::scope(|scope| {
2121        for _ in 1..workers {
2122            scope.spawn(worker);
2123        }
2124        worker();
2125    });
2126    results.into_iter().map(|r| r.into_inner()).collect()
2127}
2128
2129/// [`select_filter_params`] with its candidates scored on up to
2130/// `threads` threads. The candidate sets and the first-minimum choice are
2131/// those of the serial search, so the result does not depend on the
2132/// budget.
2133pub(crate) fn select_filter_params_threaded(
2134    planes: &KeyframePlanes,
2135    modes: &[MacroblockModes],
2136    has_coeffs: &[bool],
2137    base: &FrameFilterConfig,
2138    src: &SourcePlanes<'_>,
2139    inter: Option<&InterFilterInfo<'_>>,
2140    threads: usize,
2141) -> (u8, u8) {
2142    const STEP: u8 = 4;
2143    let score = |candidate: (u8, u8)| {
2144        score_filter_candidate(planes, modes, has_coeffs, base, src, inter, candidate)
2145    };
2146    let base_sharp = base.sharpness_level.min(7);
2147
2148    // ---- Stage 1: pick the level at the base sharpness -----------------
2149    // Coarse grid: 0, STEP, 2·STEP, … plus the endpoint 63.
2150    let mut grid: Vec<(u8, u8)> = (0..=63u8)
2151        .step_by(STEP as usize)
2152        .map(|l| (l, base_sharp))
2153        .collect();
2154    grid.push((63, base_sharp));
2155    let scores = score_candidates(&grid, threads, score);
2156    let mut best_level = 0u8;
2157    let mut best_ssd = scores[0];
2158    for (&(level, _), &s) in grid.iter().zip(&scores).skip(1) {
2159        if s < best_ssd {
2160            best_ssd = s;
2161            best_level = level;
2162        }
2163    }
2164    // Local refine: ±(STEP-1) around the grid winner.
2165    let lo = best_level.saturating_sub(STEP - 1);
2166    let hi = best_level.saturating_add(STEP - 1).min(63);
2167    let refine: Vec<(u8, u8)> = (lo..=hi)
2168        .filter(|&l| l != best_level)
2169        .map(|l| (l, base_sharp))
2170        .collect();
2171    let scores = score_candidates(&refine, threads, score);
2172    for (&(level, _), &s) in refine.iter().zip(&scores) {
2173        if s < best_ssd {
2174            best_ssd = s;
2175            best_level = level;
2176        }
2177    }
2178
2179    // Level 0 wins: sharpness is irrelevant (the §15 skip runs).
2180    if best_level == 0 {
2181        return (0, base_sharp);
2182    }
2183
2184    // ---- Stage 2: sweep sharpness at the chosen level ------------------
2185    let sweep: Vec<(u8, u8)> = (0u8..=7)
2186        .filter(|&sharp| sharp != base_sharp)
2187        .map(|sharp| (best_level, sharp))
2188        .collect();
2189    let scores = score_candidates(&sweep, threads, score);
2190    let mut best_sharp = base_sharp;
2191    for (&(_, sharp), &s) in sweep.iter().zip(&scores) {
2192        if s < best_ssd {
2193            best_ssd = s;
2194            best_sharp = sharp;
2195        }
2196    }
2197
2198    (best_level, best_sharp)
2199}
2200
2201/// A band of macroblock rows lifted out of a frame, for scoring filter
2202/// levels on part of the picture.
2203struct FilterSample<'a> {
2204    planes: KeyframePlanes,
2205    modes: &'a [MacroblockModes],
2206    has_coeffs: &'a [bool],
2207    /// The band's slice of the inter-frame decisions (`None` on a key
2208    /// frame).
2209    #[allow(clippy::type_complexity)] // two parallel per-macroblock slices
2210    inter: Option<(
2211        &'a [Option<crate::motion_comp::RefFrame>],
2212        &'a [Option<crate::near_mv::InterMode>],
2213    )>,
2214    /// First macroblock row of the band in the frame.
2215    first_row: usize,
2216}
2217
2218/// Choose the §9.4 `loop_filter_level` of an inter frame from a sample
2219/// of the picture (clean-room; the level is the encoder's choice).
2220///
2221/// [`select_filter_params_sampled`] with the sharpness left at the base
2222/// value.
2223#[allow(clippy::too_many_arguments)]
2224pub(crate) fn select_filter_level_sampled(
2225    planes: &KeyframePlanes,
2226    modes: &[MacroblockModes],
2227    has_coeffs: &[bool],
2228    base: &FrameFilterConfig,
2229    src: &SourcePlanes<'_>,
2230    inter: &InterFilterInfo<'_>,
2231    every_rows: usize,
2232    threads: usize,
2233) -> u8 {
2234    let sample = FilterSampling {
2235        every_rows,
2236        sweep_sharpness: false,
2237    };
2238    select_filter_params_sampled(
2239        planes,
2240        modes,
2241        has_coeffs,
2242        base,
2243        src,
2244        Some(inter),
2245        sample,
2246        threads,
2247    )
2248    .0
2249}
2250
2251/// How [`select_filter_params_sampled`] samples the picture.
2252#[derive(Debug, Clone, Copy)]
2253pub(crate) struct FilterSampling {
2254    /// A band of two macroblock rows is taken every this many rows.
2255    pub(crate) every_rows: usize,
2256    /// Also try the other seven sharpness values at the chosen level.
2257    pub(crate) sweep_sharpness: bool,
2258}
2259
2260impl FilterSampling {
2261    /// The sampling the key-frame encoder uses for a picture of
2262    /// `mb_rows` macroblock rows: three bands spread over the height of
2263    /// a small picture (a fifth of it), up to six on a large one (a
2264    /// sixteenth of a 12-megapixel picture — in macroblocks the sample
2265    /// also grows with the picture's width), with the sharpness sweep.
2266    pub(crate) fn for_key_frame(mb_rows: usize) -> Self {
2267        let bands = (mb_rows / 32).clamp(3, 6);
2268        FilterSampling {
2269            every_rows: (mb_rows / bands).max(2),
2270            sweep_sharpness: true,
2271        }
2272    }
2273}
2274
2275/// Choose the §9.4 `loop_filter_level` (and optionally the sharpness) of
2276/// a frame from a sample of the picture (clean-room; both are the
2277/// encoder's choice).
2278///
2279/// Bands of two macroblock rows are taken every `every_rows` rows; each
2280/// candidate filters copies of the bands (a band's first row without its
2281/// top edge) and is scored by the bands' visible-window SSD against the
2282/// source. The level is found coarse to fine: every eighth level, then
2283/// ±4, ±2 and ±1 around the running best — 15 candidates against the
2284/// full search's ~30 full-frame passes — and the sharpness sweep adds
2285/// seven more. Candidates are scored on up to `threads` threads; the
2286/// choice does not depend on the budget.
2287#[allow(clippy::too_many_arguments)]
2288pub(crate) fn select_filter_params_sampled(
2289    planes: &KeyframePlanes,
2290    modes: &[MacroblockModes],
2291    has_coeffs: &[bool],
2292    base: &FrameFilterConfig,
2293    src: &SourcePlanes<'_>,
2294    inter: Option<&InterFilterInfo<'_>>,
2295    sampling: FilterSampling,
2296    threads: usize,
2297) -> (u8, u8) {
2298    const BAND_ROWS: usize = 2;
2299    let (mb_cols, mb_rows) = (planes.mb_cols, planes.mb_rows);
2300    let (ys, cs) = (planes.y_stride, planes.uv_stride);
2301    let every_rows = sampling.every_rows.max(BAND_ROWS);
2302    let mut samples: Vec<FilterSample<'_>> = Vec::new();
2303    let mut first_row = 0usize;
2304    while first_row < mb_rows {
2305        let rows = BAND_ROWS.min(mb_rows - first_row);
2306        let mbs = first_row * mb_cols..(first_row + rows) * mb_cols;
2307        samples.push(FilterSample {
2308            planes: KeyframePlanes {
2309                y: planes.y[first_row * 16 * ys..(first_row + rows) * 16 * ys].to_vec(),
2310                u: planes.u[first_row * 8 * cs..(first_row + rows) * 8 * cs].to_vec(),
2311                v: planes.v[first_row * 8 * cs..(first_row + rows) * 8 * cs].to_vec(),
2312                y_stride: ys,
2313                uv_stride: cs,
2314                mb_cols,
2315                mb_rows: rows,
2316            },
2317            modes: &modes[mbs.clone()],
2318            has_coeffs: &has_coeffs[mbs.clone()],
2319            inter: inter.map(|info| (&info.ref_frames[mbs.clone()], &info.inter_modes[mbs])),
2320            first_row,
2321        });
2322        first_row += every_rows;
2323    }
2324    let base_sharp = base.sharpness_level.min(7);
2325    let score = |(level, sharpness): (u8, u8)| -> u64 {
2326        let mut total = 0u64;
2327        for sample in &samples {
2328            let y0 = sample.first_row * 16;
2329            if y0 >= src.height {
2330                continue;
2331            }
2332            let band_src = SourcePlanes {
2333                width: src.width,
2334                height: (sample.planes.mb_rows * 16).min(src.height - y0),
2335                y: &src.y[y0 * src.y_stride..],
2336                u: &src.u[(y0 / 2) * src.uv_stride..],
2337                v: &src.v[(y0 / 2) * src.uv_stride..],
2338                y_stride: src.y_stride,
2339                uv_stride: src.uv_stride,
2340            };
2341            if level == 0 {
2342                total += reconstruction_ssd(&sample.planes, &band_src);
2343                continue;
2344            }
2345            let mut cand = sample.planes.clone();
2346            let cfg = FrameFilterConfig {
2347                loop_filter_level: level,
2348                sharpness_level: sharpness,
2349                ..*base
2350            };
2351            match sample.inter {
2352                Some((ref_frames, inter_modes)) => filter_inter_frame_flags(
2353                    &mut cand,
2354                    sample.modes,
2355                    sample.has_coeffs,
2356                    ref_frames,
2357                    inter_modes,
2358                    &cfg,
2359                ),
2360                None => filter_frame_flags(&mut cand, sample.modes, sample.has_coeffs, &cfg),
2361            }
2362            total += reconstruction_ssd(&cand, &band_src);
2363        }
2364        total
2365    };
2366
2367    let coarse: Vec<(u8, u8)> = (0..=56u8)
2368        .step_by(8)
2369        .chain([63])
2370        .map(|level| (level, base_sharp))
2371        .collect();
2372    let scores = score_candidates(&coarse, threads, score);
2373    let mut best_level = coarse[0].0;
2374    let mut best_ssd = scores[0];
2375    for (&(level, _), &s) in coarse.iter().zip(&scores).skip(1) {
2376        if s < best_ssd {
2377            best_ssd = s;
2378            best_level = level;
2379        }
2380    }
2381    for step in [4u8, 2, 1] {
2382        let mut around: Vec<(u8, u8)> = Vec::with_capacity(2);
2383        if best_level >= step {
2384            around.push((best_level - step, base_sharp));
2385        }
2386        if best_level + step <= 63 {
2387            around.push((best_level + step, base_sharp));
2388        }
2389        let scores = score_candidates(&around, threads, score);
2390        for (&(level, _), &s) in around.iter().zip(&scores) {
2391            if s < best_ssd {
2392                best_ssd = s;
2393                best_level = level;
2394            }
2395        }
2396    }
2397    let mut best_sharp = base_sharp;
2398    if sampling.sweep_sharpness && best_level != 0 {
2399        let sweep: Vec<(u8, u8)> = (0u8..=7)
2400            .filter(|&sharp| sharp != base_sharp)
2401            .map(|sharp| (best_level, sharp))
2402            .collect();
2403        let scores = score_candidates(&sweep, threads, score);
2404        for (&(_, sharp), &s) in sweep.iter().zip(&scores) {
2405            if s < best_ssd {
2406                best_ssd = s;
2407                best_sharp = sharp;
2408            }
2409        }
2410    }
2411    (best_level, best_sharp)
2412}
2413
2414/// The per-macroblock filter decisions of a key frame (`None` = level 0).
2415fn key_frame_filter_specs(
2416    modes: &[MacroblockModes],
2417    has_coeffs: &[bool],
2418    config: &FrameFilterConfig,
2419) -> Vec<Option<bands::MbFilterSpec>> {
2420    modes
2421        .iter()
2422        .zip(has_coeffs)
2423        .map(|(mb, &coded)| {
2424            let level = calculate_mb_filter_level(config, mb.segment_id, mb.y_mode);
2425            (level != 0).then(|| bands::MbFilterSpec {
2426                params: LoopFilterParams::derive(level, config.sharpness_level, config.key_frame),
2427                filter_subblocks: mb.y_mode == IntraYMode::B || coded,
2428            })
2429        })
2430        .collect()
2431}
2432
2433/// [`filter_frame_flags`] on up to `threads` threads (see `bands.rs`);
2434/// byte-for-byte the serial result.
2435pub(crate) fn filter_frame_flags_threaded(
2436    planes: &mut KeyframePlanes,
2437    modes: &[MacroblockModes],
2438    has_coeffs: &[bool],
2439    config: &FrameFilterConfig,
2440    threads: usize,
2441) {
2442    let expected = planes.mb_cols * planes.mb_rows;
2443    if threads <= 1 || planes.mb_rows < 2 || modes.len() != expected || has_coeffs.len() != expected
2444    {
2445        return filter_frame_flags(planes, modes, has_coeffs, config);
2446    }
2447    let specs = key_frame_filter_specs(modes, has_coeffs, config);
2448    bands::filter_banded(planes, &specs, config.simple, threads);
2449}
2450
2451/// [`filter_inter_frame_flags`] on up to `threads` threads (see
2452/// `bands.rs`); byte-for-byte the serial result.
2453#[allow(clippy::too_many_arguments)]
2454pub(crate) fn filter_inter_frame_flags_threaded(
2455    planes: &mut KeyframePlanes,
2456    modes: &[MacroblockModes],
2457    has_coeffs: &[bool],
2458    ref_frames: &[Option<crate::motion_comp::RefFrame>],
2459    inter_modes: &[Option<crate::near_mv::InterMode>],
2460    config: &FrameFilterConfig,
2461    threads: usize,
2462) {
2463    let expected = planes.mb_cols * planes.mb_rows;
2464    if threads <= 1
2465        || planes.mb_rows < 2
2466        || modes.len() != expected
2467        || has_coeffs.len() != expected
2468        || ref_frames.len() != expected
2469        || inter_modes.len() != expected
2470    {
2471        return filter_inter_frame_flags(
2472            planes,
2473            modes,
2474            has_coeffs,
2475            ref_frames,
2476            inter_modes,
2477            config,
2478        );
2479    }
2480    let specs: Vec<Option<bands::MbFilterSpec>> = (0..expected)
2481        .map(|index| {
2482            let mb = &modes[index];
2483            let level = calculate_mb_filter_level_inter(
2484                config,
2485                mb.segment_id,
2486                ref_frames[index],
2487                inter_modes[index],
2488                mb.y_mode,
2489            );
2490            (level != 0).then(|| bands::MbFilterSpec {
2491                params: LoopFilterParams::derive(level, config.sharpness_level, config.key_frame),
2492                filter_subblocks: mb.y_mode == IntraYMode::B || has_coeffs[index],
2493            })
2494        })
2495        .collect();
2496    bands::filter_banded(planes, &specs, config.simple, threads);
2497}
2498
2499/// Flag-driven core of [`filter_frame`]: the §15.1 step-2/4 decision needs
2500/// only one boolean per macroblock (`mb_has_coeffs`), so the decode loop can
2501/// compute that flag while the coefficients are still hot in cache and avoid
2502/// materialising a whole-frame `Vec<MbCoeffs>` (≈ 800 bytes / MB) solely to
2503/// feed the loop filter. `has_coeffs[index]` must equal `mb_has_coeffs` of the
2504/// MB at raster `index`; the result is byte-for-byte identical to
2505/// [`filter_frame`] (proved by `tests::filter_frame_flags_matches_coeffs`).
2506pub(crate) fn filter_frame_flags(
2507    planes: &mut KeyframePlanes,
2508    modes: &[MacroblockModes],
2509    has_coeffs: &[bool],
2510    config: &FrameFilterConfig,
2511) {
2512    let mb_cols = planes.mb_cols;
2513    let mb_rows = planes.mb_rows;
2514    if mb_cols == 0 || mb_rows == 0 {
2515        return;
2516    }
2517    let expected = mb_cols * mb_rows;
2518    if modes.len() != expected || has_coeffs.len() != expected {
2519        return;
2520    }
2521
2522    let ys = planes.y_stride;
2523    let cs = planes.uv_stride;
2524
2525    for mb_row in 0..mb_rows {
2526        for mb_col in 0..mb_cols {
2527            let index = mb_row * mb_cols + mb_col;
2528            let mb = &modes[index];
2529
2530            let level = calculate_mb_filter_level(config, mb.segment_id, mb.y_mode);
2531            // §15 page 84: skip the macroblock entirely when level is 0.
2532            if level == 0 {
2533                continue;
2534            }
2535            let params = LoopFilterParams::derive(level, config.sharpness_level, config.key_frame);
2536
2537            // §15.1 page 86: steps 2 and 4 run when the MB is B_PRED /
2538            // SPLITMV (no SPLITMV on key frames) OR has any coded coeff.
2539            let filter_subblocks = mb.y_mode == IntraYMode::B || has_coeffs[index];
2540
2541            let y_x0 = mb_col * 16;
2542            let y_y0 = mb_row * 16;
2543            let uv_x0 = mb_col * 8;
2544            let uv_y0 = mb_row * 8;
2545
2546            if config.simple {
2547                // §20.6 filter_row_simple — luma only.
2548                // Step 1: left inter-MB edge.
2549                if mb_col > 0 {
2550                    filter_v_edge_simple(&mut planes.y, ys, y_x0, y_y0, params.mbedge_limit);
2551                }
2552                // Step 2: internal vertical subblock edges (1/4, 1/2, 3/4).
2553                if filter_subblocks {
2554                    for q in 1..4 {
2555                        filter_v_edge_simple(
2556                            &mut planes.y,
2557                            ys,
2558                            y_x0 + 4 * q,
2559                            y_y0,
2560                            params.sub_bedge_limit,
2561                        );
2562                    }
2563                }
2564                // Step 3: top inter-MB edge.
2565                if mb_row > 0 {
2566                    filter_h_edge_simple(&mut planes.y, ys, y_y0, y_x0, params.mbedge_limit);
2567                }
2568                // Step 4: internal horizontal subblock edges.
2569                if filter_subblocks {
2570                    for q in 1..4 {
2571                        filter_h_edge_simple(
2572                            &mut planes.y,
2573                            ys,
2574                            y_y0 + 4 * q,
2575                            y_x0,
2576                            params.sub_bedge_limit,
2577                        );
2578                    }
2579                }
2580            } else {
2581                // §20.6 filter_row_normal — luma + both chroma planes.
2582                // Step 1: left inter-MB edges.
2583                if mb_col > 0 {
2584                    filter_v_edge_normal(&mut planes.y, ys, y_x0, y_y0, 16, &params, true);
2585                    filter_v_edge_normal(&mut planes.u, cs, uv_x0, uv_y0, 8, &params, true);
2586                    filter_v_edge_normal(&mut planes.v, cs, uv_x0, uv_y0, 8, &params, true);
2587                }
2588                // Step 2: internal vertical subblock edges. Luma has
2589                // three (1/4, 1/2, 3/4); chroma has one (centre, 1/2).
2590                if filter_subblocks {
2591                    for q in 1..4 {
2592                        filter_v_edge_normal(
2593                            &mut planes.y,
2594                            ys,
2595                            y_x0 + 4 * q,
2596                            y_y0,
2597                            16,
2598                            &params,
2599                            false,
2600                        );
2601                    }
2602                    filter_v_edge_normal(&mut planes.u, cs, uv_x0 + 4, uv_y0, 8, &params, false);
2603                    filter_v_edge_normal(&mut planes.v, cs, uv_x0 + 4, uv_y0, 8, &params, false);
2604                }
2605                // Step 3: top inter-MB edges.
2606                if mb_row > 0 {
2607                    filter_h_edge_normal(&mut planes.y, ys, y_y0, y_x0, 16, &params, true);
2608                    filter_h_edge_normal(&mut planes.u, cs, uv_y0, uv_x0, 8, &params, true);
2609                    filter_h_edge_normal(&mut planes.v, cs, uv_y0, uv_x0, 8, &params, true);
2610                }
2611                // Step 4: internal horizontal subblock edges.
2612                if filter_subblocks {
2613                    for q in 1..4 {
2614                        filter_h_edge_normal(
2615                            &mut planes.y,
2616                            ys,
2617                            y_y0 + 4 * q,
2618                            y_x0,
2619                            16,
2620                            &params,
2621                            false,
2622                        );
2623                    }
2624                    filter_h_edge_normal(&mut planes.u, cs, uv_y0 + 4, uv_x0, 8, &params, false);
2625                    filter_h_edge_normal(&mut planes.v, cs, uv_y0 + 4, uv_x0, 8, &params, false);
2626                }
2627            }
2628        }
2629    }
2630}
2631
2632#[cfg(test)]
2633mod tests {
2634    use super::*;
2635
2636    /// The whole-run §15.3 kernel equals the per-window scalar kernels
2637    /// on every position, for random and extreme windows across the
2638    /// threshold / limit range, on both edge kinds.
2639    #[test]
2640    fn normal_filter_run_matches_scalar() {
2641        let mut lcg = 0x5EED_F17Eu32;
2642        let mut next = move || {
2643            lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
2644            lcg >> 8
2645        };
2646        let mut filtered = 0usize;
2647        for case in 0..60_000u32 {
2648            let hev_threshold = [0u8, 1, 2, 3, 9, 40][(next() % 6) as usize];
2649            let interior_limit = [1u8, 2, 5, 9, 20, 63][(next() % 6) as usize];
2650            let edge_limit = [0u8, 3, 12, 40, 90, 135, 255][(next() % 7) as usize];
2651            let mut windows = [[0u8; 8]; 16];
2652            for window in windows.iter_mut() {
2653                let base = next() as u8;
2654                let spread = [0u32, 2, 6, 20, 256][(next() % 5) as usize];
2655                for px in window.iter_mut() {
2656                    *px = match case % 7 {
2657                        0 => [0u8, 255][(next() & 1) as usize],
2658                        _ if spread == 256 => next() as u8,
2659                        _ if spread == 0 => base,
2660                        _ => (base as i32 + (next() % (2 * spread + 1)) as i32 - spread as i32)
2661                            .clamp(0, 255) as u8,
2662                    };
2663                }
2664            }
2665            for mb_edge in [false, true] {
2666                let mut taps = [[0i16; 16]; 8];
2667                for (n, window) in windows.iter().enumerate() {
2668                    for k in 0..8 {
2669                        taps[k][n] = window[k] as i16 - 128;
2670                    }
2671                }
2672                normal_filter_run(
2673                    &mut taps,
2674                    hev_threshold,
2675                    interior_limit,
2676                    edge_limit,
2677                    mb_edge,
2678                );
2679                for (n, window) in windows.iter().enumerate() {
2680                    let mut want = *window;
2681                    if mb_edge {
2682                        mb_filter(hev_threshold, interior_limit, edge_limit, &mut want, 0);
2683                    } else {
2684                        subblock_filter(hev_threshold, interior_limit, edge_limit, &mut want, 0);
2685                    }
2686                    let got: [u8; 8] = core::array::from_fn(|k| (taps[k][n] + 128) as u8);
2687                    assert_eq!(
2688                        got, want,
2689                        "window {window:?} hev {hev_threshold} interior {interior_limit} edge {edge_limit} mb {mb_edge}"
2690                    );
2691                    filtered += usize::from(want != *window);
2692                }
2693            }
2694        }
2695        assert!(filtered > 100_000, "only {filtered} windows were filtered");
2696    }
2697
2698    // ----- §15.2 helpers -----------------------------------------------
2699
2700    #[test]
2701    fn clamp_s8_saturates_both_ends() {
2702        assert_eq!(clamp_s8(-200), -128);
2703        assert_eq!(clamp_s8(-129), -128);
2704        assert_eq!(clamp_s8(-128), -128);
2705        assert_eq!(clamp_s8(-1), -1);
2706        assert_eq!(clamp_s8(0), 0);
2707        assert_eq!(clamp_s8(127), 127);
2708        assert_eq!(clamp_s8(128), 127);
2709        assert_eq!(clamp_s8(500), 127);
2710    }
2711
2712    #[test]
2713    fn u2s_s2u_round_trip_in_range() {
2714        // u2s maps 0..=255 -> -128..=127; s2u inverts within the signed
2715        // range. For any pixel value, s2u(u2s(v) as i32) == v.
2716        for v in 0u8..=255 {
2717            assert_eq!(s2u(u2s(v) as i32), v, "v = {v}");
2718        }
2719    }
2720
2721    #[test]
2722    fn u2s_known_points() {
2723        assert_eq!(u2s(0), -128);
2724        assert_eq!(u2s(128), 0);
2725        assert_eq!(u2s(255), 127);
2726    }
2727
2728    #[test]
2729    fn s2u_clamps_out_of_range() {
2730        // s2u clamps the signed argument to -128..=127 before +128.
2731        assert_eq!(s2u(-200), 0); // clamp to -128 -> 0
2732        assert_eq!(s2u(200), 255); // clamp to 127 -> 255
2733        assert_eq!(s2u(0), 128);
2734    }
2735
2736    // ----- §15.4 control parameters ------------------------------------
2737
2738    #[test]
2739    fn derive_interior_limit_no_sharpness() {
2740        // sharpness 0: interior_limit == loop_filter_level (but never 0).
2741        let p = LoopFilterParams::derive(30, 0, true);
2742        assert_eq!(p.interior_limit, 30);
2743        let p0 = LoopFilterParams::derive(0, 0, true);
2744        assert_eq!(p0.interior_limit, 1, "interior_limit floored to 1");
2745    }
2746
2747    #[test]
2748    fn derive_interior_limit_low_sharpness_shifts_by_one() {
2749        // sharpness in 1..=4 shifts right by 1, then caps at 9 - sharpness.
2750        // level 20, sharpness 2: 20 >> 1 = 10, cap = 9 - 2 = 7 -> 7.
2751        let p = LoopFilterParams::derive(20, 2, true);
2752        assert_eq!(p.interior_limit, 7);
2753        // level 10, sharpness 1: 10 >> 1 = 5, cap = 8 -> 5 (uncapped).
2754        let p2 = LoopFilterParams::derive(10, 1, true);
2755        assert_eq!(p2.interior_limit, 5);
2756    }
2757
2758    #[test]
2759    fn derive_interior_limit_high_sharpness_shifts_by_two() {
2760        // sharpness > 4 shifts right by 2, then caps at 9 - sharpness.
2761        // level 40, sharpness 7: 40 >> 2 = 10, cap = 9 - 7 = 2 -> 2.
2762        let p = LoopFilterParams::derive(40, 7, true);
2763        assert_eq!(p.interior_limit, 2);
2764        // level 8, sharpness 5: 8 >> 2 = 2, cap = 9 - 5 = 4 -> 2 (uncapped).
2765        let p2 = LoopFilterParams::derive(8, 5, true);
2766        assert_eq!(p2.interior_limit, 2);
2767    }
2768
2769    #[test]
2770    fn derive_hev_threshold_key_frame_ladder() {
2771        assert_eq!(LoopFilterParams::derive(45, 0, true).hev_threshold, 2);
2772        assert_eq!(LoopFilterParams::derive(40, 0, true).hev_threshold, 2);
2773        assert_eq!(LoopFilterParams::derive(39, 0, true).hev_threshold, 1);
2774        assert_eq!(LoopFilterParams::derive(15, 0, true).hev_threshold, 1);
2775        assert_eq!(LoopFilterParams::derive(14, 0, true).hev_threshold, 0);
2776    }
2777
2778    #[test]
2779    fn derive_hev_threshold_interframe_ladder() {
2780        assert_eq!(LoopFilterParams::derive(45, 0, false).hev_threshold, 3);
2781        assert_eq!(LoopFilterParams::derive(40, 0, false).hev_threshold, 3);
2782        assert_eq!(LoopFilterParams::derive(39, 0, false).hev_threshold, 2);
2783        assert_eq!(LoopFilterParams::derive(20, 0, false).hev_threshold, 2);
2784        assert_eq!(LoopFilterParams::derive(19, 0, false).hev_threshold, 1);
2785        assert_eq!(LoopFilterParams::derive(15, 0, false).hev_threshold, 1);
2786        assert_eq!(LoopFilterParams::derive(14, 0, false).hev_threshold, 0);
2787    }
2788
2789    #[test]
2790    fn derive_edge_limits_formula() {
2791        // level 30, sharpness 0 -> interior_limit 30.
2792        // mbedge = (30 + 2) * 2 + 30 = 94; sub_bedge = 30 * 2 + 30 = 90.
2793        let p = LoopFilterParams::derive(30, 0, true);
2794        assert_eq!(p.interior_limit, 30);
2795        assert_eq!(p.mbedge_limit, 94);
2796        assert_eq!(p.sub_bedge_limit, 90);
2797    }
2798
2799    #[test]
2800    fn derive_edge_limits_max_level_fits_u8() {
2801        // level 63, sharpness 0 -> interior_limit 63.
2802        // mbedge = (63 + 2) * 2 + 63 = 193; sub_bedge = 126 + 63 = 189.
2803        let p = LoopFilterParams::derive(63, 0, true);
2804        assert_eq!(p.mbedge_limit, 193);
2805        assert_eq!(p.sub_bedge_limit, 189);
2806    }
2807
2808    // ----- §15.2 simple filter -----------------------------------------
2809
2810    #[test]
2811    fn simple_segment_skips_when_metric_exceeds_limit() {
2812        // p1 p0 | q0 q1 with a large p0/q0 jump; tiny limit disables.
2813        let mut seg = [10u8, 10, 200, 200];
2814        let before = seg;
2815        simple_segment(1, &mut seg, 0);
2816        assert_eq!(seg, before, "filter must not run when metric > limit");
2817    }
2818
2819    #[test]
2820    fn simple_segment_adjusts_small_step() {
2821        // A modest edge difference under a generous limit gets shaved.
2822        let mut seg = [100u8, 100, 116, 116];
2823        simple_segment(255, &mut seg, 0);
2824        // p0 should rise toward q0, q0 should fall toward p0; the
2825        // adjustment preserves their ordering and pulls them together.
2826        assert!(seg[1] >= 100, "p0 moved toward q0");
2827        assert!(seg[2] <= 116, "q0 moved toward p0");
2828        assert!(seg[2] - seg[1] < 16, "gap reduced");
2829        // Outer taps untouched by the simple filter.
2830        assert_eq!(seg[0], 100);
2831        assert_eq!(seg[3], 116);
2832    }
2833
2834    #[test]
2835    fn common_adjust_hand_derived_no_outer_taps() {
2836        // Re-derive the spec arithmetic for a known input with
2837        // use_outer_taps = false. p1=100 p0=100 q0=108 q1=108.
2838        // u2s: p0 = -28, q0 = -20. a = c(0 + 3*(-20 - -28)) = c(24) = 24.
2839        // b = c(24 + 3) >> 3 = 27 >> 3 = 3.
2840        // a = c(24 + 4) >> 3 = 28 >> 3 = 3.
2841        // Q0 = s2u(q0 - a) = s2u(-20 - 3) = s2u(-23) = 105.
2842        // P0 = s2u(p0 + b) = s2u(-28 + 3) = s2u(-25) = 103.
2843        let mut seg = [100u8, 100, 108, 108];
2844        let ret = common_adjust(false, &mut seg, 0);
2845        assert_eq!(ret, 3, "returned a");
2846        assert_eq!(seg[1], 103, "P0");
2847        assert_eq!(seg[2], 105, "Q0");
2848        assert_eq!(seg[0], 100, "P1 untouched");
2849        assert_eq!(seg[3], 108, "Q1 untouched");
2850    }
2851
2852    #[test]
2853    fn common_adjust_outer_taps_changes_result() {
2854        // Same edge but with outer taps engaged the outer term shifts a.
2855        // p1=90 q1=120: outer = c(u2s(90) - u2s(120)) = c(-38 - -8)
2856        // = c(-30) = -30. p0=100 q0=108: a = c(-30 + 3*8) = c(-6) = -6.
2857        // b = c(-6 + 3) >> 3 = (-3) >> 3 = -1.
2858        // a = c(-6 + 4) >> 3 = (-2) >> 3 = -1.
2859        // Q0 = s2u(-20 - -1) = s2u(-19) = 109.
2860        // P0 = s2u(-28 + -1) = s2u(-29) = 99.
2861        let mut seg = [90u8, 100, 108, 120];
2862        let ret = common_adjust(true, &mut seg, 0);
2863        assert_eq!(ret, -1, "returned a");
2864        assert_eq!(seg[1], 99, "P0");
2865        assert_eq!(seg[2], 109, "Q0");
2866    }
2867
2868    // ----- §15.3 normal filter -----------------------------------------
2869
2870    #[test]
2871    fn subblock_filter_skips_when_interior_diff_too_large() {
2872        // A large p3/p2 step exceeds interior_limit -> filter_yes false.
2873        let mut seg = [10u8, 200, 100, 100, 108, 108, 108, 108];
2874        let before = seg;
2875        subblock_filter(0, 5, 255, &mut seg, 0);
2876        assert_eq!(seg, before, "interior difference disables filter");
2877    }
2878
2879    #[test]
2880    fn subblock_filter_low_hev_adjusts_inner_pixels() {
2881        // Smooth interior, modest edge step, hev_threshold high so the
2882        // edge is treated as low-variance -> p1/q1 also get adjusted.
2883        let mut seg = [100u8, 100, 100, 100, 110, 110, 110, 110];
2884        let before = seg;
2885        subblock_filter(50, 100, 255, &mut seg, 0);
2886        // p0 (idx 3) and q0 (idx 4) move together.
2887        assert!(seg[3] > before[3], "p0 raised");
2888        assert!(seg[4] < before[4], "q0 lowered");
2889        // Low hev path also nudges p1 (idx 2) and q1 (idx 5).
2890        assert!(seg[2] >= before[2], "p1 nudged up");
2891        assert!(seg[5] <= before[5], "q1 nudged down");
2892    }
2893
2894    #[test]
2895    fn subblock_filter_high_hev_leaves_inner_pixels() {
2896        // hev_threshold 0 with a steep p1->p0 inner gradient -> high edge
2897        // variance (|p1 - p0| = 10 > 0), so the inner p1/q1 adjustment is
2898        // skipped and only common_adjust runs on p0/q0.
2899        let mut seg = [100u8, 100, 100, 110, 120, 120, 120, 120];
2900        let before = seg;
2901        subblock_filter(0, 100, 255, &mut seg, 0);
2902        // p1/q1 (idx 2/5) untouched in the high-variance branch.
2903        assert_eq!(seg[2], before[2], "p1 untouched under hev");
2904        assert_eq!(seg[5], before[5], "q1 untouched under hev");
2905        // Edge pixels (idx 3/4) still adjusted by common_adjust.
2906        assert!(seg[3] > before[3]);
2907        assert!(seg[4] < before[4]);
2908    }
2909
2910    #[test]
2911    fn mb_filter_skips_when_disabled() {
2912        let mut seg = [10u8, 200, 100, 100, 108, 108, 108, 108];
2913        let before = seg;
2914        mb_filter(0, 5, 255, &mut seg, 0);
2915        assert_eq!(seg, before, "interior difference disables MB filter");
2916    }
2917
2918    #[test]
2919    fn mb_filter_low_hev_modifies_six_pixels() {
2920        // Low-variance edge: the wider filter touches p2,p1,p0,q0,q1,q2.
2921        let mut seg = [100u8, 100, 100, 100, 112, 112, 112, 112];
2922        let before = seg;
2923        mb_filter(50, 100, 255, &mut seg, 0);
2924        // Six interior pixels (idx 1..=6) all move; p3/q3 untouched.
2925        assert!(seg[3] > before[3], "p0");
2926        assert!(seg[4] < before[4], "q0");
2927        assert!(seg[2] >= before[2], "p1");
2928        assert!(seg[5] <= before[5], "q1");
2929        assert!(seg[1] >= before[1], "p2");
2930        assert!(seg[6] <= before[6], "q2");
2931        assert_eq!(seg[0], before[0], "p3 untouched");
2932        assert_eq!(seg[7], before[7], "q3 untouched");
2933    }
2934
2935    #[test]
2936    fn mb_filter_high_hev_falls_back_to_common_adjust() {
2937        // High-variance edge (steep p1->p0 inner gradient, |p1 - p0| = 10
2938        // > 0 against hev_threshold 0): only the inner 4-pixel window is
2939        // adjusted (common_adjust with outer taps); p2/q2 stay put.
2940        let mut seg = [100u8, 100, 100, 110, 120, 120, 120, 120];
2941        let before = seg;
2942        mb_filter(0, 100, 255, &mut seg, 0);
2943        assert_eq!(seg[1], before[1], "p2 untouched under hev");
2944        assert_eq!(seg[6], before[6], "q2 untouched under hev");
2945        // Inner edge pixels (idx 3/4) adjusted by common_adjust.
2946        assert!(seg[3] > before[3]);
2947        assert!(seg[4] < before[4]);
2948    }
2949
2950    #[test]
2951    fn mb_filter_low_hev_hand_derived() {
2952        // Re-derive the §15.3 MBfilter arithmetic for an exact match.
2953        // Segment (unsigned): 100 100 100 100 | 116 116 116 116.
2954        // signed: p3..p0 = -28; q0..q3 = -12.
2955        // hev: |p1 - p0| = 0, |q1 - q0| = 0 -> 0 > threshold(50)? no.
2956        //   So low-variance branch.
2957        // w = c(c(p1 - q1) + 3*(q0 - p0))
2958        //   = c(c(-28 - -12) + 3*(-12 - -28))
2959        //   = c(c(-16) + 3*16) = c(-16 + 48) = c(32) = 32.
2960        // a0 = c((27*32 + 63) >> 7) = c((864 + 63) >> 7) = c(927 >> 7)
2961        //    = c(7) = 7.  Q0 = s2u(-12 - 7) = s2u(-19) = 109;
2962        //    P0 = s2u(-28 + 7) = s2u(-21) = 107.
2963        // a1 = c((18*32 + 63) >> 7) = c((576 + 63) >> 7) = c(639 >> 7)
2964        //    = c(4) = 4.  Q1 = s2u(-12 - 4) = 112; P1 = s2u(-28 + 4) = 104.
2965        // a2 = c((9*32 + 63) >> 7) = c((288 + 63) >> 7) = c(351 >> 7)
2966        //    = c(2) = 2.  Q2 = s2u(-12 - 2) = 114; P2 = s2u(-28 + 2) = 102.
2967        let mut seg = [100u8, 100, 100, 100, 116, 116, 116, 116];
2968        mb_filter(50, 100, 255, &mut seg, 0);
2969        assert_eq!(seg, [100, 102, 104, 107, 109, 112, 114, 116]);
2970    }
2971
2972    #[test]
2973    fn filter_routines_respect_base_offset() {
2974        // The same filtering applied at a non-zero base must leave the
2975        // surrounding buffer untouched and operate on the window.
2976        let mut seg = vec![7u8; 12];
2977        seg[2..10].copy_from_slice(&[100, 100, 100, 100, 116, 116, 116, 116]);
2978        mb_filter(50, 100, 255, &mut seg, 2);
2979        // Guard bytes intact.
2980        assert_eq!(&seg[0..2], &[7, 7]);
2981        assert_eq!(&seg[10..12], &[7, 7]);
2982        // Window matches the hand-derived result above.
2983        assert_eq!(&seg[2..10], &[100, 102, 104, 107, 109, 112, 114, 116]);
2984    }
2985
2986    // ----- §15.1 / §20.6 per-MB filter-level derivation ----------------
2987    // KeyframePlanes, MbCoeffs, IntraYMode and MacroblockModes come in via
2988    // `use super::*`; IntraUvMode is only needed by the test helpers.
2989    use crate::macroblock::IntraUvMode;
2990
2991    fn base_config() -> FrameFilterConfig {
2992        FrameFilterConfig {
2993            simple: false,
2994            key_frame: true,
2995            loop_filter_level: 20,
2996            sharpness_level: 0,
2997            segmentation_enabled: false,
2998            segment_abs: false,
2999            segment_lf_level: [0; MAX_MB_SEGMENTS],
3000            delta_enabled: false,
3001            ref_delta_current: 0,
3002            bpred_mode_delta: 0,
3003            ref_delta_last: 0,
3004            ref_delta_golden: 0,
3005            ref_delta_altref: 0,
3006            zero_mv_mode_delta: 0,
3007            other_mv_mode_delta: 0,
3008            split_mv_mode_delta: 0,
3009        }
3010    }
3011
3012    fn flat_planes(value: u8, mb_cols: usize, mb_rows: usize) -> KeyframePlanes {
3013        let y_stride = mb_cols * 16;
3014        let uv_stride = mb_cols * 8;
3015        KeyframePlanes {
3016            y: vec![value; y_stride * mb_rows * 16],
3017            u: vec![value; uv_stride * mb_rows * 8],
3018            v: vec![value; uv_stride * mb_rows * 8],
3019            y_stride,
3020            uv_stride,
3021            mb_cols,
3022            mb_rows,
3023        }
3024    }
3025
3026    fn mode(y_mode: IntraYMode, segment_id: Option<u8>) -> MacroblockModes {
3027        MacroblockModes {
3028            segment_id,
3029            mb_skip_coeff: true,
3030            y_mode,
3031            subblock_modes: None,
3032            uv_mode: IntraUvMode::Dc,
3033        }
3034    }
3035
3036    #[test]
3037    fn mb_filter_level_no_overrides_is_base() {
3038        let c = base_config();
3039        assert_eq!(calculate_mb_filter_level(&c, None, IntraYMode::Dc), 20);
3040        // segment_id ignored when segmentation disabled.
3041        assert_eq!(calculate_mb_filter_level(&c, Some(3), IntraYMode::Dc), 20);
3042    }
3043
3044    #[test]
3045    fn mb_filter_level_segment_delta_adds() {
3046        let mut c = base_config();
3047        c.segmentation_enabled = true;
3048        c.segment_abs = false;
3049        c.segment_lf_level = [5, -8, 0, 0];
3050        // segment 0: 20 + 5 = 25.
3051        assert_eq!(calculate_mb_filter_level(&c, Some(0), IntraYMode::Dc), 25);
3052        // segment 1: 20 + (-8) = 12.
3053        assert_eq!(calculate_mb_filter_level(&c, Some(1), IntraYMode::Dc), 12);
3054    }
3055
3056    #[test]
3057    fn mb_filter_level_segment_absolute_replaces() {
3058        let mut c = base_config();
3059        c.segmentation_enabled = true;
3060        c.segment_abs = true;
3061        c.segment_lf_level = [40, 0, 63, 7];
3062        // absolute mode replaces the base entirely.
3063        assert_eq!(calculate_mb_filter_level(&c, Some(0), IntraYMode::Dc), 40);
3064        assert_eq!(calculate_mb_filter_level(&c, Some(2), IntraYMode::Dc), 63);
3065        // absolute 0 -> level 0 (caller then skips the MB).
3066        assert_eq!(calculate_mb_filter_level(&c, Some(1), IntraYMode::Dc), 0);
3067    }
3068
3069    #[test]
3070    fn mb_filter_level_segment_clamps_before_deltas() {
3071        // §20.6 clamps to 0..=63 after the segment override and again
3072        // after the deltas. A segment delta that overshoots saturates.
3073        let mut c = base_config();
3074        c.segmentation_enabled = true;
3075        c.segment_abs = false;
3076        c.segment_lf_level = [60, -40, 0, 0];
3077        // 20 + 60 = 80 -> clamp 63.
3078        assert_eq!(calculate_mb_filter_level(&c, Some(0), IntraYMode::Dc), 63);
3079        // 20 - 40 = -20 -> clamp 0.
3080        assert_eq!(calculate_mb_filter_level(&c, Some(1), IntraYMode::Dc), 0);
3081    }
3082
3083    #[test]
3084    fn mb_filter_level_ref_and_bpred_mode_deltas() {
3085        let mut c = base_config();
3086        c.delta_enabled = true;
3087        c.ref_delta_current = 4;
3088        c.bpred_mode_delta = -3;
3089        // Non-B_PRED: only the reference delta applies. 20 + 4 = 24.
3090        assert_eq!(calculate_mb_filter_level(&c, None, IntraYMode::Dc), 24);
3091        // B_PRED: ref + mode. 20 + 4 - 3 = 21.
3092        assert_eq!(calculate_mb_filter_level(&c, None, IntraYMode::B), 21);
3093    }
3094
3095    #[test]
3096    fn mb_filter_level_deltas_clamp_at_ends() {
3097        let mut c = base_config();
3098        c.loop_filter_level = 62;
3099        c.delta_enabled = true;
3100        c.ref_delta_current = 10; // 62 + 10 = 72 -> clamp 63.
3101        assert_eq!(calculate_mb_filter_level(&c, None, IntraYMode::Dc), 63);
3102        c.loop_filter_level = 2;
3103        c.ref_delta_current = -10; // 2 - 10 = -8 -> clamp 0.
3104        assert_eq!(calculate_mb_filter_level(&c, None, IntraYMode::Dc), 0);
3105    }
3106
3107    #[test]
3108    fn mb_filter_level_deltas_disabled_when_flag_off() {
3109        let mut c = base_config();
3110        c.delta_enabled = false;
3111        c.ref_delta_current = 30;
3112        c.bpred_mode_delta = 30;
3113        // Both deltas ignored.
3114        assert_eq!(calculate_mb_filter_level(&c, None, IntraYMode::B), 20);
3115    }
3116
3117    // ----- §15.1 frame geometry ----------------------------------------
3118
3119    #[test]
3120    fn filter_frame_level_zero_is_noop() {
3121        let mut c = base_config();
3122        c.loop_filter_level = 0;
3123        // Two MBs with a sharp boundary; level 0 must leave them alone.
3124        let mut planes = flat_planes(100, 2, 1);
3125        for px in planes.y[16..32].iter_mut() {
3126            *px = 200;
3127        }
3128        let before = planes.clone();
3129        let modes = vec![mode(IntraYMode::Dc, None), mode(IntraYMode::Dc, None)];
3130        let coeffs = vec![MbCoeffs::default(); 2];
3131        filter_frame(&mut planes, &modes, &coeffs, &c);
3132        assert_eq!(planes, before, "level 0 must skip filtering entirely");
3133    }
3134
3135    #[test]
3136    fn filter_frame_normal_mb_edge_hand_derived() {
3137        // A 2×1 luma frame: MB(0,0) flat 100, MB(0,1) flat 110. Skip
3138        // coeffs so the subblock steps are skipped, isolating MB(0,1)'s
3139        // left inter-MB vertical edge (frame column 16). The normal MB
3140        // filter's wide low-variance branch rewrites p2,p1,p0,q0,q1,q2
3141        // (columns 13..=18) to the hand-derived values; everything else
3142        // is untouched.
3143        //
3144        // level 20, sharpness 0, key frame:
3145        //   interior_limit = 20, mbedge_limit = (20+2)*2+20 = 64,
3146        //   hev_threshold = 1 (level >= 15).
3147        // signed p* = -28, q* = -18; |p1-p0| = |q1-q0| = 0 -> low var.
3148        // w = c(c(-28 - -18) + 3*(-18 - -28)) = c(c(-10) + 30) = c(20) = 20.
3149        // a0 = c((27*20+63)>>7) = c(4) = 4: P0=104, Q0=106.
3150        // a1 = c((18*20+63)>>7) = c(3) = 3: P1=105, Q1=107.
3151        // a2 = c((9*20+63)>>7)  = c(1) = 1: P2=103, Q2=109.
3152        let c = base_config();
3153        let mut planes = flat_planes(100, 2, 1);
3154        for r in 0..16 {
3155            for px in planes.y[r * 32 + 16..r * 32 + 32].iter_mut() {
3156                *px = 110;
3157            }
3158        }
3159        let before = planes.clone();
3160        let modes = vec![mode(IntraYMode::Dc, None), mode(IntraYMode::Dc, None)];
3161        let coeffs = vec![MbCoeffs::default(); 2]; // no coeffs -> steps 2/4 skipped
3162        filter_frame(&mut planes, &modes, &coeffs, &c);
3163
3164        // The six pixels straddling column 16 on every row are rewritten.
3165        // Columns 13,14,15 = P2,P1,P0; columns 16,17,18 = Q0,Q1,Q2.
3166        for r in 0..16 {
3167            let row = r * 32;
3168            assert_eq!(planes.y[row + 13], 101, "P2 row {r}");
3169            assert_eq!(planes.y[row + 14], 103, "P1 row {r}");
3170            assert_eq!(planes.y[row + 15], 104, "P0 row {r}");
3171            assert_eq!(planes.y[row + 16], 106, "Q0 row {r}");
3172            assert_eq!(planes.y[row + 17], 107, "Q1 row {r}");
3173            assert_eq!(planes.y[row + 18], 109, "Q2 row {r}");
3174            // Columns away from the edge are untouched.
3175            assert_eq!(planes.y[row + 12], before.y[row + 12]);
3176            assert_eq!(planes.y[row + 19], before.y[row + 19]);
3177            assert_eq!(planes.y[row], 100);
3178            assert_eq!(planes.y[row + 31], 110);
3179        }
3180        // Chroma planes are flat (both MBs same value) -> unchanged.
3181        assert_eq!(planes.u, before.u);
3182        assert_eq!(planes.v, before.v);
3183    }
3184
3185    #[test]
3186    fn filter_frame_leftmost_mb_skips_left_edge() {
3187        // A single-MB-wide frame stacked 2 rows: MB(0,0) flat 100,
3188        // MB(1,0) flat 120. There is no left inter-MB edge for either MB
3189        // (both are on the leftmost column), so step 1 is skipped; the
3190        // top inter-MB edge of MB(1,0) (frame row 16) is filtered.
3191        let c = base_config();
3192        let mut planes = flat_planes(100, 1, 2);
3193        for px in planes.y[16 * 16..32 * 16].iter_mut() {
3194            *px = 120;
3195        }
3196        // Also flatten chroma rows: MB(1,0) chroma 120 to exercise the
3197        // horizontal chroma edge.
3198        for px in planes.u[8 * 8..16 * 8].iter_mut() {
3199            *px = 120;
3200        }
3201        for px in planes.v[8 * 8..16 * 8].iter_mut() {
3202            *px = 120;
3203        }
3204        let before = planes.clone();
3205        let modes = vec![mode(IntraYMode::Dc, None), mode(IntraYMode::Dc, None)];
3206        let coeffs = vec![MbCoeffs::default(); 2];
3207        filter_frame(&mut planes, &modes, &coeffs, &c);
3208
3209        // No vertical edge is ever filtered (both MBs are leftmost and
3210        // skip coeffs disable internal subblock edges), so every row's
3211        // far-from-the-horizontal-edge pixels are untouched: rows 0..=12
3212        // and 19..=31 stay exactly at their original flat fills. The
3213        // horizontal MB edge at luma row 16 rewrites rows 13..=18.
3214        for r in 0..13 {
3215            for col in 0..16 {
3216                assert_eq!(
3217                    planes.y[r * 16 + col],
3218                    before.y[r * 16 + col],
3219                    "row {r} col {col} (above horizontal edge influence) untouched"
3220                );
3221            }
3222        }
3223        for r in 19..32 {
3224            for col in 0..16 {
3225                assert_eq!(
3226                    planes.y[r * 16 + col],
3227                    before.y[r * 16 + col],
3228                    "row {r} col {col} (below horizontal edge influence) untouched"
3229                );
3230            }
3231        }
3232        // The horizontal MB edge at luma row 16 changed the pixels above
3233        // and below it (including column 0 — horizontal edges span the
3234        // full MB width, so the leftmost column IS a p/q here).
3235        assert_ne!(planes.y[15 * 16], before.y[15 * 16], "P-side col0 moved");
3236        assert_ne!(planes.y[16 * 16], before.y[16 * 16], "Q-side col0 moved");
3237        // Chroma horizontal edge at chroma row 8 also moved.
3238        assert_ne!(planes.u[7 * 8 + 3], before.u[7 * 8 + 3]);
3239        assert_ne!(planes.v[8 * 8 + 3], before.v[8 * 8 + 3]);
3240    }
3241
3242    #[test]
3243    fn filter_frame_simple_touches_only_luma() {
3244        // Simple filter: a 2×1 frame with a luma step. Only luma is
3245        // touched; chroma (even if it had a step) is left alone.
3246        let mut c = base_config();
3247        c.simple = true;
3248        let mut planes = flat_planes(100, 2, 1);
3249        for r in 0..16 {
3250            for px in planes.y[r * 32 + 16..r * 32 + 32].iter_mut() {
3251                *px = 110;
3252            }
3253        }
3254        // Introduce a chroma step too — the simple filter must ignore it.
3255        for r in 0..8 {
3256            for px in planes.u[r * 16 + 8..r * 16 + 16].iter_mut() {
3257                *px = 130;
3258            }
3259        }
3260        let before = planes.clone();
3261        let modes = vec![mode(IntraYMode::Dc, None), mode(IntraYMode::Dc, None)];
3262        let coeffs = vec![MbCoeffs::default(); 2];
3263        filter_frame(&mut planes, &modes, &coeffs, &c);
3264
3265        // Luma changed at the MB edge (column 16).
3266        assert_ne!(planes.y[15], before.y[15], "luma P0 moved");
3267        assert_ne!(planes.y[16], before.y[16], "luma Q0 moved");
3268        // Chroma untouched by the simple filter.
3269        assert_eq!(planes.u, before.u, "simple filter must not touch U");
3270        assert_eq!(planes.v, before.v, "simple filter must not touch V");
3271    }
3272
3273    #[test]
3274    fn filter_frame_subblock_steps_gated_by_coeffs() {
3275        // A single non-skip MB (mode DC) with a synthetic internal luma
3276        // ramp. With no coded coefficients the internal subblock edges
3277        // must be skipped (the §15.1 page-86 rule); with a coefficient
3278        // present they run and modify the interior.
3279        let c = base_config();
3280        // Build a luma plane with a step at internal vertical edge x=8
3281        // (the 1/2 subblock edge), flat elsewhere within the MB.
3282        let mut planes = flat_planes(100, 1, 1);
3283        for r in 0..16 {
3284            for col in 8..16 {
3285                planes.y[r * 16 + col] = 112;
3286            }
3287        }
3288        let modes = vec![mode(IntraYMode::Dc, None)];
3289
3290        // No coefficients -> steps 2/4 skipped -> the internal edge at
3291        // column 8 is NOT filtered.
3292        let mut p_skip = planes.clone();
3293        filter_frame(&mut p_skip, &modes, &[MbCoeffs::default()], &c);
3294        assert_eq!(
3295            p_skip, planes,
3296            "no coeffs: internal subblock edges must be skipped (top-left MB has no MB edges either)"
3297        );
3298
3299        // A single coded coefficient -> steps 2/4 run -> column 8 edge
3300        // gets filtered.
3301        let mut coeffs = MbCoeffs::default();
3302        coeffs.y[0][1] = 7; // any non-zero coefficient flags coded data
3303        let mut p_run = planes.clone();
3304        filter_frame(&mut p_run, &modes, &[coeffs], &c);
3305        assert_ne!(
3306            p_run, planes,
3307            "coded coeff: internal subblock edge must be filtered"
3308        );
3309        // The change is localized around column 8.
3310        assert_ne!(p_run.y[7], planes.y[7], "P0 of x=8 edge moved");
3311        assert_ne!(p_run.y[8], planes.y[8], "Q0 of x=8 edge moved");
3312    }
3313
3314    #[test]
3315    fn filter_frame_bpred_runs_subblocks_without_coeffs() {
3316        // A B_PRED MB triggers the subblock steps even with no coded
3317        // coefficients (mode B_PRED satisfies the §15.1 page-86 rule).
3318        let c = base_config();
3319        let mut planes = flat_planes(100, 1, 1);
3320        for r in 0..16 {
3321            for col in 8..16 {
3322                planes.y[r * 16 + col] = 112;
3323            }
3324        }
3325        let modes = vec![mode(IntraYMode::B, None)];
3326        let mut p = planes.clone();
3327        filter_frame(&mut p, &modes, &[MbCoeffs::default()], &c);
3328        assert_ne!(
3329            p, planes,
3330            "B_PRED MB must filter internal subblock edges even when skip"
3331        );
3332    }
3333
3334    /// Build a textured `mb_cols × mb_rows` plane set with a value step at
3335    /// every internal subblock edge so steps 2/4 visibly move pixels when
3336    /// they run.
3337    fn textured_planes(mb_cols: usize, mb_rows: usize) -> KeyframePlanes {
3338        let mut p = flat_planes(100, mb_cols, mb_rows);
3339        let ys = p.y_stride;
3340        for r in 0..mb_rows * 16 {
3341            for col in 0..mb_cols * 16 {
3342                // Saw-tooth on a 4-pixel period — straddles every 4-pixel
3343                // subblock edge and the 16-pixel MB edges.
3344                p.y[r * ys + col] = 96 + ((col / 4 + r / 4) % 5) as u8 * 8;
3345            }
3346        }
3347        let cs = p.uv_stride;
3348        for r in 0..mb_rows * 8 {
3349            for col in 0..mb_cols * 8 {
3350                p.u[r * cs + col] = 90 + ((col / 4 + r / 4) % 4) as u8 * 10;
3351                p.v[r * cs + col] = 130 - ((col / 4 + r / 4) % 4) as u8 * 10;
3352            }
3353        }
3354        p
3355    }
3356
3357    #[test]
3358    fn filter_frame_flags_matches_coeffs() {
3359        // The flag-driven `filter_frame_flags` must be byte-for-byte
3360        // identical to the public `filter_frame` for every combination of
3361        // per-MB coeff occupancy × mode × config (simple/normal).
3362        let mb_cols = 3;
3363        let mb_rows = 2;
3364        let n = mb_cols * mb_rows;
3365        let y_modes = [
3366            IntraYMode::Dc,
3367            IntraYMode::V,
3368            IntraYMode::H,
3369            IntraYMode::Tm,
3370            IntraYMode::B,
3371            IntraYMode::Dc,
3372        ];
3373        for &simple in &[false, true] {
3374            let mut c = base_config();
3375            c.simple = simple;
3376            // Sweep every occupancy bitmask over the n MBs.
3377            for mask in 0u32..(1 << n) {
3378                let modes: Vec<_> = (0..n).map(|i| mode(y_modes[i], None)).collect();
3379                let coeffs: Vec<MbCoeffs> = (0..n)
3380                    .map(|i| {
3381                        let mut mc = MbCoeffs::default();
3382                        if (mask >> i) & 1 == 1 {
3383                            // A single non-zero AC coefficient flags coded data.
3384                            mc.y[0][1] = 9;
3385                        }
3386                        mc
3387                    })
3388                    .collect();
3389                let flags: Vec<bool> = coeffs.iter().map(mb_has_coeffs).collect();
3390
3391                let mut p_coeffs = textured_planes(mb_cols, mb_rows);
3392                let mut p_flags = p_coeffs.clone();
3393                filter_frame(&mut p_coeffs, &modes, &coeffs, &c);
3394                filter_frame_flags(&mut p_flags, &modes, &flags, &c);
3395                assert_eq!(
3396                    p_coeffs, p_flags,
3397                    "filter_frame_flags must match filter_frame (simple={simple}, mask={mask:#b})"
3398                );
3399            }
3400        }
3401    }
3402
3403    /// The row-band threaded filter equals the raster-order pass for
3404    /// every frame shape, filter type, mix of filtered / unfiltered
3405    /// macroblocks and thread count.
3406    #[test]
3407    fn banded_filter_matches_serial() {
3408        use crate::motion_comp::RefFrame;
3409        use crate::near_mv::InterMode;
3410        let mut lcg = 0x9E37_79B9u32;
3411        let mut next = move || {
3412            lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
3413            lcg >> 16
3414        };
3415        for (mb_cols, mb_rows) in [(1usize, 2usize), (2, 2), (5, 3), (3, 7), (9, 6)] {
3416            let n = mb_cols * mb_rows;
3417            for case in 0..6 {
3418                let mut planes = KeyframePlanes {
3419                    y: (0..n * 256).map(|_| next() as u8).collect(),
3420                    u: (0..n * 64).map(|_| next() as u8).collect(),
3421                    v: (0..n * 64).map(|_| next() as u8).collect(),
3422                    y_stride: mb_cols * 16,
3423                    uv_stride: mb_cols * 8,
3424                    mb_cols,
3425                    mb_rows,
3426                };
3427                // Smooth most of the picture so the filters engage.
3428                for (i, p) in planes.y.iter_mut().enumerate() {
3429                    *p = (*p % 24) + ((i / 7) % 200) as u8;
3430                }
3431                let modes: Vec<_> = (0..n)
3432                    .map(|_| {
3433                        mode(
3434                            [IntraYMode::Dc, IntraYMode::B, IntraYMode::V][next() as usize % 3],
3435                            None,
3436                        )
3437                    })
3438                    .collect();
3439                let has_coeffs: Vec<bool> = (0..n).map(|_| next() % 3 == 0).collect();
3440                let refs: Vec<Option<RefFrame>> = (0..n)
3441                    .map(|_| {
3442                        [None, Some(RefFrame::Last), Some(RefFrame::Golden)][next() as usize % 3]
3443                    })
3444                    .collect();
3445                let inter: Vec<Option<InterMode>> = refs
3446                    .iter()
3447                    .map(|r| {
3448                        r.map(|_| {
3449                            [InterMode::Zero, InterMode::New, InterMode::Split][next() as usize % 3]
3450                        })
3451                    })
3452                    .collect();
3453                let mut c = base_config();
3454                c.key_frame = false;
3455                c.simple = case % 2 == 1;
3456                c.loop_filter_level = [9, 30, 63][case / 2];
3457                c.sharpness_level = (case % 4) as u8;
3458                c.delta_enabled = case >= 2;
3459                c.ref_delta_current = -40;
3460                c.ref_delta_golden = 12;
3461                c.zero_mv_mode_delta = -6;
3462                let mut want = planes.clone();
3463                filter_inter_frame_flags(&mut want, &modes, &has_coeffs, &refs, &inter, &c);
3464                assert_ne!(want.y, planes.y, "the filter did something");
3465                for threads in [2usize, 3, 8] {
3466                    let mut got = planes.clone();
3467                    filter_inter_frame_flags_threaded(
3468                        &mut got,
3469                        &modes,
3470                        &has_coeffs,
3471                        &refs,
3472                        &inter,
3473                        &c,
3474                        threads,
3475                    );
3476                    assert_eq!(
3477                        got.y, want.y,
3478                        "{mb_cols}x{mb_rows} case {case} threads {threads}"
3479                    );
3480                    assert_eq!(
3481                        got.u, want.u,
3482                        "{mb_cols}x{mb_rows} case {case} threads {threads}"
3483                    );
3484                    assert_eq!(
3485                        got.v, want.v,
3486                        "{mb_cols}x{mb_rows} case {case} threads {threads}"
3487                    );
3488                }
3489                // Key-frame flavour.
3490                c.key_frame = true;
3491                let mut want = planes.clone();
3492                filter_frame_flags(&mut want, &modes, &has_coeffs, &c);
3493                let mut got = planes.clone();
3494                filter_frame_flags_threaded(&mut got, &modes, &has_coeffs, &c, 4);
3495                assert_eq!(got.y, want.y, "key {mb_cols}x{mb_rows} case {case}");
3496                assert_eq!(got.u, want.u, "key {mb_cols}x{mb_rows} case {case}");
3497                assert_eq!(got.v, want.v, "key {mb_cols}x{mb_rows} case {case}");
3498            }
3499        }
3500    }
3501
3502    #[test]
3503    fn filter_inter_frame_flags_matches_coeffs() {
3504        use crate::motion_comp::RefFrame;
3505        use crate::near_mv::InterMode;
3506        let mb_cols = 3;
3507        let mb_rows = 2;
3508        let n = mb_cols * mb_rows;
3509        let y_modes = [
3510            IntraYMode::Dc,
3511            IntraYMode::B, // mapped SPLITMV
3512            IntraYMode::V,
3513            IntraYMode::Dc,
3514            IntraYMode::H,
3515            IntraYMode::Tm,
3516        ];
3517        let refs = [
3518            Some(RefFrame::Last),
3519            Some(RefFrame::Golden),
3520            None,
3521            Some(RefFrame::AltRef),
3522            Some(RefFrame::Last),
3523            None,
3524        ];
3525        let inter = [
3526            Some(InterMode::Zero),
3527            Some(InterMode::Split),
3528            None,
3529            Some(InterMode::New),
3530            Some(InterMode::Nearest),
3531            None,
3532        ];
3533        let mut c = base_config();
3534        c.key_frame = false;
3535        for &simple in &[false, true] {
3536            c.simple = simple;
3537            for mask in 0u32..(1 << n) {
3538                let modes: Vec<_> = (0..n).map(|i| mode(y_modes[i], None)).collect();
3539                let coeffs: Vec<MbCoeffs> = (0..n)
3540                    .map(|i| {
3541                        let mut mc = MbCoeffs::default();
3542                        if (mask >> i) & 1 == 1 {
3543                            mc.u[0][2] = 5;
3544                        }
3545                        mc
3546                    })
3547                    .collect();
3548                let flags: Vec<bool> = coeffs.iter().map(mb_has_coeffs).collect();
3549
3550                let mut p_coeffs = textured_planes(mb_cols, mb_rows);
3551                let mut p_flags = p_coeffs.clone();
3552                filter_inter_frame(&mut p_coeffs, &modes, &coeffs, &refs, &inter, &c);
3553                filter_inter_frame_flags(&mut p_flags, &modes, &flags, &refs, &inter, &c);
3554                assert_eq!(
3555                    p_coeffs, p_flags,
3556                    "filter_inter_frame_flags must match filter_inter_frame (simple={simple}, mask={mask:#b})"
3557                );
3558            }
3559        }
3560    }
3561
3562    #[test]
3563    fn filter_frame_config_keyframe_resolves_header() {
3564        // FrameFilterConfig::keyframe pulls the level inputs out of a
3565        // parsed header. Build a minimal header by hand and check the
3566        // resolved config.
3567        use crate::coded_header::{MbLfAdjustments, UpdateSegmentation};
3568
3569        let mut header = minimal_header();
3570        header.filter_type = true; // simple
3571        header.loop_filter_level = 31;
3572        header.sharpness_level = 5;
3573        header.segmentation_enabled = true;
3574        header.update_segmentation = Some(UpdateSegmentation {
3575            update_mb_segmentation_map: true,
3576            update_segment_feature_data: true,
3577            segment_feature_mode_absolute: true,
3578            quantizer_update: [None; 4],
3579            loop_filter_update: [Some(10), None, Some(-4), Some(63)],
3580            segment_prob: [None; 3],
3581        });
3582        header.mb_lf_adjustments = MbLfAdjustments {
3583            loop_filter_adj_enable: true,
3584            mode_ref_lf_delta_update: true,
3585            ref_frame_delta_update: [Some(2), None, None, None],
3586            mb_mode_delta_update: [Some(-5), None, None, None],
3587        };
3588
3589        let cfg = FrameFilterConfig::keyframe(&header);
3590        assert!(cfg.simple);
3591        assert!(cfg.key_frame);
3592        assert_eq!(cfg.loop_filter_level, 31);
3593        assert_eq!(cfg.sharpness_level, 5);
3594        assert!(cfg.segmentation_enabled);
3595        assert!(cfg.segment_abs);
3596        assert_eq!(cfg.segment_lf_level, [10, 0, -4, 63]);
3597        assert!(cfg.delta_enabled);
3598        assert_eq!(cfg.ref_delta_current, 2);
3599        assert_eq!(cfg.bpred_mode_delta, -5);
3600    }
3601
3602    #[test]
3603    fn filter_frame_config_keyframe_no_segmentation() {
3604        let header = minimal_header();
3605        let cfg = FrameFilterConfig::keyframe(&header);
3606        assert!(!cfg.segmentation_enabled);
3607        assert_eq!(cfg.segment_lf_level, [0; MAX_MB_SEGMENTS]);
3608        assert!(!cfg.delta_enabled);
3609        assert_eq!(cfg.ref_delta_current, 0);
3610        assert_eq!(cfg.bpred_mode_delta, 0);
3611    }
3612
3613    /// A minimal `Vp8CodedHeader` with the loop-filter knobs zeroed,
3614    /// used by the `FrameFilterConfig::keyframe` resolution tests.
3615    fn minimal_header() -> crate::Vp8CodedHeader {
3616        use crate::coded_header::{MbLfAdjustments, QuantIndices};
3617        crate::Vp8CodedHeader {
3618            color_space: Some(false),
3619            clamping_type: Some(false),
3620            segmentation_enabled: false,
3621            update_segmentation: None,
3622            filter_type: false,
3623            loop_filter_level: 0,
3624            sharpness_level: 0,
3625            mb_lf_adjustments: MbLfAdjustments {
3626                loop_filter_adj_enable: false,
3627                mode_ref_lf_delta_update: false,
3628                ref_frame_delta_update: [None; 4],
3629                mb_mode_delta_update: [None; 4],
3630            },
3631            log2_nbr_of_dct_partitions: 0,
3632            nbr_of_dct_partitions: 1,
3633            quant_indices: QuantIndices {
3634                y_ac_qi: 0,
3635                y_dc_delta: None,
3636                y2_dc_delta: None,
3637                y2_ac_delta: None,
3638                uv_dc_delta: None,
3639                uv_ac_delta: None,
3640            },
3641            refresh_entropy_probs: false,
3642            refresh_golden_frame: None,
3643            refresh_alternate_frame: None,
3644            copy_buffer_to_golden: None,
3645            copy_buffer_to_alternate: None,
3646            sign_bias_golden: None,
3647            sign_bias_alternate: None,
3648            refresh_last: None,
3649            token_prob_updates: [[[[None; 11]; 3]; 8]; 4],
3650            mb_no_skip_coeff: false,
3651            prob_skip_false: None,
3652            prob_intra: None,
3653            prob_last: None,
3654            prob_gf: None,
3655            intra_y_mode_prob_update: None,
3656            intra_uv_mode_prob_update: None,
3657            mv_prob_update: None,
3658        }
3659    }
3660
3661    // ----- §9.4 RD loop-filter-level selection -------------------------
3662
3663    /// A reconstruction that flat-matches its source: no block-edge error,
3664    /// so any filtering can only spread error and the selector must pick
3665    /// level 0.
3666    #[test]
3667    fn select_filter_level_flat_source_picks_zero() {
3668        let mb_cols = 2;
3669        let mb_rows = 2;
3670        let n = mb_cols * mb_rows;
3671        let planes = flat_planes(120, mb_cols, mb_rows);
3672        let modes: Vec<_> = (0..n).map(|_| mode(IntraYMode::Dc, None)).collect();
3673        let has_coeffs = vec![true; n]; // pretend every MB coded, so subblock edges are eligible
3674        let cfg = base_config();
3675        // Source equals the reconstruction exactly.
3676        let src = SourcePlanes {
3677            width: mb_cols * 16,
3678            height: mb_rows * 16,
3679            y: &planes.y,
3680            u: &planes.u,
3681            v: &planes.v,
3682            y_stride: planes.y_stride,
3683            uv_stride: planes.uv_stride,
3684        };
3685        let level = select_filter_level(&planes, &modes, &has_coeffs, &cfg, &src, None);
3686        assert_eq!(level, 0, "flat lossless reconstruction wants no filtering");
3687        // And the SSD at the chosen level is exactly zero.
3688        assert_eq!(reconstruction_ssd(&planes, &src), 0);
3689    }
3690
3691    /// A reconstruction with a sharp inter-MB-edge step the source does
3692    /// NOT have: filtering smooths the step toward the (smooth) source, so
3693    /// the selector must engage at a non-zero level and the chosen level's
3694    /// SSD must beat the unfiltered SSD.
3695    #[test]
3696    fn select_filter_level_engages_on_block_edge() {
3697        let mb_cols = 2;
3698        let mb_rows = 1;
3699        let n = mb_cols * mb_rows;
3700        // Reconstruction: left MB at 100, right MB at 160 — a hard 60-level
3701        // step down the shared vertical MB edge at column 16.
3702        let mut planes = flat_planes(100, mb_cols, mb_rows);
3703        let ys = planes.y_stride;
3704        for r in 0..mb_rows * 16 {
3705            for col in 16..mb_cols * 16 {
3706                planes.y[r * ys + col] = 160;
3707            }
3708        }
3709        // Source: a gentle ramp across the same edge (no hard step), so the
3710        // reconstruction's block edge is genuine coding error the filter
3711        // can shave toward the truth.
3712        let mut src_y = vec![0u8; ys * mb_rows * 16];
3713        for r in 0..mb_rows * 16 {
3714            for col in 0..mb_cols * 16 {
3715                // 100 on the far left climbing to 160 on the far right.
3716                src_y[r * ys + col] = (100 + col * 60 / (mb_cols * 16 - 1)) as u8;
3717            }
3718        }
3719        // Chroma source = reconstruction (no chroma error to confound the Y
3720        // signal).
3721        let src = SourcePlanes {
3722            width: mb_cols * 16,
3723            height: mb_rows * 16,
3724            y: &src_y,
3725            u: &planes.u,
3726            v: &planes.v,
3727            y_stride: ys,
3728            uv_stride: planes.uv_stride,
3729        };
3730        let modes: Vec<_> = (0..n).map(|_| mode(IntraYMode::Dc, None)).collect();
3731        let has_coeffs = vec![true; n];
3732        let cfg = base_config();
3733
3734        let unfiltered = reconstruction_ssd(&planes, &src);
3735        let level = select_filter_level(&planes, &modes, &has_coeffs, &cfg, &src, None);
3736        assert!(
3737            level > 0,
3738            "a hard block edge against a smooth source must engage the filter, got level {level}"
3739        );
3740
3741        // The chosen level must actually reduce the SSD vs unfiltered.
3742        let mut filtered = planes.clone();
3743        let mut fc = cfg;
3744        fc.loop_filter_level = level;
3745        filter_frame_flags(&mut filtered, &modes, &has_coeffs, &fc);
3746        let after = reconstruction_ssd(&filtered, &src);
3747        assert!(
3748            after < unfiltered,
3749            "chosen level {level} SSD {after} must beat unfiltered {unfiltered}"
3750        );
3751
3752        // The joint (level, sharpness) selector must agree with the
3753        // level-only one on its level and return an in-range sharpness, and
3754        // its chosen pair must score no worse than the level-only result.
3755        let (jl, js) = select_filter_params(&planes, &modes, &has_coeffs, &cfg, &src, None);
3756        assert_eq!(
3757            jl, level,
3758            "joint selector level agrees with select_filter_level"
3759        );
3760        assert!(js <= 7, "sharpness {js} in §9.4 range");
3761        let mut jf = planes.clone();
3762        let mut jc = cfg;
3763        jc.loop_filter_level = jl;
3764        jc.sharpness_level = js;
3765        filter_frame_flags(&mut jf, &modes, &has_coeffs, &jc);
3766        let joint_ssd = reconstruction_ssd(&jf, &src);
3767        assert!(
3768            joint_ssd <= after,
3769            "joint (level={jl}, sharp={js}) SSD {joint_ssd} must not exceed level-only {after}"
3770        );
3771    }
3772
3773    #[test]
3774    fn select_filter_params_flat_source_picks_zero_level() {
3775        let mb_cols = 2;
3776        let mb_rows = 2;
3777        let n = mb_cols * mb_rows;
3778        let planes = flat_planes(120, mb_cols, mb_rows);
3779        let modes: Vec<_> = (0..n).map(|_| mode(IntraYMode::Dc, None)).collect();
3780        let has_coeffs = vec![true; n];
3781        let mut cfg = base_config();
3782        cfg.sharpness_level = 3; // non-default base sharpness
3783        let src = SourcePlanes {
3784            width: mb_cols * 16,
3785            height: mb_rows * 16,
3786            y: &planes.y,
3787            u: &planes.u,
3788            v: &planes.v,
3789            y_stride: planes.y_stride,
3790            uv_stride: planes.uv_stride,
3791        };
3792        let (level, sharp) = select_filter_params(&planes, &modes, &has_coeffs, &cfg, &src, None);
3793        assert_eq!(level, 0, "lossless flat reconstruction wants no filtering");
3794        // Level 0 ⇒ sharpness irrelevant; the base sharpness is returned.
3795        assert_eq!(sharp, 3, "base sharpness returned when level is 0");
3796    }
3797
3798    // ----- §15 SIMD kernel byte-exactness ------------------------------
3799    //
3800    // The SIMD kernels must reproduce the scalar per-segment kernels
3801    // bit-for-bit on every lane. These tests run only under `--features
3802    // simd`; they drive a deterministic stress matrix of pixel windows
3803    // and filter parameters through both the vector kernel and the
3804    // always-compiled scalar per-segment reference, asserting equality.
3805
3806    #[cfg(feature = "simd")]
3807    fn stress_windows() -> Vec<[u8; 8]> {
3808        // A spread of ramps, flats, spikes and pseudo-random windows that
3809        // exercise both the `filter_yes`/metric-pass and -fail branches
3810        // and both hev polarities.
3811        let mut v = vec![
3812            [120, 122, 124, 126, 130, 132, 134, 136], // gentle ramp (filters)
3813            [10, 12, 14, 16, 240, 242, 244, 246],     // hard step (gate fails)
3814            [128; 8],                                 // flat (filters, no-op)
3815            [126, 127, 128, 129, 130, 131, 132, 133], // tiny ramp
3816            [100, 140, 100, 140, 100, 140, 100, 140], // high interior diff
3817            [0, 0, 0, 255, 255, 255, 255, 255],       // edge spike
3818        ];
3819        let mut s: u32 = 0x1234_5678;
3820        for _ in 0..64 {
3821            let mut w = [0u8; 8];
3822            for slot in w.iter_mut() {
3823                s = s.wrapping_mul(1_103_515_245).wrapping_add(12_345);
3824                *slot = (s >> 16) as u8;
3825            }
3826            v.push(w);
3827        }
3828        v
3829    }
3830
3831    #[cfg(feature = "simd")]
3832    #[test]
3833    fn subblock_filter_simd_matches_scalar() {
3834        use core::simd::Simd;
3835        let windows = stress_windows();
3836        for &(hev_t, ilim, elim) in &[
3837            (0u8, 1u8, 1u8),
3838            (4, 4, 4),
3839            (2, 8, 16),
3840            (10, 30, 60),
3841            (0, 63, 127),
3842        ] {
3843            // Pack 4 windows per vector group; pad with the first window.
3844            let mut idx = 0;
3845            while idx < windows.len() {
3846                let group: [[u8; 8]; 4] =
3847                    core::array::from_fn(|l| windows[(idx + l) % windows.len()]);
3848
3849                // Scalar reference, per segment.
3850                let mut expected = group;
3851                for w in expected.iter_mut() {
3852                    subblock_filter(hev_t, ilim, elim, w, 0);
3853                }
3854
3855                // SIMD: gather as signed lanes, run, scatter back.
3856                let mut seg: [Simd<i32, 4>; 8] = [Simd::splat(0); 8];
3857                for (k, slot) in seg.iter_mut().enumerate() {
3858                    *slot = Simd::from_array(core::array::from_fn(|l| group[l][k] as i32 - 128));
3859                }
3860                subblock_filter_v(hev_t, ilim, elim, &mut seg);
3861                let mut got = group;
3862                for (k, slot) in seg.iter().enumerate() {
3863                    let out = (*slot + Simd::splat(128)).to_array();
3864                    for (l, &val) in out.iter().enumerate() {
3865                        got[l][k] = val as u8;
3866                    }
3867                }
3868
3869                assert_eq!(
3870                    got, expected,
3871                    "subblock hev={hev_t} i={ilim} e={elim} idx={idx}"
3872                );
3873                idx += 4;
3874            }
3875        }
3876    }
3877
3878    #[cfg(feature = "simd")]
3879    #[test]
3880    fn mb_filter_simd_matches_scalar() {
3881        use core::simd::Simd;
3882        let windows = stress_windows();
3883        for &(hev_t, ilim, elim) in &[
3884            (0u8, 1u8, 1u8),
3885            (4, 4, 4),
3886            (2, 8, 16),
3887            (10, 30, 60),
3888            (0, 63, 127),
3889        ] {
3890            let mut idx = 0;
3891            while idx < windows.len() {
3892                let group: [[u8; 8]; 4] =
3893                    core::array::from_fn(|l| windows[(idx + l) % windows.len()]);
3894
3895                let mut expected = group;
3896                for w in expected.iter_mut() {
3897                    mb_filter(hev_t, ilim, elim, w, 0);
3898                }
3899
3900                let mut seg: [Simd<i32, 4>; 8] = [Simd::splat(0); 8];
3901                for (k, slot) in seg.iter_mut().enumerate() {
3902                    *slot = Simd::from_array(core::array::from_fn(|l| group[l][k] as i32 - 128));
3903                }
3904                mb_filter_v(hev_t, ilim, elim, &mut seg);
3905                let mut got = group;
3906                for (k, slot) in seg.iter().enumerate() {
3907                    let out = (*slot + Simd::splat(128)).to_array();
3908                    for (l, &val) in out.iter().enumerate() {
3909                        got[l][k] = val as u8;
3910                    }
3911                }
3912
3913                assert_eq!(got, expected, "mb hev={hev_t} i={ilim} e={elim} idx={idx}");
3914                idx += 4;
3915            }
3916        }
3917    }
3918
3919    #[cfg(feature = "simd")]
3920    #[test]
3921    fn simple_segment_simd_matches_scalar() {
3922        use core::simd::Simd;
3923        let windows = stress_windows();
3924        for &elim in &[1u8, 4, 16, 60, 127] {
3925            let mut idx = 0;
3926            while idx < windows.len() {
3927                // Simple filter operates on the inner 4 pixels p1 p0 q0 q1.
3928                let group: [[u8; 4]; 4] = core::array::from_fn(|l| {
3929                    let w = windows[(idx + l) % windows.len()];
3930                    [w[2], w[3], w[4], w[5]]
3931                });
3932
3933                let mut expected = group;
3934                for w in expected.iter_mut() {
3935                    simple_segment(elim, w, 0);
3936                }
3937
3938                let p1 = Simd::from_array(core::array::from_fn(|l| group[l][0] as i32));
3939                let p0 = Simd::from_array(core::array::from_fn(|l| group[l][1] as i32));
3940                let q0 = Simd::from_array(core::array::from_fn(|l| group[l][2] as i32));
3941                let q1 = Simd::from_array(core::array::from_fn(|l| group[l][3] as i32));
3942                let (np0, nq0) = simple_segment_v(elim, p1, p0, q0, q1);
3943                let np0 = np0.to_array();
3944                let nq0 = nq0.to_array();
3945
3946                for l in 0..4 {
3947                    assert_eq!(
3948                        [np0[l] as u8, nq0[l] as u8],
3949                        [expected[l][1], expected[l][2]],
3950                        "simple e={elim} idx={idx} lane={l}"
3951                    );
3952                }
3953                idx += 4;
3954            }
3955        }
3956    }
3957}