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 {
14086 if threshold == 0 {14086 if threshold == 0 {
14087 return 0;14087 return 0;
14088 }14088 }
14089- let shift = (damping - cdef_msb(threshold)).max(0);14089+ cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
14090- diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())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+ }
14091 }14158 }
14092 14159
14093 /// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant14160 /// 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 {
14168 /// previously-filtered neighbour must never feed this block's own sum).14235 /// previously-filtered neighbour must never feed this block's own sum).
14169 #[allow(clippy::too_many_arguments)]14236 #[allow(clippy::too_many_arguments)]
14170 fn cdef_filter_block(14237 fn cdef_filter_block(
14171- sample: impl Fn(i32, i32) -> i32,14238+ src: &[i32],
14172 dst: &mut PlaneBuf,14239 dst: &mut PlaneBuf,
14173 ox: usize,14240 ox: usize,
14174 oy: usize,14241 oy: usize,
@@ -14189,19 +14256,33 @@ fn cdef_filter_block(
14189 // derivative) carries the bit-depth shift, so the tap-set parity bit14256 // derivative) carries the bit-depth shift, so the tap-set parity bit
14190 // must be read back above that shift, not off the raw low bit.14257 // must be read back above that shift, not off the raw low bit.
14191 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];14258 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]);
14192 for i in 0..bh {14272 for i in 0..bh {
14193 for j in 0..bw {14273 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);
14195 let mut sum = 0i32;14276 let mut sum = 0i32;
14196 let mut max = x;14277 let mut max = x;
14197 let mut min = x;14278 let mut min = x;
14198 for k in 0..2usize {14279 for k in 0..2usize {
14199 if enable_primary {14280 if enable_primary {
14200- let (tr, tc) = CDEF_DIRECTIONS[dir][k];14281+ let (tr, tc) = pri_dir[k];
14201- let p0 = sample(i as i32 + tr, j as i32 + tc);14282+ let p0 = at(i32i + tr, i32j + tc);
14202- let p1 = sample(i as i32 - tr, j as i32 - tc);14283+ let p1 = at(i32i - tr, i32j - tc);
14203- sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);14284+ sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
14204- sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);14285+ sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
14205 if clipping_required {14286 if clipping_required {
14206 if p0 != CDEF_VERY_LARGE {14287 if p0 != CDEF_VERY_LARGE {
14207 max = max.max(p0);14288 max = max.max(p0);
@@ -14213,12 +14294,12 @@ fn cdef_filter_block(
14213 }14294 }
14214 }14295 }
14215 if enable_secondary {14296 if enable_secondary {
14216- let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];14297+ let (tr0, tc0) = sec_dir0[k];
14217- let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];14298+ let (tr1, tc1) = sec_dir1[k];
14218- let s0 = sample(i as i32 + tr0, j as i32 + tc0);14299+ let s0 = at(i32i + tr0, i32j + tc0);
14219- let s1 = sample(i as i32 - tr0, j as i32 - tc0);14300+ let s1 = at(i32i - tr0, i32j - tc0);
14220- let s2 = sample(i as i32 + tr1, j as i32 + tc1);14301+ let s2 = at(i32i + tr1, i32j + tc1);
14221- let s3 = sample(i as i32 - tr1, j as i32 - tc1);14302+ let s3 = at(i32i - tr1, i32j - tc1);
14222 if clipping_required {14303 if clipping_required {
14223 for s in [s0, s1, s2, s3] {14304 for s in [s0, s1, s2, s3] {
14224 if s != CDEF_VERY_LARGE {14305 if s != CDEF_VERY_LARGE {
@@ -14228,17 +14309,17 @@ fn cdef_filter_block(
14228 min = min.min(s0).min(s1).min(s2).min(s3);14309 min = min.min(s0).min(s1).min(s2).min(s3);
14229 }14310 }
14230 sum += CDEF_SEC_TAPS[k]14311 sum += CDEF_SEC_TAPS[k]
14231- * (cdef_constrain(s0 - x, sec_strength, sec_damping)14312+ * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
14232- + cdef_constrain(s1 - x, sec_strength, sec_damping)14313+ + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
14233- + cdef_constrain(s2 - x, sec_strength, sec_damping)14314+ + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
14234- + cdef_constrain(s3 - x, sec_strength, sec_damping));14315+ + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
14235 }14316 }
14236 }14317 }
14237 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);14318 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
14238 if clipping_required {14319 if clipping_required {
14239 y = y.clamp(min, max);14320 y = y.clamp(min, max);
14240 }14321 }
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;
14242 }14323 }
14243 }14324 }
14244 }14325 }
@@ -15915,7 +15996,12 @@ fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32;
15915 return [p1, p0, q0, q1];15996 return [p1, p0, q0, q1];
15916 }15997 }
15917 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;15998 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;
15919 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);16005 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
15920 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };16006 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
15921 let filter = sclamp(outer + 3 * (qs0 - ps0));16007 let filter = sclamp(outer + 3 * (qs0 - ps0));
@@ -16083,6 +16169,7 @@ fn filter_edge(
16083 let shift = bit_depth() - 8;16169 let shift = bit_depth() - 8;
16084 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);16170 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
16085 let flat_thresh = 1i32 << shift;16171 let flat_thresh = 1i32 << shift;
16172+ let smax = sample_max();
16086 for i in 0..4isize {16173 for i in 0..4isize {
16087 let center = (base as isize + i * outer_stride) as usize;16174 let center = (base as isize + i * outer_stride) as usize;
16088 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };16175 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
@@ -16094,10 +16181,10 @@ fn filter_edge(
16094 && (q1 - q0).abs() <= limit16181 && (q1 - q0).abs() <= limit
16095 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;16182 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
16096 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);16183 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
16097- data[idx(-2)] = op1.clamp(0, sample_max()) as u16;16184+ data[idx(-2)] = op1.clamp(0, smax) as u16;
16098- data[idx(-1)] = op0.clamp(0, sample_max()) as u16;16185+ data[idx(-1)] = op0.clamp(0, smax) as u16;
16099- data[idx(0)] = oq0.clamp(0, sample_max()) as u16;16186+ data[idx(0)] = oq0.clamp(0, smax) as u16;
16100- data[idx(1)] = oq1.clamp(0, sample_max()) as u16;16187+ data[idx(1)] = oq1.clamp(0, smax) as u16;
16101 }16188 }
16102 6 => {16189 6 => {
16103 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));16190 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(
16111 && (p2 - p0).abs() <= flat_thresh16198 && (p2 - p0).abs() <= flat_thresh
16112 && (q2 - q0).abs() <= flat_thresh;16199 && (q2 - q0).abs() <= flat_thresh;
16113 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);16200 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;16201+ data[idx(-2)] = op1.clamp(0, smax) as u16;
16115- data[idx(-1)] = op0.clamp(0, sample_max()) as u16;16202+ data[idx(-1)] = op0.clamp(0, smax) as u16;
16116- data[idx(0)] = oq0.clamp(0, sample_max()) as u16;16203+ data[idx(0)] = oq0.clamp(0, smax) as u16;
16117- data[idx(1)] = oq1.clamp(0, sample_max()) as u16;16204+ data[idx(1)] = oq1.clamp(0, smax) as u16;
16118 }16205 }
16119 8 => {16206 8 => {
16120 let (p3, p2, p1, p0, q0, q1, q2, q3) =16207 let (p3, p2, p1, p0, q0, q1, q2, q3) =
@@ -16134,12 +16221,12 @@ fn filter_edge(
16134 && (q3 - q0).abs() <= flat_thresh;16221 && (q3 - q0).abs() <= flat_thresh;
16135 let [op2, op1, op0, oq0, oq1, oq2] =16222 let [op2, op1, op0, oq0, oq1, oq2] =
16136 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);16223 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
16137- data[idx(-3)] = op2.clamp(0, sample_max()) as u16;16224+ data[idx(-3)] = op2.clamp(0, smax) as u16;
16138- data[idx(-2)] = op1.clamp(0, sample_max()) as u16;16225+ data[idx(-2)] = op1.clamp(0, smax) as u16;
16139- data[idx(-1)] = op0.clamp(0, sample_max()) as u16;16226+ data[idx(-1)] = op0.clamp(0, smax) as u16;
16140- data[idx(0)] = oq0.clamp(0, sample_max()) as u16;16227+ data[idx(0)] = oq0.clamp(0, smax) as u16;
16141- data[idx(1)] = oq1.clamp(0, sample_max()) as u16;16228+ data[idx(1)] = oq1.clamp(0, smax) as u16;
16142- data[idx(2)] = oq2.clamp(0, sample_max()) as u16;16229+ data[idx(2)] = oq2.clamp(0, smax) as u16;
16143 }16230 }
16144 _ => {16231 _ => {
16145 let (p6, p5, p4, p3, p2, p1, p0) =16232 let (p6, p5, p4, p3, p2, p1, p0) =
@@ -16170,7 +16257,7 @@ fn filter_edge(
16170 q6,16257 q6,
16171 );16258 );
16172 for (k, v) in (-6..=5isize).zip(out) {16259 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;
16174 }16261 }
16175 }16262 }
16176 }16263 }
@@ -16273,6 +16360,43 @@ fn deblock_plane(
16273 }16360 }
16274 }16361 }
16275 16362
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+
16276 fn apply_cdef(16400 fn apply_cdef(
16277 y: &mut PlaneBuf,16401 y: &mut PlaneBuf,
16278 u: &mut PlaneBuf,16402 u: &mut PlaneBuf,
@@ -16343,6 +16467,8 @@ fn apply_cdef(
16343 return;16467 return;
16344 }16468 }
16345 let sb_cols = CDEF_SB_COLS.with(|c| c.get());16469 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.
16346 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());16472 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
16347 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {16473 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
16348 if sb_cols == 0 {16474 if sb_cols == 0 {
@@ -16354,14 +16480,18 @@ fn apply_cdef(
16354 .copied()16480 .copied()
16355 .unwrap_or(0) as usize16481 .unwrap_or(0) as usize
16356 };16482 };
16357- let src_y = y.data.clone();16483+ let src_y = scratch_from(&y.data);
16358- let src_u = u.data.clone();16484+ let src_u = scratch_from(&u.data);
16359- let src_v = v.data.clone();16485+ let src_v = scratch_from(&v.data);
16360 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,16486 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
16361 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.16487 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
16362 let coeff_shift = i32::from(bit_depth()) - 8;16488 let coeff_shift = i32::from(bit_depth()) - 8;
16363 let damping = i32::from(cdef.damping) + coeff_shift;16489 let damping = i32::from(cdef.damping) + coeff_shift;
16364 let damping_uv = (damping - 1).max(0);16490 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)];
16365 let mut mi_r = 0usize;16495 let mut mi_r = 0usize;
16366 while mi_r < skip_grid.mi_rows {16496 while mi_r < skip_grid.mi_rows {
16367 let mut mi_c = 0usize;16497 let mut mi_c = 0usize;
@@ -16372,14 +16502,22 @@ fn apply_cdef(
16372 if !skip_grid.is_skip_txfm(mi_r, mi_c) {16502 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
16373 let sidx = strength_idx(mi_r, mi_c);16503 let sidx = strength_idx(mi_r, mi_c);
16374 let (ox, oy) = (mi_c * 4, mi_r * 4);16504 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+ }
16375 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);16516 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);
16376 let sample_y = |r: i32, c: i32| -> i32 {16518 let sample_y = |r: i32, c: i32| -> i32 {
16377- let (ny, nx) = (oy as i32 + r, ox as i32 + c);16519+ win_y[(r + CDEF_BORDER as i32) as usize * (8 + 2 * CDEF_BORDER)
16378- if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {16520+ + (c + CDEF_BORDER as i32) as usize]
16379- CDEF_VERY_LARGE
16380- } else {
16381- i32::from(src_y[ny as usize * y_stride + nx as usize])
16382- }
16383 };16521 };
16384 // lane-cdef r1: the direction search reads the SAME padded16522 // lane-cdef r1: the direction search reads the SAME padded
16385 // block the taps do -- libaom runs `cdef_find_dir` on the16523 // block the taps do -- libaom runs `cdef_find_dir` on the
@@ -16417,7 +16555,7 @@ fn apply_cdef(
16417 }16555 }
16418 if enable_primary || enable_secondary {16556 if enable_primary || enable_secondary {
16419 cdef_filter_block(16557 cdef_filter_block(
16420- sample_y,16558+ &win_y,
16421 y,16559 y,
16422 ox,16560 ox,
16423 oy,16561 oy,
@@ -16444,16 +16582,9 @@ fn apply_cdef(
16444 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {16582 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
16445 let (tw, th) = (plane.true_width, plane.true_height);16583 let (tw, th) = (plane.true_width, plane.true_height);
16446 let stride = plane.width;16584 let stride = plane.width;
16447- let sample_uv = |r: i32, c: i32| -> i32 {16585+ cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
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- };
16455 cdef_filter_block(16586 cdef_filter_block(
16456- sample_uv,16587+ &win_uv,
16457 plane,16588 plane,
16458 cox,16589 cox,
16459 coy,16590 coy,
@@ -16475,6 +16606,9 @@ fn apply_cdef(
16475 }16606 }
16476 mi_r += 2;16607 mi_r += 2;
16477 }16608 }
16609+ scratch_return(src_y);
16610+ scratch_return(src_u);
16611+ scratch_return(src_v);
16478 }16612 }
16479 16613
16480 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's16614 /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
@@ -16512,7 +16646,8 @@ fn apply_loop_restoration(
16512 // (class av1-truesize-lane: true frame size vs mi-rounded).16646 // (class av1-truesize-lane: true frame size vs mi-rounded).
16513 (frame_w, frame_h): (usize, usize),16647 (frame_w, frame_h): (usize, usize),
16514 ) {16648 ) {
16515- y.data = crate::restoration::apply_loop_restoration_plane(16649+ let mut out = scratch_empty();
16650+ crate::restoration::apply_loop_restoration_plane(
16516 &y.data,16651 &y.data,
16517 &deblocked_y.data,16652 &deblocked_y.data,
16518 y.width,16653 y.width,
@@ -16523,8 +16658,12 @@ fn apply_loop_restoration(
16523 lr.loop_restoration_size[0],16658 lr.loop_restoration_size[0],
16524 grid,16659 grid,
16525 0,16660 0,
16661+ &mut out,
16526 );16662 );
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(
16528 &u.data,16667 &u.data,
16529 &deblocked_u.data,16668 &deblocked_u.data,
16530 u.width,16669 u.width,
@@ -16535,8 +16674,12 @@ fn apply_loop_restoration(
16535 lr.loop_restoration_size[1],16674 lr.loop_restoration_size[1],
16536 grid,16675 grid,
16537 1,16676 1,
16677+ &mut out,
16538 );16678 );
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(
16540 &v.data,16683 &v.data,
16541 &deblocked_v.data,16684 &deblocked_v.data,
16542 v.width,16685 v.width,
@@ -16547,7 +16690,10 @@ fn apply_loop_restoration(
16547 lr.loop_restoration_size[2],16690 lr.loop_restoration_size[2],
16548 grid,16691 grid,
16549 2,16692 2,
16693+ &mut out,
16550 );16694 );
16695+ std::mem::swap(&mut v.data, &mut out);
16696+ scratch_return(out);
16551 }16697 }
16552 16698
16553 /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,16699 /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
@@ -18863,7 +19009,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
18863 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None19009 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
18864 && lr.loop_restoration_size[p] != 019010 && lr.loop_restoration_size[p] != 0
18865 });19011 });
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)));
18867 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own19014 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
18868 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter19015 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
18869 // dump above these bisect WHICH filter stage introduced a mismatch.19016 // dump above these bisect WHICH filter stage introduced a mismatch.
@@ -18921,6 +19068,11 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
18921 (lr_w, frame_height as usize),19068 (lr_w, frame_height as usize),
18922 );19069 );
18923 }19070 }
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+ }
18924 19076
18925 let (fw, fh) = (lr_w, frame_height as usize);19077 let (fw, fh) = (lr_w, frame_height as usize);
18926 // An upscaled frame is already at its final size with no mi-aligned19078 // 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(
30891 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None31043 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
30892 && lr.loop_restoration_size[p] != 031044 && lr.loop_restoration_size[p] != 0
30893 });31045 });
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)));
30895 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own31048 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
30896 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter31049 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
30897 // dump above these bisect WHICH filter stage introduced a mismatch.31050 // dump above these bisect WHICH filter stage introduced a mismatch.
@@ -30949,6 +31102,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
30949 (lr_w, frame_height as usize),31102 (lr_w, frame_height as usize),
30950 );31103 );
30951 }31104 }
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+ }
30952 31110
30953 let motion_field = build_motion_field(31111 let motion_field = build_motion_field(
30954 &grid,31112 &grid,
@@ -31029,6 +31187,49 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
31029 #[cfg(test)]31187 #[cfg(test)]
31030 mod tests {31188 mod tests {
31031 31189
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+
31032 /// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce31233 /// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce
31033 /// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]`31234 /// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]`
31034 /// (libaom `av1/common/blockd.h:1036`/`1097`) exactly -- the g35 residue31235 /// (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(
461 );461 );
462 }462 }
463 463
464- if std::env::var_os("EC_TRACE_TPL").is_some() {464+ if crate::envflags::env_flag!("EC_TRACE_TPL") {
465 eprintln!("EC_TPL_FIELD oh={cur_order_hint} rows={rows} cols={cols}");465 eprintln!("EC_TPL_FIELD oh={cur_order_hint} rows={rows} cols={cols}");
466 for r in 0..rows {466 for r in 0..rows {
467 let row: String = (0..cols)467 let row: String = (0..cols)
@@ -516,7 +516,7 @@ pub fn add_tpl_ref_mv(
516 return None;516 return None;
517 }517 }
518 let probe = tpl.get(row8 as usize / 2, col8 as usize / 2);518 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") {
520 match probe {520 match probe {
521 None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"),521 None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"),
522 Some((m, rfo)) => eprintln!(522 Some((m, rfo)) => eprintln!(
crates/ec-av1/src/restoration.rsmodified+43 -19
@@ -674,28 +674,48 @@ fn compute_ab(
674 let gh = h + 2;674 let gh = h + 2;
675 let mut ab = vec![(0i32, 0i64); gw * gh];675 let mut ab = vec![(0i32, 0i64); gw * gh];
676 let n = ((2 * r + 1) * (2 * r + 1)) as i64;676 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);
677 for gi in 0..gh {689 for gi in 0..gh {
678 let i = gi as i64 - 1;690 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+ }
679 for gj in 0..gw {706 for gj in 0..gw {
680 let j = gj as i64 - 1;707 let j = gj as i64 - 1;
681 let mut a = 0i64;708 let mut a = 0i64;
682 let mut b = 0i64;709 let mut b = 0i64;
683- for dr in -r..=r {710+ for k in gj..gj + 2 * ru + 1 {
684- let row = v_start as i64 + i + dr as i64;711+ a += col_a[k];
685- for dc in -r..=r {712+ b += col_b[k];
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- }
692 }713 }
693 // libaom `restoration.c:660` -- the box sums are brought back714 // libaom `restoration.c:660` -- the box sums are brought back
694 // to the 8-bit scale before `p` is formed (`a` is a sum of715 // to the 8-bit scale before `p` is formed (`a` is a sum of
695 // squares, so it loses twice the shift `b` does); `B[k]` below716 // squares, so it loses twice the shift `b` does); `B[k]` below
696 // keeps the RAW `b`, only `p` uses the scaled pair. At 8-bit717 // keeps the RAW `b`, only `p` uses the scaled pair. At 8-bit
697 // both shifts are 0, which is why this was invisible until now.718 // 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);
699 let a_s = round2(a, 2 * bd_shift);719 let a_s = round2(a, 2 * bd_shift);
700 let b_s = round2(b, bd_shift);720 let b_s = round2(b, bd_shift);
701 let p = if a_s * n < b_s * b_s { 0 } else { a_s * n - b_s * b_s };721 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(
705 (256 - a_val) as i64 * b * SGR_ONE_BY_X[(n - 1) as usize] as i64,725 (256 - a_val) as i64 * b * SGR_ONE_BY_X[(n - 1) as usize] as i64,
706 SGRPROJ_RECIP_BITS,726 SGRPROJ_RECIP_BITS,
707 );727 );
708- if std::env::var("EC_LR_CALL_DUMP").is_ok()728+ if crate::envflags::env_flag!("EC_LR_CALL_DUMP")
709 && v_start as i64 + i == 60729 && v_start as i64 + i == 60
710 && h_start as i64 + j == 6730 && h_start as i64 + j == 6
711 && r == 1731 && r == 1
@@ -759,7 +779,7 @@ fn apply_sgrproj_stripe(
759 // r7 traced (`[-16,-32]`); dump the real 9-byte dense-arm (r1) "u"-tap779 // r7 traced (`[-16,-32]`); dump the real 9-byte dense-arm (r1) "u"-tap
760 // window (physical rows 59..=61, cols 5..=7 -- r7's traced tap) straight780 // window (physical rows 59..=61, cols 5..=7 -- r7's traced tap) straight
761 // from `lr_sample` for this exact call, no coordinate matching involved.781 // 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] {
763 let bytes: Vec<i32> = (59..=61)783 let bytes: Vec<i32> = (59..=61)
764 .flat_map(|row| {784 .flat_map(|row| {
765 (5..=7).map(move |col| {785 (5..=7).map(move |col| {
@@ -844,7 +864,7 @@ fn apply_sgrproj_stripe(
844 let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;864 let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;
845 let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);865 let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);
846 v += xq[1] as i64 * (flt1 - u);866 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")
848 && info.xqd == [-16, -32]868 && info.xqd == [-16, -32]
849 && v_start as i64 + i == 61869 && v_start as i64 + i == 61
850 && h_start as i64 + j == 6870 && h_start as i64 + j == 6
@@ -929,7 +949,7 @@ fn filter_restoration_unit(
929 /// restoration-unit pixels replaced -- a restoration unit must never read949 /// restoration-unit pixels replaced -- a restoration unit must never read
930 /// another, already-filtered unit's output (spec keeps a separate950 /// another, already-filtered unit's output (spec keeps a separate
931 /// destination buffer for exactly this reason), so this never filters in951 /// destination buffer for exactly this reason), so this never filters in
932-/// place.952+/// place -- `out` is that buffer, refilled from `cdef` on entry.
933 #[allow(clippy::too_many_arguments)]953 #[allow(clippy::too_many_arguments)]
934 pub(crate) fn apply_loop_restoration_plane(954 pub(crate) fn apply_loop_restoration_plane(
935 cdef: &[u16],955 cdef: &[u16],
@@ -942,10 +962,15 @@ pub(crate) fn apply_loop_restoration_plane(
942 unit_size: u32,962 unit_size: u32,
943 grid: &RestorationGrid,963 grid: &RestorationGrid,
944 plane: usize,964 plane: usize,
945-) -> Vec<u16> {965+ // lane-perf6: the destination buffer, refilled from `cdef` here. It used
946- let mut out = cdef.to_vec();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);
947 if ftype == RestorationType::None || unit_size == 0 {972 if ftype == RestorationType::None || unit_size == 0 {
948- return out;973+ return;
949 }974 }
950 let voffset = 8u32 >> ss_y;975 let voffset = 8u32 >> ss_y;
951 let ext_size = (unit_size * 3) / 2;976 let ext_size = (unit_size * 3) / 2;
@@ -968,7 +993,7 @@ pub(crate) fn apply_loop_restoration_plane(
968 let filter = grid.get(plane, rrow, rcol);993 let filter = grid.get(plane, rrow, rcol);
969 if filter != UnitFilter::None {994 if filter != UnitFilter::None {
970 filter_restoration_unit(995 filter_restoration_unit(
971- &mut out,996+ out,
972 cdef,997 cdef,
973 deblocked,998 deblocked,
974 stride,999 stride,
@@ -989,7 +1014,6 @@ pub(crate) fn apply_loop_restoration_plane(
989 rrow += 1;1014 rrow += 1;
990 }1015 }
991 debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");1016 debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");
992- out
993 }1017 }
994 1018
995 #[cfg(test)]1019 #[cfg(test)]
crates/ec-av1/src/warp.rsmodified+1 -1
@@ -444,7 +444,7 @@ pub fn warp_affine(
444 subsampling_x: i32,444 subsampling_x: i32,
445 subsampling_y: i32,445 subsampling_y: i32,
446 ) {446 ) {
447- if std::env::var_os("EC_MC_TRACE").is_some() {447+ if crate::envflags::env_flag!("EC_MC_TRACE") {
448 eprintln!("EC_MC_WARP x={p_col} y={p_row} w={p_width} h={p_height}");448 eprintln!("EC_MC_WARP x={p_col} y={p_row} w={p_width} h={p_height}");
449 }449 }
450 let bd = i32::from(crate::decode::bit_depth());450 let bd = i32::from(crate::decode::bit_depth());