forge
Explore
Log in

Don't you dare go Hollow

The encoder writes multi-tile frames (uniform spacing, per-tile CDF/LR/neighbour reset)

Browse files at this commit

b8332eb690e02c18645c1731b76e7884afcd435cAhmet Kaan GümüşParent: 7c2597d
  • feat
    • the encoder writes multi-tile frames (uniform spacing, per-tile CDF/LR/neighbour reset)
Show full message
feat(av1): the encoder writes multi-tile frames (uniform spacing, per-tile CDF/LR/neighbour reset)
crates/ec-av1/src/decode.rsmodified+95 -3
@@ -20749,18 +20749,61 @@ pub(crate) fn decode_key_frame_tile_lr(
20749 lr: &LoopRestorationParams,20749 lr: &LoopRestorationParams,
20750 fctx: &crate::decode::FrameCtx,20750 fctx: &crate::decode::FrameCtx,
20751 ) -> Result<Picture> {20751 ) -> Result<Picture> {
20752- let delta = DeltaParams::default();
20753 let single_tile = TileInfo {20752 let single_tile = TileInfo {
20754 mi_col_starts: vec![0, mi_cols],20753 mi_col_starts: vec![0, mi_cols],
20755 mi_row_starts: vec![0, mi_rows],20754 mi_row_starts: vec![0, mi_rows],
20756 ..TileInfo::default()20755 ..TileInfo::default()
20757 };20756 };
20758- decode_key_frame_tile_with_cdfs(20757+ decode_key_frame_tiles_lr(
20759 &[data],20758 &[data],
20760 &single_tile,20759 &single_tile,
20761 mi_cols,20760 mi_cols,
20762 mi_rows,20761 mi_rows,
20763 base_q_idx,20762 base_q_idx,
20763+ frame_width,
20764+ frame_height,
20765+ enable_filter_intra,
20766+ cdef,
20767+ loop_filter,
20768+ tx_select,
20769+ reduced_tx_set,
20770+ allow_screen_content_tools,
20771+ allow_intrabc,
20772+ lr,
20773+ fctx,
20774+ )
20775+}
20776+
20777+/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the
20778+/// encoder's own filter search hands back one payload per tile plus the
20779+/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets
20780+/// are the decoder's own (`decode_key_frame_tile_with_cdfs`).
20781+#[allow(clippy::too_many_arguments)]
20782+pub(crate) fn decode_key_frame_tiles_lr(
20783+ tiles: &[&[u8]],
20784+ tile_info: &TileInfo,
20785+ mi_cols: u32,
20786+ mi_rows: u32,
20787+ base_q_idx: u8,
20788+ frame_width: u32,
20789+ frame_height: u32,
20790+ enable_filter_intra: bool,
20791+ cdef: &CdefParams,
20792+ loop_filter: &LoopFilterParams,
20793+ tx_select: bool,
20794+ reduced_tx_set: bool,
20795+ allow_screen_content_tools: bool,
20796+ allow_intrabc: bool,
20797+ lr: &LoopRestorationParams,
20798+ fctx: &crate::decode::FrameCtx,
20799+) -> Result<Picture> {
20800+ let delta = DeltaParams::default();
20801+ decode_key_frame_tile_with_cdfs(
20802+ tiles,
20803+ tile_info,
20804+ mi_cols,
20805+ mi_rows,
20806+ base_q_idx,
20764 crate::quant::QuantDeltas::default(),20807 crate::quant::QuantDeltas::default(),
20765 frame_width,20808 frame_width,
20766 frame_height,20809 frame_height,
@@ -32916,12 +32959,61 @@ pub(crate) fn decode_inter_frame_tile_lr(
32916 mi_row_starts: vec![0, mi_rows],32959 mi_row_starts: vec![0, mi_rows],
32917 ..TileInfo::default()32960 ..TileInfo::default()
32918 };32961 };
32919- decode_inter_frame_tile_with_cdfs(32962+ decode_inter_frame_tiles_lr(
32920 &[data],32963 &[data],
32921 &single_tile,32964 &single_tile,
32922 mi_cols,32965 mi_cols,
32923 mi_rows,32966 mi_rows,
32924 base_q_idx,32967 base_q_idx,
32968+ frame_width,
32969+ frame_height,
32970+ refpix,
32971+ cdef,
32972+ loop_filter,
32973+ allow_high_precision_mv,
32974+ force_integer_mv,
32975+ interp_fixed,
32976+ enable_dual_filter,
32977+ reference_select,
32978+ tx_select,
32979+ lr,
32980+ initial_cdfs,
32981+ sign_bias,
32982+ fctx,
32983+ )
32984+}
32985+
32986+/// [`decode_inter_frame_tile_lr`] for a frame coded as SEVERAL tiles; see
32987+/// [`decode_key_frame_tiles_lr`].
32988+#[allow(clippy::too_many_arguments)]
32989+pub(crate) fn decode_inter_frame_tiles_lr(
32990+ tiles: &[&[u8]],
32991+ tile_info: &TileInfo,
32992+ mi_cols: u32,
32993+ mi_rows: u32,
32994+ base_q_idx: u8,
32995+ frame_width: u32,
32996+ frame_height: u32,
32997+ refpix: &RefPix<'_>,
32998+ cdef: &CdefParams,
32999+ loop_filter: &LoopFilterParams,
33000+ allow_high_precision_mv: bool,
33001+ force_integer_mv: bool,
33002+ interp_fixed: Option<mc::InterpFilterKind>,
33003+ enable_dual_filter: bool,
33004+ reference_select: bool,
33005+ tx_select: bool,
33006+ lr: &LoopRestorationParams,
33007+ initial_cdfs: Option<Cdfs>,
33008+ sign_bias: crate::mvstack::SignBiasTable,
33009+ fctx: &crate::decode::FrameCtx,
33010+) -> Result<Picture> {
33011+ decode_inter_frame_tile_with_cdfs(
33012+ tiles,
33013+ tile_info,
33014+ mi_cols,
33015+ mi_rows,
33016+ base_q_idx,
32925 crate::quant::QuantDeltas::default(),33017 crate::quant::QuantDeltas::default(),
32926 frame_width,33018 frame_width,
32927 frame_height,33019 frame_height,
crates/ec-av1/src/encode.rsmodified+241 -75
@@ -870,9 +870,28 @@ struct Plane<'a> {
870 /// edge.870 /// edge.
871 true_width: usize,871 true_width: usize,
872 true_height: usize,872 true_height: usize,
873+ /// This plane's own tile's pixel bounds, in this plane's units -- the
874+ /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
875+ /// prediction never reaches across a tile edge even though the
876+ /// neighbouring tile's real samples sit right there in the shared
877+ /// reconstruction. `(0, 0, width, height)` is the single-tile case and
878+ /// leaves every edge exactly as it was before tiles existed.
879+ tile_x0: usize,
880+ tile_y0: usize,
881+ tile_x1: usize,
882+ tile_y1: usize,
873 }883 }
874 884
875 impl Plane<'_> {885 impl Plane<'_> {
886+ /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
887+ /// called at every superblock of the frame-raster search with the rect
888+ /// of the tile that superblock belongs to.
889+ fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
890+ self.tile_x0 = x0;
891+ self.tile_y0 = y0;
892+ self.tile_x1 = x1.min(self.width);
893+ self.tile_y1 = y1.min(self.height);
894+ }
876 /// The reconstructed samples a block at `(x, y)` predicts from: the row895 /// The reconstructed samples a block at `(x, y)` predicts from: the row
877 /// above it, the column to its left and the sample between them, each896 /// above it, the column to its left and the sample between them, each
878 /// missing where the block sits against an edge of the frame.897 /// missing where the block sits against an edge of the frame.
@@ -924,14 +943,17 @@ impl Plane<'_> {
924 // `a_picture_off_the_block_grid_is_refused`), never through a block943 // `a_picture_off_the_block_grid_is_refused`), never through a block
925 // this encoder actually commits. Such a block has no true-edge944 // this encoder actually commits. Such a block has no true-edge
926 // samples above or left of it at all, same as `y == 0`/`x == 0`.945 // samples above or left of it at all, same as `y == 0`/`x == 0`.
927- let above = (y > 0 && across > x)946+ let across = across.min(self.tile_x1);
947+ let down = down.min(self.tile_y1);
948+ let above = (y > self.tile_y0 && across > x)
928 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());949 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());
929- let left = (x > 0 && down > y).then(|| {950+ let left = (x > self.tile_x0 && down > y).then(|| {
930 (y..down)951 (y..down)
931 .map(|row| self.reconstruction[row * self.width + x - 1])952 .map(|row| self.reconstruction[row * self.width + x - 1])
932 .collect::<Vec<_>>()953 .collect::<Vec<_>>()
933 });954 });
934- let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]);955+ let corner = (x > self.tile_x0 && y > self.tile_y0)
956+ .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
935 (above, left, corner)957 (above, left, corner)
936 }958 }
937 959
@@ -2753,6 +2775,63 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
2753 .collect()2775 .collect()
2754 }2776 }
2755 2777
2778+thread_local! {
2779+ /// The tile grid the next frame is coded with, as `(TileColsLog2,
2780+ /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
2781+ /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
2782+ /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
2783+ /// one tile per frame, what every caller that never arms anything gets
2784+ /// and what every stream this crate wrote before tiles existed carries.
2785+ static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
2786+}
2787+
2788+/// Arms this thread's next frame encodes with a tile grid (log2 counts).
2789+pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
2790+ TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
2791+}
2792+
2793+fn armed_tiles() -> (u32, u32) {
2794+ TILE_LOG2.with(std::cell::Cell::get)
2795+}
2796+
2797+/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
2798+/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
2799+/// tables the frame stores (spec 7.20), which is what
2800+/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
2801+/// below publish.
2802+fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
2803+ ec_av1_syntax::TileInfo {
2804+ uniform_spacing: true,
2805+ cols: layout.cols(),
2806+ rows: layout.rows(),
2807+ cols_log2: layout.cols_log2,
2808+ rows_log2: layout.rows_log2,
2809+ mi_col_starts: layout.mi_col_starts(),
2810+ mi_row_starts: layout.mi_row_starts(),
2811+ context_update_tile_id: layout.largest_tile() as u32,
2812+ tile_size_bytes,
2813+ }
2814+}
2815+
2816+/// Clips the three planes' intra edge reads to `rect`, the tile the
2817+/// superblock about to be searched belongs to (the encoder side of the
2818+/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
2819+/// raster order -- which is a linear extension of every tile's own coding
2820+/// order, so a block still only ever predicts from samples already
2821+/// reconstructed -- and only availability is tile-relative.
2822+fn clip_planes_to_tile(
2823+ luma: &mut Plane<'_>,
2824+ chroma: &mut [Plane<'_>; 2],
2825+ rect: crate::tile::TileRect,
2826+) {
2827+ let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
2828+ let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
2829+ luma.set_tile(x0, y0, x1, y1);
2830+ for plane in chroma.iter_mut() {
2831+ plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
2832+ }
2833+}
2834+
2756 /// Encodes one picture as a key frame.2835 /// Encodes one picture as a key frame.
2757 ///2836 ///
2758 /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer2837 /// `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(
2893 if tx_select {2972 if tx_select {
2894 header.tx_mode = TxMode::Select;2973 header.tx_mode = TxMode::Select;
2895 }2974 }
2975+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
2896 2976
2897 // Prediction reads no further than this, in each plane's own units --2977 // Prediction reads no further than this, in each plane's own units --
2898 // see `Plane::true_width`/`true_height`.2978 // see `Plane::true_width`/`true_height`.
@@ -2911,6 +2991,10 @@ pub(crate) fn encode_key_frame_inner(
2911 height: picture.height,2991 height: picture.height,
2912 true_width,2992 true_width,
2913 true_height,2993 true_height,
2994+ tile_x0: 0,
2995+ tile_y0: 0,
2996+ tile_x1: picture.width,
2997+ tile_y1: picture.height,
2914 };2998 };
2915 let mut chroma = [2999 let mut chroma = [
2916 Plane {3000 Plane {
@@ -2920,6 +3004,10 @@ pub(crate) fn encode_key_frame_inner(
2920 height: picture.height / 2,3004 height: picture.height / 2,
2921 true_width: true_width / 2,3005 true_width: true_width / 2,
2922 true_height: true_height / 2,3006 true_height: true_height / 2,
3007+ tile_x0: 0,
3008+ tile_y0: 0,
3009+ tile_x1: picture.width / 2,
3010+ tile_y1: picture.height / 2,
2923 },3011 },
2924 Plane {3012 Plane {
2925 source: &picture_v8,3013 source: &picture_v8,
@@ -2928,6 +3016,10 @@ pub(crate) fn encode_key_frame_inner(
2928 height: picture.height / 2,3016 height: picture.height / 2,
2929 true_width: true_width / 2,3017 true_width: true_width / 2,
2930 true_height: true_height / 2,3018 true_height: true_height / 2,
3019+ tile_x0: 0,
3020+ tile_y0: 0,
3021+ tile_x1: picture.width / 2,
3022+ tile_y1: picture.height / 2,
2931 },3023 },
2932 ];3024 ];
2933 3025
@@ -2959,10 +3051,24 @@ pub(crate) fn encode_key_frame_inner(
2959 let mut above_mode = vec![DC_PRED; cols * 2];3051 let mut above_mode = vec![DC_PRED; cols * 2];
2960 let mut left_mode = vec![DC_PRED; rows * 2];3052 let mut left_mode = vec![DC_PRED; rows * 2];
2961 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));3053 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3054+ // This frame's tile grid (one tile unless the facade armed more).
3055+ let layout =
3056+ crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
3057+ header.tile_info = tile_info_of(&layout, 1);
3058+ // The filter search re-decodes this frame's tiles; the decoder derives
3059+ // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
3060+ // `mi_row_starts`), which is what makes the writer's rects and the
3061+ // reader's the same rects.
3062+ let header_tile_info = header.tile_info.clone();
2962 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);3063 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
2963 let mut modes = Vec::with_capacity(cols * rows);3064 let mut modes = Vec::with_capacity(cols * rows);
2964 for sb_row in 0..sb_rows {3065 for sb_row in 0..sb_rows {
2965 for sb_col in 0..sb_cols {3066 for sb_col in 0..sb_cols {
3067+ clip_planes_to_tile(
3068+ &mut luma,
3069+ &mut chroma,
3070+ layout.rect(layout.index_of_sb(sb_row as u32, sb_col as u32)),
3071+ );
2966 // The quadrants of a superblock are coded in the order the decoder3072 // The quadrants of a superblock are coded in the order the decoder
2967 // walks them, which for a 64x64 split into 32x32 blocks is raster3073 // walks them, which for a 64x64 split into 32x32 blocks is raster
2968 // order among the quadrants that are inside the frame.3074 // order among the quadrants that are inside the frame.
@@ -3158,56 +3264,65 @@ pub(crate) fn encode_key_frame_inner(
3158 // defaults again (spec 7.20's `started_from` arm) -- the first inter3264 // defaults again (spec 7.20's `started_from` arm) -- the first inter
3159 // frame after it therefore starts from the defaults too.3265 // frame after it therefore starts from the defaults too.
3160 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);3266 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3161- let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));3267+ let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3162- let start_cdfs = CdfSnapshot(cdfs.clone());3268+ let start_cdfs = CdfSnapshot(cdfs);
3163- let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(3269+ // The luma restoration-unit grid this frame's `lr_params` implies
3270+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3271+ // swallowed by the one before it), for the tile writer's own per-unit
3272+ // walk.
3273+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3274+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3275+ // Every tile is coded from this frame's OWN starting tables and leaves
3276+ // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
3277+ // loop-restoration reference and its neighbour contexts), so the tiles
3278+ // are independent of each other and of the order they are written in.
3279+ let code_tiles = |bits: u8,
3280+ sb_cols: usize,
3281+ grid: &[u8],
3282+ units: &[Option<crate::restoration::WienerInfo>]|
3283+ -> Result<Vec<Vec<u8>>> {
3284+ let mut out = Vec::with_capacity(layout.count());
3285+ for index in 0..layout.count() {
3286+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3287+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3288+ let mut cdfs = start_cdfs.0.clone();
3289+ out.push(crate::tile::sb_coeff_key_frame_tile_cdfs(
3164 mi_cols,3290 mi_cols,
3165 mi_rows,3291 mi_rows,
3166 base_q_idx,3292 base_q_idx,
3167 &superblocks,3293 &superblocks,
3168 tx_select,3294 tx_select,
3169 &mut cdfs,3295 &mut cdfs,
3170- )?;3296+ layout.rect(index),
3297+ )?);
3298+ }
3299+ Ok(out)
3300+ };
3301+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
3171 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing3302 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
3172 // the tile just coded back to the decoder under each candidate (see3303 // the tile just coded back to the decoder under each candidate (see
3173 // `crate::filter_search`), and keep the filtered picture that wins as3304 // `crate::filter_search`), and keep the filtered picture that wins as
3174 // the reconstruction -- what a decoder outputs, and what the next3305 // the reconstruction -- what a decoder outputs, and what the next
3175 // frame predicts from.3306 // frame predicts from.
3176- // The luma restoration-unit grid this frame's `lr_params` implies
3177- // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3178- // swallowed by the one before it), for the tile writer's own per-unit
3179- // walk.
3180- let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3181- let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3182 pick_and_apply_filters(3307 pick_and_apply_filters(
3183 &mut header,3308 &mut header,
3184 &mut luma,3309 &mut luma,
3185 &mut chroma,3310 &mut chroma,
3186 [&picture_y8, &picture_u8, &picture_v8],3311 [&picture_y8, &picture_u8, &picture_v8],
3187 true,3312 true,
3188- &mut tile,3313+ &mut tiles,
3189 search.lambda,3314 search.lambda,
3190 fctx,3315 fctx,
3191 // Every re-code starts from this frame's OWN starting tables, never3316 // Every re-code starts from this frame's OWN starting tables, never
3192 // from where the first write left them: the second tile is the same3317 // from where the first write left them: the second tile is the same
3193 // symbol sequence plus new ones, so it must adapt from the same3318 // symbol sequence plus new ones, so it must adapt from the same
3194 // point the decoder will.3319 // point the decoder will.
3195- |bits, sb_cols, grid, units| {3320+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
3196- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());3321+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
3197- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());3322+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
3198- let mut cdfs = start_cdfs.0.clone();3323+ crate::decode::decode_key_frame_tiles_lr(
3199- crate::tile::sb_coeff_key_frame_tile_cdfs(3324+ &payloads,
3200- mi_cols,3325+ &header_tile_info,
3201- mi_rows,
3202- base_q_idx,
3203- &superblocks,
3204- tx_select,
3205- &mut cdfs,
3206- )
3207- },
3208- |lf, cdef, h, tile, lr| {
3209- crate::decode::decode_key_frame_tile_lr(
3210- tile,
3211 h.mi_cols,3326 h.mi_cols,
3212 h.mi_rows,3327 h.mi_rows,
3213 base_q_idx,3328 base_q_idx,
@@ -3225,6 +3340,9 @@ pub(crate) fn encode_key_frame_inner(
3225 )3340 )
3226 },3341 },
3227 )?;3342 )?;
3343+ let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
3344+ header.tile_info.tile_size_bytes = tile_size_bytes;
3345+ let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
3228 let mut stream = temporal_delimiter();3346 let mut stream = temporal_delimiter();
3229 stream.extend_from_slice(&sequence_header_obu(&seq)?);3347 stream.extend_from_slice(&sequence_header_obu(&seq)?);
3230 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);3348 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3274,19 +3392,25 @@ fn pick_and_apply_filters(
3274 chroma: &mut [Plane<'_>; 2],3392 chroma: &mut [Plane<'_>; 2],
3275 source: [&[u8]; 3],3393 source: [&[u8]; 3],
3276 search: bool,3394 search: bool,
3277- // The coded tile, replaced in place when the search chooses a per-64x643395+ // The coded tiles, one payload per tile of the frame's grid, replaced in
3278- // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile3396+ // place when the search chooses a per-64x64 `cdef_idx` list
3279- // payload, so the tile is written a second time under `recode` and the3397+ // (`cdef_bits > 0`): those literals live in the tile payloads, so every
3280- // winner re-decoded from it.3398+ // tile is written a second time under `recode` and the winner
3281- tile: &mut Vec<u8>,3399+ // re-decoded from them.
3400+ tiles: &mut Vec<Vec<u8>>,
3282 lambda: f64,3401 lambda: f64,
3283 fctx: &crate::decode::FrameCtx,3402 fctx: &crate::decode::FrameCtx,
3284- recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<u8>>,3403+ recode: impl Fn(
3404+ u8,
3405+ usize,
3406+ &[u8],
3407+ &[Option<crate::restoration::WienerInfo>],
3408+ ) -> Result<Vec<Vec<u8>>>,
3285 decode: impl Fn(3409 decode: impl Fn(
3286 &LoopFilterParams,3410 &LoopFilterParams,
3287 &CdefParams,3411 &CdefParams,
3288 &FrameHeader,3412 &FrameHeader,
3289- &[u8],3413+ &[Vec<u8>],
3290 &LoopRestorationParams,3414 &LoopRestorationParams,
3291 ) -> Result<Picture>,3415 ) -> Result<Picture>,
3292 ) -> Result<()> {3416 ) -> Result<()> {
@@ -3313,7 +3437,7 @@ fn pick_and_apply_filters(
3313 return Ok(picture);3437 return Ok(picture);
3314 }3438 }
3315 crate::decode::arm_filter_replay();3439 crate::decode::arm_filter_replay();
3316- decode(lf, cdef, &hdr, tile, &none_lr)3440+ decode(lf, cdef, &hdr, tiles, &none_lr)
3317 },3441 },
3318 source,3442 source,
3319 luma.width,3443 luma.width,
@@ -3344,14 +3468,14 @@ fn pick_and_apply_filters(
3344 fctx.capture_stages.set(lr_on);3468 fctx.capture_stages.set(lr_on);
3345 let mut filtered = if idx_grid.is_empty() {3469 let mut filtered = if idx_grid.is_empty() {
3346 if lr_on {3470 if lr_on {
3347- decode(&lf, &cdef, &hdr, tile, &none_lr)?3471+ decode(&lf, &cdef, &hdr, tiles, &none_lr)?
3348 } else {3472 } else {
3349 picture3473 picture
3350 }3474 }
3351 } else {3475 } else {
3352 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;3476 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
3353 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;3477 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
3354- *tile = coded;3478+ *tiles = coded;
3355 picture3479 picture
3356 };3480 };
3357 fctx.capture_stages.set(false);3481 fctx.capture_stages.set(false);
@@ -3382,7 +3506,7 @@ fn pick_and_apply_filters(
3382 if units.iter().any(Option::is_some) {3506 if units.iter().any(Option::is_some) {
3383 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;3507 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
3384 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;3508 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
3385- *tile = coded;3509+ *tiles = coded;
3386 lr = want;3510 lr = want;
3387 }3511 }
3388 }3512 }
@@ -4268,6 +4392,10 @@ pub(crate) fn encode_inter_frame(
4268 height: picture.height,4392 height: picture.height,
4269 true_width,4393 true_width,
4270 true_height,4394 true_height,
4395+ tile_x0: 0,
4396+ tile_y0: 0,
4397+ tile_x1: picture.width,
4398+ tile_y1: picture.height,
4271 };4399 };
4272 let mut chroma = [4400 let mut chroma = [
4273 Plane {4401 Plane {
@@ -4277,6 +4405,10 @@ pub(crate) fn encode_inter_frame(
4277 height: picture.height / 2,4405 height: picture.height / 2,
4278 true_width: true_width / 2,4406 true_width: true_width / 2,
4279 true_height: true_height / 2,4407 true_height: true_height / 2,
4408+ tile_x0: 0,
4409+ tile_y0: 0,
4410+ tile_x1: picture.width / 2,
4411+ tile_y1: picture.height / 2,
4280 },4412 },
4281 Plane {4413 Plane {
4282 source: &picture_v8,4414 source: &picture_v8,
@@ -4285,6 +4417,10 @@ pub(crate) fn encode_inter_frame(
4285 height: picture.height / 2,4417 height: picture.height / 2,
4286 true_width: true_width / 2,4418 true_width: true_width / 2,
4287 true_height: true_height / 2,4419 true_height: true_height / 2,
4420+ tile_x0: 0,
4421+ tile_y0: 0,
4422+ tile_x1: picture.width / 2,
4423+ tile_y1: picture.height / 2,
4288 },4424 },
4289 ];4425 ];
4290 4426
@@ -4307,6 +4443,12 @@ pub(crate) fn encode_inter_frame(
4307 let (cols, rows) = (cols as usize, rows as usize);4443 let (cols, rows) = (cols as usize, rows as usize);
4308 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));4444 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
4309 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);4445 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
4446+ // This frame's tile grid, as in `encode_key_frame_inner`.
4447+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
4448+ let layout =
4449+ crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
4450+ header.tile_info = tile_info_of(&layout, 1);
4451+ let header_tile_info = header.tile_info.clone();
4310 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is4452 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
4311 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --4453 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
4312 // once per frame (lane-av1rd2), not once per block, which is a whole4454 // once per frame (lane-av1rd2), not once per block, which is a whole
@@ -4317,6 +4459,18 @@ pub(crate) fn encode_inter_frame(
4317 4459
4318 for sb_r in 0..sb_rows {4460 for sb_r in 0..sb_rows {
4319 for sb_c in 0..sb_cols {4461 for sb_c in 0..sb_cols {
4462+ // Neighbour availability -- intra edges and the MV stack's
4463+ // scans alike -- stops at this superblock's own tile, exactly
4464+ // where the decoder stops it (`PlaneBuf::set_tile_origin`,
4465+ // `MiGrid::set_tile_bounds`).
4466+ let rect = layout.rect(layout.index_of_sb(sb_r as u32, sb_c as u32));
4467+ clip_planes_to_tile(&mut luma, &mut chroma, rect);
4468+ grid.set_tile_bounds(
4469+ rect.mi_row0 as usize,
4470+ rect.mi_col0 as usize,
4471+ rect.mi_row1 as usize,
4472+ rect.mi_col1 as usize,
4473+ );
4320 for quadrant in 0..4 {4474 for quadrant in 0..4 {
4321 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);4475 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
4322 // Same filter as the tile writer's: a quadrant whose own mi4476 // Same filter as the tile writer's: a quadrant whose own mi
@@ -4709,19 +4863,46 @@ pub(crate) fn encode_inter_frame(
4709 // next frame's writer starts from them -- exactly what4863 // next frame's writer starts from them -- exactly what
4710 // `crate::stream::stored_cdfs_for` hands the decoder.4864 // `crate::stream::stored_cdfs_for` hands the decoder.
4711 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);4865 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
4712- let mut cdfs = start_cdfs4866+ let cdfs = start_cdfs
4713 .cloned()4867 .cloned()
4714 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));4868 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
4715- let start_cdfs = CdfSnapshot(cdfs.clone());4869+ let start_cdfs = CdfSnapshot(cdfs);
4870+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
4871+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
4872+ // What this frame stores is the LARGEST tile's end-of-tile tables --
4873+ // its own header's `context_update_tile_id` (spec 7.20), which
4874+ // `tile_info_of` set to exactly that tile.
4875+ let store_tile = layout.largest_tile();
4876+ let end_cdfs = std::cell::RefCell::new(None);
4877+ // As in `encode_key_frame_inner`: every tile starts from this frame's
4878+ // own tables, so no tile depends on any other.
4879+ let code_tiles = |bits: u8,
4880+ sb_cols: usize,
4881+ grid: &[u8],
4882+ units: &[Option<crate::restoration::WienerInfo>]|
4883+ -> Result<Vec<Vec<u8>>> {
4884+ let mut out = Vec::with_capacity(layout.count());
4885+ for index in 0..layout.count() {
4886+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4887+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4716 crate::tile::arm_sign_bias(sign_bias);4888 crate::tile::arm_sign_bias(sign_bias);
4717- let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(4889+ let mut cdfs = start_cdfs.0.clone();
4890+ out.push(crate::tile::sb_coeff_inter_frame_tile_cdfs(
4718 mi_cols,4891 mi_cols,
4719 mi_rows,4892 mi_rows,
4720 base_q_idx,4893 base_q_idx,
4721 &blocks,4894 &blocks,
4722 tx_select,4895 tx_select,
4723 &mut cdfs,4896 &mut cdfs,
4724- )?;4897+ layout.rect(index),
4898+ )?);
4899+ if index == store_tile {
4900+ *end_cdfs.borrow_mut() = Some(cdfs);
4901+ }
4902+ }
4903+ Ok(out)
4904+ };
4905+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
4725 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs4906 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
4726 // this tile against the same single-slot reference this encoder predicted4907 // this tile against the same single-slot reference this encoder predicted
4727 // from, under each candidate level.4908 // from, under each candidate level.
@@ -4730,7 +4911,6 @@ pub(crate) fn encode_inter_frame(
4730 // reference whose height is not the header's own `frame_height` (spec4911 // reference whose height is not the header's own `frame_height` (spec
4731 // 7.9's compatible-size rule), and the chained-decode round trips prove4912 // 7.9's compatible-size rule), and the chained-decode round trips prove
4732 // the two predict identically.4913 // the two predict identically.
4733- let end_cdfs = std::cell::RefCell::new(cdfs);
4734 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);4914 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
4735 let trial_ref = if (reference.width, reference.height) == (fw, fh) {4915 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
4736 reference.clone()4916 reference.clone()
@@ -4777,12 +4957,6 @@ pub(crate) fn encode_inter_frame(
4777 refs[4] = trial_golden.as_ref();4957 refs[4] = trial_golden.as_ref();
4778 refs[7] = trial_altref.as_ref();4958 refs[7] = trial_altref.as_ref();
4779 let refpix = crate::decode::RefPix::ready(refs);4959 let refpix = crate::decode::RefPix::ready(refs);
4780- // The luma restoration-unit grid this frame's `lr_params` implies
4781- // (`av1_lr_count_units` rounds to nearest, so a short last unit is
4782- // swallowed by the one before it), for the tile writer's own per-unit
4783- // walk.
4784- let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
4785- let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
4786 pick_and_apply_filters(4960 pick_and_apply_filters(
4787 &mut header,4961 &mut header,
4788 &mut luma,4962 &mut luma,
@@ -4793,34 +4967,19 @@ pub(crate) fn encode_inter_frame(
4793 // `TxMode::Select` too (it used to skip and leave every inter frame4967 // `TxMode::Select` too (it used to skip and leave every inter frame
4794 // unfiltered once Select became the default).4968 // unfiltered once Select became the default).
4795 true,4969 true,
4796- &mut tile,4970+ &mut tiles,
4797 search.lambda,4971 search.lambda,
4798 fctx,4972 fctx,
4799 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables4973 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
4800 // are what the NEXT frame writes from, so the winning re-code4974 // are what the NEXT frame writes from, so the winning re-code
4801 // publishes its own into `end_cdfs` -- the first write's are stale4975 // publishes its own into `end_cdfs` -- the first write's are stale
4802 // the moment a second tile is coded.4976 // the moment a second tile is coded.
4803- |bits, sb_cols, grid, units| {4977+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
4804- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());4978+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
4805- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());4979+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
4806- crate::tile::arm_sign_bias(sign_bias);4980+ crate::decode::decode_inter_frame_tiles_lr(
4807- let mut cdfs = start_cdfs.0.clone();4981+ &payloads,
4808- let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(4982+ &header_tile_info,
4809- mi_cols,
4810- mi_rows,
4811- base_q_idx,
4812- &blocks,
4813- tx_select,
4814- &mut cdfs,
4815- );
4816- if coded.is_ok() {
4817- *end_cdfs.borrow_mut() = cdfs;
4818- }
4819- coded
4820- },
4821- |lf, cdef, h, tile, lr| {
4822- crate::decode::decode_inter_frame_tile_lr(
4823- tile,
4824 h.mi_cols,4983 h.mi_cols,
4825 h.mi_rows,4984 h.mi_rows,
4826 base_q_idx,4985 base_q_idx,
@@ -4845,9 +5004,14 @@ pub(crate) fn encode_inter_frame(
4845 )5004 )
4846 },5005 },
4847 )?;5006 )?;
4848- let mut cdfs = end_cdfs.into_inner();5007+ let mut cdfs = end_cdfs
5008+ .into_inner()
5009+ .unwrap_or_else(|| start_cdfs.0.clone());
4849 cdfs.reset_counts();5010 cdfs.reset_counts();
4850 let next_cdfs = CdfSnapshot(cdfs);5011 let next_cdfs = CdfSnapshot(cdfs);
5012+ let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
5013+ header.tile_info.tile_size_bytes = tile_size_bytes;
5014+ let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
4851 let mut stream = temporal_delimiter();5015 let mut stream = temporal_delimiter();
4852 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);5016 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
4853 5017
@@ -7733,6 +7897,8 @@ mod tests {
7733 base_q_idx: q,7897 base_q_idx: q,
7734 gop: source.len(),7898 gop: source.len(),
7735 colour: Colour::Unspecified,7899 colour: Colour::Unspecified,
7900+ tile_cols_log2: 0,
7901+ tile_rows_log2: 0,
7736 };7902 };
7737 let start = std::time::Instant::now();7903 let start = std::time::Instant::now();
7738 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();7904 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
crates/ec-av1/src/encoder.rsmodified+68 -0
@@ -276,6 +276,32 @@ pub struct EncoderConfig {
276 pub gop: usize,276 pub gop: usize,
277 /// The colour the sequence header signals.277 /// The colour the sequence header signals.
278 pub colour: Colour,278 pub colour: Colour,
279+ /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 <<
280+ /// tile_cols_log2` uniformly spaced tile columns, each coded and
281+ /// decodable on its own. `0` -- one tile column -- is the default and
282+ /// is byte for byte the stream this encoder wrote before tiles existed.
283+ pub tile_cols_log2: u32,
284+ /// `TileRowsLog2`, the same down the rows.
285+ pub tile_rows_log2: u32,
286+}
287+
288+impl EncoderConfig {
289+ /// A config at `width`x`height` with one tile, `gop` pictures between
290+ /// key frames and no colour signalling -- what every caller that does
291+ /// not care about tiles writes, so that adding a field here does not
292+ /// rewrite them.
293+ #[must_use]
294+ pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self {
295+ Self {
296+ width,
297+ height,
298+ base_q_idx,
299+ gop,
300+ colour,
301+ tile_cols_log2: 0,
302+ tile_rows_log2: 0,
303+ }
304+ }
279 }305 }
280 306
281 /// One coded picture: its OBUs, in the order a demuxer that just wants bytes307 /// One coded picture: its OBUs, in the order a demuxer that just wants bytes
@@ -510,6 +536,22 @@ impl Av1Encoder {
510 // do, before the first `encode()` call rather than only surfacing it536 // do, before the first `encode()` call rather than only surfacing it
511 // then.537 // then.
512 Picture::grey(config.width, config.height).check_even()?;538 Picture::grey(config.width, config.height).check_even()?;
539+ // A tile is a whole number of superblocks, so a frame cannot carry
540+ // more tile columns (rows) than it has 64x64 superblocks across
541+ // (down) -- the header's own `max_log2_tile_cols` bound (spec
542+ // 5.9.15), refused here rather than at the first `encode()` call.
543+ let sb_cols = config.width.div_ceil(64) as u32;
544+ let sb_rows = config.height.div_ceil(64) as u32;
545+ if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows {
546+ return Err(Error::unsupported(
547+ "AV1 encode",
548+ format!(
549+ "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has",
550+ 1 << config.tile_cols_log2,
551+ 1 << config.tile_rows_log2
552+ ),
553+ ));
554+ }
513 Ok(Self {555 Ok(Self {
514 carried_cdfs: None,556 carried_cdfs: None,
515 golden: None,557 golden: None,
@@ -632,6 +674,7 @@ impl Av1Encoder {
632 /// # Errors674 /// # Errors
633 /// As [`Av1Encoder::encode`], minus the pyramid refusal.675 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
634 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {676 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
677+ crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
635 if (picture.width, picture.height) != (self.config.width, self.config.height) {678 if (picture.width, picture.height) != (self.config.width, self.config.height) {
636 return Err(Error::unsupported(679 return Err(Error::unsupported(
637 "AV1 encode",680 "AV1 encode",
@@ -671,6 +714,7 @@ impl Av1Encoder {
671 /// # Errors714 /// # Errors
672 /// As [`Av1Encoder::encode_frames`].715 /// As [`Av1Encoder::encode_frames`].
673 pub fn flush(&mut self) -> Result<Vec<Packet>> {716 pub fn flush(&mut self) -> Result<Vec<Packet>> {
717+ crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
674 self.drain_pending()718 self.drain_pending()
675 }719 }
676 720
@@ -1014,6 +1058,8 @@ mod tests {
1014 base_q_idx: 100,1058 base_q_idx: 100,
1015 gop: 2,1059 gop: 2,
1016 colour: Colour::Bt709Limited,1060 colour: Colour::Bt709Limited,
1061+ tile_cols_log2: 0,
1062+ tile_rows_log2: 0,
1017 };1063 };
1018 let mut enc = Av1Encoder::new(config).unwrap();1064 let mut enc = Av1Encoder::new(config).unwrap();
1019 for t in 0..5u64 {1065 for t in 0..5u64 {
@@ -1034,6 +1080,8 @@ mod tests {
1034 base_q_idx: 100,1080 base_q_idx: 100,
1035 gop: 3,1081 gop: 3,
1036 colour: Colour::Unspecified,1082 colour: Colour::Unspecified,
1083+ tile_cols_log2: 0,
1084+ tile_rows_log2: 0,
1037 };1085 };
1038 let mut enc = Av1Encoder::new(config).unwrap();1086 let mut enc = Av1Encoder::new(config).unwrap();
1039 let keys: Vec<bool> = (0..7)1087 let keys: Vec<bool> = (0..7)
@@ -1132,6 +1180,8 @@ mod tests {
1132 base_q_idx: 120,1180 base_q_idx: 120,
1133 gop: 15,1181 gop: 15,
1134 colour: Colour::Bt709Limited,1182 colour: Colour::Bt709Limited,
1183+ tile_cols_log2: 0,
1184+ tile_rows_log2: 0,
1135 };1185 };
1136 let mut enc = Av1Encoder::new(config).unwrap();1186 let mut enc = Av1Encoder::new(config).unwrap();
1137 assert_eq!(enc.display_size(), (width, height));1187 assert_eq!(enc.display_size(), (width, height));
@@ -1185,6 +1235,8 @@ mod tests {
1185 base_q_idx: 100,1235 base_q_idx: 100,
1186 gop: 4,1236 gop: 4,
1187 colour: Colour::Bt709Limited,1237 colour: Colour::Bt709Limited,
1238+ tile_cols_log2: 0,
1239+ tile_rows_log2: 0,
1188 };1240 };
1189 let mut enc = Av1Encoder::new(config).unwrap();1241 let mut enc = Av1Encoder::new(config).unwrap();
1190 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();1242 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
@@ -1207,6 +1259,8 @@ mod tests {
1207 base_q_idx: 100,1259 base_q_idx: 100,
1208 gop: 4,1260 gop: 4,
1209 colour: Colour::Bt601Limited,1261 colour: Colour::Bt601Limited,
1262+ tile_cols_log2: 0,
1263+ tile_rows_log2: 0,
1210 };1264 };
1211 let mut enc = Av1Encoder::new(config).unwrap();1265 let mut enc = Av1Encoder::new(config).unwrap();
1212 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();1266 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
@@ -1227,6 +1281,8 @@ mod tests {
1227 base_q_idx: 100,1281 base_q_idx: 100,
1228 gop: 4,1282 gop: 4,
1229 colour: Colour::Bt709Limited,1283 colour: Colour::Bt709Limited,
1284+ tile_cols_log2: 0,
1285+ tile_rows_log2: 0,
1230 };1286 };
1231 let mut enc = Av1Encoder::new(config).unwrap();1287 let mut enc = Av1Encoder::new(config).unwrap();
1232 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();1288 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
@@ -1242,6 +1298,8 @@ mod tests {
1242 base_q_idx: 100,1298 base_q_idx: 100,
1243 gop: 0,1299 gop: 0,
1244 colour: Colour::Bt709Limited,1300 colour: Colour::Bt709Limited,
1301+ tile_cols_log2: 0,
1302+ tile_rows_log2: 0,
1245 };1303 };
1246 let err = Av1Encoder::new(config).unwrap_err();1304 let err = Av1Encoder::new(config).unwrap_err();
1247 assert!(err.to_string().contains("gop"), "{err}");1305 assert!(err.to_string().contains("gop"), "{err}");
@@ -1313,6 +1371,8 @@ mod tests {
1313 base_q_idx: 100,1371 base_q_idx: 100,
1314 gop: 24,1372 gop: 24,
1315 colour: Colour::Bt709Limited,1373 colour: Colour::Bt709Limited,
1374+ tile_cols_log2: 0,
1375+ tile_rows_log2: 0,
1316 };1376 };
1317 let mut enc =1377 let mut enc =
1318 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();1378 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
@@ -1352,6 +1412,8 @@ mod tests {
1352 base_q_idx: 100,1412 base_q_idx: 100,
1353 gop: frames,1413 gop: frames,
1354 colour: Colour::Bt709Limited,1414 colour: Colour::Bt709Limited,
1415+ tile_cols_log2: 0,
1416+ tile_rows_log2: 0,
1355 };1417 };
1356 let rate = RateTarget::Bitrate {1418 let rate = RateTarget::Bitrate {
1357 bits_per_second,1419 bits_per_second,
@@ -1409,6 +1471,8 @@ mod tests {
1409 base_q_idx: 100,1471 base_q_idx: 100,
1410 gop: 24,1472 gop: 24,
1411 colour: Colour::Bt709Limited,1473 colour: Colour::Bt709Limited,
1474+ tile_cols_log2: 0,
1475+ tile_rows_log2: 0,
1412 };1476 };
1413 let mut enc =1477 let mut enc =
1414 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();1478 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
@@ -1491,6 +1555,8 @@ mod tests {
1491 base_q_idx: 120,1555 base_q_idx: 120,
1492 gop: 32,1556 gop: 32,
1493 colour: Colour::Bt709Limited,1557 colour: Colour::Bt709Limited,
1558+ tile_cols_log2: 0,
1559+ tile_rows_log2: 0,
1494 };1560 };
1495 let pyramid = Pyramid {1561 let pyramid = Pyramid {
1496 mini_gop: 4,1562 mini_gop: 4,
@@ -1594,6 +1660,8 @@ mod tests {
1594 base_q_idx: 100,1660 base_q_idx: 100,
1595 gop: 8,1661 gop: 8,
1596 colour: Colour::Bt709Limited,1662 colour: Colour::Bt709Limited,
1663+ tile_cols_log2: 0,
1664+ tile_rows_log2: 0,
1597 };1665 };
1598 let mut enc =1666 let mut enc =
1599 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();1667 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
crates/ec-av1/src/frame.rsmodified+41 -0
@@ -595,6 +595,47 @@ pub fn show_existing_frame_obu(seq: &SequenceHeader, frame_to_show_map_idx: u8)
595 ))595 ))
596 }596 }
597 597
598+/// How wide a tile group's per-tile size field has to be for these tiles
599+/// (`TileSizeBytes`, spec 5.11.1: every non-last tile carries `size - 1` in
600+/// that many bytes, so the widest of them decides).
601+pub(crate) fn tile_size_bytes_for(tiles: &[Vec<u8>]) -> u32 {
602+ let widest = tiles
603+ .iter()
604+ .rev()
605+ .skip(1)
606+ .map(|t| t.len().saturating_sub(1))
607+ .max()
608+ .unwrap_or(0);
609+ match widest {
610+ 0..=0xFF => 1,
611+ 0x100..=0xFFFF => 2,
612+ 0x1_0000..=0xFF_FFFF => 3,
613+ _ => 4,
614+ }
615+}
616+
617+/// `tile_group_obu()` (spec 5.11.1) for a group holding every tile of the
618+/// frame: `tile_start_and_end_present_flag = 0` (only coded when the frame
619+/// has more than one tile), byte alignment, then each tile's size (all but
620+/// the last, little endian, `tile_size_bytes` wide) ahead of its payload.
621+/// One tile leaves the payload exactly as it was, which is what every
622+/// single-tile stream this crate wrote before tiles existed carries.
623+pub(crate) fn tile_group_payload(tiles: &[Vec<u8>], tile_size_bytes: u32) -> Vec<u8> {
624+ if tiles.len() == 1 {
625+ return tiles[0].clone();
626+ }
627+ // The flag bit plus `byte_alignment()`: one zero byte.
628+ let mut out = vec![0u8];
629+ for (i, tile) in tiles.iter().enumerate() {
630+ if i + 1 < tiles.len() {
631+ let size = (tile.len() - 1) as u32;
632+ out.extend((0..tile_size_bytes).map(|b| (size >> (8 * b)) as u8));
633+ }
634+ out.extend_from_slice(tile);
635+ }
636+ out
637+}
638+
598 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group639 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group
599 /// payload the caller supplies.640 /// payload the caller supplies.
600 pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {641 pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {
crates/ec-av1/src/tile.rsmodified+179 -6
@@ -116,6 +116,150 @@ fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32)
116 /// `crate::decode`), the span [`write_lr`] resolves its units over.116 /// `crate::decode`), the span [`write_lr`] resolves its units over.
117 const SB_MI_W: u32 = 16;117 const SB_MI_W: u32 = 16;
118 118
119+/// One tile's own superblock and mode-info span (spec 5.11.1's tile loop
120+/// bounds): `MiColStarts[i]..MiColStarts[i+1]` and the same down the rows,
121+/// with the superblock indices those mi bounds fall on. The writers walk
122+/// exactly this rect, and everything a block reads outside it -- the
123+/// neighbour bands, the MV grid -- is left at the "unavailable" state a
124+/// tile's own first row and column see, which is how the decoder clips them
125+/// (`MiGrid::set_tile_bounds`, `PlaneBuf::set_tile_origin`).
126+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127+pub(crate) struct TileRect {
128+ pub(crate) sb_col0: u32,
129+ pub(crate) sb_col1: u32,
130+ pub(crate) sb_row0: u32,
131+ pub(crate) sb_row1: u32,
132+ pub(crate) mi_col0: u32,
133+ pub(crate) mi_col1: u32,
134+ pub(crate) mi_row0: u32,
135+ pub(crate) mi_row1: u32,
136+}
137+
138+impl TileRect {
139+ /// The whole frame as one tile -- what every single-tile caller writes.
140+ pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self {
141+ let (cols, rows) = block_grid(mi_cols, mi_rows);
142+ Self {
143+ sb_col0: 0,
144+ sb_col1: cols.div_ceil(2),
145+ sb_row0: 0,
146+ sb_row1: rows.div_ceil(2),
147+ mi_col0: 0,
148+ mi_col1: mi_cols,
149+ mi_row0: 0,
150+ mi_row1: mi_rows,
151+ }
152+ }
153+}
154+
155+/// A frame's uniform tile grid (spec 5.9.15's `uniform_tile_spacing_flag`
156+/// arm, mirrored from `ec_av1_syntax::frame::read_tile_info` so that what
157+/// this encoder writes and what a decoder derives from the same two log2
158+/// fields are the same rects). 64x64 superblocks only, which is the only
159+/// size this encoder's sequence header signals.
160+#[derive(Clone, Debug)]
161+pub(crate) struct TileLayout {
162+ pub(crate) cols_log2: u32,
163+ pub(crate) rows_log2: u32,
164+ /// Tile column starts in superblocks, `cols + 1` entries.
165+ col_starts_sb: Vec<u32>,
166+ /// Tile row starts in superblocks, `rows + 1` entries.
167+ row_starts_sb: Vec<u32>,
168+ mi_cols: u32,
169+ mi_rows: u32,
170+}
171+
172+impl TileLayout {
173+ /// The layout `cols_log2`/`rows_log2` name for this frame's mi grid.
174+ pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self {
175+ let (cols32, rows32) = block_grid(mi_cols, mi_rows);
176+ let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2));
177+ let starts = |total: u32, log2: u32| {
178+ let step = total.div_ceil(1 << log2).max(1);
179+ let mut v: Vec<u32> = (0..total).step_by(step as usize).collect();
180+ v.push(total);
181+ v
182+ };
183+ Self {
184+ cols_log2,
185+ rows_log2,
186+ col_starts_sb: starts(sb_cols, cols_log2),
187+ row_starts_sb: starts(sb_rows, rows_log2),
188+ mi_cols,
189+ mi_rows,
190+ }
191+ }
192+
193+ pub(crate) fn cols(&self) -> u32 {
194+ self.col_starts_sb.len() as u32 - 1
195+ }
196+
197+ pub(crate) fn rows(&self) -> u32 {
198+ self.row_starts_sb.len() as u32 - 1
199+ }
200+
201+ pub(crate) fn count(&self) -> usize {
202+ (self.cols() * self.rows()) as usize
203+ }
204+
205+ /// `MiColStarts`/`MiRowStarts` as the frame header carries them.
206+ pub(crate) fn mi_col_starts(&self) -> Vec<u32> {
207+ let mut v: Vec<u32> = self.col_starts_sb[..self.cols() as usize]
208+ .iter()
209+ .map(|sb| sb * SB_MI_W)
210+ .collect();
211+ v.push(self.mi_cols);
212+ v
213+ }
214+
215+ pub(crate) fn mi_row_starts(&self) -> Vec<u32> {
216+ let mut v: Vec<u32> = self.row_starts_sb[..self.rows() as usize]
217+ .iter()
218+ .map(|sb| sb * SB_MI_W)
219+ .collect();
220+ v.push(self.mi_rows);
221+ v
222+ }
223+
224+ /// Tile `index` (row major, `TileNum`) as a rect.
225+ pub(crate) fn rect(&self, index: usize) -> TileRect {
226+ let (r, c) = (index / self.cols() as usize, index % self.cols() as usize);
227+ let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]);
228+ let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]);
229+ TileRect {
230+ sb_col0,
231+ sb_col1,
232+ sb_row0,
233+ sb_row1,
234+ mi_col0: sb_col0 * SB_MI_W,
235+ mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols),
236+ mi_row0: sb_row0 * SB_MI_W,
237+ mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows),
238+ }
239+ }
240+
241+ /// Which tile the superblock at `(sb_r, sb_c)` belongs to -- what the
242+ /// encoder's frame-raster search consults to clip a block's neighbour
243+ /// availability to its own tile.
244+ pub(crate) fn index_of_sb(&self, sb_r: u32, sb_c: u32) -> usize {
245+ let col = self.col_starts_sb[1..].partition_point(|&s| s <= sb_c);
246+ let row = self.row_starts_sb[1..].partition_point(|&s| s <= sb_r);
247+ row * self.cols() as usize + col
248+ }
249+
250+ /// The largest tile by mi area, `context_update_tile_id`'s own rule
251+ /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both
252+ /// name the biggest tile, whose end-of-tile tables the frame stores).
253+ pub(crate) fn largest_tile(&self) -> usize {
254+ (0..self.count())
255+ .max_by_key(|&i| {
256+ let t = self.rect(i);
257+ ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64)
258+ })
259+ .unwrap_or(0)
260+ }
261+}
262+
119 /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).263 /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
120 struct CdefIdxPlan {264 struct CdefIdxPlan {
121 /// The header's `cdef_bits`; never 0 while armed.265 /// The header's `cdef_bits`; never 0 while armed.
@@ -1240,7 +1384,15 @@ pub fn sb_coeff_key_frame_tile_tx(
1240 tx_select: bool,1384 tx_select: bool,
1241 ) -> Result<Vec<u8>> {1385 ) -> Result<Vec<u8>> {
1242 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));1386 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1243- sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs)1387+ sb_coeff_key_frame_tile_cdfs(
1388+ mi_cols,
1389+ mi_rows,
1390+ base_q_idx,
1391+ superblocks,
1392+ tx_select,
1393+ &mut cdfs,
1394+ TileRect::whole(mi_cols, mi_rows),
1395+ )
1244 }1396 }
1245 1397
1246 /// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the1398 /// [`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(
1258 superblocks: &[Superblock],1410 superblocks: &[Superblock],
1259 tx_select: bool,1411 tx_select: bool,
1260 cdfs: &mut Cdfs,1412 cdfs: &mut Cdfs,
1413+ // This tile's own span (spec 5.11.1): the writer walks only these
1414+ // superblocks, and its neighbour bands start blank, so everything
1415+ // outside reads as unavailable exactly as the decoder's own per-tile
1416+ // reset makes it.
1417+ tile: TileRect,
1261 ) -> Result<Vec<u8>> {1418 ) -> Result<Vec<u8>> {
1262 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.1419 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
1263 let _cdef_idx = CdefIdxGuard;1420 let _cdef_idx = CdefIdxGuard;
@@ -1321,9 +1478,9 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1321 // off.1478 // off.
1322 let mut cdfs = cdfs;1479 let mut cdfs = cdfs;
1323 let mut enc = SymbolEncoder::new();1480 let mut enc = SymbolEncoder::new();
1324- for sb_r in 0..sb_rows {1481+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
1325 neighbours.start_row();1482 neighbours.start_row();
1326- for sb_c in 0..sb_cols {1483+ for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
1327 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);1484 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
1328 let at = (sb_r as usize * 4, sb_c as usize * 4);1485 let at = (sb_r as usize * 4, sb_c as usize * 4);
1329 let ctx = neighbours.partition_ctx(at, SB);1486 let ctx = neighbours.partition_ctx(at, SB);
@@ -3170,7 +3327,15 @@ pub fn sb_coeff_inter_frame_tile_tx(
3170 tx_select: bool,3327 tx_select: bool,
3171 ) -> Result<Vec<u8>> {3328 ) -> Result<Vec<u8>> {
3172 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));3329 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3173- sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs)3330+ sb_coeff_inter_frame_tile_cdfs(
3331+ mi_cols,
3332+ mi_rows,
3333+ base_q_idx,
3334+ blocks,
3335+ tx_select,
3336+ &mut cdfs,
3337+ TileRect::whole(mi_cols, mi_rows),
3338+ )
3174 }3339 }
3175 3340
3176 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --3341 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
@@ -3185,6 +3350,8 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3185 blocks: &[Quadrant],3350 blocks: &[Quadrant],
3186 tx_select: bool,3351 tx_select: bool,
3187 cdfs: &mut Cdfs,3352 cdfs: &mut Cdfs,
3353+ // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
3354+ tile: TileRect,
3188 ) -> Result<Vec<u8>> {3355 ) -> Result<Vec<u8>> {
3189 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.3356 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3190 let _cdef_idx = CdefIdxGuard;3357 let _cdef_idx = CdefIdxGuard;
@@ -3226,6 +3393,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3226 mi_rows as usize,3393 mi_rows as usize,
3227 );3394 );
3228 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);3395 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
3396+ grid.set_tile_bounds(
3397+ tile.mi_row0 as usize,
3398+ tile.mi_col0 as usize,
3399+ tile.mi_row1 as usize,
3400+ tile.mi_col1 as usize,
3401+ );
3229 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));3402 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
3230 let mut cdfs = cdfs;3403 let mut cdfs = cdfs;
3231 let mut enc = SymbolEncoder::new();3404 let mut enc = SymbolEncoder::new();
@@ -3253,9 +3426,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3253 vec![0i32; TX16 * TX16],3426 vec![0i32; TX16 * TX16],
3254 ];3427 ];
3255 3428
3256- for sb_r in 0..sb_rows {3429+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
3257 neighbours.start_row();3430 neighbours.start_row();
3258- for sb_c in 0..sb_cols {3431+ for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
3259 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);3432 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
3260 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);3433 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
3261 let sb_ctx = neighbours.partition_ctx(sb_at, SB);3434 let sb_ctx = neighbours.partition_ctx(sb_at, SB);