From 34dfd1e2d87598ae4c7560112d51d0764b3a7c4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 23:35:22 +0300 Subject: [PATCH] perf(av1): the loop-restoration stage replays the decoder's own kernel instead of decoding the re-coded tile The chosen Wiener units used to be realised by DECODING the re-coded tile (5.6% of a 4K frame), purely to reach the restored reference frame. Loop restoration reads nothing of that tile beyond the per-unit filters the stage just chose, so the final replay now keeps its post-CDEF luma plus the TRUE post-deblock stripe-border rows (plane_snapshot, exactly the rows restoration::lr_src_row substitutes) and runs apply_loop_restoration_plane on them. Chroma restores nothing, so only luma moves; the wide-margin stash's luma is refreshed in place. Pinned by encoder::tests::filter_replay_final_matches_the_capture_decode, which now also decodes the re-coded tile and asserts picture, chroma and wide-margin luma identical (fired on 8 frames of the gate clip). --- crates/ec-av1/src/decode.rs | 90 +++++++++++++++++++++++++++++++++++++ crates/ec-av1/src/encode.rs | 45 ++++++++++++++++++- 2 files changed, 133 insertions(+), 2 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 3bb895c0..ba5f92d7 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -19735,6 +19735,12 @@ pub(crate) struct FilterReplay { /// 1080p frame's wall in allocation, not in filtering. Recycled here /// instead; the pool holds at most the six planes one candidate has live. scratch: Vec>, + /// lane-av1cap2: the final replay's post-CDEF luma plane and the TRUE + /// post-deblock rows loop restoration substitutes at its stripe + /// borders ([`plane_snapshot`], exactly `restoration::lr_src_row`'s + /// rows) -- what [`replay_restoration`] filters, instead of decoding + /// the re-coded tile a second time. + final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>, /// The last deblocked planes and the levels that produced them. /// Deblocking depends on nothing else the search moves, and the search /// fixes the levels before it walks the CDEF strengths, so every @@ -19824,6 +19830,7 @@ fn capture_filter_replay( true_width, true_height, scratch: Vec::new(), + final_luma: None, deblocked: None, }); }); @@ -19957,6 +19964,15 @@ fn replay_inner( pre, ); drop(ct); + if final_pass.is_some_and(|(_, want)| want) { + // The loop-restoration search runs on the stages above (where + // post-CDEF stands in for post-deblock, as the capture decode + // had it); the FILTER this frame ends up applying reads the + // real post-deblock rows, which is what the decoder does. + let snapshot = r.deblocked.as_ref().map(|(_, dy, ..)| plane_snapshot(dy, 0)); + let scratch = &mut r.scratch; + r.final_luma = snapshot.map(|d| (pooled(&y, scratch), d)); + } let stages = final_pass.and_then(|(_, want)| { want.then(|| FilterStages { deblocked: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()], @@ -20022,6 +20038,80 @@ fn replay_inner( }) } +/// lane-av1cap2: the loop-restoration half of the final replay. Once the +/// units are chosen the tile is coded a second time to carry them, and that +/// re-coded tile used to be DECODED to reach the restored reference frame +/// (5.6% of a 4K frame's encode). Loop restoration reads nothing of that +/// tile but the per-unit filters the encoder just picked: it is the +/// decoder's own [`crate::restoration::apply_loop_restoration_plane`] on +/// the post-CDEF plane the final replay produced, with the TRUE +/// post-deblock stripe-border rows -- the same call the decoder's +/// `apply_loop_restoration` makes, on the same input. Only luma moves: the +/// encoder never writes a chroma restoration type other than +/// `RESTORE_NONE`, whose kernel hands its input straight back. +/// +/// Returns the cropped luma plane and refreshes the wide-margin stash's own +/// luma (restoration writes strictly inside `frame_width x frame_height`, +/// so the margin columns past it stand). `None` when nothing was captured +/// -- the caller then decodes for real. +pub(crate) fn replay_restoration( + lr: &LoopRestorationParams, + units: &[Option], + fctx: &FrameCtx, +) -> Option> { + #[cfg(test)] + if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) { + return None; + } + REPLAY.with_borrow_mut(|slot| { + let r = slot.as_mut()?; + let (cdefed, deblocked) = r.final_luma.as_ref()?; + let (fw, fh) = (r.frame_width, r.frame_height); + let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32); + let (horz, vert) = (grid.horz_units[0], grid.vert_units[0]); + if horz == 0 || units.len() != horz * vert { + return None; + } + for (i, filter) in units.iter().enumerate() { + if let Some(info) = filter { + grid.set(0, i / horz, i % horz, crate::restoration::UnitFilter::Wiener(*info)); + } + } + let stride = cdefed.width; + let mut out = scratch_empty(); + crate::restoration::apply_loop_restoration_plane( + &cdefed.data, + &deblocked.data, + stride, + fw, + fh, + 0, + lr.frame_restoration_type[0], + lr.loop_restoration_size[0], + &grid, + 0, + &mut out, + None, + fctx, + ); + fctx.last_frame_wide_margin.with(|m| { + if let Some(p) = m.borrow_mut().as_mut() { + let tw = p.width; + for row in 0..p.height.min(fh) { + let n = tw.min(fw); + p.y[row * tw..][..n].copy_from_slice(&out[row * stride..][..n]); + } + } + }); + let mut y = Vec::with_capacity(fw * fh); + for row in 0..fh { + y.extend(out[row * stride..][..fw].iter().copied()); + } + scratch_return(out); + Some(y) + }) +} + /// The output crop, taking the plane by value: a frame whose width is /// already superblock-aligned (only its height is padded) has a padded /// buffer whose stride equals the visible width, so the crop is a pure diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 15cd1bf5..761d6fe4 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -6135,7 +6135,9 @@ fn pick_and_apply_filters( _ => panic!("one path captured filter stages and the other did not"), } } - crate::decode::clear_filter_replay(); + // lane-av1cap2: the capture stays live past the restoration search -- + // `crate::decode::replay_restoration` filters the same post-CDEF plane + // rather than decoding the re-coded tile. Cleared at the end instead. let mut lr = LoopRestorationParams::default(); if lr_on { let mut want = LoopRestorationParams { @@ -6165,11 +6167,50 @@ fn pick_and_apply_filters( if units.iter().any(Option::is_some) { let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; let _t = crate::par::timer(crate::par::S_CAPTURE); - filtered = decode(&lf, &cdef, &hdr, &coded, &want)?; + // lane-av1cap2: that re-coded tile used to be DECODED here to + // reach the restored reference frame -- 5.6% of a 4K frame, + // for a filter that reads nothing of the tile but the per-unit + // Wiener filters this stage just chose. Run the decoder's own + // restoration kernel on the replay's post-CDEF plane instead + // (`crate::decode::replay_restoration`), with the real + // post-deblock stripe borders. + match crate::decode::replay_restoration(&want, &units, fctx) { + Some(y) => { + #[cfg(test)] + let margin = fctx + .last_frame_wide_margin + .with(|m| m.borrow().as_ref().map(|p| p.y.clone())); + #[cfg(test)] + if crate::decode::verify_final_replay() { + let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?; + assert!( + (want_pic.width, want_pic.height) == (filtered.width, filtered.height) + && want_pic.u == filtered.u + && want_pic.v == filtered.v, + "the restoration replay moved a chroma plane or the picture size", + ); + assert!( + want_pic.y == y, + "the restoration replay is not the decode of the re-coded tile", + ); + assert!( + fctx.last_frame_wide_margin + .with(|m| m.borrow().as_ref().map(|p| p.y.clone())) + == margin, + "the restoration replay's wide-margin luma is not the decode's", + ); + } + filtered.y = y; + } + // Nothing captured: the winner came out of a full decode, + // so this one does too. + None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?, + } *tiles = coded; lr = want; } } + crate::decode::clear_filter_replay(); header.loop_restoration = lr; let dec_cw = filtered.width.div_ceil(2); let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));