forge
Explore
Log in

Don't you dare go Hollow

The CDEF candidate loop keeps one destination and restores only what the last candidate wrote

Browse files at this commit

3847d870f03202f16aa657ae18a3155331c2e61bAhmet Kaan GümüşParent: 1aa39c7
  • perf
    • the CDEF candidate loop keeps one destination and restores only what the last candidate wrote
Show full message
perf(av1): the CDEF candidate loop keeps one destination and restores only what the last candidate wrote

The encoder's filter search scores ~32 candidates on one captured
reconstruction, and the ~17 of them that only move a CDEF strength used
to copy the three post-deblock planes (~19 MB at 4K) into fresh
destinations before every one -- 7% of a 4K frame's wall, the largest
plane-copy bucket left.

`cdef_band` now fills a per-8x8-unit map (bit 0 luma, bit 1 chroma) of
the units it actually filtered, which is what the reuse needs: the
per-unit variance goes through `cdef_adjust_strength`, so a candidate
with a lower primary strength can leave units its predecessor wrote and
the map is not a function of the strengths alone (the reason an earlier
lane recorded this reuse as not provably exact).

The replay keeps its destination planes between candidates and restores,
from the post-deblock cache, the column span between the first and last
written unit of each unit row -- contiguous, never more than the
whole-plane copy it replaces. Two restores fall away entirely: a plane
whose strengths did not move, and a plane whose new primary strength is
no lower with a secondary that is zero only if the old one's was, since
`cdef_adjust_strength` is monotone and every unit CDEF writes it writes
from the post-deblock source alone. Only while both candidates carry one
strength pair and read the same cdef_idx grid; the final replay restores
everything.

Byte-exact: the pins (q150 7173 / q60 26362), enc_probe FNV on the
640x384 gate clip at q 150/120/90/60 and on both real-film 1920x768
crops at q 150/60 all match a b7990ec1 baseline binary exactly, and the
replay-identity, facade and thread-count determinism tests pass.

