diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index f0e554b6..0621a971 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -2794,6 +2794,53 @@ fn armed_tiles() -> (u32, u32) { TILE_LOG2.with(std::cell::Cell::get) } +/// Codes a frame's `tiles` tiles, each entirely on its own (see +/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of +/// the crate's own pool, and hands back their payloads in tile order plus +/// whatever `code` returned for tile `store` -- the CDF state +/// `context_update_tile_id` names. The result cannot depend on the thread +/// count: each job writes one tile from the frame's own starting tables into +/// its own slot. +fn write_tiles(tiles: usize, store: usize, code: F) -> Result<(Vec>, Option)> +where + F: Fn(usize) -> Result<(Vec, Option)> + Sync + Send, +{ + type Slot = Option, Option)>>; + let threads = crate::par::tile_threads().min(tiles); + let mut slots: Vec = Vec::new(); + if threads <= 1 { + for index in 0..tiles { + slots.push(Some(code(index))); + } + } else { + let done: std::sync::Mutex> = std::sync::Mutex::new((0..tiles).map(|_| None).collect()); + { + let batch = crate::par::Batch::new("ec-av1-tile"); + for (from, to) in crate::par::bands(tiles, threads) { + let done = &done; + let code = &code; + batch.submit(move || { + for index in from..to { + let coded = code(index); + done.lock().expect("tile slots")[index] = Some(coded); + } + }); + } + } + slots = done.into_inner().expect("tile slots"); + } + let mut out = Vec::with_capacity(tiles); + let mut stored = None; + for (index, slot) in slots.into_iter().enumerate() { + let (bytes, cdfs) = slot.expect("every tile was coded")?; + if index == store { + stored = cdfs; + } + out.push(bytes); + } + Ok((out, stored)) +} + /// The frame header's `tile_info` (spec 5.9.15) for `layout`: /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF /// tables the frame stores (spec 7.20), which is what @@ -3281,12 +3328,11 @@ pub(crate) fn encode_key_frame_inner( grid: &[u8], units: &[Option]| -> Result>> { - let mut out = Vec::with_capacity(layout.count()); - for index in 0..layout.count() { + let (out, _) = write_tiles(layout.count(), usize::MAX, |index| { crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); let mut cdfs = start_cdfs.0.clone(); - out.push(crate::tile::sb_coeff_key_frame_tile_cdfs( + let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( mi_cols, mi_rows, base_q_idx, @@ -3294,8 +3340,9 @@ pub(crate) fn encode_key_frame_inner( tx_select, &mut cdfs, layout.rect(index), - )?); - } + )?; + Ok((bytes, None)) + })?; Ok(out) }; let mut tiles = code_tiles(0, sb_cols, &[], &[])?; @@ -4881,18 +4928,18 @@ pub(crate) fn encode_inter_frame( cdef_grid: &[u8], units: &[Option]| -> Result>> { - let mut out = Vec::with_capacity(layout.count()); - // One grid for the whole frame, carried from tile to tile (the - // decoder keeps exactly one too) and rebuilt from nothing on every - // re-code. - let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); - mv_grid.set_sign_bias(sign_bias); - for index in 0..layout.count() { + let (out, stored) = write_tiles(layout.count(), store_tile, |index| { crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); crate::tile::arm_sign_bias(sign_bias); let mut cdfs = start_cdfs.0.clone(); - out.push(crate::tile::sb_coeff_inter_frame_tile_cdfs( + // Each tile's own MV grid: a candidate scan never reaches past + // the tile's bounds, so a grid holding only this tile's own + // blocks reads exactly as the decoder's frame-wide one does + // under `MiGrid::set_tile_bounds`. + let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); + mv_grid.set_sign_bias(sign_bias); + let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs( mi_cols, mi_rows, base_q_idx, @@ -4901,10 +4948,11 @@ pub(crate) fn encode_inter_frame( &mut cdfs, layout.rect(index), &mut mv_grid, - )?); - if index == store_tile { - *end_cdfs.borrow_mut() = Some(cdfs); - } + )?; + Ok((bytes, Some(cdfs))) + })?; + if let Some(cdfs) = stored { + *end_cdfs.borrow_mut() = Some(cdfs); } Ok(out) }; diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 0eb2941b..09bbe66a 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -1731,6 +1731,48 @@ mod tests { } } + /// The tiles of a frame are entropy-independent, so the bytes must not + /// depend on how many workers wrote them: the same stream at one tile + /// thread and at four, per layout. + #[test] + fn tile_bytes_do_not_depend_on_the_thread_count() { + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let (width, height) = (320usize, 192usize); + let sources: Vec = (0..3).map(|t| test_card(width, height, t * 3)).collect(); + let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { + crate::par::set_tile_threads(threads); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 3, + colour: Colour::Bt709Limited, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + for picture in &sources { + stream.extend_from_slice(&enc.encode(picture).unwrap().data); + } + stream + }; + for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { + let one = coded(1, cols_log2, rows_log2); + let four = coded(4, cols_log2, rows_log2); + assert_eq!( + one, + four, + "{}x{} tiles: {} bytes at one thread, {} at four", + 1 << cols_log2, + 1 << rows_log2, + one.len(), + four.len() + ); + } + crate::par::set_tile_threads(1); + } + /// The same round trip at a real 1920x1080 crop of the gate's own clip /// -- the size the editor's export actually runs at, where a tile grid /// is worth having. Ignored by default only for its wall (a 1080p diff --git a/crates/ec-av1/src/par.rs b/crates/ec-av1/src/par.rs index e16ac1d1..ae9681c6 100644 --- a/crates/ec-av1/src/par.rs +++ b/crates/ec-av1/src/par.rs @@ -55,6 +55,35 @@ pub(crate) fn set_filter_threads(n: usize) { FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); } +/// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's +/// tiles across (default 1 = the shipped single-threaded write). Tiles are +/// entropy-independent by construction (each starts from the frame's own +/// tables and resets its own contexts), so the bytes a frame comes out as do +/// not depend on this -- `encoder::tests::tile_bytes_do_not_depend_on_the_ +/// thread_count` is the pin. +static TILE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub(crate) fn tile_threads() -> usize { + match TILE_THREADS.load(std::sync::atomic::Ordering::Relaxed) { + 0 => { + let n = crate::envflags::var("EC_AV1_TILE_THREADS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(1) + .clamp(1, 64); + TILE_THREADS.store(n, std::sync::atomic::Ordering::Relaxed); + n + } + n => n, + } +} + +/// Test-only override of [`tile_threads`]; see [`set_filter_threads`]. +#[cfg(test)] +pub(crate) fn set_tile_threads(n: usize) { + TILE_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); +} + /// Splits `units` work units into at most `threads` contiguous, non-empty /// bands. The caller picks the unit so that a band boundary is always a legal /// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 381638d7..56316bde 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1900,7 +1900,7 @@ pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx}; @@ -3131,7 +3131,7 @@ mod tests { ); } - fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> { + pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> { GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()) } diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index 247872d5..ca2dabce 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -348,7 +348,9 @@ fn bench_av1_encode(rows: &mut Vec) { // `EC_AV1_TILES=[:]` benches the encoder's tile // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1` // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones - // the byte pins carry. + // the byte pins carry. `EC_AV1_TILE_THREADS=` (read by `ec_av1::par`) + // spreads those tiles across `n` pool workers; the bytes are the same + // either way, only the wall changes. let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES") .ok() .and_then(|spec| {