forge
Explore
Log in

Don't you dare go Hollow

The RD/motion search runs per tile, on the tile thread pool

Browse files at this commit

8421ce2227e75c469b6eb3ab1d014b36ca129c1eAhmet Kaan GümüşParent: b58ff3f
  • perf
    • the RD/motion search runs per tile, on the tile thread pool
Show full message
perf(av1): the RD/motion search runs per tile, on the tile thread pool

The frame's superblock loop was one whole-frame pass in raster order even
when the frame carried a tile grid; only the entropy write was split
(lane-av1tiles), which is why tile threads bought nothing measurable.

Both search loops now run one job per tile through `search_tiles`, the
search-side counterpart of `write_tiles`: each job owns its own
reconstruction planes, its own `MiGrid`, its own neighbour-mode bands and
its own `FrameCtx`, and copies its rectangle back into the frame's planes
at the end. Availability was already tile-relative, so a tile reads
nothing another tile wrote.

Inter frames are byte-identical to the whole-frame loop at every layout.
Key frames change at MULTI-TILE layouts only: the mode-cost bands are now
tile-local, which is what the tile writer actually reads back (a tile
resets its neighbour contexts, spec 5.11.1) -- the old frame-scoped bands
let a block at a tile's left edge cost its mode against the tile to its
west. One tile is unchanged, and the byte pins hold.
crates/ec-av1/src/encode.rsmodified+213 -26
@@ -3060,6 +3060,103 @@ where
3060 Ok((out, stored))3060 Ok((out, stored))
3061 }3061 }
3062 3062
3063+/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
3064+/// workers, and returns the results in tile order. The counterpart of
3065+/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
3066+/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
3067+/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
3068+/// availability is already tile-relative (`clip_planes_to_tile`,
3069+/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
3070+/// other tiles have run -- gated by
3071+/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
3072+/// covers the search as well as the write.
3073+///
3074+/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
3075+/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
3076+/// does it for the decoder's filter bands.
3077+fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
3078+where
3079+ T: Send,
3080+ F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
3081+{
3082+ let threads = crate::par::tile_threads().min(tiles);
3083+ if threads <= 1 {
3084+ return (0..tiles).map(|index| job(index, fctx)).collect();
3085+ }
3086+ type Slot<T> = Option<Result<T>>;
3087+ let done: std::sync::Mutex<Vec<Slot<T>>> =
3088+ std::sync::Mutex::new((0..tiles).map(|_| None).collect());
3089+ {
3090+ let batch = crate::par::Batch::new("ec-av1-tile-search");
3091+ for (from, to) in crate::par::bands(tiles, threads) {
3092+ let done = &done;
3093+ let job = &job;
3094+ let ctx = crate::decode::filter_ctx_copy(fctx);
3095+ batch.submit(move || {
3096+ for index in from..to {
3097+ let searched = job(index, &ctx);
3098+ done.lock().expect("tile slots")[index] = Some(searched);
3099+ }
3100+ });
3101+ }
3102+ }
3103+ done.into_inner()
3104+ .expect("tile slots")
3105+ .into_iter()
3106+ .map(|slot| slot.expect("every tile was searched"))
3107+ .collect()
3108+}
3109+
3110+/// One tile job's own copy of a plane: the frame's source, a blank
3111+/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
3112+/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
3113+/// of the frame's reconstruction because a tile's prediction never reads a
3114+/// sample outside its own rectangle, and every sample inside it is written
3115+/// before it is read.
3116+fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
3117+ Plane {
3118+ source,
3119+ reconstruction: vec![128; source.len()],
3120+ width,
3121+ height,
3122+ true_width,
3123+ true_height,
3124+ tile_x0: 0,
3125+ tile_y0: 0,
3126+ tile_x1: width,
3127+ tile_y1: height,
3128+ }
3129+}
3130+
3131+/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
3132+/// the frame's plane, through the [`crate::par::Shared`] every job holds.
3133+///
3134+/// corner-cut: the disjointness that makes the aliasing sound is the caller's
3135+/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
3136+/// rectangles partition it -- checked end-to-end by
3137+/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
3138+/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
3139+/// row-range `split_at_mut` plumbing through `Plane`, which would have to
3140+/// thread an origin offset through every prediction and transform call site
3141+/// for the same bytes.
3142+#[allow(unsafe_code)]
3143+fn copy_rect(
3144+ dst: crate::par::Shared<'_, Vec<u8>>,
3145+ src: &[u8],
3146+ stride: usize,
3147+ x0: usize,
3148+ y0: usize,
3149+ x1: usize,
3150+ y1: usize,
3151+) {
3152+ // SAFETY: this job touches only its own tile rectangle (see above).
3153+ let dst = unsafe { dst.get() };
3154+ for y in y0..y1 {
3155+ let (a, b) = (y * stride + x0, y * stride + x1);
3156+ dst[a..b].copy_from_slice(&src[a..b]);
3157+ }
3158+}
3159+
3063 /// The frame header's `tile_info` (spec 5.9.15) for `layout`:3160 /// The frame header's `tile_info` (spec 5.9.15) for `layout`:
3064 /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF3161 /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
3065 /// tables the frame stores (spec 7.20), which is what3162 /// tables the frame stores (spec 7.20), which is what
@@ -3314,8 +3411,6 @@ pub(crate) fn encode_key_frame_inner(
3314 // symbol the writer will actually write.3411 // symbol the writer will actually write.
3315 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,3412 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
3316 // because a 32x32 block may be split into four 16x16 ones.3413 // because a 32x32 block may be split into four 16x16 ones.
3317- let mut above_mode = vec![DC_PRED; cols * 2];
3318- let mut left_mode = vec![DC_PRED; rows * 2];
3319 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));3414 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3320 // This frame's tile grid (one tile unless the facade armed more).3415 // This frame's tile grid (one tile unless the facade armed more).
3321 let layout =3416 let layout =
@@ -3326,15 +3421,36 @@ pub(crate) fn encode_key_frame_inner(
3326 // `mi_row_starts`), which is what makes the writer's rects and the3421 // `mi_row_starts`), which is what makes the writer's rects and the
3327 // reader's the same rects.3422 // reader's the same rects.
3328 let header_tile_info = header.tile_info.clone();3423 let header_tile_info = header.tile_info.clone();
3329- let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);3424+ // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
3330- let mut modes = Vec::with_capacity(cols * rows);3425+ // once over the whole frame. Each tile job builds its own reconstruction
3331- for sb_row in 0..sb_rows {3426+ // planes and its own `above_mode`/`left_mode` bands, which is also what
3332- for sb_col in 0..sb_cols {3427+ // the tile writer reads -- a tile resets its neighbour contexts (spec
3333- clip_planes_to_tile(3428+ // 5.11.1), so a block at a tile's left edge must cost its mode against
3334- &mut luma,3429+ // the default context, not against whatever the tile to its west left in
3335- &mut chroma,3430+ // that row. At one tile the bands are the frame's, exactly as before.
3336- layout.rect(layout.index_of_sb(sb_row as u32, sb_col as u32)),3431+ let (frame_width, frame_height) = (picture.width, picture.height);
3337- );3432+ let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
3433+ let [cb, cr] = &mut chroma;
3434+ let chroma_out = [
3435+ crate::par::Shared::new(&mut cb.reconstruction),
3436+ crate::par::Shared::new(&mut cr.reconstruction),
3437+ ];
3438+ let search_tile = |index: usize,
3439+ fctx: &crate::decode::FrameCtx|
3440+ -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
3441+ let rect = layout.rect(index);
3442+ let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
3443+ let mut chroma = [
3444+ fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
3445+ fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
3446+ ];
3447+ clip_planes_to_tile(&mut luma, &mut chroma, rect);
3448+ let mut above_mode = vec![DC_PRED; cols * 2];
3449+ let mut left_mode = vec![DC_PRED; rows * 2];
3450+ let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
3451+ for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
3452+ for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
3453+ let mut modes = Vec::with_capacity(4);
3338 // The quadrants of a superblock are coded in the order the decoder3454 // The quadrants of a superblock are coded in the order the decoder
3339 // walks them, which for a 64x64 split into 32x32 blocks is raster3455 // walks them, which for a 64x64 split into 32x32 blocks is raster
3340 // order among the quadrants that are inside the frame.3456 // order among the quadrants that are inside the frame.
@@ -3518,9 +3634,40 @@ pub(crate) fn encode_key_frame_inner(
3518 blocks.push(Quadrant::Whole(whole));3634 blocks.push(Quadrant::Whole(whole));
3519 }3635 }
3520 }3636 }
3521- superblocks.push(Superblock::Split(blocks));3637+ coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes));
3522 }3638 }
3523 }3639 }
3640+ let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
3641+ let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
3642+ copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
3643+ for (&out, tile) in chroma_out.iter().zip(&chroma) {
3644+ copy_rect(
3645+ out,
3646+ &tile.reconstruction,
3647+ frame_width / 2,
3648+ x0 / 2,
3649+ y0 / 2,
3650+ x1.div_ceil(2),
3651+ y1.div_ceil(2),
3652+ );
3653+ }
3654+ Ok(coded)
3655+ };
3656+ let searched = search_tiles(layout.count(), fctx, search_tile)?;
3657+ // Back into frame raster order: the tile writer indexes `superblocks` by
3658+ // the frame's own superblock index, and `modes` is the coding order the
3659+ // ablation drivers read.
3660+ let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
3661+ for (at, superblock, block_modes) in searched.into_iter().flatten() {
3662+ in_order[at] = Some((superblock, block_modes));
3663+ }
3664+ let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
3665+ let mut modes = Vec::with_capacity(cols * rows);
3666+ for slot in in_order {
3667+ let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
3668+ superblocks.push(superblock);
3669+ modes.extend_from_slice(&block_modes);
3670+ }
3524 3671
3525 #[cfg(test)]3672 #[cfg(test)]
3526 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));3673 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
@@ -4952,7 +5099,7 @@ pub(crate) fn encode_inter_frame(
4952 // whenever the true size is not a 64x64 multiple.5099 // whenever the true size is not a 64x64 multiple.
4953 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);5100 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
4954 let (cols, rows) = (cols as usize, rows as usize);5101 let (cols, rows) = (cols as usize, rows as usize);
4955- let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));5102+ let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
4956 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);5103 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
4957 // This frame's tile grid, as in `encode_key_frame_inner`.5104 // This frame's tile grid, as in `encode_key_frame_inner`.
4958 let (tile_cols_log2, tile_rows_log2) = armed_tiles();5105 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
@@ -4964,24 +5111,42 @@ pub(crate) fn encode_inter_frame(
4964 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --5111 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
4965 // once per frame (lane-av1rd2), not once per block, which is a whole5112 // once per frame (lane-av1rd2), not once per block, which is a whole
4966 // plane's map per 32x32 block and now per leaf too.5113 // plane's map per 32x32 block and now per leaf too.
4967- let mut grid = MiGrid::new(mi_cols, mi_rows);
4968- grid.set_sign_bias(sign_bias);
4969 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];5114 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
4970-5115+ // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
4971- for sb_r in 0..sb_rows {5116+ // availability -- intra edges and the MV stack's scans alike -- already
4972- for sb_c in 0..sb_cols {5117+ // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
4973- // Neighbour availability -- intra edges and the MV stack's5118+ // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
4974- // scans alike -- stops at this superblock's own tile, exactly5119+ // giving each job its own planes and its own `MiGrid` therefore leaves
4975- // where the decoder stops it (`PlaneBuf::set_tile_origin`,5120+ // every decision, and so every coded bit, exactly where the whole-frame
4976- // `MiGrid::set_tile_bounds`).5121+ // loop left it, at any tile count and any thread count.
4977- let rect = layout.rect(layout.index_of_sb(sb_r as u32, sb_c as u32));5122+ let (frame_width, frame_height) = (picture.width, picture.height);
5123+ let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
5124+ let [cb, cr] = &mut chroma;
5125+ let chroma_out = [
5126+ crate::par::Shared::new(&mut cb.reconstruction),
5127+ crate::par::Shared::new(&mut cr.reconstruction),
5128+ ];
5129+ let search_tile = |index: usize,
5130+ fctx: &crate::decode::FrameCtx|
5131+ -> Result<Vec<(usize, Quadrant)>> {
5132+ let rect = layout.rect(index);
5133+ let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
5134+ let mut chroma = [
5135+ fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
5136+ fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
5137+ ];
4978 clip_planes_to_tile(&mut luma, &mut chroma, rect);5138 clip_planes_to_tile(&mut luma, &mut chroma, rect);
5139+ let mut grid = MiGrid::new(mi_cols, mi_rows);
5140+ grid.set_sign_bias(sign_bias);
4979 grid.set_tile_bounds(5141 grid.set_tile_bounds(
4980 rect.mi_row0 as usize,5142 rect.mi_row0 as usize,
4981 rect.mi_col0 as usize,5143 rect.mi_col0 as usize,
4982 rect.mi_row1 as usize,5144 rect.mi_row1 as usize,
4983 rect.mi_col1 as usize,5145 rect.mi_col1 as usize,
4984 );5146 );
5147+ let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
5148+ for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
5149+ for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
4985 for quadrant in 0..4 {5150 for quadrant in 0..4 {
4986 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);5151 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
4987 // Same filter as the tile writer's: a quadrant whose own mi5152 // Same filter as the tile writer's: a quadrant whose own mi
@@ -5206,14 +5371,14 @@ pub(crate) fn encode_inter_frame(
5206 // grid, and their reconstruction is what the5371 // grid, and their reconstruction is what the
5207 // planes hold.5372 // planes hold.
5208 partition_hit(1);5373 partition_hit(1);
5209- blocks[r32 * cols + c32] = Quadrant::Split(leaves);5374+ blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
5210 continue;5375 continue;
5211 }5376 }
5212 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);5377 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
5213 }5378 }
5214 partition_hit(0);5379 partition_hit(0);
5215 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);5380 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);
5216- blocks[r32 * cols + c32] = Quadrant::Whole(block);5381+ blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
5217 } else {5382 } else {
5218 // The sub-positions actually inside the true frame, same5383 // The sub-positions actually inside the true frame, same
5219 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.5384 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
@@ -5378,11 +5543,33 @@ pub(crate) fn encode_inter_frame(
5378 });5543 });
5379 }5544 }
5380 }5545 }
5381- blocks[r32 * cols + c32] = Quadrant::Split(leaves);5546+ blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
5382 }5547 }
5383 }5548 }
5384 }5549 }
5385 }5550 }
5551+ let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
5552+ let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
5553+ copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
5554+ for (&out, tile) in chroma_out.iter().zip(&chroma) {
5555+ copy_rect(
5556+ out,
5557+ &tile.reconstruction,
5558+ frame_width / 2,
5559+ x0 / 2,
5560+ y0 / 2,
5561+ x1.div_ceil(2),
5562+ y1.div_ceil(2),
5563+ );
5564+ }
5565+ Ok(blocks)
5566+ };
5567+ for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
5568+ .into_iter()
5569+ .flatten()
5570+ {
5571+ blocks[at] = quadrant;
5572+ }
5386 5573
5387 let modes = blocks5574 let modes = blocks
5388 .iter()5575 .iter()
crates/ec-av1/src/tile.rsmodified+0 -9
@@ -238,15 +238,6 @@ impl TileLayout {
238 }238 }
239 }239 }
240 240
241- /// Which tile the superblock at `(sb_r, sb_c)` belongs to -- what the
242- /// encoder's frame-raster search consults to clip a block's neighbour
243- /// availability to its own tile.
244- pub(crate) fn index_of_sb(&self, sb_r: u32, sb_c: u32) -> usize {
245- let col = self.col_starts_sb[1..].partition_point(|&s| s <= sb_c);
246- let row = self.row_starts_sb[1..].partition_point(|&s| s <= sb_r);
247- row * self.cols() as usize + col
248- }
249-
250 /// The largest tile by mi area, `context_update_tile_id`'s own rule241 /// The largest tile by mi area, `context_update_tile_id`'s own rule
251 /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both242 /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both
252 /// name the biggest tile, whose end-of-tile tables the frame stores).243 /// name the biggest tile, whose end-of-tile tables the frame stores).