forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into lane-av1tiles

Browse files at this commit

b8d4d36916573ebaa7387ff4ff1f8bff845f1fbbAhmet Kaan GümüşParent: ebca9e839035c8
crates/ec-av1/src/decode.rsmodified+27 -13
@@ -19725,6 +19725,11 @@ pub(crate) struct FilterReplay {
1972519725 frame_height: usize,
1972619726 width: usize,
1972719727 height: usize,
19728+ /// The last deblocked planes and the levels that produced them.
19729+ /// Deblocking depends on nothing else the search moves, and the search
19730+ /// fixes the levels before it walks the CDEF strengths, so every
19731+ /// candidate after the first of a level pair replays CDEF alone.
19732+ deblocked: Option<(LoopFilterParams, PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
1972819733 }
1972919734
1973019735 thread_local! {
@@ -19772,6 +19777,7 @@ fn capture_filter_replay(
1977219777 frame_height,
1977319778 width,
1977419779 height,
19780+ deblocked: None,
1977519781 });
1977619782 });
1977719783 }
@@ -19785,23 +19791,31 @@ pub(crate) fn replay_filters(
1978519791 cdef: &CdefParams,
1978619792 fctx: &FrameCtx,
1978719793 ) -> Option<Picture> {
19788- REPLAY.with_borrow(|slot| {
19789- let r = slot.as_ref()?;
19794+ REPLAY.with_borrow_mut(|slot| {
19795+ let r = slot.as_mut()?;
1979019796 let copy = |p: &PlaneBuf<'_>| PlaneBuf {
1979119797 data: std::borrow::Cow::Owned(p.data.to_vec()),
1979219798 ..*p
1979319799 };
19794- let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));
19795- apply_deblock(
19796- &mut y,
19797- &mut u,
19798- &mut v,
19799- loop_filter,
19800- &r.neighbours,
19801- r.frame_width,
19802- r.frame_height,
19803- fctx,
19804- );
19800+ let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
19801+ let (mut y, mut u, mut v) = if hit {
19802+ let (_, dy, du, dv) = r.deblocked.as_ref().expect("just matched");
19803+ (copy(dy), copy(du), copy(dv))
19804+ } else {
19805+ let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));
19806+ apply_deblock(
19807+ &mut y,
19808+ &mut u,
19809+ &mut v,
19810+ loop_filter,
19811+ &r.neighbours,
19812+ r.frame_width,
19813+ r.frame_height,
19814+ fctx,
19815+ );
19816+ r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v)));
19817+ (y, u, v)
19818+ };
1980519819 apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);
1980619820 // The capture only happens on the shape the decoder's own tail
1980719821 // returns whole (no superres, no loop restoration, no crop), so this
crates/ec-av1/src/filter_search.rsmodified+121 -45
@@ -55,24 +55,22 @@ pub(crate) fn take_cdef_presets() -> Vec<(u8, Vec<usize>)> {
5555 }
5656
5757 /// Squared error between a decoded plane and the source it was coded from,
58-/// over the frame's own cropped `w x h` (the two planes have different
59-/// strides: the source is the encoder's padded coding surface).
60-fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: usize) -> u64 {
61- let mut sse = 0u64;
62- for row in 0..h {
63- let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
64- for (&a, &b) in d.iter().zip(s) {
65- let diff = i64::from(a) - i64::from(b);
66- sse += (diff * diff) as u64;
67- }
68- }
69- sse
70-}
71-
72-/// [`plane_sse`], accumulated per CDEF unit instead of over the frame: `out`
73-/// is one entry per 64x64 SUPERBLOCK (stride `sb_cols`) and `unit` is the
74-/// unit side in this plane's own samples (64 for luma, 32 for 4:2:0 chroma),
75-/// which is what makes the luma and chroma sums land in the same slot.
58+/// accumulated BOTH per CDEF unit and over the frame's own cropped `w x h`
59+/// in one pass: `out` is one entry per 64x64 SUPERBLOCK (stride `sb_cols`),
60+/// `unit` the unit side in this plane's own samples (64 for luma, 32 for
61+/// 4:2:0 chroma) -- which is what makes the luma and chroma sums land in the
62+/// same slot -- and the return value the frame-level sum of the same terms.
63+/// The two planes have different strides: the source is the encoder's padded
64+/// coding surface.
65+///
66+/// The unit chunking is what makes this vectorise (lane-av1fsearch: this was
67+/// the encoder's second-largest self-time symbol): the old shape divided
68+/// `col / unit` per sample and accumulated straight into `out`, which LLVM
69+/// cannot turn into a reduction. Here every unit's row segment is its own
70+/// `u32` reduction -- `unit <= 64` samples of at most `(2^12-1)^2` each, so
71+/// the accumulator cannot overflow -- and the `u64` sums are the same
72+/// integers added in a different order.
73+#[allow(clippy::too_many_arguments)]
7674 fn unit_sse(
7775 dec: &[u16],
7876 dec_w: usize,
@@ -83,15 +81,22 @@ fn unit_sse(
8381 unit: usize,
8482 sb_cols: usize,
8583 out: &mut [u64],
86-) {
84+) -> u64 {
85+ let mut total = 0u64;
8786 for row in 0..h {
8887 let base = (row / unit) * sb_cols;
8988 let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
90- for (col, (&a, &b)) in d.iter().zip(s).enumerate() {
91- let diff = i64::from(a) - i64::from(b);
92- out[base + col / unit] += (diff * diff) as u64;
89+ for (i, (dc, sc)) in d.chunks(unit).zip(s.chunks(unit)).enumerate() {
90+ let mut acc = 0u32;
91+ for (&a, &b) in dc.iter().zip(sc) {
92+ let diff = i32::from(a) - i32::from(b);
93+ acc += (diff * diff) as u32;
94+ }
95+ out[base + i] += u64::from(acc);
96+ total += u64::from(acc);
9397 }
9498 }
99+ total
95100 }
96101
97102 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit
@@ -159,22 +164,57 @@ pub(crate) fn pick_filters(
159164 ) -> Result<(LoopFilterParams, CdefParams, Vec<u8>, Picture)> {
160165 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
161166 let nsb = sb_cols * sb_rows;
162- let mut trials: Vec<Trial> = Vec::new();
163- let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {
164- if let Some(i) = trials.iter().position(|t| t.cand == cand) {
167+ // The two sides of a candidate are scored independently: `apply_deblock`
168+ // filters luma on `level[0..2]` alone and each chroma plane on
169+ // `level[2..4]` alone, and CDEF's strengths are per plane type too (a
170+ // zero strength pair is the identity filter), so a candidate that moves
171+ // only the chroma slot leaves every luma sample -- and every luma error
172+ // term -- exactly as the previous candidate had it. Each side's error is
173+ // therefore memoized under the parameters that side actually reads,
174+ // which is what takes ~32 candidates' worth of summing down to ~17 luma
175+ // and ~12 chroma passes.
176+ struct Search {
177+ trials: Vec<Trial>,
178+ /// `(luma deblock level, luma CDEF strengths) -> (frame sse, per-unit sse)`.
179+ luma: Vec<((u8, (u8, u8)), (u64, Vec<u64>))>,
180+ /// `(luma deblock level, chroma deblock level, chroma CDEF
181+ /// strengths) -> the same`. The luma level is in the key because
182+ /// CDEF's direction search runs on the post-deblock LUMA window and
183+ /// chroma reuses that direction (`decode.rs`: `uv_dir`); it is
184+ /// pinned to 0 for a chroma-CDEF-off candidate, whose chroma planes
185+ /// CDEF never touches at all.
186+ chroma: Vec<((u8, u8, (u8, u8)), (u64, Vec<u64>))>,
187+ }
188+ let mut st = Search { trials: Vec::new(), luma: Vec::new(), chroma: Vec::new() };
189+ let eval = |cand: Cand, st: &mut Search| -> Result<usize> {
190+ if let Some(i) = st.trials.iter().position(|t| t.cand == cand) {
165191 return Ok(i);
166192 }
167193 let picture = decode(&loop_filter(cand), &cdef(cand, damping))?;
168194 let dec_cw = picture.width.div_ceil(2);
169- let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);
170- let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)
171- + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);
172- let mut sse64 = vec![0u64; nsb];
173- unit_sse(&picture.y, picture.width, source[0], src_w, fw, fh, 64, sb_cols, &mut sse64);
174- unit_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch, 32, sb_cols, &mut sse64);
175- unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut sse64);
176- trials.push(Trial { cand, picture, sse_y, sse_uv, sse64 });
177- Ok(trials.len() - 1)
195+ let (lkey, ckey) = (
196+ (cand.lf.0, cand.y),
197+ (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv),
198+ );
199+ if !st.luma.iter().any(|(k, _)| *k == lkey) {
200+ let mut units = vec![0u64; nsb];
201+ let sse =
202+ unit_sse(&picture.y, picture.width, source[0], src_w, fw, fh, 64, sb_cols, &mut units);
203+ st.luma.push((lkey, (sse, units)));
204+ }
205+ if !st.chroma.iter().any(|(k, _)| *k == ckey) {
206+ let mut units = vec![0u64; nsb];
207+ let sse = unit_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch, 32, sb_cols, &mut units)
208+ + unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut units);
209+ st.chroma.push((ckey, (sse, units)));
210+ }
211+ let (sse_y, sse_uv, sse64) = {
212+ let l = &st.luma.iter().find(|(k, _)| *k == lkey).expect("just inserted").1;
213+ let c = &st.chroma.iter().find(|(k, _)| *k == ckey).expect("just inserted").1;
214+ (l.0, c.0, l.1.iter().zip(&c.1).map(|(a, b)| a + b).collect())
215+ };
216+ st.trials.push(Trial { cand, picture, sse_y, sse_uv, sse64 });
217+ Ok(st.trials.len() - 1)
178218 };
179219 // One stage of the coordinate search: try `values` in the slot `set`
180220 // moves and keep the one with the lowest error `sse` reads.
@@ -182,16 +222,16 @@ pub(crate) fn pick_filters(
182222 values: &[u8],
183223 set: fn(&mut Cand, u8),
184224 sse: fn(&Trial) -> u64,
185- trials: &mut Vec<Trial>|
225+ st: &mut Search|
186226 -> Result<()> {
187227 let mut winner = *best;
188228 let mut lowest = u64::MAX;
189229 for &v in values {
190230 let mut cand = *best;
191231 set(&mut cand, v);
192- let i = eval(cand, trials)?;
193- if sse(&trials[i]) < lowest {
194- lowest = sse(&trials[i]);
232+ let i = eval(cand, st)?;
233+ if sse(&st.trials[i]) < lowest {
234+ lowest = sse(&st.trials[i]);
195235 winner = cand;
196236 }
197237 }
@@ -201,23 +241,24 @@ pub(crate) fn pick_filters(
201241
202242 let mut best = Cand { lf: (0, 0), y: (0, 0), uv: (0, 0) };
203243 // Deblocking luma: the coarse ladder, then +-1/+-2 around its winner.
204- stage(&mut best, &COARSE, |c, v| c.lf = (v, v), |t| t.sse_y, &mut trials)?;
244+ stage(&mut best, &COARSE, |c, v| c.lf = (v, v), |t| t.sse_y, &mut st)?;
205245 let refine: Vec<u8> = [-2i32, -1, 1, 2]
206246 .iter()
207247 .filter_map(|d| u8::try_from(i32::from(best.lf.0) + d).ok())
208248 .filter(|&l| l <= 63)
209249 .collect();
210- stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut trials)?;
250+ stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut st)?;
211251 // Deblocking chroma, three points around the luma winner.
212252 let chroma_levels = [0, best.lf.0 / 2, best.lf.0];
213- stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut trials)?;
253+ stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut st)?;
214254 // CDEF, primary then secondary, luma on luma error and chroma on chroma.
215- stage(&mut best, &CDEF_PRI, |c, v| c.y.0 = v, |t| t.sse_y, &mut trials)?;
216- stage(&mut best, &CDEF_SEC, |c, v| c.y.1 = v, |t| t.sse_y, &mut trials)?;
217- stage(&mut best, &CDEF_PRI, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut trials)?;
218- stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;
255+ stage(&mut best, &CDEF_PRI, |c, v| c.y.0 = v, |t| t.sse_y, &mut st)?;
256+ stage(&mut best, &CDEF_SEC, |c, v| c.y.1 = v, |t| t.sse_y, &mut st)?;
257+ stage(&mut best, &CDEF_PRI, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut st)?;
258+ stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut st)?;
219259
220260 CHOSEN.with(|c| c.borrow_mut().push(best));
261+ let trials = st.trials;
221262
222263 // libaom `av1_cdef_search`'s shape, on the candidates this coordinate
223264 // search already decoded: every trial that ran under the WINNING
@@ -480,3 +521,38 @@ thread_local! {
480521 pub(crate) fn take_lr_histogram() -> (usize, usize) {
481522 LR_CHOSEN.with(|c| std::mem::take(&mut *c.borrow_mut()))
482523 }
524+
525+#[cfg(test)]
526+mod tests {
527+ use super::unit_sse;
528+
529+ /// [`unit_sse`]'s chunked, `u32`-accumulating shape against the naive
530+ /// per-sample reference it replaced -- per unit AND in total, on a plane
531+ /// whose width is not a whole number of units (the case where the last
532+ /// chunk is short) and with strides wider than the region scored.
533+ #[test]
534+ fn unit_sse_matches_the_naive_sum() {
535+ let (w, h, unit, sb_cols) = (100usize, 70usize, 32usize, 4usize);
536+ let (dec_w, src_w) = (w + 7, w + 13);
537+ let mut state = 0x1234_5678u32;
538+ let mut rnd = move || {
539+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
540+ (state >> 24) as u8
541+ };
542+ let dec: Vec<u16> = (0..dec_w * h).map(|_| u16::from(rnd())).collect();
543+ let src: Vec<u8> = (0..src_w * h).map(|_| rnd()).collect();
544+ let mut want = vec![7u64; sb_cols * 4]; // a non-zero start: this accumulates
545+ let mut total = 0u64;
546+ for row in 0..h {
547+ let base = (row / unit) * sb_cols;
548+ for col in 0..w {
549+ let diff = i64::from(dec[row * dec_w + col]) - i64::from(src[row * src_w + col]);
550+ want[base + col / unit] += (diff * diff) as u64;
551+ total += (diff * diff) as u64;
552+ }
553+ }
554+ let mut got = vec![7u64; sb_cols * 4];
555+ assert_eq!(unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut got), total);
556+ assert_eq!(got, want);
557+ }
558+}