//! AV1 loop restoration: spec 5.11.57 `read_lr`/`read_lr_unit` (per-superblock //! symbol reads, once corners are computed per //! `av1_loop_restoration_corners_in_sb`, restoration.c:1277) and spec 7.17's //! two pixel filters (Wiener, self-guided/SGR). See `lanes/lr.report.md` for //! the full derivation (libaom `decodeframe.c`/`restoration.c` line refs). use archmage::SimdToken; use crate::msac::SymbolDecoder; use ec_av1_syntax::obu::floor_log2; use ec_av1_syntax::{LoopRestorationParams, RestorationType}; /// `ns(n)` (spec 4.10.7) read through the arithmetic coder's equiprobable /// bit primitive (`aom_read_literal`/`SymbolDecoder::literal`), matching /// libaom's `read_primitive_quniform_`. Same algorithm as /// `ec_av1_syntax::obu::read_ns`, ported to the msac reader `decode_subexp` /// needs (LR's coefficients ride the arithmetic-coded tile, not the /// uncompressed header `BitReader` global motion's subexp already targets). fn ns_msac(dec: &mut SymbolDecoder, n: u32) -> u32 { if n <= 1 { return 0; } let w = floor_log2(n) + 1; let m = (1u32 << w) - n; let v = dec.literal(w - 1); if v < m { return v; } (v << 1) - m + dec.literal(1) } /// `decode_subexp()` (spec 5.9.28) with `k` a parameter, not the fixed `3` /// global motion uses -- libaom's `read_primitive_subexpfin_`. LR's Wiener /// taps and SGR `xqd` each pick a different `k` (1/2/3 for the three Wiener /// taps, 4 for SGR). fn decode_subexp_msac(dec: &mut SymbolDecoder, num_syms: u32, k: u32) -> u32 { let mut i = 0u32; let mut mk = 0u32; loop { let b = if i > 0 { k + i - 1 } else { k }; let a = 1u32 << b; if num_syms <= mk + 3 * a { return ns_msac(dec, num_syms - mk) + mk; } if dec.literal(1) == 0 { return dec.literal(b) + mk; } i += 1; mk += a; } } /// `inv_recenter_nonneg` (`aom_dsp/recenter.h`) == spec `inverse_recenter`. fn inverse_recenter(r: u32, v: u32) -> u32 { if v > 2 * r { v } else if v & 1 != 0 { r - ((v + 1) >> 1) } else { r + (v >> 1) } } /// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed /// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around /// `reference`. fn decode_unsigned_subexp_with_ref_msac( dec: &mut SymbolDecoder, n: u32, k: u32, reference: u32, ) -> u32 { let v = decode_subexp_msac(dec, n, k); if (reference << 1) <= n { inverse_recenter(reference, v) } else { n - 1 - inverse_recenter(n - 1 - reference, v) } } /// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter` /// call `aom_read_primitive_refsubexpfin(rb, max-min+1, k, ref-min)+min`. fn decode_signed_subexp_with_ref_msac( dec: &mut SymbolDecoder, low: i32, high: i32, k: u32, reference: i32, ) -> i32 { let n = (high - low) as u32; let r = (reference - low).clamp(0, n as i32) as u32; decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low } // --------------------------------------------------------------------------- // lane-av1lr: the WRITE side of the three primitives above, for the encoder's // per-restoration-unit syntax (`crate::tile`). Each is libaom's own writer // (`aom_dsp/bitwriter.h`'s `write_primitive_*`) and the exact inverse of the // reader it sits under; `wiener_filter_roundtrips` below pins the pair. /// `aom_write_primitive_quniform`, the inverse of [`ns_msac`]. fn write_ns(enc: &mut crate::msac::SymbolEncoder, n: u32, v: u32) { if n <= 1 { return; } let w = floor_log2(n) + 1; let m = (1u32 << w) - n; if v < m { enc.literal(v, w - 1); } else { enc.literal(m + ((v - m) >> 1), w - 1); enc.literal((v - m) & 1, 1); } } /// `aom_write_primitive_subexpfin`, the inverse of [`decode_subexp_msac`]. fn write_subexp(enc: &mut crate::msac::SymbolEncoder, num_syms: u32, k: u32, v: u32) { let mut i = 0u32; let mut mk = 0u32; loop { let b = if i > 0 { k + i - 1 } else { k }; let a = 1u32 << b; if num_syms <= mk + 3 * a { write_ns(enc, num_syms - mk, v - mk); return; } if v < mk + a { enc.literal(0, 1); enc.literal(v - mk, b); return; } enc.literal(1, 1); i += 1; mk += a; } } /// `recenter_nonneg`, the inverse of [`inverse_recenter`]. fn recenter(r: u32, v: u32) -> u32 { if v > 2 * r { v } else if v >= r { (v - r) << 1 } else { ((r - v) << 1) - 1 } } /// Inverse of [`decode_unsigned_subexp_with_ref_msac`]. fn write_unsigned_subexp_with_ref( enc: &mut crate::msac::SymbolEncoder, n: u32, k: u32, reference: u32, v: u32, ) { let recentred = if (reference << 1) <= n { recenter(reference, v) } else { recenter(n - 1 - reference, n - 1 - v) }; write_subexp(enc, n, k, recentred); } /// Inverse of [`decode_signed_subexp_with_ref_msac`]. fn write_signed_subexp_with_ref( enc: &mut crate::msac::SymbolEncoder, low: i32, high: i32, k: u32, reference: i32, v: i32, ) { let n = (high - low) as u32; let r = (reference - low).clamp(0, n as i32) as u32; write_unsigned_subexp_with_ref(enc, n, k, r, (v - low).clamp(0, n as i32 - 1) as u32); } /// Inverse of [`read_wiener_filter`]: writes one unit's two directions and /// advances the caller's running per-plane reference, exactly as the reader /// advances its own. pub(crate) fn write_wiener_filter( enc: &mut crate::msac::SymbolEncoder, chroma: bool, reference: &mut WienerInfo, info: &WienerInfo, ) { write_wiener_direction(enc, chroma, &reference.vfilter, &info.vfilter); write_wiener_direction(enc, chroma, &reference.hfilter, &info.hfilter); *reference = *info; } /// Inverse of [`read_wiener_direction`]. fn write_wiener_direction( enc: &mut crate::msac::SymbolEncoder, chroma: bool, reference: &[i32; 7], taps: &[i32; 7], ) { for i in 0..3 { if i == 0 && chroma { continue; } write_signed_subexp_with_ref( enc, WIENER_TAP_MINV[i], WIENER_TAP_MAXV[i] + 1, WIENER_TAP_K[i], reference[i], taps[i], ); } } /// A Wiener unit's three free taps per direction, as [`WienerInfo`] (the /// centre tap is derived, spec 7.17.4). pub(crate) fn wiener_from_taps(v: [i32; 3], h: [i32; 3]) -> WienerInfo { let fill = |t: [i32; 3]| { let centre = 128 - 2 * (t[0] + t[1] + t[2]); [t[0], t[1], t[2], centre, t[2], t[1], t[0]] }; WienerInfo { vfilter: fill(v), hfilter: fill(h), } } #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live const WIENER_HALFWIN: usize = 3; #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live pub(crate) const WIENER_WIN: usize = 7; const WIENER_TAP_MINV: [i32; 3] = [-5, -23, -17]; const WIENER_TAP_MAXV: [i32; 3] = [10, 8, 46]; const WIENER_TAP_K: [u32; 3] = [1, 2, 3]; const WIENER_TAP_MIDV: [i32; 3] = [3, -7, 15]; /// `WienerInfo`: a restoration unit's 7-tap separable filter, symmetric /// (spec `vfilter[i] == vfilter[6-i]`), with the centre tap derived /// (`WIENER_FILT_STEP - 2*sum(taps 0..3)`, spec 7.17.4). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct WienerInfo { pub vfilter: [i32; 7], pub hfilter: [i32; 7], } impl Default for WienerInfo { fn default() -> Self { Self { vfilter: midpoint_filter(), hfilter: midpoint_filter(), } } } fn midpoint_filter() -> [i32; 7] { let [t0, t1, t2] = WIENER_TAP_MIDV; let centre = 128 - 2 * (t0 + t1 + t2); [t0, t1, t2, centre, t2, t1, t0] } /// One direction's 3 free taps (spec `read_wiener_filter`'s per-direction /// loop): reads with `k`/min/max per tap index, recentred on `ref_dir` /// (which the caller updates to the just-decoded value after each unit, /// spec `ref_wiener_info` -- reset to the midpoint filter at each tile). fn read_wiener_direction(dec: &mut SymbolDecoder, chroma: bool, reference: &[i32; 7]) -> [i32; 7] { let mut taps = [0i32; 3]; for i in 0..3 { // `wiener_win == WIENER_WIN_CHROMA` (5-tap) skips tap 0, which is // always 0 for chroma (spec `read_wiener_filter`, `wiener_win` // branch on plane). if i == 0 && chroma { taps[0] = 0; continue; } taps[i] = decode_signed_subexp_with_ref_msac( dec, WIENER_TAP_MINV[i], WIENER_TAP_MAXV[i] + 1, WIENER_TAP_K[i], reference[i], ); } let centre = 128 - 2 * (taps[0] + taps[1] + taps[2]); [taps[0], taps[1], taps[2], centre, taps[2], taps[1], taps[0]] } /// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating /// `reference` in place (the running per-plane, per-tile reference state). fn read_wiener_filter( dec: &mut SymbolDecoder, chroma: bool, reference: &mut WienerInfo, ) -> WienerInfo { let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter); let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter); let info = WienerInfo { vfilter, hfilter }; *reference = info; info } /// `SgrprojInfo`: one self-guided restoration unit's parameter-set index /// and the two (at most) coded correction weights. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct SgrprojInfo { pub ep: usize, pub xqd: [i32; 2], } const SGRPROJ_PRJ_BITS: i32 = 7; const SGRPROJ_PRJ_MIN0: i32 = -(1 << SGRPROJ_PRJ_BITS) * 3 / 4; const SGRPROJ_PRJ_MAX0: i32 = SGRPROJ_PRJ_MIN0 + (1 << SGRPROJ_PRJ_BITS) - 1; const SGRPROJ_PRJ_MIN1: i32 = -(1 << SGRPROJ_PRJ_BITS) / 4; const SGRPROJ_PRJ_MAX1: i32 = SGRPROJ_PRJ_MIN1 + (1 << SGRPROJ_PRJ_BITS) - 1; const SGRPROJ_PRJ_SUBEXP_K: u32 = 4; /// `av1_sgr_params` (`restoration.c:36`): `(r0, r1, s0, s1)` per of the 16 /// `SGRPROJ_PARAMS_BITS`-selected parameter sets. `r == 0` for a radius /// means that pass is skipped (its `xqd` is then forced, not coded). pub(crate) const SGR_PARAMS: [(i32, i32, i32, i32); 16] = [ (2, 1, 140, 3236), (2, 1, 112, 2158), (2, 1, 93, 1618), (2, 1, 80, 1438), (2, 1, 70, 1295), (2, 1, 58, 1177), (2, 1, 47, 1079), (2, 1, 37, 996), (2, 1, 30, 925), (2, 1, 25, 863), (0, 1, -1, 2589), (0, 1, -1, 1618), (0, 1, -1, 1177), (0, 1, -1, 925), (2, 0, 56, -1), (2, 0, 22, -1), ]; /// `read_sgrproj_filter` (decodeframe.c ~1651). `reference` is the running /// per-plane, per-tile `xqd` state (spec `ref_sgrproj_info`), updated in /// place after every read (both coded and forced components). fn read_sgrproj_filter(dec: &mut SymbolDecoder, reference: &mut SgrprojInfo) -> SgrprojInfo { let ep = dec.literal(4) as usize; let (r0, r1, _s0, _s1) = SGR_PARAMS[ep]; let mut xqd = [0i32; 2]; if r0 == 0 { xqd[0] = 0; xqd[1] = decode_unsigned_subexp_with_ref_msac( dec, (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32, SGRPROJ_PRJ_SUBEXP_K, (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32, ) as i32 + SGRPROJ_PRJ_MIN1; } else if r1 == 0 { xqd[0] = decode_unsigned_subexp_with_ref_msac( dec, (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32, SGRPROJ_PRJ_SUBEXP_K, (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32, ) as i32 + SGRPROJ_PRJ_MIN0; xqd[1] = ((1 << SGRPROJ_PRJ_BITS) - xqd[0]).clamp(SGRPROJ_PRJ_MIN1, SGRPROJ_PRJ_MAX1); } else { xqd[0] = decode_unsigned_subexp_with_ref_msac( dec, (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32, SGRPROJ_PRJ_SUBEXP_K, (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32, ) as i32 + SGRPROJ_PRJ_MIN0; xqd[1] = decode_unsigned_subexp_with_ref_msac( dec, (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32, SGRPROJ_PRJ_SUBEXP_K, (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32, ) as i32 + SGRPROJ_PRJ_MIN1; } let info = SgrprojInfo { ep, xqd }; *reference = info; info } impl Default for SgrprojInfo { fn default() -> Self { Self { ep: 0, xqd: [ (SGRPROJ_PRJ_MIN0 + SGRPROJ_PRJ_MAX0) / 2, (SGRPROJ_PRJ_MIN1 + SGRPROJ_PRJ_MAX1) / 2, ], } } } /// One restoration unit's decoded filter (spec `RestorationUnitInfo`, /// `RESTORE_NONE`/`WIENER`/`SGRPROJ` -- `Switchable`-frame units pick one of /// these per unit; `Wiener`/`Sgrproj`-frame units are all this same variant /// or `None`). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum UnitFilter { None, Wiener(WienerInfo), Sgrproj(SgrprojInfo), } /// Per-plane restoration-unit grid for one tile/frame (spec `RestorationInfo` /// per plane) -- `av1_lr_count_units`'s `horz_units`/`vert_units` sizing plus /// the flattened `runit_idx = rcol + rrow*horz_units` storage `read_lr` /// fills in superblock order. pub(crate) struct RestorationGrid { pub horz_units: [usize; 3], pub vert_units: [usize; 3], units: [Vec; 3], } impl RestorationGrid { pub(crate) fn new(lr: &LoopRestorationParams, frame_width: u32, frame_height: u32) -> Self { Self::with_ss(lr, frame_width, frame_height, 1, 1) } pub(crate) fn with_ss( lr: &LoopRestorationParams, frame_width: u32, frame_height: u32, ss_x: u8, ss_y: u8, ) -> Self { let mut horz_units = [1usize; 3]; let mut vert_units = [1usize; 3]; let mut units: [Vec; 3] = [Vec::new(), Vec::new(), Vec::new()]; for plane in 0..3 { if lr.frame_restoration_type[plane] == RestorationType::None { continue; } let (pw, ph) = if plane == 0 { (frame_width, frame_height) } else { ( (frame_width + u32::from(ss_x)) >> ss_x, (frame_height + u32::from(ss_y)) >> ss_y, ) }; let unit_size = lr.loop_restoration_size[plane]; horz_units[plane] = count_units(pw, unit_size); vert_units[plane] = count_units(ph, unit_size); units[plane] = vec![UnitFilter::None; horz_units[plane] * vert_units[plane]]; } Self { horz_units, vert_units, units, } } pub(crate) fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) { let idx = rcol + rrow * self.horz_units[plane]; self.units[plane][idx] = filter; } pub(crate) fn get(&self, plane: usize, rrow: usize, rcol: usize) -> UnitFilter { let idx = rcol + rrow * self.horz_units[plane]; self.units[plane][idx] } } /// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest. pub(crate) fn count_units(plane_size: u32, unit_size: u32) -> usize { (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize } fn ceil_div(a: u32, b: u32) -> u32 { a.div_ceil(b) } /// `read_lr` (spec 5.11.57) for one superblock at mode-info position /// `(mi_row, mi_col)`: for every plane the frame uses LR on, computes the /// unit-grid corners this superblock covers /// (`av1_loop_restoration_corners_in_sb`, restoration.c:1277 -- every unit /// is >= 64px, so only the top-of-superblock call ever has non-empty /// corners, matching this decoder's own once-per-SB call site) and reads /// one `read_lr_unit` per covered `(rrow, rcol)`, per plane, in plane /// order. /// /// `mi_row`/`mi_col`/`sb_mi` are all in **mode-info units (4x4)**, in true /// frame coordinates -- this is the one call that converts a superblock's /// position into absolute frame space, so it cannot carry the half-mi /// convention the partition walks use. A 64px superblock is 8 mi and a /// 128px superblock is 16 mi; the callers pass `SB_MI / 2` and `SB_MI` /// respectively (`SB_MI` being 16). The corners themselves then step each /// axis by [`MI_SIZE_8PX`] pixels -- see that constant's doc for why it is /// 8 and not libaom's 4. #[allow(clippy::too_many_arguments)] pub(crate) fn read_lr( dec: &mut SymbolDecoder, cdfs: &mut crate::cdf_state::Cdfs, lr: &LoopRestorationParams, grid: &mut RestorationGrid, reference: &mut [(WienerInfo, SgrprojInfo); 3], mi_row: u32, mi_col: u32, sb_mi: u32, fctx: &crate::decode::FrameCtx, ) { if !lr.uses_lr { return; } // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it. #[allow(clippy::needless_range_loop)] for plane in 0..3 { let ftype = lr.frame_restoration_type[plane]; if ftype == RestorationType::None { continue; } // `av1_loop_restoration_corners_in_sb` (restoration.c:1303-1338), // transcribed per axis. The two axes are NOT symmetric: libaom // derives `mi_size_x` from `subsampling_x` and `mi_size_y` from // `subsampling_y`, and derives the row corners from the Y term // alone. This decoder used one `mi_size = 4 >> subsampling_x` for // both axes, so at 4:2:2 (ss_x 1, ss_y 0) the row range was // computed from the COLUMN axis's subsampling -- a 4x-too-small // row step, which made `rrow0 == rrow1` (an empty range, zero // `read_lr_unit` calls) wherever libaom reads a chroma unit. That // is the two missing `wiener_restore_cdf` reads this lane spent // nine rounds localising: the oracle reads three at mi(30,62), // this decoder read one. // // One mode-info unit is 8 pixels (`MI_SIZE_8PX`; see its doc for why // that is not libaom's `MI_SIZE`). Superres // widens the column axis only (spec 7.16), so it enters `num_x` // and `denom_x` and leaves the row axis alone, exactly as libaom // does with `av1_superres_scaled`. let is_uv = plane != 0; let ss_x = if is_uv { crate::decode::ss_x(fctx) as u32 } else { 0 }; let ss_y = if is_uv { crate::decode::ss_y(fctx) as u32 } else { 0 }; let mi_size_x = MI_SIZE_8PX >> ss_x; let mi_size_y = MI_SIZE_8PX >> ss_y; let unit_size = lr.loop_restoration_size[plane]; let horz_units = grid.horz_units[plane] as u32; let vert_units = grid.vert_units[plane] as u32; let (num_x, denom_x) = match crate::decode::superres(fctx) { Some((_, d)) => (mi_size_x * d, unit_size * SCALE_NUMERATOR), None => (mi_size_x, unit_size), }; let num_y = mi_size_y; let denom_y = unit_size; let rcol0 = ceil_div(mi_col * num_x, denom_x); let rcol1 = ceil_div((mi_col + sb_mi) * num_x, denom_x).min(horz_units); let rrow0 = ceil_div(mi_row * num_y, denom_y); let rrow1 = ceil_div((mi_row + sb_mi) * num_y, denom_y).min(vert_units); let chroma = plane != 0; for rrow in rrow0..rrow1 { for rcol in rcol0..rcol1 { let filter = read_lr_unit(dec, cdfs, ftype, chroma, &mut reference[plane]); grid.set(plane, rrow as usize, rcol as usize, filter); } } } } // r3 gate self-pin: how many units decoded a real (non-`None`) filter, by // kind -- proves a real `--enable-restoration=1` aomenc stream actually // exercises `read_lr_unit`'s Wiener/SGR/switchable arms, not just that the // symbol-count/refusal-string wiring compiles. Never reset -- summed across // a gate's whole attempt loop, matching `MASKED_COMPOUND_HITS`/`WEDGE_HITS` // (decode.rs) which this mirrors. thread_local! { static WIENER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SGRPROJ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SWITCHABLE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // lane-reelckf2 r1: how many *stripes* a real filter ran on with the frame's // own top row as their above boundary (`stripe_v_start == 0`, the 56-row // first stripe of `RESTORATION_UNIT_OFFSET == 8`), and how many ran on a // short LAST stripe (`stripe_v_end == plane_h` with a partial height). Those // are the two stripe shapes whose boundary substitution differs from every // interior stripe, and no gate size before this one had either. thread_local! { static LR_STRIPE0_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static LR_LAST_STRIPE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Pixels per mode-info unit (4x4 mi is 8 pixels). This is what /// `av1_loop_restoration_corners_in_sb` (`restoration.c:1303-1338`) steps /// each axis by, subsampled per axis: `MI_SIZE_8PX >> ss_x` for columns, /// `MI_SIZE_8PX >> ss_y` for rows. /// /// NAMING, because it is a trap: libaom's own `MI_SIZE` is **4** /// (`av1/common/enums.h:39-40`, `1 << MI_SIZE_LOG2` with `MI_SIZE_LOG2 2`), /// and libaom writes `mi_size_x = MI_SIZE >> ss_x` -- the same expression, /// at half this value. The factor of two is not a transcription slip: its /// `denom_x`/`denom_y` (`rsi->restoration_unit_size`) is a PIXEL count /// (128 for a 128px superblock), so libaom's numerator and denominator /// already sit on opposite scales, and doubling the numerator lands both in /// pixels. This constant is deliberately NOT called `MI_SIZE`, so nobody /// "corrects" it back to 4 and halves every restoration-unit range. /// /// The authority is the paired trace, not this comment: at 8 the whole /// 16-frame 4:2:2 stream pairs 246735-for-246735 against the instrumented /// oracle, and at 4 it does not. const MI_SIZE_8PX: u32 = 8; /// `SCALE_NUMERATOR` (aom_scale.h): the superres scale's fixed point, 8. const SCALE_NUMERATOR: u32 = 8; fn read_lr_unit( dec: &mut SymbolDecoder, cdfs: &mut crate::cdf_state::Cdfs, ftype: RestorationType, chroma: bool, reference: &mut (WienerInfo, SgrprojInfo), ) -> UnitFilter { match ftype { RestorationType::Switchable => { let t = dec.symbol(&mut cdfs.restore_switchable); match t { 0 => UnitFilter::None, 1 => UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)), _ => UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)), } } RestorationType::Wiener => { if dec.symbol(&mut cdfs.restore_wiener) != 0 { UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)) } else { UnitFilter::None } } RestorationType::Sgrproj => { let bit = dec.symbol(&mut cdfs.restore_sgrproj); if bit != 0 { UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)) } else { UnitFilter::None } } RestorationType::None => UnitFilter::None, } } // --------------------------------------------------------------------- // Spec 7.17: the two pixel filters (Wiener, self-guided) plus the // restoration-unit/stripe walk that drives them. // --------------------------------------------------------------------- /// `Round2` (spec 4.7): halves round up, arithmetic shift for negative sums /// -- same primitive as `mc.rs`/`warp.rs`'s own `round2`, here at `i64` /// since the self-guided filter's intermediate products don't fit `i32`. fn round2(value: i64, shift: u32) -> i64 { if shift == 0 { value } else { (value + (1i64 << (shift - 1))) >> shift } } /// One plane's sample fetch for the pixel filters (spec 7.17.2's stripe /// boundary substitution, libaom `setup_processing_stripe_boundary`/ /// `get_stripe_boundary_info`): within the stripe `[stripe_v_start, /// stripe_v_end)` currently being filtered, read the post-CDEF plane; /// outside it (the 3-row border both filters' kernels reach into), read the /// post-deblock, pre-CDEF plane instead -- UNLESS the stripe is the very /// first/last stripe in the whole plane, where the frame's own top/bottom /// edge replicates (`av1_extend_frame`) rather than crossing into deblocked /// data. Columns always clamp to the plane's own true width -- restoration /// unit COLUMN boundaries have no such substitution, only stripe (row) /// boundaries do. #[allow(clippy::too_many_arguments)] fn lr_sample( cdef: &[u16], deblocked: &[u16], stride: usize, plane_w: usize, plane_h: usize, stripe_v_start: usize, stripe_v_end: usize, row: i64, col: i64, ) -> i32 { let col_c = col.clamp(0, plane_w as i64 - 1) as usize; i32::from( lr_src_row( cdef, deblocked, stride, plane_w, plane_h, stripe_v_start, stripe_v_end, row, )[col_c], ) } /// The plane row [`lr_sample`] reads, resolved once. Which buffer and which /// row a sample comes from depends only on `row` -- the column only ever /// clamps -- so a whole-row consumer (the Wiener horizontal pass) resolves /// the substitution once per row instead of once per tap. [`lr_sample`] is /// this function plus that clamp, so the rule has one statement. #[allow(clippy::too_many_arguments)] fn lr_src_row<'a>( cdef: &'a [u16], deblocked: &'a [u16], stride: usize, plane_w: usize, plane_h: usize, stripe_v_start: usize, stripe_v_end: usize, row: i64, ) -> &'a [u16] { let (buf, src_row) = if row >= stripe_v_start as i64 && row < stripe_v_end as i64 { (cdef, row as usize) } else if row < stripe_v_start as i64 { if stripe_v_start == 0 { (cdef, 0) } else { // libaom saves 2 deblocked context lines and duplicates the // outer one to fill a 3-row border (`RESTORATION_BORDER`): // row `stripe_v_start-1` reads deblocked row `stripe_v_start-1`, // rows `stripe_v_start-2`/`-3` both read deblocked row // `stripe_v_start-2`. let dist = stripe_v_start as i64 - 1 - row; ( deblocked, if dist == 0 { stripe_v_start - 1 } else { stripe_v_start.saturating_sub(2) }, ) } } else if stripe_v_end == plane_h { (cdef, plane_h - 1) } else { // Mirror image of the above: rows `stripe_v_end`/`stripe_v_end+1` // read their own deblocked row, row `stripe_v_end+2` duplicates // `stripe_v_end+1`. let dist = (row - stripe_v_end as i64).min(1) as usize; (deblocked, (stripe_v_end + dist).min(plane_h - 1)) }; &buf[src_row * stride..src_row * stride + plane_w] } /// Wiener pixel filter (spec 7.17.4, libaom `wiener_filter_stripe` -> /// `av1_wiener_convolve_add_src_c`), one stripe-height chunk of one /// restoration unit: a separable 7-tap horizontal pass (rounded by /// `WIENER_ROUND0_BITS==3`, clipped to spec's intermediate range) feeding a /// 7-tap vertical pass (rounded by `2*FILTER_BITS-3==11`) -- the same /// `INTER_ROUND_0`/`INTER_ROUND_1` shifts `mc.rs`'s motion compensation /// uses, since AV1 reuses that same separable-filter machinery here with a /// custom 7-tap kernel instead of the fixed subpel tables. libaom's C /// folds an extra `+/- (1 << ...)` bias into each pass to compensate for a /// pointer-alignment trick that borrows the interpolation filter's 8-tap /// convolution loop for a 7-tap kernel; that bias cancels algebraically /// against `WienerInfo`'s own derived centre tap (`128 - 2*sum(taps)`), so /// plugging the real taps straight into `sum(tap * sample)` (no bias term) /// reproduces the same output byte-for-byte. #[allow(clippy::too_many_arguments)] fn apply_wiener_stripe( out: &mut [u16], row0: usize, cdef: &[u16], deblocked: &[u16], stride: usize, plane_w: usize, plane_h: usize, h_start: usize, h_end: usize, v_start: usize, v_end: usize, info: &WienerInfo, fctx: &crate::decode::FrameCtx, ) { let w = h_end - h_start; let h = v_end - v_start; if w == 0 || h == 0 { return; } let bd = i64::from(crate::decode::bit_depth(fctx)); // lane-av112bit: libaom `get_conv_params_wiener` (`convolve.h:107..118`) // raises the Wiener pair by the same `intbufrange` delta as MC's: at // 12-bit `round_0` is 5 and `round_1` 9 (8/10-bit: 3 and 11). The ROUNDS // are parameterised; the intermediate CLAMP below keeps the corpus-proven // constant-bound structure extended by the same bd formulas -- a first // attempt at the C clamp's exact per-sample transform (the add_src bias // is `src[centre] << FILTER_BITS + (1 << (bd + FILTER_BITS - 1))`, which // survives `Round2(_, round_0)` as `(128 >> round_0) * s + // (1 << (bd + 6 - round_0))`) MOVED the 10-bit 128-superblock film gate // (frame 1 luma): libaom's 8-tap-loop alignment trick means the C // horizontal intermediate is not `ours + that bias` wherever the clamp // actually binds, so the exact transform is NOT derivable from the // convolve source alone. The bd-formula clamp is what every 8/10-bit // byte-exact gate (this film included) has always pinned, and the 12-bit // key witness passes byte-exact with it; where C's real clamp would bind // differently at 12 bits remains unproven either way -- recorded in // `lanes/av112bit.report.md` as the open half of the Wiener lift. let wiener_bias = 1i64 << (bd + 3); let wiener_limit = 1i64 << (bd + 5); let (round0, round1) = crate::mc::round_pair(bd as u32); let rows = h + 6; // lane-perf7: reused across stripes, as the sgrproj `ab` grids are -- // this was a fresh allocation per stripe. Every entry is written below. let mut inter = WIENER_INTER_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut())); inter.clear(); // lane-perf8: `mc::vpass_row` reads a fixed 8 taps from `row`, so the // last vertical output needs two rows of padding past the `h + 6` the // 7-tap kernel actually uses. Tap 7 is zero, so they never contribute. inter.resize((h + 8) * w, 0i16); // lane-perf8: this pass IS `mc.rs`'s horizontal one -- a 7-tap `i16` // convolution over contiguous samples rounded by `Round2(_, 3)`, which // is `INTER_ROUND_0` -- so it runs on that module's kernels with the // eighth tap zeroed, instead of a scalar `lr_sample` call per tap. The // stripe substitution is resolved once per row by `lr_src_row`, and only // a unit touching the plane's left or right edge needs the clamped copy. let hf = &info.hfilter; let t16: [i16; 8] = [ hf[0] as i16, hf[1] as i16, hf[2] as i16, hf[3] as i16, hf[4] as i16, hf[5] as i16, hf[6] as i16, 0, ]; // lane-mc: the intermediate is `i16` now. Both bounds are inside that // range at every supported bit depth (the centred sum's own range, // `|kernel| <= 348` against `2^bd - 1` samples, never reaches them), so // the kernel's saturating store composes with this clamp instead of // changing it: `[-2^(bd+3), 2^(bd+5)-1-2^(bd+3)]` -- 8-bit // `[-2048, 6143]`, 10-bit `[-8192, 24575]`. At 12-bit those formulas // leave `i16`, so the clamp there is the widest `i16` window -- which // strictly contains the kernel's own mathematical range (`|sum| <= // round2(348 * 4095, round_0=5) == 27976 < 2^15`), i.e. it never binds, // the property the 8/10-bit bounds have on the whole proven corpus. let (lo_bound, hi_bound) = if bd >= 12 { (i16::MIN, i16::MAX) } else { (-wiener_bias as i16, (wiener_limit - 1 - wiener_bias) as i16) }; let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut())); for r in 0..rows { let row = v_start as i64 - 3 + r as i64; let src = lr_src_row( cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, ); let lo = h_start as i64 - 3; let out = &mut inter[r * w..r * w + w]; // The row the pass convolves, contiguous when the block sits inside // the plane and the clamped copy (`hbuf`) at an edge. let interior = lo >= 0 && lo as usize + w + 7 <= plane_w; if !interior { hbuf.clear(); hbuf.extend( (0..w + 7).map(|k| src[(lo + k as i64).clamp(0, plane_w as i64 - 1) as usize]), ); } let row_slice: &[u16] = if interior { &src[lo as usize..] } else { &hbuf }; crate::mc::hpass_contig(row_slice, &t16, out, round0); for v in out.iter_mut() { *v = (*v).clamp(lo_bound, hi_bound); } } WIENER_ROW_SCRATCH.with(|c| *c.borrow_mut() = hbuf); // lane-perf7: the clamp bound is the frame's, so it is read once here // instead of taking a thread-local read per output sample. let smax = i64::from(crate::decode::sample_max(fctx)); // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves // the accumulator unrounded, and `Round2(_, round1)` is the frame's // non-compound `round_1` (11 at 8/10-bit, 9 at 12 -- libaom's // `get_conv_params_wiener`). let vf = &info.vfilter; let taps: [i32; 8] = [vf[0], vf[1], vf[2], vf[3], vf[4], vf[5], vf[6], 0]; let mut acc = WIENER_ACC_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut())); acc.clear(); acc.resize(w, 0i32); for r in 0..h { crate::mc::vpass_row(&inter[r * w..], w, w, 1, &taps, &mut acc); let dst = &mut out[(v_start + r - row0) * stride + h_start..][..w]; for (o, &a) in dst.iter_mut().zip(acc.iter()) { *o = round2(i64::from(a), round1).clamp(0, smax) as u16; } } WIENER_ACC_SCRATCH.with(|c| *c.borrow_mut() = acc); WIENER_INTER_SCRATCH.with(|c| *c.borrow_mut() = inter); } thread_local! { /// [`apply_wiener_stripe`]'s horizontal-pass intermediate, kept across /// calls so a stripe does not allocate (lane-perf7). static WIENER_INTER_SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; /// The clamped-column copy the horizontal pass needs at a plane edge. static WIENER_ROW_SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; /// The vertical pass's unrounded accumulator row. static WIENER_ACC_SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; /// [`compute_ab`]'s two `(A, B)` grids, likewise (lane-perf7). #[allow(clippy::type_complexity)] static SGR_AB_SCRATCH: std::cell::RefCell<(Vec<(i32, i64)>, Vec<(i32, i64)>)> = const { std::cell::RefCell::new((Vec::new(), Vec::new())) }; } /// `av1_x_by_xplus1` (`restoration.c`): `round(256*z/(z+1))` for `z` in /// `[0,255]`, saturating the `z==0` case to `1` instead of `0` (see the /// libaom source comment this ports -- keeps `256-A[k]` inside a `u8` and /// avoids a later overflow, without visibly affecting a near-flat block). // r8: this table was transcribed with two errors -- index 101 (253 written // as 254) and indices 165..=169 (254 written as 255) -- traced by comparing // a call-unique dump (gated on the pinned stream's `xqd == [-16,-32]`, not a // reused coordinate) against libaom's real `av1_x_by_xplus1` at the same // `z=101`; both tables now generated straight from // `~/.cache/aom-oracle/src/av1/common/restoration.c` to rule out any other // transcription slip. const SGR_X_BY_XPLUS1: [i32; 256] = [ 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, 240, 241, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, 248, 248, 248, 248, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 256, ]; /// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25` /// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`. const SGR_ONE_BY_X: [i32; 25] = [ 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228, 216, 205, 195, 186, 178, 171, 164, ]; const SGRPROJ_MTABLE_BITS: u32 = 20; const SGRPROJ_RECIP_BITS: u32 = 12; const SGRPROJ_SGR_BITS: u32 = 8; const SGRPROJ_RST_BITS: u32 = 4; /// `calculate_intermediate_result` (`restoration.c`): the blend-factor pair /// `(A[k], B[k])` at every position in `-1..=h` x `-1..=w` relative to a /// restoration unit (a 1-pixel border around the unit, spec 7.17.3's /// `BoxFilter`), for one of the two SGR radii. `r`/`s` are `SGR_PARAMS[ep]`'s /// `(r0,s0)` or `(r1,s1)`; libaom computes this only at odd rows for the /// `r==2` ("fast") radius as a running-sum speed optimisation -- the box /// sum itself is identical at every row regardless, so computing it /// everywhere (this function does, via a plain windowed sum through /// [`lr_sample`] rather than libaom's O(1)-per-step sliding sum) and only /// *reading* the odd rows back in [`apply_sgrproj_stripe`]'s fast branch /// reproduces the same values without porting the sliding-window trick. #[allow(clippy::too_many_arguments)] fn compute_ab( cdef: &[u16], deblocked: &[u16], stride: usize, plane_w: usize, plane_h: usize, h_start: usize, v_start: usize, v_end: usize, w: usize, h: usize, r: i32, s: i32, // lane-perf7: a reused scratch buffer. This used to be a fresh // `vec![(0, 0); (w + 2) * (h + 2)]` per call (two calls per sgrproj // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every // page then faulted in on first touch. Every entry is written below, so // the resize's fill value is never read. ab: &mut Vec<(i32, i64)>, fctx: &crate::decode::FrameCtx, ) { let gw = w + 2; let gh = h + 2; ab.clear(); ab.resize(gw * gh, (0i32, 0i64)); let n = (2 * r + 1) * (2 * r + 1); // lane-perf6: the box sums are separable. Summing every grid point's own // (2r+1)^2 window called `lr_sample` -- whose stripe-boundary test is the // expensive part -- (2r+1) times more often than needed; one column-sum // pass per grid row reads each source sample once per row instead, and // the horizontal sum is then (2r+1) adds. let ru = r as usize; let ncols = gw + 2 * ru; // lane-sgr: `i32` sums. A sample is at most `2^bd - 1 <= 4095`, so the // widest possible window sum of squares is `25 * 4095^2 == 419M` and the // widest plain sum `25 * 4095 == 102k`: both far inside `i32`, and every // downstream product is either kept in `i64` (the two that need it) or // likewise bounded (`a_s * n <= 25 * 25 * 65025 / 16`). Halving the // accumulator width is what lets the row loops below vectorise. debug_assert!(crate::decode::sample_max(fctx) <= 4095); debug_assert!(s > 0); let mut sums = vec![0i32; 2 * ncols + 2 * gw]; let (col_a, rest) = sums.split_at_mut(ncols); let (col_b, rest) = rest.split_at_mut(ncols); // lane-sgr: the sliding horizontal sums are laid down as two rows first, // so the `(A, B)` map over them is a straight-line pass `ab_row` can run // eight points at a time. let (a_row, b_row) = rest.split_at_mut(gw); // lane-sgr: one contiguous copy of the source row's whole footprint, with // the column clamp (edge replication) applied while filling, so the // accumulate loops below are branch-free over a plain slice instead of a // `lr_sample` call -- clamp included -- per element. let mut samp = vec![0u16; ncols]; // Hoisted out of the per-point body: one thread-local read per call. let bd_shift = u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8); let base_col = h_start as i64 - 1 - r as i64; let dump = crate::envflags::env_flag!("EC_LR_CALL_DUMP"); let one_by_x = SGR_ONE_BY_X[(n - 1) as usize] as i64; // lane-perf9: the column sums slide down the grid too. Grid row `gi+1`'s // window is row `gi`'s minus its top source row plus one new bottom row, // so each source sample is read once per grid row instead of (2r+1) // times -- the same exactness argument as the separable split above // (integer addition is associative, and subtracting a row that was added // is exact), and `lr_sample`'s stripe-boundary test, which is what makes // a sample read expensive, is a pure function of `(row, col)`. for gi in 0..gh { let i = gi as i64 - 1; { let mut accumulate = |row: i64, add: bool| { let src = lr_src_row( cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, ); fill_clamped_row(src, plane_w, base_col, &mut samp); if add { for ((c_a, c_b), &px) in col_a.iter_mut().zip(col_b.iter_mut()).zip(samp.iter()) { let px = i32::from(px); *c_a += px * px; *c_b += px; } } else { for ((c_a, c_b), &px) in col_a.iter_mut().zip(col_b.iter_mut()).zip(samp.iter()) { let px = i32::from(px); *c_a -= px * px; *c_b -= px; } } }; if gi == 0 { for dr in -r..=r { accumulate(v_start as i64 + i + dr as i64, true); } } else { accumulate(v_start as i64 + i - 1 - r as i64, false); accumulate(v_start as i64 + i + r as i64, true); } } // The horizontal sum slides the same way (one add and one subtract // per grid point instead of 2r+1 adds). let mut a = col_a[..2 * ru + 1].iter().sum::(); let mut b = col_b[..2 * ru + 1].iter().sum::(); for gj in 0..gw { if gj > 0 { a += col_a[gj + 2 * ru] - col_a[gj - 1]; b += col_b[gj + 2 * ru] - col_b[gj - 1]; } a_row[gj] = a; b_row[gj] = b; } ab_row( a_row, b_row, n, s, bd_shift, one_by_x, &mut ab[gi * gw..gi * gw + gw], ); let dump_gj = 6i64 - h_start as i64 + 1; if dump && v_start as i64 + i == 60 && r == 1 && (0..gw as i64).contains(&dump_gj) { let gj = dump_gj as usize; let (a, b) = (a_row[gj], b_row[gj]); let a_s = round2_u31(a, 2 * bd_shift); let b_s = round2_u31(b, bd_shift); let p = (a_s * n - b_s * b_s).max(0); let z = z_index(p, s); let (a_val, b_val) = ab[gi * gw + gj]; eprintln!( "EC_LR_CALL_DUMP compute_ab u_tap: r={r} s={s} n={n} box_a={a} box_b={b} \ p={p} z={z} a_val={a_val} b_val={b_val}" ); } } } /// `z = Round2(p * s, SGRPROJ_MTABLE_BITS)` clamped to the /// [`SGR_X_BY_XPLUS1`] domain -- the one product that does not fit 32 bits. #[inline] fn z_index(p: i32, s: i32) -> usize { ((i64::from(p) * i64::from(s) + (1 << (SGRPROJ_MTABLE_BITS - 1))) >> SGRPROJ_MTABLE_BITS) .clamp(0, 255) as usize } /// One grid point's `(A[k], B[k])` from its two box sums -- libaom /// `restoration.c:660..672`, and the reference every [`ab_row`] arm matches. #[inline] fn ab_point(a: i32, b: i32, n: i32, s: i32, bd_shift: u32, one_by_x: i64) -> (i32, i64) { // libaom `restoration.c:660` -- the box sums are brought back to the // 8-bit scale before `p` is formed (`a` is a sum of squares, so it loses // twice the shift `b` does); `B[k]` keeps the RAW `b`, only `p` uses the // scaled pair. At 8-bit both shifts are 0, which is why this was // invisible until now. let a_s = round2_u31(a, 2 * bd_shift); let b_s = round2_u31(b, bd_shift); let p = (a_s * n - b_s * b_s).max(0); let a_val = SGR_X_BY_XPLUS1[z_index(p, s)]; let b_val = round2( (256 - a_val) as i64 * i64::from(b) * one_by_x, SGRPROJ_RECIP_BITS, ); (a_val, b_val) } /// One grid row's `(A, B)` pairs: [`ab_point`] per element, eight at a time /// under AVX2 (the kernel is that arithmetic lane-wise, same widths). #[allow(clippy::too_many_arguments)] fn ab_row( a_row: &[i32], b_row: &[i32], n: i32, s: i32, bd_shift: u32, one_by_x: i64, out: &mut [(i32, i64)], ) { let done = match archmage::X64V3Token::summon() { Some(t) => sgr_simd::ab_row_avx2(t, a_row, b_row, n, s, bd_shift, one_by_x as i32, out), None => 0usize, }; for gj in done..out.len() { out[gj] = ab_point(a_row[gj], b_row[gj], n, s, bd_shift, one_by_x); } } /// [`ab_row`]'s AVX2 kernel. #[cfg(target_arch = "x86_64")] mod sgr_simd { use super::{SGR_X_BY_XPLUS1, SGRPROJ_MTABLE_BITS, SGRPROJ_RECIP_BITS}; use archmage::{X64V3Token, arcane}; use std::arch::x86_64::*; /// Eight grid points of `super::ab_point` per iteration, returning how /// many points were written (a multiple of 8; the tail stays scalar). /// /// Every lane repeats the scalar arithmetic at the widths /// `compute_ab` proves: `a, b >= 0` and `s > 0`, `p < 2^26`, /// `p * s < 2^38`, `(256 - A) * one_by_x < 2^21` and that times /// `b < 2^17` is `< 2^38` -- so the two 64-bit products below lose no /// bit, and the unsigned `mul_epu32` sees no negative operand. #[arcane] #[allow(clippy::too_many_arguments)] pub fn ab_row_avx2( _t: X64V3Token, a_row: &[i32], b_row: &[i32], n: i32, s: i32, bd_shift: u32, one_by_x: i32, out: &mut [(i32, i64)], ) -> usize { let len = out.len().min(a_row.len()).min(b_row.len()); let nv = _mm256_set1_epi32(n); let sv = _mm256_set1_epi32(s); let obx = _mm256_set1_epi32(one_by_x); let c255 = _mm256_set1_epi32(255); let c256 = _mm256_set1_epi32(256); let zero = _mm256_setzero_si256(); let rnd_z = _mm256_set1_epi64x(1 << (SGRPROJ_MTABLE_BITS - 1)); let rnd_b = _mm256_set1_epi64x(1 << (SGRPROJ_RECIP_BITS - 1)); let sh_z = _mm_cvtsi32_si128(SGRPROJ_MTABLE_BITS as i32); let sh_b = _mm_cvtsi32_si128(SGRPROJ_RECIP_BITS as i32); let sh_a = _mm_cvtsi32_si128(2 * bd_shift as i32); let sh_bd = _mm_cvtsi32_si128(bd_shift as i32); let rnd_a = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (2 * bd_shift - 1) }); let rnd_bd = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (bd_shift - 1) }); let mut gj = 0usize; while gj + 8 <= len { let a = bytemuck::cast::<[i32; 8], __m256i>(a_row[gj..gj + 8].try_into().unwrap()); let b = bytemuck::cast::<[i32; 8], __m256i>(b_row[gj..gj + 8].try_into().unwrap()); let a_s = _mm256_srl_epi32(_mm256_add_epi32(a, rnd_a), sh_a); let b_s = _mm256_srl_epi32(_mm256_add_epi32(b, rnd_bd), sh_bd); let p = _mm256_max_epi32( _mm256_sub_epi32(_mm256_mullo_epi32(a_s, nv), _mm256_mullo_epi32(b_s, b_s)), zero, ); let z = _mm256_min_epi32(mul_shift(p, sv, rnd_z, sh_z), c255); let zv: [i32; 8] = bytemuck::cast(z); let a_val: __m256i = bytemuck::cast(zv.map(|i| SGR_X_BY_XPLUS1[i as usize])); let t = _mm256_mullo_epi32(_mm256_sub_epi32(c256, a_val), obx); let b_val = mul_shift(t, b, rnd_b, sh_b); let av: [i32; 8] = bytemuck::cast(a_val); let bv: [i32; 8] = bytemuck::cast(b_val); for k in 0..8 { out[gj + k] = (av[k], i64::from(bv[k])); } gj += 8; } gj } /// `Round2(x * y, shift)` lane-wise for eight non-negative `i32` lanes, /// with the product formed in 64 bits (even and odd lanes separately, /// `mul_epu32`) and packed back once the shift makes it fit again. #[target_feature(enable = "avx2")] fn mul_shift(x: __m256i, y: __m256i, rnd: __m256i, shift: __m128i) -> __m256i { let ev = _mm256_mul_epu32(x, y); let od = _mm256_mul_epu32(_mm256_srli_epi64(x, 32), _mm256_srli_epi64(y, 32)); let ev = _mm256_srl_epi64(_mm256_add_epi64(ev, rnd), shift); let od = _mm256_srl_epi64(_mm256_add_epi64(od, rnd), shift); _mm256_blend_epi32(ev, _mm256_slli_epi64(od, 32), 0b1010_1010) } } /// `Round2` for the non-negative box sums (same value as [`round2`], one /// width narrower). #[inline] fn round2_u31(value: i32, shift: u32) -> i32 { if shift == 0 { value } else { (value + (1 << (shift - 1))) >> shift } } /// Copies one source row's `out.len()` samples starting at `base_col` into a /// contiguous scratch, replicating the plane's edge sample outside /// `[0, plane_w)` -- exactly the clamp [`lr_sample`] applies per element. #[inline] fn fill_clamped_row(src: &[u16], plane_w: usize, base_col: i64, out: &mut [u16]) { let ncols = out.len(); if base_col >= 0 && base_col as usize + ncols <= plane_w { out.copy_from_slice(&src[base_col as usize..base_col as usize + ncols]); } else { for (k, o) in out.iter_mut().enumerate() { *o = src[(base_col + k as i64).clamp(0, plane_w as i64 - 1) as usize]; } } } /// Self-guided pixel filter (spec 7.17.3, libaom `sgrproj_filter_stripe` -> /// `av1_apply_selfguided_restoration_c`), one stripe-height chunk of one /// restoration unit: up to two box-filtered blends (`SGR_PARAMS[ep]`'s `r0` /// "fast"/even-odd-row and `r1` dense radii, either may be `0` and skipped) /// combined with the decoded `xqd` weights via `av1_decode_xq`. #[allow(clippy::too_many_arguments)] fn apply_sgrproj_stripe( out: &mut [u16], row0: usize, cdef: &[u16], deblocked: &[u16], stride: usize, plane_w: usize, plane_h: usize, h_start: usize, h_end: usize, v_start: usize, v_end: usize, info: &SgrprojInfo, fctx: &crate::decode::FrameCtx, ) { let w = h_end - h_start; let h = v_end - v_start; if w == 0 || h == 0 { return; } let (r0, r1, s0, s1) = SGR_PARAMS[info.ep]; let gw = w + 2; let idx = |gi: i64, gj: i64| -> usize { (gi + 1) as usize * gw + (gj + 1) as usize }; let (mut buf0, mut buf1) = SGR_AB_SCRATCH.with(|c| { let mut m = c.borrow_mut(); (std::mem::take(&mut m.0), std::mem::take(&mut m.1)) }); if r0 > 0 { compute_ab( cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0, &mut buf0, fctx, ); } if r1 > 0 { compute_ab( cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1, &mut buf1, fctx, ); } let ab0 = (r0 > 0).then_some(&buf0); let ab1 = (r1 > 0).then_some(&buf1); // r8: call-unique debug dump -- r6's coordinate-only gate (`v_start==60`) // matched several unrelated calls across the gate's attempt sweep, so its // captured bytes were never provably from the failing call. `info.xqd` // is this restoration unit's own decoded weights, unique to the one call // r7 traced (`[-16,-32]`); dump the real 9-byte dense-arm (r1) "u"-tap // window (physical rows 59..=61, cols 5..=7 -- r7's traced tap) straight // from `lr_sample` for this exact call, no coordinate matching involved. if crate::envflags::env_flag!("EC_LR_CALL_DUMP") && r1 > 0 && info.xqd == [-16, -32] { let bytes: Vec = (59..=61) .flat_map(|row| { (5..=7).map(move |col| { lr_sample( cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col, ) }) }) .collect(); eprintln!( "EC_LR_CALL_DUMP: xqd={:?} v_start={v_start} v_end={v_end} h_start={h_start} \ u-tap 9-byte window (rows 59..=61, cols 5..=7) = {bytes:?}", info.xqd ); } let mut xq = [0i32; 2]; if r0 == 0 { xq[0] = 0; xq[1] = (1 << SGRPROJ_PRJ_BITS) - info.xqd[1]; } else if r1 == 0 { xq[0] = info.xqd[0]; xq[1] = 0; } else { xq[0] = info.xqd[0]; xq[1] = (1 << SGRPROJ_PRJ_BITS) - xq[0] - info.xqd[1]; } // lane-perf7: as in `apply_wiener_stripe`, the clamp bound is read once // per stripe instead of per output sample. let smax = i64::from(crate::decode::sample_max(fctx)); for i in 0..h as i64 { for j in 0..w as i64 { let dgd = lr_sample( cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, v_start as i64 + i, h_start as i64 + j, ) as i64; let u = dgd << SGRPROJ_RST_BITS; let mut v = u << SGRPROJ_PRJ_BITS; if let Some(ab) = &ab0 { // "Fast" radius (`r0==2`): A/B were only ever meaningfully // computed at odd rows (see `compute_ab`'s doc comment) -- // an even output row blends its two odd neighbour rows // (weight 6/5, `nb=5`), an odd output row reuses its own // row's A/B plus column neighbours (weight 6/5, `nb=4`). let (a, b, nb) = if i & 1 == 0 { let (a_um1, b_um1) = ab[idx(i - 1, j)]; let (a_up1, b_up1) = ab[idx(i + 1, j)]; let (a_uml, b_uml) = ab[idx(i - 1, j - 1)]; let (a_umr, b_umr) = ab[idx(i - 1, j + 1)]; let (a_upl, b_upl) = ab[idx(i + 1, j - 1)]; let (a_upr, b_upr) = ab[idx(i + 1, j + 1)]; let a = (a_um1 + a_up1) as i64 * 6 + (a_uml + a_umr + a_upl + a_upr) as i64 * 5; let b = (b_um1 + b_up1) * 6 + (b_uml + b_umr + b_upl + b_upr) * 5; (a, b, 5u32) } else { let (a_c, b_c) = ab[idx(i, j)]; let (a_l, b_l) = ab[idx(i, j - 1)]; let (a_r, b_r) = ab[idx(i, j + 1)]; let a = a_c as i64 * 6 + (a_l + a_r) as i64 * 5; let b = b_c * 6 + (b_l + b_r) * 5; (a, b, 4u32) }; let flt0 = round2(a * dgd + b, SGRPROJ_SGR_BITS + nb - SGRPROJ_RST_BITS); v += xq[0] as i64 * (flt0 - u); } if let Some(ab) = &ab1 { // Dense radius (`r1==1`): every row was computed, so the // combine is the full 3x3 neighbourhood (weight 4/3). let (a_c, b_c) = ab[idx(i, j)]; let (a_u, b_u) = ab[idx(i - 1, j)]; let (a_d, b_d) = ab[idx(i + 1, j)]; let (a_l, b_l) = ab[idx(i, j - 1)]; let (a_r, b_r) = ab[idx(i, j + 1)]; let (a_ul, b_ul) = ab[idx(i - 1, j - 1)]; let (a_ur, b_ur) = ab[idx(i - 1, j + 1)]; let (a_dl, b_dl) = ab[idx(i + 1, j - 1)]; let (a_dr, b_dr) = ab[idx(i + 1, j + 1)]; let a = (a_c + a_u + a_d + a_l + a_r) as i64 * 4 + (a_ul + a_ur + a_dl + a_dr) as i64 * 3; let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3; let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS); v += xq[1] as i64 * (flt1 - u); if crate::envflags::env_flag!("EC_LR_CALL_DUMP") && info.xqd == [-16, -32] && v_start as i64 + i == 61 && h_start as i64 + j == 6 { eprintln!( "EC_LR_CALL_DUMP combine: c={:?} u_tap(row60)={:?} d={:?} l={:?} r={:?} \ ul={:?} ur={:?} dl={:?} dr={:?} dense a={a} b={b} dgd={dgd} \ u={u} flt1={flt1} xq={xq:?} v_before_final_round={v}", ab[idx(i, j)], ab[idx(i - 1, j)], ab[idx(i + 1, j)], ab[idx(i, j - 1)], ab[idx(i, j + 1)], ab[idx(i - 1, j - 1)], ab[idx(i - 1, j + 1)], ab[idx(i + 1, j - 1)], ab[idx(i + 1, j + 1)] ); } } let out_v = round2(v, SGRPROJ_PRJ_BITS as u32 + SGRPROJ_RST_BITS).clamp(0, smax) as u16; out[(v_start as i64 + i - row0 as i64) as usize * stride + (h_start as i64 + j) as usize] = out_v; } } SGR_AB_SCRATCH.with(|c| *c.borrow_mut() = (buf0, buf1)); } /// Chunks one restoration unit's `[v_start, v_end)` extent into 64-row /// (56 for the plane's very first stripe -- `RESTORATION_UNIT_OFFSET==8`) /// processing stripes and filters each (libaom /// `av1_loop_restoration_filter_unit`'s own `while (i < unit_h)` loop) -- /// a restoration unit can be up to `256*1.5` px tall, spanning several /// stripes, each of which needs its own boundary-source decision from /// [`lr_sample`]. #[allow(clippy::too_many_arguments)] fn filter_restoration_unit( out: &mut [u16], row0: usize, cdef: &[u16], deblocked: &[u16], stride: usize, plane_w: usize, plane_h: usize, h_start: usize, h_end: usize, v_start: usize, v_end: usize, ss_y: u32, filter: UnitFilter, fctx: &crate::decode::FrameCtx, ) { let full_stripe_height = 64usize >> ss_y; let runit_offset = 8usize >> ss_y; let unit_h = v_end - v_start; let mut i = 0usize; while i < unit_h { let stripe_v_start = v_start + i; let frame_stripe = (stripe_v_start + runit_offset) / full_stripe_height; let nominal_h = full_stripe_height - if frame_stripe == 0 { runit_offset } else { 0 }; let h = nominal_h.min(unit_h - i); let stripe_v_end = stripe_v_start + h; match filter { UnitFilter::Wiener(info) => apply_wiener_stripe( out, row0, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, fctx, ), UnitFilter::Sgrproj(info) => apply_sgrproj_stripe( out, row0, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, fctx, ), UnitFilter::None => {} } i += h; } } /// Applies loop restoration to one whole plane's post-CDEF samples (spec /// 7.17). Walks restoration units exactly as libaom's /// `foreach_rest_unit_in_plane` (`unit_size` steps, the tail folded into /// the previous unit when the remainder is under `1.5*unit_size` -- the /// same round-to-nearest [`count_units`] already used to size /// [`RestorationGrid`]), then re-offsets internal row boundaries by /// `RESTORATION_UNIT_OFFSET==8` (the first/last row of the plane keeps its /// full extent). Returns a fresh copy of `cdef` with only this plane's /// restoration-unit pixels replaced -- a restoration unit must never read /// another, already-filtered unit's output (spec keeps a separate /// destination buffer for exactly this reason), so this never filters in /// place -- `out` is that buffer, refilled from `cdef` on entry. #[allow(clippy::too_many_arguments)] pub(crate) fn apply_loop_restoration_plane( cdef: &[u16], deblocked: &[u16], stride: usize, plane_w: usize, plane_h: usize, ss_y: u32, ftype: RestorationType, unit_size: u32, grid: &RestorationGrid, plane: usize, // lane-perf6: the destination buffer, refilled from `cdef` here. It used // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte // allocation whose every page then faulted in on first touch. out: &mut Vec, // `Some((r_lo, r_hi))` restricts the call to those RU ROWS. `out` is then // the caller's, already sized, and only this range's rows are refilled from `cdef` (the rows below `plane_h` are // the caller's own tail copy). `None` is the whole-plane form. rrows: Option<(usize, usize)>, fctx: &crate::decode::FrameCtx, ) { let rows = lr_unit_rows(plane_h, unit_size, ss_y, ftype); let Some((r_lo, r_hi)) = rrows else { out.clear(); out.extend_from_slice(cdef); if rows.is_empty() { return; } // Each band's RU rows write one contiguous run of `out` rows (the // rows run `v_start..v_end` back to back), so a band owns its own slice. let pbands: Vec<(usize, usize)> = crate::par::bands(rows.len(), crate::par::filter_threads()) .into_iter() .map(|(a, b)| (rows[a].0 as usize, rows[b - 1].1 as usize)) .collect(); crate::par::run_bands_mut( &pbands, stride, fctx, out.as_mut_slice(), |lo, hi, mine, fctx| { let r_lo = rows.partition_point(|r| (r.0 as usize) < lo); let r_hi = rows.partition_point(|r| (r.0 as usize) < hi); for rrow in r_lo..r_hi { lr_unit_row( mine, lo, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, rrow, &rows, fctx, ); } }, ); debug_assert_eq!( rows.len(), grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units" ); return; }; for rrow in r_lo..r_hi.min(rows.len()) { let (v_start, v_end) = rows[rrow]; let (a, b) = (v_start as usize * stride, v_end as usize * stride); out[a..b].copy_from_slice(&cdef[a..b]); lr_unit_row( out, 0, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, rrow, &rows, fctx, ); } } /// One plane's restoration-unit ROW walk, resolved to each row's `out` write /// span `v_start..v_end`. The walk is data-dependent (a short remainder is /// swallowed by the previous unit row), so both callers resolve it into this /// list first: the next row's `v_start` is this one's `v_end`, so the spans /// partition `0..plane_h` and row bands are disjoint. Empty when the plane /// restores nothing. pub(crate) fn lr_unit_rows( plane_h: usize, unit_size: u32, ss_y: u32, ftype: RestorationType, ) -> Vec<(u32, u32)> { let mut rows: Vec<(u32, u32)> = Vec::new(); if ftype == RestorationType::None || unit_size == 0 { return rows; } let voffset = 8u32 >> ss_y; let ext_size = (unit_size * 3) / 2; let mut y0 = 0u32; while y0 < plane_h as u32 { let remaining_h = plane_h as u32 - y0; let uh = if remaining_h < ext_size { remaining_h } else { unit_size }; let v_start = (y0 as i64 - voffset as i64).max(0) as u32; let mut v_end = y0 + uh; if v_end < plane_h as u32 { v_end -= voffset; } rows.push((v_start, v_end)); y0 += uh; } rows } /// The restoration units of one RU row, filtered into `out`. Reads only /// `cdef`/`deblocked`, writes only this row's `v_start..v_end` span. #[allow(clippy::too_many_arguments)] fn lr_unit_row( out: &mut [u16], row0: usize, cdef: &[u16], deblocked: &[u16], stride: usize, plane_w: usize, plane_h: usize, ss_y: u32, unit_size: u32, grid: &RestorationGrid, plane: usize, rrow: usize, rows: &[(u32, u32)], fctx: &crate::decode::FrameCtx, ) { let ext_size = (unit_size * 3) / 2; let (v_start, v_end) = rows[rrow]; let mut x0 = 0u32; let mut rcol = 0usize; while x0 < plane_w as u32 { let remaining_w = plane_w as u32 - x0; let uw = if remaining_w < ext_size { remaining_w } else { unit_size }; let filter = grid.get(plane, rrow, rcol); if filter != UnitFilter::None { filter_restoration_unit( out, row0, cdef, deblocked, stride, plane_w, plane_h, x0 as usize, (x0 + uw) as usize, v_start as usize, v_end as usize, ss_y, filter, fctx, ); } x0 += uw; rcol += 1; } } #[cfg(test)] mod tests { use super::*; use crate::msac::{SymbolDecoder, SymbolEncoder}; /// The write side these roundtrips exercise now lives beside the /// readers (`write_ns`/`write_subexp`/`write_unsigned_subexp_with_ref`, /// used by the encoder's per-unit LR syntax) instead of being a /// test-only transcription of it -- one implementation, pinned here. /// /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4, /// `num_syms` up to 96) actually hit, per `WIENER_TAP_MAXV`-`MINV`+1 / /// `SGRPROJ_PRJ_MAX-MIN+1`. #[test] fn subexp_roundtrips_every_value() { for &(num_syms, k) in &[ (16u32, 1u32), (32, 2), (64, 3), (96, 4), (128, 4), (3, 1), (1, 3), ] { for v in 0..num_syms { let mut enc = SymbolEncoder::new(); write_subexp(&mut enc, num_syms, k, v); let payload = enc.finish(); let mut dec = SymbolDecoder::new(&payload); let got = decode_subexp_msac(&mut dec, num_syms, k); assert_eq!(got, v, "num_syms={num_syms} k={k} v={v}"); } } } /// The recentred, ref-relative form `read_wiener_filter`/ /// `read_sgrproj_filter` actually call -- every `(n, reference, v)` /// combination for LR's own tap-0 range (16 values, matching /// `WIENER_FILT_TAP0_MAXV-MINV+1`). #[test] fn unsigned_subexp_with_ref_roundtrips() { let n = 16u32; for k in 1..=4u32 { for reference in 0..n { for v in 0..n { let mut enc = SymbolEncoder::new(); write_unsigned_subexp_with_ref(&mut enc, n, k, reference, v); let payload = enc.finish(); let mut dec = SymbolDecoder::new(&payload); let got = decode_unsigned_subexp_with_ref_msac(&mut dec, n, k, reference); assert_eq!(got, v, "n={n} k={k} reference={reference} v={v}"); } } } } /// Signed wrapper sanity: a handful of `(low, high, k, reference, v)` /// covering LR's actual Wiener tap-1/tap-2 and SGR `xqd0`/`xqd1` ranges. #[test] fn signed_subexp_with_ref_roundtrips() { let cases: [(i32, i32, u32); 4] = [ (-5, 11, 1), // Wiener tap0 (-23, 9, 2), // Wiener tap1 (-17, 47, 3), // Wiener tap2 (-96, 32, 4), // SGR xqd0 ]; for (low, high, k) in cases { let n = (high - low) as u32; for reference_v in [low, low + n as i32 / 3, high - 1] { for v in [low, low + n as i32 / 2, high - 1] { let r = (reference_v - low).clamp(0, n as i32) as u32; let coded_v = (v - low) as u32; let mut enc = SymbolEncoder::new(); write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v); let payload = enc.finish(); let mut dec = SymbolDecoder::new(&payload); let got = decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v); assert_eq!( got, v, "low={low} high={high} k={k} reference={reference_v} v={v}" ); } } } } /// [`write_wiener_filter`] against [`read_wiener_filter`], including the /// running per-tile reference both sides advance: three units in a row, /// luma (7-tap) and chroma (5-tap, tap 0 forced to zero). #[test] fn wiener_filter_roundtrips() { for chroma in [false, true] { let units = [ wiener_from_taps([0, 0, 8], [0, 0, 8]), wiener_from_taps([0, 4, 12], [0, 0, -8]), wiener_from_taps([0, 0, 0], [0, 0, 0]), ]; let units: Vec = units.to_vec(); let mut enc = SymbolEncoder::new(); let mut wref = WienerInfo::default(); for u in &units { write_wiener_filter(&mut enc, chroma, &mut wref, u); } let payload = enc.finish(); let mut dec = SymbolDecoder::new(&payload); let mut rref = WienerInfo::default(); for u in &units { assert_eq!( read_wiener_filter(&mut dec, chroma, &mut rref), *u, "chroma={chroma}" ); } } } }