A frame's tiles are written in parallel on the crate's own pool
Browse files at this commit1878642195b77d1f9e3b987de4799f8f352777c6Parent: a01d142- feat
- a frame's tiles are written in parallel on the crate's own pool
5 changed files +141 -20
- crates/ec-av1/src/encode.rs +65 -17
- crates/ec-av1/src/encoder.rs +42 -0
- crates/ec-av1/src/par.rs +29 -0
- crates/ec-av1/src/stream.rs +2 -2
- tools/ec-bench/src/main.rs +3 -1
crates/ec-av1/src/encode.rsmodified+65 -17
| @@ -2794,6 +2794,53 @@ fn armed_tiles() -> (u32, u32) { | |||
| 2794 | TILE_LOG2.with(std::cell::Cell::get) | 2794 | TILE_LOG2.with(std::cell::Cell::get) |
| 2795 | } | 2795 | } |
| 2796 | 2796 | ||
| 2797 | +/// Codes a frame's `tiles` tiles, each entirely on its own (see | ||
| 2798 | +/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of | ||
| 2799 | +/// the crate's own pool, and hands back their payloads in tile order plus | ||
| 2800 | +/// whatever `code` returned for tile `store` -- the CDF state | ||
| 2801 | +/// `context_update_tile_id` names. The result cannot depend on the thread | ||
| 2802 | +/// count: each job writes one tile from the frame's own starting tables into | ||
| 2803 | +/// its own slot. | ||
| 2804 | +fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)> | ||
| 2805 | +where | ||
| 2806 | + F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send, | ||
| 2807 | +{ | ||
| 2808 | + type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>; | ||
| 2809 | + let threads = crate::par::tile_threads().min(tiles); | ||
| 2810 | + let mut slots: Vec<Slot> = Vec::new(); | ||
| 2811 | + if threads <= 1 { | ||
| 2812 | + for index in 0..tiles { | ||
| 2813 | + slots.push(Some(code(index))); | ||
| 2814 | + } | ||
| 2815 | + } else { | ||
| 2816 | + let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect()); | ||
| 2817 | + { | ||
| 2818 | + let batch = crate::par::Batch::new("ec-av1-tile"); | ||
| 2819 | + for (from, to) in crate::par::bands(tiles, threads) { | ||
| 2820 | + let done = &done; | ||
| 2821 | + let code = &code; | ||
| 2822 | + batch.submit(move || { | ||
| 2823 | + for index in from..to { | ||
| 2824 | + let coded = code(index); | ||
| 2825 | + done.lock().expect("tile slots")[index] = Some(coded); | ||
| 2826 | + } | ||
| 2827 | + }); | ||
| 2828 | + } | ||
| 2829 | + } | ||
| 2830 | + slots = done.into_inner().expect("tile slots"); | ||
| 2831 | + } | ||
| 2832 | + let mut out = Vec::with_capacity(tiles); | ||
| 2833 | + let mut stored = None; | ||
| 2834 | + for (index, slot) in slots.into_iter().enumerate() { | ||
| 2835 | + let (bytes, cdfs) = slot.expect("every tile was coded")?; | ||
| 2836 | + if index == store { | ||
| 2837 | + stored = cdfs; | ||
| 2838 | + } | ||
| 2839 | + out.push(bytes); | ||
| 2840 | + } | ||
| 2841 | + Ok((out, stored)) | ||
| 2842 | +} | ||
| 2843 | + | ||
| 2797 | /// The frame header's `tile_info` (spec 5.9.15) for `layout`: | 2844 | /// The frame header's `tile_info` (spec 5.9.15) for `layout`: |
| 2798 | /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF | 2845 | /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF |
| 2799 | /// tables the frame stores (spec 7.20), which is what | 2846 | /// tables the frame stores (spec 7.20), which is what |
| @@ -3281,12 +3328,11 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3281 | grid: &[u8], | 3328 | grid: &[u8], |
| 3282 | units: &[Option<crate::restoration::WienerInfo>]| | 3329 | units: &[Option<crate::restoration::WienerInfo>]| |
| 3283 | -> Result<Vec<Vec<u8>>> { | 3330 | -> Result<Vec<Vec<u8>>> { |
| 3284 | - let mut out = Vec::with_capacity(layout.count()); | 3331 | + let (out, _) = write_tiles(layout.count(), usize::MAX, |index| { |
| 3285 | - for index in 0..layout.count() { | ||
| 3286 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); | 3332 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 3287 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); | 3333 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 3288 | let mut cdfs = start_cdfs.0.clone(); | 3334 | let mut cdfs = start_cdfs.0.clone(); |
| 3289 | - out.push(crate::tile::sb_coeff_key_frame_tile_cdfs( | 3335 | + let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( |
| 3290 | mi_cols, | 3336 | mi_cols, |
| 3291 | mi_rows, | 3337 | mi_rows, |
| 3292 | base_q_idx, | 3338 | base_q_idx, |
| @@ -3294,8 +3340,9 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3294 | tx_select, | 3340 | tx_select, |
| 3295 | &mut cdfs, | 3341 | &mut cdfs, |
| 3296 | layout.rect(index), | 3342 | layout.rect(index), |
| 3297 | - )?); | 3343 | + )?; |
| 3298 | - } | 3344 | + Ok((bytes, None)) |
| 3345 | + })?; | ||
| 3299 | Ok(out) | 3346 | Ok(out) |
| 3300 | }; | 3347 | }; |
| 3301 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; | 3348 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| @@ -4881,18 +4928,18 @@ pub(crate) fn encode_inter_frame( | |||
| 4881 | cdef_grid: &[u8], | 4928 | cdef_grid: &[u8], |
| 4882 | units: &[Option<crate::restoration::WienerInfo>]| | 4929 | units: &[Option<crate::restoration::WienerInfo>]| |
| 4883 | -> Result<Vec<Vec<u8>>> { | 4930 | -> Result<Vec<Vec<u8>>> { |
| 4884 | - let mut out = Vec::with_capacity(layout.count()); | 4931 | + let (out, stored) = write_tiles(layout.count(), store_tile, |index| { |
| 4885 | - // One grid for the whole frame, carried from tile to tile (the | ||
| 4886 | - // decoder keeps exactly one too) and rebuilt from nothing on every | ||
| 4887 | - // re-code. | ||
| 4888 | - let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); | ||
| 4889 | - mv_grid.set_sign_bias(sign_bias); | ||
| 4890 | - for index in 0..layout.count() { | ||
| 4891 | crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); | 4932 | crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); |
| 4892 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); | 4933 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 4893 | crate::tile::arm_sign_bias(sign_bias); | 4934 | crate::tile::arm_sign_bias(sign_bias); |
| 4894 | let mut cdfs = start_cdfs.0.clone(); | 4935 | let mut cdfs = start_cdfs.0.clone(); |
| 4895 | - out.push(crate::tile::sb_coeff_inter_frame_tile_cdfs( | 4936 | + // Each tile's own MV grid: a candidate scan never reaches past |
| 4937 | + // the tile's bounds, so a grid holding only this tile's own | ||
| 4938 | + // blocks reads exactly as the decoder's frame-wide one does | ||
| 4939 | + // under `MiGrid::set_tile_bounds`. | ||
| 4940 | + let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); | ||
| 4941 | + mv_grid.set_sign_bias(sign_bias); | ||
| 4942 | + let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs( | ||
| 4896 | mi_cols, | 4943 | mi_cols, |
| 4897 | mi_rows, | 4944 | mi_rows, |
| 4898 | base_q_idx, | 4945 | base_q_idx, |
| @@ -4901,10 +4948,11 @@ pub(crate) fn encode_inter_frame( | |||
| 4901 | &mut cdfs, | 4948 | &mut cdfs, |
| 4902 | layout.rect(index), | 4949 | layout.rect(index), |
| 4903 | &mut mv_grid, | 4950 | &mut mv_grid, |
| 4904 | - )?); | 4951 | + )?; |
| 4905 | - if index == store_tile { | 4952 | + Ok((bytes, Some(cdfs))) |
| 4906 | - *end_cdfs.borrow_mut() = Some(cdfs); | 4953 | + })?; |
| 4907 | - } | 4954 | + if let Some(cdfs) = stored { |
| 4955 | + *end_cdfs.borrow_mut() = Some(cdfs); | ||
| 4908 | } | 4956 | } |
| 4909 | Ok(out) | 4957 | Ok(out) |
| 4910 | }; | 4958 | }; |
crates/ec-av1/src/encoder.rsmodified+42 -0
| @@ -1731,6 +1731,48 @@ mod tests { | |||
| 1731 | } | 1731 | } |
| 1732 | } | 1732 | } |
| 1733 | 1733 | ||
| 1734 | + /// The tiles of a frame are entropy-independent, so the bytes must not | ||
| 1735 | + /// depend on how many workers wrote them: the same stream at one tile | ||
| 1736 | + /// thread and at four, per layout. | ||
| 1737 | + #[test] | ||
| 1738 | + fn tile_bytes_do_not_depend_on_the_thread_count() { | ||
| 1739 | + let _gate_lock = crate::stream::tests::lock_gate_counters(); | ||
| 1740 | + let (width, height) = (320usize, 192usize); | ||
| 1741 | + let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect(); | ||
| 1742 | + let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { | ||
| 1743 | + crate::par::set_tile_threads(threads); | ||
| 1744 | + let config = EncoderConfig { | ||
| 1745 | + width, | ||
| 1746 | + height, | ||
| 1747 | + base_q_idx: 120, | ||
| 1748 | + gop: 3, | ||
| 1749 | + colour: Colour::Bt709Limited, | ||
| 1750 | + tile_cols_log2: cols_log2, | ||
| 1751 | + tile_rows_log2: rows_log2, | ||
| 1752 | + }; | ||
| 1753 | + let mut enc = Av1Encoder::new(config).unwrap(); | ||
| 1754 | + let mut stream = Vec::new(); | ||
| 1755 | + for picture in &sources { | ||
| 1756 | + stream.extend_from_slice(&enc.encode(picture).unwrap().data); | ||
| 1757 | + } | ||
| 1758 | + stream | ||
| 1759 | + }; | ||
| 1760 | + for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { | ||
| 1761 | + let one = coded(1, cols_log2, rows_log2); | ||
| 1762 | + let four = coded(4, cols_log2, rows_log2); | ||
| 1763 | + assert_eq!( | ||
| 1764 | + one, | ||
| 1765 | + four, | ||
| 1766 | + "{}x{} tiles: {} bytes at one thread, {} at four", | ||
| 1767 | + 1 << cols_log2, | ||
| 1768 | + 1 << rows_log2, | ||
| 1769 | + one.len(), | ||
| 1770 | + four.len() | ||
| 1771 | + ); | ||
| 1772 | + } | ||
| 1773 | + crate::par::set_tile_threads(1); | ||
| 1774 | + } | ||
| 1775 | + | ||
| 1734 | /// The same round trip at a real 1920x1080 crop of the gate's own clip | 1776 | /// The same round trip at a real 1920x1080 crop of the gate's own clip |
| 1735 | /// -- the size the editor's export actually runs at, where a tile grid | 1777 | /// -- the size the editor's export actually runs at, where a tile grid |
| 1736 | /// is worth having. Ignored by default only for its wall (a 1080p | 1778 | /// is worth having. Ignored by default only for its wall (a 1080p |
crates/ec-av1/src/par.rsmodified+29 -0
| @@ -55,6 +55,35 @@ pub(crate) fn set_filter_threads(n: usize) { | |||
| 55 | FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); | 55 | FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); |
| 56 | } | 56 | } |
| 57 | 57 | ||
| 58 | +/// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's | ||
| 59 | +/// tiles across (default 1 = the shipped single-threaded write). Tiles are | ||
| 60 | +/// entropy-independent by construction (each starts from the frame's own | ||
| 61 | +/// tables and resets its own contexts), so the bytes a frame comes out as do | ||
| 62 | +/// not depend on this -- `encoder::tests::tile_bytes_do_not_depend_on_the_ | ||
| 63 | +/// thread_count` is the pin. | ||
| 64 | +static TILE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | ||
| 65 | + | ||
| 66 | +pub(crate) fn tile_threads() -> usize { | ||
| 67 | + match TILE_THREADS.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 68 | + 0 => { | ||
| 69 | + let n = crate::envflags::var("EC_AV1_TILE_THREADS") | ||
| 70 | + .ok() | ||
| 71 | + .and_then(|v| v.trim().parse::<usize>().ok()) | ||
| 72 | + .unwrap_or(1) | ||
| 73 | + .clamp(1, 64); | ||
| 74 | + TILE_THREADS.store(n, std::sync::atomic::Ordering::Relaxed); | ||
| 75 | + n | ||
| 76 | + } | ||
| 77 | + n => n, | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// Test-only override of [`tile_threads`]; see [`set_filter_threads`]. | ||
| 82 | +#[cfg(test)] | ||
| 83 | +pub(crate) fn set_tile_threads(n: usize) { | ||
| 84 | + TILE_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); | ||
| 85 | +} | ||
| 86 | + | ||
| 58 | /// Splits `units` work units into at most `threads` contiguous, non-empty | 87 | /// Splits `units` work units into at most `threads` contiguous, non-empty |
| 59 | /// bands. The caller picks the unit so that a band boundary is always a legal | 88 | /// bands. The caller picks the unit so that a band boundary is always a legal |
| 60 | /// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one | 89 | /// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one |
crates/ec-av1/src/stream.rsmodified+2 -2
| @@ -1900,7 +1900,7 @@ pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) { | |||
| 1900 | } | 1900 | } |
| 1901 | 1901 | ||
| 1902 | #[cfg(test)] | 1902 | #[cfg(test)] |
| 1903 | -mod tests { | 1903 | +pub(crate) mod tests { |
| 1904 | use super::*; | 1904 | use super::*; |
| 1905 | use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx}; | 1905 | use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx}; |
| 1906 | 1906 | ||
| @@ -3131,7 +3131,7 @@ mod tests { | |||
| 3131 | ); | 3131 | ); |
| 3132 | } | 3132 | } |
| 3133 | 3133 | ||
| 3134 | - fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> { | 3134 | + pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> { |
| 3135 | GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()) | 3135 | GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()) |
| 3136 | } | 3136 | } |
| 3137 | 3137 | ||
tools/ec-bench/src/main.rsmodified+3 -1
| @@ -348,7 +348,9 @@ fn bench_av1_encode(rows: &mut Vec<Row>) { | |||
| 348 | // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` benches the encoder's tile | 348 | // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` benches the encoder's tile |
| 349 | // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1` | 349 | // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1` |
| 350 | // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones | 350 | // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones |
| 351 | - // the byte pins carry. | 351 | + // the byte pins carry. `EC_AV1_TILE_THREADS=<n>` (read by `ec_av1::par`) |
| 352 | + // spreads those tiles across `n` pool workers; the bytes are the same | ||
| 353 | + // either way, only the wall changes. | ||
| 352 | let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES") | 354 | let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES") |
| 353 | .ok() | 355 | .ok() |
| 354 | .and_then(|spec| { | 356 | .and_then(|spec| { |