diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 0a5f91f9..fb589431 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -20763,18 +20763,61 @@ pub(crate) fn decode_key_frame_tile_lr( lr: &LoopRestorationParams, fctx: &crate::decode::FrameCtx, ) -> Result { - let delta = DeltaParams::default(); let single_tile = TileInfo { mi_col_starts: vec![0, mi_cols], mi_row_starts: vec![0, mi_rows], ..TileInfo::default() }; - decode_key_frame_tile_with_cdfs( + decode_key_frame_tiles_lr( &[data], &single_tile, mi_cols, mi_rows, base_q_idx, + frame_width, + frame_height, + enable_filter_intra, + cdef, + loop_filter, + tx_select, + reduced_tx_set, + allow_screen_content_tools, + allow_intrabc, + lr, + fctx, + ) +} + +/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the +/// encoder's own filter search hands back one payload per tile plus the +/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets +/// are the decoder's own (`decode_key_frame_tile_with_cdfs`). +#[allow(clippy::too_many_arguments)] +pub(crate) fn decode_key_frame_tiles_lr( + tiles: &[&[u8]], + tile_info: &TileInfo, + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + frame_width: u32, + frame_height: u32, + enable_filter_intra: bool, + cdef: &CdefParams, + loop_filter: &LoopFilterParams, + tx_select: bool, + reduced_tx_set: bool, + allow_screen_content_tools: bool, + allow_intrabc: bool, + lr: &LoopRestorationParams, + fctx: &crate::decode::FrameCtx, +) -> Result { + let delta = DeltaParams::default(); + decode_key_frame_tile_with_cdfs( + tiles, + tile_info, + mi_cols, + mi_rows, + base_q_idx, crate::quant::QuantDeltas::default(), frame_width, frame_height, @@ -25394,6 +25437,7 @@ fn decode_inter_block( // combinations that don't implement scaled MC yet. frame_width: usize, fctx: &crate::decode::FrameCtx, ) -> Result<()> { + // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the // few 16-px-granular uses below. @@ -32945,12 +32989,65 @@ pub(crate) fn decode_inter_frame_tile_lr( mi_row_starts: vec![0, mi_rows], ..TileInfo::default() }; - decode_inter_frame_tile_with_cdfs( + decode_inter_frame_tiles_lr( &[data], &single_tile, mi_cols, mi_rows, base_q_idx, + frame_width, + frame_height, + refpix, + cdef, + loop_filter, + allow_high_precision_mv, + force_integer_mv, + interp_fixed, + enable_dual_filter, + reference_select, + tx_select, + lr, + initial_cdfs, + sign_bias, + allow_screen_content_tools, + fctx, + ) +} + +/// [`decode_inter_frame_tile_lr`] for a frame coded as SEVERAL tiles; see +/// [`decode_key_frame_tiles_lr`]. +#[allow(clippy::too_many_arguments)] +pub(crate) fn decode_inter_frame_tiles_lr( + tiles: &[&[u8]], + tile_info: &TileInfo, + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + frame_width: u32, + frame_height: u32, + refpix: &RefPix<'_>, + cdef: &CdefParams, + loop_filter: &LoopFilterParams, + allow_high_precision_mv: bool, + force_integer_mv: bool, + interp_fixed: Option, + enable_dual_filter: bool, + reference_select: bool, + tx_select: bool, + lr: &LoopRestorationParams, + initial_cdfs: Option, + sign_bias: crate::mvstack::SignBiasTable, + // This frame header's own `allow_screen_content_tools` (see the + // single-tile wrapper): the palette syntax its intra blocks carry. + allow_screen_content_tools: bool, + fctx: &crate::decode::FrameCtx, +) -> Result { + decode_inter_frame_tile_with_cdfs( + tiles, + tile_info, + mi_cols, + mi_rows, + base_q_idx, crate::quant::QuantDeltas::default(), frame_width, frame_height, diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 26353fed..ae79ebdf 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1110,9 +1110,28 @@ struct Plane<'a> { /// edge. true_width: usize, true_height: usize, + /// This plane's own tile's pixel bounds, in this plane's units -- the + /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra + /// prediction never reaches across a tile edge even though the + /// neighbouring tile's real samples sit right there in the shared + /// reconstruction. `(0, 0, width, height)` is the single-tile case and + /// leaves every edge exactly as it was before tiles existed. + tile_x0: usize, + tile_y0: usize, + tile_x1: usize, + tile_y1: usize, } impl Plane<'_> { + /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]), + /// called at every superblock of the frame-raster search with the rect + /// of the tile that superblock belongs to. + fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) { + self.tile_x0 = x0; + self.tile_y0 = y0; + self.tile_x1 = x1.min(self.width); + self.tile_y1 = y1.min(self.height); + } /// The reconstructed samples a block at `(x, y)` predicts from: the row /// above it, the column to its left and the sample between them, each /// missing where the block sits against an edge of the frame. @@ -1164,14 +1183,17 @@ impl Plane<'_> { // `a_picture_off_the_block_grid_is_refused`), never through a block // this encoder actually commits. Such a block has no true-edge // samples above or left of it at all, same as `y == 0`/`x == 0`. - let above = (y > 0 && across > x) + let across = across.min(self.tile_x1); + let down = down.min(self.tile_y1); + let above = (y > self.tile_y0 && across > x) .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec()); - let left = (x > 0 && down > y).then(|| { + let left = (x > self.tile_x0 && down > y).then(|| { (y..down) .map(|row| self.reconstruction[row * self.width + x - 1]) .collect::>() }); - let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]); + let corner = (x > self.tile_x0 && y > self.tile_y0) + .then(|| self.reconstruction[(y - 1) * self.width + x - 1]); (above, left, corner) } @@ -3241,6 +3263,126 @@ fn coeffs(levels: &[i32], side: usize) -> Vec { .collect() } +thread_local! { + /// The tile grid the next frame is coded with, as `(TileColsLog2, + /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its + /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s + /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is + /// one tile per frame, what every caller that never arms anything gets + /// and what every stream this crate wrote before tiles existed carries. + static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) }; +} + +/// Arms this thread's next frame encodes with a tile grid (log2 counts). +pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) { + TILE_LOG2.with(|c| c.set((cols_log2, rows_log2))); +} + +fn armed_tiles() -> (u32, u32) { + let armed = TILE_LOG2.with(std::cell::Cell::get); + if armed != (0, 0) { + return armed; + } + // `EC_AV1_TILES=[:]` in a TEST build, so the BD gate + // (which codes through `encode_sequence`, not the facade) can measure what + // a tile grid costs without a knob of its own -- same shape as + // `EC_AV1_LR`/`EC_AV1_PYRAMID`. + match std::env::var("EC_AV1_TILES").ok() { + Some(v) if cfg!(test) => { + let mut f = v.split(':'); + let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0); + let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0); + (cols, rows) + } + _ => armed, + } +} + +/// 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 +/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops +/// below publish. +fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo { + ec_av1_syntax::TileInfo { + uniform_spacing: true, + cols: layout.cols(), + rows: layout.rows(), + cols_log2: layout.cols_log2, + rows_log2: layout.rows_log2, + mi_col_starts: layout.mi_col_starts(), + mi_row_starts: layout.mi_row_starts(), + context_update_tile_id: layout.largest_tile() as u32, + tile_size_bytes, + } +} + +/// Clips the three planes' intra edge reads to `rect`, the tile the +/// superblock about to be searched belongs to (the encoder side of the +/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame +/// raster order -- which is a linear extension of every tile's own coding +/// order, so a block still only ever predicts from samples already +/// reconstructed -- and only availability is tile-relative. +fn clip_planes_to_tile( + luma: &mut Plane<'_>, + chroma: &mut [Plane<'_>; 2], + rect: crate::tile::TileRect, +) { + let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); + let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); + luma.set_tile(x0, y0, x1, y1); + for plane in chroma.iter_mut() { + plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2)); + } +} + /// Encodes one picture as a key frame. /// /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer @@ -3393,6 +3535,7 @@ pub(crate) fn encode_key_frame_inner( if tx_select { header.tx_mode = TxMode::Select; } + let (tile_cols_log2, tile_rows_log2) = armed_tiles(); // Prediction reads no further than this, in each plane's own units -- // see `Plane::true_width`/`true_height`. @@ -3411,6 +3554,10 @@ pub(crate) fn encode_key_frame_inner( height: picture.height, true_width, true_height, + tile_x0: 0, + tile_y0: 0, + tile_x1: picture.width, + tile_y1: picture.height, }; let mut chroma = [ Plane { @@ -3420,6 +3567,10 @@ pub(crate) fn encode_key_frame_inner( height: picture.height / 2, true_width: true_width / 2, true_height: true_height / 2, + tile_x0: 0, + tile_y0: 0, + tile_x1: picture.width / 2, + tile_y1: picture.height / 2, }, Plane { source: &picture_v8, @@ -3428,6 +3579,10 @@ pub(crate) fn encode_key_frame_inner( height: picture.height / 2, true_width: true_width / 2, true_height: true_height / 2, + tile_x0: 0, + tile_y0: 0, + tile_x1: picture.width / 2, + tile_y1: picture.height / 2, }, ]; @@ -3460,10 +3615,24 @@ pub(crate) fn encode_key_frame_inner( let mut above_mode = vec![DC_PRED; cols * 2]; let mut left_mode = vec![DC_PRED; rows * 2]; let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); + // This frame's tile grid (one tile unless the facade armed more). + let layout = + crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); + header.tile_info = tile_info_of(&layout, 1); + // The filter search re-decodes this frame's tiles; the decoder derives + // every tile's own rect from this same `tile_info` (its `mi_col_starts`/ + // `mi_row_starts`), which is what makes the writer's rects and the + // reader's the same rects. + let header_tile_info = header.tile_info.clone(); let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); let mut modes = Vec::with_capacity(cols * rows); for sb_row in 0..sb_rows { for sb_col in 0..sb_cols { + clip_planes_to_tile( + &mut luma, + &mut chroma, + layout.rect(layout.index_of_sb(sb_row as u32, sb_col as u32)), + ); // The quadrants of a superblock are coded in the order the decoder // walks them, which for a 64x64 split into 32x32 blocks is raster // order among the quadrants that are inside the frame. @@ -3659,58 +3828,66 @@ pub(crate) fn encode_key_frame_inner( // defaults again (spec 7.20's `started_from` arm) -- the first inter // frame after it therefore starts from the defaults too. let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); - let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); - let start_cdfs = CdfSnapshot(cdfs.clone()); - crate::tile::arm_screen(screen); - let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs( - mi_cols, - mi_rows, - base_q_idx, - &superblocks, - tx_select, - &mut cdfs, - )?; - // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing - // the tile just coded back to the decoder under each candidate (see - // `crate::filter_search`), and keep the filtered picture that wins as - // the reconstruction -- what a decoder outputs, and what the next - // frame predicts from. + let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); + let start_cdfs = CdfSnapshot(cdfs); // The luma restoration-unit grid this frame's `lr_params` implies // (`av1_lr_count_units` rounds to nearest, so a short last unit is // swallowed by the one before it), for the tile writer's own per-unit // walk. let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; + // Every tile is coded from this frame's OWN starting tables and leaves + // its own end state behind (spec 5.11.1: each tile resets the CDFs, the + // loop-restoration reference and its neighbour contexts), so the tiles + // are independent of each other and of the order they are written in. + let code_tiles = |bits: u8, + sb_cols: usize, + grid: &[u8], + units: &[Option]| + -> Result>> { + 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(); + crate::tile::arm_screen(screen); + let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( + mi_cols, + mi_rows, + base_q_idx, + &superblocks, + tx_select, + &mut cdfs, + layout.rect(index), + )?; + Ok((bytes, None)) + })?; + Ok(out) + }; + let mut tiles = code_tiles(0, sb_cols, &[], &[])?; + // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing + // the tile just coded back to the decoder under each candidate (see + // `crate::filter_search`), and keep the filtered picture that wins as + // the reconstruction -- what a decoder outputs, and what the next + // frame predicts from. pick_and_apply_filters( &mut header, &mut luma, &mut chroma, [&picture_y8, &picture_u8, &picture_v8], true, - &mut tile, + &mut tiles, search.lambda, fctx, // Every re-code starts from this frame's OWN starting tables, never // from where the first write left them: the second tile is the same // symbol sequence plus new ones, so it must adapt from the same // point the decoder will. - |bits, sb_cols, grid, units| { - 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(); - crate::tile::arm_screen(screen); - crate::tile::sb_coeff_key_frame_tile_cdfs( - mi_cols, - mi_rows, - base_q_idx, - &superblocks, - tx_select, - &mut cdfs, - ) - }, - |lf, cdef, h, tile, lr| { - crate::decode::decode_key_frame_tile_lr( - tile, + |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), + |lf, cdef, h, tiles: &[Vec], lr| { + let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); + crate::decode::decode_key_frame_tiles_lr( + &payloads, + &header_tile_info, h.mi_cols, h.mi_rows, base_q_idx, @@ -3728,6 +3905,9 @@ pub(crate) fn encode_key_frame_inner( ) }, )?; + let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); + header.tile_info.tile_size_bytes = tile_size_bytes; + let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); let mut stream = temporal_delimiter(); stream.extend_from_slice(&sequence_header_obu(&seq)?); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); @@ -3778,19 +3958,25 @@ fn pick_and_apply_filters( chroma: &mut [Plane<'_>; 2], source: [&[u8]; 3], search: bool, - // The coded tile, replaced in place when the search chooses a per-64x64 - // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile - // payload, so the tile is written a second time under `recode` and the - // winner re-decoded from it. - tile: &mut Vec, + // The coded tiles, one payload per tile of the frame's grid, replaced in + // place when the search chooses a per-64x64 `cdef_idx` list + // (`cdef_bits > 0`): those literals live in the tile payloads, so every + // tile is written a second time under `recode` and the winner + // re-decoded from them. + tiles: &mut Vec>, lambda: f64, fctx: &crate::decode::FrameCtx, - recode: impl Fn(u8, usize, &[u8], &[Option]) -> Result>, + recode: impl Fn( + u8, + usize, + &[u8], + &[Option], + ) -> Result>>, decode: impl Fn( &LoopFilterParams, &CdefParams, &FrameHeader, - &[u8], + &[Vec], &LoopRestorationParams, ) -> Result, ) -> Result<()> { @@ -3817,7 +4003,7 @@ fn pick_and_apply_filters( return Ok(picture); } crate::decode::arm_filter_replay(); - decode(lf, cdef, &hdr, tile, &none_lr) + decode(lf, cdef, &hdr, tiles, &none_lr) }, source, luma.width, @@ -3848,14 +4034,14 @@ fn pick_and_apply_filters( fctx.capture_stages.set(lr_on); let mut filtered = if idx_grid.is_empty() { if lr_on { - decode(&lf, &cdef, &hdr, tile, &none_lr)? + decode(&lf, &cdef, &hdr, tiles, &none_lr)? } else { picture } } else { let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?; let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?; - *tile = coded; + *tiles = coded; picture }; fctx.capture_stages.set(false); @@ -3886,7 +4072,7 @@ fn pick_and_apply_filters( if units.iter().any(Option::is_some) { let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; filtered = decode(&lf, &cdef, &hdr, &coded, &want)?; - *tile = coded; + *tiles = coded; lr = want; } } @@ -5026,6 +5212,10 @@ pub(crate) fn encode_inter_frame( height: picture.height, true_width, true_height, + tile_x0: 0, + tile_y0: 0, + tile_x1: picture.width, + tile_y1: picture.height, }; let mut chroma = [ Plane { @@ -5035,6 +5225,10 @@ pub(crate) fn encode_inter_frame( height: picture.height / 2, true_width: true_width / 2, true_height: true_height / 2, + tile_x0: 0, + tile_y0: 0, + tile_x1: picture.width / 2, + tile_y1: picture.height / 2, }, Plane { source: &picture_v8, @@ -5043,6 +5237,10 @@ pub(crate) fn encode_inter_frame( height: picture.height / 2, true_width: true_width / 2, true_height: true_height / 2, + tile_x0: 0, + tile_y0: 0, + tile_x1: picture.width / 2, + tile_y1: picture.height / 2, }, ]; @@ -5066,6 +5264,12 @@ pub(crate) fn encode_inter_frame( let (cols, rows) = (cols as usize, rows as usize); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); + // This frame's tile grid, as in `encode_key_frame_inner`. + let (tile_cols_log2, tile_rows_log2) = armed_tiles(); + let layout = + crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); + header.tile_info = tile_info_of(&layout, 1); + let header_tile_info = header.tile_info.clone(); // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is // integer-`u8`-scale), so the DPB reference plane is narrowed for it -- // once per frame (lane-av1rd2), not once per block, which is a whole @@ -5076,6 +5280,18 @@ pub(crate) fn encode_inter_frame( for sb_r in 0..sb_rows { for sb_c in 0..sb_cols { + // Neighbour availability -- intra edges and the MV stack's + // scans alike -- stops at this superblock's own tile, exactly + // where the decoder stops it (`PlaneBuf::set_tile_origin`, + // `MiGrid::set_tile_bounds`). + let rect = layout.rect(layout.index_of_sb(sb_r as u32, sb_c as u32)); + clip_planes_to_tile(&mut luma, &mut chroma, rect); + grid.set_tile_bounds( + rect.mi_row0 as usize, + rect.mi_col0 as usize, + rect.mi_row1 as usize, + rect.mi_col1 as usize, + ); for quadrant in 0..4 { let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); // Same filter as the tile writer's: a quadrant whose own mi @@ -5502,22 +5718,59 @@ pub(crate) fn encode_inter_frame( // next frame's writer starts from them -- exactly what // `crate::stream::stored_cdfs_for` hands the decoder. let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); - let mut cdfs = start_cdfs + let cdfs = start_cdfs .cloned() .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); - let start_cdfs = CdfSnapshot(cdfs.clone()); - crate::tile::arm_sign_bias(sign_bias); - crate::tile::arm_reference_select(header.reference_select); - crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); - crate::tile::arm_screen(screen); - let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs( - mi_cols, - mi_rows, - base_q_idx, - &blocks, - tx_select, - &mut cdfs, - )?; + let start_cdfs = CdfSnapshot(cdfs); + let reference_select_bit = header.reference_select; + let order_hint_bits = seq.order_hint_bits; + let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; + let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; + // What this frame stores is the LARGEST tile's end-of-tile tables -- + // its own header's `context_update_tile_id` (spec 7.20), which + // `tile_info_of` set to exactly that tile. + let store_tile = layout.largest_tile(); + let end_cdfs = std::cell::RefCell::new(None); + // As in `encode_key_frame_inner`: every tile starts from this frame's + // own tables, so no tile depends on any other. + let code_tiles = |bits: u8, + sb_cols: usize, + cdef_grid: &[u8], + units: &[Option]| + -> Result>> { + 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); + // Thread-locals: every tile job arms its own worker. + crate::tile::arm_reference_select(reference_select_bit); + crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); + crate::tile::arm_screen(screen); + let mut cdfs = start_cdfs.0.clone(); + // 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, + &blocks, + tx_select, + &mut cdfs, + layout.rect(index), + &mut mv_grid, + )?; + Ok((bytes, Some(cdfs))) + })?; + if let Some(cdfs) = stored { + *end_cdfs.borrow_mut() = Some(cdfs); + } + Ok(out) + }; + let mut tiles = code_tiles(0, sb_cols, &[], &[])?; // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs // this tile against the same single-slot reference this encoder predicted // from, under each candidate level. @@ -5526,7 +5779,6 @@ pub(crate) fn encode_inter_frame( // reference whose height is not the header's own `frame_height` (spec // 7.9's compatible-size rule), and the chained-decode round trips prove // the two predict identically. - let end_cdfs = std::cell::RefCell::new(cdfs); let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); let trial_ref = if (reference.width, reference.height) == (fw, fh) { reference.clone() @@ -5573,12 +5825,6 @@ pub(crate) fn encode_inter_frame( refs[4] = trial_golden.as_ref(); refs[7] = trial_altref.as_ref(); let refpix = crate::decode::RefPix::ready(refs); - // The luma restoration-unit grid this frame's `lr_params` implies - // (`av1_lr_count_units` rounds to nearest, so a short last unit is - // swallowed by the one before it), for the tile writer's own per-unit - // walk. - let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; - let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; pick_and_apply_filters( &mut header, &mut luma, @@ -5589,37 +5835,19 @@ pub(crate) fn encode_inter_frame( // `TxMode::Select` too (it used to skip and leave every inter frame // unfiltered once Select became the default). true, - &mut tile, + &mut tiles, search.lambda, fctx, // As in `encode_key_frame_inner`, but this frame's end-of-tile tables // are what the NEXT frame writes from, so the winning re-code // publishes its own into `end_cdfs` -- the first write's are stale // the moment a second tile is coded. - |bits, sb_cols, grid, units| { - crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); - crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); - crate::tile::arm_sign_bias(sign_bias); - crate::tile::arm_reference_select(reference_select()); - crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); - crate::tile::arm_screen(screen); - let mut cdfs = start_cdfs.0.clone(); - let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs( - mi_cols, - mi_rows, - base_q_idx, - &blocks, - tx_select, - &mut cdfs, - ); - if coded.is_ok() { - *end_cdfs.borrow_mut() = cdfs; - } - coded - }, - |lf, cdef, h, tile, lr| { - crate::decode::decode_inter_frame_tile_lr( - tile, + |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), + |lf, cdef, h, tiles: &[Vec], lr| { + let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); + crate::decode::decode_inter_frame_tiles_lr( + &payloads, + &header_tile_info, h.mi_cols, h.mi_rows, base_q_idx, @@ -5645,9 +5873,14 @@ pub(crate) fn encode_inter_frame( ) }, )?; - let mut cdfs = end_cdfs.into_inner(); + let mut cdfs = end_cdfs + .into_inner() + .unwrap_or_else(|| start_cdfs.0.clone()); cdfs.reset_counts(); let next_cdfs = CdfSnapshot(cdfs); + let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); + header.tile_info.tile_size_bytes = tile_size_bytes; + let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); let mut stream = temporal_delimiter(); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); @@ -8660,6 +8893,8 @@ mod tests { base_q_idx: q, gop: source.len(), colour: Colour::Unspecified, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let start = std::time::Instant::now(); let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 18ebd61d..459ea325 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -276,6 +276,32 @@ pub struct EncoderConfig { pub gop: usize, /// The colour the sequence header signals. pub colour: Colour, + /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 << + /// tile_cols_log2` uniformly spaced tile columns, each coded and + /// decodable on its own. `0` -- one tile column -- is the default and + /// is byte for byte the stream this encoder wrote before tiles existed. + pub tile_cols_log2: u32, + /// `TileRowsLog2`, the same down the rows. + pub tile_rows_log2: u32, +} + +impl EncoderConfig { + /// A config at `width`x`height` with one tile, `gop` pictures between + /// key frames and no colour signalling -- what every caller that does + /// not care about tiles writes, so that adding a field here does not + /// rewrite them. + #[must_use] + pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self { + Self { + width, + height, + base_q_idx, + gop, + colour, + tile_cols_log2: 0, + tile_rows_log2: 0, + } + } } /// One coded picture: its OBUs, in the order a demuxer that just wants bytes @@ -510,6 +536,22 @@ impl Av1Encoder { // do, before the first `encode()` call rather than only surfacing it // then. Picture::grey(config.width, config.height).check_even()?; + // A tile is a whole number of superblocks, so a frame cannot carry + // more tile columns (rows) than it has 64x64 superblocks across + // (down) -- the header's own `max_log2_tile_cols` bound (spec + // 5.9.15), refused here rather than at the first `encode()` call. + let sb_cols = config.width.div_ceil(64) as u32; + let sb_rows = config.height.div_ceil(64) as u32; + if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows { + return Err(Error::unsupported( + "AV1 encode", + format!( + "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has", + 1 << config.tile_cols_log2, + 1 << config.tile_rows_log2 + ), + )); + } Ok(Self { carried_cdfs: None, golden: None, @@ -632,6 +674,7 @@ impl Av1Encoder { /// # Errors /// As [`Av1Encoder::encode`], minus the pyramid refusal. pub fn encode_frames(&mut self, picture: &Picture) -> Result> { + crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); if (picture.width, picture.height) != (self.config.width, self.config.height) { return Err(Error::unsupported( "AV1 encode", @@ -671,6 +714,7 @@ impl Av1Encoder { /// # Errors /// As [`Av1Encoder::encode_frames`]. pub fn flush(&mut self) -> Result> { + crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); self.drain_pending() } @@ -1029,6 +1073,8 @@ mod tests { base_q_idx: 100, gop: 2, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); for t in 0..5u64 { @@ -1049,6 +1095,8 @@ mod tests { base_q_idx: 100, gop: 3, colour: Colour::Unspecified, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let keys: Vec = (0..7) @@ -1147,6 +1195,8 @@ mod tests { base_q_idx: 120, gop: 15, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); assert_eq!(enc.display_size(), (width, height)); @@ -1200,6 +1250,8 @@ mod tests { base_q_idx: 100, gop: 4, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); @@ -1222,6 +1274,8 @@ mod tests { base_q_idx: 100, gop: 4, colour: Colour::Bt601Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); @@ -1242,6 +1296,8 @@ mod tests { base_q_idx: 100, gop: 4, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); @@ -1257,6 +1313,8 @@ mod tests { base_q_idx: 100, gop: 0, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let err = Av1Encoder::new(config).unwrap_err(); assert!(err.to_string().contains("gop"), "{err}"); @@ -1328,6 +1386,8 @@ mod tests { base_q_idx: 100, gop: 24, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); @@ -1367,6 +1427,8 @@ mod tests { base_q_idx: 100, gop: frames, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let rate = RateTarget::Bitrate { bits_per_second, @@ -1424,6 +1486,8 @@ mod tests { base_q_idx: 100, gop: 24, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); @@ -1499,13 +1563,15 @@ mod tests { /// display-order list and fails here. #[test] fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { - let (width, height) = (128usize, 64usize); + let (width, height) = (128usize, 128usize); let config = EncoderConfig { width, height, base_q_idx: 120, gop: 32, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let pyramid = Pyramid { mini_gop: 4, @@ -1586,6 +1652,246 @@ mod tests { } } + /// Every tile layout this encoder can write decodes SAMPLE-EXACT + /// through both decoders -- ours and ffmpeg's -- and the frames really + /// carry the tiles the header claims (the OBU parser locates one payload + /// per tile, so a stream that quietly stayed single-tile fails here + /// rather than passing on a green round trip). + /// + /// The bytes are what the gate is on: an encoder that clipped its + /// neighbour availability wrong writes a stream whose two decoders agree + /// with each other and disagree with nothing -- so the ffmpeg half is + /// the one that catches a tile boundary the writer respected and the + /// spec does not, and the parser half catches the reverse. + #[test] + fn every_tile_layout_decodes_sample_exact_through_both_decoders() { + let (width, height) = (640usize, 384usize); + let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); + let mut sizes = Vec::new(); + for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, + }; + let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + for (i, picture) in sources.iter().enumerate() { + let packet = enc + .encode(picture) + .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}")); + stream.extend_from_slice(&packet.data); + } + sizes.push((layout.clone(), stream.len())); + + // The frames carry the tiles their headers claim. + let mut parser = ec_av1_syntax::Av1Parser::new(); + let mut frames = 0usize; + let mut offset = 0usize; + while offset < stream.len() { + let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); + let unit: usize = obus.iter().map(|o| o.total_size).sum(); + for obu in &obus { + if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { + assert_eq!( + (parsed.tile_info.cols, parsed.tile_info.rows), + (1 << cols_log2, 1 << rows_log2), + "{layout}: the header's own tile grid" + ); + assert_eq!( + tiles.len(), + 1 << (cols_log2 + rows_log2), + "{layout}: tile payloads located in the tile group" + ); + frames += 1; + } + } + offset += unit; + } + assert_eq!(frames, sources.len(), "{layout}: coded frames"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg"); + continue; + } + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); + } + } + } + let base = sizes[0].1 as f64; + for (layout, bytes) in &sizes { + eprintln!( + "{layout}: {bytes} bytes ({:+.2}% vs one tile)", + (*bytes as f64 / base - 1.0) * 100.0 + ); + } + } + + /// What tiles and tile threads are worth at the size the editor exports + /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall + /// per cell. Ignored by default (minutes). + #[test] + #[ignore = "1080p wall table: minutes, run it with --ignored"] + fn tile_wall_table_at_1080p() { + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let (width, height) = (1920usize, 1080usize); + let Some(sources) = h264_clip_frames(width, height, 8) else { + eprintln!("SKIP tile_wall_table_at_1080p: no fixture"); + return; + }; + let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)]; + let threadings = [1usize, 2, 4, 8]; + let mut table: Vec<(String, usize, f64, usize)> = Vec::new(); + for pass in 0..2 { + for &(cols_log2, rows_log2) in &layouts { + for &threads in &threadings { + crate::par::set_tile_threads(threads); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let start = std::time::Instant::now(); + let mut bytes = 0usize; + for picture in &sources { + bytes += enc.encode(picture).unwrap().data.len(); + } + let wall = start.elapsed().as_secs_f64(); + let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2); + match table.iter_mut().find(|r| r.0 == name && r.1 == threads) { + Some(row) => row.2 = row.2.min(wall), + None => table.push((name, threads, wall, bytes)), + } + let _ = pass; + } + } + } + crate::par::set_tile_threads(1); + eprintln!("| tiles | threads | wall (s, best of 2) | bytes |"); + for (name, threads, wall, bytes) in &table { + eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |"); + } + } + + /// 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 + /// encode of three pictures), not for any weakness in the check. + #[test] + #[ignore = "1080p encode: minutes, run it with --ignored"] + fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { + let (width, height) = (1920usize, 1080usize); + let Some(sources) = h264_clip_frames(width, height, 3) else { + eprintln!("SKIP the 1080p tile round trip: no fixture"); + return; + }; + for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { + 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 layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + for (i, picture) in sources.iter().enumerate() { + let packet = enc + .encode(picture) + .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}")); + stream.extend_from_slice(&packet.data); + } + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg"); + continue; + } + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "1080p {layout} frame {i}: luma differs first at ({}, {})", + at % width, + at / width + ); + } + } + eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); + } + } + /// [`RateTarget::Quality`] is monotone: a higher quality dial never /// produces a smaller stream or a worse mean PSNR than a lower one, on /// the same real clip. @@ -1609,6 +1915,8 @@ mod tests { base_q_idx: 100, gop: 8, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let mut enc = Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); diff --git a/crates/ec-av1/src/frame.rs b/crates/ec-av1/src/frame.rs index 8c56ff98..911cba0c 100644 --- a/crates/ec-av1/src/frame.rs +++ b/crates/ec-av1/src/frame.rs @@ -644,6 +644,47 @@ pub fn show_existing_frame_obu(seq: &SequenceHeader, frame_to_show_map_idx: u8) )) } +/// How wide a tile group's per-tile size field has to be for these tiles +/// (`TileSizeBytes`, spec 5.11.1: every non-last tile carries `size - 1` in +/// that many bytes, so the widest of them decides). +pub(crate) fn tile_size_bytes_for(tiles: &[Vec]) -> u32 { + let widest = tiles + .iter() + .rev() + .skip(1) + .map(|t| t.len().saturating_sub(1)) + .max() + .unwrap_or(0); + match widest { + 0..=0xFF => 1, + 0x100..=0xFFFF => 2, + 0x1_0000..=0xFF_FFFF => 3, + _ => 4, + } +} + +/// `tile_group_obu()` (spec 5.11.1) for a group holding every tile of the +/// frame: `tile_start_and_end_present_flag = 0` (only coded when the frame +/// has more than one tile), byte alignment, then each tile's size (all but +/// the last, little endian, `tile_size_bytes` wide) ahead of its payload. +/// One tile leaves the payload exactly as it was, which is what every +/// single-tile stream this crate wrote before tiles existed carries. +pub(crate) fn tile_group_payload(tiles: &[Vec], tile_size_bytes: u32) -> Vec { + if tiles.len() == 1 { + return tiles[0].clone(); + } + // The flag bit plus `byte_alignment()`: one zero byte. + let mut out = vec![0u8]; + for (i, tile) in tiles.iter().enumerate() { + if i + 1 < tiles.len() { + let size = (tile.len() - 1) as u32; + out.extend((0..tile_size_bytes).map(|b| (size >> (8 * b)) as u8)); + } + out.extend_from_slice(tile); + } + out +} + /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group /// payload the caller supplies. pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result> { 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 35daaa47..bebdcd5d 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}; @@ -3136,7 +3136,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/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 46b06f80..d50629cd 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -116,6 +116,150 @@ fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32) /// `crate::decode`), the span [`write_lr`] resolves its units over. const SB_MI_W: u32 = 16; +/// One tile's own superblock and mode-info span (spec 5.11.1's tile loop +/// bounds): `MiColStarts[i]..MiColStarts[i+1]` and the same down the rows, +/// with the superblock indices those mi bounds fall on. The writers walk +/// exactly this rect, and everything a block reads outside it -- the +/// neighbour bands, the MV grid -- is left at the "unavailable" state a +/// tile's own first row and column see, which is how the decoder clips them +/// (`MiGrid::set_tile_bounds`, `PlaneBuf::set_tile_origin`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct TileRect { + pub(crate) sb_col0: u32, + pub(crate) sb_col1: u32, + pub(crate) sb_row0: u32, + pub(crate) sb_row1: u32, + pub(crate) mi_col0: u32, + pub(crate) mi_col1: u32, + pub(crate) mi_row0: u32, + pub(crate) mi_row1: u32, +} + +impl TileRect { + /// The whole frame as one tile -- what every single-tile caller writes. + pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self { + let (cols, rows) = block_grid(mi_cols, mi_rows); + Self { + sb_col0: 0, + sb_col1: cols.div_ceil(2), + sb_row0: 0, + sb_row1: rows.div_ceil(2), + mi_col0: 0, + mi_col1: mi_cols, + mi_row0: 0, + mi_row1: mi_rows, + } + } +} + +/// A frame's uniform tile grid (spec 5.9.15's `uniform_tile_spacing_flag` +/// arm, mirrored from `ec_av1_syntax::frame::read_tile_info` so that what +/// this encoder writes and what a decoder derives from the same two log2 +/// fields are the same rects). 64x64 superblocks only, which is the only +/// size this encoder's sequence header signals. +#[derive(Clone, Debug)] +pub(crate) struct TileLayout { + pub(crate) cols_log2: u32, + pub(crate) rows_log2: u32, + /// Tile column starts in superblocks, `cols + 1` entries. + col_starts_sb: Vec, + /// Tile row starts in superblocks, `rows + 1` entries. + row_starts_sb: Vec, + mi_cols: u32, + mi_rows: u32, +} + +impl TileLayout { + /// The layout `cols_log2`/`rows_log2` name for this frame's mi grid. + pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self { + let (cols32, rows32) = block_grid(mi_cols, mi_rows); + let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2)); + let starts = |total: u32, log2: u32| { + let step = total.div_ceil(1 << log2).max(1); + let mut v: Vec = (0..total).step_by(step as usize).collect(); + v.push(total); + v + }; + Self { + cols_log2, + rows_log2, + col_starts_sb: starts(sb_cols, cols_log2), + row_starts_sb: starts(sb_rows, rows_log2), + mi_cols, + mi_rows, + } + } + + pub(crate) fn cols(&self) -> u32 { + self.col_starts_sb.len() as u32 - 1 + } + + pub(crate) fn rows(&self) -> u32 { + self.row_starts_sb.len() as u32 - 1 + } + + pub(crate) fn count(&self) -> usize { + (self.cols() * self.rows()) as usize + } + + /// `MiColStarts`/`MiRowStarts` as the frame header carries them. + pub(crate) fn mi_col_starts(&self) -> Vec { + let mut v: Vec = self.col_starts_sb[..self.cols() as usize] + .iter() + .map(|sb| sb * SB_MI_W) + .collect(); + v.push(self.mi_cols); + v + } + + pub(crate) fn mi_row_starts(&self) -> Vec { + let mut v: Vec = self.row_starts_sb[..self.rows() as usize] + .iter() + .map(|sb| sb * SB_MI_W) + .collect(); + v.push(self.mi_rows); + v + } + + /// Tile `index` (row major, `TileNum`) as a rect. + pub(crate) fn rect(&self, index: usize) -> TileRect { + let (r, c) = (index / self.cols() as usize, index % self.cols() as usize); + let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]); + let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]); + TileRect { + sb_col0, + sb_col1, + sb_row0, + sb_row1, + mi_col0: sb_col0 * SB_MI_W, + mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols), + mi_row0: sb_row0 * SB_MI_W, + mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows), + } + } + + /// Which tile the superblock at `(sb_r, sb_c)` belongs to -- what the + /// encoder's frame-raster search consults to clip a block's neighbour + /// availability to its own tile. + pub(crate) fn index_of_sb(&self, sb_r: u32, sb_c: u32) -> usize { + let col = self.col_starts_sb[1..].partition_point(|&s| s <= sb_c); + let row = self.row_starts_sb[1..].partition_point(|&s| s <= sb_r); + row * self.cols() as usize + col + } + + /// The largest tile by mi area, `context_update_tile_id`'s own rule + /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both + /// name the biggest tile, whose end-of-tile tables the frame stores). + pub(crate) fn largest_tile(&self) -> usize { + (0..self.count()) + .max_by_key(|&i| { + let t = self.rect(i); + ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64) + }) + .unwrap_or(0) + } +} + /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]). struct CdefIdxPlan { /// The header's `cdef_bits`; never 0 while armed. @@ -1175,6 +1319,14 @@ impl Quadrant { /// What the blocks above and to the left of the one being coded left behind, /// kept on the 16x16 grid the smallest block sits on. struct Neighbours { + /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/ + /// `MiColStart`): every "is there a neighbour above/left of me" answer is + /// TILE-relative, not frame-relative -- the decoder's own + /// `Neighbours::start_tile` sets the same pair, and a writer that asked + /// `mi_row > 0` instead coded a tile's own first row against a neighbour + /// the decoder does not have (class: new map ignores tile edge). + tile_row0_mi: usize, + tile_col0_mi: usize, /// Per plane, whether the neighbour coded anything and the sign of its DC. above: Vec<[Neighbour; 3]>, /// The same, down the left edge. @@ -1305,6 +1457,8 @@ impl Neighbours { /// mode-info units. fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self { Self { + tile_row0_mi: 0, + tile_col0_mi: 0, above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)], left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)], above_mode: vec![DC_PRED; cols], @@ -1340,6 +1494,23 @@ impl Neighbours { } /// Clears the left edge, which a tile starts every superblock row with. + /// Points this writer's availability answers at one tile + /// ([`Self::tile_row0_mi`]). + fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) { + self.tile_row0_mi = row0_mi; + self.tile_col0_mi = col0_mi; + } + + /// Whether the block at mode-info row `mi_r` has a neighbour above it + /// INSIDE its own tile, and the same to the left. + fn has_above(&self, mi_r: usize) -> bool { + mi_r > self.tile_row0_mi + } + + fn has_left(&self, mi_c: usize) -> bool { + mi_c > self.tile_col0_mi + } + fn start_row(&mut self) { self.left.iter_mut().for_each(|l| *l = Default::default()); self.left_mode.iter_mut().for_each(|m| *m = DC_PRED); @@ -1460,7 +1631,7 @@ impl Neighbours { /// off a CDF row one higher than the decoder's, which is the first /// divergence of the inter `TxMode::Select` stream. fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize { - let (has_above, has_left) = (mi_r > 0, mi_c > 0); + let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c)); let mut above = usize::from(self.above_txfm[mi_c]) >= own_side; let mut left = usize::from(self.left_txfm[mi_r]) >= own_side; if has_above && self.above_inter[mi_c] { @@ -1477,8 +1648,8 @@ impl Neighbours { /// largest transform, plus whether the one to the left is at least as /// tall. A neighbour outside the tile contributes nothing. fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize { - usize::from(mi_r > 0 && usize::from(self.above_tx[mi_c]) >= max_tx) - + usize::from(mi_c > 0 && usize::from(self.left_tx[mi_r]) >= max_tx) + usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx) + + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx) } /// Publishes one block's resolved transform side over every 4x4 unit it @@ -1801,7 +1972,15 @@ pub fn sb_coeff_key_frame_tile_tx( tx_select: bool, ) -> Result> { let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); - sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs) + sb_coeff_key_frame_tile_cdfs( + mi_cols, + mi_rows, + base_q_idx, + superblocks, + tx_select, + &mut cdfs, + TileRect::whole(mi_cols, mi_rows), + ) } /// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the @@ -1819,6 +1998,11 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( superblocks: &[Superblock], tx_select: bool, cdfs: &mut Cdfs, + // This tile's own span (spec 5.11.1): the writer walks only these + // superblocks, and its neighbour bands start blank, so everything + // outside reads as unavailable exactly as the decoder's own per-tile + // reset makes it. + tile: TileRect, ) -> Result> { // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. let _cdef_idx = CdefIdxGuard; @@ -1876,15 +2060,16 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( mi_cols as usize, mi_rows as usize, ); + neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize); // The tile adapts every non-literal CDF it writes, exactly as the decoder // adapts the ones it reads, so the frame header leaves `disable_cdf_update` // off. let mut cdfs = cdfs; let mut enc = SymbolEncoder::new(); - for sb_r in 0..sb_rows { + for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) { neighbours.start_row(); - for sb_c in 0..sb_cols { + for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) { write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); let at = (sb_r as usize * 4, sb_c as usize * 4); let ctx = neighbours.partition_ctx(at, SB); @@ -3955,7 +4140,16 @@ pub fn sb_coeff_inter_frame_tile_tx( tx_select: bool, ) -> Result> { let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); - sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs) + sb_coeff_inter_frame_tile_cdfs( + mi_cols, + mi_rows, + base_q_idx, + blocks, + tx_select, + &mut cdfs, + TileRect::whole(mi_cols, mi_rows), + &mut MiGrid::new(mi_cols as usize, mi_rows as usize), + ) } /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind -- @@ -3970,6 +4164,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( blocks: &[Quadrant], tx_select: bool, cdfs: &mut Cdfs, + // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`]. + tile: TileRect, + // The frame's MV grid, carried across the frame's tiles by the caller + // (see the comment at `set_tile_bounds` below). + grid: &mut MiGrid, ) -> Result> { // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. let _cdef_idx = CdefIdxGuard; @@ -4010,7 +4209,21 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( mi_cols as usize, mi_rows as usize, ); - let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); + neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize); + // The MV grid spans the FRAME and carries every tile written before this + // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs` + // keeps one grid for the whole frame and narrows its read window per + // tile): the tile bounds below are what stops a candidate scan reaching + // across the boundary, and a grid that was merely empty out there would + // not read the same as the decoder's wherever a scan reads the array + // without asking `MiGrid::get` first. + let mut grid = &mut *grid; + grid.set_tile_bounds( + tile.mi_row0 as usize, + tile.mi_col0 as usize, + tile.mi_row1 as usize, + tile.mi_col1 as usize, + ); grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get)); let mut cdfs = cdfs; let mut enc = SymbolEncoder::new(); @@ -4038,9 +4251,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( vec![0i32; TX16 * TX16], ]; - for sb_r in 0..sb_rows { + for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) { neighbours.start_row(); - for sb_c in 0..sb_cols { + for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) { write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); let sb_ctx = neighbours.partition_ctx(sb_at, SB); @@ -4283,9 +4496,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( }; let (r, c) = at; - let has_above = r32 > 0; - let has_left = c32 > 0; let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + let has_above = neighbours.has_above(mi_r); + let has_left = neighbours.has_left(mi_c); let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]); enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); @@ -4532,7 +4745,7 @@ fn write_inter_frame_leaf( enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); write_cdef_idx(enc, (mi_r, mi_c), block.skip); - let (has_above, has_left) = (r > 0, c > 0); + let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c)); let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); let is_inter = block.inter.is_some(); @@ -4763,7 +4976,7 @@ fn write_inter_frame_leaf8( enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); write_cdef_idx(enc, leaf_mi, block.skip); - let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0); + let (has_above, has_left) = (neighbours.has_above(leaf_mi.0), neighbours.has_left(leaf_mi.1)); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); let is_inter = block.inter.is_some(); enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]); diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index 4c647f09..ca2dabce 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -345,12 +345,28 @@ fn bench_av1_encode(rows: &mut Vec) { rows.push(missing("ec-av1", "decode")); return; } + // `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. `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| { + let mut f = spec.split(':'); + let cols = f.next()?.parse().ok()?; + Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0))) + }) + .unwrap_or((0, 0)); let cfg = Av1Config { width: w as usize, height: h as usize, base_q_idx: 100, gop: 10, colour: Colour::default(), + tile_cols_log2, + tile_rows_log2, }; // `EC_AV1_PYRAMID=[::]` benches the // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead