From b8332eb690e02c18645c1731b76e7884afcd435c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 10:26:45 +0300 Subject: [PATCH] feat(av1): the encoder writes multi-tile frames (uniform spacing, per-tile CDF/LR/neighbour reset) --- crates/ec-av1/src/decode.rs | 98 +++++++++- crates/ec-av1/src/encode.rs | 340 ++++++++++++++++++++++++++--------- crates/ec-av1/src/encoder.rs | 68 +++++++ crates/ec-av1/src/frame.rs | 41 +++++ crates/ec-av1/src/tile.rs | 185 ++++++++++++++++++- 5 files changed, 636 insertions(+), 96 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 7b33b083..019eba44 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -20749,18 +20749,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, @@ -32916,12 +32959,61 @@ 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, + 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, + 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 ef5b7316..7714cf63 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -870,9 +870,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. @@ -924,14 +943,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) } @@ -2753,6 +2775,63 @@ 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) { + TILE_LOG2.with(std::cell::Cell::get) +} + +/// 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 @@ -2893,6 +2972,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`. @@ -2911,6 +2991,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 { @@ -2920,6 +3004,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, @@ -2928,6 +3016,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, }, ]; @@ -2959,10 +3051,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. @@ -3158,56 +3264,65 @@ 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()); - 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 mut out = Vec::with_capacity(layout.count()); + for index in 0..layout.count() { + 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( + mi_cols, + mi_rows, + base_q_idx, + &superblocks, + tx_select, + &mut cdfs, + layout.rect(index), + )?); + } + 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::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, @@ -3225,6 +3340,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)?); @@ -3274,19 +3392,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<()> { @@ -3313,7 +3437,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, @@ -3344,14 +3468,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); @@ -3382,7 +3506,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; } } @@ -4268,6 +4392,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 { @@ -4277,6 +4405,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, @@ -4285,6 +4417,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, }, ]; @@ -4307,6 +4443,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 @@ -4317,6 +4459,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 @@ -4709,19 +4863,46 @@ 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); - 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 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, + grid: &[u8], + units: &[Option]| + -> Result>> { + let mut out = Vec::with_capacity(layout.count()); + for index in 0..layout.count() { + 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); + let mut cdfs = start_cdfs.0.clone(); + out.push(crate::tile::sb_coeff_inter_frame_tile_cdfs( + mi_cols, + mi_rows, + base_q_idx, + &blocks, + tx_select, + &mut cdfs, + layout.rect(index), + )?); + if index == store_tile { + *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. @@ -4730,7 +4911,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() @@ -4777,12 +4957,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, @@ -4793,34 +4967,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); - 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, @@ -4845,9 +5004,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)?); @@ -7733,6 +7897,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 98c1292a..49d699b9 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() } @@ -1014,6 +1058,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 { @@ -1034,6 +1080,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) @@ -1132,6 +1180,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)); @@ -1185,6 +1235,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(); @@ -1207,6 +1259,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(); @@ -1227,6 +1281,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(); @@ -1242,6 +1298,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}"); @@ -1313,6 +1371,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(); @@ -1352,6 +1412,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, @@ -1409,6 +1471,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(); @@ -1491,6 +1555,8 @@ mod tests { base_q_idx: 120, gop: 32, colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, }; let pyramid = Pyramid { mini_gop: 4, @@ -1594,6 +1660,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 818195ce..882f2dfa 100644 --- a/crates/ec-av1/src/frame.rs +++ b/crates/ec-av1/src/frame.rs @@ -595,6 +595,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/tile.rs b/crates/ec-av1/src/tile.rs index 54ace68e..abd3bf1c 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. @@ -1240,7 +1384,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 @@ -1258,6 +1410,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; @@ -1321,9 +1478,9 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( // 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); @@ -3170,7 +3327,15 @@ 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), + ) } /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind -- @@ -3185,6 +3350,8 @@ 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, ) -> Result> { // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. let _cdef_idx = CdefIdxGuard; @@ -3226,6 +3393,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( mi_rows as usize, ); let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); + 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(); @@ -3253,9 +3426,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);