forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into lane-av1comp

Browse files at this commit

ae1b6ce215482b370f06aca845db5f62972f2eb0Ahmet Kaan GümüşParent: e062d5b39035c8
crates/ec-av1/src/decode.rsmodified+16 -2
@@ -19725,6 +19725,11 @@ pub(crate) struct FilterReplay {
19725 frame_height: usize,19725 frame_height: usize,
19726 width: usize,19726 width: usize,
19727 height: usize,19727 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>)>,
19728 }19733 }
19729 19734
19730 thread_local! {19735 thread_local! {
@@ -19772,6 +19777,7 @@ fn capture_filter_replay(
19772 frame_height,19777 frame_height,
19773 width,19778 width,
19774 height,19779 height,
19780+ deblocked: None,
19775 });19781 });
19776 });19782 });
19777 }19783 }
@@ -19785,12 +19791,17 @@ pub(crate) fn replay_filters(
19785 cdef: &CdefParams,19791 cdef: &CdefParams,
19786 fctx: &FrameCtx,19792 fctx: &FrameCtx,
19787 ) -> Option<Picture> {19793 ) -> Option<Picture> {
19788- REPLAY.with_borrow(|slot| {19794+ REPLAY.with_borrow_mut(|slot| {
19789- let r = slot.as_ref()?;19795+ let r = slot.as_mut()?;
19790 let copy = |p: &PlaneBuf<'_>| PlaneBuf {19796 let copy = |p: &PlaneBuf<'_>| PlaneBuf {
19791 data: std::borrow::Cow::Owned(p.data.to_vec()),19797 data: std::borrow::Cow::Owned(p.data.to_vec()),
19792 ..*p19798 ..*p
19793 };19799 };
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 {
19794 let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));19805 let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));
19795 apply_deblock(19806 apply_deblock(
19796 &mut y,19807 &mut y,
@@ -19802,6 +19813,9 @@ pub(crate) fn replay_filters(
19802 r.frame_height,19813 r.frame_height,
19803 fctx,19814 fctx,
19804 );19815 );
19816+ r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v)));
19817+ (y, u, v)
19818+ };
19805 apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);19819 apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);
19806 // The capture only happens on the shape the decoder's own tail19820 // The capture only happens on the shape the decoder's own tail
19807 // returns whole (no superres, no loop restoration, no crop), so this19821 // 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>)> {
55 }55 }
56 56
57 /// Squared error between a decoded plane and the source it was coded from,57 /// 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 different58+/// accumulated BOTH per CDEF unit and over the frame's own cropped `w x h`
59-/// strides: the source is the encoder's padded coding surface).59+/// in one pass: `out` is one entry per 64x64 SUPERBLOCK (stride `sb_cols`),
60-fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: usize) -> u64 {60+/// `unit` the unit side in this plane's own samples (64 for luma, 32 for
61- let mut sse = 0u64;61+/// 4:2:0 chroma) -- which is what makes the luma and chroma sums land in the
62- for row in 0..h {62+/// same slot -- and the return value the frame-level sum of the same terms.
63- let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);63+/// The two planes have different strides: the source is the encoder's padded
64- for (&a, &b) in d.iter().zip(s) {64+/// coding surface.
65- let diff = i64::from(a) - i64::from(b);65+///
66- sse += (diff * diff) as u64;66+/// The unit chunking is what makes this vectorise (lane-av1fsearch: this was
67- }67+/// the encoder's second-largest self-time symbol): the old shape divided
68- }68+/// `col / unit` per sample and accumulated straight into `out`, which LLVM
69- sse69+/// cannot turn into a reduction. Here every unit's row segment is its own
70-}70+/// `u32` reduction -- `unit <= 64` samples of at most `(2^12-1)^2` each, so
71-71+/// the accumulator cannot overflow -- and the `u64` sums are the same
72-/// [`plane_sse`], accumulated per CDEF unit instead of over the frame: `out`72+/// integers added in a different order.
73-/// is one entry per 64x64 SUPERBLOCK (stride `sb_cols`) and `unit` is the73+#[allow(clippy::too_many_arguments)]
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.
76 fn unit_sse(74 fn unit_sse(
77 dec: &[u16],75 dec: &[u16],
78 dec_w: usize,76 dec_w: usize,
@@ -83,15 +81,22 @@ fn unit_sse(
83 unit: usize,81 unit: usize,
84 sb_cols: usize,82 sb_cols: usize,
85 out: &mut [u64],83 out: &mut [u64],
86-) {84+) -> u64 {
85+ let mut total = 0u64;
87 for row in 0..h {86 for row in 0..h {
88 let base = (row / unit) * sb_cols;87 let base = (row / unit) * sb_cols;
89 let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);88 let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
90- for (col, (&a, &b)) in d.iter().zip(s).enumerate() {89+ for (i, (dc, sc)) in d.chunks(unit).zip(s.chunks(unit)).enumerate() {
91- let diff = i64::from(a) - i64::from(b);90+ let mut acc = 0u32;
92- out[base + col / unit] += (diff * diff) as u64;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);
93 }97 }
94 }98 }
99+ total
95 }100 }
96 101
97 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit102 /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit
@@ -159,22 +164,57 @@ pub(crate) fn pick_filters(
159 ) -> Result<(LoopFilterParams, CdefParams, Vec<u8>, Picture)> {164 ) -> Result<(LoopFilterParams, CdefParams, Vec<u8>, Picture)> {
160 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));165 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
161 let nsb = sb_cols * sb_rows;166 let nsb = sb_cols * sb_rows;
162- let mut trials: Vec<Trial> = Vec::new();167+ // The two sides of a candidate are scored independently: `apply_deblock`
163- let eval = |cand: Cand, trials: &mut Vec<Trial>| -> Result<usize> {168+ // filters luma on `level[0..2]` alone and each chroma plane on
164- if let Some(i) = trials.iter().position(|t| t.cand == cand) {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) {
165 return Ok(i);191 return Ok(i);
166 }192 }
167 let picture = decode(&loop_filter(cand), &cdef(cand, damping))?;193 let picture = decode(&loop_filter(cand), &cdef(cand, damping))?;
168 let dec_cw = picture.width.div_ceil(2);194 let dec_cw = picture.width.div_ceil(2);
169- let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh);195+ let (lkey, ckey) = (
170- let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch)196+ (cand.lf.0, cand.y),
171- + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch);197+ (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv),
172- let mut sse64 = vec![0u64; nsb];198+ );
173- unit_sse(&picture.y, picture.width, source[0], src_w, fw, fh, 64, sb_cols, &mut sse64);199+ if !st.luma.iter().any(|(k, _)| *k == lkey) {
174- unit_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch, 32, sb_cols, &mut sse64);200+ let mut units = vec![0u64; nsb];
175- unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut sse64);201+ let sse =
176- trials.push(Trial { cand, picture, sse_y, sse_uv, sse64 });202+ unit_sse(&picture.y, picture.width, source[0], src_w, fw, fh, 64, sb_cols, &mut units);
177- Ok(trials.len() - 1)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)
178 };218 };
179 // One stage of the coordinate search: try `values` in the slot `set`219 // One stage of the coordinate search: try `values` in the slot `set`
180 // moves and keep the one with the lowest error `sse` reads.220 // moves and keep the one with the lowest error `sse` reads.
@@ -182,16 +222,16 @@ pub(crate) fn pick_filters(
182 values: &[u8],222 values: &[u8],
183 set: fn(&mut Cand, u8),223 set: fn(&mut Cand, u8),
184 sse: fn(&Trial) -> u64,224 sse: fn(&Trial) -> u64,
185- trials: &mut Vec<Trial>|225+ st: &mut Search|
186 -> Result<()> {226 -> Result<()> {
187 let mut winner = *best;227 let mut winner = *best;
188 let mut lowest = u64::MAX;228 let mut lowest = u64::MAX;
189 for &v in values {229 for &v in values {
190 let mut cand = *best;230 let mut cand = *best;
191 set(&mut cand, v);231 set(&mut cand, v);
192- let i = eval(cand, trials)?;232+ let i = eval(cand, st)?;
193- if sse(&trials[i]) < lowest {233+ if sse(&st.trials[i]) < lowest {
194- lowest = sse(&trials[i]);234+ lowest = sse(&st.trials[i]);
195 winner = cand;235 winner = cand;
196 }236 }
197 }237 }
@@ -201,23 +241,24 @@ pub(crate) fn pick_filters(
201 241
202 let mut best = Cand { lf: (0, 0), y: (0, 0), uv: (0, 0) };242 let mut best = Cand { lf: (0, 0), y: (0, 0), uv: (0, 0) };
203 // Deblocking luma: the coarse ladder, then +-1/+-2 around its winner.243 // 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)?;
205 let refine: Vec<u8> = [-2i32, -1, 1, 2]245 let refine: Vec<u8> = [-2i32, -1, 1, 2]
206 .iter()246 .iter()
207 .filter_map(|d| u8::try_from(i32::from(best.lf.0) + d).ok())247 .filter_map(|d| u8::try_from(i32::from(best.lf.0) + d).ok())
208 .filter(|&l| l <= 63)248 .filter(|&l| l <= 63)
209 .collect();249 .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)?;
211 // Deblocking chroma, three points around the luma winner.251 // Deblocking chroma, three points around the luma winner.
212 let chroma_levels = [0, best.lf.0 / 2, best.lf.0];252 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)?;
214 // CDEF, primary then secondary, luma on luma error and chroma on chroma.254 // 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)?;255+ stage(&mut best, &CDEF_PRI, |c, v| c.y.0 = v, |t| t.sse_y, &mut st)?;
216- stage(&mut best, &CDEF_SEC, |c, v| c.y.1 = v, |t| t.sse_y, &mut trials)?;256+ stage(&mut best, &CDEF_SEC, |c, v| c.y.1 = v, |t| t.sse_y, &mut st)?;
217- stage(&mut best, &CDEF_PRI, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut trials)?;257+ stage(&mut best, &CDEF_PRI, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut st)?;
218- stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?;258+ stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut st)?;
219 259
220 CHOSEN.with(|c| c.borrow_mut().push(best));260 CHOSEN.with(|c| c.borrow_mut().push(best));
261+ let trials = st.trials;
221 262
222 // libaom `av1_cdef_search`'s shape, on the candidates this coordinate263 // libaom `av1_cdef_search`'s shape, on the candidates this coordinate
223 // search already decoded: every trial that ran under the WINNING264 // search already decoded: every trial that ran under the WINNING
@@ -480,3 +521,38 @@ thread_local! {
480 pub(crate) fn take_lr_histogram() -> (usize, usize) {521 pub(crate) fn take_lr_histogram() -> (usize, usize) {
481 LR_CHOSEN.with(|c| std::mem::take(&mut *c.borrow_mut()))522 LR_CHOSEN.with(|c| std::mem::take(&mut *c.borrow_mut()))
482 }523 }
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+}