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 {
1974119741 /// rows) -- what [`replay_restoration`] filters, instead of decoding
1974219742 /// the re-coded tile a second time.
1974319743 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>,
1974419759 /// The last deblocked planes and the levels that produced them.
1974519760 /// Deblocking depends on nothing else the search moves, and the search
1974619761 /// fixes the levels before it walks the CDEF strengths, so every
@@ -19830,12 +19845,66 @@ fn capture_filter_replay(
1983019845 true_width,
1983119846 true_height,
1983219847 scratch: Vec::new(),
19848+ work: None,
19849+ wrote: Vec::new(),
19850+ work_cdef: None,
1983319851 final_luma: None,
1983419852 deblocked: None,
1983519853 });
1983619854 });
1983719855 }
1983819856
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+
1983919908 /// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
1984019909 /// own buffer pool: a cleared `Vec` that already has the capacity keeps the
1984119910 /// allocator and the page fault handler out of the filter search.
@@ -19920,13 +19989,54 @@ fn replay_inner(
1992019989 // of them rather than taking their buffers.
1992119990 let mut share = false;
1992219991 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);
1992319994 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+ };
1992420018 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
1992520019 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+ }
1992720033 } else {
1992820034 // The levels moved, so the cached deblocked planes are dead:
1992920035 // 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;
1993020040 if let Some((_, dy, du, dv)) = r.deblocked.take() {
1993120041 r.scratch.push(dy.data.into_owned());
1993220042 r.scratch.push(du.data.into_owned());
@@ -19974,12 +20084,17 @@ fn replay_inner(
1997420084 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec());
1997520085 }
1997620086 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);
1997720091 let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| {
1997820092 (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())
1997920093 });
1998020094 apply_cdef(
1998120095 &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx,
1998220096 pre,
20097+ Some(&mut wrote),
1998320098 );
1998420099 drop(ct);
1998520100 if final_pass.is_some_and(|(_, want)| want) {
@@ -20017,6 +20132,8 @@ fn replay_inner(
2001720132 let (fw, fh) = (r.frame_width, r.frame_height);
2001820133 if fw == r.width && fh == r.height {
2001920134 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
20135+ r.wrote = Vec::new();
20136+ r.work_cdef = None;
2002020137 if share {
2002120138 let picture = Picture {
2002220139 width: r.width,
@@ -20067,13 +20184,14 @@ fn replay_inner(
2006720184 // deblocked planes this candidate's successors reuse, or they go
2006820185 // back to the pool.
2006920186 if share {
20187+ r.wrote = Vec::new();
20188+ r.work_cdef = None;
2007020189 r.deblocked = Some((*loop_filter, y, u, v));
2007120190 } else {
20072- for plane in [y, u, v] {
20073- if r.scratch.len() < 6 {
20074- r.scratch.push(plane.data.into_owned());
20075- }
20076- }
20191+ // lane-av1speed3: kept whole (post-CDEF samples and all) for the
20192+ // next candidate, together with the map of what CDEF wrote.
20193+ r.wrote = wrote;
20194+ r.work = Some((y, u, v));
2007720195 }
2007820196 Some((out, stages))
2007920197 })
@@ -20208,7 +20326,16 @@ fn cdef_band(
2020820326 damping_uv: i32,
2020920327 (frame_w, frame_h): (usize, usize),
2021020328 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]>,
2021120337 ) {
20338+ let unit_cols = skip_grid.mi_cols.div_ceil(2);
2021220339 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
2021320340 if sb_cols == 0 {
2021420341 return 0;
@@ -20304,6 +20431,11 @@ fn cdef_band(
2030420431 let uv_dir = if t_uv != 0 { dir } else { 0 };
2030520432 let enable_primary_uv = t_uv != 0;
2030620433 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+ }
2030720439 if enable_primary_uv || enable_secondary_uv {
2030820440 let (cox, coy) = (ox / 2, oy / 2);
2030920441 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
@@ -20508,6 +20640,7 @@ fn pipe_run(
2050820640 cdef_rows(
2050920641 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
2051020642 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
20643+ None,
2051120644 );
2051220645 }
2051320646 }
@@ -20818,6 +20951,9 @@ fn cdef_rows(
2081820951 (frame_w, frame_h): (usize, usize),
2081920952 r_lo0: usize,
2082020953 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]>>,
2082120957 ) {
2082220958 let mi_rows = skip_grid.mi_rows;
2082320959 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
@@ -20838,6 +20974,10 @@ fn cdef_rows(
2083820974 // disjoint from every other band's (see `Shared`).
2083920975 #[allow(unsafe_code)]
2084020976 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() });
2084120981 cdef_band(
2084220982 r_lo,
2084320983 r_hi,
@@ -20856,6 +20996,7 @@ fn cdef_rows(
2085620996 damping_uv,
2085720997 (frame_w, frame_h),
2085820998 fctx,
20999+ wr,
2085921000 );
2086021001 });
2086121002 }
@@ -20876,6 +21017,10 @@ fn apply_cdef(
2087621017 // -- so it hands them straight in and the copy does not happen. `None`
2087721018 // (every decode) copies as before.
2087821019 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]>,
2087921024 ) {
2088021025 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
2088121026 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
@@ -20917,6 +21062,7 @@ fn apply_cdef(
2091721062 cdef_rows(
2091821063 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
2091921064 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
21065+ wrote.as_deref_mut().map(crate::par::Shared::new),
2092021066 );
2092121067 if owned {
2092221068 scratch_return(src_y.into_owned());
@@ -23499,6 +23645,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2349923645 &neighbours,
2350023646 (frame_width as usize, frame_height as usize), fctx,
2350123647 None,
23648+ None,
2350223649 );
2350323650 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
2350423651 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(
3631536462 &neighbours,
3631636463 (frame_width as usize, frame_height as usize), fctx,
3631736464 None,
36465+ None,
3631836466 );
3631936467 }
3632036468 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);