From 8a4a771a4745f6ba758ee92b871a3dd35d4ef04e 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 12:12:12 +0300 Subject: [PATCH] perf(av1): the filter search's replay now covers cropped frames The encoder scores ~30 deblock/CDEF candidates per frame by replaying the loop filters on one captured reconstruction (`decode::FilterReplay`), but the capture demanded `frame == plane` dimensions -- and no export size meets that: 1080 and 1608 both pad to a superblock row. Every candidate at those sizes fell through to a full re-decode of the frame, which the new per-stage breakdown measures at 57% of a 1080p frame's wall. The capture now also fires on a cropped frame and the replay finishes with the decoder's own cropped return path (crop + wide-margin stash), so it is still exactly the decode it stands in for. 1920x1080, 8 frames, 4x2 tiles, 8 tile threads: 6.75s -> 2.63s (1.19 -> 3.05 fps); filter search 57.2% -> 27.6% of wall. Adds `par::timer`/`EC_AV1_STAGE_TIMES` (off by default: one relaxed atomic load per stage per frame) and `encoder::tests::filter_stage_wall_*`, plus `filter_replay_codes_the_same_stream_as_a_full_decode` at a cropping size. --- crates/ec-av1/src/decode.rs | 91 +++++++++++++++---- crates/ec-av1/src/encode.rs | 9 ++ crates/ec-av1/src/encoder.rs | 135 +++++++++++++++++++++++++++++ crates/ec-av1/src/filter_search.rs | 2 + crates/ec-av1/src/par.rs | 73 ++++++++++++++++ 5 files changed, 293 insertions(+), 17 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index fb589431..7b76ac74 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -19725,6 +19725,10 @@ pub(crate) struct FilterReplay { frame_height: usize, width: usize, height: usize, + /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin + /// stash the cropped return path leaves behind. + true_width: usize, + true_height: usize, /// 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 @@ -19745,6 +19749,17 @@ pub(crate) fn arm_filter_replay() { REPLAY_ARMED.set(true); } +/// Test-only: force every filter candidate through a full decode, so a gate +/// can hold the replay against the decode it stands in for +/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`). +#[cfg(test)] +static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[cfg(test)] +pub(crate) fn set_filter_replay_disabled(off: bool) { + REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed); +} + /// Drop the armed flag and anything captured: the tile it belongs to is done. pub(crate) fn clear_filter_replay() { REPLAY_ARMED.set(false); @@ -19762,6 +19777,8 @@ fn capture_filter_replay( frame_height: usize, width: usize, height: usize, + true_width: usize, + true_height: usize, ) { if !REPLAY_ARMED.replace(false) { return; @@ -19777,6 +19794,8 @@ fn capture_filter_replay( frame_height, width, height, + true_width, + true_height, deblocked: None, }); }); @@ -19791,6 +19810,10 @@ pub(crate) fn replay_filters( cdef: &CdefParams, 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 copy = |p: &PlaneBuf<'_>| PlaneBuf { @@ -19803,6 +19826,7 @@ pub(crate) fn replay_filters( (copy(dy), copy(du), copy(dv)) } else { let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v)); + let _t = crate::par::timer(crate::par::S_DEBLOCK); apply_deblock( &mut y, &mut u, @@ -19816,17 +19840,53 @@ pub(crate) fn replay_filters( r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v))); (y, u, v) }; + let ct = crate::par::timer(crate::par::S_CDEF); apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx); - // The capture only happens on the shape the decoder's own tail - // returns whole (no superres, no loop restoration, no crop), so this - // is that tail. - fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); + drop(ct); + // The capture only happens on the shape whose tail is the two + // filter calls and the crop (no superres, no loop restoration), so + // what is left is that crop -- byte for byte the cropped return path + // of the decode this replaces, wide-margin stash included. + // + // lane-av1fpar: the crop is why this arm exists at all. The capture + // used to demand `frame == plane` dimensions, which no editor size + // meets (1080 and 1608 both pad to a superblock row), so every + // candidate of every frame at those sizes fell through to a full + // re-decode -- 57% of a 1080p frame's wall. + let (fw, fh) = (r.frame_width, r.frame_height); + if fw == r.width && fh == r.height { + fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); + return Some(Picture { + width: r.width, + height: r.height, + y: y.data.into_owned(), + u: u.data.into_owned(), + v: v.data.into_owned(), + }); + } + let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec { + let mut out = Vec::with_capacity(w * h); + for row in 0..h { + out.extend(plane.data[row * plane.width..][..w].iter().copied()); + } + out + }; + let (tw, th) = (r.true_width, r.true_height); + fctx.last_frame_wide_margin.with(|m| { + *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture { + width: tw, + height: th, + y: crop(&y, tw, th), + u: crop(&u, tw.div_ceil(2), th.div_ceil(2)), + v: crop(&v, tw.div_ceil(2), th.div_ceil(2)), + }); + }); Some(Picture { - width: r.width, - height: r.height, - y: y.data.into_owned(), - u: u.data.into_owned(), - v: v.data.into_owned(), + width: fw, + height: fh, + y: crop_owned(y, fw, fh), + u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)), + v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)), }) }) } @@ -23110,8 +23170,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // frame tile per candidate -- capture it once (see [`FilterReplay`]), // on the shape whose tail is the two filter calls and nothing else. if superres(fctx).is_none() - && frame_width as usize == width - && frame_height as usize == height && !(0..3).any(|p| { lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None && lr.loop_restoration_size[p] != 0 @@ -23126,6 +23184,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( frame_height as usize, width, height, + true_width, + true_height, ); } apply_deblock( @@ -35847,12 +35907,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // same coded tile ([`FilterReplay`]). Capture the reconstruction here, // before either filter has touched it -- but only on the shape whose // tail is exactly `apply_deblock` + `apply_cdef` and nothing else. - if !pipelined - && !lr_active - && superres(fctx).is_none() - && frame_width as usize == width - && frame_height as usize == height - { + if !pipelined && !lr_active && superres(fctx).is_none() { capture_filter_replay( &y, &u, @@ -35862,6 +35917,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_height as usize, width, height, + true_width, + true_height, ); } if pipelined { diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 96cc895f..d75f16a0 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3309,6 +3309,7 @@ fn write_tiles(tiles: usize, store: usize, code: F) -> Result<(Vec>, where F: Fn(usize) -> Result<(Vec, Option)> + Sync + Send, { + let _t = crate::par::timer(crate::par::S_TILE_WRITE); type Slot = Option, Option)>>; let threads = crate::par::tile_threads().min(tiles); let mut slots: Vec = Vec::new(); @@ -3364,6 +3365,7 @@ where T: Send, F: Fn(usize, &crate::decode::FrameCtx) -> Result + Sync, { + let _t = crate::par::timer(crate::par::S_TILE_SEARCH); let threads = crate::par::tile_threads().min(tiles); if threads <= 1 { return (0..tiles).map(|index| job(index, fctx)).collect(); @@ -4144,6 +4146,7 @@ fn pick_and_apply_filters( // preset search reads comes off the REPLAYED picture, which is the same // picture a decode produces -- that is what the replay is pinned on. crate::decode::clear_filter_replay(); + let ft = crate::par::timer(crate::par::S_FILTER); let search_result = crate::filter_search::pick_filters( |lf, cdef| { if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { @@ -4159,6 +4162,7 @@ fn pick_and_apply_filters( (sb_cols, sb_rows), lambda, ); + drop(ft); crate::decode::clear_filter_replay(); let (lf, cdef, idx_grid, picture) = search_result?; header.loop_filter = lf; @@ -4181,12 +4185,14 @@ fn pick_and_apply_filters( fctx.capture_stages.set(lr_on); let mut filtered = if idx_grid.is_empty() { if lr_on { + let _t = crate::par::timer(crate::par::S_CAPTURE); decode(&lf, &cdef, &hdr, tiles, &none_lr)? } else { picture } } else { let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?; + let _t = crate::par::timer(crate::par::S_CAPTURE); let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?; *tiles = coded; picture @@ -4200,6 +4206,7 @@ fn pick_and_apply_filters( ..LoopRestorationParams::default() }; want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; + let lrt = crate::par::timer(crate::par::S_LR); let units = match crate::decode::take_filter_stages(fctx) { Some(stages) => crate::filter_search::pick_restoration( &stages, @@ -4216,8 +4223,10 @@ fn pick_and_apply_filters( // rather than paying ~1 bit per 64x64 for a tile full of // `restore_wiener = 0` symbols (the BD gate saw exactly that on the // clip whose units never take a filter). + drop(lrt); 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)?; *tiles = coded; lr = want; diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index b31d2980..d331570b 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -1862,6 +1862,141 @@ mod tests { tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]); } + /// lane-av1fpar: the filter search scores its ~30 candidates by replaying + /// the loop filters on one captured reconstruction instead of decoding + /// the coded tile again per candidate. The replay must be that decode, + /// byte for byte -- including at a size that CROPS (1080 and 1608 both + /// pad to a superblock row, i.e. every export size the editor uses), + /// which is the arm this lane opened. + #[test] + fn filter_replay_codes_the_same_stream_as_a_full_decode() { + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let run = |width: usize, height: usize, off: bool| { + let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); + crate::decode::set_filter_replay_disabled(off); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 2, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + for picture in &sources { + stream.extend_from_slice(&enc.encode(picture).unwrap().data); + } + crate::decode::set_filter_replay_disabled(false); + stream + }; + // 320x160 crops (the coding surface is 320x192, one superblock row + // taller); 320x192 is a whole number of superblocks, the shape the + // replay already covered. + for (width, height) in [(320usize, 160usize), (320, 192)] { + let replayed = run(width, height, false); + let decoded = run(width, height, true); + assert_eq!( + replayed, + decoded, + "{width}x{height}: the filter replay is not the decode it stands in for \ + ({} bytes replayed, {} decoded)", + replayed.len(), + decoded.len(), + ); + } + } + + /// lane-av1fpar: where a frame's wall actually goes, stage by stage -- + /// the per-tile search, the tile write, the frame-level filter search + /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture + /// decode the loop-restoration search rides on, and that search itself. + /// Measurement, not a pass/fail gate. + #[test] + #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] + fn filter_stage_wall_1080p() { + filter_stage_wall(1920, 1080, 8, (2, 1), &[8]); + } + + #[test] + #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] + fn filter_stage_wall_4k() { + filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]); + } + + fn filter_stage_wall( + width: usize, + height: usize, + frames: usize, + (cols_log2, rows_log2): (u32, u32), + threads: &[usize], + ) { + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let Some(sources) = h264_clip_frames(width, height, frames) else { + eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg"); + return; + }; + crate::par::set_stage_times(true); + for &t in threads { + crate::par::set_tile_threads(t); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: frames, + colour: Colour::Bt709Limited, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let _ = crate::par::take_stage_ns(); + let start = std::time::Instant::now(); + for picture in &sources { + assert!(!enc.encode(picture).unwrap().data.is_empty()); + } + let wall = start.elapsed().as_secs_f64(); + let ns = crate::par::take_stage_ns(); + let ms = |i: usize| ns[i] as f64 / 1e6; + eprintln!( + "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \ + {wall:.2}s wall, {:.2} fps", + 1 << cols_log2, + 1 << rows_log2, + frames as f64 / wall, + ); + eprintln!("| stage | ms | ms/frame | % of wall |"); + for (i, name) in crate::par::STAGES.iter().enumerate() { + eprintln!( + "| {name} | {:.0} | {:.1} | {:.1}% |", + ms(i), + ms(i) / frames as f64, + 100.0 * ms(i) / (wall * 1e3), + ); + } + // Top-level stages only (the deblock/CDEF/SSE rows are inside + // the filter-search total); the rest is per-frame setup, the + // source conversion and the splice. + let top: f64 = [ + crate::par::S_TILE_SEARCH, + crate::par::S_TILE_WRITE, + crate::par::S_FILTER, + crate::par::S_CAPTURE, + crate::par::S_LR, + ] + .iter() + .map(|&i| ms(i)) + .sum(); + eprintln!( + "accounted {:.1}% of wall; outside the tile search {:.1}%", + 100.0 * top / (wall * 1e3), + 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)), + ); + } + crate::par::set_stage_times(false); + crate::par::set_tile_threads(1); + } + fn tile_search_wall( width: usize, height: usize, diff --git a/crates/ec-av1/src/filter_search.rs b/crates/ec-av1/src/filter_search.rs index 40372902..b9403a17 100644 --- a/crates/ec-av1/src/filter_search.rs +++ b/crates/ec-av1/src/filter_search.rs @@ -196,6 +196,7 @@ pub(crate) fn pick_filters( (cand.lf.0, cand.y), (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv), ); + let sst = crate::par::timer(crate::par::S_SSE); if !st.luma.iter().any(|(k, _)| *k == lkey) { let mut units = vec![0u64; nsb]; let sse = @@ -208,6 +209,7 @@ pub(crate) fn pick_filters( + unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut units); st.chroma.push((ckey, (sse, units))); } + drop(sst); let (sse_y, sse_uv, sse64) = { let l = &st.luma.iter().find(|(k, _)| *k == lkey).expect("just inserted").1; let c = &st.chroma.iter().find(|(k, _)| *k == ckey).expect("just inserted").1; diff --git a/crates/ec-av1/src/par.rs b/crates/ec-av1/src/par.rs index 3ad04f74..db791017 100644 --- a/crates/ec-av1/src/par.rs +++ b/crates/ec-av1/src/par.rs @@ -459,3 +459,76 @@ impl Drop for Batch<'_> { } } } + +// --- lane-av1fpar: encoder per-stage wall breakdown ----------------------- +// +// Amdahl on the per-tile search (lane-av1tsearch) put ~43% of an inter frame +// OUTSIDE the tile search without saying what it was. These counters name it: +// one accumulator per serial stage of `encode_*_frame`, added to on whatever +// thread runs the stage and printed by `encoder::tests::filter_stage_wall_*`. +// Off (the default) each `stage` call is one relaxed atomic load. + +/// The stages [`stage`] accumulates, in the order a frame runs them. +pub(crate) const STAGES: [&str; 8] = [ + "tile search", + "tile write", + "filter: deblock replay", + "filter: cdef replay", + "filter: sse", + "filter search (total)", + "capture decode", + "lr search", +]; +pub(crate) const S_TILE_SEARCH: usize = 0; +pub(crate) const S_TILE_WRITE: usize = 1; +pub(crate) const S_DEBLOCK: usize = 2; +pub(crate) const S_CDEF: usize = 3; +pub(crate) const S_SSE: usize = 4; +pub(crate) const S_FILTER: usize = 5; +pub(crate) const S_CAPTURE: usize = 6; +pub(crate) const S_LR: usize = 7; + +static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] = + [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()]; +/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES`, or +/// [`set_stage_times`] from a gate (the env snapshot is process-constant). +static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn stage_times() -> bool { + match STAGE_ON.load(std::sync::atomic::Ordering::Relaxed) { + 0 => { + let on = 1 + usize::from(crate::envflags::is_set("EC_AV1_STAGE_TIMES")); + STAGE_ON.store(on, std::sync::atomic::Ordering::Relaxed); + on == 2 + } + n => n == 2, + } +} + +/// Test-only override of [`stage_times`]; process-global. +#[cfg(test)] +pub(crate) fn set_stage_times(on: bool) { + STAGE_ON.store(1 + usize::from(on), std::sync::atomic::Ordering::Relaxed); +} + +/// A live stage measurement: added to stage `i` when it drops. `None` when +/// the breakdown is off, so a call site is `let _t = par::timer(S_X);`. +pub(crate) struct Timer(usize, std::time::Instant); + +#[inline] +pub(crate) fn timer(i: usize) -> Option { + stage_times().then(|| Timer(i, std::time::Instant::now())) +} + +impl Drop for Timer { + fn drop(&mut self) { + STAGE_NS[self.0] + .fetch_add(self.1.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Takes and clears the breakdown, in [`STAGES`] order. +#[cfg(test)] +pub(crate) fn take_stage_ns() -> [u64; STAGES.len()] { + std::array::from_fn(|i| STAGE_NS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +}