forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into lane-av1comp3

Browse files at this commit

8974f274135e3f7d064cb28c4961fd985967508dAhmet Kaan GümüşParent: 4619f22d4248c3
crates/ec-av1/src/decode.rsmodified+132 -27
@@ -19725,6 +19725,16 @@ 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,
19732+ /// lane-av1fpar: plane buffers this replay is done with. Every candidate
19733+ /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
19734+ /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
19735+ /// 1080p frame's wall in allocation, not in filtering. Recycled here
19736+ /// instead; the pool holds at most the six planes one candidate has live.
19737+ scratch: Vec<Vec<u16>>,
19728 /// The last deblocked planes and the levels that produced them.19738 /// The last deblocked planes and the levels that produced them.
19729 /// Deblocking depends on nothing else the search moves, and the search19739 /// Deblocking depends on nothing else the search moves, and the search
19730 /// fixes the levels before it walks the CDEF strengths, so every19740 /// fixes the levels before it walks the CDEF strengths, so every
@@ -19745,6 +19755,17 @@ pub(crate) fn arm_filter_replay() {
19745 REPLAY_ARMED.set(true);19755 REPLAY_ARMED.set(true);
19746 }19756 }
19747 19757
19758+/// Test-only: force every filter candidate through a full decode, so a gate
19759+/// can hold the replay against the decode it stands in for
19760+/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
19761+#[cfg(test)]
19762+static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
19763+
19764+#[cfg(test)]
19765+pub(crate) fn set_filter_replay_disabled(off: bool) {
19766+ REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
19767+}
19768+
19748 /// Drop the armed flag and anything captured: the tile it belongs to is done.19769 /// Drop the armed flag and anything captured: the tile it belongs to is done.
19749 pub(crate) fn clear_filter_replay() {19770 pub(crate) fn clear_filter_replay() {
19750 REPLAY_ARMED.set(false);19771 REPLAY_ARMED.set(false);
@@ -19762,6 +19783,8 @@ fn capture_filter_replay(
19762 frame_height: usize,19783 frame_height: usize,
19763 width: usize,19784 width: usize,
19764 height: usize,19785 height: usize,
19786+ true_width: usize,
19787+ true_height: usize,
19765 ) {19788 ) {
19766 if !REPLAY_ARMED.replace(false) {19789 if !REPLAY_ARMED.replace(false) {
19767 return;19790 return;
@@ -19777,11 +19800,38 @@ fn capture_filter_replay(
19777 frame_height,19800 frame_height,
19778 width,19801 width,
19779 height,19802 height,
19803+ true_width,
19804+ true_height,
19805+ scratch: Vec::new(),
19780 deblocked: None,19806 deblocked: None,
19781 });19807 });
19782 });19808 });
19783 }19809 }
19784 19810
19811+/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
19812+/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
19813+/// allocator and the page fault handler out of the filter search.
19814+fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
19815+ let mut buf = scratch.pop().unwrap_or_default();
19816+ let src: &[u16] = &p.data;
19817+ let threads = crate::par::filter_threads();
19818+ if buf.len() != src.len() || threads <= 1 {
19819+ buf.clear();
19820+ buf.extend_from_slice(src);
19821+ } else {
19822+ // A recycled buffer is already the right length, so the copy is a
19823+ // plain `copy_from_slice` -- and one worth banding: ~6 MB per
19824+ // candidate is memory bandwidth, not arithmetic, and the halves are
19825+ // disjoint `&mut` slices (no `par::Shared` needed).
19826+ let per = src.len().div_ceil(threads);
19827+ let batch = crate::par::Batch::new("ec-av1-filter");
19828+ for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
19829+ batch.submit(move || dst.copy_from_slice(src));
19830+ }
19831+ }
19832+ PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p }
19833+}
19834+
19785 /// The filter half of a captured decode, under new parameters: exactly the19835 /// The filter half of a captured decode, under new parameters: exactly the
19786 /// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a19836 /// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
19787 /// copy of the captured planes. `None` when nothing is captured (the caller19837 /// copy of the captured planes. `None` when nothing is captured (the caller
@@ -19791,18 +19841,30 @@ pub(crate) fn replay_filters(
19791 cdef: &CdefParams,19841 cdef: &CdefParams,
19792 fctx: &FrameCtx,19842 fctx: &FrameCtx,
19793 ) -> Option<Picture> {19843 ) -> Option<Picture> {
19844+ #[cfg(test)]
19845+ if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
19846+ return None;
19847+ }
19794 REPLAY.with_borrow_mut(|slot| {19848 REPLAY.with_borrow_mut(|slot| {
19795 let r = slot.as_mut()?;19849 let r = slot.as_mut()?;
19796- let copy = |p: &PlaneBuf<'_>| PlaneBuf {
19797- data: std::borrow::Cow::Owned(p.data.to_vec()),
19798- ..*p
19799- };
19800 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);19850 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
19851+ let cpt = crate::par::timer(crate::par::S_COPY);
19801 let (mut y, mut u, mut v) = if hit {19852 let (mut y, mut u, mut v) = if hit {
19802- let (_, dy, du, dv) = r.deblocked.as_ref().expect("just matched");19853+ let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
19803- (copy(dy), copy(du), copy(dv))19854+ let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
19855+ (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch))
19804 } else {19856 } else {
19805- let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));19857+ // The levels moved, so the cached deblocked planes are dead:
19858+ // their buffers are this candidate's working copies.
19859+ if let Some((_, dy, du, dv)) = r.deblocked.take() {
19860+ r.scratch.push(dy.data.into_owned());
19861+ r.scratch.push(du.data.into_owned());
19862+ r.scratch.push(dv.data.into_owned());
19863+ }
19864+ let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch);
19865+ let (mut y, mut u, mut v) =
19866+ (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch));
19867+ let _t = crate::par::timer(crate::par::S_DEBLOCK);
19806 apply_deblock(19868 apply_deblock(
19807 &mut y,19869 &mut y,
19808 &mut u,19870 &mut u,
@@ -19813,21 +19875,67 @@ pub(crate) fn replay_filters(
19813 r.frame_height,19875 r.frame_height,
19814 fctx,19876 fctx,
19815 );19877 );
19816- r.deblocked = Some((*loop_filter, copy(&y), copy(&u), copy(&v)));19878+ let scratch = &mut r.scratch;
19879+ r.deblocked =
19880+ Some((*loop_filter, pooled(&y, scratch), pooled(&u, scratch), pooled(&v, scratch)));
19817 (y, u, v)19881 (y, u, v)
19818 };19882 };
19883+ drop(cpt);
19884+ 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);19885 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 tail19886+ drop(ct);
19821- // returns whole (no superres, no loop restoration, no crop), so this19887+ // The capture only happens on the shape whose tail is the two
19822- // is that tail.19888+ // filter calls and the crop (no superres, no loop restoration), so
19823- fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);19889+ // what is left is that crop -- byte for byte the cropped return path
19824- Some(Picture {19890+ // of the decode this replaces, wide-margin stash included.
19825- width: r.width,19891+ //
19826- height: r.height,19892+ // lane-av1fpar: the crop is why this arm exists at all. The capture
19827- y: y.data.into_owned(),19893+ // used to demand `frame == plane` dimensions, which no editor size
19828- u: u.data.into_owned(),19894+ // meets (1080 and 1608 both pad to a superblock row), so every
19829- v: v.data.into_owned(),19895+ // candidate of every frame at those sizes fell through to a full
19830- })19896+ // re-decode -- 57% of a 1080p frame's wall.
19897+ let (fw, fh) = (r.frame_width, r.frame_height);
19898+ if fw == r.width && fh == r.height {
19899+ fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
19900+ return Some(Picture {
19901+ width: r.width,
19902+ height: r.height,
19903+ y: y.data.into_owned(),
19904+ u: u.data.into_owned(),
19905+ v: v.data.into_owned(),
19906+ });
19907+ }
19908+ let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
19909+ let mut out = Vec::with_capacity(w * h);
19910+ for row in 0..h {
19911+ out.extend(plane.data[row * plane.width..][..w].iter().copied());
19912+ }
19913+ out
19914+ };
19915+ let (tw, th) = (r.true_width, r.true_height);
19916+ fctx.last_frame_wide_margin.with(|m| {
19917+ *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture {
19918+ width: tw,
19919+ height: th,
19920+ y: crop(&y, tw, th),
19921+ u: crop(&u, tw.div_ceil(2), th.div_ceil(2)),
19922+ v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
19923+ });
19924+ });
19925+ let out = Picture {
19926+ width: fw,
19927+ height: fh,
19928+ y: crop(&y, fw, fh),
19929+ u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
19930+ v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
19931+ };
19932+ // The working planes outlive the crop, so they go back to the pool.
19933+ for plane in [y, u, v] {
19934+ if r.scratch.len() < 6 {
19935+ r.scratch.push(plane.data.into_owned());
19936+ }
19937+ }
19938+ Some(out)
19831 })19939 })
19832 }19940 }
19833 19941
@@ -23110,8 +23218,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
23110 // frame tile per candidate -- capture it once (see [`FilterReplay`]),23218 // frame tile per candidate -- capture it once (see [`FilterReplay`]),
23111 // on the shape whose tail is the two filter calls and nothing else.23219 // on the shape whose tail is the two filter calls and nothing else.
23112 if superres(fctx).is_none()23220 if superres(fctx).is_none()
23113- && frame_width as usize == width
23114- && frame_height as usize == height
23115 && !(0..3).any(|p| {23221 && !(0..3).any(|p| {
23116 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None23222 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
23117 && lr.loop_restoration_size[p] != 023223 && lr.loop_restoration_size[p] != 0
@@ -23126,6 +23232,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
23126 frame_height as usize,23232 frame_height as usize,
23127 width,23233 width,
23128 height,23234 height,
23235+ true_width,
23236+ true_height,
23129 );23237 );
23130 }23238 }
23131 apply_deblock(23239 apply_deblock(
@@ -35847,12 +35955,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
35847 // same coded tile ([`FilterReplay`]). Capture the reconstruction here,35955 // same coded tile ([`FilterReplay`]). Capture the reconstruction here,
35848 // before either filter has touched it -- but only on the shape whose35956 // before either filter has touched it -- but only on the shape whose
35849 // tail is exactly `apply_deblock` + `apply_cdef` and nothing else.35957 // tail is exactly `apply_deblock` + `apply_cdef` and nothing else.
35850- if !pipelined35958+ 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(35959 capture_filter_replay(
35857 &y,35960 &y,
35858 &u,35961 &u,
@@ -35862,6 +35965,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
35862 frame_height as usize,35965 frame_height as usize,
35863 width,35966 width,
35864 height,35967 height,
35968+ true_width,
35969+ true_height,
35865 );35970 );
35866 }35971 }
35867 if pipelined {35972 if pipelined {
crates/ec-av1/src/encode.rsmodified+15 -0
@@ -3498,6 +3498,7 @@ fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>,
3498 where3498 where
3499 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,3499 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
3500 {3500 {
3501+ let _t = crate::par::timer(crate::par::S_TILE_WRITE);
3501 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;3502 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
3502 let threads = crate::par::tile_threads().min(tiles);3503 let threads = crate::par::tile_threads().min(tiles);
3503 let mut slots: Vec<Slot> = Vec::new();3504 let mut slots: Vec<Slot> = Vec::new();
@@ -3553,6 +3554,7 @@ where
3553 T: Send,3554 T: Send,
3554 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,3555 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
3555 {3556 {
3557+ let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
3556 let threads = crate::par::tile_threads().min(tiles);3558 let threads = crate::par::tile_threads().min(tiles);
3557 if threads <= 1 {3559 if threads <= 1 {
3558 return (0..tiles).map(|index| job(index, fctx)).collect();3560 return (0..tiles).map(|index| job(index, fctx)).collect();
@@ -4333,12 +4335,19 @@ fn pick_and_apply_filters(
4333 // preset search reads comes off the REPLAYED picture, which is the same4335 // preset search reads comes off the REPLAYED picture, which is the same
4334 // picture a decode produces -- that is what the replay is pinned on.4336 // picture a decode produces -- that is what the replay is pinned on.
4335 crate::decode::clear_filter_replay();4337 crate::decode::clear_filter_replay();
4338+ // lane-av1fpar: the per-tile search is over, so every core is idle from
4339+ // here to the end of the frame -- band each candidate's deblock/CDEF
4340+ // replay, the capture decode's own filter chain and the loop-restoration
4341+ // passes across the same workers the search used.
4342+ let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
4343+ let ft = crate::par::timer(crate::par::S_FILTER);
4336 let search_result = crate::filter_search::pick_filters(4344 let search_result = crate::filter_search::pick_filters(
4337 |lf, cdef| {4345 |lf, cdef| {
4338 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {4346 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
4339 return Ok(picture);4347 return Ok(picture);
4340 }4348 }
4341 crate::decode::arm_filter_replay();4349 crate::decode::arm_filter_replay();
4350+ let _t = crate::par::timer(crate::par::S_FIRST);
4342 decode(lf, cdef, &hdr, tiles, &none_lr)4351 decode(lf, cdef, &hdr, tiles, &none_lr)
4343 },4352 },
4344 source,4353 source,
@@ -4348,6 +4357,7 @@ fn pick_and_apply_filters(
4348 (sb_cols, sb_rows),4357 (sb_cols, sb_rows),
4349 lambda,4358 lambda,
4350 );4359 );
4360+ drop(ft);
4351 crate::decode::clear_filter_replay();4361 crate::decode::clear_filter_replay();
4352 let (lf, cdef, idx_grid, picture) = search_result?;4362 let (lf, cdef, idx_grid, picture) = search_result?;
4353 header.loop_filter = lf;4363 header.loop_filter = lf;
@@ -4370,12 +4380,14 @@ fn pick_and_apply_filters(
4370 fctx.capture_stages.set(lr_on);4380 fctx.capture_stages.set(lr_on);
4371 let mut filtered = if idx_grid.is_empty() {4381 let mut filtered = if idx_grid.is_empty() {
4372 if lr_on {4382 if lr_on {
4383+ let _t = crate::par::timer(crate::par::S_CAPTURE);
4373 decode(&lf, &cdef, &hdr, tiles, &none_lr)?4384 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
4374 } else {4385 } else {
4375 picture4386 picture
4376 }4387 }
4377 } else {4388 } else {
4378 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;4389 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
4390+ let _t = crate::par::timer(crate::par::S_CAPTURE);
4379 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;4391 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
4380 *tiles = coded;4392 *tiles = coded;
4381 picture4393 picture
@@ -4389,6 +4401,7 @@ fn pick_and_apply_filters(
4389 ..LoopRestorationParams::default()4401 ..LoopRestorationParams::default()
4390 };4402 };
4391 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;4403 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
4404+ let lrt = crate::par::timer(crate::par::S_LR);
4392 let units = match crate::decode::take_filter_stages(fctx) {4405 let units = match crate::decode::take_filter_stages(fctx) {
4393 Some(stages) => crate::filter_search::pick_restoration(4406 Some(stages) => crate::filter_search::pick_restoration(
4394 &stages,4407 &stages,
@@ -4405,8 +4418,10 @@ fn pick_and_apply_filters(
4405 // rather than paying ~1 bit per 64x64 for a tile full of4418 // rather than paying ~1 bit per 64x64 for a tile full of
4406 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the4419 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
4407 // clip whose units never take a filter).4420 // clip whose units never take a filter).
4421+ drop(lrt);
4408 if units.iter().any(Option::is_some) {4422 if units.iter().any(Option::is_some) {
4409 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;4423 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
4424+ let _t = crate::par::timer(crate::par::S_CAPTURE);
4410 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;4425 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
4411 *tiles = coded;4426 *tiles = coded;
4412 lr = want;4427 lr = want;
crates/ec-av1/src/encoder.rsmodified+172 -0
@@ -1862,6 +1862,178 @@ 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 frame-level FILTER stage is banded across the same
1866+ /// workers the tile search uses (`par::override_filter_threads`), so the
1867+ /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in
1868+ /// pieces. Every piece is a disjoint band of the same integers, so the
1869+ /// stream must not move -- at a size that crops and is several superblock
1870+ /// rows tall, which is what makes the bands non-trivial.
1871+ #[test]
1872+ fn filter_stage_bytes_do_not_depend_on_the_thread_count() {
1873+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1874+ let (width, height) = (384usize, 288usize);
1875+ let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1876+ let coded = |threads: usize| {
1877+ crate::par::set_tile_threads(threads);
1878+ let config = EncoderConfig {
1879+ width,
1880+ height,
1881+ base_q_idx: 120,
1882+ gop: 2,
1883+ colour: Colour::Bt709Limited,
1884+ tile_cols_log2: 0,
1885+ tile_rows_log2: 0,
1886+ };
1887+ let mut enc = Av1Encoder::new(config).unwrap();
1888+ let mut stream = Vec::new();
1889+ for picture in &sources {
1890+ stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1891+ }
1892+ stream
1893+ };
1894+ // One tile, so only the filter stage can differ between these.
1895+ let one = coded(1);
1896+ for threads in [2usize, 4, 8] {
1897+ assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads");
1898+ }
1899+ crate::par::set_tile_threads(1);
1900+ }
1901+
1902+ /// lane-av1fpar: the filter search scores its ~30 candidates by replaying
1903+ /// the loop filters on one captured reconstruction instead of decoding
1904+ /// the coded tile again per candidate. The replay must be that decode,
1905+ /// byte for byte -- including at a size that CROPS (1080 and 1608 both
1906+ /// pad to a superblock row, i.e. every export size the editor uses),
1907+ /// which is the arm this lane opened.
1908+ #[test]
1909+ fn filter_replay_codes_the_same_stream_as_a_full_decode() {
1910+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1911+ let run = |width: usize, height: usize, off: bool| {
1912+ let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1913+ crate::decode::set_filter_replay_disabled(off);
1914+ let config = EncoderConfig {
1915+ width,
1916+ height,
1917+ base_q_idx: 120,
1918+ gop: 2,
1919+ colour: Colour::Bt709Limited,
1920+ tile_cols_log2: 0,
1921+ tile_rows_log2: 0,
1922+ };
1923+ let mut enc = Av1Encoder::new(config).unwrap();
1924+ let mut stream = Vec::new();
1925+ for picture in &sources {
1926+ stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1927+ }
1928+ crate::decode::set_filter_replay_disabled(false);
1929+ stream
1930+ };
1931+ // 320x160 crops (the coding surface is 320x192, one superblock row
1932+ // taller); 320x192 is a whole number of superblocks, the shape the
1933+ // replay already covered.
1934+ for (width, height) in [(320usize, 160usize), (320, 192)] {
1935+ let replayed = run(width, height, false);
1936+ let decoded = run(width, height, true);
1937+ assert_eq!(
1938+ replayed,
1939+ decoded,
1940+ "{width}x{height}: the filter replay is not the decode it stands in for \
1941+ ({} bytes replayed, {} decoded)",
1942+ replayed.len(),
1943+ decoded.len(),
1944+ );
1945+ }
1946+ }
1947+
1948+ /// lane-av1fpar: where a frame's wall actually goes, stage by stage --
1949+ /// the per-tile search, the tile write, the frame-level filter search
1950+ /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture
1951+ /// decode the loop-restoration search rides on, and that search itself.
1952+ /// Measurement, not a pass/fail gate.
1953+ #[test]
1954+ #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1955+ fn filter_stage_wall_1080p() {
1956+ filter_stage_wall(1920, 1080, 8, (2, 1), &[8]);
1957+ }
1958+
1959+ #[test]
1960+ #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1961+ fn filter_stage_wall_4k() {
1962+ filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]);
1963+ }
1964+
1965+ fn filter_stage_wall(
1966+ width: usize,
1967+ height: usize,
1968+ frames: usize,
1969+ (cols_log2, rows_log2): (u32, u32),
1970+ threads: &[usize],
1971+ ) {
1972+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1973+ let Some(sources) = h264_clip_frames(width, height, frames) else {
1974+ eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg");
1975+ return;
1976+ };
1977+ crate::par::set_stage_times(true);
1978+ for &t in threads {
1979+ crate::par::set_tile_threads(t);
1980+ let config = EncoderConfig {
1981+ width,
1982+ height,
1983+ base_q_idx: 120,
1984+ gop: frames,
1985+ colour: Colour::Bt709Limited,
1986+ tile_cols_log2: cols_log2,
1987+ tile_rows_log2: rows_log2,
1988+ };
1989+ let mut enc = Av1Encoder::new(config).unwrap();
1990+ let _ = crate::par::take_stage_ns();
1991+ let start = std::time::Instant::now();
1992+ for picture in &sources {
1993+ assert!(!enc.encode(picture).unwrap().data.is_empty());
1994+ }
1995+ let wall = start.elapsed().as_secs_f64();
1996+ let ns = crate::par::take_stage_ns();
1997+ let ms = |i: usize| ns[i] as f64 / 1e6;
1998+ eprintln!(
1999+ "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \
2000+ {wall:.2}s wall, {:.2} fps",
2001+ 1 << cols_log2,
2002+ 1 << rows_log2,
2003+ frames as f64 / wall,
2004+ );
2005+ eprintln!("| stage | ms | ms/frame | % of wall |");
2006+ for (i, name) in crate::par::STAGES.iter().enumerate() {
2007+ eprintln!(
2008+ "| {name} | {:.0} | {:.1} | {:.1}% |",
2009+ ms(i),
2010+ ms(i) / frames as f64,
2011+ 100.0 * ms(i) / (wall * 1e3),
2012+ );
2013+ }
2014+ // Top-level stages only (the deblock/CDEF/SSE rows are inside
2015+ // the filter-search total); the rest is per-frame setup, the
2016+ // source conversion and the splice.
2017+ let top: f64 = [
2018+ crate::par::S_TILE_SEARCH,
2019+ crate::par::S_TILE_WRITE,
2020+ crate::par::S_FILTER,
2021+ crate::par::S_CAPTURE,
2022+ crate::par::S_LR,
2023+ ]
2024+ .iter()
2025+ .map(|&i| ms(i))
2026+ .sum();
2027+ eprintln!(
2028+ "accounted {:.1}% of wall; outside the tile search {:.1}%",
2029+ 100.0 * top / (wall * 1e3),
2030+ 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)),
2031+ );
2032+ }
2033+ crate::par::set_stage_times(false);
2034+ crate::par::set_tile_threads(1);
2035+ }
2036+
1865 fn tile_search_wall(2037 fn tile_search_wall(
1866 width: usize,2038 width: usize,
1867 height: usize,2039 height: usize,
crates/ec-av1/src/filter_search.rsmodified+90 -17
@@ -81,10 +81,52 @@ fn unit_sse(
81 unit: usize,81 unit: usize,
82 sb_cols: usize,82 sb_cols: usize,
83 out: &mut [u64],83 out: &mut [u64],
84+) -> u64 {
85+ // lane-av1fpar: the whole-frame pass, split across the filter workers by
86+ // UNIT ROW -- each band owns its own rows of `out` (`chunks_mut`, so the
87+ // disjointness is the borrow checker's) and its partial totals are `u64`
88+ // integers, which add up to the same value in any order.
89+ let threads = crate::par::filter_threads().min(h.div_ceil(unit));
90+ if threads <= 1 {
91+ return unit_sse_rows(dec, dec_w, src, src_w, w, 0, h, unit, sb_cols, out);
92+ }
93+ let per = h.div_ceil(unit).div_ceil(threads);
94+ let total = std::sync::atomic::AtomicU64::new(0);
95+ {
96+ let batch = crate::par::Batch::new("ec-av1-filter");
97+ for (band, rows) in out.chunks_mut(per * sb_cols).enumerate() {
98+ let (r0, r1) = ((band * per * unit).min(h), ((band + 1) * per * unit).min(h));
99+ if r0 == r1 {
100+ continue;
101+ }
102+ let total = &total;
103+ batch.submit(move || {
104+ let sse = unit_sse_rows(dec, dec_w, src, src_w, w, r0, r1, unit, sb_cols, rows);
105+ total.fetch_add(sse, std::sync::atomic::Ordering::Relaxed);
106+ });
107+ }
108+ }
109+ total.into_inner()
110+}
111+
112+/// [`unit_sse`] over rows `r0..r1` alone, accumulating into `out` as if it
113+/// started at unit row `r0 / unit`.
114+#[allow(clippy::too_many_arguments)]
115+fn unit_sse_rows(
116+ dec: &[u16],
117+ dec_w: usize,
118+ src: &[u8],
119+ src_w: usize,
120+ w: usize,
121+ r0: usize,
122+ r1: usize,
123+ unit: usize,
124+ sb_cols: usize,
125+ out: &mut [u64],
84 ) -> u64 {126 ) -> u64 {
85 let mut total = 0u64;127 let mut total = 0u64;
86- for row in 0..h {128+ for row in r0..r1 {
87- let base = (row / unit) * sb_cols;129+ let base = ((row - r0) / unit) * sb_cols;
88 let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);130 let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]);
89 for (i, (dc, sc)) in d.chunks(unit).zip(s.chunks(unit)).enumerate() {131 for (i, (dc, sc)) in d.chunks(unit).zip(s.chunks(unit)).enumerate() {
90 let mut acc = 0u32;132 let mut acc = 0u32;
@@ -196,6 +238,7 @@ pub(crate) fn pick_filters(
196 (cand.lf.0, cand.y),238 (cand.lf.0, cand.y),
197 (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv),239 (if cand.uv == (0, 0) { 0 } else { cand.lf.0 }, cand.lf.1, cand.uv),
198 );240 );
241+ let sst = crate::par::timer(crate::par::S_SSE);
199 if !st.luma.iter().any(|(k, _)| *k == lkey) {242 if !st.luma.iter().any(|(k, _)| *k == lkey) {
200 let mut units = vec![0u64; nsb];243 let mut units = vec![0u64; nsb];
201 let sse =244 let sse =
@@ -208,6 +251,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);251 + 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)));252 st.chroma.push((ckey, (sse, units)));
210 }253 }
254+ drop(sst);
211 let (sse_y, sse_uv, sse64) = {255 let (sse_y, sse_uv, sse64) = {
212 let l = &st.luma.iter().find(|(k, _)| *k == lkey).expect("just inserted").1;256 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;257 let c = &st.chroma.iter().find(|(k, _)| *k == ckey).expect("just inserted").1;
@@ -456,13 +500,33 @@ pub(crate) fn pick_restoration(
456 sse500 sse
457 };501 };
458 // Cost of leaving every unit alone, then one whole-plane pass per502 // Cost of leaving every unit alone, then one whole-plane pass per
459- // candidate to price taking it.503+ // candidate to price taking it. Both walks are banded by unit ROW
460- let mut best: Vec<(f64, Option<crate::restoration::WienerInfo>)> = (0..horz * vert)504+ // (lane-av1fpar): a unit's cost is read off its own samples alone and
461- .map(|i| {505+ // written to its own slot, so the bands are `chunks_mut` of the same
462- let sse = unit_sse(&stages.cdefed[0], i / horz, i % horz) as f64;506+ // `best` and the choice cannot depend on how many of them there are.
463- (sse + lambda * LR_NONE_BITS, None)507+ let rows_of = |plane: &[u16], r0: usize, slice: &mut [(f64, Option<crate::restoration::WienerInfo>)], score: &dyn Fn(u64, &mut (f64, Option<crate::restoration::WienerInfo>))| {
464- })508+ for (i, slot) in slice.iter_mut().enumerate() {
465- .collect();509+ score(unit_sse(plane, r0 + i / horz, i % horz), slot);
510+ }
511+ };
512+ let banded = |plane: &[u16], best: &mut [(f64, Option<crate::restoration::WienerInfo>)], score: &(dyn Fn(u64, &mut (f64, Option<crate::restoration::WienerInfo>)) + Sync)| {
513+ let threads = crate::par::filter_threads().min(vert);
514+ if threads <= 1 {
515+ rows_of(plane, 0, best, score);
516+ return;
517+ }
518+ let per = vert.div_ceil(threads);
519+ let batch = crate::par::Batch::new("ec-av1-filter");
520+ for (band, slice) in best.chunks_mut(per * horz).enumerate() {
521+ let rows_of = &rows_of;
522+ batch.submit(move || rows_of(plane, band * per, slice, score));
523+ }
524+ };
525+ let mut best: Vec<(f64, Option<crate::restoration::WienerInfo>)> =
526+ vec![(0.0, None); horz * vert];
527+ banded(&stages.cdefed[0], &mut best, &|sse, slot| {
528+ *slot = (sse as f64 + lambda * LR_NONE_BITS, None);
529+ });
466 let mut out = Vec::new();530 let mut out = Vec::new();
467 for taps in WIENER_CANDIDATES {531 for taps in WIENER_CANDIDATES {
468 let info = crate::restoration::wiener_from_taps(taps, taps);532 let info = crate::restoration::wiener_from_taps(taps, taps);
@@ -487,15 +551,12 @@ pub(crate) fn pick_restoration(
487 None,551 None,
488 fctx,552 fctx,
489 );553 );
490- for rrow in 0..vert {554+ banded(&out, &mut best, &|sse, slot| {
491- for rcol in 0..horz {555+ let cost = sse as f64 + lambda * LR_WIENER_BITS;
492- let cost = unit_sse(&out, rrow, rcol) as f64 + lambda * LR_WIENER_BITS;556+ if cost < slot.0 {
493- let slot = &mut best[rcol + rrow * horz];557+ *slot = (cost, Some(info));
494- if cost < slot.0 {
495- *slot = (cost, Some(info));
496- }
497 }558 }
498- }559+ });
499 }560 }
500 let chosen: Vec<Option<crate::restoration::WienerInfo>> =561 let chosen: Vec<Option<crate::restoration::WienerInfo>> =
501 best.into_iter().map(|(_, f)| f).collect();562 best.into_iter().map(|(_, f)| f).collect();
@@ -554,5 +615,17 @@ mod tests {
554 let mut got = vec![7u64; sb_cols * 4];615 let mut got = vec![7u64; sb_cols * 4];
555 assert_eq!(unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut got), total);616 assert_eq!(unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut got), total);
556 assert_eq!(got, want);617 assert_eq!(got, want);
618+ // lane-av1fpar: and banded across workers -- same per-unit slots,
619+ // same frame total (the partial sums are integers).
620+ for threads in [2usize, 4, 8] {
621+ let _bands = crate::par::override_filter_threads(threads);
622+ let mut banded = vec![7u64; sb_cols * 4];
623+ assert_eq!(
624+ unit_sse(&dec, dec_w, &src, src_w, w, h, unit, sb_cols, &mut banded),
625+ total,
626+ "{threads} bands: the frame total moved"
627+ );
628+ assert_eq!(banded, want, "{threads} bands: a unit's error moved");
629+ }
557 }630 }
558 }631 }
crates/ec-av1/src/par.rsmodified+110 -0
@@ -32,7 +32,40 @@
32 /// touching the process environment.32 /// touching the process environment.
33 static FILTER_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);33 static FILTER_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
34 34
35+thread_local! {
36+ /// This thread's override of [`filter_threads`], 0 = none. The ENCODER's
37+ /// frame-level filter search sets it for the span of that search
38+ /// (lane-av1fpar): the tile search is over by then, so every core is
39+ /// free, and each candidate's deblock/CDEF replay is exactly the banded
40+ /// stage the decoder already splits -- same bands, same byte-exact
41+ /// output, gated by
42+ /// `a_real_stream_filters_identically_with_one_and_four_filter_threads`
43+ /// on the decode side and by
44+ /// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count` here.
45+ static FILTER_BANDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
46+}
47+
48+/// Restores the previous [`FILTER_BANDS`] override when it drops.
49+pub(crate) struct FilterBands(usize);
50+
51+impl Drop for FilterBands {
52+ fn drop(&mut self) {
53+ FILTER_BANDS.set(self.0);
54+ }
55+}
56+
57+/// Bands every filter stage on THIS thread across `n` workers until the
58+/// returned guard drops; `n <= 1` leaves the process default in place.
59+pub(crate) fn override_filter_threads(n: usize) -> FilterBands {
60+ let previous = FILTER_BANDS.replace(if n > 1 { n.clamp(1, 64) } else { 0 });
61+ FilterBands(previous)
62+}
63+
35 pub(crate) fn filter_threads() -> usize {64 pub(crate) fn filter_threads() -> usize {
65+ let over = FILTER_BANDS.get();
66+ if over > 0 {
67+ return over;
68+ }
36 match FILTER_THREADS.load(std::sync::atomic::Ordering::Relaxed) {69 match FILTER_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
37 0 => {70 0 => {
38 let n = crate::envflags::var("EC_AV1_FILTER_THREADS")71 let n = crate::envflags::var("EC_AV1_FILTER_THREADS")
@@ -459,3 +492,80 @@ impl Drop for Batch<'_> {
459 }492 }
460 }493 }
461 }494 }
495+
496+// --- lane-av1fpar: encoder per-stage wall breakdown -----------------------
497+//
498+// Amdahl on the per-tile search (lane-av1tsearch) put ~43% of an inter frame
499+// OUTSIDE the tile search without saying what it was. These counters name it:
500+// one accumulator per serial stage of `encode_*_frame`, added to on whatever
501+// thread runs the stage and printed by `encoder::tests::filter_stage_wall_*`.
502+// Off (the default) each `stage` call is one relaxed atomic load.
503+
504+/// The stages [`stage`] accumulates, in the order a frame runs them.
505+pub(crate) const STAGES: [&str; 10] = [
506+ "tile search",
507+ "tile write",
508+ "filter: deblock replay",
509+ "filter: cdef replay",
510+ "filter: sse",
511+ "filter search (total)",
512+ "capture decode",
513+ "lr search",
514+ "filter: plane copies",
515+ "filter: first decode",
516+];
517+pub(crate) const S_TILE_SEARCH: usize = 0;
518+pub(crate) const S_TILE_WRITE: usize = 1;
519+pub(crate) const S_DEBLOCK: usize = 2;
520+pub(crate) const S_CDEF: usize = 3;
521+pub(crate) const S_SSE: usize = 4;
522+pub(crate) const S_FILTER: usize = 5;
523+pub(crate) const S_CAPTURE: usize = 6;
524+pub(crate) const S_LR: usize = 7;
525+pub(crate) const S_COPY: usize = 8;
526+pub(crate) const S_FIRST: usize = 9;
527+
528+static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] =
529+ [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];
530+/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES`, or
531+/// [`set_stage_times`] from a gate (the env snapshot is process-constant).
532+static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
533+
534+fn stage_times() -> bool {
535+ match STAGE_ON.load(std::sync::atomic::Ordering::Relaxed) {
536+ 0 => {
537+ let on = 1 + usize::from(crate::envflags::is_set("EC_AV1_STAGE_TIMES"));
538+ STAGE_ON.store(on, std::sync::atomic::Ordering::Relaxed);
539+ on == 2
540+ }
541+ n => n == 2,
542+ }
543+}
544+
545+/// Test-only override of [`stage_times`]; process-global.
546+#[cfg(test)]
547+pub(crate) fn set_stage_times(on: bool) {
548+ STAGE_ON.store(1 + usize::from(on), std::sync::atomic::Ordering::Relaxed);
549+}
550+
551+/// A live stage measurement: added to stage `i` when it drops. `None` when
552+/// the breakdown is off, so a call site is `let _t = par::timer(S_X);`.
553+pub(crate) struct Timer(usize, std::time::Instant);
554+
555+#[inline]
556+pub(crate) fn timer(i: usize) -> Option<Timer> {
557+ stage_times().then(|| Timer(i, std::time::Instant::now()))
558+}
559+
560+impl Drop for Timer {
561+ fn drop(&mut self) {
562+ STAGE_NS[self.0]
563+ .fetch_add(self.1.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
564+ }
565+}
566+
567+/// Takes and clears the breakdown, in [`STAGES`] order.
568+#[cfg(test)]
569+pub(crate) fn take_stage_ns() -> [u64; STAGES.len()] {
570+ std::array::from_fn(|i| STAGE_NS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
571+}