forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into lane-av1comp2

Browse files at this commit

c76c7ff7e6d7698912d97b69ffc2493583ac5ebaAhmet Kaan GümüşParent: d53c852b58ff3f
crates/ec-av1/src/decode.rsmodified+96 -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.
@@ -32939,12 +32983,61 @@ pub(crate) fn decode_inter_frame_tile_lr(
3293932983 mi_row_starts: vec![0, mi_rows],
3294032984 ..TileInfo::default()
3294132985 };
32942- decode_inter_frame_tile_with_cdfs(
32986+ decode_inter_frame_tiles_lr(
3294332987 &[data],
3294432988 &single_tile,
3294532989 mi_cols,
3294632990 mi_rows,
3294732991 base_q_idx,
32992+ frame_width,
32993+ frame_height,
32994+ refpix,
32995+ cdef,
32996+ loop_filter,
32997+ allow_high_precision_mv,
32998+ force_integer_mv,
32999+ interp_fixed,
33000+ enable_dual_filter,
33001+ reference_select,
33002+ tx_select,
33003+ lr,
33004+ initial_cdfs,
33005+ sign_bias,
33006+ fctx,
33007+ )
33008+}
33009+
33010+/// [`decode_inter_frame_tile_lr`] for a frame coded as SEVERAL tiles; see
33011+/// [`decode_key_frame_tiles_lr`].
33012+#[allow(clippy::too_many_arguments)]
33013+pub(crate) fn decode_inter_frame_tiles_lr(
33014+ tiles: &[&[u8]],
33015+ tile_info: &TileInfo,
33016+ mi_cols: u32,
33017+ mi_rows: u32,
33018+ base_q_idx: u8,
33019+ frame_width: u32,
33020+ frame_height: u32,
33021+ refpix: &RefPix<'_>,
33022+ cdef: &CdefParams,
33023+ loop_filter: &LoopFilterParams,
33024+ allow_high_precision_mv: bool,
33025+ force_integer_mv: bool,
33026+ interp_fixed: Option<mc::InterpFilterKind>,
33027+ enable_dual_filter: bool,
33028+ reference_select: bool,
33029+ tx_select: bool,
33030+ lr: &LoopRestorationParams,
33031+ initial_cdfs: Option<Cdfs>,
33032+ sign_bias: crate::mvstack::SignBiasTable,
33033+ fctx: &crate::decode::FrameCtx,
33034+) -> Result<Picture> {
33035+ decode_inter_frame_tile_with_cdfs(
33036+ tiles,
33037+ tile_info,
33038+ mi_cols,
33039+ mi_rows,
33040+ base_q_idx,
3294833041 crate::quant::QuantDeltas::default(),
3294933042 frame_width,
3295033043 frame_height,
crates/ec-av1/src/encode.rsmodified+328 -91
@@ -979,9 +979,28 @@ struct Plane<'a> {
979979 /// edge.
980980 true_width: usize,
981981 true_height: usize,
982+ /// This plane's own tile's pixel bounds, in this plane's units -- the
983+ /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
984+ /// prediction never reaches across a tile edge even though the
985+ /// neighbouring tile's real samples sit right there in the shared
986+ /// reconstruction. `(0, 0, width, height)` is the single-tile case and
987+ /// leaves every edge exactly as it was before tiles existed.
988+ tile_x0: usize,
989+ tile_y0: usize,
990+ tile_x1: usize,
991+ tile_y1: usize,
982992 }
983993
984994 impl Plane<'_> {
995+ /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
996+ /// called at every superblock of the frame-raster search with the rect
997+ /// of the tile that superblock belongs to.
998+ fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
999+ self.tile_x0 = x0;
1000+ self.tile_y0 = y0;
1001+ self.tile_x1 = x1.min(self.width);
1002+ self.tile_y1 = y1.min(self.height);
1003+ }
9851004 /// The reconstructed samples a block at `(x, y)` predicts from: the row
9861005 /// above it, the column to its left and the sample between them, each
9871006 /// missing where the block sits against an edge of the frame.
@@ -1033,14 +1052,17 @@ impl Plane<'_> {
10331052 // `a_picture_off_the_block_grid_is_refused`), never through a block
10341053 // this encoder actually commits. Such a block has no true-edge
10351054 // samples above or left of it at all, same as `y == 0`/`x == 0`.
1036- let above = (y > 0 && across > x)
1055+ let across = across.min(self.tile_x1);
1056+ let down = down.min(self.tile_y1);
1057+ let above = (y > self.tile_y0 && across > x)
10371058 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());
1038- let left = (x > 0 && down > y).then(|| {
1059+ let left = (x > self.tile_x0 && down > y).then(|| {
10391060 (y..down)
10401061 .map(|row| self.reconstruction[row * self.width + x - 1])
10411062 .collect::<Vec<_>>()
10421063 });
1043- let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
1064+ let corner = (x > self.tile_x0 && y > self.tile_y0)
1065+ .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
10441066 (above, left, corner)
10451067 }
10461068
@@ -2971,6 +2993,126 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
29712993 .collect()
29722994 }
29732995
2996+thread_local! {
2997+ /// The tile grid the next frame is coded with, as `(TileColsLog2,
2998+ /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
2999+ /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
3000+ /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
3001+ /// one tile per frame, what every caller that never arms anything gets
3002+ /// and what every stream this crate wrote before tiles existed carries.
3003+ static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
3004+}
3005+
3006+/// Arms this thread's next frame encodes with a tile grid (log2 counts).
3007+pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
3008+ TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
3009+}
3010+
3011+fn armed_tiles() -> (u32, u32) {
3012+ let armed = TILE_LOG2.with(std::cell::Cell::get);
3013+ if armed != (0, 0) {
3014+ return armed;
3015+ }
3016+ // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
3017+ // (which codes through `encode_sequence`, not the facade) can measure what
3018+ // a tile grid costs without a knob of its own -- same shape as
3019+ // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
3020+ match std::env::var("EC_AV1_TILES").ok() {
3021+ Some(v) if cfg!(test) => {
3022+ let mut f = v.split(':');
3023+ let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
3024+ let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
3025+ (cols, rows)
3026+ }
3027+ _ => armed,
3028+ }
3029+}
3030+
3031+/// Codes a frame's `tiles` tiles, each entirely on its own (see
3032+/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
3033+/// the crate's own pool, and hands back their payloads in tile order plus
3034+/// whatever `code` returned for tile `store` -- the CDF state
3035+/// `context_update_tile_id` names. The result cannot depend on the thread
3036+/// count: each job writes one tile from the frame's own starting tables into
3037+/// its own slot.
3038+fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
3039+where
3040+ F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
3041+{
3042+ type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
3043+ let threads = crate::par::tile_threads().min(tiles);
3044+ let mut slots: Vec<Slot> = Vec::new();
3045+ if threads <= 1 {
3046+ for index in 0..tiles {
3047+ slots.push(Some(code(index)));
3048+ }
3049+ } else {
3050+ let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
3051+ {
3052+ let batch = crate::par::Batch::new("ec-av1-tile");
3053+ for (from, to) in crate::par::bands(tiles, threads) {
3054+ let done = &done;
3055+ let code = &code;
3056+ batch.submit(move || {
3057+ for index in from..to {
3058+ let coded = code(index);
3059+ done.lock().expect("tile slots")[index] = Some(coded);
3060+ }
3061+ });
3062+ }
3063+ }
3064+ slots = done.into_inner().expect("tile slots");
3065+ }
3066+ let mut out = Vec::with_capacity(tiles);
3067+ let mut stored = None;
3068+ for (index, slot) in slots.into_iter().enumerate() {
3069+ let (bytes, cdfs) = slot.expect("every tile was coded")?;
3070+ if index == store {
3071+ stored = cdfs;
3072+ }
3073+ out.push(bytes);
3074+ }
3075+ Ok((out, stored))
3076+}
3077+
3078+/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
3079+/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
3080+/// tables the frame stores (spec 7.20), which is what
3081+/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
3082+/// below publish.
3083+fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
3084+ ec_av1_syntax::TileInfo {
3085+ uniform_spacing: true,
3086+ cols: layout.cols(),
3087+ rows: layout.rows(),
3088+ cols_log2: layout.cols_log2,
3089+ rows_log2: layout.rows_log2,
3090+ mi_col_starts: layout.mi_col_starts(),
3091+ mi_row_starts: layout.mi_row_starts(),
3092+ context_update_tile_id: layout.largest_tile() as u32,
3093+ tile_size_bytes,
3094+ }
3095+}
3096+
3097+/// Clips the three planes' intra edge reads to `rect`, the tile the
3098+/// superblock about to be searched belongs to (the encoder side of the
3099+/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
3100+/// raster order -- which is a linear extension of every tile's own coding
3101+/// order, so a block still only ever predicts from samples already
3102+/// reconstructed -- and only availability is tile-relative.
3103+fn clip_planes_to_tile(
3104+ luma: &mut Plane<'_>,
3105+ chroma: &mut [Plane<'_>; 2],
3106+ rect: crate::tile::TileRect,
3107+) {
3108+ let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
3109+ let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
3110+ luma.set_tile(x0, y0, x1, y1);
3111+ for plane in chroma.iter_mut() {
3112+ plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
3113+ }
3114+}
3115+
29743116 /// Encodes one picture as a key frame.
29753117 ///
29763118 /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
@@ -3111,6 +3253,7 @@ pub(crate) fn encode_key_frame_inner(
31113253 if tx_select {
31123254 header.tx_mode = TxMode::Select;
31133255 }
3256+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
31143257
31153258 // Prediction reads no further than this, in each plane's own units --
31163259 // see `Plane::true_width`/`true_height`.
@@ -3129,6 +3272,10 @@ pub(crate) fn encode_key_frame_inner(
31293272 height: picture.height,
31303273 true_width,
31313274 true_height,
3275+ tile_x0: 0,
3276+ tile_y0: 0,
3277+ tile_x1: picture.width,
3278+ tile_y1: picture.height,
31323279 };
31333280 let mut chroma = [
31343281 Plane {
@@ -3138,6 +3285,10 @@ pub(crate) fn encode_key_frame_inner(
31383285 height: picture.height / 2,
31393286 true_width: true_width / 2,
31403287 true_height: true_height / 2,
3288+ tile_x0: 0,
3289+ tile_y0: 0,
3290+ tile_x1: picture.width / 2,
3291+ tile_y1: picture.height / 2,
31413292 },
31423293 Plane {
31433294 source: &picture_v8,
@@ -3146,6 +3297,10 @@ pub(crate) fn encode_key_frame_inner(
31463297 height: picture.height / 2,
31473298 true_width: true_width / 2,
31483299 true_height: true_height / 2,
3300+ tile_x0: 0,
3301+ tile_y0: 0,
3302+ tile_x1: picture.width / 2,
3303+ tile_y1: picture.height / 2,
31493304 },
31503305 ];
31513306
@@ -3177,10 +3332,24 @@ pub(crate) fn encode_key_frame_inner(
31773332 let mut above_mode = vec![DC_PRED; cols * 2];
31783333 let mut left_mode = vec![DC_PRED; rows * 2];
31793334 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3335+ // This frame's tile grid (one tile unless the facade armed more).
3336+ let layout =
3337+ crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
3338+ header.tile_info = tile_info_of(&layout, 1);
3339+ // The filter search re-decodes this frame's tiles; the decoder derives
3340+ // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
3341+ // `mi_row_starts`), which is what makes the writer's rects and the
3342+ // reader's the same rects.
3343+ let header_tile_info = header.tile_info.clone();
31803344 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
31813345 let mut modes = Vec::with_capacity(cols * rows);
31823346 for sb_row in 0..sb_rows {
31833347 for sb_col in 0..sb_cols {
3348+ clip_planes_to_tile(
3349+ &mut luma,
3350+ &mut chroma,
3351+ layout.rect(layout.index_of_sb(sb_row as u32, sb_col as u32)),
3352+ );
31843353 // The quadrants of a superblock are coded in the order the decoder
31853354 // walks them, which for a 64x64 split into 32x32 blocks is raster
31863355 // order among the quadrants that are inside the frame.
@@ -3376,56 +3545,65 @@ pub(crate) fn encode_key_frame_inner(
33763545 // defaults again (spec 7.20's `started_from` arm) -- the first inter
33773546 // frame after it therefore starts from the defaults too.
33783547 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3379- let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3380- let start_cdfs = CdfSnapshot(cdfs.clone());
3381- let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
3382- mi_cols,
3383- mi_rows,
3384- base_q_idx,
3385- &superblocks,
3386- tx_select,
3387- &mut cdfs,
3388- )?;
3389- // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
3390- // the tile just coded back to the decoder under each candidate (see
3391- // `crate::filter_search`), and keep the filtered picture that wins as
3392- // the reconstruction -- what a decoder outputs, and what the next
3393- // frame predicts from.
3548+ let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3549+ let start_cdfs = CdfSnapshot(cdfs);
33943550 // The luma restoration-unit grid this frame's `lr_params` implies
33953551 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
33963552 // swallowed by the one before it), for the tile writer's own per-unit
33973553 // walk.
33983554 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
33993555 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3556+ // Every tile is coded from this frame's OWN starting tables and leaves
3557+ // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
3558+ // loop-restoration reference and its neighbour contexts), so the tiles
3559+ // are independent of each other and of the order they are written in.
3560+ let code_tiles = |bits: u8,
3561+ sb_cols: usize,
3562+ grid: &[u8],
3563+ units: &[Option<crate::restoration::WienerInfo>]|
3564+ -> Result<Vec<Vec<u8>>> {
3565+ let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
3566+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3567+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3568+ let mut cdfs = start_cdfs.0.clone();
3569+ let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
3570+ mi_cols,
3571+ mi_rows,
3572+ base_q_idx,
3573+ &superblocks,
3574+ tx_select,
3575+ &mut cdfs,
3576+ layout.rect(index),
3577+ )?;
3578+ Ok((bytes, None))
3579+ })?;
3580+ Ok(out)
3581+ };
3582+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
3583+ // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
3584+ // the tile just coded back to the decoder under each candidate (see
3585+ // `crate::filter_search`), and keep the filtered picture that wins as
3586+ // the reconstruction -- what a decoder outputs, and what the next
3587+ // frame predicts from.
34003588 pick_and_apply_filters(
34013589 &mut header,
34023590 &mut luma,
34033591 &mut chroma,
34043592 [&picture_y8, &picture_u8, &picture_v8],
34053593 true,
3406- &mut tile,
3594+ &mut tiles,
34073595 search.lambda,
34083596 fctx,
34093597 // Every re-code starts from this frame's OWN starting tables, never
34103598 // from where the first write left them: the second tile is the same
34113599 // symbol sequence plus new ones, so it must adapt from the same
34123600 // point the decoder will.
3413- |bits, sb_cols, grid, units| {
3414- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3415- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3416- let mut cdfs = start_cdfs.0.clone();
3417- crate::tile::sb_coeff_key_frame_tile_cdfs(
3418- mi_cols,
3419- mi_rows,
3420- base_q_idx,
3421- &superblocks,
3422- tx_select,
3423- &mut cdfs,
3424- )
3425- },
3426- |lf, cdef, h, tile, lr| {
3427- crate::decode::decode_key_frame_tile_lr(
3428- tile,
3601+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
3602+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
3603+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
3604+ crate::decode::decode_key_frame_tiles_lr(
3605+ &payloads,
3606+ &header_tile_info,
34293607 h.mi_cols,
34303608 h.mi_rows,
34313609 base_q_idx,
@@ -3443,6 +3621,9 @@ pub(crate) fn encode_key_frame_inner(
34433621 )
34443622 },
34453623 )?;
3624+ let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
3625+ header.tile_info.tile_size_bytes = tile_size_bytes;
3626+ let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
34463627 let mut stream = temporal_delimiter();
34473628 stream.extend_from_slice(&sequence_header_obu(&seq)?);
34483629 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3492,19 +3673,25 @@ fn pick_and_apply_filters(
34923673 chroma: &mut [Plane<'_>; 2],
34933674 source: [&[u8]; 3],
34943675 search: bool,
3495- // The coded tile, replaced in place when the search chooses a per-64x64
3496- // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile
3497- // payload, so the tile is written a second time under `recode` and the
3498- // winner re-decoded from it.
3499- tile: &mut Vec<u8>,
3676+ // The coded tiles, one payload per tile of the frame's grid, replaced in
3677+ // place when the search chooses a per-64x64 `cdef_idx` list
3678+ // (`cdef_bits > 0`): those literals live in the tile payloads, so every
3679+ // tile is written a second time under `recode` and the winner
3680+ // re-decoded from them.
3681+ tiles: &mut Vec<Vec<u8>>,
35003682 lambda: f64,
35013683 fctx: &crate::decode::FrameCtx,
3502- recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<u8>>,
3684+ recode: impl Fn(
3685+ u8,
3686+ usize,
3687+ &[u8],
3688+ &[Option<crate::restoration::WienerInfo>],
3689+ ) -> Result<Vec<Vec<u8>>>,
35033690 decode: impl Fn(
35043691 &LoopFilterParams,
35053692 &CdefParams,
35063693 &FrameHeader,
3507- &[u8],
3694+ &[Vec<u8>],
35083695 &LoopRestorationParams,
35093696 ) -> Result<Picture>,
35103697 ) -> Result<()> {
@@ -3531,7 +3718,7 @@ fn pick_and_apply_filters(
35313718 return Ok(picture);
35323719 }
35333720 crate::decode::arm_filter_replay();
3534- decode(lf, cdef, &hdr, tile, &none_lr)
3721+ decode(lf, cdef, &hdr, tiles, &none_lr)
35353722 },
35363723 source,
35373724 luma.width,
@@ -3562,14 +3749,14 @@ fn pick_and_apply_filters(
35623749 fctx.capture_stages.set(lr_on);
35633750 let mut filtered = if idx_grid.is_empty() {
35643751 if lr_on {
3565- decode(&lf, &cdef, &hdr, tile, &none_lr)?
3752+ decode(&lf, &cdef, &hdr, tiles, &none_lr)?
35663753 } else {
35673754 picture
35683755 }
35693756 } else {
35703757 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
35713758 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
3572- *tile = coded;
3759+ *tiles = coded;
35733760 picture
35743761 };
35753762 fctx.capture_stages.set(false);
@@ -3600,7 +3787,7 @@ fn pick_and_apply_filters(
36003787 if units.iter().any(Option::is_some) {
36013788 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
36023789 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
3603- *tile = coded;
3790+ *tiles = coded;
36043791 lr = want;
36053792 }
36063793 }
@@ -4814,6 +5001,10 @@ pub(crate) fn encode_inter_frame(
48145001 height: picture.height,
48155002 true_width,
48165003 true_height,
5004+ tile_x0: 0,
5005+ tile_y0: 0,
5006+ tile_x1: picture.width,
5007+ tile_y1: picture.height,
48175008 };
48185009 let mut chroma = [
48195010 Plane {
@@ -4823,6 +5014,10 @@ pub(crate) fn encode_inter_frame(
48235014 height: picture.height / 2,
48245015 true_width: true_width / 2,
48255016 true_height: true_height / 2,
5017+ tile_x0: 0,
5018+ tile_y0: 0,
5019+ tile_x1: picture.width / 2,
5020+ tile_y1: picture.height / 2,
48265021 },
48275022 Plane {
48285023 source: &picture_v8,
@@ -4831,6 +5026,10 @@ pub(crate) fn encode_inter_frame(
48315026 height: picture.height / 2,
48325027 true_width: true_width / 2,
48335028 true_height: true_height / 2,
5029+ tile_x0: 0,
5030+ tile_y0: 0,
5031+ tile_x1: picture.width / 2,
5032+ tile_y1: picture.height / 2,
48345033 },
48355034 ];
48365035
@@ -4853,6 +5052,12 @@ pub(crate) fn encode_inter_frame(
48535052 let (cols, rows) = (cols as usize, rows as usize);
48545053 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
48555054 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
5055+ // This frame's tile grid, as in `encode_key_frame_inner`.
5056+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
5057+ let layout =
5058+ crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
5059+ header.tile_info = tile_info_of(&layout, 1);
5060+ let header_tile_info = header.tile_info.clone();
48565061 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
48575062 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
48585063 // once per frame (lane-av1rd2), not once per block, which is a whole
@@ -4863,6 +5068,18 @@ pub(crate) fn encode_inter_frame(
48635068
48645069 for sb_r in 0..sb_rows {
48655070 for sb_c in 0..sb_cols {
5071+ // Neighbour availability -- intra edges and the MV stack's
5072+ // scans alike -- stops at this superblock's own tile, exactly
5073+ // where the decoder stops it (`PlaneBuf::set_tile_origin`,
5074+ // `MiGrid::set_tile_bounds`).
5075+ let rect = layout.rect(layout.index_of_sb(sb_r as u32, sb_c as u32));
5076+ clip_planes_to_tile(&mut luma, &mut chroma, rect);
5077+ grid.set_tile_bounds(
5078+ rect.mi_row0 as usize,
5079+ rect.mi_col0 as usize,
5080+ rect.mi_row1 as usize,
5081+ rect.mi_col1 as usize,
5082+ );
48665083 for quadrant in 0..4 {
48675084 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
48685085 // Same filter as the tile writer's: a quadrant whose own mi
@@ -5289,21 +5506,58 @@ pub(crate) fn encode_inter_frame(
52895506 // next frame's writer starts from them -- exactly what
52905507 // `crate::stream::stored_cdfs_for` hands the decoder.
52915508 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
5292- let mut cdfs = start_cdfs
5509+ let cdfs = start_cdfs
52935510 .cloned()
52945511 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
5295- let start_cdfs = CdfSnapshot(cdfs.clone());
5296- crate::tile::arm_sign_bias(sign_bias);
5297- crate::tile::arm_reference_select(header.reference_select);
5298- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
5299- let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5300- mi_cols,
5301- mi_rows,
5302- base_q_idx,
5303- &blocks,
5304- tx_select,
5305- &mut cdfs,
5306- )?;
5512+ let start_cdfs = CdfSnapshot(cdfs);
5513+ let reference_select_bit = header.reference_select;
5514+ let order_hint_bits = seq.order_hint_bits;
5515+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
5516+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
5517+ // What this frame stores is the LARGEST tile's end-of-tile tables --
5518+ // its own header's `context_update_tile_id` (spec 7.20), which
5519+ // `tile_info_of` set to exactly that tile.
5520+ let store_tile = layout.largest_tile();
5521+ let end_cdfs = std::cell::RefCell::new(None);
5522+ // As in `encode_key_frame_inner`: every tile starts from this frame's
5523+ // own tables, so no tile depends on any other.
5524+ let code_tiles = |bits: u8,
5525+ sb_cols: usize,
5526+ cdef_grid: &[u8],
5527+ units: &[Option<crate::restoration::WienerInfo>]|
5528+ -> Result<Vec<Vec<u8>>> {
5529+ let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
5530+ crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
5531+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
5532+ crate::tile::arm_sign_bias(sign_bias);
5533+ // Thread-locals: every tile job arms its own worker.
5534+ crate::tile::arm_reference_select(reference_select_bit);
5535+ crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
5536+ let mut cdfs = start_cdfs.0.clone();
5537+ // Each tile's own MV grid: a candidate scan never reaches past
5538+ // the tile's bounds, so a grid holding only this tile's own
5539+ // blocks reads exactly as the decoder's frame-wide one does
5540+ // under `MiGrid::set_tile_bounds`.
5541+ let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
5542+ mv_grid.set_sign_bias(sign_bias);
5543+ let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5544+ mi_cols,
5545+ mi_rows,
5546+ base_q_idx,
5547+ &blocks,
5548+ tx_select,
5549+ &mut cdfs,
5550+ layout.rect(index),
5551+ &mut mv_grid,
5552+ )?;
5553+ Ok((bytes, Some(cdfs)))
5554+ })?;
5555+ if let Some(cdfs) = stored {
5556+ *end_cdfs.borrow_mut() = Some(cdfs);
5557+ }
5558+ Ok(out)
5559+ };
5560+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
53075561 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
53085562 // this tile against the same single-slot reference this encoder predicted
53095563 // from, under each candidate level.
@@ -5312,7 +5566,6 @@ pub(crate) fn encode_inter_frame(
53125566 // reference whose height is not the header's own `frame_height` (spec
53135567 // 7.9's compatible-size rule), and the chained-decode round trips prove
53145568 // the two predict identically.
5315- let end_cdfs = std::cell::RefCell::new(cdfs);
53165569 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
53175570 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
53185571 reference.clone()
@@ -5359,12 +5612,6 @@ pub(crate) fn encode_inter_frame(
53595612 refs[4] = trial_golden.as_ref();
53605613 refs[7] = trial_altref.as_ref();
53615614 let refpix = crate::decode::RefPix::ready(refs);
5362- // The luma restoration-unit grid this frame's `lr_params` implies
5363- // (`av1_lr_count_units` rounds to nearest, so a short last unit is
5364- // swallowed by the one before it), for the tile writer's own per-unit
5365- // walk.
5366- let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
5367- let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
53685615 pick_and_apply_filters(
53695616 &mut header,
53705617 &mut luma,
@@ -5375,36 +5622,19 @@ pub(crate) fn encode_inter_frame(
53755622 // `TxMode::Select` too (it used to skip and leave every inter frame
53765623 // unfiltered once Select became the default).
53775624 true,
5378- &mut tile,
5625+ &mut tiles,
53795626 search.lambda,
53805627 fctx,
53815628 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
53825629 // are what the NEXT frame writes from, so the winning re-code
53835630 // publishes its own into `end_cdfs` -- the first write's are stale
53845631 // the moment a second tile is coded.
5385- |bits, sb_cols, grid, units| {
5386- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
5387- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
5388- crate::tile::arm_sign_bias(sign_bias);
5389- crate::tile::arm_reference_select(reference_select());
5390- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
5391- let mut cdfs = start_cdfs.0.clone();
5392- let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5393- mi_cols,
5394- mi_rows,
5395- base_q_idx,
5396- &blocks,
5397- tx_select,
5398- &mut cdfs,
5399- );
5400- if coded.is_ok() {
5401- *end_cdfs.borrow_mut() = cdfs;
5402- }
5403- coded
5404- },
5405- |lf, cdef, h, tile, lr| {
5406- crate::decode::decode_inter_frame_tile_lr(
5407- tile,
5632+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
5633+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
5634+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
5635+ crate::decode::decode_inter_frame_tiles_lr(
5636+ &payloads,
5637+ &header_tile_info,
54085638 h.mi_cols,
54095639 h.mi_rows,
54105640 base_q_idx,
@@ -5429,9 +5659,14 @@ pub(crate) fn encode_inter_frame(
54295659 )
54305660 },
54315661 )?;
5432- let mut cdfs = end_cdfs.into_inner();
5662+ let mut cdfs = end_cdfs
5663+ .into_inner()
5664+ .unwrap_or_else(|| start_cdfs.0.clone());
54335665 cdfs.reset_counts();
54345666 let next_cdfs = CdfSnapshot(cdfs);
5667+ let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
5668+ header.tile_info.tile_size_bytes = tile_size_bytes;
5669+ let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
54355670 let mut stream = temporal_delimiter();
54365671 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
54375672
@@ -8328,6 +8563,8 @@ mod tests {
83288563 base_q_idx: q,
83298564 gop: source.len(),
83308565 colour: Colour::Unspecified,
8566+ tile_cols_log2: 0,
8567+ tile_rows_log2: 0,
83318568 };
83328569 let start = std::time::Instant::now();
83338570 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
@@ -3131,7 +3131,7 @@ mod tests {
31313131 );
31323132 }
31333133
3134- fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
3134+ pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
31353135 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
31363136 }
31373137
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.
@@ -1202,6 +1346,14 @@ impl Quadrant {
12021346 /// What the blocks above and to the left of the one being coded left behind,
12031347 /// kept on the 16x16 grid the smallest block sits on.
12041348 struct Neighbours {
1349+ /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/
1350+ /// `MiColStart`): every "is there a neighbour above/left of me" answer is
1351+ /// TILE-relative, not frame-relative -- the decoder's own
1352+ /// `Neighbours::start_tile` sets the same pair, and a writer that asked
1353+ /// `mi_row > 0` instead coded a tile's own first row against a neighbour
1354+ /// the decoder does not have (class: new map ignores tile edge).
1355+ tile_row0_mi: usize,
1356+ tile_col0_mi: usize,
12051357 /// Per plane, whether the neighbour coded anything and the sign of its DC.
12061358 above: Vec<[Neighbour; 3]>,
12071359 /// The same, down the left edge.
@@ -1311,6 +1463,8 @@ impl Neighbours {
13111463 /// mode-info units.
13121464 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
13131465 Self {
1466+ tile_row0_mi: 0,
1467+ tile_col0_mi: 0,
13141468 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
13151469 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
13161470 above_mode: vec![DC_PRED; cols],
@@ -1341,6 +1495,23 @@ impl Neighbours {
13411495 }
13421496
13431497 /// Clears the left edge, which a tile starts every superblock row with.
1498+ /// Points this writer's availability answers at one tile
1499+ /// ([`Self::tile_row0_mi`]).
1500+ fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) {
1501+ self.tile_row0_mi = row0_mi;
1502+ self.tile_col0_mi = col0_mi;
1503+ }
1504+
1505+ /// Whether the block at mode-info row `mi_r` has a neighbour above it
1506+ /// INSIDE its own tile, and the same to the left.
1507+ fn has_above(&self, mi_r: usize) -> bool {
1508+ mi_r > self.tile_row0_mi
1509+ }
1510+
1511+ fn has_left(&self, mi_c: usize) -> bool {
1512+ mi_c > self.tile_col0_mi
1513+ }
1514+
13441515 fn start_row(&mut self) {
13451516 self.left.iter_mut().for_each(|l| *l = Default::default());
13461517 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
@@ -1385,7 +1556,7 @@ impl Neighbours {
13851556 /// off a CDF row one higher than the decoder's, which is the first
13861557 /// divergence of the inter `TxMode::Select` stream.
13871558 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
1388- let (has_above, has_left) = (mi_r > 0, mi_c > 0);
1559+ let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c));
13891560 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
13901561 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
13911562 if has_above && self.above_inter[mi_c] {
@@ -1402,8 +1573,8 @@ impl Neighbours {
14021573 /// largest transform, plus whether the one to the left is at least as
14031574 /// tall. A neighbour outside the tile contributes nothing.
14041575 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
1405- usize::from(mi_r > 0 && usize::from(self.above_tx[mi_c]) >= max_tx)
1406- + usize::from(mi_c > 0 && usize::from(self.left_tx[mi_r]) >= max_tx)
1576+ usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
1577+ + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
14071578 }
14081579
14091580 /// Publishes one block's resolved transform side over every 4x4 unit it
@@ -1722,7 +1893,15 @@ pub fn sb_coeff_key_frame_tile_tx(
17221893 tx_select: bool,
17231894 ) -> Result<Vec<u8>> {
17241895 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1725- sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs)
1896+ sb_coeff_key_frame_tile_cdfs(
1897+ mi_cols,
1898+ mi_rows,
1899+ base_q_idx,
1900+ superblocks,
1901+ tx_select,
1902+ &mut cdfs,
1903+ TileRect::whole(mi_cols, mi_rows),
1904+ )
17261905 }
17271906
17281907 /// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
@@ -1740,6 +1919,11 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
17401919 superblocks: &[Superblock],
17411920 tx_select: bool,
17421921 cdfs: &mut Cdfs,
1922+ // This tile's own span (spec 5.11.1): the writer walks only these
1923+ // superblocks, and its neighbour bands start blank, so everything
1924+ // outside reads as unavailable exactly as the decoder's own per-tile
1925+ // reset makes it.
1926+ tile: TileRect,
17431927 ) -> Result<Vec<u8>> {
17441928 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
17451929 let _cdef_idx = CdefIdxGuard;
@@ -1797,15 +1981,16 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
17971981 mi_cols as usize,
17981982 mi_rows as usize,
17991983 );
1984+ neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
18001985
18011986 // The tile adapts every non-literal CDF it writes, exactly as the decoder
18021987 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
18031988 // off.
18041989 let mut cdfs = cdfs;
18051990 let mut enc = SymbolEncoder::new();
1806- for sb_r in 0..sb_rows {
1991+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
18071992 neighbours.start_row();
1808- for sb_c in 0..sb_cols {
1993+ for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
18091994 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
18101995 let at = (sb_r as usize * 4, sb_c as usize * 4);
18111996 let ctx = neighbours.partition_ctx(at, SB);
@@ -3666,7 +3851,16 @@ pub fn sb_coeff_inter_frame_tile_tx(
36663851 tx_select: bool,
36673852 ) -> Result<Vec<u8>> {
36683853 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3669- sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs)
3854+ sb_coeff_inter_frame_tile_cdfs(
3855+ mi_cols,
3856+ mi_rows,
3857+ base_q_idx,
3858+ blocks,
3859+ tx_select,
3860+ &mut cdfs,
3861+ TileRect::whole(mi_cols, mi_rows),
3862+ &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
3863+ )
36703864 }
36713865
36723866 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
@@ -3681,6 +3875,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
36813875 blocks: &[Quadrant],
36823876 tx_select: bool,
36833877 cdfs: &mut Cdfs,
3878+ // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
3879+ tile: TileRect,
3880+ // The frame's MV grid, carried across the frame's tiles by the caller
3881+ // (see the comment at `set_tile_bounds` below).
3882+ grid: &mut MiGrid,
36843883 ) -> Result<Vec<u8>> {
36853884 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
36863885 let _cdef_idx = CdefIdxGuard;
@@ -3721,7 +3920,21 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
37213920 mi_cols as usize,
37223921 mi_rows as usize,
37233922 );
3724- let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
3923+ neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
3924+ // The MV grid spans the FRAME and carries every tile written before this
3925+ // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
3926+ // keeps one grid for the whole frame and narrows its read window per
3927+ // tile): the tile bounds below are what stops a candidate scan reaching
3928+ // across the boundary, and a grid that was merely empty out there would
3929+ // not read the same as the decoder's wherever a scan reads the array
3930+ // without asking `MiGrid::get` first.
3931+ let mut grid = &mut *grid;
3932+ grid.set_tile_bounds(
3933+ tile.mi_row0 as usize,
3934+ tile.mi_col0 as usize,
3935+ tile.mi_row1 as usize,
3936+ tile.mi_col1 as usize,
3937+ );
37253938 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
37263939 let mut cdfs = cdfs;
37273940 let mut enc = SymbolEncoder::new();
@@ -3749,9 +3962,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
37493962 vec![0i32; TX16 * TX16],
37503963 ];
37513964
3752- for sb_r in 0..sb_rows {
3965+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
37533966 neighbours.start_row();
3754- for sb_c in 0..sb_cols {
3967+ for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
37553968 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
37563969 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
37573970 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
@@ -3994,9 +4207,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
39944207 };
39954208
39964209 let (r, c) = at;
3997- let has_above = r32 > 0;
3998- let has_left = c32 > 0;
39994210 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4211+ let has_above = neighbours.has_above(mi_r);
4212+ let has_left = neighbours.has_left(mi_c);
40004213 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
40014214 + usize::from(neighbours.left_skip[mi_r]);
40024215 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
@@ -4233,7 +4446,7 @@ fn write_inter_frame_leaf(
42334446 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
42344447 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
42354448
4236- let (has_above, has_left) = (r > 0, c > 0);
4449+ let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c));
42374450 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
42384451 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
42394452 let is_inter = block.inter.is_some();
@@ -4454,7 +4667,7 @@ fn write_inter_frame_leaf8(
44544667 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
44554668 write_cdef_idx(enc, leaf_mi, block.skip);
44564669
4457- let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
4670+ let (has_above, has_left) = (neighbours.has_above(leaf_mi.0), neighbours.has_left(leaf_mi.1));
44584671 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
44594672 let is_inter = block.inter.is_some();
44604673 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