forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into lane-av1comp2

Browse files at this commit

945005e337b3fd566b076c8128a8ca0bc2fc94f3Ahmet Kaan GümüşParent: bbdc307fe25c8d
crates/ec-av1/src/encode.rsmodified+213 -26
@@ -3360,6 +3360,103 @@ where
3360 Ok((out, stored))3360 Ok((out, stored))
3361 }3361 }
3362 3362
3363+/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
3364+/// workers, and returns the results in tile order. The counterpart of
3365+/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
3366+/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
3367+/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
3368+/// availability is already tile-relative (`clip_planes_to_tile`,
3369+/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
3370+/// other tiles have run -- gated by
3371+/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
3372+/// covers the search as well as the write.
3373+///
3374+/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
3375+/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
3376+/// does it for the decoder's filter bands.
3377+fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
3378+where
3379+ T: Send,
3380+ F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
3381+{
3382+ let threads = crate::par::tile_threads().min(tiles);
3383+ if threads <= 1 {
3384+ return (0..tiles).map(|index| job(index, fctx)).collect();
3385+ }
3386+ type Slot<T> = Option<Result<T>>;
3387+ let done: std::sync::Mutex<Vec<Slot<T>>> =
3388+ std::sync::Mutex::new((0..tiles).map(|_| None).collect());
3389+ {
3390+ let batch = crate::par::Batch::new("ec-av1-tile-search");
3391+ for (from, to) in crate::par::bands(tiles, threads) {
3392+ let done = &done;
3393+ let job = &job;
3394+ let ctx = crate::decode::filter_ctx_copy(fctx);
3395+ batch.submit(move || {
3396+ for index in from..to {
3397+ let searched = job(index, &ctx);
3398+ done.lock().expect("tile slots")[index] = Some(searched);
3399+ }
3400+ });
3401+ }
3402+ }
3403+ done.into_inner()
3404+ .expect("tile slots")
3405+ .into_iter()
3406+ .map(|slot| slot.expect("every tile was searched"))
3407+ .collect()
3408+}
3409+
3410+/// One tile job's own copy of a plane: the frame's source, a blank
3411+/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
3412+/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
3413+/// of the frame's reconstruction because a tile's prediction never reads a
3414+/// sample outside its own rectangle, and every sample inside it is written
3415+/// before it is read.
3416+fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
3417+ Plane {
3418+ source,
3419+ reconstruction: vec![128; source.len()],
3420+ width,
3421+ height,
3422+ true_width,
3423+ true_height,
3424+ tile_x0: 0,
3425+ tile_y0: 0,
3426+ tile_x1: width,
3427+ tile_y1: height,
3428+ }
3429+}
3430+
3431+/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
3432+/// the frame's plane, through the [`crate::par::Shared`] every job holds.
3433+///
3434+/// corner-cut: the disjointness that makes the aliasing sound is the caller's
3435+/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
3436+/// rectangles partition it -- checked end-to-end by
3437+/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
3438+/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
3439+/// row-range `split_at_mut` plumbing through `Plane`, which would have to
3440+/// thread an origin offset through every prediction and transform call site
3441+/// for the same bytes.
3442+#[allow(unsafe_code)]
3443+fn copy_rect(
3444+ dst: crate::par::Shared<'_, Vec<u8>>,
3445+ src: &[u8],
3446+ stride: usize,
3447+ x0: usize,
3448+ y0: usize,
3449+ x1: usize,
3450+ y1: usize,
3451+) {
3452+ // SAFETY: this job touches only its own tile rectangle (see above).
3453+ let dst = unsafe { dst.get() };
3454+ for y in y0..y1 {
3455+ let (a, b) = (y * stride + x0, y * stride + x1);
3456+ dst[a..b].copy_from_slice(&src[a..b]);
3457+ }
3458+}
3459+
3363 /// The frame header's `tile_info` (spec 5.9.15) for `layout`:3460 /// The frame header's `tile_info` (spec 5.9.15) for `layout`:
3364 /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF3461 /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
3365 /// tables the frame stores (spec 7.20), which is what3462 /// tables the frame stores (spec 7.20), which is what
@@ -3627,8 +3724,6 @@ pub(crate) fn encode_key_frame_inner(
3627 // symbol the writer will actually write.3724 // symbol the writer will actually write.
3628 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,3725 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
3629 // because a 32x32 block may be split into four 16x16 ones.3726 // because a 32x32 block may be split into four 16x16 ones.
3630- let mut above_mode = vec![DC_PRED; cols * 2];
3631- let mut left_mode = vec![DC_PRED; rows * 2];
3632 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));3727 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3633 // This frame's tile grid (one tile unless the facade armed more).3728 // This frame's tile grid (one tile unless the facade armed more).
3634 let layout =3729 let layout =
@@ -3639,15 +3734,36 @@ pub(crate) fn encode_key_frame_inner(
3639 // `mi_row_starts`), which is what makes the writer's rects and the3734 // `mi_row_starts`), which is what makes the writer's rects and the
3640 // reader's the same rects.3735 // reader's the same rects.
3641 let header_tile_info = header.tile_info.clone();3736 let header_tile_info = header.tile_info.clone();
3642- let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);3737+ // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
3643- let mut modes = Vec::with_capacity(cols * rows);3738+ // once over the whole frame. Each tile job builds its own reconstruction
3644- for sb_row in 0..sb_rows {3739+ // planes and its own `above_mode`/`left_mode` bands, which is also what
3645- for sb_col in 0..sb_cols {3740+ // the tile writer reads -- a tile resets its neighbour contexts (spec
3646- clip_planes_to_tile(3741+ // 5.11.1), so a block at a tile's left edge must cost its mode against
3647- &mut luma,3742+ // the default context, not against whatever the tile to its west left in
3648- &mut chroma,3743+ // that row. At one tile the bands are the frame's, exactly as before.
3649- layout.rect(layout.index_of_sb(sb_row as u32, sb_col as u32)),3744+ let (frame_width, frame_height) = (picture.width, picture.height);
3650- );3745+ let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
3746+ let [cb, cr] = &mut chroma;
3747+ let chroma_out = [
3748+ crate::par::Shared::new(&mut cb.reconstruction),
3749+ crate::par::Shared::new(&mut cr.reconstruction),
3750+ ];
3751+ let search_tile = |index: usize,
3752+ fctx: &crate::decode::FrameCtx|
3753+ -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
3754+ let rect = layout.rect(index);
3755+ let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
3756+ let mut chroma = [
3757+ fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
3758+ fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
3759+ ];
3760+ clip_planes_to_tile(&mut luma, &mut chroma, rect);
3761+ let mut above_mode = vec![DC_PRED; cols * 2];
3762+ let mut left_mode = vec![DC_PRED; rows * 2];
3763+ let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
3764+ for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
3765+ for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
3766+ let mut modes = Vec::with_capacity(4);
3651 // The quadrants of a superblock are coded in the order the decoder3767 // The quadrants of a superblock are coded in the order the decoder
3652 // walks them, which for a 64x64 split into 32x32 blocks is raster3768 // walks them, which for a 64x64 split into 32x32 blocks is raster
3653 // order among the quadrants that are inside the frame.3769 // order among the quadrants that are inside the frame.
@@ -3831,9 +3947,40 @@ pub(crate) fn encode_key_frame_inner(
3831 blocks.push(Quadrant::Whole(whole));3947 blocks.push(Quadrant::Whole(whole));
3832 }3948 }
3833 }3949 }
3834- superblocks.push(Superblock::Split(blocks));3950+ coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes));
3835 }3951 }
3836 }3952 }
3953+ let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
3954+ let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
3955+ copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
3956+ for (&out, tile) in chroma_out.iter().zip(&chroma) {
3957+ copy_rect(
3958+ out,
3959+ &tile.reconstruction,
3960+ frame_width / 2,
3961+ x0 / 2,
3962+ y0 / 2,
3963+ x1.div_ceil(2),
3964+ y1.div_ceil(2),
3965+ );
3966+ }
3967+ Ok(coded)
3968+ };
3969+ let searched = search_tiles(layout.count(), fctx, search_tile)?;
3970+ // Back into frame raster order: the tile writer indexes `superblocks` by
3971+ // the frame's own superblock index, and `modes` is the coding order the
3972+ // ablation drivers read.
3973+ let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
3974+ for (at, superblock, block_modes) in searched.into_iter().flatten() {
3975+ in_order[at] = Some((superblock, block_modes));
3976+ }
3977+ let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
3978+ let mut modes = Vec::with_capacity(cols * rows);
3979+ for slot in in_order {
3980+ let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
3981+ superblocks.push(superblock);
3982+ modes.extend_from_slice(&block_modes);
3983+ }
3837 3984
3838 #[cfg(test)]3985 #[cfg(test)]
3839 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));3986 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
@@ -5360,7 +5507,7 @@ pub(crate) fn encode_inter_frame(
5360 // whenever the true size is not a 64x64 multiple.5507 // whenever the true size is not a 64x64 multiple.
5361 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);5508 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
5362 let (cols, rows) = (cols as usize, rows as usize);5509 let (cols, rows) = (cols as usize, rows as usize);
5363- let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));5510+ let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
5364 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);5511 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
5365 // This frame's tile grid, as in `encode_key_frame_inner`.5512 // This frame's tile grid, as in `encode_key_frame_inner`.
5366 let (tile_cols_log2, tile_rows_log2) = armed_tiles();5513 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
@@ -5372,24 +5519,42 @@ pub(crate) fn encode_inter_frame(
5372 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --5519 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
5373 // once per frame (lane-av1rd2), not once per block, which is a whole5520 // once per frame (lane-av1rd2), not once per block, which is a whole
5374 // plane's map per 32x32 block and now per leaf too.5521 // plane's map per 32x32 block and now per leaf too.
5375- let mut grid = MiGrid::new(mi_cols, mi_rows);
5376- grid.set_sign_bias(sign_bias);
5377 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];5522 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
5378-5523+ // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
5379- for sb_r in 0..sb_rows {5524+ // availability -- intra edges and the MV stack's scans alike -- already
5380- for sb_c in 0..sb_cols {5525+ // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
5381- // Neighbour availability -- intra edges and the MV stack's5526+ // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
5382- // scans alike -- stops at this superblock's own tile, exactly5527+ // giving each job its own planes and its own `MiGrid` therefore leaves
5383- // where the decoder stops it (`PlaneBuf::set_tile_origin`,5528+ // every decision, and so every coded bit, exactly where the whole-frame
5384- // `MiGrid::set_tile_bounds`).5529+ // loop left it, at any tile count and any thread count.
5385- let rect = layout.rect(layout.index_of_sb(sb_r as u32, sb_c as u32));5530+ let (frame_width, frame_height) = (picture.width, picture.height);
5531+ let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
5532+ let [cb, cr] = &mut chroma;
5533+ let chroma_out = [
5534+ crate::par::Shared::new(&mut cb.reconstruction),
5535+ crate::par::Shared::new(&mut cr.reconstruction),
5536+ ];
5537+ let search_tile = |index: usize,
5538+ fctx: &crate::decode::FrameCtx|
5539+ -> Result<Vec<(usize, Quadrant)>> {
5540+ let rect = layout.rect(index);
5541+ let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
5542+ let mut chroma = [
5543+ fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
5544+ fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
5545+ ];
5386 clip_planes_to_tile(&mut luma, &mut chroma, rect);5546 clip_planes_to_tile(&mut luma, &mut chroma, rect);
5547+ let mut grid = MiGrid::new(mi_cols, mi_rows);
5548+ grid.set_sign_bias(sign_bias);
5387 grid.set_tile_bounds(5549 grid.set_tile_bounds(
5388 rect.mi_row0 as usize,5550 rect.mi_row0 as usize,
5389 rect.mi_col0 as usize,5551 rect.mi_col0 as usize,
5390 rect.mi_row1 as usize,5552 rect.mi_row1 as usize,
5391 rect.mi_col1 as usize,5553 rect.mi_col1 as usize,
5392 );5554 );
5555+ let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
5556+ for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
5557+ for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
5393 for quadrant in 0..4 {5558 for quadrant in 0..4 {
5394 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);5559 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
5395 // Same filter as the tile writer's: a quadrant whose own mi5560 // Same filter as the tile writer's: a quadrant whose own mi
@@ -5614,14 +5779,14 @@ pub(crate) fn encode_inter_frame(
5614 // grid, and their reconstruction is what the5779 // grid, and their reconstruction is what the
5615 // planes hold.5780 // planes hold.
5616 partition_hit(1);5781 partition_hit(1);
5617- blocks[r32 * cols + c32] = Quadrant::Split(leaves);5782+ blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
5618 continue;5783 continue;
5619 }5784 }
5620 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);5785 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
5621 }5786 }
5622 partition_hit(0);5787 partition_hit(0);
5623 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);5788 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);
5624- blocks[r32 * cols + c32] = Quadrant::Whole(block);5789+ blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
5625 } else {5790 } else {
5626 // The sub-positions actually inside the true frame, same5791 // The sub-positions actually inside the true frame, same
5627 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.5792 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
@@ -5786,11 +5951,33 @@ pub(crate) fn encode_inter_frame(
5786 });5951 });
5787 }5952 }
5788 }5953 }
5789- blocks[r32 * cols + c32] = Quadrant::Split(leaves);5954+ blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
5790 }5955 }
5791 }5956 }
5792 }5957 }
5793 }5958 }
5959+ let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
5960+ let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
5961+ copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
5962+ for (&out, tile) in chroma_out.iter().zip(&chroma) {
5963+ copy_rect(
5964+ out,
5965+ &tile.reconstruction,
5966+ frame_width / 2,
5967+ x0 / 2,
5968+ y0 / 2,
5969+ x1.div_ceil(2),
5970+ y1.div_ceil(2),
5971+ );
5972+ }
5973+ Ok(blocks)
5974+ };
5975+ for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
5976+ .into_iter()
5977+ .flatten()
5978+ {
5979+ blocks[at] = quadrant;
5980+ }
5794 5981
5795 let modes = blocks5982 let modes = blocks
5796 .iter()5983 .iter()
crates/ec-av1/src/encoder.rsmodified+165 -0
@@ -1839,6 +1839,171 @@ mod tests {
1839 crate::par::set_tile_threads(1);1839 crate::par::set_tile_threads(1);
1840 }1840 }
1841 1841
1842+ /// What the per-tile search (lane-av1tsearch) is worth in wall and in
1843+ /// frames per second at the editor's own export sizes: every tile layout
1844+ /// crossed with every tile-thread count, plus librav1e at the matching
1845+ /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes
1846+ /// over the whole table (A,B,A,B... rather than AA,BB) with the best of
1847+ /// the two kept, so a thermal drift cannot order the rows.
1848+ ///
1849+ /// Measurement, not a pass/fail gate: it asserts only that every cell
1850+ /// produced a stream.
1851+ #[test]
1852+ #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1853+ fn tile_search_wall_1080p() {
1854+ tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]);
1855+ }
1856+
1857+ /// The same table at the 4K frame size the editor exports (3840x1608),
1858+ /// at the two layouts with enough tiles to fill this box.
1859+ #[test]
1860+ #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1861+ fn tile_search_wall_4k() {
1862+ tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
1863+ }
1864+
1865+ fn tile_search_wall(
1866+ width: usize,
1867+ height: usize,
1868+ frames: usize,
1869+ layouts: &[(u32, u32)],
1870+ threads: &[usize],
1871+ ) {
1872+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1873+ let Some(sources) = h264_clip_frames(width, height, frames) else {
1874+ eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg");
1875+ return;
1876+ };
1877+ let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) {
1878+ crate::par::set_tile_threads(t);
1879+ let config = EncoderConfig {
1880+ width,
1881+ height,
1882+ base_q_idx: 120,
1883+ gop: frames,
1884+ colour: Colour::Bt709Limited,
1885+ tile_cols_log2: cols_log2,
1886+ tile_rows_log2: rows_log2,
1887+ };
1888+ let mut enc = Av1Encoder::new(config).unwrap();
1889+ let start = std::time::Instant::now();
1890+ let mut bytes = 0usize;
1891+ for picture in &sources {
1892+ bytes += enc.encode(picture).unwrap().data.len();
1893+ }
1894+ (start.elapsed(), bytes)
1895+ };
1896+ let cells: Vec<((u32, u32), usize)> = layouts
1897+ .iter()
1898+ .flat_map(|&l| threads.iter().map(move |&t| (l, t)))
1899+ .collect();
1900+ let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()];
1901+ for _pass in 0..2 {
1902+ for (i, &((c, r), t)) in cells.iter().enumerate() {
1903+ let got = run(c, r, t);
1904+ assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r);
1905+ if best[i].is_none_or(|(w, _)| got.0 < w) {
1906+ best[i] = Some(got);
1907+ }
1908+ }
1909+ }
1910+ crate::par::set_tile_threads(1);
1911+ eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes");
1912+ eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |");
1913+ let base = best[0].expect("the first cell ran").0.as_secs_f64();
1914+ for (i, &((c, r), t)) in cells.iter().enumerate() {
1915+ let (wall, bytes) = best[i].expect("every cell ran");
1916+ let secs = wall.as_secs_f64();
1917+ eprintln!(
1918+ "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |",
1919+ 1 << c,
1920+ 1 << r,
1921+ 1 << (c + r),
1922+ frames as f64 / secs,
1923+ base / secs,
1924+ );
1925+ }
1926+ // Parallel efficiency per layout: what the extra threads actually
1927+ // took off that layout's own single-threaded wall, and so what share
1928+ // of the added cores sat idle.
1929+ for &(c, r) in layouts {
1930+ let one = cells
1931+ .iter()
1932+ .position(|&(l, t)| l == (c, r) && t == threads[0])
1933+ .map(|i| best[i].expect("cell").0.as_secs_f64());
1934+ let Some(one) = one else { continue };
1935+ for &t in &threads[1..] {
1936+ let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell");
1937+ let secs = best[i].expect("cell").0.as_secs_f64();
1938+ let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64;
1939+ let speedup = one / secs;
1940+ eprintln!(
1941+ "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \
1942+ idle share {:.0}%",
1943+ 1 << c,
1944+ 1 << r,
1945+ threads[0],
1946+ 100.0 * (1.0 - speedup / workers).max(0.0),
1947+ );
1948+ }
1949+ }
1950+ rav1e_wall_reference(width, height, frames, layouts, threads);
1951+ }
1952+
1953+ /// librav1e at the same sizes, layouts and thread counts, through ffmpeg
1954+ /// -- the reference the wall table is read against.
1955+ fn rav1e_wall_reference(
1956+ width: usize,
1957+ height: usize,
1958+ frames: usize,
1959+ layouts: &[(u32, u32)],
1960+ threads: &[usize],
1961+ ) {
1962+ let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1963+ .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
1964+ let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output();
1965+ let has_rav1e = listed
1966+ .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
1967+ .unwrap_or(false);
1968+ if !has_rav1e || !clip.exists() {
1969+ eprintln!("SKIP the rav1e reference: no librav1e or no fixture");
1970+ return;
1971+ }
1972+ eprintln!("| rav1e layout | threads | wall | fps | bytes |");
1973+ for &(c, r) in layouts {
1974+ for &t in threads {
1975+ let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id()));
1976+ let params = format!(
1977+ "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}",
1978+ 1 << c,
1979+ 1 << r
1980+ );
1981+ let start = std::time::Instant::now();
1982+ let status = Command::new("ffmpeg")
1983+ .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])
1984+ .args(["-frames:v", &frames.to_string()])
1985+ .args(["-vf", &format!("scale={width}:{height}")])
1986+ .args(["-c:v", "librav1e", "-rav1e-params", &params])
1987+ .arg(out.to_str().unwrap())
1988+ .output()
1989+ .expect("ffmpeg failed to run");
1990+ let secs = start.elapsed().as_secs_f64();
1991+ if !status.status.success() {
1992+ eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or(""));
1993+ continue;
1994+ }
1995+ let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
1996+ let _ = std::fs::remove_file(&out);
1997+ eprintln!(
1998+ "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |",
1999+ 1 << c,
2000+ 1 << r,
2001+ frames as f64 / secs
2002+ );
2003+ }
2004+ }
2005+ }
2006+
1842 /// The same round trip at a real 1920x1080 crop of the gate's own clip2007 /// The same round trip at a real 1920x1080 crop of the gate's own clip
1843 /// -- the size the editor's export actually runs at, where a tile grid2008 /// -- the size the editor's export actually runs at, where a tile grid
1844 /// is worth having. Ignored by default only for its wall (a 1080p2009 /// is worth having. Ignored by default only for its wall (a 1080p
crates/ec-av1/src/par.rsmodified+14 -4
@@ -56,11 +56,21 @@ pub(crate) fn set_filter_threads(n: usize) {
56 }56 }
57 57
58 /// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's58 /// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's
59-/// tiles across (default 1 = the shipped single-threaded write). Tiles are59+/// tiles across -- both the RD/motion SEARCH (`encode::search_tiles`) and the
60-/// entropy-independent by construction (each starts from the frame's own60+/// entropy WRITE (`encode::write_tiles`); default 1 = the shipped
61-/// tables and resets its own contexts), so the bytes a frame comes out as do61+/// single-threaded encode. Tiles are independent by construction (each starts
62-/// not depend on this -- `encoder::tests::tile_bytes_do_not_depend_on_the_62+/// from the frame's own tables, resets its own contexts, and reads no sample
63+/// and no mode outside its own rectangle), so the bytes a frame comes out as
64+/// do not depend on this -- `encoder::tests::tile_bytes_do_not_depend_on_the_
63 /// thread_count` is the pin.65 /// thread_count` is the pin.
66+///
67+/// Measured (lane-av1tsearch, 12-core box, best of two interleaved passes):
68+/// 1920x1080, 12 frames -- 11.49 s at one tile (any thread count), 6.98 s at
69+/// 4x2 tiles and 8 threads (1.65x, 1.04 -> 1.72 fps); 3840x1608, 6 frames --
70+/// 17.12 s at 4x2 tiles and one thread, 8.64 s at 8 (1.98x, 0.35 -> 0.69
71+/// fps). Past ~8 tiles the extra tiles cost bytes without buying wall: what
72+/// is left is the per-frame serial tail (the filter search re-decodes the
73+/// whole frame), ~43% of an inter frame by Amdahl on those numbers.
64 static TILE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);74 static TILE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
65 75
66 pub(crate) fn tile_threads() -> usize {76 pub(crate) fn tile_threads() -> usize {
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).