forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

restoration.rs1838 lines, 71.7 KiBHistoryRawDownload
1//! AV1 loop restoration: spec 5.11.57 `read_lr`/`read_lr_unit` (per-superblock
2//! symbol reads, once corners are computed per
3//! `av1_loop_restoration_corners_in_sb`, restoration.c:1277) and spec 7.17's
4//! two pixel filters (Wiener, self-guided/SGR). See `lanes/lr.report.md` for
5//! the full derivation (libaom `decodeframe.c`/`restoration.c` line refs).
6use archmage::SimdToken;
7use crate::hits::hit;
8
9use crate::msac::SymbolDecoder;
10use ec_av1_syntax::obu::floor_log2;
11use ec_av1_syntax::{LoopRestorationParams, RestorationType};
12
13/// `ns(n)` (spec 4.10.7) read through the arithmetic coder's equiprobable
14/// bit primitive (`aom_read_literal`/`SymbolDecoder::literal`), matching
15/// libaom's `read_primitive_quniform_`. Same algorithm as
16/// `ec_av1_syntax::obu::read_ns`, ported to the msac reader `decode_subexp`
17/// needs (LR's coefficients ride the arithmetic-coded tile, not the
18/// uncompressed header `BitReader` global motion's subexp already targets).
19fn ns_msac(dec: &mut SymbolDecoder, n: u32) -> u32 {
20 if n <= 1 {
21 return 0;
22 }
23 let w = floor_log2(n) + 1;
24 let m = (1u32 << w) - n;
25 let v = dec.literal(w - 1);
26 if v < m {
27 return v;
28 }
29 (v << 1) - m + dec.literal(1)
30}
31
32/// `decode_subexp()` (spec 5.9.28) with `k` a parameter, not the fixed `3`
33/// global motion uses -- libaom's `read_primitive_subexpfin_`. LR's Wiener
34/// taps and SGR `xqd` each pick a different `k` (1/2/3 for the three Wiener
35/// taps, 4 for SGR).
36fn decode_subexp_msac(dec: &mut SymbolDecoder, num_syms: u32, k: u32) -> u32 {
37 let mut i = 0u32;
38 let mut mk = 0u32;
39 loop {
40 let b = if i > 0 { k + i - 1 } else { k };
41 let a = 1u32 << b;
42 if num_syms <= mk + 3 * a {
43 return ns_msac(dec, num_syms - mk) + mk;
44 }
45 if dec.literal(1) == 0 {
46 return dec.literal(b) + mk;
47 }
48 i += 1;
49 mk += a;
50 }
51}
52
53/// `inv_recenter_nonneg` (`aom_dsp/recenter.h`) == spec `inverse_recenter`.
54fn inverse_recenter(r: u32, v: u32) -> u32 {
55 if v > 2 * r {
56 v
57 } else if v & 1 != 0 {
58 r - ((v + 1) >> 1)
59 } else {
60 r + (v >> 1)
61 }
62}
63
64/// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed
65/// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around
66/// `reference`.
67fn decode_unsigned_subexp_with_ref_msac(
68 dec: &mut SymbolDecoder,
69 n: u32,
70 k: u32,
71 reference: u32,
72) -> u32 {
73 let v = decode_subexp_msac(dec, n, k);
74 if (reference << 1) <= n {
75 inverse_recenter(reference, v)
76 } else {
77 n - 1 - inverse_recenter(n - 1 - reference, v)
78 }
79}
80
81/// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter`
82/// call `aom_read_primitive_refsubexpfin(rb, max-min+1, k, ref-min)+min`.
83fn decode_signed_subexp_with_ref_msac(
84 dec: &mut SymbolDecoder,
85 low: i32,
86 high: i32,
87 k: u32,
88 reference: i32,
89) -> i32 {
90 let n = (high - low) as u32;
91 let r = (reference - low).clamp(0, n as i32) as u32;
92 decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low
93}
94
95// ---------------------------------------------------------------------------
96// lane-av1lr: the WRITE side of the three primitives above, for the encoder's
97// per-restoration-unit syntax (`crate::tile`). Each is libaom's own writer
98// (`aom_dsp/bitwriter.h`'s `write_primitive_*`) and the exact inverse of the
99// reader it sits under; `wiener_filter_roundtrips` below pins the pair.
100
101/// `aom_write_primitive_quniform`, the inverse of [`ns_msac`].
102fn write_ns(enc: &mut crate::msac::SymbolEncoder, n: u32, v: u32) {
103 if n <= 1 {
104 return;
105 }
106 let w = floor_log2(n) + 1;
107 let m = (1u32 << w) - n;
108 if v < m {
109 enc.literal(v, w - 1);
110 } else {
111 enc.literal(m + ((v - m) >> 1), w - 1);
112 enc.literal((v - m) & 1, 1);
113 }
114}
115
116/// `aom_write_primitive_subexpfin`, the inverse of [`decode_subexp_msac`].
117fn write_subexp(enc: &mut crate::msac::SymbolEncoder, num_syms: u32, k: u32, v: u32) {
118 let mut i = 0u32;
119 let mut mk = 0u32;
120 loop {
121 let b = if i > 0 { k + i - 1 } else { k };
122 let a = 1u32 << b;
123 if num_syms <= mk + 3 * a {
124 write_ns(enc, num_syms - mk, v - mk);
125 return;
126 }
127 if v < mk + a {
128 enc.literal(0, 1);
129 enc.literal(v - mk, b);
130 return;
131 }
132 enc.literal(1, 1);
133 i += 1;
134 mk += a;
135 }
136}
137
138/// `recenter_nonneg`, the inverse of [`inverse_recenter`].
139fn recenter(r: u32, v: u32) -> u32 {
140 if v > 2 * r {
141 v
142 } else if v >= r {
143 (v - r) << 1
144 } else {
145 ((r - v) << 1) - 1
146 }
147}
148
149/// Inverse of [`decode_unsigned_subexp_with_ref_msac`].
150fn write_unsigned_subexp_with_ref(
151 enc: &mut crate::msac::SymbolEncoder,
152 n: u32,
153 k: u32,
154 reference: u32,
155 v: u32,
156) {
157 let recentred = if (reference << 1) <= n {
158 recenter(reference, v)
159 } else {
160 recenter(n - 1 - reference, n - 1 - v)
161 };
162 write_subexp(enc, n, k, recentred);
163}
164
165/// Inverse of [`decode_signed_subexp_with_ref_msac`].
166fn write_signed_subexp_with_ref(
167 enc: &mut crate::msac::SymbolEncoder,
168 low: i32,
169 high: i32,
170 k: u32,
171 reference: i32,
172 v: i32,
173) {
174 let n = (high - low) as u32;
175 let r = (reference - low).clamp(0, n as i32) as u32;
176 write_unsigned_subexp_with_ref(enc, n, k, r, (v - low).clamp(0, n as i32 - 1) as u32);
177}
178
179/// Inverse of [`read_wiener_filter`]: writes one unit's two directions and
180/// advances the caller's running per-plane reference, exactly as the reader
181/// advances its own.
182pub(crate) fn write_wiener_filter(
183 enc: &mut crate::msac::SymbolEncoder,
184 chroma: bool,
185 reference: &mut WienerInfo,
186 info: &WienerInfo,
187) {
188 write_wiener_direction(enc, chroma, &reference.vfilter, &info.vfilter);
189 write_wiener_direction(enc, chroma, &reference.hfilter, &info.hfilter);
190 *reference = *info;
191}
192
193/// Inverse of [`read_wiener_direction`].
194fn write_wiener_direction(
195 enc: &mut crate::msac::SymbolEncoder,
196 chroma: bool,
197 reference: &[i32; 7],
198 taps: &[i32; 7],
199) {
200 for i in 0..3 {
201 if i == 0 && chroma {
202 continue;
203 }
204 write_signed_subexp_with_ref(
205 enc,
206 WIENER_TAP_MINV[i],
207 WIENER_TAP_MAXV[i] + 1,
208 WIENER_TAP_K[i],
209 reference[i],
210 taps[i],
211 );
212 }
213}
214
215/// A Wiener unit's three free taps per direction, as [`WienerInfo`] (the
216/// centre tap is derived, spec 7.17.4).
217pub(crate) fn wiener_from_taps(v: [i32; 3], h: [i32; 3]) -> WienerInfo {
218 let fill = |t: [i32; 3]| {
219 let centre = 128 - 2 * (t[0] + t[1] + t[2]);
220 [t[0], t[1], t[2], centre, t[2], t[1], t[0]]
221 };
222 WienerInfo {
223 vfilter: fill(v),
224 hfilter: fill(h),
225 }
226}
227
228#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
229const WIENER_HALFWIN: usize = 3;
230#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
231pub(crate) const WIENER_WIN: usize = 7;
232const WIENER_TAP_MINV: [i32; 3] = [-5, -23, -17];
233const WIENER_TAP_MAXV: [i32; 3] = [10, 8, 46];
234const WIENER_TAP_K: [u32; 3] = [1, 2, 3];
235const WIENER_TAP_MIDV: [i32; 3] = [3, -7, 15];
236
237/// `WienerInfo`: a restoration unit's 7-tap separable filter, symmetric
238/// (spec `vfilter[i] == vfilter[6-i]`), with the centre tap derived
239/// (`WIENER_FILT_STEP - 2*sum(taps 0..3)`, spec 7.17.4).
240#[derive(Clone, Copy, Debug, PartialEq)]
241pub(crate) struct WienerInfo {
242 pub vfilter: [i32; 7],
243 pub hfilter: [i32; 7],
244}
245
246impl Default for WienerInfo {
247 fn default() -> Self {
248 Self {
249 vfilter: midpoint_filter(),
250 hfilter: midpoint_filter(),
251 }
252 }
253}
254
255fn midpoint_filter() -> [i32; 7] {
256 let [t0, t1, t2] = WIENER_TAP_MIDV;
257 let centre = 128 - 2 * (t0 + t1 + t2);
258 [t0, t1, t2, centre, t2, t1, t0]
259}
260
261/// One direction's 3 free taps (spec `read_wiener_filter`'s per-direction
262/// loop): reads with `k`/min/max per tap index, recentred on `ref_dir`
263/// (which the caller updates to the just-decoded value after each unit,
264/// spec `ref_wiener_info` -- reset to the midpoint filter at each tile).
265fn read_wiener_direction(dec: &mut SymbolDecoder, chroma: bool, reference: &[i32; 7]) -> [i32; 7] {
266 let mut taps = [0i32; 3];
267 for i in 0..3 {
268 // `wiener_win == WIENER_WIN_CHROMA` (5-tap) skips tap 0, which is
269 // always 0 for chroma (spec `read_wiener_filter`, `wiener_win`
270 // branch on plane).
271 if i == 0 && chroma {
272 taps[0] = 0;
273 continue;
274 }
275 taps[i] = decode_signed_subexp_with_ref_msac(
276 dec,
277 WIENER_TAP_MINV[i],
278 WIENER_TAP_MAXV[i] + 1,
279 WIENER_TAP_K[i],
280 reference[i],
281 );
282 }
283 let centre = 128 - 2 * (taps[0] + taps[1] + taps[2]);
284 [taps[0], taps[1], taps[2], centre, taps[2], taps[1], taps[0]]
285}
286
287/// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating
288/// `reference` in place (the running per-plane, per-tile reference state).
289fn read_wiener_filter(
290 dec: &mut SymbolDecoder,
291 chroma: bool,
292 reference: &mut WienerInfo,
293) -> WienerInfo {
294 let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter);
295 let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter);
296 let info = WienerInfo { vfilter, hfilter };
297 *reference = info;
298 info
299}
300
301/// `SgrprojInfo`: one self-guided restoration unit's parameter-set index
302/// and the two (at most) coded correction weights.
303#[derive(Clone, Copy, Debug, PartialEq)]
304pub(crate) struct SgrprojInfo {
305 pub ep: usize,
306 pub xqd: [i32; 2],
307}
308
309const SGRPROJ_PRJ_BITS: i32 = 7;
310const SGRPROJ_PRJ_MIN0: i32 = -(1 << SGRPROJ_PRJ_BITS) * 3 / 4;
311const SGRPROJ_PRJ_MAX0: i32 = SGRPROJ_PRJ_MIN0 + (1 << SGRPROJ_PRJ_BITS) - 1;
312const SGRPROJ_PRJ_MIN1: i32 = -(1 << SGRPROJ_PRJ_BITS) / 4;
313const SGRPROJ_PRJ_MAX1: i32 = SGRPROJ_PRJ_MIN1 + (1 << SGRPROJ_PRJ_BITS) - 1;
314const SGRPROJ_PRJ_SUBEXP_K: u32 = 4;
315
316/// `av1_sgr_params` (`restoration.c:36`): `(r0, r1, s0, s1)` per of the 16
317/// `SGRPROJ_PARAMS_BITS`-selected parameter sets. `r == 0` for a radius
318/// means that pass is skipped (its `xqd` is then forced, not coded).
319pub(crate) const SGR_PARAMS: [(i32, i32, i32, i32); 16] = [
320 (2, 1, 140, 3236),
321 (2, 1, 112, 2158),
322 (2, 1, 93, 1618),
323 (2, 1, 80, 1438),
324 (2, 1, 70, 1295),
325 (2, 1, 58, 1177),
326 (2, 1, 47, 1079),
327 (2, 1, 37, 996),
328 (2, 1, 30, 925),
329 (2, 1, 25, 863),
330 (0, 1, -1, 2589),
331 (0, 1, -1, 1618),
332 (0, 1, -1, 1177),
333 (0, 1, -1, 925),
334 (2, 0, 56, -1),
335 (2, 0, 22, -1),
336];
337
338/// `read_sgrproj_filter` (decodeframe.c ~1651). `reference` is the running
339/// per-plane, per-tile `xqd` state (spec `ref_sgrproj_info`), updated in
340/// place after every read (both coded and forced components).
341fn read_sgrproj_filter(dec: &mut SymbolDecoder, reference: &mut SgrprojInfo) -> SgrprojInfo {
342 let ep = dec.literal(4) as usize;
343 let (r0, r1, _s0, _s1) = SGR_PARAMS[ep];
344 let mut xqd = [0i32; 2];
345 if r0 == 0 {
346 xqd[0] = 0;
347 xqd[1] = decode_unsigned_subexp_with_ref_msac(
348 dec,
349 (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32,
350 SGRPROJ_PRJ_SUBEXP_K,
351 (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32,
352 ) as i32
353 + SGRPROJ_PRJ_MIN1;
354 } else if r1 == 0 {
355 xqd[0] = decode_unsigned_subexp_with_ref_msac(
356 dec,
357 (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32,
358 SGRPROJ_PRJ_SUBEXP_K,
359 (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32,
360 ) as i32
361 + SGRPROJ_PRJ_MIN0;
362 xqd[1] = ((1 << SGRPROJ_PRJ_BITS) - xqd[0]).clamp(SGRPROJ_PRJ_MIN1, SGRPROJ_PRJ_MAX1);
363 } else {
364 xqd[0] = decode_unsigned_subexp_with_ref_msac(
365 dec,
366 (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32,
367 SGRPROJ_PRJ_SUBEXP_K,
368 (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32,
369 ) as i32
370 + SGRPROJ_PRJ_MIN0;
371 xqd[1] = decode_unsigned_subexp_with_ref_msac(
372 dec,
373 (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32,
374 SGRPROJ_PRJ_SUBEXP_K,
375 (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32,
376 ) as i32
377 + SGRPROJ_PRJ_MIN1;
378 }
379 let info = SgrprojInfo { ep, xqd };
380 *reference = info;
381 info
382}
383
384impl Default for SgrprojInfo {
385 fn default() -> Self {
386 Self {
387 ep: 0,
388 xqd: [
389 (SGRPROJ_PRJ_MIN0 + SGRPROJ_PRJ_MAX0) / 2,
390 (SGRPROJ_PRJ_MIN1 + SGRPROJ_PRJ_MAX1) / 2,
391 ],
392 }
393 }
394}
395
396/// One restoration unit's decoded filter (spec `RestorationUnitInfo`,
397/// `RESTORE_NONE`/`WIENER`/`SGRPROJ` -- `Switchable`-frame units pick one of
398/// these per unit; `Wiener`/`Sgrproj`-frame units are all this same variant
399/// or `None`).
400#[derive(Clone, Copy, Debug, PartialEq)]
401pub(crate) enum UnitFilter {
402 None,
403 Wiener(WienerInfo),
404 Sgrproj(SgrprojInfo),
405}
406
407/// Per-plane restoration-unit grid for one tile/frame (spec `RestorationInfo`
408/// per plane) -- `av1_lr_count_units`'s `horz_units`/`vert_units` sizing plus
409/// the flattened `runit_idx = rcol + rrow*horz_units` storage `read_lr`
410/// fills in superblock order.
411pub(crate) struct RestorationGrid {
412 pub horz_units: [usize; 3],
413 pub vert_units: [usize; 3],
414 units: [Vec<UnitFilter>; 3],
415}
416
417impl RestorationGrid {
418 pub(crate) fn new(lr: &LoopRestorationParams, frame_width: u32, frame_height: u32) -> Self {
419 Self::with_ss(lr, frame_width, frame_height, 1, 1)
420 }
421
422 pub(crate) fn with_ss(
423 lr: &LoopRestorationParams,
424 frame_width: u32,
425 frame_height: u32,
426 ss_x: u8,
427 ss_y: u8,
428 ) -> Self {
429 let mut horz_units = [1usize; 3];
430 let mut vert_units = [1usize; 3];
431 let mut units: [Vec<UnitFilter>; 3] = [Vec::new(), Vec::new(), Vec::new()];
432 for plane in 0..3 {
433 if lr.frame_restoration_type[plane] == RestorationType::None {
434 continue;
435 }
436 let (pw, ph) = if plane == 0 {
437 (frame_width, frame_height)
438 } else {
439 (
440 (frame_width + u32::from(ss_x)) >> ss_x,
441 (frame_height + u32::from(ss_y)) >> ss_y,
442 )
443 };
444 let unit_size = lr.loop_restoration_size[plane];
445 horz_units[plane] = count_units(pw, unit_size);
446 vert_units[plane] = count_units(ph, unit_size);
447 units[plane] = vec![UnitFilter::None; horz_units[plane] * vert_units[plane]];
448 }
449 Self {
450 horz_units,
451 vert_units,
452 units,
453 }
454 }
455
456 pub(crate) fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) {
457 let idx = rcol + rrow * self.horz_units[plane];
458 self.units[plane][idx] = filter;
459 }
460
461 pub(crate) fn get(&self, plane: usize, rrow: usize, rcol: usize) -> UnitFilter {
462 let idx = rcol + rrow * self.horz_units[plane];
463 self.units[plane][idx]
464 }
465}
466
467/// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest.
468pub(crate) fn count_units(plane_size: u32, unit_size: u32) -> usize {
469 (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize
470}
471
472fn ceil_div(a: u32, b: u32) -> u32 {
473 a.div_ceil(b)
474}
475
476/// `read_lr` (spec 5.11.57) for one superblock at mode-info position
477/// `(mi_row, mi_col)`: for every plane the frame uses LR on, computes the
478/// unit-grid corners this superblock covers
479/// (`av1_loop_restoration_corners_in_sb`, restoration.c:1277 -- every unit
480/// is >= 64px, so only the top-of-superblock call ever has non-empty
481/// corners, matching this decoder's own once-per-SB call site) and reads
482/// one `read_lr_unit` per covered `(rrow, rcol)`, per plane, in plane
483/// order.
484///
485/// `mi_row`/`mi_col`/`sb_mi` are all in **mode-info units (4x4)**, in true
486/// frame coordinates -- this is the one call that converts a superblock's
487/// position into absolute frame space, so it cannot carry the half-mi
488/// convention the partition walks use. A 64px superblock is 8 mi and a
489/// 128px superblock is 16 mi; the callers pass `SB_MI / 2` and `SB_MI`
490/// respectively (`SB_MI` being 16). The corners themselves then step each
491/// axis by [`MI_SIZE_8PX`] pixels -- see that constant's doc for why it is
492/// 8 and not libaom's 4.
493#[allow(clippy::too_many_arguments)]
494pub(crate) fn read_lr(
495 dec: &mut SymbolDecoder,
496 cdfs: &mut crate::cdf_state::Cdfs,
497 lr: &LoopRestorationParams,
498 grid: &mut RestorationGrid,
499 reference: &mut [(WienerInfo, SgrprojInfo); 3],
500 mi_row: u32,
501 mi_col: u32,
502 sb_mi: u32,
503 fctx: &crate::decode::FrameCtx,
504) {
505 if !lr.uses_lr {
506 return;
507 }
508 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
509 #[allow(clippy::needless_range_loop)]
510 for plane in 0..3 {
511 let ftype = lr.frame_restoration_type[plane];
512 if ftype == RestorationType::None {
513 continue;
514 }
515 // `av1_loop_restoration_corners_in_sb` (restoration.c:1303-1338),
516 // transcribed per axis. The two axes are NOT symmetric: libaom
517 // derives `mi_size_x` from `subsampling_x` and `mi_size_y` from
518 // `subsampling_y`, and derives the row corners from the Y term
519 // alone. This decoder used one `mi_size = 4 >> subsampling_x` for
520 // both axes, so at 4:2:2 (ss_x 1, ss_y 0) the row range was
521 // computed from the COLUMN axis's subsampling -- a 4x-too-small
522 // row step, which made `rrow0 == rrow1` (an empty range, zero
523 // `read_lr_unit` calls) wherever libaom reads a chroma unit. That
524 // is the two missing `wiener_restore_cdf` reads this lane spent
525 // nine rounds localising: the oracle reads three at mi(30,62),
526 // this decoder read one.
527 //
528 // One mode-info unit is 8 pixels (`MI_SIZE_8PX`; see its doc for why
529 // that is not libaom's `MI_SIZE`). Superres
530 // widens the column axis only (spec 7.16), so it enters `num_x`
531 // and `denom_x` and leaves the row axis alone, exactly as libaom
532 // does with `av1_superres_scaled`.
533 let is_uv = plane != 0;
534 let ss_x = if is_uv {
535 crate::decode::ss_x(fctx) as u32
536 } else {
537 0
538 };
539 let ss_y = if is_uv {
540 crate::decode::ss_y(fctx) as u32
541 } else {
542 0
543 };
544 let mi_size_x = MI_SIZE_8PX >> ss_x;
545 let mi_size_y = MI_SIZE_8PX >> ss_y;
546 let unit_size = lr.loop_restoration_size[plane];
547 let horz_units = grid.horz_units[plane] as u32;
548 let vert_units = grid.vert_units[plane] as u32;
549 let (num_x, denom_x) = match crate::decode::superres(fctx) {
550 Some((_, d)) => (mi_size_x * d, unit_size * SCALE_NUMERATOR),
551 None => (mi_size_x, unit_size),
552 };
553 let num_y = mi_size_y;
554 let denom_y = unit_size;
555 let rcol0 = ceil_div(mi_col * num_x, denom_x);
556 let rcol1 = ceil_div((mi_col + sb_mi) * num_x, denom_x).min(horz_units);
557 let rrow0 = ceil_div(mi_row * num_y, denom_y);
558 let rrow1 = ceil_div((mi_row + sb_mi) * num_y, denom_y).min(vert_units);
559 let chroma = plane != 0;
560 for rrow in rrow0..rrow1 {
561 for rcol in rcol0..rcol1 {
562 let filter = read_lr_unit(dec, cdfs, ftype, chroma, &mut reference[plane]);
563 grid.set(plane, rrow as usize, rcol as usize, filter);
564 }
565 }
566 }
567}
568
569// r3 gate self-pin: how many units decoded a real (non-`None`) filter, by
570// kind -- proves a real `--enable-restoration=1` aomenc stream actually
571// exercises `read_lr_unit`'s Wiener/SGR/switchable arms, not just that the
572// symbol-count/refusal-string wiring compiles. Never reset -- summed across
573// a gate's whole attempt loop, matching `MASKED_COMPOUND_HITS`/`WEDGE_HITS`
574// (decode.rs) which this mirrors.
575thread_local! {
576 static WIENER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
577 static SGRPROJ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
578 static SWITCHABLE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
579}
580
581// lane-reelckf2 r1: how many *stripes* a real filter ran on with the frame's
582// own top row as their above boundary (`stripe_v_start == 0`, the 56-row
583// first stripe of `RESTORATION_UNIT_OFFSET == 8`), and how many ran on a
584// short LAST stripe (`stripe_v_end == plane_h` with a partial height). Those
585// are the two stripe shapes whose boundary substitution differs from every
586// interior stripe, and no gate size before this one had either.
587thread_local! {
588 static LR_STRIPE0_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
589 static LR_LAST_STRIPE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
590}
591
592/// Pixels per mode-info unit (4x4 mi is 8 pixels). This is what
593/// `av1_loop_restoration_corners_in_sb` (`restoration.c:1303-1338`) steps
594/// each axis by, subsampled per axis: `MI_SIZE_8PX >> ss_x` for columns,
595/// `MI_SIZE_8PX >> ss_y` for rows.
596///
597/// NAMING, because it is a trap: libaom's own `MI_SIZE` is **4**
598/// (`av1/common/enums.h:39-40`, `1 << MI_SIZE_LOG2` with `MI_SIZE_LOG2 2`),
599/// and libaom writes `mi_size_x = MI_SIZE >> ss_x` -- the same expression,
600/// at half this value. The factor of two is not a transcription slip: its
601/// `denom_x`/`denom_y` (`rsi->restoration_unit_size`) is a PIXEL count
602/// (128 for a 128px superblock), so libaom's numerator and denominator
603/// already sit on opposite scales, and doubling the numerator lands both in
604/// pixels. This constant is deliberately NOT called `MI_SIZE`, so nobody
605/// "corrects" it back to 4 and halves every restoration-unit range.
606///
607/// The authority is the paired trace, not this comment: at 8 the whole
608/// 16-frame 4:2:2 stream pairs 246735-for-246735 against the instrumented
609/// oracle, and at 4 it does not.
610const MI_SIZE_8PX: u32 = 8;
611/// `SCALE_NUMERATOR` (aom_scale.h): the superres scale's fixed point, 8.
612const SCALE_NUMERATOR: u32 = 8;
613/// Current value of [`LR_STRIPE0_HITS`].
614#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
615pub(crate) fn lr_stripe0_hits() -> usize {
616 LR_STRIPE0_HITS.with(|c| c.get())
617}
618/// Current value of [`LR_LAST_STRIPE_HITS`].
619#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
620pub(crate) fn lr_last_stripe_hits() -> usize {
621 LR_LAST_STRIPE_HITS.with(|c| c.get())
622}
623
624/// Current value of [`WIENER_HITS`].
625#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
626pub(crate) fn wiener_hits() -> usize {
627 WIENER_HITS.with(|c| c.get())
628}
629/// Current value of [`SGRPROJ_HITS`].
630#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
631pub(crate) fn sgrproj_hits() -> usize {
632 SGRPROJ_HITS.with(|c| c.get())
633}
634/// Current value of [`SWITCHABLE_HITS`] -- bumped once per unit whose frame
635/// `restoration_type` is `Switchable`, regardless of which `RestoreType`
636/// (`None`/Wiener/Sgrproj) that unit's own symbol resolved to.
637#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
638pub(crate) fn switchable_hits() -> usize {
639 SWITCHABLE_HITS.with(|c| c.get())
640}
641
642fn read_lr_unit(
643 dec: &mut SymbolDecoder,
644 cdfs: &mut crate::cdf_state::Cdfs,
645 ftype: RestorationType,
646 chroma: bool,
647 reference: &mut (WienerInfo, SgrprojInfo),
648) -> UnitFilter {
649 match ftype {
650 RestorationType::Switchable => {
651 hit!(SWITCHABLE_HITS);
652 let t = dec.symbol(&mut cdfs.restore_switchable);
653 match t {
654 0 => UnitFilter::None,
655 1 => {
656 hit!(WIENER_HITS);
657 UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))
658 }
659 _ => {
660 hit!(SGRPROJ_HITS);
661 UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
662 }
663 }
664 }
665 RestorationType::Wiener => {
666 if dec.symbol(&mut cdfs.restore_wiener) != 0 {
667 hit!(WIENER_HITS);
668 UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))
669 } else {
670 UnitFilter::None
671 }
672 }
673 RestorationType::Sgrproj => {
674 let bit = dec.symbol(&mut cdfs.restore_sgrproj);
675 if bit != 0 {
676 hit!(SGRPROJ_HITS);
677 UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
678 } else {
679 UnitFilter::None
680 }
681 }
682 RestorationType::None => UnitFilter::None,
683 }
684}
685
686// ---------------------------------------------------------------------
687// Spec 7.17: the two pixel filters (Wiener, self-guided) plus the
688// restoration-unit/stripe walk that drives them.
689// ---------------------------------------------------------------------
690
691/// `Round2` (spec 4.7): halves round up, arithmetic shift for negative sums
692/// -- same primitive as `mc.rs`/`warp.rs`'s own `round2`, here at `i64`
693/// since the self-guided filter's intermediate products don't fit `i32`.
694fn round2(value: i64, shift: u32) -> i64 {
695 if shift == 0 {
696 value
697 } else {
698 (value + (1i64 << (shift - 1))) >> shift
699 }
700}
701
702/// One plane's sample fetch for the pixel filters (spec 7.17.2's stripe
703/// boundary substitution, libaom `setup_processing_stripe_boundary`/
704/// `get_stripe_boundary_info`): within the stripe `[stripe_v_start,
705/// stripe_v_end)` currently being filtered, read the post-CDEF plane;
706/// outside it (the 3-row border both filters' kernels reach into), read the
707/// post-deblock, pre-CDEF plane instead -- UNLESS the stripe is the very
708/// first/last stripe in the whole plane, where the frame's own top/bottom
709/// edge replicates (`av1_extend_frame`) rather than crossing into deblocked
710/// data. Columns always clamp to the plane's own true width -- restoration
711/// unit COLUMN boundaries have no such substitution, only stripe (row)
712/// boundaries do.
713#[allow(clippy::too_many_arguments)]
714fn lr_sample(
715 cdef: &[u16],
716 deblocked: &[u16],
717 stride: usize,
718 plane_w: usize,
719 plane_h: usize,
720 stripe_v_start: usize,
721 stripe_v_end: usize,
722 row: i64,
723 col: i64,
724) -> i32 {
725 let col_c = col.clamp(0, plane_w as i64 - 1) as usize;
726 i32::from(
727 lr_src_row(
728 cdef,
729 deblocked,
730 stride,
731 plane_w,
732 plane_h,
733 stripe_v_start,
734 stripe_v_end,
735 row,
736 )[col_c],
737 )
738}
739
740/// The plane row [`lr_sample`] reads, resolved once. Which buffer and which
741/// row a sample comes from depends only on `row` -- the column only ever
742/// clamps -- so a whole-row consumer (the Wiener horizontal pass) resolves
743/// the substitution once per row instead of once per tap. [`lr_sample`] is
744/// this function plus that clamp, so the rule has one statement.
745#[allow(clippy::too_many_arguments)]
746fn lr_src_row<'a>(
747 cdef: &'a [u16],
748 deblocked: &'a [u16],
749 stride: usize,
750 plane_w: usize,
751 plane_h: usize,
752 stripe_v_start: usize,
753 stripe_v_end: usize,
754 row: i64,
755) -> &'a [u16] {
756 let (buf, src_row) = if row >= stripe_v_start as i64 && row < stripe_v_end as i64 {
757 (cdef, row as usize)
758 } else if row < stripe_v_start as i64 {
759 if stripe_v_start == 0 {
760 (cdef, 0)
761 } else {
762 // libaom saves 2 deblocked context lines and duplicates the
763 // outer one to fill a 3-row border (`RESTORATION_BORDER`):
764 // row `stripe_v_start-1` reads deblocked row `stripe_v_start-1`,
765 // rows `stripe_v_start-2`/`-3` both read deblocked row
766 // `stripe_v_start-2`.
767 let dist = stripe_v_start as i64 - 1 - row;
768 (
769 deblocked,
770 if dist == 0 {
771 stripe_v_start - 1
772 } else {
773 stripe_v_start.saturating_sub(2)
774 },
775 )
776 }
777 } else if stripe_v_end == plane_h {
778 (cdef, plane_h - 1)
779 } else {
780 // Mirror image of the above: rows `stripe_v_end`/`stripe_v_end+1`
781 // read their own deblocked row, row `stripe_v_end+2` duplicates
782 // `stripe_v_end+1`.
783 let dist = (row - stripe_v_end as i64).min(1) as usize;
784 (deblocked, (stripe_v_end + dist).min(plane_h - 1))
785 };
786 &buf[src_row * stride..src_row * stride + plane_w]
787}
788
789/// Wiener pixel filter (spec 7.17.4, libaom `wiener_filter_stripe` ->
790/// `av1_wiener_convolve_add_src_c`), one stripe-height chunk of one
791/// restoration unit: a separable 7-tap horizontal pass (rounded by
792/// `WIENER_ROUND0_BITS==3`, clipped to spec's intermediate range) feeding a
793/// 7-tap vertical pass (rounded by `2*FILTER_BITS-3==11`) -- the same
794/// `INTER_ROUND_0`/`INTER_ROUND_1` shifts `mc.rs`'s motion compensation
795/// uses, since AV1 reuses that same separable-filter machinery here with a
796/// custom 7-tap kernel instead of the fixed subpel tables. libaom's C
797/// folds an extra `+/- (1 << ...)` bias into each pass to compensate for a
798/// pointer-alignment trick that borrows the interpolation filter's 8-tap
799/// convolution loop for a 7-tap kernel; that bias cancels algebraically
800/// against `WienerInfo`'s own derived centre tap (`128 - 2*sum(taps)`), so
801/// plugging the real taps straight into `sum(tap * sample)` (no bias term)
802/// reproduces the same output byte-for-byte.
803#[allow(clippy::too_many_arguments)]
804fn apply_wiener_stripe(
805 out: &mut [u16],
806 row0: usize,
807 cdef: &[u16],
808 deblocked: &[u16],
809 stride: usize,
810 plane_w: usize,
811 plane_h: usize,
812 h_start: usize,
813 h_end: usize,
814 v_start: usize,
815 v_end: usize,
816 info: &WienerInfo,
817 fctx: &crate::decode::FrameCtx,
818) {
819 let w = h_end - h_start;
820 let h = v_end - v_start;
821 if w == 0 || h == 0 {
822 return;
823 }
824 let bd = i64::from(crate::decode::bit_depth(fctx));
825 // lane-av112bit: libaom `get_conv_params_wiener` (`convolve.h:107..118`)
826 // raises the Wiener pair by the same `intbufrange` delta as MC's: at
827 // 12-bit `round_0` is 5 and `round_1` 9 (8/10-bit: 3 and 11). The ROUNDS
828 // are parameterised; the intermediate CLAMP below keeps the corpus-proven
829 // constant-bound structure extended by the same bd formulas -- a first
830 // attempt at the C clamp's exact per-sample transform (the add_src bias
831 // is `src[centre] << FILTER_BITS + (1 << (bd + FILTER_BITS - 1))`, which
832 // survives `Round2(_, round_0)` as `(128 >> round_0) * s +
833 // (1 << (bd + 6 - round_0))`) MOVED the 10-bit 128-superblock film gate
834 // (frame 1 luma): libaom's 8-tap-loop alignment trick means the C
835 // horizontal intermediate is not `ours + that bias` wherever the clamp
836 // actually binds, so the exact transform is NOT derivable from the
837 // convolve source alone. The bd-formula clamp is what every 8/10-bit
838 // byte-exact gate (this film included) has always pinned, and the 12-bit
839 // key witness passes byte-exact with it; where C's real clamp would bind
840 // differently at 12 bits remains unproven either way -- recorded in
841 // `lanes/av112bit.report.md` as the open half of the Wiener lift.
842 let wiener_bias = 1i64 << (bd + 3);
843 let wiener_limit = 1i64 << (bd + 5);
844 let (round0, round1) = crate::mc::round_pair(bd as u32);
845 let rows = h + 6;
846 // lane-perf7: reused across stripes, as the sgrproj `ab` grids are --
847 // this was a fresh allocation per stripe. Every entry is written below.
848 let mut inter = WIENER_INTER_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
849 inter.clear();
850 // lane-perf8: `mc::vpass_row` reads a fixed 8 taps from `row`, so the
851 // last vertical output needs two rows of padding past the `h + 6` the
852 // 7-tap kernel actually uses. Tap 7 is zero, so they never contribute.
853 inter.resize((h + 8) * w, 0i16);
854 // lane-perf8: this pass IS `mc.rs`'s horizontal one -- a 7-tap `i16`
855 // convolution over contiguous samples rounded by `Round2(_, 3)`, which
856 // is `INTER_ROUND_0` -- so it runs on that module's kernels with the
857 // eighth tap zeroed, instead of a scalar `lr_sample` call per tap. The
858 // stripe substitution is resolved once per row by `lr_src_row`, and only
859 // a unit touching the plane's left or right edge needs the clamped copy.
860 let hf = &info.hfilter;
861 let t16: [i16; 8] = [
862 hf[0] as i16,
863 hf[1] as i16,
864 hf[2] as i16,
865 hf[3] as i16,
866 hf[4] as i16,
867 hf[5] as i16,
868 hf[6] as i16,
869 0,
870 ];
871 // lane-mc: the intermediate is `i16` now. Both bounds are inside that
872 // range at every supported bit depth (the centred sum's own range,
873 // `|kernel| <= 348` against `2^bd - 1` samples, never reaches them), so
874 // the kernel's saturating store composes with this clamp instead of
875 // changing it: `[-2^(bd+3), 2^(bd+5)-1-2^(bd+3)]` -- 8-bit
876 // `[-2048, 6143]`, 10-bit `[-8192, 24575]`. At 12-bit those formulas
877 // leave `i16`, so the clamp there is the widest `i16` window -- which
878 // strictly contains the kernel's own mathematical range (`|sum| <=
879 // round2(348 * 4095, round_0=5) == 27976 < 2^15`), i.e. it never binds,
880 // the property the 8/10-bit bounds have on the whole proven corpus.
881 let (lo_bound, hi_bound) = if bd >= 12 {
882 (i16::MIN, i16::MAX)
883 } else {
884 (-wiener_bias as i16, (wiener_limit - 1 - wiener_bias) as i16)
885 };
886 let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
887 for r in 0..rows {
888 let row = v_start as i64 - 3 + r as i64;
889 let src = lr_src_row(
890 cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row,
891 );
892 let lo = h_start as i64 - 3;
893 let out = &mut inter[r * w..r * w + w];
894 // The row the pass convolves, contiguous when the block sits inside
895 // the plane and the clamped copy (`hbuf`) at an edge.
896 let interior = lo >= 0 && lo as usize + w + 7 <= plane_w;
897 if !interior {
898 hbuf.clear();
899 hbuf.extend(
900 (0..w + 7).map(|k| src[(lo + k as i64).clamp(0, plane_w as i64 - 1) as usize]),
901 );
902 }
903 let row_slice: &[u16] = if interior { &src[lo as usize..] } else { &hbuf };
904 crate::mc::hpass_contig(row_slice, &t16, out, round0);
905 for v in out.iter_mut() {
906 *v = (*v).clamp(lo_bound, hi_bound);
907 }
908 }
909 WIENER_ROW_SCRATCH.with(|c| *c.borrow_mut() = hbuf);
910 // lane-perf7: the clamp bound is the frame's, so it is read once here
911 // instead of taking a thread-local read per output sample.
912 let smax = i64::from(crate::decode::sample_max(fctx));
913 // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves
914 // the accumulator unrounded, and `Round2(_, round1)` is the frame's
915 // non-compound `round_1` (11 at 8/10-bit, 9 at 12 -- libaom's
916 // `get_conv_params_wiener`).
917 let vf = &info.vfilter;
918 let taps: [i32; 8] = [vf[0], vf[1], vf[2], vf[3], vf[4], vf[5], vf[6], 0];
919 let mut acc = WIENER_ACC_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
920 acc.clear();
921 acc.resize(w, 0i32);
922 for r in 0..h {
923 crate::mc::vpass_row(&inter[r * w..], w, w, 1, &taps, &mut acc);
924 let dst = &mut out[(v_start + r - row0) * stride + h_start..][..w];
925 for (o, &a) in dst.iter_mut().zip(acc.iter()) {
926 *o = round2(i64::from(a), round1).clamp(0, smax) as u16;
927 }
928 }
929 WIENER_ACC_SCRATCH.with(|c| *c.borrow_mut() = acc);
930 WIENER_INTER_SCRATCH.with(|c| *c.borrow_mut() = inter);
931}
932
933thread_local! {
934 /// [`apply_wiener_stripe`]'s horizontal-pass intermediate, kept across
935 /// calls so a stripe does not allocate (lane-perf7).
936 static WIENER_INTER_SCRATCH: std::cell::RefCell<Vec<i16>> =
937 const { std::cell::RefCell::new(Vec::new()) };
938 /// The clamped-column copy the horizontal pass needs at a plane edge.
939 static WIENER_ROW_SCRATCH: std::cell::RefCell<Vec<u16>> =
940 const { std::cell::RefCell::new(Vec::new()) };
941 /// The vertical pass's unrounded accumulator row.
942 static WIENER_ACC_SCRATCH: std::cell::RefCell<Vec<i32>> =
943 const { std::cell::RefCell::new(Vec::new()) };
944 /// [`compute_ab`]'s two `(A, B)` grids, likewise (lane-perf7).
945 #[allow(clippy::type_complexity)]
946 static SGR_AB_SCRATCH: std::cell::RefCell<(Vec<(i32, i64)>, Vec<(i32, i64)>)> =
947 const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
948}
949
950/// `av1_x_by_xplus1` (`restoration.c`): `round(256*z/(z+1))` for `z` in
951/// `[0,255]`, saturating the `z==0` case to `1` instead of `0` (see the
952/// libaom source comment this ports -- keeps `256-A[k]` inside a `u8` and
953/// avoids a later overflow, without visibly affecting a near-flat block).
954// r8: this table was transcribed with two errors -- index 101 (253 written
955// as 254) and indices 165..=169 (254 written as 255) -- traced by comparing
956// a call-unique dump (gated on the pinned stream's `xqd == [-16,-32]`, not a
957// reused coordinate) against libaom's real `av1_x_by_xplus1` at the same
958// `z=101`; both tables now generated straight from
959// `~/.cache/aom-oracle/src/av1/common/restoration.c` to rule out any other
960// transcription slip.
961const SGR_X_BY_XPLUS1: [i32; 256] = [
962 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, 240, 241, 242, 243,
963 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, 248, 248, 248, 248, 249, 249, 249, 249,
964 249, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252,
965 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253,
966 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
967 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
968 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
969 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
970 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255,
971 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
972 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
973 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
974 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
975 255, 255, 255, 255, 255, 255, 255, 255, 256,
976];
977
978/// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25`
979/// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`.
980const SGR_ONE_BY_X: [i32; 25] = [
981 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228,
982 216, 205, 195, 186, 178, 171, 164,
983];
984
985const SGRPROJ_MTABLE_BITS: u32 = 20;
986const SGRPROJ_RECIP_BITS: u32 = 12;
987const SGRPROJ_SGR_BITS: u32 = 8;
988const SGRPROJ_RST_BITS: u32 = 4;
989
990/// `calculate_intermediate_result` (`restoration.c`): the blend-factor pair
991/// `(A[k], B[k])` at every position in `-1..=h` x `-1..=w` relative to a
992/// restoration unit (a 1-pixel border around the unit, spec 7.17.3's
993/// `BoxFilter`), for one of the two SGR radii. `r`/`s` are `SGR_PARAMS[ep]`'s
994/// `(r0,s0)` or `(r1,s1)`; libaom computes this only at odd rows for the
995/// `r==2` ("fast") radius as a running-sum speed optimisation -- the box
996/// sum itself is identical at every row regardless, so computing it
997/// everywhere (this function does, via a plain windowed sum through
998/// [`lr_sample`] rather than libaom's O(1)-per-step sliding sum) and only
999/// *reading* the odd rows back in [`apply_sgrproj_stripe`]'s fast branch
1000/// reproduces the same values without porting the sliding-window trick.
1001#[allow(clippy::too_many_arguments)]
1002fn compute_ab(
1003 cdef: &[u16],
1004 deblocked: &[u16],
1005 stride: usize,
1006 plane_w: usize,
1007 plane_h: usize,
1008 h_start: usize,
1009 v_start: usize,
1010 v_end: usize,
1011 w: usize,
1012 h: usize,
1013 r: i32,
1014 s: i32,
1015 // lane-perf7: a reused scratch buffer. This used to be a fresh
1016 // `vec![(0, 0); (w + 2) * (h + 2)]` per call (two calls per sgrproj
1017 // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every
1018 // page then faulted in on first touch. Every entry is written below, so
1019 // the resize's fill value is never read.
1020 ab: &mut Vec<(i32, i64)>,
1021 fctx: &crate::decode::FrameCtx,
1022) {
1023 let gw = w + 2;
1024 let gh = h + 2;
1025 ab.clear();
1026 ab.resize(gw * gh, (0i32, 0i64));
1027 let n = (2 * r + 1) * (2 * r + 1);
1028 // lane-perf6: the box sums are separable. Summing every grid point's own
1029 // (2r+1)^2 window called `lr_sample` -- whose stripe-boundary test is the
1030 // expensive part -- (2r+1) times more often than needed; one column-sum
1031 // pass per grid row reads each source sample once per row instead, and
1032 // the horizontal sum is then (2r+1) adds.
1033 let ru = r as usize;
1034 let ncols = gw + 2 * ru;
1035 // lane-sgr: `i32` sums. A sample is at most `2^bd - 1 <= 4095`, so the
1036 // widest possible window sum of squares is `25 * 4095^2 == 419M` and the
1037 // widest plain sum `25 * 4095 == 102k`: both far inside `i32`, and every
1038 // downstream product is either kept in `i64` (the two that need it) or
1039 // likewise bounded (`a_s * n <= 25 * 25 * 65025 / 16`). Halving the
1040 // accumulator width is what lets the row loops below vectorise.
1041 debug_assert!(crate::decode::sample_max(fctx) <= 4095);
1042 debug_assert!(s > 0);
1043 let mut sums = vec![0i32; 2 * ncols + 2 * gw];
1044 let (col_a, rest) = sums.split_at_mut(ncols);
1045 let (col_b, rest) = rest.split_at_mut(ncols);
1046 // lane-sgr: the sliding horizontal sums are laid down as two rows first,
1047 // so the `(A, B)` map over them is a straight-line pass `ab_row` can run
1048 // eight points at a time.
1049 let (a_row, b_row) = rest.split_at_mut(gw);
1050 // lane-sgr: one contiguous copy of the source row's whole footprint, with
1051 // the column clamp (edge replication) applied while filling, so the
1052 // accumulate loops below are branch-free over a plain slice instead of a
1053 // `lr_sample` call -- clamp included -- per element.
1054 let mut samp = vec![0u16; ncols];
1055 // Hoisted out of the per-point body: one thread-local read per call.
1056 let bd_shift = u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);
1057 let base_col = h_start as i64 - 1 - r as i64;
1058 let dump = crate::envflags::env_flag!("EC_LR_CALL_DUMP");
1059 let one_by_x = SGR_ONE_BY_X[(n - 1) as usize] as i64;
1060 // lane-perf9: the column sums slide down the grid too. Grid row `gi+1`'s
1061 // window is row `gi`'s minus its top source row plus one new bottom row,
1062 // so each source sample is read once per grid row instead of (2r+1)
1063 // times -- the same exactness argument as the separable split above
1064 // (integer addition is associative, and subtracting a row that was added
1065 // is exact), and `lr_sample`'s stripe-boundary test, which is what makes
1066 // a sample read expensive, is a pure function of `(row, col)`.
1067 for gi in 0..gh {
1068 let i = gi as i64 - 1;
1069 {
1070 let mut accumulate = |row: i64, add: bool| {
1071 let src = lr_src_row(
1072 cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row,
1073 );
1074 fill_clamped_row(src, plane_w, base_col, &mut samp);
1075 if add {
1076 for ((c_a, c_b), &px) in col_a.iter_mut().zip(col_b.iter_mut()).zip(samp.iter())
1077 {
1078 let px = i32::from(px);
1079 *c_a += px * px;
1080 *c_b += px;
1081 }
1082 } else {
1083 for ((c_a, c_b), &px) in col_a.iter_mut().zip(col_b.iter_mut()).zip(samp.iter())
1084 {
1085 let px = i32::from(px);
1086 *c_a -= px * px;
1087 *c_b -= px;
1088 }
1089 }
1090 };
1091 if gi == 0 {
1092 for dr in -r..=r {
1093 accumulate(v_start as i64 + i + dr as i64, true);
1094 }
1095 } else {
1096 accumulate(v_start as i64 + i - 1 - r as i64, false);
1097 accumulate(v_start as i64 + i + r as i64, true);
1098 }
1099 }
1100 // The horizontal sum slides the same way (one add and one subtract
1101 // per grid point instead of 2r+1 adds).
1102 let mut a = col_a[..2 * ru + 1].iter().sum::<i32>();
1103 let mut b = col_b[..2 * ru + 1].iter().sum::<i32>();
1104 for gj in 0..gw {
1105 if gj > 0 {
1106 a += col_a[gj + 2 * ru] - col_a[gj - 1];
1107 b += col_b[gj + 2 * ru] - col_b[gj - 1];
1108 }
1109 a_row[gj] = a;
1110 b_row[gj] = b;
1111 }
1112 ab_row(
1113 a_row,
1114 b_row,
1115 n,
1116 s,
1117 bd_shift,
1118 one_by_x,
1119 &mut ab[gi * gw..gi * gw + gw],
1120 );
1121 let dump_gj = 6i64 - h_start as i64 + 1;
1122 if dump && v_start as i64 + i == 60 && r == 1 && (0..gw as i64).contains(&dump_gj) {
1123 let gj = dump_gj as usize;
1124 let (a, b) = (a_row[gj], b_row[gj]);
1125 let a_s = round2_u31(a, 2 * bd_shift);
1126 let b_s = round2_u31(b, bd_shift);
1127 let p = (a_s * n - b_s * b_s).max(0);
1128 let z = z_index(p, s);
1129 let (a_val, b_val) = ab[gi * gw + gj];
1130 eprintln!(
1131 "EC_LR_CALL_DUMP compute_ab u_tap: r={r} s={s} n={n} box_a={a} box_b={b} \
1132 p={p} z={z} a_val={a_val} b_val={b_val}"
1133 );
1134 }
1135 }
1136}
1137
1138/// `z = Round2(p * s, SGRPROJ_MTABLE_BITS)` clamped to the
1139/// [`SGR_X_BY_XPLUS1`] domain -- the one product that does not fit 32 bits.
1140#[inline]
1141fn z_index(p: i32, s: i32) -> usize {
1142 ((i64::from(p) * i64::from(s) + (1 << (SGRPROJ_MTABLE_BITS - 1))) >> SGRPROJ_MTABLE_BITS)
1143 .clamp(0, 255) as usize
1144}
1145
1146/// One grid point's `(A[k], B[k])` from its two box sums -- libaom
1147/// `restoration.c:660..672`, and the reference every [`ab_row`] arm matches.
1148#[inline]
1149fn ab_point(a: i32, b: i32, n: i32, s: i32, bd_shift: u32, one_by_x: i64) -> (i32, i64) {
1150 // libaom `restoration.c:660` -- the box sums are brought back to the
1151 // 8-bit scale before `p` is formed (`a` is a sum of squares, so it loses
1152 // twice the shift `b` does); `B[k]` keeps the RAW `b`, only `p` uses the
1153 // scaled pair. At 8-bit both shifts are 0, which is why this was
1154 // invisible until now.
1155 let a_s = round2_u31(a, 2 * bd_shift);
1156 let b_s = round2_u31(b, bd_shift);
1157 let p = (a_s * n - b_s * b_s).max(0);
1158 let a_val = SGR_X_BY_XPLUS1[z_index(p, s)];
1159 let b_val = round2(
1160 (256 - a_val) as i64 * i64::from(b) * one_by_x,
1161 SGRPROJ_RECIP_BITS,
1162 );
1163 (a_val, b_val)
1164}
1165
1166/// One grid row's `(A, B)` pairs: [`ab_point`] per element, eight at a time
1167/// under AVX2 (the kernel is that arithmetic lane-wise, same widths).
1168#[allow(clippy::too_many_arguments)]
1169fn ab_row(
1170 a_row: &[i32],
1171 b_row: &[i32],
1172 n: i32,
1173 s: i32,
1174 bd_shift: u32,
1175 one_by_x: i64,
1176 out: &mut [(i32, i64)],
1177) {
1178 let done = match archmage::X64V3Token::summon() {
1179 Some(t) => sgr_simd::ab_row_avx2(t, a_row, b_row, n, s, bd_shift, one_by_x as i32, out),
1180 None => 0usize,
1181 };
1182 for gj in done..out.len() {
1183 out[gj] = ab_point(a_row[gj], b_row[gj], n, s, bd_shift, one_by_x);
1184 }
1185}
1186
1187/// [`ab_row`]'s AVX2 kernel.
1188#[cfg(target_arch = "x86_64")]
1189mod sgr_simd {
1190 use super::{SGRPROJ_MTABLE_BITS, SGRPROJ_RECIP_BITS, SGR_X_BY_XPLUS1};
1191 use archmage::{X64V3Token, arcane};
1192 use std::arch::x86_64::*;
1193
1194 /// Eight grid points of `super::ab_point` per iteration, returning how
1195 /// many points were written (a multiple of 8; the tail stays scalar).
1196 ///
1197 /// Every lane repeats the scalar arithmetic at the widths
1198 /// `compute_ab` proves: `a, b >= 0` and `s > 0`, `p < 2^26`,
1199 /// `p * s < 2^38`, `(256 - A) * one_by_x < 2^21` and that times
1200 /// `b < 2^17` is `< 2^38` -- so the two 64-bit products below lose no
1201 /// bit, and the unsigned `mul_epu32` sees no negative operand.
1202 #[arcane]
1203 #[allow(clippy::too_many_arguments)]
1204 pub fn ab_row_avx2(
1205 _t: X64V3Token,
1206 a_row: &[i32],
1207 b_row: &[i32],
1208 n: i32,
1209 s: i32,
1210 bd_shift: u32,
1211 one_by_x: i32,
1212 out: &mut [(i32, i64)],
1213 ) -> usize {
1214 let len = out.len().min(a_row.len()).min(b_row.len());
1215 let nv = _mm256_set1_epi32(n);
1216 let sv = _mm256_set1_epi32(s);
1217 let obx = _mm256_set1_epi32(one_by_x);
1218 let c255 = _mm256_set1_epi32(255);
1219 let c256 = _mm256_set1_epi32(256);
1220 let zero = _mm256_setzero_si256();
1221 let rnd_z = _mm256_set1_epi64x(1 << (SGRPROJ_MTABLE_BITS - 1));
1222 let rnd_b = _mm256_set1_epi64x(1 << (SGRPROJ_RECIP_BITS - 1));
1223 let sh_z = _mm_cvtsi32_si128(SGRPROJ_MTABLE_BITS as i32);
1224 let sh_b = _mm_cvtsi32_si128(SGRPROJ_RECIP_BITS as i32);
1225 let sh_a = _mm_cvtsi32_si128(2 * bd_shift as i32);
1226 let sh_bd = _mm_cvtsi32_si128(bd_shift as i32);
1227 let rnd_a = _mm256_set1_epi32(if bd_shift == 0 {
1228 0
1229 } else {
1230 1 << (2 * bd_shift - 1)
1231 });
1232 let rnd_bd = _mm256_set1_epi32(if bd_shift == 0 {
1233 0
1234 } else {
1235 1 << (bd_shift - 1)
1236 });
1237 let mut gj = 0usize;
1238 while gj + 8 <= len {
1239 let a = bytemuck::cast::<[i32; 8], __m256i>(a_row[gj..gj + 8].try_into().unwrap());
1240 let b = bytemuck::cast::<[i32; 8], __m256i>(b_row[gj..gj + 8].try_into().unwrap());
1241 let a_s = _mm256_srl_epi32(_mm256_add_epi32(a, rnd_a), sh_a);
1242 let b_s = _mm256_srl_epi32(_mm256_add_epi32(b, rnd_bd), sh_bd);
1243 let p = _mm256_max_epi32(
1244 _mm256_sub_epi32(_mm256_mullo_epi32(a_s, nv), _mm256_mullo_epi32(b_s, b_s)),
1245 zero,
1246 );
1247 let z = _mm256_min_epi32(mul_shift(p, sv, rnd_z, sh_z), c255);
1248 let zv: [i32; 8] = bytemuck::cast(z);
1249 let a_val: __m256i = bytemuck::cast(zv.map(|i| SGR_X_BY_XPLUS1[i as usize]));
1250 let t = _mm256_mullo_epi32(_mm256_sub_epi32(c256, a_val), obx);
1251 let b_val = mul_shift(t, b, rnd_b, sh_b);
1252 let av: [i32; 8] = bytemuck::cast(a_val);
1253 let bv: [i32; 8] = bytemuck::cast(b_val);
1254 for k in 0..8 {
1255 out[gj + k] = (av[k], i64::from(bv[k]));
1256 }
1257 gj += 8;
1258 }
1259 gj
1260 }
1261
1262 /// `Round2(x * y, shift)` lane-wise for eight non-negative `i32` lanes,
1263 /// with the product formed in 64 bits (even and odd lanes separately,
1264 /// `mul_epu32`) and packed back once the shift makes it fit again.
1265 #[target_feature(enable = "avx2")]
1266 fn mul_shift(x: __m256i, y: __m256i, rnd: __m256i, shift: __m128i) -> __m256i {
1267 let ev = _mm256_mul_epu32(x, y);
1268 let od = _mm256_mul_epu32(_mm256_srli_epi64(x, 32), _mm256_srli_epi64(y, 32));
1269 let ev = _mm256_srl_epi64(_mm256_add_epi64(ev, rnd), shift);
1270 let od = _mm256_srl_epi64(_mm256_add_epi64(od, rnd), shift);
1271 _mm256_blend_epi32(ev, _mm256_slli_epi64(od, 32), 0b1010_1010)
1272 }
1273}
1274
1275/// `Round2` for the non-negative box sums (same value as [`round2`], one
1276/// width narrower).
1277#[inline]
1278fn round2_u31(value: i32, shift: u32) -> i32 {
1279 if shift == 0 {
1280 value
1281 } else {
1282 (value + (1 << (shift - 1))) >> shift
1283 }
1284}
1285
1286/// Copies one source row's `out.len()` samples starting at `base_col` into a
1287/// contiguous scratch, replicating the plane's edge sample outside
1288/// `[0, plane_w)` -- exactly the clamp [`lr_sample`] applies per element.
1289#[inline]
1290fn fill_clamped_row(src: &[u16], plane_w: usize, base_col: i64, out: &mut [u16]) {
1291 let ncols = out.len();
1292 if base_col >= 0 && base_col as usize + ncols <= plane_w {
1293 out.copy_from_slice(&src[base_col as usize..base_col as usize + ncols]);
1294 } else {
1295 for (k, o) in out.iter_mut().enumerate() {
1296 *o = src[(base_col + k as i64).clamp(0, plane_w as i64 - 1) as usize];
1297 }
1298 }
1299}
1300
1301/// Self-guided pixel filter (spec 7.17.3, libaom `sgrproj_filter_stripe` ->
1302/// `av1_apply_selfguided_restoration_c`), one stripe-height chunk of one
1303/// restoration unit: up to two box-filtered blends (`SGR_PARAMS[ep]`'s `r0`
1304/// "fast"/even-odd-row and `r1` dense radii, either may be `0` and skipped)
1305/// combined with the decoded `xqd` weights via `av1_decode_xq`.
1306#[allow(clippy::too_many_arguments)]
1307fn apply_sgrproj_stripe(
1308 out: &mut [u16],
1309 row0: usize,
1310 cdef: &[u16],
1311 deblocked: &[u16],
1312 stride: usize,
1313 plane_w: usize,
1314 plane_h: usize,
1315 h_start: usize,
1316 h_end: usize,
1317 v_start: usize,
1318 v_end: usize,
1319 info: &SgrprojInfo,
1320 fctx: &crate::decode::FrameCtx,
1321) {
1322 let w = h_end - h_start;
1323 let h = v_end - v_start;
1324 if w == 0 || h == 0 {
1325 return;
1326 }
1327 let (r0, r1, s0, s1) = SGR_PARAMS[info.ep];
1328 let gw = w + 2;
1329 let idx = |gi: i64, gj: i64| -> usize { (gi + 1) as usize * gw + (gj + 1) as usize };
1330
1331 let (mut buf0, mut buf1) = SGR_AB_SCRATCH.with(|c| {
1332 let mut m = c.borrow_mut();
1333 (std::mem::take(&mut m.0), std::mem::take(&mut m.1))
1334 });
1335 if r0 > 0 {
1336 compute_ab(
1337 cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0,
1338 &mut buf0, fctx,
1339 );
1340 }
1341 if r1 > 0 {
1342 compute_ab(
1343 cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1,
1344 &mut buf1, fctx,
1345 );
1346 }
1347 let ab0 = (r0 > 0).then_some(&buf0);
1348 let ab1 = (r1 > 0).then_some(&buf1);
1349
1350 // r8: call-unique debug dump -- r6's coordinate-only gate (`v_start==60`)
1351 // matched several unrelated calls across the gate's attempt sweep, so its
1352 // captured bytes were never provably from the failing call. `info.xqd`
1353 // is this restoration unit's own decoded weights, unique to the one call
1354 // r7 traced (`[-16,-32]`); dump the real 9-byte dense-arm (r1) "u"-tap
1355 // window (physical rows 59..=61, cols 5..=7 -- r7's traced tap) straight
1356 // from `lr_sample` for this exact call, no coordinate matching involved.
1357 if crate::envflags::env_flag!("EC_LR_CALL_DUMP") && r1 > 0 && info.xqd == [-16, -32] {
1358 let bytes: Vec<i32> = (59..=61)
1359 .flat_map(|row| {
1360 (5..=7).map(move |col| {
1361 lr_sample(
1362 cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col,
1363 )
1364 })
1365 })
1366 .collect();
1367 eprintln!(
1368 "EC_LR_CALL_DUMP: xqd={:?} v_start={v_start} v_end={v_end} h_start={h_start} \
1369 u-tap 9-byte window (rows 59..=61, cols 5..=7) = {bytes:?}",
1370 info.xqd
1371 );
1372 }
1373
1374 let mut xq = [0i32; 2];
1375 if r0 == 0 {
1376 xq[0] = 0;
1377 xq[1] = (1 << SGRPROJ_PRJ_BITS) - info.xqd[1];
1378 } else if r1 == 0 {
1379 xq[0] = info.xqd[0];
1380 xq[1] = 0;
1381 } else {
1382 xq[0] = info.xqd[0];
1383 xq[1] = (1 << SGRPROJ_PRJ_BITS) - xq[0] - info.xqd[1];
1384 }
1385
1386 // lane-perf7: as in `apply_wiener_stripe`, the clamp bound is read once
1387 // per stripe instead of per output sample.
1388 let smax = i64::from(crate::decode::sample_max(fctx));
1389 for i in 0..h as i64 {
1390 for j in 0..w as i64 {
1391 let dgd = lr_sample(
1392 cdef,
1393 deblocked,
1394 stride,
1395 plane_w,
1396 plane_h,
1397 v_start,
1398 v_end,
1399 v_start as i64 + i,
1400 h_start as i64 + j,
1401 ) as i64;
1402 let u = dgd << SGRPROJ_RST_BITS;
1403 let mut v = u << SGRPROJ_PRJ_BITS;
1404 if let Some(ab) = &ab0 {
1405 // "Fast" radius (`r0==2`): A/B were only ever meaningfully
1406 // computed at odd rows (see `compute_ab`'s doc comment) --
1407 // an even output row blends its two odd neighbour rows
1408 // (weight 6/5, `nb=5`), an odd output row reuses its own
1409 // row's A/B plus column neighbours (weight 6/5, `nb=4`).
1410 let (a, b, nb) = if i & 1 == 0 {
1411 let (a_um1, b_um1) = ab[idx(i - 1, j)];
1412 let (a_up1, b_up1) = ab[idx(i + 1, j)];
1413 let (a_uml, b_uml) = ab[idx(i - 1, j - 1)];
1414 let (a_umr, b_umr) = ab[idx(i - 1, j + 1)];
1415 let (a_upl, b_upl) = ab[idx(i + 1, j - 1)];
1416 let (a_upr, b_upr) = ab[idx(i + 1, j + 1)];
1417 let a = (a_um1 + a_up1) as i64 * 6 + (a_uml + a_umr + a_upl + a_upr) as i64 * 5;
1418 let b = (b_um1 + b_up1) * 6 + (b_uml + b_umr + b_upl + b_upr) * 5;
1419 (a, b, 5u32)
1420 } else {
1421 let (a_c, b_c) = ab[idx(i, j)];
1422 let (a_l, b_l) = ab[idx(i, j - 1)];
1423 let (a_r, b_r) = ab[idx(i, j + 1)];
1424 let a = a_c as i64 * 6 + (a_l + a_r) as i64 * 5;
1425 let b = b_c * 6 + (b_l + b_r) * 5;
1426 (a, b, 4u32)
1427 };
1428 let flt0 = round2(a * dgd + b, SGRPROJ_SGR_BITS + nb - SGRPROJ_RST_BITS);
1429 v += xq[0] as i64 * (flt0 - u);
1430 }
1431 if let Some(ab) = &ab1 {
1432 // Dense radius (`r1==1`): every row was computed, so the
1433 // combine is the full 3x3 neighbourhood (weight 4/3).
1434 let (a_c, b_c) = ab[idx(i, j)];
1435 let (a_u, b_u) = ab[idx(i - 1, j)];
1436 let (a_d, b_d) = ab[idx(i + 1, j)];
1437 let (a_l, b_l) = ab[idx(i, j - 1)];
1438 let (a_r, b_r) = ab[idx(i, j + 1)];
1439 let (a_ul, b_ul) = ab[idx(i - 1, j - 1)];
1440 let (a_ur, b_ur) = ab[idx(i - 1, j + 1)];
1441 let (a_dl, b_dl) = ab[idx(i + 1, j - 1)];
1442 let (a_dr, b_dr) = ab[idx(i + 1, j + 1)];
1443 let a = (a_c + a_u + a_d + a_l + a_r) as i64 * 4
1444 + (a_ul + a_ur + a_dl + a_dr) as i64 * 3;
1445 let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;
1446 let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);
1447 v += xq[1] as i64 * (flt1 - u);
1448 if crate::envflags::env_flag!("EC_LR_CALL_DUMP")
1449 && info.xqd == [-16, -32]
1450 && v_start as i64 + i == 61
1451 && h_start as i64 + j == 6
1452 {
1453 eprintln!(
1454 "EC_LR_CALL_DUMP combine: c={:?} u_tap(row60)={:?} d={:?} l={:?} r={:?} \
1455 ul={:?} ur={:?} dl={:?} dr={:?} dense a={a} b={b} dgd={dgd} \
1456 u={u} flt1={flt1} xq={xq:?} v_before_final_round={v}",
1457 ab[idx(i, j)],
1458 ab[idx(i - 1, j)],
1459 ab[idx(i + 1, j)],
1460 ab[idx(i, j - 1)],
1461 ab[idx(i, j + 1)],
1462 ab[idx(i - 1, j - 1)],
1463 ab[idx(i - 1, j + 1)],
1464 ab[idx(i + 1, j - 1)],
1465 ab[idx(i + 1, j + 1)]
1466 );
1467 }
1468 }
1469 let out_v = round2(v, SGRPROJ_PRJ_BITS as u32 + SGRPROJ_RST_BITS).clamp(0, smax) as u16;
1470 out[(v_start as i64 + i - row0 as i64) as usize * stride + (h_start as i64 + j) as usize] =
1471 out_v;
1472 }
1473 }
1474 SGR_AB_SCRATCH.with(|c| *c.borrow_mut() = (buf0, buf1));
1475}
1476
1477/// Chunks one restoration unit's `[v_start, v_end)` extent into 64-row
1478/// (56 for the plane's very first stripe -- `RESTORATION_UNIT_OFFSET==8`)
1479/// processing stripes and filters each (libaom
1480/// `av1_loop_restoration_filter_unit`'s own `while (i < unit_h)` loop) --
1481/// a restoration unit can be up to `256*1.5` px tall, spanning several
1482/// stripes, each of which needs its own boundary-source decision from
1483/// [`lr_sample`].
1484#[allow(clippy::too_many_arguments)]
1485fn filter_restoration_unit(
1486 out: &mut [u16],
1487 row0: usize,
1488 cdef: &[u16],
1489 deblocked: &[u16],
1490 stride: usize,
1491 plane_w: usize,
1492 plane_h: usize,
1493 h_start: usize,
1494 h_end: usize,
1495 v_start: usize,
1496 v_end: usize,
1497 ss_y: u32,
1498 filter: UnitFilter,
1499 fctx: &crate::decode::FrameCtx,
1500) {
1501 let full_stripe_height = 64usize >> ss_y;
1502 let runit_offset = 8usize >> ss_y;
1503 let unit_h = v_end - v_start;
1504 let mut i = 0usize;
1505 while i < unit_h {
1506 let stripe_v_start = v_start + i;
1507 let frame_stripe = (stripe_v_start + runit_offset) / full_stripe_height;
1508 let nominal_h = full_stripe_height - if frame_stripe == 0 { runit_offset } else { 0 };
1509 let h = nominal_h.min(unit_h - i);
1510 let stripe_v_end = stripe_v_start + h;
1511 if !matches!(filter, UnitFilter::None) {
1512 if stripe_v_start == 0 {
1513 hit!(LR_STRIPE0_HITS);
1514 }
1515 if stripe_v_end == plane_h && h < nominal_h {
1516 hit!(LR_LAST_STRIPE_HITS);
1517 }
1518 }
1519 match filter {
1520 UnitFilter::Wiener(info) => apply_wiener_stripe(
1521 out,
1522 row0,
1523 cdef,
1524 deblocked,
1525 stride,
1526 plane_w,
1527 plane_h,
1528 h_start,
1529 h_end,
1530 stripe_v_start,
1531 stripe_v_end,
1532 &info,
1533 fctx,
1534 ),
1535 UnitFilter::Sgrproj(info) => apply_sgrproj_stripe(
1536 out,
1537 row0,
1538 cdef,
1539 deblocked,
1540 stride,
1541 plane_w,
1542 plane_h,
1543 h_start,
1544 h_end,
1545 stripe_v_start,
1546 stripe_v_end,
1547 &info,
1548 fctx,
1549 ),
1550 UnitFilter::None => {}
1551 }
1552 i += h;
1553 }
1554}
1555
1556/// Applies loop restoration to one whole plane's post-CDEF samples (spec
1557/// 7.17). Walks restoration units exactly as libaom's
1558/// `foreach_rest_unit_in_plane` (`unit_size` steps, the tail folded into
1559/// the previous unit when the remainder is under `1.5*unit_size` -- the
1560/// same round-to-nearest [`count_units`] already used to size
1561/// [`RestorationGrid`]), then re-offsets internal row boundaries by
1562/// `RESTORATION_UNIT_OFFSET==8` (the first/last row of the plane keeps its
1563/// full extent). Returns a fresh copy of `cdef` with only this plane's
1564/// restoration-unit pixels replaced -- a restoration unit must never read
1565/// another, already-filtered unit's output (spec keeps a separate
1566/// destination buffer for exactly this reason), so this never filters in
1567/// place -- `out` is that buffer, refilled from `cdef` on entry.
1568#[allow(clippy::too_many_arguments)]
1569pub(crate) fn apply_loop_restoration_plane(
1570 cdef: &[u16],
1571 deblocked: &[u16],
1572 stride: usize,
1573 plane_w: usize,
1574 plane_h: usize,
1575 ss_y: u32,
1576 ftype: RestorationType,
1577 unit_size: u32,
1578 grid: &RestorationGrid,
1579 plane: usize,
1580 // lane-perf6: the destination buffer, refilled from `cdef` here. It used
1581 // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte
1582 // allocation whose every page then faulted in on first touch.
1583 out: &mut Vec<u16>,
1584 // `Some((r_lo, r_hi))` restricts the call to those RU ROWS. `out` is then
1585 // the caller's, already sized, and only this range's rows are refilled from `cdef` (the rows below `plane_h` are
1586 // the caller's own tail copy). `None` is the whole-plane form.
1587 rrows: Option<(usize, usize)>,
1588 fctx: &crate::decode::FrameCtx,
1589) {
1590 let rows = lr_unit_rows(plane_h, unit_size, ss_y, ftype);
1591 let Some((r_lo, r_hi)) = rrows else {
1592 out.clear();
1593 out.extend_from_slice(cdef);
1594 if rows.is_empty() {
1595 return;
1596 }
1597 // Each band's RU rows write one contiguous run of `out` rows (the
1598 // rows run `v_start..v_end` back to back), so a band owns its own slice.
1599 let pbands: Vec<(usize, usize)> = crate::par::bands(rows.len(), crate::par::filter_threads())
1600 .into_iter()
1601 .map(|(a, b)| (rows[a].0 as usize, rows[b - 1].1 as usize))
1602 .collect();
1603 crate::par::run_bands_mut(&pbands, stride, fctx, out.as_mut_slice(), |lo, hi, mine, fctx| {
1604 let r_lo = rows.partition_point(|r| (r.0 as usize) < lo);
1605 let r_hi = rows.partition_point(|r| (r.0 as usize) < hi);
1606 for rrow in r_lo..r_hi {
1607 lr_unit_row(
1608 mine, lo, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid,
1609 plane, rrow, &rows, fctx,
1610 );
1611 }
1612 });
1613 debug_assert_eq!(
1614 rows.len(),
1615 grid.vert_units[plane],
1616 "RU row walk must match RestorationGrid::new's count_units"
1617 );
1618 return;
1619 };
1620 for rrow in r_lo..r_hi.min(rows.len()) {
1621 let (v_start, v_end) = rows[rrow];
1622 let (a, b) = (v_start as usize * stride, v_end as usize * stride);
1623 out[a..b].copy_from_slice(&cdef[a..b]);
1624 lr_unit_row(
1625 out, 0, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane,
1626 rrow, &rows, fctx,
1627 );
1628 }
1629}
1630
1631/// One plane's restoration-unit ROW walk, resolved to each row's `out` write
1632/// span `v_start..v_end`. The walk is data-dependent (a short remainder is
1633/// swallowed by the previous unit row), so both callers resolve it into this
1634/// list first: the next row's `v_start` is this one's `v_end`, so the spans
1635/// partition `0..plane_h` and row bands are disjoint. Empty when the plane
1636/// restores nothing.
1637pub(crate) fn lr_unit_rows(
1638 plane_h: usize,
1639 unit_size: u32,
1640 ss_y: u32,
1641 ftype: RestorationType,
1642) -> Vec<(u32, u32)> {
1643 let mut rows: Vec<(u32, u32)> = Vec::new();
1644 if ftype == RestorationType::None || unit_size == 0 {
1645 return rows;
1646 }
1647 let voffset = 8u32 >> ss_y;
1648 let ext_size = (unit_size * 3) / 2;
1649 let mut y0 = 0u32;
1650 while y0 < plane_h as u32 {
1651 let remaining_h = plane_h as u32 - y0;
1652 let uh = if remaining_h < ext_size {
1653 remaining_h
1654 } else {
1655 unit_size
1656 };
1657 let v_start = (y0 as i64 - voffset as i64).max(0) as u32;
1658 let mut v_end = y0 + uh;
1659 if v_end < plane_h as u32 {
1660 v_end -= voffset;
1661 }
1662 rows.push((v_start, v_end));
1663 y0 += uh;
1664 }
1665 rows
1666}
1667
1668/// The restoration units of one RU row, filtered into `out`. Reads only
1669/// `cdef`/`deblocked`, writes only this row's `v_start..v_end` span.
1670#[allow(clippy::too_many_arguments)]
1671fn lr_unit_row(
1672 out: &mut [u16],
1673 row0: usize,
1674 cdef: &[u16],
1675 deblocked: &[u16],
1676 stride: usize,
1677 plane_w: usize,
1678 plane_h: usize,
1679 ss_y: u32,
1680 unit_size: u32,
1681 grid: &RestorationGrid,
1682 plane: usize,
1683 rrow: usize,
1684 rows: &[(u32, u32)],
1685 fctx: &crate::decode::FrameCtx,
1686) {
1687 let ext_size = (unit_size * 3) / 2;
1688 let (v_start, v_end) = rows[rrow];
1689 let mut x0 = 0u32;
1690 let mut rcol = 0usize;
1691 while x0 < plane_w as u32 {
1692 let remaining_w = plane_w as u32 - x0;
1693 let uw = if remaining_w < ext_size {
1694 remaining_w
1695 } else {
1696 unit_size
1697 };
1698 let filter = grid.get(plane, rrow, rcol);
1699 if filter != UnitFilter::None {
1700 filter_restoration_unit(
1701 out,
1702 row0,
1703 cdef,
1704 deblocked,
1705 stride,
1706 plane_w,
1707 plane_h,
1708 x0 as usize,
1709 (x0 + uw) as usize,
1710 v_start as usize,
1711 v_end as usize,
1712 ss_y,
1713 filter,
1714 fctx,
1715 );
1716 }
1717 x0 += uw;
1718 rcol += 1;
1719 }
1720}
1721
1722#[cfg(test)]
1723mod tests {
1724 use super::*;
1725 use crate::msac::{SymbolDecoder, SymbolEncoder};
1726
1727 /// The write side these roundtrips exercise now lives beside the
1728 /// readers (`write_ns`/`write_subexp`/`write_unsigned_subexp_with_ref`,
1729 /// used by the encoder's per-unit LR syntax) instead of being a
1730 /// test-only transcription of it -- one implementation, pinned here. ///
1731 /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of
1732 /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4,
1733 /// `num_syms` up to 96) actually hit, per `WIENER_TAP_MAXV`-`MINV`+1 /
1734 /// `SGRPROJ_PRJ_MAX-MIN+1`.
1735 #[test]
1736 fn subexp_roundtrips_every_value() {
1737 for &(num_syms, k) in &[
1738 (16u32, 1u32),
1739 (32, 2),
1740 (64, 3),
1741 (96, 4),
1742 (128, 4),
1743 (3, 1),
1744 (1, 3),
1745 ] {
1746 for v in 0..num_syms {
1747 let mut enc = SymbolEncoder::new();
1748 write_subexp(&mut enc, num_syms, k, v);
1749 let payload = enc.finish();
1750 let mut dec = SymbolDecoder::new(&payload);
1751 let got = decode_subexp_msac(&mut dec, num_syms, k);
1752 assert_eq!(got, v, "num_syms={num_syms} k={k} v={v}");
1753 }
1754 }
1755 }
1756
1757 /// The recentred, ref-relative form `read_wiener_filter`/
1758 /// `read_sgrproj_filter` actually call -- every `(n, reference, v)`
1759 /// combination for LR's own tap-0 range (16 values, matching
1760 /// `WIENER_FILT_TAP0_MAXV-MINV+1`).
1761 #[test]
1762 fn unsigned_subexp_with_ref_roundtrips() {
1763 let n = 16u32;
1764 for k in 1..=4u32 {
1765 for reference in 0..n {
1766 for v in 0..n {
1767 let mut enc = SymbolEncoder::new();
1768 write_unsigned_subexp_with_ref(&mut enc, n, k, reference, v);
1769 let payload = enc.finish();
1770 let mut dec = SymbolDecoder::new(&payload);
1771 let got = decode_unsigned_subexp_with_ref_msac(&mut dec, n, k, reference);
1772 assert_eq!(got, v, "n={n} k={k} reference={reference} v={v}");
1773 }
1774 }
1775 }
1776 }
1777
1778 /// Signed wrapper sanity: a handful of `(low, high, k, reference, v)`
1779 /// covering LR's actual Wiener tap-1/tap-2 and SGR `xqd0`/`xqd1` ranges.
1780 #[test]
1781 fn signed_subexp_with_ref_roundtrips() {
1782 let cases: [(i32, i32, u32); 4] = [
1783 (-5, 11, 1), // Wiener tap0
1784 (-23, 9, 2), // Wiener tap1
1785 (-17, 47, 3), // Wiener tap2
1786 (-96, 32, 4), // SGR xqd0
1787 ];
1788 for (low, high, k) in cases {
1789 let n = (high - low) as u32;
1790 for reference_v in [low, low + n as i32 / 3, high - 1] {
1791 for v in [low, low + n as i32 / 2, high - 1] {
1792 let r = (reference_v - low).clamp(0, n as i32) as u32;
1793 let coded_v = (v - low) as u32;
1794 let mut enc = SymbolEncoder::new();
1795 write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v);
1796 let payload = enc.finish();
1797 let mut dec = SymbolDecoder::new(&payload);
1798 let got =
1799 decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v);
1800 assert_eq!(
1801 got, v,
1802 "low={low} high={high} k={k} reference={reference_v} v={v}"
1803 );
1804 }
1805 }
1806 }
1807 }
1808
1809 /// [`write_wiener_filter`] against [`read_wiener_filter`], including the
1810 /// running per-tile reference both sides advance: three units in a row,
1811 /// luma (7-tap) and chroma (5-tap, tap 0 forced to zero).
1812 #[test]
1813 fn wiener_filter_roundtrips() {
1814 for chroma in [false, true] {
1815 let units = [
1816 wiener_from_taps([0, 0, 8], [0, 0, 8]),
1817 wiener_from_taps([0, 4, 12], [0, 0, -8]),
1818 wiener_from_taps([0, 0, 0], [0, 0, 0]),
1819 ];
1820 let units: Vec<WienerInfo> = units.to_vec();
1821 let mut enc = SymbolEncoder::new();
1822 let mut wref = WienerInfo::default();
1823 for u in &units {
1824 write_wiener_filter(&mut enc, chroma, &mut wref, u);
1825 }
1826 let payload = enc.finish();
1827 let mut dec = SymbolDecoder::new(&payload);
1828 let mut rref = WienerInfo::default();
1829 for u in &units {
1830 assert_eq!(
1831 read_wiener_filter(&mut dec, chroma, &mut rref),
1832 *u,
1833 "chroma={chroma}"
1834 );
1835 }
1836 }
1837 }
1838}