forge
Explore
Log in

Don't you dare go Hollow

The filter search's replay now covers cropped frames

Browse files at this commit

8a4a771a4745f6ba758ee92b871a3dd35d4ef04eAhmet Kaan GümüşParent: fe25c8d
  • perf
    • the filter search's replay now covers cropped frames
Show full message
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.rsmodified+74 -17
@@ -19725,6 +19725,10 @@ pub(crate) struct FilterReplay {
1972519725 frame_height: usize,
1972619726 width: usize,
1972719727 height: usize,
19728+ /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin
19729+ /// stash the cropped return path leaves behind.
19730+ true_width: usize,
19731+ true_height: usize,
1972819732 /// The last deblocked planes and the levels that produced them.
1972919733 /// Deblocking depends on nothing else the search moves, and the search
1973019734 /// fixes the levels before it walks the CDEF strengths, so every
@@ -19745,6 +19749,17 @@ pub(crate) fn arm_filter_replay() {
1974519749 REPLAY_ARMED.set(true);
1974619750 }
1974719751
19752+/// Test-only: force every filter candidate through a full decode, so a gate
19753+/// can hold the replay against the decode it stands in for
19754+/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
19755+#[cfg(test)]
19756+static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
19757+
19758+#[cfg(test)]
19759+pub(crate) fn set_filter_replay_disabled(off: bool) {
19760+ REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
19761+}
19762+
1974819763 /// Drop the armed flag and anything captured: the tile it belongs to is done.
1974919764 pub(crate) fn clear_filter_replay() {
1975019765 REPLAY_ARMED.set(false);
@@ -19762,6 +19777,8 @@ fn capture_filter_replay(
1976219777 frame_height: usize,
1976319778 width: usize,
1976419779 height: usize,
19780+ true_width: usize,
19781+ true_height: usize,
1976519782 ) {
1976619783 if !REPLAY_ARMED.replace(false) {
1976719784 return;
@@ -19777,6 +19794,8 @@ fn capture_filter_replay(
1977719794 frame_height,
1977819795 width,
1977919796 height,
19797+ true_width,
19798+ true_height,
1978019799 deblocked: None,
1978119800 });
1978219801 });
@@ -19791,6 +19810,10 @@ pub(crate) fn replay_filters(
1979119810 cdef: &CdefParams,
1979219811 fctx: &FrameCtx,
1979319812 ) -> Option<Picture> {
19813+ #[cfg(test)]
19814+ if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
19815+ return None;
19816+ }
1979419817 REPLAY.with_borrow_mut(|slot| {
1979519818 let r = slot.as_mut()?;
1979619819 let copy = |p: &PlaneBuf<'_>| PlaneBuf {
@@ -19803,6 +19826,7 @@ pub(crate) fn replay_filters(
1980319826 (copy(dy), copy(du), copy(dv))
1980419827 } else {
1980519828 let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));
19829+ let _t = crate::par::timer(crate::par::S_DEBLOCK);
1980619830 apply_deblock(
1980719831 &mut y,
1980819832 &mut u,
@@ -19816,17 +19840,53 @@ pub(crate) fn replay_filters(
1981619840 r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v)));
1981719841 (y, u, v)
1981819842 };
19843+ let ct = crate::par::timer(crate::par::S_CDEF);
1981919844 apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);
19820- // The capture only happens on the shape the decoder's own tail
19821- // returns whole (no superres, no loop restoration, no crop), so this
19822- // is that tail.
19823- fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
19845+ drop(ct);
19846+ // The capture only happens on the shape whose tail is the two
19847+ // filter calls and the crop (no superres, no loop restoration), so
19848+ // what is left is that crop -- byte for byte the cropped return path
19849+ // of the decode this replaces, wide-margin stash included.
19850+ //
19851+ // lane-av1fpar: the crop is why this arm exists at all. The capture
19852+ // used to demand `frame == plane` dimensions, which no editor size
19853+ // meets (1080 and 1608 both pad to a superblock row), so every
19854+ // candidate of every frame at those sizes fell through to a full
19855+ // re-decode -- 57% of a 1080p frame's wall.
19856+ let (fw, fh) = (r.frame_width, r.frame_height);
19857+ if fw == r.width && fh == r.height {
19858+ fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
19859+ return Some(Picture {
19860+ width: r.width,
19861+ height: r.height,
19862+ y: y.data.into_owned(),
19863+ u: u.data.into_owned(),
19864+ v: v.data.into_owned(),
19865+ });
19866+ }
19867+ let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
19868+ let mut out = Vec::with_capacity(w * h);
19869+ for row in 0..h {
19870+ out.extend(plane.data[row * plane.width..][..w].iter().copied());
19871+ }
19872+ out
19873+ };
19874+ let (tw, th) = (r.true_width, r.true_height);
19875+ fctx.last_frame_wide_margin.with(|m| {
19876+ *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture {
19877+ width: tw,
19878+ height: th,
19879+ y: crop(&y, tw, th),
19880+ u: crop(&u, tw.div_ceil(2), th.div_ceil(2)),
19881+ v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
19882+ });
19883+ });
1982419884 Some(Picture {
19825- width: r.width,
19826- height: r.height,
19827- y: y.data.into_owned(),
19828- u: u.data.into_owned(),
19829- v: v.data.into_owned(),
19885+ width: fw,
19886+ height: fh,
19887+ y: crop_owned(y, fw, fh),
19888+ u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)),
19889+ v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)),
1983019890 })
1983119891 })
1983219892 }
@@ -23110,8 +23170,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2311023170 // frame tile per candidate -- capture it once (see [`FilterReplay`]),
2311123171 // on the shape whose tail is the two filter calls and nothing else.
2311223172 if superres(fctx).is_none()
23113- && frame_width as usize == width
23114- && frame_height as usize == height
2311523173 && !(0..3).any(|p| {
2311623174 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
2311723175 && lr.loop_restoration_size[p] != 0
@@ -23126,6 +23184,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2312623184 frame_height as usize,
2312723185 width,
2312823186 height,
23187+ true_width,
23188+ true_height,
2312923189 );
2313023190 }
2313123191 apply_deblock(
@@ -35847,12 +35907,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3584735907 // same coded tile ([`FilterReplay`]). Capture the reconstruction here,
3584835908 // before either filter has touched it -- but only on the shape whose
3584935909 // tail is exactly `apply_deblock` + `apply_cdef` and nothing else.
35850- if !pipelined
35851- && !lr_active
35852- && superres(fctx).is_none()
35853- && frame_width as usize == width
35854- && frame_height as usize == height
35855- {
35910+ if !pipelined && !lr_active && superres(fctx).is_none() {
3585635911 capture_filter_replay(
3585735912 &y,
3585835913 &u,
@@ -35862,6 +35917,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3586235917 frame_height as usize,
3586335918 width,
3586435919 height,
35920+ true_width,
35921+ true_height,
3586535922 );
3586635923 }
3586735924 if pipelined {
crates/ec-av1/src/encode.rsmodified+9 -0
@@ -3309,6 +3309,7 @@ fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>,
33093309 where
33103310 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
33113311 {
3312+ let _t = crate::par::timer(crate::par::S_TILE_WRITE);
33123313 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
33133314 let threads = crate::par::tile_threads().min(tiles);
33143315 let mut slots: Vec<Slot> = Vec::new();
@@ -3364,6 +3365,7 @@ where
33643365 T: Send,
33653366 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
33663367 {
3368+ let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
33673369 let threads = crate::par::tile_threads().min(tiles);
33683370 if threads <= 1 {
33693371 return (0..tiles).map(|index| job(index, fctx)).collect();
@@ -4144,6 +4146,7 @@ fn pick_and_apply_filters(
41444146 // preset search reads comes off the REPLAYED picture, which is the same
41454147 // picture a decode produces -- that is what the replay is pinned on.
41464148 crate::decode::clear_filter_replay();
4149+ let ft = crate::par::timer(crate::par::S_FILTER);
41474150 let search_result = crate::filter_search::pick_filters(
41484151 |lf, cdef| {
41494152 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
@@ -4159,6 +4162,7 @@ fn pick_and_apply_filters(
41594162 (sb_cols, sb_rows),
41604163 lambda,
41614164 );
4165+ drop(ft);
41624166 crate::decode::clear_filter_replay();
41634167 let (lf, cdef, idx_grid, picture) = search_result?;
41644168 header.loop_filter = lf;
@@ -4181,12 +4185,14 @@ fn pick_and_apply_filters(
41814185 fctx.capture_stages.set(lr_on);
41824186 let mut filtered = if idx_grid.is_empty() {
41834187 if lr_on {
4188+ let _t = crate::par::timer(crate::par::S_CAPTURE);
41844189 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
41854190 } else {
41864191 picture
41874192 }
41884193 } else {
41894194 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
4195+ let _t = crate::par::timer(crate::par::S_CAPTURE);
41904196 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
41914197 *tiles = coded;
41924198 picture
@@ -4200,6 +4206,7 @@ fn pick_and_apply_filters(
42004206 ..LoopRestorationParams::default()
42014207 };
42024208 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
4209+ let lrt = crate::par::timer(crate::par::S_LR);
42034210 let units = match crate::decode::take_filter_stages(fctx) {
42044211 Some(stages) => crate::filter_search::pick_restoration(
42054212 &stages,
@@ -4216,8 +4223,10 @@ fn pick_and_apply_filters(
42164223 // rather than paying ~1 bit per 64x64 for a tile full of
42174224 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
42184225 // clip whose units never take a filter).
4226+ drop(lrt);
42194227 if units.iter().any(Option::is_some) {
42204228 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
4229+ let _t = crate::par::timer(crate::par::S_CAPTURE);
42214230 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
42224231 *tiles = coded;
42234232 lr = want;
crates/ec-av1/src/encoder.rsmodified+135 -0
@@ -1862,6 +1862,141 @@ mod tests {
18621862 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
18631863 }
18641864
1865+ /// lane-av1fpar: the filter search scores its ~30 candidates by replaying
1866+ /// the loop filters on one captured reconstruction instead of decoding
1867+ /// the coded tile again per candidate. The replay must be that decode,
1868+ /// byte for byte -- including at a size that CROPS (1080 and 1608 both
1869+ /// pad to a superblock row, i.e. every export size the editor uses),
1870+ /// which is the arm this lane opened.
1871+ #[test]
1872+ fn filter_replay_codes_the_same_stream_as_a_full_decode() {
1873+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1874+ let run = |width: usize, height: usize, off: bool| {
1875+ let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1876+ crate::decode::set_filter_replay_disabled(off);
1877+ let config = EncoderConfig {
1878+ width,
1879+ height,
1880+ base_q_idx: 120,
1881+ gop: 2,
1882+ colour: Colour::Bt709Limited,
1883+ tile_cols_log2: 0,
1884+ tile_rows_log2: 0,
1885+ };
1886+ let mut enc = Av1Encoder::new(config).unwrap();
1887+ let mut stream = Vec::new();
1888+ for picture in &sources {
1889+ stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1890+ }
1891+ crate::decode::set_filter_replay_disabled(false);
1892+ stream
1893+ };
1894+ // 320x160 crops (the coding surface is 320x192, one superblock row
1895+ // taller); 320x192 is a whole number of superblocks, the shape the
1896+ // replay already covered.
1897+ for (width, height) in [(320usize, 160usize), (320, 192)] {
1898+ let replayed = run(width, height, false);
1899+ let decoded = run(width, height, true);
1900+ assert_eq!(
1901+ replayed,
1902+ decoded,
1903+ "{width}x{height}: the filter replay is not the decode it stands in for \
1904+ ({} bytes replayed, {} decoded)",
1905+ replayed.len(),
1906+ decoded.len(),
1907+ );
1908+ }
1909+ }
1910+
1911+ /// lane-av1fpar: where a frame's wall actually goes, stage by stage --
1912+ /// the per-tile search, the tile write, the frame-level filter search
1913+ /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture
1914+ /// decode the loop-restoration search rides on, and that search itself.
1915+ /// Measurement, not a pass/fail gate.
1916+ #[test]
1917+ #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1918+ fn filter_stage_wall_1080p() {
1919+ filter_stage_wall(1920, 1080, 8, (2, 1), &[8]);
1920+ }
1921+
1922+ #[test]
1923+ #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1924+ fn filter_stage_wall_4k() {
1925+ filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]);
1926+ }
1927+
1928+ fn filter_stage_wall(
1929+ width: usize,
1930+ height: usize,
1931+ frames: usize,
1932+ (cols_log2, rows_log2): (u32, u32),
1933+ threads: &[usize],
1934+ ) {
1935+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1936+ let Some(sources) = h264_clip_frames(width, height, frames) else {
1937+ eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg");
1938+ return;
1939+ };
1940+ crate::par::set_stage_times(true);
1941+ for &t in threads {
1942+ crate::par::set_tile_threads(t);
1943+ let config = EncoderConfig {
1944+ width,
1945+ height,
1946+ base_q_idx: 120,
1947+ gop: frames,
1948+ colour: Colour::Bt709Limited,
1949+ tile_cols_log2: cols_log2,
1950+ tile_rows_log2: rows_log2,
1951+ };
1952+ let mut enc = Av1Encoder::new(config).unwrap();
1953+ let _ = crate::par::take_stage_ns();
1954+ let start = std::time::Instant::now();
1955+ for picture in &sources {
1956+ assert!(!enc.encode(picture).unwrap().data.is_empty());
1957+ }
1958+ let wall = start.elapsed().as_secs_f64();
1959+ let ns = crate::par::take_stage_ns();
1960+ let ms = |i: usize| ns[i] as f64 / 1e6;
1961+ eprintln!(
1962+ "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \
1963+ {wall:.2}s wall, {:.2} fps",
1964+ 1 << cols_log2,
1965+ 1 << rows_log2,
1966+ frames as f64 / wall,
1967+ );
1968+ eprintln!("| stage | ms | ms/frame | % of wall |");
1969+ for (i, name) in crate::par::STAGES.iter().enumerate() {
1970+ eprintln!(
1971+ "| {name} | {:.0} | {:.1} | {:.1}% |",
1972+ ms(i),
1973+ ms(i) / frames as f64,
1974+ 100.0 * ms(i) / (wall * 1e3),
1975+ );
1976+ }
1977+ // Top-level stages only (the deblock/CDEF/SSE rows are inside
1978+ // the filter-search total); the rest is per-frame setup, the
1979+ // source conversion and the splice.
1980+ let top: f64 = [
1981+ crate::par::S_TILE_SEARCH,
1982+ crate::par::S_TILE_WRITE,
1983+ crate::par::S_FILTER,
1984+ crate::par::S_CAPTURE,
1985+ crate::par::S_LR,
1986+ ]
1987+ .iter()
1988+ .map(|&i| ms(i))
1989+ .sum();
1990+ eprintln!(
1991+ "accounted {:.1}% of wall; outside the tile search {:.1}%",
1992+ 100.0 * top / (wall * 1e3),
1993+ 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)),
1994+ );
1995+ }
1996+ crate::par::set_stage_times(false);
1997+ crate::par::set_tile_threads(1);
1998+ }
1999+
18652000 fn tile_search_wall(
18662001 width: usize,
18672002 height: usize,
crates/ec-av1/src/filter_search.rsmodified+2 -0
@@ -196,6 +196,7 @@ pub(crate) fn pick_filters(
196196 (cand.lf.0, cand.y),
197197 (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv),
198198 );
199+ let sst = crate::par::timer(crate::par::S_SSE);
199200 if !st.luma.iter().any(|(k, _)| *k == lkey) {
200201 let mut units = vec![0u64; nsb];
201202 let sse =
@@ -208,6 +209,7 @@ pub(crate) fn pick_filters(
208209 + unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut units);
209210 st.chroma.push((ckey, (sse, units)));
210211 }
212+ drop(sst);
211213 let (sse_y, sse_uv, sse64) = {
212214 let l = &st.luma.iter().find(|(k, _)| *k == lkey).expect("just inserted").1;
213215 let c = &st.chroma.iter().find(|(k, _)| *k == ckey).expect("just inserted").1;
crates/ec-av1/src/par.rsmodified+73 -0
@@ -459,3 +459,76 @@ impl Drop for Batch<'_> {
459459 }
460460 }
461461 }
462+
463+// --- lane-av1fpar: encoder per-stage wall breakdown -----------------------
464+//
465+// Amdahl on the per-tile search (lane-av1tsearch) put ~43% of an inter frame
466+// OUTSIDE the tile search without saying what it was. These counters name it:
467+// one accumulator per serial stage of `encode_*_frame`, added to on whatever
468+// thread runs the stage and printed by `encoder::tests::filter_stage_wall_*`.
469+// Off (the default) each `stage` call is one relaxed atomic load.
470+
471+/// The stages [`stage`] accumulates, in the order a frame runs them.
472+pub(crate) const STAGES: [&str; 8] = [
473+ "tile search",
474+ "tile write",
475+ "filter: deblock replay",
476+ "filter: cdef replay",
477+ "filter: sse",
478+ "filter search (total)",
479+ "capture decode",
480+ "lr search",
481+];
482+pub(crate) const S_TILE_SEARCH: usize = 0;
483+pub(crate) const S_TILE_WRITE: usize = 1;
484+pub(crate) const S_DEBLOCK: usize = 2;
485+pub(crate) const S_CDEF: usize = 3;
486+pub(crate) const S_SSE: usize = 4;
487+pub(crate) const S_FILTER: usize = 5;
488+pub(crate) const S_CAPTURE: usize = 6;
489+pub(crate) const S_LR: usize = 7;
490+
491+static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] =
492+ [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];
493+/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES`, or
494+/// [`set_stage_times`] from a gate (the env snapshot is process-constant).
495+static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
496+
497+fn stage_times() -> bool {
498+ match STAGE_ON.load(std::sync::atomic::Ordering::Relaxed) {
499+ 0 => {
500+ let on = 1 + usize::from(crate::envflags::is_set("EC_AV1_STAGE_TIMES"));
501+ STAGE_ON.store(on, std::sync::atomic::Ordering::Relaxed);
502+ on == 2
503+ }
504+ n => n == 2,
505+ }
506+}
507+
508+/// Test-only override of [`stage_times`]; process-global.
509+#[cfg(test)]
510+pub(crate) fn set_stage_times(on: bool) {
511+ STAGE_ON.store(1 + usize::from(on), std::sync::atomic::Ordering::Relaxed);
512+}
513+
514+/// A live stage measurement: added to stage `i` when it drops. `None` when
515+/// the breakdown is off, so a call site is `let _t = par::timer(S_X);`.
516+pub(crate) struct Timer(usize, std::time::Instant);
517+
518+#[inline]
519+pub(crate) fn timer(i: usize) -> Option<Timer> {
520+ stage_times().then(|| Timer(i, std::time::Instant::now()))
521+}
522+
523+impl Drop for Timer {
524+ fn drop(&mut self) {
525+ STAGE_NS[self.0]
526+ .fetch_add(self.1.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
527+ }
528+}
529+
530+/// Takes and clears the breakdown, in [`STAGES`] order.
531+#[cfg(test)]
532+pub(crate) fn take_stage_ns() -> [u64; STAGES.len()] {
533+ std::array::from_fn(|i| STAGE_NS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
534+}