forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-perf6' (d14a4132): per-pixel env lookups removed from loop restoration, CDEF gathered window and resolved damping shift, pooled per-frame plane buffers, deblock bit-depth hoist, separable sgrproj box sums; byte-exact on four inputs, 4K 1.29x

Browse files at this commit

fb5fc2e9e98f576aa9c9c8b09d89de7026ded446Ahmet Kaan GümüşParent: 4256150ac194aa
crates/ec-av1/src/decode.rsmodified+261 -60
@@ -14086,8 +14086,75 @@ fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
1408614086 if threshold == 0 {
1408714087 return 0;
1408814088 }
14089- let shift = (damping - cdef_msb(threshold)).max(0);
14090- diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
14089+ cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
14090+}
14091+
14092+/// `constrain`'s damping shift: a function of the block's threshold and
14093+/// damping alone, so the filter loop computes it once per block instead of
14094+/// the `leading_zeros` + branch it used to do twice per tap read.
14095+fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
14096+ (damping - cdef_msb(threshold)).max(0)
14097+}
14098+
14099+/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
14100+/// non-zero on every call (the caller only filters when its strength is).
14101+fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
14102+ let a = diff.abs();
14103+ diff.signum() * (threshold - (a >> shift)).clamp(0, a)
14104+}
14105+
14106+/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
14107+/// lies inside its own samples grown by this much.
14108+const CDEF_BORDER: usize = 2;
14109+
14110+/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
14111+/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
14112+/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
14113+/// index a small contiguous window instead of re-deriving the frame-bounds
14114+/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
14115+/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
14116+fn cdef_gather(
14117+ src: &[u16],
14118+ stride: usize,
14119+ true_w: usize,
14120+ true_h: usize,
14121+ ox: usize,
14122+ oy: usize,
14123+ bw: usize,
14124+ bh: usize,
14125+ buf: &mut [i32],
14126+) {
14127+ let bstride = bw + 2 * CDEF_BORDER;
14128+ let rows = bh + 2 * CDEF_BORDER;
14129+ if oy >= CDEF_BORDER
14130+ && ox >= CDEF_BORDER
14131+ && oy + bh + CDEF_BORDER <= true_h
14132+ && ox + bw + CDEF_BORDER <= true_w
14133+ {
14134+ // Interior block: every tap is inside the frame, so the whole window
14135+ // is `rows` contiguous runs.
14136+ for r in 0..rows {
14137+ let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
14138+ let src_row = &src[s0..s0 + bstride];
14139+ let dst_row = &mut buf[r * bstride..r * bstride + bstride];
14140+ for (d, &v) in dst_row.iter_mut().zip(src_row) {
14141+ *d = i32::from(v);
14142+ }
14143+ }
14144+ return;
14145+ }
14146+ for r in 0..rows {
14147+ let ny = oy as isize + r as isize - CDEF_BORDER as isize;
14148+ for c in 0..bstride {
14149+ let nx = ox as isize + c as isize - CDEF_BORDER as isize;
14150+ buf[r * bstride + c] =
14151+ if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
14152+ CDEF_VERY_LARGE
14153+ } else {
14154+ i32::from(src[ny as usize * stride + nx as usize])
14155+ };
14156+ }
14157+ }
1409114158 }
1409214159
1409314160 /// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
@@ -14168,7 +14235,7 @@ fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
1416814235 /// previously-filtered neighbour must never feed this block's own sum).
1416914236 #[allow(clippy::too_many_arguments)]
1417014237 fn cdef_filter_block(
14171- sample: impl Fn(i32, i32) -> i32,
14238+ src: &[i32],
1417214239 dst: &mut PlaneBuf,
1417314240 ox: usize,
1417414241 oy: usize,
@@ -14189,19 +14256,33 @@ fn cdef_filter_block(
1418914256 // derivative) carries the bit-depth shift, so the tap-set parity bit
1419014257 // must be read back above that shift, not off the raw low bit.
1419114258 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
14259+ // Both damping shifts depend only on this block's strengths (spec 7.15.3's
14260+ // `constrain`), so they are resolved here rather than per tap read.
14261+ let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
14262+ let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
14263+ let bstride = bw + 2 * CDEF_BORDER;
14264+ let smax = sample_max();
14265+ // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
14266+ // reaching +-CDEF_BORDER, so every index below is in range by construction.
14267+ let at = |i: i32, j: i32| -> i32 {
14268+ src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize]
14269+ };
14270+ let (pri_dir, sec_dir0, sec_dir1) =
14271+ (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
1419214272 for i in 0..bh {
1419314273 for j in 0..bw {
14194- let x = sample(i as i32, j as i32);
14274+ let (i32i, i32j) = (i as i32, j as i32);
14275+ let x = at(i32i, i32j);
1419514276 let mut sum = 0i32;
1419614277 let mut max = x;
1419714278 let mut min = x;
1419814279 for k in 0..2usize {
1419914280 if enable_primary {
14200- let (tr, tc) = CDEF_DIRECTIONS[dir][k];
14201- let p0 = sample(i as i32 + tr, j as i32 + tc);
14202- let p1 = sample(i as i32 - tr, j as i32 - tc);
14203- sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
14204- sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
14281+ let (tr, tc) = pri_dir[k];
14282+ let p0 = at(i32i + tr, i32j + tc);
14283+ let p1 = at(i32i - tr, i32j - tc);
14284+ sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
14285+ sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
1420514286 if clipping_required {
1420614287 if p0 != CDEF_VERY_LARGE {
1420714288 max = max.max(p0);
@@ -14213,12 +14294,12 @@ fn cdef_filter_block(
1421314294 }
1421414295 }
1421514296 if enable_secondary {
14216- let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
14217- let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
14218- let s0 = sample(i as i32 + tr0, j as i32 + tc0);
14219- let s1 = sample(i as i32 - tr0, j as i32 - tc0);
14220- let s2 = sample(i as i32 + tr1, j as i32 + tc1);
14221- let s3 = sample(i as i32 - tr1, j as i32 - tc1);
14297+ let (tr0, tc0) = sec_dir0[k];
14298+ let (tr1, tc1) = sec_dir1[k];
14299+ let s0 = at(i32i + tr0, i32j + tc0);
14300+ let s1 = at(i32i - tr0, i32j - tc0);
14301+ let s2 = at(i32i + tr1, i32j + tc1);
14302+ let s3 = at(i32i - tr1, i32j - tc1);
1422214303 if clipping_required {
1422314304 for s in [s0, s1, s2, s3] {
1422414305 if s != CDEF_VERY_LARGE {
@@ -14228,17 +14309,17 @@ fn cdef_filter_block(
1422814309 min = min.min(s0).min(s1).min(s2).min(s3);
1422914310 }
1423014311 sum += CDEF_SEC_TAPS[k]
14231- * (cdef_constrain(s0 - x, sec_strength, sec_damping)
14232- + cdef_constrain(s1 - x, sec_strength, sec_damping)
14233- + cdef_constrain(s2 - x, sec_strength, sec_damping)
14234- + cdef_constrain(s3 - x, sec_strength, sec_damping));
14312+ * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
14313+ + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
14314+ + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
14315+ + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
1423514316 }
1423614317 }
1423714318 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
1423814319 if clipping_required {
1423914320 y = y.clamp(min, max);
1424014321 }
14241- dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
14322+ dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, smax) as u16;
1424214323 }
1424314324 }
1424414325 }
@@ -15915,7 +15996,12 @@ fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32;
1591515996 return [p1, p0, q0, q1];
1591615997 }
1591715998 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
15918- let centre = 128i32 << (bit_depth() - 8);
15999+ // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
16000+ // this kernel's eight clamps, and this kernel runs per deblocked sample.
16001+ // Same bound, resolved once.
16002+ let scale = 1i32 << (bit_depth() - 8);
16003+ let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
16004+ let centre = 128i32 * scale;
1591916005 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
1592016006 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
1592116007 let filter = sclamp(outer + 3 * (qs0 - ps0));
@@ -16083,6 +16169,7 @@ fn filter_edge(
1608316169 let shift = bit_depth() - 8;
1608416170 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
1608516171 let flat_thresh = 1i32 << shift;
16172+ let smax = sample_max();
1608616173 for i in 0..4isize {
1608716174 let center = (base as isize + i * outer_stride) as usize;
1608816175 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
@@ -16094,10 +16181,10 @@ fn filter_edge(
1609416181 && (q1 - q0).abs() <= limit
1609516182 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
1609616183 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
16097- data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
16098- data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
16099- data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
16100- data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
16184+ data[idx(-2)] = op1.clamp(0, smax) as u16;
16185+ data[idx(-1)] = op0.clamp(0, smax) as u16;
16186+ data[idx(0)] = oq0.clamp(0, smax) as u16;
16187+ data[idx(1)] = oq1.clamp(0, smax) as u16;
1610116188 }
1610216189 6 => {
1610316190 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
@@ -16111,10 +16198,10 @@ fn filter_edge(
1611116198 && (p2 - p0).abs() <= flat_thresh
1611216199 && (q2 - q0).abs() <= flat_thresh;
1611316200 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
16114- data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
16115- data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
16116- data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
16117- data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
16201+ data[idx(-2)] = op1.clamp(0, smax) as u16;
16202+ data[idx(-1)] = op0.clamp(0, smax) as u16;
16203+ data[idx(0)] = oq0.clamp(0, smax) as u16;
16204+ data[idx(1)] = oq1.clamp(0, smax) as u16;
1611816205 }
1611916206 8 => {
1612016207 let (p3, p2, p1, p0, q0, q1, q2, q3) =
@@ -16134,12 +16221,12 @@ fn filter_edge(
1613416221 && (q3 - q0).abs() <= flat_thresh;
1613516222 let [op2, op1, op0, oq0, oq1, oq2] =
1613616223 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
16137- data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
16138- data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
16139- data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
16140- data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
16141- data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
16142- data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
16224+ data[idx(-3)] = op2.clamp(0, smax) as u16;
16225+ data[idx(-2)] = op1.clamp(0, smax) as u16;
16226+ data[idx(-1)] = op0.clamp(0, smax) as u16;
16227+ data[idx(0)] = oq0.clamp(0, smax) as u16;
16228+ data[idx(1)] = oq1.clamp(0, smax) as u16;
16229+ data[idx(2)] = oq2.clamp(0, smax) as u16;
1614316230 }
1614416231 _ => {
1614516232 let (p6, p5, p4, p3, p2, p1, p0) =
@@ -16170,7 +16257,7 @@ fn filter_edge(
1617016257 q6,
1617116258 );
1617216259 for (k, v) in (-6..=5isize).zip(out) {
16173- data[idx(k)] = v.clamp(0, sample_max()) as u16;
16260+ data[idx(k)] = v.clamp(0, smax) as u16;
1617416261 }
1617516262 }
1617616263 }
@@ -16273,6 +16360,43 @@ fn deblock_plane(
1627316360 }
1627416361 }
1627516362
16363+thread_local! {
16364+ /// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
16365+ /// pre-CDEF snapshot of all three planes, a post-deblock snapshot when
16366+ /// loop restoration is active, and a fresh LR destination per plane --
16367+ /// freshly allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K,
16368+ /// so every sample written also takes a first-touch page fault. The
16369+ /// buffers are handed back here instead and refilled in place.
16370+ static PLANE_SCRATCH: std::cell::RefCell<Vec<Vec<u16>>> =
16371+ const { std::cell::RefCell::new(Vec::new()) };
16372+}
16373+
16374+/// A pooled buffer holding a copy of `src`.
16375+fn scratch_from(src: &[u16]) -> Vec<u16> {
16376+ let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default();
16377+ v.clear();
16378+ v.extend_from_slice(src);
16379+ v
16380+}
16381+
16382+/// An empty pooled buffer, for a caller that fills it itself.
16383+fn scratch_empty() -> Vec<u16> {
16384+ let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default();
16385+ v.clear();
16386+ v
16387+}
16388+
16389+/// A plane's post-deblock snapshot, its samples taken from the pool (every
16390+/// other field is `usize`).
16391+fn plane_snapshot(p: &PlaneBuf) -> PlaneBuf {
16392+ PlaneBuf { data: scratch_from(&p.data), ..*p }
16393+}
16394+
16395+/// Hands a buffer back to the pool; the capacity is what is worth keeping.
16396+fn scratch_return(v: Vec<u16>) {
16397+ PLANE_SCRATCH.with(|p| p.borrow_mut().push(v));
16398+}
16399+
1627616400 fn apply_cdef(
1627716401 y: &mut PlaneBuf,
1627816402 u: &mut PlaneBuf,
@@ -16343,6 +16467,8 @@ fn apply_cdef(
1634316467 return;
1634416468 }
1634516469 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
16470+ // One entry per superblock (a few hundred at 4K), so this clone is not
16471+ // one of the per-frame copies lane-perf6 pooled below.
1634616472 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
1634716473 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
1634816474 if sb_cols == 0 {
@@ -16354,14 +16480,18 @@ fn apply_cdef(
1635416480 .copied()
1635516481 .unwrap_or(0) as usize
1635616482 };
16357- let src_y = y.data.clone();
16358- let src_u = u.data.clone();
16359- let src_v = v.data.clone();
16483+ let src_y = scratch_from(&y.data);
16484+ let src_u = scratch_from(&u.data);
16485+ let src_v = scratch_from(&v.data);
1636016486 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
1636116487 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
1636216488 let coeff_shift = i32::from(bit_depth()) - 8;
1636316489 let damping = i32::from(cdef.damping) + coeff_shift;
1636416490 let damping_uv = (damping - 1).max(0);
16491+ // One scratch window per plane kind, reused by every unit (8x8 luma and
16492+ // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
16493+ let mut win_y = [0i32; (8 + 2 * CDEF_BORDER) * (8 + 2 * CDEF_BORDER)];
16494+ let mut win_uv = [0i32; (4 + 2 * CDEF_BORDER) * (4 + 2 * CDEF_BORDER)];
1636516495 let mut mi_r = 0usize;
1636616496 while mi_r < skip_grid.mi_rows {
1636716497 let mut mi_c = 0usize;
@@ -16372,14 +16502,22 @@ fn apply_cdef(
1637216502 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
1637316503 let sidx = strength_idx(mi_r, mi_c);
1637416504 let (ox, oy) = (mi_c * 4, mi_r * 4);
16505+ // Nothing to do for this unit at all: the direction search is
16506+ // only ever consumed through a strength, so a unit whose four
16507+ // strengths are zero never needs its 8x8 window gathered.
16508+ if cdef.y_pri_strength[sidx] == 0
16509+ && cdef.y_sec_strength[sidx] == 0
16510+ && cdef.uv_pri_strength[sidx] == 0
16511+ && cdef.uv_sec_strength[sidx] == 0
16512+ {
16513+ mi_c += 2;
16514+ continue;
16515+ }
1637516516 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
16517+ cdef_gather(&src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
1637616518 let sample_y = |r: i32, c: i32| -> i32 {
16377- let (ny, nx) = (oy as i32 + r, ox as i32 + c);
16378- if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
16379- CDEF_VERY_LARGE
16380- } else {
16381- i32::from(src_y[ny as usize * y_stride + nx as usize])
16382- }
16519+ win_y[(r + CDEF_BORDER as i32) as usize * (8 + 2 * CDEF_BORDER)
16520+ + (c + CDEF_BORDER as i32) as usize]
1638316521 };
1638416522 // lane-cdef r1: the direction search reads the SAME padded
1638516523 // block the taps do -- libaom runs `cdef_find_dir` on the
@@ -16417,7 +16555,7 @@ fn apply_cdef(
1641716555 }
1641816556 if enable_primary || enable_secondary {
1641916557 cdef_filter_block(
16420- sample_y,
16558+ &win_y,
1642116559 y,
1642216560 ox,
1642316561 oy,
@@ -16444,16 +16582,9 @@ fn apply_cdef(
1644416582 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
1644516583 let (tw, th) = (plane.true_width, plane.true_height);
1644616584 let stride = plane.width;
16447- let sample_uv = |r: i32, c: i32| -> i32 {
16448- let (ny, nx) = (coy as i32 + r, cox as i32 + c);
16449- if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
16450- CDEF_VERY_LARGE
16451- } else {
16452- i32::from(src_p[ny as usize * stride + nx as usize])
16453- }
16454- };
16585+ cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
1645516586 cdef_filter_block(
16456- sample_uv,
16587+ &win_uv,
1645716588 plane,
1645816589 cox,
1645916590 coy,
@@ -16475,6 +16606,9 @@ fn apply_cdef(
1647516606 }
1647616607 mi_r += 2;
1647716608 }
16609+ scratch_return(src_y);
16610+ scratch_return(src_u);
16611+ scratch_return(src_v);
1647816612 }
1647916613
1648016614 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
@@ -16512,7 +16646,8 @@ fn apply_loop_restoration(
1651216646 // (class av1-truesize-lane: true frame size vs mi-rounded).
1651316647 (frame_w, frame_h): (usize, usize),
1651416648 ) {
16515- y.data = crate::restoration::apply_loop_restoration_plane(
16649+ let mut out = scratch_empty();
16650+ crate::restoration::apply_loop_restoration_plane(
1651616651 &y.data,
1651716652 &deblocked_y.data,
1651816653 y.width,
@@ -16523,8 +16658,12 @@ fn apply_loop_restoration(
1652316658 lr.loop_restoration_size[0],
1652416659 grid,
1652516660 0,
16661+ &mut out,
1652616662 );
16527- u.data = crate::restoration::apply_loop_restoration_plane(
16663+ std::mem::swap(&mut y.data, &mut out);
16664+ scratch_return(out);
16665+ let mut out = scratch_empty();
16666+ crate::restoration::apply_loop_restoration_plane(
1652816667 &u.data,
1652916668 &deblocked_u.data,
1653016669 u.width,
@@ -16535,8 +16674,12 @@ fn apply_loop_restoration(
1653516674 lr.loop_restoration_size[1],
1653616675 grid,
1653716676 1,
16677+ &mut out,
1653816678 );
16539- v.data = crate::restoration::apply_loop_restoration_plane(
16679+ std::mem::swap(&mut u.data, &mut out);
16680+ scratch_return(out);
16681+ let mut out = scratch_empty();
16682+ crate::restoration::apply_loop_restoration_plane(
1654016683 &v.data,
1654116684 &deblocked_v.data,
1654216685 v.width,
@@ -16547,7 +16690,10 @@ fn apply_loop_restoration(
1654716690 lr.loop_restoration_size[2],
1654816691 grid,
1654916692 2,
16693+ &mut out,
1655016694 );
16695+ std::mem::swap(&mut v.data, &mut out);
16696+ scratch_return(out);
1655116697 }
1655216698
1655316699 /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
@@ -18863,7 +19009,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1886319009 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
1886419010 && lr.loop_restoration_size[p] != 0
1886519011 });
18866- let deblocked = lr_active.then(|| (y.clone(), u.clone(), v.clone()));
19012+ let deblocked =
19013+ lr_active.then(|| (plane_snapshot(&y), plane_snapshot(&u), plane_snapshot(&v)));
1886719014 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
1886819015 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
1886919016 // dump above these bisect WHICH filter stage introduced a mismatch.
@@ -18921,6 +19068,11 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1892119068 (lr_w, frame_height as usize),
1892219069 );
1892319070 }
19071+ if let Some((db_y, db_u, db_v)) = deblocked {
19072+ scratch_return(db_y.data);
19073+ scratch_return(db_u.data);
19074+ scratch_return(db_v.data);
19075+ }
1892419076
1892519077 let (fw, fh) = (lr_w, frame_height as usize);
1892619078 // An upscaled frame is already at its final size with no mi-aligned
@@ -30891,7 +31043,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3089131043 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
3089231044 && lr.loop_restoration_size[p] != 0
3089331045 });
30894- let deblocked = lr_active.then(|| (y.clone(), u.clone(), v.clone()));
31046+ let deblocked =
31047+ lr_active.then(|| (plane_snapshot(&y), plane_snapshot(&u), plane_snapshot(&v)));
3089531048 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
3089631049 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
3089731050 // dump above these bisect WHICH filter stage introduced a mismatch.
@@ -30949,6 +31102,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3094931102 (lr_w, frame_height as usize),
3095031103 );
3095131104 }
31105+ if let Some((db_y, db_u, db_v)) = deblocked {
31106+ scratch_return(db_y.data);
31107+ scratch_return(db_u.data);
31108+ scratch_return(db_v.data);
31109+ }
3095231110
3095331111 let motion_field = build_motion_field(
3095431112 &grid,
@@ -31029,6 +31187,49 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3102931187 #[cfg(test)]
3103031188 mod tests {
3103131189
31190+ /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and
31191+ /// a pre-resolved damping shift instead of a bounds-testing closure and a
31192+ /// per-tap `msb`. Both replacements must be value-identical to the spec
31193+ /// forms they came from, over the whole strength/damping/diff domain.
31194+ #[test]
31195+ fn cdef_gather_and_shifted_constrain_match_the_spec_forms() {
31196+ for damping in 3..=9i32 {
31197+ for threshold in 1..=64i32 {
31198+ let shift = super::cdef_constrain_shift(threshold, damping);
31199+ for diff in -300..=300i32 {
31200+ assert_eq!(
31201+ super::cdef_constrain(diff, threshold, damping),
31202+ super::cdef_constrain_shifted(diff, threshold, shift),
31203+ "diff={diff} threshold={threshold} damping={damping}"
31204+ );
31205+ }
31206+ }
31207+ }
31208+ // `cdef_gather`'s interior fast path and its bounds-testing slow path
31209+ // must agree with the per-sample closure the filter used to call, at
31210+ // every block position including the three that straddle the crop.
31211+ let (stride, tw, th) = (24usize, 21usize, 19usize);
31212+ let src: Vec<u16> = (0..stride * 24).map(|i| (i * 7 % 1024) as u16).collect();
31213+ for &(ox, oy, bw, bh) in &[(0, 0, 8, 8), (8, 8, 8, 8), (16, 16, 8, 8), (4, 12, 4, 4)] {
31214+ let bstride = bw + 2 * super::CDEF_BORDER;
31215+ let mut win = vec![0i32; bstride * (bh + 2 * super::CDEF_BORDER)];
31216+ super::cdef_gather(&src, stride, tw, th, ox, oy, bw, bh, &mut win);
31217+ for r in -(super::CDEF_BORDER as i32)..(bh + super::CDEF_BORDER) as i32 {
31218+ for c in -(super::CDEF_BORDER as i32)..(bw + super::CDEF_BORDER) as i32 {
31219+ let (ny, nx) = (oy as i32 + r, ox as i32 + c);
31220+ let want = if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
31221+ super::CDEF_VERY_LARGE
31222+ } else {
31223+ i32::from(src[ny as usize * stride + nx as usize])
31224+ };
31225+ let got = win[(r + super::CDEF_BORDER as i32) as usize * bstride
31226+ + (c + super::CDEF_BORDER as i32) as usize];
31227+ assert_eq!(got, want, "({ox},{oy}) r={r} c={c}");
31228+ }
31229+ }
31230+ }
31231+ }
31232+
3103231233 /// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce
3103331234 /// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]`
3103431235 /// (libaom `av1/common/blockd.h:1036`/`1097`) exactly -- the g35 residue
crates/ec-av1/src/motion_field.rsmodified+2 -2
@@ -461,7 +461,7 @@ pub fn setup_motion_field(
461461 );
462462 }
463463
464- if std::env::var_os("EC_TRACE_TPL").is_some() {
464+ if crate::envflags::env_flag!("EC_TRACE_TPL") {
465465 eprintln!("EC_TPL_FIELD oh={cur_order_hint} rows={rows} cols={cols}");
466466 for r in 0..rows {
467467 let row: String = (0..cols)
@@ -516,7 +516,7 @@ pub fn add_tpl_ref_mv(
516516 return None;
517517 }
518518 let probe = tpl.get(row8 as usize / 2, col8 as usize / 2);
519- if std::env::var_os("EC_TRACE_TPL").is_some() {
519+ if crate::envflags::env_flag!("EC_TRACE_TPL") {
520520 match probe {
521521 None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"),
522522 Some((m, rfo)) => eprintln!(
crates/ec-av1/src/restoration.rsmodified+43 -19
@@ -674,28 +674,48 @@ fn compute_ab(
674674 let gh = h + 2;
675675 let mut ab = vec![(0i32, 0i64); gw * gh];
676676 let n = ((2 * r + 1) * (2 * r + 1)) as i64;
677+ // lane-perf6: the box sums are separable. Summing every grid point's own
678+ // (2r+1)^2 window called `lr_sample` -- whose stripe-boundary test is the
679+ // expensive part -- (2r+1) times more often than needed; one column-sum
680+ // pass per grid row reads each source sample once per row instead, and
681+ // the horizontal sum is then (2r+1) adds of i64s. Integer addition is
682+ // exact and associative, so the totals are unchanged bit for bit.
683+ let ru = r as usize;
684+ let ncols = gw + 2 * ru;
685+ let mut col_a = vec![0i64; ncols];
686+ let mut col_b = vec![0i64; ncols];
687+ // Hoisted out of the per-point body: one thread-local read per call.
688+ let bd_shift = u32::from(crate::decode::bit_depth()).saturating_sub(8);
677689 for gi in 0..gh {
678690 let i = gi as i64 - 1;
691+ let base_col = h_start as i64 - 1 - r as i64;
692+ for k in 0..ncols {
693+ let col = base_col + k as i64;
694+ let (mut ca, mut cb) = (0i64, 0i64);
695+ for dr in -r..=r {
696+ let row = v_start as i64 + i + dr as i64;
697+ let px = lr_sample(
698+ cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col,
699+ ) as i64;
700+ ca += px * px;
701+ cb += px;
702+ }
703+ col_a[k] = ca;
704+ col_b[k] = cb;
705+ }
679706 for gj in 0..gw {
680707 let j = gj as i64 - 1;
681708 let mut a = 0i64;
682709 let mut b = 0i64;
683- for dr in -r..=r {
684- let row = v_start as i64 + i + dr as i64;
685- for dc in -r..=r {
686- let col = h_start as i64 + j + dc as i64;
687- let px =
688- lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col) as i64;
689- a += px * px;
690- b += px;
691- }
710+ for k in gj..gj + 2 * ru + 1 {
711+ a += col_a[k];
712+ b += col_b[k];
692713 }
693714 // libaom `restoration.c:660` -- the box sums are brought back
694715 // to the 8-bit scale before `p` is formed (`a` is a sum of
695716 // squares, so it loses twice the shift `b` does); `B[k]` below
696717 // keeps the RAW `b`, only `p` uses the scaled pair. At 8-bit
697718 // both shifts are 0, which is why this was invisible until now.
698- let bd_shift = u32::from(crate::decode::bit_depth()).saturating_sub(8);
699719 let a_s = round2(a, 2 * bd_shift);
700720 let b_s = round2(b, bd_shift);
701721 let p = if a_s * n < b_s * b_s { 0 } else { a_s * n - b_s * b_s };
@@ -705,7 +725,7 @@ fn compute_ab(
705725 (256 - a_val) as i64 * b * SGR_ONE_BY_X[(n - 1) as usize] as i64,
706726 SGRPROJ_RECIP_BITS,
707727 );
708- if std::env::var("EC_LR_CALL_DUMP").is_ok()
728+ if crate::envflags::env_flag!("EC_LR_CALL_DUMP")
709729 && v_start as i64 + i == 60
710730 && h_start as i64 + j == 6
711731 && r == 1
@@ -759,7 +779,7 @@ fn apply_sgrproj_stripe(
759779 // r7 traced (`[-16,-32]`); dump the real 9-byte dense-arm (r1) "u"-tap
760780 // window (physical rows 59..=61, cols 5..=7 -- r7's traced tap) straight
761781 // from `lr_sample` for this exact call, no coordinate matching involved.
762- if std::env::var("EC_LR_CALL_DUMP").is_ok() && r1 > 0 && info.xqd == [-16, -32] {
782+ if crate::envflags::env_flag!("EC_LR_CALL_DUMP") && r1 > 0 && info.xqd == [-16, -32] {
763783 let bytes: Vec<i32> = (59..=61)
764784 .flat_map(|row| {
765785 (5..=7).map(move |col| {
@@ -844,7 +864,7 @@ fn apply_sgrproj_stripe(
844864 let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;
845865 let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);
846866 v += xq[1] as i64 * (flt1 - u);
847- if std::env::var("EC_LR_CALL_DUMP").is_ok()
867+ if crate::envflags::env_flag!("EC_LR_CALL_DUMP")
848868 && info.xqd == [-16, -32]
849869 && v_start as i64 + i == 61
850870 && h_start as i64 + j == 6
@@ -929,7 +949,7 @@ fn filter_restoration_unit(
929949 /// restoration-unit pixels replaced -- a restoration unit must never read
930950 /// another, already-filtered unit's output (spec keeps a separate
931951 /// destination buffer for exactly this reason), so this never filters in
932-/// place.
952+/// place -- `out` is that buffer, refilled from `cdef` on entry.
933953 #[allow(clippy::too_many_arguments)]
934954 pub(crate) fn apply_loop_restoration_plane(
935955 cdef: &[u16],
@@ -942,10 +962,15 @@ pub(crate) fn apply_loop_restoration_plane(
942962 unit_size: u32,
943963 grid: &RestorationGrid,
944964 plane: usize,
945-) -> Vec<u16> {
946- let mut out = cdef.to_vec();
965+ // lane-perf6: the destination buffer, refilled from `cdef` here. It used
966+ // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte
967+ // allocation whose every page then faulted in on first touch.
968+ out: &mut Vec<u16>,
969+) {
970+ out.clear();
971+ out.extend_from_slice(cdef);
947972 if ftype == RestorationType::None || unit_size == 0 {
948- return out;
973+ return;
949974 }
950975 let voffset = 8u32 >> ss_y;
951976 let ext_size = (unit_size * 3) / 2;
@@ -968,7 +993,7 @@ pub(crate) fn apply_loop_restoration_plane(
968993 let filter = grid.get(plane, rrow, rcol);
969994 if filter != UnitFilter::None {
970995 filter_restoration_unit(
971- &mut out,
996+ out,
972997 cdef,
973998 deblocked,
974999 stride,
@@ -989,7 +1014,6 @@ pub(crate) fn apply_loop_restoration_plane(
9891014 rrow += 1;
9901015 }
9911016 debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");
992- out
9931017 }
9941018
9951019 #[cfg(test)]
crates/ec-av1/src/warp.rsmodified+1 -1
@@ -444,7 +444,7 @@ pub fn warp_affine(
444444 subsampling_x: i32,
445445 subsampling_y: i32,
446446 ) {
447- if std::env::var_os("EC_MC_TRACE").is_some() {
447+ if crate::envflags::env_flag!("EC_MC_TRACE") {
448448 eprintln!("EC_MC_WARP x={p_col} y={p_row} w={p_width} h={p_height}");
449449 }
450450 let bd = i32::from(crate::decode::bit_depth());