4K 3840x1608 4x2 tiles / 8 threads, best of 3 on a contended box:
plane copies 316 -> 268 ms per 4 frames (-15%), cdef replay unmoved.
crates/ec-av1/src/decode.rsmodified+154 -6
@@ -19741,6 +19741,21 @@ pub(crate) struct FilterReplay {
19741 /// rows) -- what [`replay_restoration`] filters, instead of decoding19741 /// rows) -- what [`replay_restoration`] filters, instead of decoding
19742 /// the re-coded tile a second time.19742 /// the re-coded tile a second time.
19743 final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>,19743 final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>,
19744+ /// lane-av1speed3: the previous candidate's DESTINATION planes, still
19745+ /// holding its post-CDEF samples, and one byte per 8x8 CDEF unit its
19746+ /// filter wrote (see [`cdef_band`]). The CDEF half of the search moves
19747+ /// no deblocking level, so every candidate of it used to copy the three
19748+ /// post-deblock planes (~19 MB at 4K) into fresh destinations. Here the
19749+ /// destinations are kept and only the units the last candidate touched
19750+ /// are restored -- the same bytes, since a unit nobody wrote still holds
19751+ /// the deblocked sample it was copied from.
19752+ work: Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
19753+ wrote: Vec<u8>,
19754+ /// The strengths [`FilterReplay::work`] was filtered under: a plane whose
19755+ /// new candidate can only write MORE units than the old one needs no
19756+ /// restore at all, since every unit CDEF writes it writes from the
19757+ /// post-deblock source alone.
19758+ work_cdef: Option<CdefParams>,
19744 /// The last deblocked planes and the levels that produced them.19759 /// The last deblocked planes and the levels that produced them.
19745 /// Deblocking depends on nothing else the search moves, and the search19760 /// Deblocking depends on nothing else the search moves, and the search
19746 /// fixes the levels before it walks the CDEF strengths, so every19761 /// fixes the levels before it walks the CDEF strengths, so every
@@ -19830,12 +19845,66 @@ fn capture_filter_replay(
19830 true_width,19845 true_width,
19831 true_height,19846 true_height,
19832 scratch: Vec::new(),19847 scratch: Vec::new(),
19848+ work: None,
19849+ wrote: Vec::new(),
19850+ work_cdef: None,
19833 final_luma: None,19851 final_luma: None,
19834 deblocked: None,19852 deblocked: None,
19835 });19853 });
19836 });19854 });
19837 }19855 }
19838 19856
19857+/// Restores, from the post-deblock cache, every sample the previous CDEF
19858+/// candidate may have written: for each unit row, the column span between
19859+/// its first and last written unit (a superset of the written units, which
19860+/// is what makes the copy contiguous -- and never more than the whole-plane
19861+/// copy it replaces). `unit` is this plane's CDEF unit side, 8 for luma and
19862+/// 4 for 4:2:0 chroma.
19863+fn restore_written(
19864+ dst: &mut PlaneBuf<'static>,
19865+ src: &PlaneBuf<'_>,
19866+ wrote: &[u8],
19867+ mask: u8,
19868+ unit_cols: usize,
19869+ unit: usize,
19870+) {
19871+ let w = dst.width;
19872+ if w == 0 || unit_cols == 0 || wrote.is_empty() {
19873+ return;
19874+ }
19875+ let rows = dst.data.len() / w;
19876+ let s: &[u16] = &src.data;
19877+ let d = dst.data.to_mut();
19878+ let band = |d: &mut [u16], wr: &[u8], ur0: usize| {
19879+ for (i, row) in wr.chunks(unit_cols).enumerate() {
19880+ let Some(c0) = row.iter().position(|&b| b & mask != 0) else {
19881+ continue;
19882+ };
19883+ let c1 = row.iter().rposition(|&b| b & mask != 0).expect("just found one");
19884+ let (x0, x1) = ((c0 * unit).min(w), ((c1 + 1) * unit).min(w));
19885+ let ur = ur0 + i;
19886+ let (y0, y1) = ((ur * unit).min(rows), ((ur + 1) * unit).min(rows));
19887+ for r in y0..y1 {
19888+ let off = (r - ur0 * unit) * w;
19889+ d[off + x0..off + x1].copy_from_slice(&s[r * w + x0..r * w + x1]);
19890+ }
19891+ }
19892+ };
19893+ let urows = wrote.len() / unit_cols;
19894+ let threads = crate::par::filter_threads().min(urows.max(1));
19895+ if threads <= 1 {
19896+ band(d, wrote, 0);
19897+ return;
19898+ }
19899+ let per = urows.div_ceil(threads);
19900+ let batch = crate::par::Batch::new("ec-av1-filter");
19901+ for (i, (dc, wr)) in d.chunks_mut(per * unit * w).zip(wrote.chunks(per * unit_cols)).enumerate()
19902+ {
19903+ let band = &band;
19904+ batch.submit(move || band(dc, wr, i * per));
19905+ }
19906+}
19907+
19839 /// One candidate's working copy of a captured plane, off [`FilterReplay`]'s19908 /// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
19840 /// own buffer pool: a cleared `Vec` that already has the capacity keeps the19909 /// own buffer pool: a cleared `Vec` that already has the capacity keeps the
19841 /// allocator and the page fault handler out of the filter search.19910 /// allocator and the page fault handler out of the filter search.
@@ -19920,13 +19989,54 @@ fn replay_inner(
19920 // of them rather than taking their buffers.19989 // of them rather than taking their buffers.
19921 let mut share = false;19990 let mut share = false;
19922 let cpt = crate::par::timer(crate::par::S_COPY);19991 let cpt = crate::par::timer(crate::par::S_COPY);
19992+ let unit_cols = r.neighbours.mi_cols.div_ceil(2);
19993+ let unit_rows = r.neighbours.mi_rows.div_ceil(2);
19923 let (mut y, mut u, mut v) = if hit {19994 let (mut y, mut u, mut v) = if hit {
19995+ let work = r.work.take();
19996+ let wrote = std::mem::take(&mut r.wrote);
19997+ // `cdef_adjust_strength` is monotone in the strength it is given,
19998+ // so a candidate whose primary strength is no lower and whose
19999+ // secondary is zero only if the last one's was writes every unit
20000+ // the last one wrote -- and writes it from the same post-deblock
20001+ // source, so the samples under it need not be put back first.
20002+ // Only while both candidates carry ONE strength pair (`bits ==
20003+ // 0`, every scoring candidate) and read the same `cdef_idx` grid.
20004+ let superset = |cur: (u8, u8), old: (u8, u8)| cur.0 >= old.0 && (cur.1 != 0 || old.1 == 0);
20005+ let (skip_y, skip_uv) = match (final_pass, &r.work_cdef) {
20006+ (None, Some(old)) if old.bits == 0 && cdef.bits == 0 => (
20007+ superset(
20008+ (cdef.y_pri_strength[0], cdef.y_sec_strength[0]),
20009+ (old.y_pri_strength[0], old.y_sec_strength[0]),
20010+ ),
20011+ superset(
20012+ (cdef.uv_pri_strength[0], cdef.uv_sec_strength[0]),
20013+ (old.uv_pri_strength[0], old.uv_sec_strength[0]),
20014+ ),
20015+ ),
20016+ _ => (false, false),
20017+ };
19924 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);20018 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
19925 let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");20019 let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
19926- (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch))20020+ match work {
20021+ Some((mut wy, mut wu, mut wv)) => {
20022+ if !skip_y {
20023+ restore_written(&mut wy, dy, &wrote, 1, unit_cols, 8);
20024+ }
20025+ if !skip_uv {
20026+ restore_written(&mut wu, du, &wrote, 2, unit_cols, 4);
20027+ restore_written(&mut wv, dv, &wrote, 2, unit_cols, 4);
20028+ }
20029+ (wy, wu, wv)
20030+ }
20031+ None => (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch)),
20032+ }
19927 } else {20033 } else {
19928 // The levels moved, so the cached deblocked planes are dead:20034 // The levels moved, so the cached deblocked planes are dead:
19929 // their buffers are this candidate's working copies.20035 // their buffers are this candidate's working copies.
20036+ for plane in r.work.take().into_iter().flat_map(|(a, b, c)| [a, b, c]) {
20037+ r.scratch.push(plane.data.into_owned());
20038+ }
20039+ r.work_cdef = None;
19930 if let Some((_, dy, du, dv)) = r.deblocked.take() {20040 if let Some((_, dy, du, dv)) = r.deblocked.take() {
19931 r.scratch.push(dy.data.into_owned());20041 r.scratch.push(dy.data.into_owned());
19932 r.scratch.push(du.data.into_owned());20042 r.scratch.push(du.data.into_owned());
@@ -19974,12 +20084,17 @@ fn replay_inner(
19974 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec());20084 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec());
19975 }20085 }
19976 let ct = crate::par::timer(crate::par::S_CDEF);20086 let ct = crate::par::timer(crate::par::S_CDEF);
20087+ let mut wrote = std::mem::take(&mut r.wrote);
20088+ wrote.clear();
20089+ wrote.resize(unit_cols * unit_rows, 0);
20090+ r.work_cdef = Some(*cdef);
19977 let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| {20091 let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| {
19978 (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())20092 (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())
19979 });20093 });
19980 apply_cdef(20094 apply_cdef(
19981 &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx,20095 &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx,
19982 pre,20096 pre,
20097+ Some(&mut wrote),
19983 );20098 );
19984 drop(ct);20099 drop(ct);
19985 if final_pass.is_some_and(|(_, want)| want) {20100 if final_pass.is_some_and(|(_, want)| want) {
@@ -20017,6 +20132,8 @@ fn replay_inner(
20017 let (fw, fh) = (r.frame_width, r.frame_height);20132 let (fw, fh) = (r.frame_width, r.frame_height);
20018 if fw == r.width && fh == r.height {20133 if fw == r.width && fh == r.height {
20019 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);20134 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
20135+ r.wrote = Vec::new();
20136+ r.work_cdef = None;
20020 if share {20137 if share {
20021 let picture = Picture {20138 let picture = Picture {
20022 width: r.width,20139 width: r.width,
@@ -20067,13 +20184,14 @@ fn replay_inner(
20067 // deblocked planes this candidate's successors reuse, or they go20184 // deblocked planes this candidate's successors reuse, or they go
20068 // back to the pool.20185 // back to the pool.
20069 if share {20186 if share {
20187+ r.wrote = Vec::new();
20188+ r.work_cdef = None;
20070 r.deblocked = Some((*loop_filter, y, u, v));20189 r.deblocked = Some((*loop_filter, y, u, v));
20071 } else {20190 } else {
20072- for plane in [y, u, v] {20191+ // lane-av1speed3: kept whole (post-CDEF samples and all) for the
20073- if r.scratch.len() < 6 {20192+ // next candidate, together with the map of what CDEF wrote.
20074- r.scratch.push(plane.data.into_owned());20193+ r.wrote = wrote;
20075- }20194+ r.work = Some((y, u, v));
20076- }
20077 }20195 }
20078 Some((out, stages))20196 Some((out, stages))
20079 })20197 })
@@ -20208,7 +20326,16 @@ fn cdef_band(
20208 damping_uv: i32,20326 damping_uv: i32,
20209 (frame_w, frame_h): (usize, usize),20327 (frame_w, frame_h): (usize, usize),
20210 fctx: &crate::decode::FrameCtx,20328 fctx: &crate::decode::FrameCtx,
20329+ // lane-av1speed3: one byte per 8x8 CDEF unit of the WHOLE frame (stride
20330+ // `mi_cols.div_ceil(2)`), set for every unit this band actually filters.
20331+ // Bit 0 = this unit's LUMA square was filtered, bit 1 = its chroma ones.
20332+ // `cdef_adjust_strength` zeroes a unit's primary strength off its own
20333+ // variance, so which units a candidate writes is not a function of its
20334+ // strengths alone -- the encoder's filter replay reuses one destination
20335+ // plane across candidates and needs the map to restore it.
20336+ mut wrote: Option<&mut [u8]>,
20211 ) {20337 ) {
20338+ let unit_cols = skip_grid.mi_cols.div_ceil(2);
20212 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {20339 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
20213 if sb_cols == 0 {20340 if sb_cols == 0 {
20214 return 0;20341 return 0;
@@ -20304,6 +20431,11 @@ fn cdef_band(
20304 let uv_dir = if t_uv != 0 { dir } else { 0 };20431 let uv_dir = if t_uv != 0 { dir } else { 0 };
20305 let enable_primary_uv = t_uv != 0;20432 let enable_primary_uv = t_uv != 0;
20306 let enable_secondary_uv = uv_sec_strength != 0;20433 let enable_secondary_uv = uv_sec_strength != 0;
20434+ if let Some(w) = wrote.as_deref_mut() {
20435+ let mark = u8::from(enable_primary || enable_secondary)
20436+ | (u8::from(enable_primary_uv || enable_secondary_uv) << 1);
20437+ w[(mi_r / 2) * unit_cols + mi_c / 2] = mark;
20438+ }
20307 if enable_primary_uv || enable_secondary_uv {20439 if enable_primary_uv || enable_secondary_uv {
20308 let (cox, coy) = (ox / 2, oy / 2);20440 let (cox, coy) = (ox / 2, oy / 2);
20309 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {20441 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
@@ -20508,6 +20640,7 @@ fn pipe_run(
20508 cdef_rows(20640 cdef_rows(
20509 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,20641 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
20510 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,20642 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
20643+ None,
20511 );20644 );
20512 }20645 }
20513 }20646 }
@@ -20818,6 +20951,9 @@ fn cdef_rows(
20818 (frame_w, frame_h): (usize, usize),20951 (frame_w, frame_h): (usize, usize),
20819 r_lo0: usize,20952 r_lo0: usize,
20820 r_hi0: usize, fctx: &crate::decode::FrameCtx,20953 r_hi0: usize, fctx: &crate::decode::FrameCtx,
20954+ // See [`cdef_band`]. Shared because the bands below write disjoint unit
20955+ // ROWS of it, exactly as they write disjoint plane rows.
20956+ wrote: Option<crate::par::Shared<'_, [u8]>>,
20821 ) {20957 ) {
20822 let mi_rows = skip_grid.mi_rows;20958 let mi_rows = skip_grid.mi_rows;
20823 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));20959 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
@@ -20838,6 +20974,10 @@ fn cdef_rows(
20838 // disjoint from every other band's (see `Shared`).20974 // disjoint from every other band's (see `Shared`).
20839 #[allow(unsafe_code)]20975 #[allow(unsafe_code)]
20840 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };20976 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20977+ // SAFETY: this band marks only the unit rows its own mi rows cover,
20978+ // disjoint from every other band's (see `Shared`).
20979+ #[allow(unsafe_code)]
20980+ let wr = wrote.as_ref().map(|w| unsafe { w.get() });
20841 cdef_band(20981 cdef_band(
20842 r_lo,20982 r_lo,
20843 r_hi,20983 r_hi,
@@ -20856,6 +20996,7 @@ fn cdef_rows(
20856 damping_uv,20996 damping_uv,
20857 (frame_w, frame_h),20997 (frame_w, frame_h),
20858 fctx,20998 fctx,
20999+ wr,
20859 );21000 );
20860 });21001 });
20861 }21002 }
@@ -20876,6 +21017,10 @@ fn apply_cdef(
20876 // -- so it hands them straight in and the copy does not happen. `None`21017 // -- so it hands them straight in and the copy does not happen. `None`
20877 // (every decode) copies as before.21018 // (every decode) copies as before.
20878 src: Option<(&[u16], &[u16], &[u16])>,21019 src: Option<(&[u16], &[u16], &[u16])>,
21020+ // See [`cdef_band`]: `Some` only from the encoder's filter replay, which
21021+ // clears and sizes it (`mi_cols.div_ceil(2) * mi_rows.div_ceil(2)`)
21022+ // before the call.
21023+ mut wrote: Option<&mut [u8]>,
20879 ) {21024 ) {
20880 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.21025 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
20881 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {21026 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
@@ -20917,6 +21062,7 @@ fn apply_cdef(
20917 cdef_rows(21062 cdef_rows(
20918 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,21063 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
20919 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,21064 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
21065+ wrote.as_deref_mut().map(crate::par::Shared::new),
20920 );21066 );
20921 if owned {21067 if owned {
20922 scratch_return(src_y.into_owned());21068 scratch_return(src_y.into_owned());
@@ -23499,6 +23645,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
23499 &neighbours,23645 &neighbours,
23500 (frame_width as usize, frame_height as usize), fctx,23646 (frame_width as usize, frame_height as usize), fctx,
23501 None,23647 None,
23648+ None,
23502 );23649 );
23503 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);23650 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
23504 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);23651 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
@@ -36315,6 +36462,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
36315 &neighbours,36462 &neighbours,
36316 (frame_width as usize, frame_height as usize), fctx,36463 (frame_width as usize, frame_height as usize), fctx,
36317 None,36464 None,
36465+ None,
36318 );36466 );
36319 }36467 }
36320 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);36468 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);