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 {
19725 frame_height: usize,19725 frame_height: usize,
19726 width: usize,19726 width: usize,
19727 height: usize,19727 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,
19728 /// The last deblocked planes and the levels that produced them.19732 /// The last deblocked planes and the levels that produced them.
19729 /// Deblocking depends on nothing else the search moves, and the search19733 /// Deblocking depends on nothing else the search moves, and the search
19730 /// fixes the levels before it walks the CDEF strengths, so every19734 /// fixes the levels before it walks the CDEF strengths, so every
@@ -19745,6 +19749,17 @@ pub(crate) fn arm_filter_replay() {
19745 REPLAY_ARMED.set(true);19749 REPLAY_ARMED.set(true);
19746 }19750 }
19747 19751
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+
19748 /// Drop the armed flag and anything captured: the tile it belongs to is done.19763 /// Drop the armed flag and anything captured: the tile it belongs to is done.
19749 pub(crate) fn clear_filter_replay() {19764 pub(crate) fn clear_filter_replay() {
19750 REPLAY_ARMED.set(false);19765 REPLAY_ARMED.set(false);
@@ -19762,6 +19777,8 @@ fn capture_filter_replay(
19762 frame_height: usize,19777 frame_height: usize,
19763 width: usize,19778 width: usize,
19764 height: usize,19779 height: usize,
19780+ true_width: usize,
19781+ true_height: usize,
19765 ) {19782 ) {
19766 if !REPLAY_ARMED.replace(false) {19783 if !REPLAY_ARMED.replace(false) {
19767 return;19784 return;
@@ -19777,6 +19794,8 @@ fn capture_filter_replay(
19777 frame_height,19794 frame_height,
19778 width,19795 width,
19779 height,19796 height,
19797+ true_width,
19798+ true_height,
19780 deblocked: None,19799 deblocked: None,
19781 });19800 });
19782 });19801 });
@@ -19791,6 +19810,10 @@ pub(crate) fn replay_filters(
19791 cdef: &CdefParams,19810 cdef: &CdefParams,
19792 fctx: &FrameCtx,19811 fctx: &FrameCtx,
19793 ) -> Option<Picture> {19812 ) -> Option<Picture> {
19813+ #[cfg(test)]
19814+ if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
19815+ return None;
19816+ }
19794 REPLAY.with_borrow_mut(|slot| {19817 REPLAY.with_borrow_mut(|slot| {
19795 let r = slot.as_mut()?;19818 let r = slot.as_mut()?;
19796 let copy = |p: &PlaneBuf<'_>| PlaneBuf {19819 let copy = |p: &PlaneBuf<'_>| PlaneBuf {
@@ -19803,6 +19826,7 @@ pub(crate) fn replay_filters(
19803 (copy(dy), copy(du), copy(dv))19826 (copy(dy), copy(du), copy(dv))
19804 } else {19827 } else {
19805 let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));19828 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);
19806 apply_deblock(19830 apply_deblock(
19807 &mut y,19831 &mut y,
19808 &mut u,19832 &mut u,
@@ -19816,17 +19840,53 @@ pub(crate) fn replay_filters(
19816 r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v)));19840 r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v)));
19817 (y, u, v)19841 (y, u, v)
19818 };19842 };
19843+ let ct = crate::par::timer(crate::par::S_CDEF);
19819 apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);19844 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 tail19845+ drop(ct);
19821- // returns whole (no superres, no loop restoration, no crop), so this19846+ // The capture only happens on the shape whose tail is the two
19822- // is that tail.19847+ // filter calls and the crop (no superres, no loop restoration), so
19823- fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);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+ });
19824 Some(Picture {19884 Some(Picture {
19825- width: r.width,19885+ width: fw,
19826- height: r.height,19886+ height: fh,
19827- y: y.data.into_owned(),19887+ y: crop_owned(y, fw, fh),
19828- u: u.data.into_owned(),19888+ u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)),
19829- v: v.data.into_owned(),19889+ v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)),
19830 })19890 })
19831 })19891 })
19832 }19892 }
@@ -23110,8 +23170,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
23110 // frame tile per candidate -- capture it once (see [`FilterReplay`]),23170 // frame tile per candidate -- capture it once (see [`FilterReplay`]),
23111 // on the shape whose tail is the two filter calls and nothing else.23171 // on the shape whose tail is the two filter calls and nothing else.
23112 if superres(fctx).is_none()23172 if superres(fctx).is_none()
23113- && frame_width as usize == width
23114- && frame_height as usize == height
23115 && !(0..3).any(|p| {23173 && !(0..3).any(|p| {
23116 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None23174 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
23117 && lr.loop_restoration_size[p] != 023175 && lr.loop_restoration_size[p] != 0
@@ -23126,6 +23184,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
23126 frame_height as usize,23184 frame_height as usize,
23127 width,23185 width,
23128 height,23186 height,
23187+ true_width,
23188+ true_height,
23129 );23189 );
23130 }23190 }
23131 apply_deblock(23191 apply_deblock(
@@ -35847,12 +35907,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
35847 // same coded tile ([`FilterReplay`]). Capture the reconstruction here,35907 // same coded tile ([`FilterReplay`]). Capture the reconstruction here,
35848 // before either filter has touched it -- but only on the shape whose35908 // before either filter has touched it -- but only on the shape whose
35849 // tail is exactly `apply_deblock` + `apply_cdef` and nothing else.35909 // tail is exactly `apply_deblock` + `apply_cdef` and nothing else.
35850- if !pipelined35910+ if !pipelined && !lr_active && superres(fctx).is_none() {
35851- && !lr_active
35852- && superres(fctx).is_none()
35853- && frame_width as usize == width
35854- && frame_height as usize == height
35855- {
35856 capture_filter_replay(35911 capture_filter_replay(
35857 &y,35912 &y,
35858 &u,35913 &u,
@@ -35862,6 +35917,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
35862 frame_height as usize,35917 frame_height as usize,
35863 width,35918 width,
35864 height,35919 height,
35920+ true_width,
35921+ true_height,
35865 );35922 );
35866 }35923 }
35867 if pipelined {35924 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>>,
3309 where3309 where
3310 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,3310 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
3311 {3311 {
3312+ let _t = crate::par::timer(crate::par::S_TILE_WRITE);
3312 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;3313 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
3313 let threads = crate::par::tile_threads().min(tiles);3314 let threads = crate::par::tile_threads().min(tiles);
3314 let mut slots: Vec<Slot> = Vec::new();3315 let mut slots: Vec<Slot> = Vec::new();
@@ -3364,6 +3365,7 @@ where
3364 T: Send,3365 T: Send,
3365 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,3366 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
3366 {3367 {
3368+ let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
3367 let threads = crate::par::tile_threads().min(tiles);3369 let threads = crate::par::tile_threads().min(tiles);
3368 if threads <= 1 {3370 if threads <= 1 {
3369 return (0..tiles).map(|index| job(index, fctx)).collect();3371 return (0..tiles).map(|index| job(index, fctx)).collect();
@@ -4144,6 +4146,7 @@ fn pick_and_apply_filters(
4144 // preset search reads comes off the REPLAYED picture, which is the same4146 // preset search reads comes off the REPLAYED picture, which is the same
4145 // picture a decode produces -- that is what the replay is pinned on.4147 // picture a decode produces -- that is what the replay is pinned on.
4146 crate::decode::clear_filter_replay();4148 crate::decode::clear_filter_replay();
4149+ let ft = crate::par::timer(crate::par::S_FILTER);
4147 let search_result = crate::filter_search::pick_filters(4150 let search_result = crate::filter_search::pick_filters(
4148 |lf, cdef| {4151 |lf, cdef| {
4149 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {4152 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
@@ -4159,6 +4162,7 @@ fn pick_and_apply_filters(
4159 (sb_cols, sb_rows),4162 (sb_cols, sb_rows),
4160 lambda,4163 lambda,
4161 );4164 );
4165+ drop(ft);
4162 crate::decode::clear_filter_replay();4166 crate::decode::clear_filter_replay();
4163 let (lf, cdef, idx_grid, picture) = search_result?;4167 let (lf, cdef, idx_grid, picture) = search_result?;
4164 header.loop_filter = lf;4168 header.loop_filter = lf;
@@ -4181,12 +4185,14 @@ fn pick_and_apply_filters(
4181 fctx.capture_stages.set(lr_on);4185 fctx.capture_stages.set(lr_on);
4182 let mut filtered = if idx_grid.is_empty() {4186 let mut filtered = if idx_grid.is_empty() {
4183 if lr_on {4187 if lr_on {
4188+ let _t = crate::par::timer(crate::par::S_CAPTURE);
4184 decode(&lf, &cdef, &hdr, tiles, &none_lr)?4189 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
4185 } else {4190 } else {
4186 picture4191 picture
4187 }4192 }
4188 } else {4193 } else {
4189 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;4194 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
4195+ let _t = crate::par::timer(crate::par::S_CAPTURE);
4190 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;4196 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
4191 *tiles = coded;4197 *tiles = coded;
4192 picture4198 picture
@@ -4200,6 +4206,7 @@ fn pick_and_apply_filters(
4200 ..LoopRestorationParams::default()4206 ..LoopRestorationParams::default()
4201 };4207 };
4202 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;4208 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
4209+ let lrt = crate::par::timer(crate::par::S_LR);
4203 let units = match crate::decode::take_filter_stages(fctx) {4210 let units = match crate::decode::take_filter_stages(fctx) {
4204 Some(stages) => crate::filter_search::pick_restoration(4211 Some(stages) => crate::filter_search::pick_restoration(
4205 &stages,4212 &stages,
@@ -4216,8 +4223,10 @@ fn pick_and_apply_filters(
4216 // rather than paying ~1 bit per 64x64 for a tile full of4223 // rather than paying ~1 bit per 64x64 for a tile full of
4217 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the4224 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
4218 // clip whose units never take a filter).4225 // clip whose units never take a filter).
4226+ drop(lrt);
4219 if units.iter().any(Option::is_some) {4227 if units.iter().any(Option::is_some) {
4220 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;4228 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
4229+ let _t = crate::par::timer(crate::par::S_CAPTURE);
4221 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;4230 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
4222 *tiles = coded;4231 *tiles = coded;
4223 lr = want;4232 lr = want;
crates/ec-av1/src/encoder.rsmodified+135 -0
@@ -1862,6 +1862,141 @@ mod tests {
1862 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);1862 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
1863 }1863 }
1864 1864
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+
1865 fn tile_search_wall(2000 fn tile_search_wall(
1866 width: usize,2001 width: usize,
1867 height: usize,2002 height: usize,
crates/ec-av1/src/filter_search.rsmodified+2 -0
@@ -196,6 +196,7 @@ pub(crate) fn pick_filters(
196 (cand.lf.0, cand.y),196 (cand.lf.0, cand.y),
197 (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv),197 (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv),
198 );198 );
199+ let sst = crate::par::timer(crate::par::S_SSE);
199 if !st.luma.iter().any(|(k, _)| *k == lkey) {200 if !st.luma.iter().any(|(k, _)| *k == lkey) {
200 let mut units = vec![0u64; nsb];201 let mut units = vec![0u64; nsb];
201 let sse =202 let sse =
@@ -208,6 +209,7 @@ pub(crate) fn pick_filters(
208 + unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut units);209 + unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut units);
209 st.chroma.push((ckey, (sse, units)));210 st.chroma.push((ckey, (sse, units)));
210 }211 }
212+ drop(sst);
211 let (sse_y, sse_uv, sse64) = {213 let (sse_y, sse_uv, sse64) = {
212 let l = &st.luma.iter().find(|(k, _)| *k == lkey).expect("just inserted").1;214 let l = &st.luma.iter().find(|(k, _)| *k == lkey).expect("just inserted").1;
213 let c = &st.chroma.iter().find(|(k, _)| *k == ckey).expect("just inserted").1;215 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<'_> {
459 }459 }
460 }460 }
461 }461 }
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+}