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(
2076320763 lr: &LoopRestorationParams,
2076420764 fctx: &crate::decode::FrameCtx,
2076520765 ) -> Result<Picture> {
20766- let delta = DeltaParams::default();
2076720766 let single_tile = TileInfo {
2076820767 mi_col_starts: vec![0, mi_cols],
2076920768 mi_row_starts: vec![0, mi_rows],
2077020769 ..TileInfo::default()
2077120770 };
20772- decode_key_frame_tile_with_cdfs(
20771+ decode_key_frame_tiles_lr(
2077320772 &[data],
2077420773 &single_tile,
2077520774 mi_cols,
2077620775 mi_rows,
2077720776 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,
2077820821 crate::quant::QuantDeltas::default(),
2077920822 frame_width,
2078020823 frame_height,
@@ -25394,6 +25437,7 @@ fn decode_inter_block(
2539425437 // combinations that don't implement scaled MC yet.
2539525438 frame_width: usize, fctx: &crate::decode::FrameCtx,
2539625439 ) -> Result<()> {
25440+
2539725441 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
2539825442 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
2539925443 // few 16-px-granular uses below.
@@ -32945,12 +32989,65 @@ pub(crate) fn decode_inter_frame_tile_lr(
3294532989 mi_row_starts: vec![0, mi_rows],
3294632990 ..TileInfo::default()
3294732991 };
32948- decode_inter_frame_tile_with_cdfs(
32992+ decode_inter_frame_tiles_lr(
3294932993 &[data],
3295032994 &single_tile,
3295132995 mi_cols,
3295232996 mi_rows,
3295332997 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,
3295433051 crate::quant::QuantDeltas::default(),
3295533052 frame_width,
3295633053 frame_height,
crates/ec-av1/src/encode.rsmodified+330 -95
@@ -1110,9 +1110,28 @@ struct Plane<'a> {
11101110 /// edge.
11111111 true_width: usize,
11121112 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,
11131123 }
11141124
11151125 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+ }
11161135 /// The reconstructed samples a block at `(x, y)` predicts from: the row
11171136 /// above it, the column to its left and the sample between them, each
11181137 /// missing where the block sits against an edge of the frame.
@@ -1164,14 +1183,17 @@ impl Plane<'_> {
11641183 // `a_picture_off_the_block_grid_is_refused`), never through a block
11651184 // this encoder actually commits. Such a block has no true-edge
11661185 // 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)
11681189 .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(|| {
11701191 (y..down)
11711192 .map(|row| self.reconstruction[row * self.width + x - 1])
11721193 .collect::<Vec<_>>()
11731194 });
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]);
11751197 (above, left, corner)
11761198 }
11771199
@@ -3241,6 +3263,126 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
32413263 .collect()
32423264 }
32433265
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+
32443386 /// Encodes one picture as a key frame.
32453387 ///
32463388 /// `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(
33933535 if tx_select {
33943536 header.tx_mode = TxMode::Select;
33953537 }
3538+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
33963539
33973540 // Prediction reads no further than this, in each plane's own units --
33983541 // see `Plane::true_width`/`true_height`.
@@ -3411,6 +3554,10 @@ pub(crate) fn encode_key_frame_inner(
34113554 height: picture.height,
34123555 true_width,
34133556 true_height,
3557+ tile_x0: 0,
3558+ tile_y0: 0,
3559+ tile_x1: picture.width,
3560+ tile_y1: picture.height,
34143561 };
34153562 let mut chroma = [
34163563 Plane {
@@ -3420,6 +3567,10 @@ pub(crate) fn encode_key_frame_inner(
34203567 height: picture.height / 2,
34213568 true_width: true_width / 2,
34223569 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,
34233574 },
34243575 Plane {
34253576 source: &picture_v8,
@@ -3428,6 +3579,10 @@ pub(crate) fn encode_key_frame_inner(
34283579 height: picture.height / 2,
34293580 true_width: true_width / 2,
34303581 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,
34313586 },
34323587 ];
34333588
@@ -3460,10 +3615,24 @@ pub(crate) fn encode_key_frame_inner(
34603615 let mut above_mode = vec![DC_PRED; cols * 2];
34613616 let mut left_mode = vec![DC_PRED; rows * 2];
34623617 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();
34633627 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
34643628 let mut modes = Vec::with_capacity(cols * rows);
34653629 for sb_row in 0..sb_rows {
34663630 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+ );
34673636 // The quadrants of a superblock are coded in the order the decoder
34683637 // walks them, which for a 64x64 split into 32x32 blocks is raster
34693638 // order among the quadrants that are inside the frame.
@@ -3659,58 +3828,66 @@ pub(crate) fn encode_key_frame_inner(
36593828 // defaults again (spec 7.20's `started_from` arm) -- the first inter
36603829 // frame after it therefore starts from the defaults too.
36613830 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));
3663- let start_cdfs = CdfSnapshot(cdfs.clone());
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.
3831+ let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3832+ let start_cdfs = CdfSnapshot(cdfs);
36783833 // The luma restoration-unit grid this frame's `lr_params` implies
36793834 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
36803835 // swallowed by the one before it), for the tile writer's own per-unit
36813836 // walk.
36823837 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
36833838 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.
36843872 pick_and_apply_filters(
36853873 &mut header,
36863874 &mut luma,
36873875 &mut chroma,
36883876 [&picture_y8, &picture_u8, &picture_v8],
36893877 true,
3690- &mut tile,
3878+ &mut tiles,
36913879 search.lambda,
36923880 fctx,
36933881 // Every re-code starts from this frame's OWN starting tables, never
36943882 // from where the first write left them: the second tile is the same
36953883 // symbol sequence plus new ones, so it must adapt from the same
36963884 // point the decoder will.
3697- |bits, sb_cols, grid, units| {
3698- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3699- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3700- let mut cdfs = start_cdfs.0.clone();
3701- crate::tile::arm_screen(screen);
3702- crate::tile::sb_coeff_key_frame_tile_cdfs(
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,
3885+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
3886+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
3887+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
3888+ crate::decode::decode_key_frame_tiles_lr(
3889+ &payloads,
3890+ &header_tile_info,
37143891 h.mi_cols,
37153892 h.mi_rows,
37163893 base_q_idx,
@@ -3728,6 +3905,9 @@ pub(crate) fn encode_key_frame_inner(
37283905 )
37293906 },
37303907 )?;
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);
37313911 let mut stream = temporal_delimiter();
37323912 stream.extend_from_slice(&sequence_header_obu(&seq)?);
37333913 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3778,19 +3958,25 @@ fn pick_and_apply_filters(
37783958 chroma: &mut [Plane<'_>; 2],
37793959 source: [&[u8]; 3],
37803960 search: bool,
3781- // The coded tile, replaced in place when the search chooses a per-64x64
3782- // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile
3783- // payload, so the tile is written a second time under `recode` and the
3784- // winner re-decoded from it.
3785- tile: &mut Vec<u8>,
3961+ // The coded tiles, one payload per tile of the frame's grid, replaced in
3962+ // place when the search chooses a per-64x64 `cdef_idx` list
3963+ // (`cdef_bits > 0`): those literals live in the tile payloads, so every
3964+ // tile is written a second time under `recode` and the winner
3965+ // re-decoded from them.
3966+ tiles: &mut Vec<Vec<u8>>,
37863967 lambda: f64,
37873968 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>>>,
37893975 decode: impl Fn(
37903976 &LoopFilterParams,
37913977 &CdefParams,
37923978 &FrameHeader,
3793- &[u8],
3979+ &[Vec<u8>],
37943980 &LoopRestorationParams,
37953981 ) -> Result<Picture>,
37963982 ) -> Result<()> {
@@ -3817,7 +4003,7 @@ fn pick_and_apply_filters(
38174003 return Ok(picture);
38184004 }
38194005 crate::decode::arm_filter_replay();
3820- decode(lf, cdef, &hdr, tile, &none_lr)
4006+ decode(lf, cdef, &hdr, tiles, &none_lr)
38214007 },
38224008 source,
38234009 luma.width,
@@ -3848,14 +4034,14 @@ fn pick_and_apply_filters(
38484034 fctx.capture_stages.set(lr_on);
38494035 let mut filtered = if idx_grid.is_empty() {
38504036 if lr_on {
3851- decode(&lf, &cdef, &hdr, tile, &none_lr)?
4037+ decode(&lf, &cdef, &hdr, tiles, &none_lr)?
38524038 } else {
38534039 picture
38544040 }
38554041 } else {
38564042 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
38574043 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
3858- *tile = coded;
4044+ *tiles = coded;
38594045 picture
38604046 };
38614047 fctx.capture_stages.set(false);
@@ -3886,7 +4072,7 @@ fn pick_and_apply_filters(
38864072 if units.iter().any(Option::is_some) {
38874073 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
38884074 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
3889- *tile = coded;
4075+ *tiles = coded;
38904076 lr = want;
38914077 }
38924078 }
@@ -5026,6 +5212,10 @@ pub(crate) fn encode_inter_frame(
50265212 height: picture.height,
50275213 true_width,
50285214 true_height,
5215+ tile_x0: 0,
5216+ tile_y0: 0,
5217+ tile_x1: picture.width,
5218+ tile_y1: picture.height,
50295219 };
50305220 let mut chroma = [
50315221 Plane {
@@ -5035,6 +5225,10 @@ pub(crate) fn encode_inter_frame(
50355225 height: picture.height / 2,
50365226 true_width: true_width / 2,
50375227 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,
50385232 },
50395233 Plane {
50405234 source: &picture_v8,
@@ -5043,6 +5237,10 @@ pub(crate) fn encode_inter_frame(
50435237 height: picture.height / 2,
50445238 true_width: true_width / 2,
50455239 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,
50465244 },
50475245 ];
50485246
@@ -5066,6 +5264,12 @@ pub(crate) fn encode_inter_frame(
50665264 let (cols, rows) = (cols as usize, rows as usize);
50675265 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
50685266 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();
50695273 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
50705274 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
50715275 // once per frame (lane-av1rd2), not once per block, which is a whole
@@ -5076,6 +5280,18 @@ pub(crate) fn encode_inter_frame(
50765280
50775281 for sb_r in 0..sb_rows {
50785282 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+ );
50795295 for quadrant in 0..4 {
50805296 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
50815297 // Same filter as the tile writer's: a quadrant whose own mi
@@ -5502,22 +5718,59 @@ pub(crate) fn encode_inter_frame(
55025718 // next frame's writer starts from them -- exactly what
55035719 // `crate::stream::stored_cdfs_for` hands the decoder.
55045720 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
5505- let mut cdfs = start_cdfs
5721+ let cdfs = start_cdfs
55065722 .cloned()
55075723 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
5508- let start_cdfs = CdfSnapshot(cdfs.clone());
5509- crate::tile::arm_sign_bias(sign_bias);
5510- crate::tile::arm_reference_select(header.reference_select);
5511- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
5512- crate::tile::arm_screen(screen);
5513- let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5514- mi_cols,
5515- mi_rows,
5516- base_q_idx,
5517- &blocks,
5518- tx_select,
5519- &mut cdfs,
5520- )?;
5724+ let start_cdfs = CdfSnapshot(cdfs);
5725+ let reference_select_bit = header.reference_select;
5726+ let order_hint_bits = seq.order_hint_bits;
5727+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
5728+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
5729+ // What this frame stores is the LARGEST tile's end-of-tile tables --
5730+ // its own header's `context_update_tile_id` (spec 7.20), which
5731+ // `tile_info_of` set to exactly that tile.
5732+ let store_tile = layout.largest_tile();
5733+ let end_cdfs = std::cell::RefCell::new(None);
5734+ // As in `encode_key_frame_inner`: every tile starts from this frame's
5735+ // own tables, so no tile depends on any other.
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, &[], &[])?;
55215774 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
55225775 // this tile against the same single-slot reference this encoder predicted
55235776 // from, under each candidate level.
@@ -5526,7 +5779,6 @@ pub(crate) fn encode_inter_frame(
55265779 // reference whose height is not the header's own `frame_height` (spec
55275780 // 7.9's compatible-size rule), and the chained-decode round trips prove
55285781 // the two predict identically.
5529- let end_cdfs = std::cell::RefCell::new(cdfs);
55305782 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
55315783 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
55325784 reference.clone()
@@ -5573,12 +5825,6 @@ pub(crate) fn encode_inter_frame(
55735825 refs[4] = trial_golden.as_ref();
55745826 refs[7] = trial_altref.as_ref();
55755827 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;
55825828 pick_and_apply_filters(
55835829 &mut header,
55845830 &mut luma,
@@ -5589,37 +5835,19 @@ pub(crate) fn encode_inter_frame(
55895835 // `TxMode::Select` too (it used to skip and leave every inter frame
55905836 // unfiltered once Select became the default).
55915837 true,
5592- &mut tile,
5838+ &mut tiles,
55935839 search.lambda,
55945840 fctx,
55955841 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
55965842 // are what the NEXT frame writes from, so the winning re-code
55975843 // publishes its own into `end_cdfs` -- the first write's are stale
55985844 // the moment a second tile is coded.
5599- |bits, sb_cols, grid, units| {
5600- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
5601- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
5602- crate::tile::arm_sign_bias(sign_bias);
5603- crate::tile::arm_reference_select(reference_select());
5604- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
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,
5845+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
5846+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
5847+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
5848+ crate::decode::decode_inter_frame_tiles_lr(
5849+ &payloads,
5850+ &header_tile_info,
56235851 h.mi_cols,
56245852 h.mi_rows,
56255853 base_q_idx,
@@ -5645,9 +5873,14 @@ pub(crate) fn encode_inter_frame(
56455873 )
56465874 },
56475875 )?;
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());
56495879 cdfs.reset_counts();
56505880 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);
56515884 let mut stream = temporal_delimiter();
56525885 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
56535886
@@ -8660,6 +8893,8 @@ mod tests {
86608893 base_q_idx: q,
86618894 gop: source.len(),
86628895 colour: Colour::Unspecified,
8896+ tile_cols_log2: 0,
8897+ tile_rows_log2: 0,
86638898 };
86648899 let start = std::time::Instant::now();
86658900 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
crates/ec-av1/src/encoder.rsmodified+309 -1
@@ -276,6 +276,32 @@ pub struct EncoderConfig {
276276 pub gop: usize,
277277 /// The colour the sequence header signals.
278278 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+ }
279305 }
280306
281307 /// One coded picture: its OBUs, in the order a demuxer that just wants bytes
@@ -510,6 +536,22 @@ impl Av1Encoder {
510536 // do, before the first `encode()` call rather than only surfacing it
511537 // then.
512538 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+ }
513555 Ok(Self {
514556 carried_cdfs: None,
515557 golden: None,
@@ -632,6 +674,7 @@ impl Av1Encoder {
632674 /// # Errors
633675 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
634676 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);
635678 if (picture.width, picture.height) != (self.config.width, self.config.height) {
636679 return Err(Error::unsupported(
637680 "AV1 encode",
@@ -671,6 +714,7 @@ impl Av1Encoder {
671714 /// # Errors
672715 /// As [`Av1Encoder::encode_frames`].
673716 pub fn flush(&mut self) -> Result<Vec<Packet>> {
717+ crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
674718 self.drain_pending()
675719 }
676720
@@ -1029,6 +1073,8 @@ mod tests {
10291073 base_q_idx: 100,
10301074 gop: 2,
10311075 colour: Colour::Bt709Limited,
1076+ tile_cols_log2: 0,
1077+ tile_rows_log2: 0,
10321078 };
10331079 let mut enc = Av1Encoder::new(config).unwrap();
10341080 for t in 0..5u64 {
@@ -1049,6 +1095,8 @@ mod tests {
10491095 base_q_idx: 100,
10501096 gop: 3,
10511097 colour: Colour::Unspecified,
1098+ tile_cols_log2: 0,
1099+ tile_rows_log2: 0,
10521100 };
10531101 let mut enc = Av1Encoder::new(config).unwrap();
10541102 let keys: Vec<bool> = (0..7)
@@ -1147,6 +1195,8 @@ mod tests {
11471195 base_q_idx: 120,
11481196 gop: 15,
11491197 colour: Colour::Bt709Limited,
1198+ tile_cols_log2: 0,
1199+ tile_rows_log2: 0,
11501200 };
11511201 let mut enc = Av1Encoder::new(config).unwrap();
11521202 assert_eq!(enc.display_size(), (width, height));
@@ -1200,6 +1250,8 @@ mod tests {
12001250 base_q_idx: 100,
12011251 gop: 4,
12021252 colour: Colour::Bt709Limited,
1253+ tile_cols_log2: 0,
1254+ tile_rows_log2: 0,
12031255 };
12041256 let mut enc = Av1Encoder::new(config).unwrap();
12051257 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
@@ -1222,6 +1274,8 @@ mod tests {
12221274 base_q_idx: 100,
12231275 gop: 4,
12241276 colour: Colour::Bt601Limited,
1277+ tile_cols_log2: 0,
1278+ tile_rows_log2: 0,
12251279 };
12261280 let mut enc = Av1Encoder::new(config).unwrap();
12271281 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
@@ -1242,6 +1296,8 @@ mod tests {
12421296 base_q_idx: 100,
12431297 gop: 4,
12441298 colour: Colour::Bt709Limited,
1299+ tile_cols_log2: 0,
1300+ tile_rows_log2: 0,
12451301 };
12461302 let mut enc = Av1Encoder::new(config).unwrap();
12471303 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
@@ -1257,6 +1313,8 @@ mod tests {
12571313 base_q_idx: 100,
12581314 gop: 0,
12591315 colour: Colour::Bt709Limited,
1316+ tile_cols_log2: 0,
1317+ tile_rows_log2: 0,
12601318 };
12611319 let err = Av1Encoder::new(config).unwrap_err();
12621320 assert!(err.to_string().contains("gop"), "{err}");
@@ -1328,6 +1386,8 @@ mod tests {
13281386 base_q_idx: 100,
13291387 gop: 24,
13301388 colour: Colour::Bt709Limited,
1389+ tile_cols_log2: 0,
1390+ tile_rows_log2: 0,
13311391 };
13321392 let mut enc =
13331393 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
@@ -1367,6 +1427,8 @@ mod tests {
13671427 base_q_idx: 100,
13681428 gop: frames,
13691429 colour: Colour::Bt709Limited,
1430+ tile_cols_log2: 0,
1431+ tile_rows_log2: 0,
13701432 };
13711433 let rate = RateTarget::Bitrate {
13721434 bits_per_second,
@@ -1424,6 +1486,8 @@ mod tests {
14241486 base_q_idx: 100,
14251487 gop: 24,
14261488 colour: Colour::Bt709Limited,
1489+ tile_cols_log2: 0,
1490+ tile_rows_log2: 0,
14271491 };
14281492 let mut enc =
14291493 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
@@ -1499,13 +1563,15 @@ mod tests {
14991563 /// display-order list and fails here.
15001564 #[test]
15011565 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
1502- let (width, height) = (128usize, 64usize);
1566+ let (width, height) = (128usize, 128usize);
15031567 let config = EncoderConfig {
15041568 width,
15051569 height,
15061570 base_q_idx: 120,
15071571 gop: 32,
15081572 colour: Colour::Bt709Limited,
1573+ tile_cols_log2: 0,
1574+ tile_rows_log2: 0,
15091575 };
15101576 let pyramid = Pyramid {
15111577 mini_gop: 4,
@@ -1586,6 +1652,246 @@ mod tests {
15861652 }
15871653 }
15881654
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+
15891895 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
15901896 /// produces a smaller stream or a worse mean PSNR than a lower one, on
15911897 /// the same real clip.
@@ -1609,6 +1915,8 @@ mod tests {
16091915 base_q_idx: 100,
16101916 gop: 8,
16111917 colour: Colour::Bt709Limited,
1918+ tile_cols_log2: 0,
1919+ tile_rows_log2: 0,
16121920 };
16131921 let mut enc =
16141922 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)
644644 ))
645645 }
646646
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+
647688 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group
648689 /// payload the caller supplies.
649690 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) {
5555 FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
5656 }
5757
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+
5887 /// Splits `units` work units into at most `threads` contiguous, non-empty
5988 /// bands. The caller picks the unit so that a band boundary is always a legal
6089 /// 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) {
19001900 }
19011901
19021902 #[cfg(test)]
1903-mod tests {
1903+pub(crate) mod tests {
19041904 use super::*;
19051905 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
19061906
@@ -3136,7 +3136,7 @@ mod tests {
31363136 );
31373137 }
31383138
3139- fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
3139+ pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
31403140 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
31413141 }
31423142
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)
116116 /// `crate::decode`), the span [`write_lr`] resolves its units over.
117117 const SB_MI_W: u32 = 16;
118118
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+
119263 /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
120264 struct CdefIdxPlan {
121265 /// The header's `cdef_bits`; never 0 while armed.
@@ -1175,6 +1319,14 @@ impl Quadrant {
11751319 /// What the blocks above and to the left of the one being coded left behind,
11761320 /// kept on the 16x16 grid the smallest block sits on.
11771321 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,
11781330 /// Per plane, whether the neighbour coded anything and the sign of its DC.
11791331 above: Vec<[Neighbour; 3]>,
11801332 /// The same, down the left edge.
@@ -1305,6 +1457,8 @@ impl Neighbours {
13051457 /// mode-info units.
13061458 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
13071459 Self {
1460+ tile_row0_mi: 0,
1461+ tile_col0_mi: 0,
13081462 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
13091463 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
13101464 above_mode: vec![DC_PRED; cols],
@@ -1340,6 +1494,23 @@ impl Neighbours {
13401494 }
13411495
13421496 /// 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+
13431514 fn start_row(&mut self) {
13441515 self.left.iter_mut().for_each(|l| *l = Default::default());
13451516 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
@@ -1460,7 +1631,7 @@ impl Neighbours {
14601631 /// off a CDF row one higher than the decoder's, which is the first
14611632 /// divergence of the inter `TxMode::Select` stream.
14621633 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));
14641635 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
14651636 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
14661637 if has_above && self.above_inter[mi_c] {
@@ -1477,8 +1648,8 @@ impl Neighbours {
14771648 /// largest transform, plus whether the one to the left is at least as
14781649 /// tall. A neighbour outside the tile contributes nothing.
14791650 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)
1481- + usize::from(mi_c > 0 && usize::from(self.left_tx[mi_r]) >= max_tx)
1651+ usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
1652+ + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
14821653 }
14831654
14841655 /// Publishes one block's resolved transform side over every 4x4 unit it
@@ -1801,7 +1972,15 @@ pub fn sb_coeff_key_frame_tile_tx(
18011972 tx_select: bool,
18021973 ) -> Result<Vec<u8>> {
18031974 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+ )
18051984 }
18061985
18071986 /// [`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(
18191998 superblocks: &[Superblock],
18201999 tx_select: bool,
18212000 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,
18222006 ) -> Result<Vec<u8>> {
18232007 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
18242008 let _cdef_idx = CdefIdxGuard;
@@ -1876,15 +2060,16 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
18762060 mi_cols as usize,
18772061 mi_rows as usize,
18782062 );
2063+ neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
18792064
18802065 // The tile adapts every non-literal CDF it writes, exactly as the decoder
18812066 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
18822067 // off.
18832068 let mut cdfs = cdfs;
18842069 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) {
18862071 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) {
18882073 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
18892074 let at = (sb_r as usize * 4, sb_c as usize * 4);
18902075 let ctx = neighbours.partition_ctx(at, SB);
@@ -3955,7 +4140,16 @@ pub fn sb_coeff_inter_frame_tile_tx(
39554140 tx_select: bool,
39564141 ) -> Result<Vec<u8>> {
39574142 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+ )
39594153 }
39604154
39614155 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
@@ -3970,6 +4164,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
39704164 blocks: &[Quadrant],
39714165 tx_select: bool,
39724166 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,
39734172 ) -> Result<Vec<u8>> {
39744173 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
39754174 let _cdef_idx = CdefIdxGuard;
@@ -4010,7 +4209,21 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
40104209 mi_cols as usize,
40114210 mi_rows as usize,
40124211 );
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+ );
40144227 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
40154228 let mut cdfs = cdfs;
40164229 let mut enc = SymbolEncoder::new();
@@ -4038,9 +4251,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
40384251 vec![0i32; TX16 * TX16],
40394252 ];
40404253
4041- for sb_r in 0..sb_rows {
4254+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
40424255 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) {
40444257 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
40454258 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
40464259 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
@@ -4283,9 +4496,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
42834496 };
42844497
42854498 let (r, c) = at;
4286- let has_above = r32 > 0;
4287- let has_left = c32 > 0;
42884499 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);
42894502 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
42904503 + usize::from(neighbours.left_skip[mi_r]);
42914504 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
@@ -4532,7 +4745,7 @@ fn write_inter_frame_leaf(
45324745 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
45334746 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
45344747
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));
45364749 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
45374750 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
45384751 let is_inter = block.inter.is_some();
@@ -4763,7 +4976,7 @@ fn write_inter_frame_leaf8(
47634976 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
47644977 write_cdef_idx(enc, leaf_mi, block.skip);
47654978
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));
47674980 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
47684981 let is_inter = block.inter.is_some();
47694982 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>) {
345345 rows.push(missing("ec-av1", "decode"));
346346 return;
347347 }
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));
348362 let cfg = Av1Config {
349363 width: w as usize,
350364 height: h as usize,
351365 base_q_idx: 100,
352366 gop: 10,
353367 colour: Colour::default(),
368+ tile_cols_log2,
369+ tile_rows_log2,
354370 };
355371 // `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` benches the
356372 // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead