forge
Explore
Log in

Don't you dare go Hollow

merge main 1c844b01 (tile layout) into the palette lane

Browse files at this commit

eeee02351b4eeb7f5673ce5662bafaf83e27396cAhmet Kaan GümüşParent: 625e01eb58ff3f
Hand-resolved: the palette write sits inside the per-tile closures main's
TileLayout introduced, so `arm_screen` is armed per tile job beside
`arm_sign_bias`/`arm_reference_select`; the new plural
`decode_inter_frame_tiles_lr` takes this lane's `allow_screen_content_tools`
and the single-tile wrapper forwards it.
crates/ec-av1/src/decode.rsmodified+100 -3
@@ -20763,18 +20763,61 @@ pub(crate) fn decode_key_frame_tile_lr(
20763 lr: &LoopRestorationParams,20763 lr: &LoopRestorationParams,
20764 fctx: &crate::decode::FrameCtx,20764 fctx: &crate::decode::FrameCtx,
20765 ) -> Result<Picture> {20765 ) -> Result<Picture> {
20766- let delta = DeltaParams::default();
20767 let single_tile = TileInfo {20766 let single_tile = TileInfo {
20768 mi_col_starts: vec![0, mi_cols],20767 mi_col_starts: vec![0, mi_cols],
20769 mi_row_starts: vec![0, mi_rows],20768 mi_row_starts: vec![0, mi_rows],
20770 ..TileInfo::default()20769 ..TileInfo::default()
20771 };20770 };
20772- decode_key_frame_tile_with_cdfs(20771+ decode_key_frame_tiles_lr(
20773 &[data],20772 &[data],
20774 &single_tile,20773 &single_tile,
20775 mi_cols,20774 mi_cols,
20776 mi_rows,20775 mi_rows,
20777 base_q_idx,20776 base_q_idx,
20777+ frame_width,
20778+ frame_height,
20779+ enable_filter_intra,
20780+ cdef,
20781+ loop_filter,
20782+ tx_select,
20783+ reduced_tx_set,
20784+ allow_screen_content_tools,
20785+ allow_intrabc,
20786+ lr,
20787+ fctx,
20788+ )
20789+}
20790+
20791+/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the
20792+/// encoder's own filter search hands back one payload per tile plus the
20793+/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets
20794+/// are the decoder's own (`decode_key_frame_tile_with_cdfs`).
20795+#[allow(clippy::too_many_arguments)]
20796+pub(crate) fn decode_key_frame_tiles_lr(
20797+ tiles: &[&[u8]],
20798+ tile_info: &TileInfo,
20799+ mi_cols: u32,
20800+ mi_rows: u32,
20801+ base_q_idx: u8,
20802+ frame_width: u32,
20803+ frame_height: u32,
20804+ enable_filter_intra: bool,
20805+ cdef: &CdefParams,
20806+ loop_filter: &LoopFilterParams,
20807+ tx_select: bool,
20808+ reduced_tx_set: bool,
20809+ allow_screen_content_tools: bool,
20810+ allow_intrabc: bool,
20811+ lr: &LoopRestorationParams,
20812+ fctx: &crate::decode::FrameCtx,
20813+) -> Result<Picture> {
20814+ let delta = DeltaParams::default();
20815+ decode_key_frame_tile_with_cdfs(
20816+ tiles,
20817+ tile_info,
20818+ mi_cols,
20819+ mi_rows,
20820+ base_q_idx,
20778 crate::quant::QuantDeltas::default(),20821 crate::quant::QuantDeltas::default(),
20779 frame_width,20822 frame_width,
20780 frame_height,20823 frame_height,
@@ -25394,6 +25437,7 @@ fn decode_inter_block(
25394 // combinations that don't implement scaled MC yet.25437 // combinations that don't implement scaled MC yet.
25395 frame_width: usize, fctx: &crate::decode::FrameCtx,25438 frame_width: usize, fctx: &crate::decode::FrameCtx,
25396 ) -> Result<()> {25439 ) -> Result<()> {
25440+
25397 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can25441 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
25398 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the25442 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
25399 // few 16-px-granular uses below.25443 // few 16-px-granular uses below.
@@ -32945,12 +32989,65 @@ pub(crate) fn decode_inter_frame_tile_lr(
32945 mi_row_starts: vec![0, mi_rows],32989 mi_row_starts: vec![0, mi_rows],
32946 ..TileInfo::default()32990 ..TileInfo::default()
32947 };32991 };
32948- decode_inter_frame_tile_with_cdfs(32992+ decode_inter_frame_tiles_lr(
32949 &[data],32993 &[data],
32950 &single_tile,32994 &single_tile,
32951 mi_cols,32995 mi_cols,
32952 mi_rows,32996 mi_rows,
32953 base_q_idx,32997 base_q_idx,
32998+ frame_width,
32999+ frame_height,
33000+ refpix,
33001+ cdef,
33002+ loop_filter,
33003+ allow_high_precision_mv,
33004+ force_integer_mv,
33005+ interp_fixed,
33006+ enable_dual_filter,
33007+ reference_select,
33008+ tx_select,
33009+ lr,
33010+ initial_cdfs,
33011+ sign_bias,
33012+ allow_screen_content_tools,
33013+ fctx,
33014+ )
33015+}
33016+
33017+/// [`decode_inter_frame_tile_lr`] for a frame coded as SEVERAL tiles; see
33018+/// [`decode_key_frame_tiles_lr`].
33019+#[allow(clippy::too_many_arguments)]
33020+pub(crate) fn decode_inter_frame_tiles_lr(
33021+ tiles: &[&[u8]],
33022+ tile_info: &TileInfo,
33023+ mi_cols: u32,
33024+ mi_rows: u32,
33025+ base_q_idx: u8,
33026+ frame_width: u32,
33027+ frame_height: u32,
33028+ refpix: &RefPix<'_>,
33029+ cdef: &CdefParams,
33030+ loop_filter: &LoopFilterParams,
33031+ allow_high_precision_mv: bool,
33032+ force_integer_mv: bool,
33033+ interp_fixed: Option<mc::InterpFilterKind>,
33034+ enable_dual_filter: bool,
33035+ reference_select: bool,
33036+ tx_select: bool,
33037+ lr: &LoopRestorationParams,
33038+ initial_cdfs: Option<Cdfs>,
33039+ sign_bias: crate::mvstack::SignBiasTable,
33040+ // This frame header's own `allow_screen_content_tools` (see the
33041+ // single-tile wrapper): the palette syntax its intra blocks carry.
33042+ allow_screen_content_tools: bool,
33043+ fctx: &crate::decode::FrameCtx,
33044+) -> Result<Picture> {
33045+ decode_inter_frame_tile_with_cdfs(
33046+ tiles,
33047+ tile_info,
33048+ mi_cols,
33049+ mi_rows,
33050+ base_q_idx,
32954 crate::quant::QuantDeltas::default(),33051 crate::quant::QuantDeltas::default(),
32955 frame_width,33052 frame_width,
32956 frame_height,33053 frame_height,
crates/ec-av1/src/encode.rsmodified+330 -95
@@ -1110,9 +1110,28 @@ struct Plane<'a> {
1110 /// edge.1110 /// edge.
1111 true_width: usize,1111 true_width: usize,
1112 true_height: usize,1112 true_height: usize,
1113+ /// This plane's own tile's pixel bounds, in this plane's units -- the
1114+ /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
1115+ /// prediction never reaches across a tile edge even though the
1116+ /// neighbouring tile's real samples sit right there in the shared
1117+ /// reconstruction. `(0, 0, width, height)` is the single-tile case and
1118+ /// leaves every edge exactly as it was before tiles existed.
1119+ tile_x0: usize,
1120+ tile_y0: usize,
1121+ tile_x1: usize,
1122+ tile_y1: usize,
1113 }1123 }
1114 1124
1115 impl Plane<'_> {1125 impl Plane<'_> {
1126+ /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
1127+ /// called at every superblock of the frame-raster search with the rect
1128+ /// of the tile that superblock belongs to.
1129+ fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
1130+ self.tile_x0 = x0;
1131+ self.tile_y0 = y0;
1132+ self.tile_x1 = x1.min(self.width);
1133+ self.tile_y1 = y1.min(self.height);
1134+ }
1116 /// The reconstructed samples a block at `(x, y)` predicts from: the row1135 /// The reconstructed samples a block at `(x, y)` predicts from: the row
1117 /// above it, the column to its left and the sample between them, each1136 /// above it, the column to its left and the sample between them, each
1118 /// missing where the block sits against an edge of the frame.1137 /// missing where the block sits against an edge of the frame.
@@ -1164,14 +1183,17 @@ impl Plane<'_> {
1164 // `a_picture_off_the_block_grid_is_refused`), never through a block1183 // `a_picture_off_the_block_grid_is_refused`), never through a block
1165 // this encoder actually commits. Such a block has no true-edge1184 // this encoder actually commits. Such a block has no true-edge
1166 // samples above or left of it at all, same as `y == 0`/`x == 0`.1185 // samples above or left of it at all, same as `y == 0`/`x == 0`.
1167- let above = (y > 0 && across > x)1186+ let across = across.min(self.tile_x1);
1187+ let down = down.min(self.tile_y1);
1188+ let above = (y > self.tile_y0 && across > x)
1168 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());1189 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());
1169- let left = (x > 0 && down > y).then(|| {1190+ let left = (x > self.tile_x0 && down > y).then(|| {
1170 (y..down)1191 (y..down)
1171 .map(|row| self.reconstruction[row * self.width + x - 1])1192 .map(|row| self.reconstruction[row * self.width + x - 1])
1172 .collect::<Vec<_>>()1193 .collect::<Vec<_>>()
1173 });1194 });
1174- let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]);1195+ let corner = (x > self.tile_x0 && y > self.tile_y0)
1196+ .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
1175 (above, left, corner)1197 (above, left, corner)
1176 }1198 }
1177 1199
@@ -3241,6 +3263,126 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
3241 .collect()3263 .collect()
3242 }3264 }
3243 3265
3266+thread_local! {
3267+ /// The tile grid the next frame is coded with, as `(TileColsLog2,
3268+ /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
3269+ /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
3270+ /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
3271+ /// one tile per frame, what every caller that never arms anything gets
3272+ /// and what every stream this crate wrote before tiles existed carries.
3273+ static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
3274+}
3275+
3276+/// Arms this thread's next frame encodes with a tile grid (log2 counts).
3277+pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
3278+ TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
3279+}
3280+
3281+fn armed_tiles() -> (u32, u32) {
3282+ let armed = TILE_LOG2.with(std::cell::Cell::get);
3283+ if armed != (0, 0) {
3284+ return armed;
3285+ }
3286+ // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
3287+ // (which codes through `encode_sequence`, not the facade) can measure what
3288+ // a tile grid costs without a knob of its own -- same shape as
3289+ // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
3290+ match std::env::var("EC_AV1_TILES").ok() {
3291+ Some(v) if cfg!(test) => {
3292+ let mut f = v.split(':');
3293+ let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
3294+ let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
3295+ (cols, rows)
3296+ }
3297+ _ => armed,
3298+ }
3299+}
3300+
3301+/// Codes a frame's `tiles` tiles, each entirely on its own (see
3302+/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
3303+/// the crate's own pool, and hands back their payloads in tile order plus
3304+/// whatever `code` returned for tile `store` -- the CDF state
3305+/// `context_update_tile_id` names. The result cannot depend on the thread
3306+/// count: each job writes one tile from the frame's own starting tables into
3307+/// its own slot.
3308+fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
3309+where
3310+ F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
3311+{
3312+ type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
3313+ let threads = crate::par::tile_threads().min(tiles);
3314+ let mut slots: Vec<Slot> = Vec::new();
3315+ if threads <= 1 {
3316+ for index in 0..tiles {
3317+ slots.push(Some(code(index)));
3318+ }
3319+ } else {
3320+ let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
3321+ {
3322+ let batch = crate::par::Batch::new("ec-av1-tile");
3323+ for (from, to) in crate::par::bands(tiles, threads) {
3324+ let done = &done;
3325+ let code = &code;
3326+ batch.submit(move || {
3327+ for index in from..to {
3328+ let coded = code(index);
3329+ done.lock().expect("tile slots")[index] = Some(coded);
3330+ }
3331+ });
3332+ }
3333+ }
3334+ slots = done.into_inner().expect("tile slots");
3335+ }
3336+ let mut out = Vec::with_capacity(tiles);
3337+ let mut stored = None;
3338+ for (index, slot) in slots.into_iter().enumerate() {
3339+ let (bytes, cdfs) = slot.expect("every tile was coded")?;
3340+ if index == store {
3341+ stored = cdfs;
3342+ }
3343+ out.push(bytes);
3344+ }
3345+ Ok((out, stored))
3346+}
3347+
3348+/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
3349+/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
3350+/// tables the frame stores (spec 7.20), which is what
3351+/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
3352+/// below publish.
3353+fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
3354+ ec_av1_syntax::TileInfo {
3355+ uniform_spacing: true,
3356+ cols: layout.cols(),
3357+ rows: layout.rows(),
3358+ cols_log2: layout.cols_log2,
3359+ rows_log2: layout.rows_log2,
3360+ mi_col_starts: layout.mi_col_starts(),
3361+ mi_row_starts: layout.mi_row_starts(),
3362+ context_update_tile_id: layout.largest_tile() as u32,
3363+ tile_size_bytes,
3364+ }
3365+}
3366+
3367+/// Clips the three planes' intra edge reads to `rect`, the tile the
3368+/// superblock about to be searched belongs to (the encoder side of the
3369+/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
3370+/// raster order -- which is a linear extension of every tile's own coding
3371+/// order, so a block still only ever predicts from samples already
3372+/// reconstructed -- and only availability is tile-relative.
3373+fn clip_planes_to_tile(
3374+ luma: &mut Plane<'_>,
3375+ chroma: &mut [Plane<'_>; 2],
3376+ rect: crate::tile::TileRect,
3377+) {
3378+ let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
3379+ let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
3380+ luma.set_tile(x0, y0, x1, y1);
3381+ for plane in chroma.iter_mut() {
3382+ plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
3383+ }
3384+}
3385+
3244 /// Encodes one picture as a key frame.3386 /// Encodes one picture as a key frame.
3245 ///3387 ///
3246 /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer3388 /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
@@ -3393,6 +3535,7 @@ pub(crate) fn encode_key_frame_inner(
3393 if tx_select {3535 if tx_select {
3394 header.tx_mode = TxMode::Select;3536 header.tx_mode = TxMode::Select;
3395 }3537 }
3538+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
3396 3539
3397 // Prediction reads no further than this, in each plane's own units --3540 // Prediction reads no further than this, in each plane's own units --
3398 // see `Plane::true_width`/`true_height`.3541 // see `Plane::true_width`/`true_height`.
@@ -3411,6 +3554,10 @@ pub(crate) fn encode_key_frame_inner(
3411 height: picture.height,3554 height: picture.height,
3412 true_width,3555 true_width,
3413 true_height,3556 true_height,
3557+ tile_x0: 0,
3558+ tile_y0: 0,
3559+ tile_x1: picture.width,
3560+ tile_y1: picture.height,
3414 };3561 };
3415 let mut chroma = [3562 let mut chroma = [
3416 Plane {3563 Plane {
@@ -3420,6 +3567,10 @@ pub(crate) fn encode_key_frame_inner(
3420 height: picture.height / 2,3567 height: picture.height / 2,
3421 true_width: true_width / 2,3568 true_width: true_width / 2,
3422 true_height: true_height / 2,3569 true_height: true_height / 2,
3570+ tile_x0: 0,
3571+ tile_y0: 0,
3572+ tile_x1: picture.width / 2,
3573+ tile_y1: picture.height / 2,
3423 },3574 },
3424 Plane {3575 Plane {
3425 source: &picture_v8,3576 source: &picture_v8,
@@ -3428,6 +3579,10 @@ pub(crate) fn encode_key_frame_inner(
3428 height: picture.height / 2,3579 height: picture.height / 2,
3429 true_width: true_width / 2,3580 true_width: true_width / 2,
3430 true_height: true_height / 2,3581 true_height: true_height / 2,
3582+ tile_x0: 0,
3583+ tile_y0: 0,
3584+ tile_x1: picture.width / 2,
3585+ tile_y1: picture.height / 2,
3431 },3586 },
3432 ];3587 ];
3433 3588
@@ -3460,10 +3615,24 @@ pub(crate) fn encode_key_frame_inner(
3460 let mut above_mode = vec![DC_PRED; cols * 2];3615 let mut above_mode = vec![DC_PRED; cols * 2];
3461 let mut left_mode = vec![DC_PRED; rows * 2];3616 let mut left_mode = vec![DC_PRED; rows * 2];
3462 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));3617 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3618+ // This frame's tile grid (one tile unless the facade armed more).
3619+ let layout =
3620+ crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
3621+ header.tile_info = tile_info_of(&layout, 1);
3622+ // The filter search re-decodes this frame's tiles; the decoder derives
3623+ // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
3624+ // `mi_row_starts`), which is what makes the writer's rects and the
3625+ // reader's the same rects.
3626+ let header_tile_info = header.tile_info.clone();
3463 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);3627 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
3464 let mut modes = Vec::with_capacity(cols * rows);3628 let mut modes = Vec::with_capacity(cols * rows);
3465 for sb_row in 0..sb_rows {3629 for sb_row in 0..sb_rows {
3466 for sb_col in 0..sb_cols {3630 for sb_col in 0..sb_cols {
3631+ clip_planes_to_tile(
3632+ &mut luma,
3633+ &mut chroma,
3634+ layout.rect(layout.index_of_sb(sb_row as u32, sb_col as u32)),
3635+ );
3467 // The quadrants of a superblock are coded in the order the decoder3636 // The quadrants of a superblock are coded in the order the decoder
3468 // walks them, which for a 64x64 split into 32x32 blocks is raster3637 // walks them, which for a 64x64 split into 32x32 blocks is raster
3469 // order among the quadrants that are inside the frame.3638 // order among the quadrants that are inside the frame.
@@ -3659,58 +3828,66 @@ pub(crate) fn encode_key_frame_inner(
3659 // defaults again (spec 7.20's `started_from` arm) -- the first inter3828 // defaults again (spec 7.20's `started_from` arm) -- the first inter
3660 // frame after it therefore starts from the defaults too.3829 // frame after it therefore starts from the defaults too.
3661 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);3830 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3662- let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));3831+ let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3663- let start_cdfs = CdfSnapshot(cdfs.clone());3832+ let start_cdfs = CdfSnapshot(cdfs);
3664- crate::tile::arm_screen(screen);
3665- let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
3666- mi_cols,
3667- mi_rows,
3668- base_q_idx,
3669- &superblocks,
3670- tx_select,
3671- &mut cdfs,
3672- )?;
3673- // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
3674- // the tile just coded back to the decoder under each candidate (see
3675- // `crate::filter_search`), and keep the filtered picture that wins as
3676- // the reconstruction -- what a decoder outputs, and what the next
3677- // frame predicts from.
3678 // The luma restoration-unit grid this frame's `lr_params` implies3833 // The luma restoration-unit grid this frame's `lr_params` implies
3679 // (`av1_lr_count_units` rounds to nearest, so a short last unit is3834 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3680 // swallowed by the one before it), for the tile writer's own per-unit3835 // swallowed by the one before it), for the tile writer's own per-unit
3681 // walk.3836 // walk.
3682 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;3837 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3683 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;3838 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3839+ // Every tile is coded from this frame's OWN starting tables and leaves
3840+ // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
3841+ // loop-restoration reference and its neighbour contexts), so the tiles
3842+ // are independent of each other and of the order they are written in.
3843+ let code_tiles = |bits: u8,
3844+ sb_cols: usize,
3845+ grid: &[u8],
3846+ units: &[Option<crate::restoration::WienerInfo>]|
3847+ -> Result<Vec<Vec<u8>>> {
3848+ let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
3849+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3850+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3851+ let mut cdfs = start_cdfs.0.clone();
3852+ crate::tile::arm_screen(screen);
3853+ let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
3854+ mi_cols,
3855+ mi_rows,
3856+ base_q_idx,
3857+ &superblocks,
3858+ tx_select,
3859+ &mut cdfs,
3860+ layout.rect(index),
3861+ )?;
3862+ Ok((bytes, None))
3863+ })?;
3864+ Ok(out)
3865+ };
3866+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
3867+ // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
3868+ // the tile just coded back to the decoder under each candidate (see
3869+ // `crate::filter_search`), and keep the filtered picture that wins as
3870+ // the reconstruction -- what a decoder outputs, and what the next
3871+ // frame predicts from.
3684 pick_and_apply_filters(3872 pick_and_apply_filters(
3685 &mut header,3873 &mut header,
3686 &mut luma,3874 &mut luma,
3687 &mut chroma,3875 &mut chroma,
3688 [&picture_y8, &picture_u8, &picture_v8],3876 [&picture_y8, &picture_u8, &picture_v8],
3689 true,3877 true,
3690- &mut tile,3878+ &mut tiles,
3691 search.lambda,3879 search.lambda,
3692 fctx,3880 fctx,
3693 // Every re-code starts from this frame's OWN starting tables, never3881 // Every re-code starts from this frame's OWN starting tables, never
3694 // from where the first write left them: the second tile is the same3882 // from where the first write left them: the second tile is the same
3695 // symbol sequence plus new ones, so it must adapt from the same3883 // symbol sequence plus new ones, so it must adapt from the same
3696 // point the decoder will.3884 // point the decoder will.
3697- |bits, sb_cols, grid, units| {3885+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
3698- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());3886+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
3699- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());3887+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
3700- let mut cdfs = start_cdfs.0.clone();3888+ crate::decode::decode_key_frame_tiles_lr(
3701- crate::tile::arm_screen(screen);3889+ &payloads,
3702- crate::tile::sb_coeff_key_frame_tile_cdfs(3890+ &header_tile_info,
3703- mi_cols,
3704- mi_rows,
3705- base_q_idx,
3706- &superblocks,
3707- tx_select,
3708- &mut cdfs,
3709- )
3710- },
3711- |lf, cdef, h, tile, lr| {
3712- crate::decode::decode_key_frame_tile_lr(
3713- tile,
3714 h.mi_cols,3891 h.mi_cols,
3715 h.mi_rows,3892 h.mi_rows,
3716 base_q_idx,3893 base_q_idx,
@@ -3728,6 +3905,9 @@ pub(crate) fn encode_key_frame_inner(
3728 )3905 )
3729 },3906 },
3730 )?;3907 )?;
3908+ let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
3909+ header.tile_info.tile_size_bytes = tile_size_bytes;
3910+ let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
3731 let mut stream = temporal_delimiter();3911 let mut stream = temporal_delimiter();
3732 stream.extend_from_slice(&sequence_header_obu(&seq)?);3912 stream.extend_from_slice(&sequence_header_obu(&seq)?);
3733 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);3913 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3778,19 +3958,25 @@ fn pick_and_apply_filters(
3778 chroma: &mut [Plane<'_>; 2],3958 chroma: &mut [Plane<'_>; 2],
3779 source: [&[u8]; 3],3959 source: [&[u8]; 3],
3780 search: bool,3960 search: bool,
3781- // The coded tile, replaced in place when the search chooses a per-64x643961+ // The coded tiles, one payload per tile of the frame's grid, replaced in
3782- // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile3962+ // place when the search chooses a per-64x64 `cdef_idx` list
3783- // payload, so the tile is written a second time under `recode` and the3963+ // (`cdef_bits > 0`): those literals live in the tile payloads, so every
3784- // winner re-decoded from it.3964+ // tile is written a second time under `recode` and the winner
3785- tile: &mut Vec<u8>,3965+ // re-decoded from them.
3966+ tiles: &mut Vec<Vec<u8>>,
3786 lambda: f64,3967 lambda: f64,
3787 fctx: &crate::decode::FrameCtx,3968 fctx: &crate::decode::FrameCtx,
3788- recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<u8>>,3969+ recode: impl Fn(
3970+ u8,
3971+ usize,
3972+ &[u8],
3973+ &[Option<crate::restoration::WienerInfo>],
3974+ ) -> Result<Vec<Vec<u8>>>,
3789 decode: impl Fn(3975 decode: impl Fn(
3790 &LoopFilterParams,3976 &LoopFilterParams,
3791 &CdefParams,3977 &CdefParams,
3792 &FrameHeader,3978 &FrameHeader,
3793- &[u8],3979+ &[Vec<u8>],
3794 &LoopRestorationParams,3980 &LoopRestorationParams,
3795 ) -> Result<Picture>,3981 ) -> Result<Picture>,
3796 ) -> Result<()> {3982 ) -> Result<()> {
@@ -3817,7 +4003,7 @@ fn pick_and_apply_filters(
3817 return Ok(picture);4003 return Ok(picture);
3818 }4004 }
3819 crate::decode::arm_filter_replay();4005 crate::decode::arm_filter_replay();
3820- decode(lf, cdef, &hdr, tile, &none_lr)4006+ decode(lf, cdef, &hdr, tiles, &none_lr)
3821 },4007 },
3822 source,4008 source,
3823 luma.width,4009 luma.width,
@@ -3848,14 +4034,14 @@ fn pick_and_apply_filters(
3848 fctx.capture_stages.set(lr_on);4034 fctx.capture_stages.set(lr_on);
3849 let mut filtered = if idx_grid.is_empty() {4035 let mut filtered = if idx_grid.is_empty() {
3850 if lr_on {4036 if lr_on {
3851- decode(&lf, &cdef, &hdr, tile, &none_lr)?4037+ decode(&lf, &cdef, &hdr, tiles, &none_lr)?
3852 } else {4038 } else {
3853 picture4039 picture
3854 }4040 }
3855 } else {4041 } else {
3856 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;4042 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
3857 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;4043 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
3858- *tile = coded;4044+ *tiles = coded;
3859 picture4045 picture
3860 };4046 };
3861 fctx.capture_stages.set(false);4047 fctx.capture_stages.set(false);
@@ -3886,7 +4072,7 @@ fn pick_and_apply_filters(
3886 if units.iter().any(Option::is_some) {4072 if units.iter().any(Option::is_some) {
3887 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;4073 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
3888 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;4074 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
3889- *tile = coded;4075+ *tiles = coded;
3890 lr = want;4076 lr = want;
3891 }4077 }
3892 }4078 }
@@ -5026,6 +5212,10 @@ pub(crate) fn encode_inter_frame(
5026 height: picture.height,5212 height: picture.height,
5027 true_width,5213 true_width,
5028 true_height,5214 true_height,
5215+ tile_x0: 0,
5216+ tile_y0: 0,
5217+ tile_x1: picture.width,
5218+ tile_y1: picture.height,
5029 };5219 };
5030 let mut chroma = [5220 let mut chroma = [
5031 Plane {5221 Plane {
@@ -5035,6 +5225,10 @@ pub(crate) fn encode_inter_frame(
5035 height: picture.height / 2,5225 height: picture.height / 2,
5036 true_width: true_width / 2,5226 true_width: true_width / 2,
5037 true_height: true_height / 2,5227 true_height: true_height / 2,
5228+ tile_x0: 0,
5229+ tile_y0: 0,
5230+ tile_x1: picture.width / 2,
5231+ tile_y1: picture.height / 2,
5038 },5232 },
5039 Plane {5233 Plane {
5040 source: &picture_v8,5234 source: &picture_v8,
@@ -5043,6 +5237,10 @@ pub(crate) fn encode_inter_frame(
5043 height: picture.height / 2,5237 height: picture.height / 2,
5044 true_width: true_width / 2,5238 true_width: true_width / 2,
5045 true_height: true_height / 2,5239 true_height: true_height / 2,
5240+ tile_x0: 0,
5241+ tile_y0: 0,
5242+ tile_x1: picture.width / 2,
5243+ tile_y1: picture.height / 2,
5046 },5244 },
5047 ];5245 ];
5048 5246
@@ -5066,6 +5264,12 @@ pub(crate) fn encode_inter_frame(
5066 let (cols, rows) = (cols as usize, rows as usize);5264 let (cols, rows) = (cols as usize, rows as usize);
5067 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));5265 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
5068 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);5266 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
5267+ // This frame's tile grid, as in `encode_key_frame_inner`.
5268+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
5269+ let layout =
5270+ crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
5271+ header.tile_info = tile_info_of(&layout, 1);
5272+ let header_tile_info = header.tile_info.clone();
5069 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is5273 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
5070 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --5274 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
5071 // once per frame (lane-av1rd2), not once per block, which is a whole5275 // once per frame (lane-av1rd2), not once per block, which is a whole
@@ -5076,6 +5280,18 @@ pub(crate) fn encode_inter_frame(
5076 5280
5077 for sb_r in 0..sb_rows {5281 for sb_r in 0..sb_rows {
5078 for sb_c in 0..sb_cols {5282 for sb_c in 0..sb_cols {
5283+ // Neighbour availability -- intra edges and the MV stack's
5284+ // scans alike -- stops at this superblock's own tile, exactly
5285+ // where the decoder stops it (`PlaneBuf::set_tile_origin`,
5286+ // `MiGrid::set_tile_bounds`).
5287+ let rect = layout.rect(layout.index_of_sb(sb_r as u32, sb_c as u32));
5288+ clip_planes_to_tile(&mut luma, &mut chroma, rect);
5289+ grid.set_tile_bounds(
5290+ rect.mi_row0 as usize,
5291+ rect.mi_col0 as usize,
5292+ rect.mi_row1 as usize,
5293+ rect.mi_col1 as usize,
5294+ );
5079 for quadrant in 0..4 {5295 for quadrant in 0..4 {
5080 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);5296 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
5081 // Same filter as the tile writer's: a quadrant whose own mi5297 // Same filter as the tile writer's: a quadrant whose own mi
@@ -5502,22 +5718,59 @@ pub(crate) fn encode_inter_frame(
5502 // next frame's writer starts from them -- exactly what5718 // next frame's writer starts from them -- exactly what
5503 // `crate::stream::stored_cdfs_for` hands the decoder.5719 // `crate::stream::stored_cdfs_for` hands the decoder.
5504 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);5720 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
5505- let mut cdfs = start_cdfs5721+ let cdfs = start_cdfs
5506 .cloned()5722 .cloned()
5507 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));5723 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
5508- let start_cdfs = CdfSnapshot(cdfs.clone());5724+ let start_cdfs = CdfSnapshot(cdfs);
5509- crate::tile::arm_sign_bias(sign_bias);5725+ let reference_select_bit = header.reference_select;
5510- crate::tile::arm_reference_select(header.reference_select);5726+ let order_hint_bits = seq.order_hint_bits;
5511- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);5727+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
5512- crate::tile::arm_screen(screen);5728+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
5513- let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(5729+ // What this frame stores is the LARGEST tile's end-of-tile tables --
5514- mi_cols,5730+ // its own header's `context_update_tile_id` (spec 7.20), which
5515- mi_rows,5731+ // `tile_info_of` set to exactly that tile.
5516- base_q_idx,5732+ let store_tile = layout.largest_tile();
5517- &blocks,5733+ let end_cdfs = std::cell::RefCell::new(None);
5518- tx_select,5734+ // As in `encode_key_frame_inner`: every tile starts from this frame's
5519- &mut cdfs,5735+ // own tables, so no tile depends on any other.
5520- )?;5736+ let code_tiles = |bits: u8,
5737+ sb_cols: usize,
5738+ cdef_grid: &[u8],
5739+ units: &[Option<crate::restoration::WienerInfo>]|
5740+ -> Result<Vec<Vec<u8>>> {
5741+ let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
5742+ crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
5743+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
5744+ crate::tile::arm_sign_bias(sign_bias);
5745+ // Thread-locals: every tile job arms its own worker.
5746+ crate::tile::arm_reference_select(reference_select_bit);
5747+ crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
5748+ crate::tile::arm_screen(screen);
5749+ let mut cdfs = start_cdfs.0.clone();
5750+ // Each tile's own MV grid: a candidate scan never reaches past
5751+ // the tile's bounds, so a grid holding only this tile's own
5752+ // blocks reads exactly as the decoder's frame-wide one does
5753+ // under `MiGrid::set_tile_bounds`.
5754+ let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
5755+ mv_grid.set_sign_bias(sign_bias);
5756+ let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5757+ mi_cols,
5758+ mi_rows,
5759+ base_q_idx,
5760+ &blocks,
5761+ tx_select,
5762+ &mut cdfs,
5763+ layout.rect(index),
5764+ &mut mv_grid,
5765+ )?;
5766+ Ok((bytes, Some(cdfs)))
5767+ })?;
5768+ if let Some(cdfs) = stored {
5769+ *end_cdfs.borrow_mut() = Some(cdfs);
5770+ }
5771+ Ok(out)
5772+ };
5773+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
5521 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs5774 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
5522 // this tile against the same single-slot reference this encoder predicted5775 // this tile against the same single-slot reference this encoder predicted
5523 // from, under each candidate level.5776 // from, under each candidate level.
@@ -5526,7 +5779,6 @@ pub(crate) fn encode_inter_frame(
5526 // reference whose height is not the header's own `frame_height` (spec5779 // reference whose height is not the header's own `frame_height` (spec
5527 // 7.9's compatible-size rule), and the chained-decode round trips prove5780 // 7.9's compatible-size rule), and the chained-decode round trips prove
5528 // the two predict identically.5781 // the two predict identically.
5529- let end_cdfs = std::cell::RefCell::new(cdfs);
5530 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);5782 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
5531 let trial_ref = if (reference.width, reference.height) == (fw, fh) {5783 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
5532 reference.clone()5784 reference.clone()
@@ -5573,12 +5825,6 @@ pub(crate) fn encode_inter_frame(
5573 refs[4] = trial_golden.as_ref();5825 refs[4] = trial_golden.as_ref();
5574 refs[7] = trial_altref.as_ref();5826 refs[7] = trial_altref.as_ref();
5575 let refpix = crate::decode::RefPix::ready(refs);5827 let refpix = crate::decode::RefPix::ready(refs);
5576- // The luma restoration-unit grid this frame's `lr_params` implies
5577- // (`av1_lr_count_units` rounds to nearest, so a short last unit is
5578- // swallowed by the one before it), for the tile writer's own per-unit
5579- // walk.
5580- let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
5581- let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
5582 pick_and_apply_filters(5828 pick_and_apply_filters(
5583 &mut header,5829 &mut header,
5584 &mut luma,5830 &mut luma,
@@ -5589,37 +5835,19 @@ pub(crate) fn encode_inter_frame(
5589 // `TxMode::Select` too (it used to skip and leave every inter frame5835 // `TxMode::Select` too (it used to skip and leave every inter frame
5590 // unfiltered once Select became the default).5836 // unfiltered once Select became the default).
5591 true,5837 true,
5592- &mut tile,5838+ &mut tiles,
5593 search.lambda,5839 search.lambda,
5594 fctx,5840 fctx,
5595 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables5841 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
5596 // are what the NEXT frame writes from, so the winning re-code5842 // are what the NEXT frame writes from, so the winning re-code
5597 // publishes its own into `end_cdfs` -- the first write's are stale5843 // publishes its own into `end_cdfs` -- the first write's are stale
5598 // the moment a second tile is coded.5844 // the moment a second tile is coded.
5599- |bits, sb_cols, grid, units| {5845+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
5600- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());5846+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
5601- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());5847+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
5602- crate::tile::arm_sign_bias(sign_bias);5848+ crate::decode::decode_inter_frame_tiles_lr(
5603- crate::tile::arm_reference_select(reference_select());5849+ &payloads,
5604- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);5850+ &header_tile_info,
5605- crate::tile::arm_screen(screen);
5606- let mut cdfs = start_cdfs.0.clone();
5607- let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5608- mi_cols,
5609- mi_rows,
5610- base_q_idx,
5611- &blocks,
5612- tx_select,
5613- &mut cdfs,
5614- );
5615- if coded.is_ok() {
5616- *end_cdfs.borrow_mut() = cdfs;
5617- }
5618- coded
5619- },
5620- |lf, cdef, h, tile, lr| {
5621- crate::decode::decode_inter_frame_tile_lr(
5622- tile,
5623 h.mi_cols,5851 h.mi_cols,
5624 h.mi_rows,5852 h.mi_rows,
5625 base_q_idx,5853 base_q_idx,
@@ -5645,9 +5873,14 @@ pub(crate) fn encode_inter_frame(
5645 )5873 )
5646 },5874 },
5647 )?;5875 )?;
5648- let mut cdfs = end_cdfs.into_inner();5876+ let mut cdfs = end_cdfs
5877+ .into_inner()
5878+ .unwrap_or_else(|| start_cdfs.0.clone());
5649 cdfs.reset_counts();5879 cdfs.reset_counts();
5650 let next_cdfs = CdfSnapshot(cdfs);5880 let next_cdfs = CdfSnapshot(cdfs);
5881+ let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
5882+ header.tile_info.tile_size_bytes = tile_size_bytes;
5883+ let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
5651 let mut stream = temporal_delimiter();5884 let mut stream = temporal_delimiter();
5652 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);5885 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
5653 5886
@@ -8660,6 +8893,8 @@ mod tests {
8660 base_q_idx: q,8893 base_q_idx: q,
8661 gop: source.len(),8894 gop: source.len(),
8662 colour: Colour::Unspecified,8895 colour: Colour::Unspecified,
8896+ tile_cols_log2: 0,
8897+ tile_rows_log2: 0,
8663 };8898 };
8664 let start = std::time::Instant::now();8899 let start = std::time::Instant::now();
8665 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();8900 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
crates/ec-av1/src/encoder.rsmodified+309 -1
@@ -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
@@ -1029,6 +1073,8 @@ mod tests {
1029 base_q_idx: 100,1073 base_q_idx: 100,
1030 gop: 2,1074 gop: 2,
1031 colour: Colour::Bt709Limited,1075 colour: Colour::Bt709Limited,
1076+ tile_cols_log2: 0,
1077+ tile_rows_log2: 0,
1032 };1078 };
1033 let mut enc = Av1Encoder::new(config).unwrap();1079 let mut enc = Av1Encoder::new(config).unwrap();
1034 for t in 0..5u64 {1080 for t in 0..5u64 {
@@ -1049,6 +1095,8 @@ mod tests {
1049 base_q_idx: 100,1095 base_q_idx: 100,
1050 gop: 3,1096 gop: 3,
1051 colour: Colour::Unspecified,1097 colour: Colour::Unspecified,
1098+ tile_cols_log2: 0,
1099+ tile_rows_log2: 0,
1052 };1100 };
1053 let mut enc = Av1Encoder::new(config).unwrap();1101 let mut enc = Av1Encoder::new(config).unwrap();
1054 let keys: Vec<bool> = (0..7)1102 let keys: Vec<bool> = (0..7)
@@ -1147,6 +1195,8 @@ mod tests {
1147 base_q_idx: 120,1195 base_q_idx: 120,
1148 gop: 15,1196 gop: 15,
1149 colour: Colour::Bt709Limited,1197 colour: Colour::Bt709Limited,
1198+ tile_cols_log2: 0,
1199+ tile_rows_log2: 0,
1150 };1200 };
1151 let mut enc = Av1Encoder::new(config).unwrap();1201 let mut enc = Av1Encoder::new(config).unwrap();
1152 assert_eq!(enc.display_size(), (width, height));1202 assert_eq!(enc.display_size(), (width, height));
@@ -1200,6 +1250,8 @@ mod tests {
1200 base_q_idx: 100,1250 base_q_idx: 100,
1201 gop: 4,1251 gop: 4,
1202 colour: Colour::Bt709Limited,1252 colour: Colour::Bt709Limited,
1253+ tile_cols_log2: 0,
1254+ tile_rows_log2: 0,
1203 };1255 };
1204 let mut enc = Av1Encoder::new(config).unwrap();1256 let mut enc = Av1Encoder::new(config).unwrap();
1205 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();1257 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
@@ -1222,6 +1274,8 @@ mod tests {
1222 base_q_idx: 100,1274 base_q_idx: 100,
1223 gop: 4,1275 gop: 4,
1224 colour: Colour::Bt601Limited,1276 colour: Colour::Bt601Limited,
1277+ tile_cols_log2: 0,
1278+ tile_rows_log2: 0,
1225 };1279 };
1226 let mut enc = Av1Encoder::new(config).unwrap();1280 let mut enc = Av1Encoder::new(config).unwrap();
1227 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();1281 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
@@ -1242,6 +1296,8 @@ mod tests {
1242 base_q_idx: 100,1296 base_q_idx: 100,
1243 gop: 4,1297 gop: 4,
1244 colour: Colour::Bt709Limited,1298 colour: Colour::Bt709Limited,
1299+ tile_cols_log2: 0,
1300+ tile_rows_log2: 0,
1245 };1301 };
1246 let mut enc = Av1Encoder::new(config).unwrap();1302 let mut enc = Av1Encoder::new(config).unwrap();
1247 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();1303 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
@@ -1257,6 +1313,8 @@ mod tests {
1257 base_q_idx: 100,1313 base_q_idx: 100,
1258 gop: 0,1314 gop: 0,
1259 colour: Colour::Bt709Limited,1315 colour: Colour::Bt709Limited,
1316+ tile_cols_log2: 0,
1317+ tile_rows_log2: 0,
1260 };1318 };
1261 let err = Av1Encoder::new(config).unwrap_err();1319 let err = Av1Encoder::new(config).unwrap_err();
1262 assert!(err.to_string().contains("gop"), "{err}");1320 assert!(err.to_string().contains("gop"), "{err}");
@@ -1328,6 +1386,8 @@ mod tests {
1328 base_q_idx: 100,1386 base_q_idx: 100,
1329 gop: 24,1387 gop: 24,
1330 colour: Colour::Bt709Limited,1388 colour: Colour::Bt709Limited,
1389+ tile_cols_log2: 0,
1390+ tile_rows_log2: 0,
1331 };1391 };
1332 let mut enc =1392 let mut enc =
1333 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();1393 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
@@ -1367,6 +1427,8 @@ mod tests {
1367 base_q_idx: 100,1427 base_q_idx: 100,
1368 gop: frames,1428 gop: frames,
1369 colour: Colour::Bt709Limited,1429 colour: Colour::Bt709Limited,
1430+ tile_cols_log2: 0,
1431+ tile_rows_log2: 0,
1370 };1432 };
1371 let rate = RateTarget::Bitrate {1433 let rate = RateTarget::Bitrate {
1372 bits_per_second,1434 bits_per_second,
@@ -1424,6 +1486,8 @@ mod tests {
1424 base_q_idx: 100,1486 base_q_idx: 100,
1425 gop: 24,1487 gop: 24,
1426 colour: Colour::Bt709Limited,1488 colour: Colour::Bt709Limited,
1489+ tile_cols_log2: 0,
1490+ tile_rows_log2: 0,
1427 };1491 };
1428 let mut enc =1492 let mut enc =
1429 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();1493 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
@@ -1499,13 +1563,15 @@ mod tests {
1499 /// display-order list and fails here.1563 /// display-order list and fails here.
1500 #[test]1564 #[test]
1501 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {1565 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
1502- let (width, height) = (128usize, 64usize);1566+ let (width, height) = (128usize, 128usize);
1503 let config = EncoderConfig {1567 let config = EncoderConfig {
1504 width,1568 width,
1505 height,1569 height,
1506 base_q_idx: 120,1570 base_q_idx: 120,
1507 gop: 32,1571 gop: 32,
1508 colour: Colour::Bt709Limited,1572 colour: Colour::Bt709Limited,
1573+ tile_cols_log2: 0,
1574+ tile_rows_log2: 0,
1509 };1575 };
1510 let pyramid = Pyramid {1576 let pyramid = Pyramid {
1511 mini_gop: 4,1577 mini_gop: 4,
@@ -1586,6 +1652,246 @@ mod tests {
1586 }1652 }
1587 }1653 }
1588 1654
1655+ /// Every tile layout this encoder can write decodes SAMPLE-EXACT
1656+ /// through both decoders -- ours and ffmpeg's -- and the frames really
1657+ /// carry the tiles the header claims (the OBU parser locates one payload
1658+ /// per tile, so a stream that quietly stayed single-tile fails here
1659+ /// rather than passing on a green round trip).
1660+ ///
1661+ /// The bytes are what the gate is on: an encoder that clipped its
1662+ /// neighbour availability wrong writes a stream whose two decoders agree
1663+ /// with each other and disagree with nothing -- so the ffmpeg half is
1664+ /// the one that catches a tile boundary the writer respected and the
1665+ /// spec does not, and the parser half catches the reverse.
1666+ #[test]
1667+ fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
1668+ let (width, height) = (640usize, 384usize);
1669+ let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1670+ let mut sizes = Vec::new();
1671+ for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] {
1672+ let config = EncoderConfig {
1673+ width,
1674+ height,
1675+ base_q_idx: 120,
1676+ gop: 4,
1677+ colour: Colour::Bt709Limited,
1678+ tile_cols_log2: cols_log2,
1679+ tile_rows_log2: rows_log2,
1680+ };
1681+ let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
1682+ let mut enc = Av1Encoder::new(config).unwrap();
1683+ let mut stream = Vec::new();
1684+ for (i, picture) in sources.iter().enumerate() {
1685+ let packet = enc
1686+ .encode(picture)
1687+ .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}"));
1688+ stream.extend_from_slice(&packet.data);
1689+ }
1690+ sizes.push((layout.clone(), stream.len()));
1691+
1692+ // The frames carry the tiles their headers claim.
1693+ let mut parser = ec_av1_syntax::Av1Parser::new();
1694+ let mut frames = 0usize;
1695+ let mut offset = 0usize;
1696+ while offset < stream.len() {
1697+ let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap();
1698+ let unit: usize = obus.iter().map(|o| o.total_size).sum();
1699+ for obu in &obus {
1700+ if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
1701+ assert_eq!(
1702+ (parsed.tile_info.cols, parsed.tile_info.rows),
1703+ (1 << cols_log2, 1 << rows_log2),
1704+ "{layout}: the header's own tile grid"
1705+ );
1706+ assert_eq!(
1707+ tiles.len(),
1708+ 1 << (cols_log2 + rows_log2),
1709+ "{layout}: tile payloads located in the tile group"
1710+ );
1711+ frames += 1;
1712+ }
1713+ }
1714+ offset += unit;
1715+ }
1716+ assert_eq!(frames, sources.len(), "{layout}: coded frames");
1717+
1718+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1719+ assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
1720+ if !have_ffmpeg() {
1721+ eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
1722+ continue;
1723+ }
1724+ let theirs = ffmpeg_decode_luma(&stream, width, height);
1725+ assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
1726+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1727+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1728+ assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size");
1729+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1730+ panic!(
1731+ "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
1732+ at % width,
1733+ at / width,
1734+ got[at],
1735+ b[at],
1736+ );
1737+ }
1738+ }
1739+ }
1740+ let base = sizes[0].1 as f64;
1741+ for (layout, bytes) in &sizes {
1742+ eprintln!(
1743+ "{layout}: {bytes} bytes ({:+.2}% vs one tile)",
1744+ (*bytes as f64 / base - 1.0) * 100.0
1745+ );
1746+ }
1747+ }
1748+
1749+ /// What tiles and tile threads are worth at the size the editor exports
1750+ /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall
1751+ /// per cell. Ignored by default (minutes).
1752+ #[test]
1753+ #[ignore = "1080p wall table: minutes, run it with --ignored"]
1754+ fn tile_wall_table_at_1080p() {
1755+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1756+ let (width, height) = (1920usize, 1080usize);
1757+ let Some(sources) = h264_clip_frames(width, height, 8) else {
1758+ eprintln!("SKIP tile_wall_table_at_1080p: no fixture");
1759+ return;
1760+ };
1761+ let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];
1762+ let threadings = [1usize, 2, 4, 8];
1763+ let mut table: Vec<(String, usize, f64, usize)> = Vec::new();
1764+ for pass in 0..2 {
1765+ for &(cols_log2, rows_log2) in &layouts {
1766+ for &threads in &threadings {
1767+ crate::par::set_tile_threads(threads);
1768+ let config = EncoderConfig {
1769+ width,
1770+ height,
1771+ base_q_idx: 120,
1772+ gop: 8,
1773+ colour: Colour::Bt709Limited,
1774+ tile_cols_log2: cols_log2,
1775+ tile_rows_log2: rows_log2,
1776+ };
1777+ let mut enc = Av1Encoder::new(config).unwrap();
1778+ let start = std::time::Instant::now();
1779+ let mut bytes = 0usize;
1780+ for picture in &sources {
1781+ bytes += enc.encode(picture).unwrap().data.len();
1782+ }
1783+ let wall = start.elapsed().as_secs_f64();
1784+ let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2);
1785+ match table.iter_mut().find(|r| r.0 == name && r.1 == threads) {
1786+ Some(row) => row.2 = row.2.min(wall),
1787+ None => table.push((name, threads, wall, bytes)),
1788+ }
1789+ let _ = pass;
1790+ }
1791+ }
1792+ }
1793+ crate::par::set_tile_threads(1);
1794+ eprintln!("| tiles | threads | wall (s, best of 2) | bytes |");
1795+ for (name, threads, wall, bytes) in &table {
1796+ eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |");
1797+ }
1798+ }
1799+
1800+ /// The tiles of a frame are entropy-independent, so the bytes must not
1801+ /// depend on how many workers wrote them: the same stream at one tile
1802+ /// thread and at four, per layout.
1803+ #[test]
1804+ fn tile_bytes_do_not_depend_on_the_thread_count() {
1805+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1806+ let (width, height) = (320usize, 192usize);
1807+ let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();
1808+ let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {
1809+ crate::par::set_tile_threads(threads);
1810+ let config = EncoderConfig {
1811+ width,
1812+ height,
1813+ base_q_idx: 120,
1814+ gop: 3,
1815+ colour: Colour::Bt709Limited,
1816+ tile_cols_log2: cols_log2,
1817+ tile_rows_log2: rows_log2,
1818+ };
1819+ let mut enc = Av1Encoder::new(config).unwrap();
1820+ let mut stream = Vec::new();
1821+ for picture in &sources {
1822+ stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1823+ }
1824+ stream
1825+ };
1826+ for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] {
1827+ let one = coded(1, cols_log2, rows_log2);
1828+ let four = coded(4, cols_log2, rows_log2);
1829+ assert_eq!(
1830+ one,
1831+ four,
1832+ "{}x{} tiles: {} bytes at one thread, {} at four",
1833+ 1 << cols_log2,
1834+ 1 << rows_log2,
1835+ one.len(),
1836+ four.len()
1837+ );
1838+ }
1839+ crate::par::set_tile_threads(1);
1840+ }
1841+
1842+ /// The same round trip at a real 1920x1080 crop of the gate's own clip
1843+ /// -- the size the editor's export actually runs at, where a tile grid
1844+ /// is worth having. Ignored by default only for its wall (a 1080p
1845+ /// encode of three pictures), not for any weakness in the check.
1846+ #[test]
1847+ #[ignore = "1080p encode: minutes, run it with --ignored"]
1848+ fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {
1849+ let (width, height) = (1920usize, 1080usize);
1850+ let Some(sources) = h264_clip_frames(width, height, 3) else {
1851+ eprintln!("SKIP the 1080p tile round trip: no fixture");
1852+ return;
1853+ };
1854+ for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] {
1855+ let config = EncoderConfig {
1856+ width,
1857+ height,
1858+ base_q_idx: 120,
1859+ gop: 3,
1860+ colour: Colour::Bt709Limited,
1861+ tile_cols_log2: cols_log2,
1862+ tile_rows_log2: rows_log2,
1863+ };
1864+ let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
1865+ let mut enc = Av1Encoder::new(config).unwrap();
1866+ let mut stream = Vec::new();
1867+ for (i, picture) in sources.iter().enumerate() {
1868+ let packet = enc
1869+ .encode(picture)
1870+ .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}"));
1871+ stream.extend_from_slice(&packet.data);
1872+ }
1873+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1874+ assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
1875+ if !have_ffmpeg() {
1876+ eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg");
1877+ continue;
1878+ }
1879+ let theirs = ffmpeg_decode_luma(&stream, width, height);
1880+ assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
1881+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1882+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1883+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1884+ panic!(
1885+ "1080p {layout} frame {i}: luma differs first at ({}, {})",
1886+ at % width,
1887+ at / width
1888+ );
1889+ }
1890+ }
1891+ eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len());
1892+ }
1893+ }
1894+
1589 /// [`RateTarget::Quality`] is monotone: a higher quality dial never1895 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
1590 /// produces a smaller stream or a worse mean PSNR than a lower one, on1896 /// produces a smaller stream or a worse mean PSNR than a lower one, on
1591 /// the same real clip.1897 /// the same real clip.
@@ -1609,6 +1915,8 @@ mod tests {
1609 base_q_idx: 100,1915 base_q_idx: 100,
1610 gop: 8,1916 gop: 8,
1611 colour: Colour::Bt709Limited,1917 colour: Colour::Bt709Limited,
1918+ tile_cols_log2: 0,
1919+ tile_rows_log2: 0,
1612 };1920 };
1613 let mut enc =1921 let mut enc =
1614 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();1922 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
crates/ec-av1/src/frame.rsmodified+41 -0
@@ -644,6 +644,47 @@ pub fn show_existing_frame_obu(seq: &SequenceHeader, frame_to_show_map_idx: u8)
644 ))644 ))
645 }645 }
646 646
647+/// How wide a tile group's per-tile size field has to be for these tiles
648+/// (`TileSizeBytes`, spec 5.11.1: every non-last tile carries `size - 1` in
649+/// that many bytes, so the widest of them decides).
650+pub(crate) fn tile_size_bytes_for(tiles: &[Vec<u8>]) -> u32 {
651+ let widest = tiles
652+ .iter()
653+ .rev()
654+ .skip(1)
655+ .map(|t| t.len().saturating_sub(1))
656+ .max()
657+ .unwrap_or(0);
658+ match widest {
659+ 0..=0xFF => 1,
660+ 0x100..=0xFFFF => 2,
661+ 0x1_0000..=0xFF_FFFF => 3,
662+ _ => 4,
663+ }
664+}
665+
666+/// `tile_group_obu()` (spec 5.11.1) for a group holding every tile of the
667+/// frame: `tile_start_and_end_present_flag = 0` (only coded when the frame
668+/// has more than one tile), byte alignment, then each tile's size (all but
669+/// the last, little endian, `tile_size_bytes` wide) ahead of its payload.
670+/// One tile leaves the payload exactly as it was, which is what every
671+/// single-tile stream this crate wrote before tiles existed carries.
672+pub(crate) fn tile_group_payload(tiles: &[Vec<u8>], tile_size_bytes: u32) -> Vec<u8> {
673+ if tiles.len() == 1 {
674+ return tiles[0].clone();
675+ }
676+ // The flag bit plus `byte_alignment()`: one zero byte.
677+ let mut out = vec![0u8];
678+ for (i, tile) in tiles.iter().enumerate() {
679+ if i + 1 < tiles.len() {
680+ let size = (tile.len() - 1) as u32;
681+ out.extend((0..tile_size_bytes).map(|b| (size >> (8 * b)) as u8));
682+ }
683+ out.extend_from_slice(tile);
684+ }
685+ out
686+}
687+
647 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group688 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group
648 /// payload the caller supplies.689 /// payload the caller supplies.
649 pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {690 pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {
crates/ec-av1/src/par.rsmodified+29 -0
@@ -55,6 +55,35 @@ pub(crate) fn set_filter_threads(n: usize) {
55 FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);55 FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
56 }56 }
57 57
58+/// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's
59+/// tiles across (default 1 = the shipped single-threaded write). Tiles are
60+/// entropy-independent by construction (each starts from the frame's own
61+/// tables and resets its own contexts), so the bytes a frame comes out as do
62+/// not depend on this -- `encoder::tests::tile_bytes_do_not_depend_on_the_
63+/// thread_count` is the pin.
64+static TILE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
65+
66+pub(crate) fn tile_threads() -> usize {
67+ match TILE_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
68+ 0 => {
69+ let n = crate::envflags::var("EC_AV1_TILE_THREADS")
70+ .ok()
71+ .and_then(|v| v.trim().parse::<usize>().ok())
72+ .unwrap_or(1)
73+ .clamp(1, 64);
74+ TILE_THREADS.store(n, std::sync::atomic::Ordering::Relaxed);
75+ n
76+ }
77+ n => n,
78+ }
79+}
80+
81+/// Test-only override of [`tile_threads`]; see [`set_filter_threads`].
82+#[cfg(test)]
83+pub(crate) fn set_tile_threads(n: usize) {
84+ TILE_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
85+}
86+
58 /// Splits `units` work units into at most `threads` contiguous, non-empty87 /// Splits `units` work units into at most `threads` contiguous, non-empty
59 /// bands. The caller picks the unit so that a band boundary is always a legal88 /// bands. The caller picks the unit so that a band boundary is always a legal
60 /// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one89 /// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one
crates/ec-av1/src/stream.rsmodified+2 -2
@@ -1900,7 +1900,7 @@ pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
1900 }1900 }
1901 1901
1902 #[cfg(test)]1902 #[cfg(test)]
1903-mod tests {1903+pub(crate) mod tests {
1904 use super::*;1904 use super::*;
1905 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};1905 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
1906 1906
@@ -3136,7 +3136,7 @@ mod tests {
3136 );3136 );
3137 }3137 }
3138 3138
3139- fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {3139+ pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
3140 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())3140 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
3141 }3141 }
3142 3142
crates/ec-av1/src/tile.rsmodified+227 -14
@@ -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.
@@ -1175,6 +1319,14 @@ impl Quadrant {
1175 /// What the blocks above and to the left of the one being coded left behind,1319 /// What the blocks above and to the left of the one being coded left behind,
1176 /// kept on the 16x16 grid the smallest block sits on.1320 /// kept on the 16x16 grid the smallest block sits on.
1177 struct Neighbours {1321 struct Neighbours {
1322+ /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/
1323+ /// `MiColStart`): every "is there a neighbour above/left of me" answer is
1324+ /// TILE-relative, not frame-relative -- the decoder's own
1325+ /// `Neighbours::start_tile` sets the same pair, and a writer that asked
1326+ /// `mi_row > 0` instead coded a tile's own first row against a neighbour
1327+ /// the decoder does not have (class: new map ignores tile edge).
1328+ tile_row0_mi: usize,
1329+ tile_col0_mi: usize,
1178 /// Per plane, whether the neighbour coded anything and the sign of its DC.1330 /// Per plane, whether the neighbour coded anything and the sign of its DC.
1179 above: Vec<[Neighbour; 3]>,1331 above: Vec<[Neighbour; 3]>,
1180 /// The same, down the left edge.1332 /// The same, down the left edge.
@@ -1305,6 +1457,8 @@ impl Neighbours {
1305 /// mode-info units.1457 /// mode-info units.
1306 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {1458 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
1307 Self {1459 Self {
1460+ tile_row0_mi: 0,
1461+ tile_col0_mi: 0,
1308 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],1462 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1309 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],1463 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1310 above_mode: vec![DC_PRED; cols],1464 above_mode: vec![DC_PRED; cols],
@@ -1340,6 +1494,23 @@ impl Neighbours {
1340 }1494 }
1341 1495
1342 /// Clears the left edge, which a tile starts every superblock row with.1496 /// Clears the left edge, which a tile starts every superblock row with.
1497+ /// Points this writer's availability answers at one tile
1498+ /// ([`Self::tile_row0_mi`]).
1499+ fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) {
1500+ self.tile_row0_mi = row0_mi;
1501+ self.tile_col0_mi = col0_mi;
1502+ }
1503+
1504+ /// Whether the block at mode-info row `mi_r` has a neighbour above it
1505+ /// INSIDE its own tile, and the same to the left.
1506+ fn has_above(&self, mi_r: usize) -> bool {
1507+ mi_r > self.tile_row0_mi
1508+ }
1509+
1510+ fn has_left(&self, mi_c: usize) -> bool {
1511+ mi_c > self.tile_col0_mi
1512+ }
1513+
1343 fn start_row(&mut self) {1514 fn start_row(&mut self) {
1344 self.left.iter_mut().for_each(|l| *l = Default::default());1515 self.left.iter_mut().for_each(|l| *l = Default::default());
1345 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);1516 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
@@ -1460,7 +1631,7 @@ impl Neighbours {
1460 /// off a CDF row one higher than the decoder's, which is the first1631 /// off a CDF row one higher than the decoder's, which is the first
1461 /// divergence of the inter `TxMode::Select` stream.1632 /// divergence of the inter `TxMode::Select` stream.
1462 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {1633 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
1463- let (has_above, has_left) = (mi_r > 0, mi_c > 0);1634+ let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c));
1464 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;1635 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
1465 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;1636 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
1466 if has_above && self.above_inter[mi_c] {1637 if has_above && self.above_inter[mi_c] {
@@ -1477,8 +1648,8 @@ impl Neighbours {
1477 /// largest transform, plus whether the one to the left is at least as1648 /// largest transform, plus whether the one to the left is at least as
1478 /// tall. A neighbour outside the tile contributes nothing.1649 /// tall. A neighbour outside the tile contributes nothing.
1479 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {1650 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
1480- usize::from(mi_r > 0 && usize::from(self.above_tx[mi_c]) >= max_tx)1651+ usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
1481- + usize::from(mi_c > 0 && usize::from(self.left_tx[mi_r]) >= max_tx)1652+ + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
1482 }1653 }
1483 1654
1484 /// Publishes one block's resolved transform side over every 4x4 unit it1655 /// Publishes one block's resolved transform side over every 4x4 unit it
@@ -1801,7 +1972,15 @@ pub fn sb_coeff_key_frame_tile_tx(
1801 tx_select: bool,1972 tx_select: bool,
1802 ) -> Result<Vec<u8>> {1973 ) -> Result<Vec<u8>> {
1803 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));1974 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1804- sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs)1975+ sb_coeff_key_frame_tile_cdfs(
1976+ mi_cols,
1977+ mi_rows,
1978+ base_q_idx,
1979+ superblocks,
1980+ tx_select,
1981+ &mut cdfs,
1982+ TileRect::whole(mi_cols, mi_rows),
1983+ )
1805 }1984 }
1806 1985
1807 /// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the1986 /// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
@@ -1819,6 +1998,11 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1819 superblocks: &[Superblock],1998 superblocks: &[Superblock],
1820 tx_select: bool,1999 tx_select: bool,
1821 cdfs: &mut Cdfs,2000 cdfs: &mut Cdfs,
2001+ // This tile's own span (spec 5.11.1): the writer walks only these
2002+ // superblocks, and its neighbour bands start blank, so everything
2003+ // outside reads as unavailable exactly as the decoder's own per-tile
2004+ // reset makes it.
2005+ tile: TileRect,
1822 ) -> Result<Vec<u8>> {2006 ) -> Result<Vec<u8>> {
1823 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.2007 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
1824 let _cdef_idx = CdefIdxGuard;2008 let _cdef_idx = CdefIdxGuard;
@@ -1876,15 +2060,16 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1876 mi_cols as usize,2060 mi_cols as usize,
1877 mi_rows as usize,2061 mi_rows as usize,
1878 );2062 );
2063+ neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
1879 2064
1880 // The tile adapts every non-literal CDF it writes, exactly as the decoder2065 // The tile adapts every non-literal CDF it writes, exactly as the decoder
1881 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`2066 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
1882 // off.2067 // off.
1883 let mut cdfs = cdfs;2068 let mut cdfs = cdfs;
1884 let mut enc = SymbolEncoder::new();2069 let mut enc = SymbolEncoder::new();
1885- for sb_r in 0..sb_rows {2070+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
1886 neighbours.start_row();2071 neighbours.start_row();
1887- for sb_c in 0..sb_cols {2072+ for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
1888 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);2073 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
1889 let at = (sb_r as usize * 4, sb_c as usize * 4);2074 let at = (sb_r as usize * 4, sb_c as usize * 4);
1890 let ctx = neighbours.partition_ctx(at, SB);2075 let ctx = neighbours.partition_ctx(at, SB);
@@ -3955,7 +4140,16 @@ pub fn sb_coeff_inter_frame_tile_tx(
3955 tx_select: bool,4140 tx_select: bool,
3956 ) -> Result<Vec<u8>> {4141 ) -> Result<Vec<u8>> {
3957 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));4142 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3958- sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs)4143+ sb_coeff_inter_frame_tile_cdfs(
4144+ mi_cols,
4145+ mi_rows,
4146+ base_q_idx,
4147+ blocks,
4148+ tx_select,
4149+ &mut cdfs,
4150+ TileRect::whole(mi_cols, mi_rows),
4151+ &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
4152+ )
3959 }4153 }
3960 4154
3961 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --4155 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
@@ -3970,6 +4164,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3970 blocks: &[Quadrant],4164 blocks: &[Quadrant],
3971 tx_select: bool,4165 tx_select: bool,
3972 cdfs: &mut Cdfs,4166 cdfs: &mut Cdfs,
4167+ // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
4168+ tile: TileRect,
4169+ // The frame's MV grid, carried across the frame's tiles by the caller
4170+ // (see the comment at `set_tile_bounds` below).
4171+ grid: &mut MiGrid,
3973 ) -> Result<Vec<u8>> {4172 ) -> Result<Vec<u8>> {
3974 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.4173 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3975 let _cdef_idx = CdefIdxGuard;4174 let _cdef_idx = CdefIdxGuard;
@@ -4010,7 +4209,21 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
4010 mi_cols as usize,4209 mi_cols as usize,
4011 mi_rows as usize,4210 mi_rows as usize,
4012 );4211 );
4013- let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);4212+ neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
4213+ // The MV grid spans the FRAME and carries every tile written before this
4214+ // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
4215+ // keeps one grid for the whole frame and narrows its read window per
4216+ // tile): the tile bounds below are what stops a candidate scan reaching
4217+ // across the boundary, and a grid that was merely empty out there would
4218+ // not read the same as the decoder's wherever a scan reads the array
4219+ // without asking `MiGrid::get` first.
4220+ let mut grid = &mut *grid;
4221+ grid.set_tile_bounds(
4222+ tile.mi_row0 as usize,
4223+ tile.mi_col0 as usize,
4224+ tile.mi_row1 as usize,
4225+ tile.mi_col1 as usize,
4226+ );
4014 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));4227 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
4015 let mut cdfs = cdfs;4228 let mut cdfs = cdfs;
4016 let mut enc = SymbolEncoder::new();4229 let mut enc = SymbolEncoder::new();
@@ -4038,9 +4251,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
4038 vec![0i32; TX16 * TX16],4251 vec![0i32; TX16 * TX16],
4039 ];4252 ];
4040 4253
4041- for sb_r in 0..sb_rows {4254+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
4042 neighbours.start_row();4255 neighbours.start_row();
4043- for sb_c in 0..sb_cols {4256+ for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
4044 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);4257 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
4045 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);4258 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
4046 let sb_ctx = neighbours.partition_ctx(sb_at, SB);4259 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
@@ -4283,9 +4496,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
4283 };4496 };
4284 4497
4285 let (r, c) = at;4498 let (r, c) = at;
4286- let has_above = r32 > 0;
4287- let has_left = c32 > 0;
4288 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));4499 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4500+ let has_above = neighbours.has_above(mi_r);
4501+ let has_left = neighbours.has_left(mi_c);
4289 let skip_ctx = usize::from(neighbours.above_skip[mi_c])4502 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
4290 + usize::from(neighbours.left_skip[mi_r]);4503 + usize::from(neighbours.left_skip[mi_r]);
4291 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4504 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
@@ -4532,7 +4745,7 @@ fn write_inter_frame_leaf(
4532 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4745 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
4533 write_cdef_idx(enc, (mi_r, mi_c), block.skip);4746 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
4534 4747
4535- let (has_above, has_left) = (r > 0, c > 0);4748+ let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c));
4536 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);4749 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
4537 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);4750 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
4538 let is_inter = block.inter.is_some();4751 let is_inter = block.inter.is_some();
@@ -4763,7 +4976,7 @@ fn write_inter_frame_leaf8(
4763 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4976 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
4764 write_cdef_idx(enc, leaf_mi, block.skip);4977 write_cdef_idx(enc, leaf_mi, block.skip);
4765 4978
4766- let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);4979+ let (has_above, has_left) = (neighbours.has_above(leaf_mi.0), neighbours.has_left(leaf_mi.1));
4767 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);4980 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
4768 let is_inter = block.inter.is_some();4981 let is_inter = block.inter.is_some();
4769 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);4982 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
tools/ec-bench/src/main.rsmodified+16 -0
@@ -345,12 +345,28 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
345 rows.push(missing("ec-av1", "decode"));345 rows.push(missing("ec-av1", "decode"));
346 return;346 return;
347 }347 }
348+ // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` benches the encoder's tile
349+ // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1`
350+ // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones
351+ // the byte pins carry. `EC_AV1_TILE_THREADS=<n>` (read by `ec_av1::par`)
352+ // spreads those tiles across `n` pool workers; the bytes are the same
353+ // either way, only the wall changes.
354+ let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES")
355+ .ok()
356+ .and_then(|spec| {
357+ let mut f = spec.split(':');
358+ let cols = f.next()?.parse().ok()?;
359+ Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0)))
360+ })
361+ .unwrap_or((0, 0));
348 let cfg = Av1Config {362 let cfg = Av1Config {
349 width: w as usize,363 width: w as usize,
350 height: h as usize,364 height: h as usize,
351 base_q_idx: 100,365 base_q_idx: 100,
352 gop: 10,366 gop: 10,
353 colour: Colour::default(),367 colour: Colour::default(),
368+ tile_cols_log2,
369+ tile_rows_log2,
354 };370 };
355 // `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` benches the371 // `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` benches the
356 // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead372 // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead