forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1tiles' (d53ac525): multi-tile frames (uniform spacing, per-tile CDF/LR/neighbour reset) with deterministic parallel tile writes

Browse files at this commit

b58ff3faa4527e28f06cf5121d1ebf9d9f457e15Ahmet Kaan GümüşParent: 583d98de6c05e0
Sample-exact through our decoder and ffmpeg at 1x1/2x1/1x2/2x2/4x2; default
1x1 byte-identical. Root cause on the way: the writer's intra_inter/tx-size
contexts asked frame-relative availability (class: new map ignores tile
edge). Tile threads buy no wall yet: the search is still whole-frame.
crates/ec-av1/src/decode.rsmodified+96 -3
@@ -20763,18 +20763,61 @@ pub(crate) fn decode_key_frame_tile_lr(
20763 lr: &LoopRestorationParams,20763 lr: &LoopRestorationParams,
20764 fctx: &crate::decode::FrameCtx,20764 fctx: &crate::decode::FrameCtx,
20765 ) -> Result<Picture> {20765 ) -> Result<Picture> {
20766- let delta = DeltaParams::default();
20767 let single_tile = TileInfo {20766 let single_tile = TileInfo {
20768 mi_col_starts: vec![0, mi_cols],20767 mi_col_starts: vec![0, mi_cols],
20769 mi_row_starts: vec![0, mi_rows],20768 mi_row_starts: vec![0, mi_rows],
20770 ..TileInfo::default()20769 ..TileInfo::default()
20771 };20770 };
20772- decode_key_frame_tile_with_cdfs(20771+ decode_key_frame_tiles_lr(
20773 &[data],20772 &[data],
20774 &single_tile,20773 &single_tile,
20775 mi_cols,20774 mi_cols,
20776 mi_rows,20775 mi_rows,
20777 base_q_idx,20776 base_q_idx,
20777+ frame_width,
20778+ frame_height,
20779+ enable_filter_intra,
20780+ cdef,
20781+ loop_filter,
20782+ tx_select,
20783+ reduced_tx_set,
20784+ allow_screen_content_tools,
20785+ allow_intrabc,
20786+ lr,
20787+ fctx,
20788+ )
20789+}
20790+
20791+/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the
20792+/// encoder's own filter search hands back one payload per tile plus the
20793+/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets
20794+/// are the decoder's own (`decode_key_frame_tile_with_cdfs`).
20795+#[allow(clippy::too_many_arguments)]
20796+pub(crate) fn decode_key_frame_tiles_lr(
20797+ tiles: &[&[u8]],
20798+ tile_info: &TileInfo,
20799+ mi_cols: u32,
20800+ mi_rows: u32,
20801+ base_q_idx: u8,
20802+ frame_width: u32,
20803+ frame_height: u32,
20804+ enable_filter_intra: bool,
20805+ cdef: &CdefParams,
20806+ loop_filter: &LoopFilterParams,
20807+ tx_select: bool,
20808+ reduced_tx_set: bool,
20809+ allow_screen_content_tools: bool,
20810+ allow_intrabc: bool,
20811+ lr: &LoopRestorationParams,
20812+ fctx: &crate::decode::FrameCtx,
20813+) -> Result<Picture> {
20814+ let delta = DeltaParams::default();
20815+ decode_key_frame_tile_with_cdfs(
20816+ tiles,
20817+ tile_info,
20818+ mi_cols,
20819+ mi_rows,
20820+ base_q_idx,
20778 crate::quant::QuantDeltas::default(),20821 crate::quant::QuantDeltas::default(),
20779 frame_width,20822 frame_width,
20780 frame_height,20823 frame_height,
@@ -25394,6 +25437,7 @@ fn decode_inter_block(
25394 // combinations that don't implement scaled MC yet.25437 // combinations that don't implement scaled MC yet.
25395 frame_width: usize, fctx: &crate::decode::FrameCtx,25438 frame_width: usize, fctx: &crate::decode::FrameCtx,
25396 ) -> Result<()> {25439 ) -> Result<()> {
25440+
25397 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can25441 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
25398 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the25442 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
25399 // few 16-px-granular uses below.25443 // few 16-px-granular uses below.
@@ -32939,12 +32983,61 @@ pub(crate) fn decode_inter_frame_tile_lr(
32939 mi_row_starts: vec![0, mi_rows],32983 mi_row_starts: vec![0, mi_rows],
32940 ..TileInfo::default()32984 ..TileInfo::default()
32941 };32985 };
32942- decode_inter_frame_tile_with_cdfs(32986+ decode_inter_frame_tiles_lr(
32943 &[data],32987 &[data],
32944 &single_tile,32988 &single_tile,
32945 mi_cols,32989 mi_cols,
32946 mi_rows,32990 mi_rows,
32947 base_q_idx,32991 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,
32948 crate::quant::QuantDeltas::default(),33041 crate::quant::QuantDeltas::default(),
32949 frame_width,33042 frame_width,
32950 frame_height,33043 frame_height,
crates/ec-av1/src/encode.rsmodified+314 -77
@@ -979,9 +979,28 @@ struct Plane<'a> {
979 /// edge.979 /// edge.
980 true_width: usize,980 true_width: usize,
981 true_height: usize,981 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,
982 }992 }
983 993
984 impl Plane<'_> {994 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+ }
985 /// The reconstructed samples a block at `(x, y)` predicts from: the row1004 /// The reconstructed samples a block at `(x, y)` predicts from: the row
986 /// above it, the column to its left and the sample between them, each1005 /// above it, the column to its left and the sample between them, each
987 /// missing where the block sits against an edge of the frame.1006 /// missing where the block sits against an edge of the frame.
@@ -1033,14 +1052,17 @@ impl Plane<'_> {
1033 // `a_picture_off_the_block_grid_is_refused`), never through a block1052 // `a_picture_off_the_block_grid_is_refused`), never through a block
1034 // this encoder actually commits. Such a block has no true-edge1053 // this encoder actually commits. Such a block has no true-edge
1035 // samples above or left of it at all, same as `y == 0`/`x == 0`.1054 // 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)
1037 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());1058 .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(|| {
1039 (y..down)1060 (y..down)
1040 .map(|row| self.reconstruction[row * self.width + x - 1])1061 .map(|row| self.reconstruction[row * self.width + x - 1])
1041 .collect::<Vec<_>>()1062 .collect::<Vec<_>>()
1042 });1063 });
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]);
1044 (above, left, corner)1066 (above, left, corner)
1045 }1067 }
1046 1068
@@ -2956,6 +2978,126 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
2956 .collect()2978 .collect()
2957 }2979 }
2958 2980
2981+thread_local! {
2982+ /// The tile grid the next frame is coded with, as `(TileColsLog2,
2983+ /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
2984+ /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
2985+ /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
2986+ /// one tile per frame, what every caller that never arms anything gets
2987+ /// and what every stream this crate wrote before tiles existed carries.
2988+ static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
2989+}
2990+
2991+/// Arms this thread's next frame encodes with a tile grid (log2 counts).
2992+pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
2993+ TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
2994+}
2995+
2996+fn armed_tiles() -> (u32, u32) {
2997+ let armed = TILE_LOG2.with(std::cell::Cell::get);
2998+ if armed != (0, 0) {
2999+ return armed;
3000+ }
3001+ // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
3002+ // (which codes through `encode_sequence`, not the facade) can measure what
3003+ // a tile grid costs without a knob of its own -- same shape as
3004+ // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
3005+ match std::env::var("EC_AV1_TILES").ok() {
3006+ Some(v) if cfg!(test) => {
3007+ let mut f = v.split(':');
3008+ let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
3009+ let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
3010+ (cols, rows)
3011+ }
3012+ _ => armed,
3013+ }
3014+}
3015+
3016+/// Codes a frame's `tiles` tiles, each entirely on its own (see
3017+/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
3018+/// the crate's own pool, and hands back their payloads in tile order plus
3019+/// whatever `code` returned for tile `store` -- the CDF state
3020+/// `context_update_tile_id` names. The result cannot depend on the thread
3021+/// count: each job writes one tile from the frame's own starting tables into
3022+/// its own slot.
3023+fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
3024+where
3025+ F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
3026+{
3027+ type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
3028+ let threads = crate::par::tile_threads().min(tiles);
3029+ let mut slots: Vec<Slot> = Vec::new();
3030+ if threads <= 1 {
3031+ for index in 0..tiles {
3032+ slots.push(Some(code(index)));
3033+ }
3034+ } else {
3035+ let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
3036+ {
3037+ let batch = crate::par::Batch::new("ec-av1-tile");
3038+ for (from, to) in crate::par::bands(tiles, threads) {
3039+ let done = &done;
3040+ let code = &code;
3041+ batch.submit(move || {
3042+ for index in from..to {
3043+ let coded = code(index);
3044+ done.lock().expect("tile slots")[index] = Some(coded);
3045+ }
3046+ });
3047+ }
3048+ }
3049+ slots = done.into_inner().expect("tile slots");
3050+ }
3051+ let mut out = Vec::with_capacity(tiles);
3052+ let mut stored = None;
3053+ for (index, slot) in slots.into_iter().enumerate() {
3054+ let (bytes, cdfs) = slot.expect("every tile was coded")?;
3055+ if index == store {
3056+ stored = cdfs;
3057+ }
3058+ out.push(bytes);
3059+ }
3060+ Ok((out, stored))
3061+}
3062+
3063+/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
3064+/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
3065+/// tables the frame stores (spec 7.20), which is what
3066+/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
3067+/// below publish.
3068+fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
3069+ ec_av1_syntax::TileInfo {
3070+ uniform_spacing: true,
3071+ cols: layout.cols(),
3072+ rows: layout.rows(),
3073+ cols_log2: layout.cols_log2,
3074+ rows_log2: layout.rows_log2,
3075+ mi_col_starts: layout.mi_col_starts(),
3076+ mi_row_starts: layout.mi_row_starts(),
3077+ context_update_tile_id: layout.largest_tile() as u32,
3078+ tile_size_bytes,
3079+ }
3080+}
3081+
3082+/// Clips the three planes' intra edge reads to `rect`, the tile the
3083+/// superblock about to be searched belongs to (the encoder side of the
3084+/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
3085+/// raster order -- which is a linear extension of every tile's own coding
3086+/// order, so a block still only ever predicts from samples already
3087+/// reconstructed -- and only availability is tile-relative.
3088+fn clip_planes_to_tile(
3089+ luma: &mut Plane<'_>,
3090+ chroma: &mut [Plane<'_>; 2],
3091+ rect: crate::tile::TileRect,
3092+) {
3093+ let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
3094+ let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
3095+ luma.set_tile(x0, y0, x1, y1);
3096+ for plane in chroma.iter_mut() {
3097+ plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
3098+ }
3099+}
3100+
2959 /// Encodes one picture as a key frame.3101 /// Encodes one picture as a key frame.
2960 ///3102 ///
2961 /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer3103 /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
@@ -3096,6 +3238,7 @@ pub(crate) fn encode_key_frame_inner(
3096 if tx_select {3238 if tx_select {
3097 header.tx_mode = TxMode::Select;3239 header.tx_mode = TxMode::Select;
3098 }3240 }
3241+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
3099 3242
3100 // Prediction reads no further than this, in each plane's own units --3243 // Prediction reads no further than this, in each plane's own units --
3101 // see `Plane::true_width`/`true_height`.3244 // see `Plane::true_width`/`true_height`.
@@ -3114,6 +3257,10 @@ pub(crate) fn encode_key_frame_inner(
3114 height: picture.height,3257 height: picture.height,
3115 true_width,3258 true_width,
3116 true_height,3259 true_height,
3260+ tile_x0: 0,
3261+ tile_y0: 0,
3262+ tile_x1: picture.width,
3263+ tile_y1: picture.height,
3117 };3264 };
3118 let mut chroma = [3265 let mut chroma = [
3119 Plane {3266 Plane {
@@ -3123,6 +3270,10 @@ pub(crate) fn encode_key_frame_inner(
3123 height: picture.height / 2,3270 height: picture.height / 2,
3124 true_width: true_width / 2,3271 true_width: true_width / 2,
3125 true_height: true_height / 2,3272 true_height: true_height / 2,
3273+ tile_x0: 0,
3274+ tile_y0: 0,
3275+ tile_x1: picture.width / 2,
3276+ tile_y1: picture.height / 2,
3126 },3277 },
3127 Plane {3278 Plane {
3128 source: &picture_v8,3279 source: &picture_v8,
@@ -3131,6 +3282,10 @@ pub(crate) fn encode_key_frame_inner(
3131 height: picture.height / 2,3282 height: picture.height / 2,
3132 true_width: true_width / 2,3283 true_width: true_width / 2,
3133 true_height: true_height / 2,3284 true_height: true_height / 2,
3285+ tile_x0: 0,
3286+ tile_y0: 0,
3287+ tile_x1: picture.width / 2,
3288+ tile_y1: picture.height / 2,
3134 },3289 },
3135 ];3290 ];
3136 3291
@@ -3162,10 +3317,24 @@ pub(crate) fn encode_key_frame_inner(
3162 let mut above_mode = vec![DC_PRED; cols * 2];3317 let mut above_mode = vec![DC_PRED; cols * 2];
3163 let mut left_mode = vec![DC_PRED; rows * 2];3318 let mut left_mode = vec![DC_PRED; rows * 2];
3164 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));3319 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3320+ // This frame's tile grid (one tile unless the facade armed more).
3321+ let layout =
3322+ crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
3323+ header.tile_info = tile_info_of(&layout, 1);
3324+ // The filter search re-decodes this frame's tiles; the decoder derives
3325+ // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
3326+ // `mi_row_starts`), which is what makes the writer's rects and the
3327+ // reader's the same rects.
3328+ let header_tile_info = header.tile_info.clone();
3165 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);3329 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
3166 let mut modes = Vec::with_capacity(cols * rows);3330 let mut modes = Vec::with_capacity(cols * rows);
3167 for sb_row in 0..sb_rows {3331 for sb_row in 0..sb_rows {
3168 for sb_col in 0..sb_cols {3332 for sb_col in 0..sb_cols {
3333+ clip_planes_to_tile(
3334+ &mut luma,
3335+ &mut chroma,
3336+ layout.rect(layout.index_of_sb(sb_row as u32, sb_col as u32)),
3337+ );
3169 // The quadrants of a superblock are coded in the order the decoder3338 // The quadrants of a superblock are coded in the order the decoder
3170 // walks them, which for a 64x64 split into 32x32 blocks is raster3339 // walks them, which for a 64x64 split into 32x32 blocks is raster
3171 // order among the quadrants that are inside the frame.3340 // order among the quadrants that are inside the frame.
@@ -3361,56 +3530,65 @@ pub(crate) fn encode_key_frame_inner(
3361 // defaults again (spec 7.20's `started_from` arm) -- the first inter3530 // defaults again (spec 7.20's `started_from` arm) -- the first inter
3362 // frame after it therefore starts from the defaults too.3531 // frame after it therefore starts from the defaults too.
3363 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);3532 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3364- let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));3533+ let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3365- let start_cdfs = CdfSnapshot(cdfs.clone());3534+ let start_cdfs = CdfSnapshot(cdfs);
3366- let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(3535+ // The luma restoration-unit grid this frame's `lr_params` implies
3536+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3537+ // swallowed by the one before it), for the tile writer's own per-unit
3538+ // walk.
3539+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3540+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3541+ // Every tile is coded from this frame's OWN starting tables and leaves
3542+ // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
3543+ // loop-restoration reference and its neighbour contexts), so the tiles
3544+ // are independent of each other and of the order they are written in.
3545+ let code_tiles = |bits: u8,
3546+ sb_cols: usize,
3547+ grid: &[u8],
3548+ units: &[Option<crate::restoration::WienerInfo>]|
3549+ -> Result<Vec<Vec<u8>>> {
3550+ let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
3551+ crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3552+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3553+ let mut cdfs = start_cdfs.0.clone();
3554+ let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
3367 mi_cols,3555 mi_cols,
3368 mi_rows,3556 mi_rows,
3369 base_q_idx,3557 base_q_idx,
3370 &superblocks,3558 &superblocks,
3371 tx_select,3559 tx_select,
3372 &mut cdfs,3560 &mut cdfs,
3561+ layout.rect(index),
3373 )?;3562 )?;
3563+ Ok((bytes, None))
3564+ })?;
3565+ Ok(out)
3566+ };
3567+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
3374 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing3568 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
3375 // the tile just coded back to the decoder under each candidate (see3569 // the tile just coded back to the decoder under each candidate (see
3376 // `crate::filter_search`), and keep the filtered picture that wins as3570 // `crate::filter_search`), and keep the filtered picture that wins as
3377 // the reconstruction -- what a decoder outputs, and what the next3571 // the reconstruction -- what a decoder outputs, and what the next
3378 // frame predicts from.3572 // frame predicts from.
3379- // The luma restoration-unit grid this frame's `lr_params` implies
3380- // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3381- // swallowed by the one before it), for the tile writer's own per-unit
3382- // walk.
3383- let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3384- let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3385 pick_and_apply_filters(3573 pick_and_apply_filters(
3386 &mut header,3574 &mut header,
3387 &mut luma,3575 &mut luma,
3388 &mut chroma,3576 &mut chroma,
3389 [&picture_y8, &picture_u8, &picture_v8],3577 [&picture_y8, &picture_u8, &picture_v8],
3390 true,3578 true,
3391- &mut tile,3579+ &mut tiles,
3392 search.lambda,3580 search.lambda,
3393 fctx,3581 fctx,
3394 // Every re-code starts from this frame's OWN starting tables, never3582 // Every re-code starts from this frame's OWN starting tables, never
3395 // from where the first write left them: the second tile is the same3583 // from where the first write left them: the second tile is the same
3396 // symbol sequence plus new ones, so it must adapt from the same3584 // symbol sequence plus new ones, so it must adapt from the same
3397 // point the decoder will.3585 // point the decoder will.
3398- |bits, sb_cols, grid, units| {3586+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
3399- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());3587+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
3400- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());3588+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
3401- let mut cdfs = start_cdfs.0.clone();3589+ crate::decode::decode_key_frame_tiles_lr(
3402- crate::tile::sb_coeff_key_frame_tile_cdfs(3590+ &payloads,
3403- mi_cols,3591+ &header_tile_info,
3404- mi_rows,
3405- base_q_idx,
3406- &superblocks,
3407- tx_select,
3408- &mut cdfs,
3409- )
3410- },
3411- |lf, cdef, h, tile, lr| {
3412- crate::decode::decode_key_frame_tile_lr(
3413- tile,
3414 h.mi_cols,3592 h.mi_cols,
3415 h.mi_rows,3593 h.mi_rows,
3416 base_q_idx,3594 base_q_idx,
@@ -3428,6 +3606,9 @@ pub(crate) fn encode_key_frame_inner(
3428 )3606 )
3429 },3607 },
3430 )?;3608 )?;
3609+ let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
3610+ header.tile_info.tile_size_bytes = tile_size_bytes;
3611+ let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
3431 let mut stream = temporal_delimiter();3612 let mut stream = temporal_delimiter();
3432 stream.extend_from_slice(&sequence_header_obu(&seq)?);3613 stream.extend_from_slice(&sequence_header_obu(&seq)?);
3433 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);3614 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3477,19 +3658,25 @@ fn pick_and_apply_filters(
3477 chroma: &mut [Plane<'_>; 2],3658 chroma: &mut [Plane<'_>; 2],
3478 source: [&[u8]; 3],3659 source: [&[u8]; 3],
3479 search: bool,3660 search: bool,
3480- // The coded tile, replaced in place when the search chooses a per-64x643661+ // The coded tiles, one payload per tile of the frame's grid, replaced in
3481- // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile3662+ // place when the search chooses a per-64x64 `cdef_idx` list
3482- // payload, so the tile is written a second time under `recode` and the3663+ // (`cdef_bits > 0`): those literals live in the tile payloads, so every
3483- // winner re-decoded from it.3664+ // tile is written a second time under `recode` and the winner
3484- tile: &mut Vec<u8>,3665+ // re-decoded from them.
3666+ tiles: &mut Vec<Vec<u8>>,
3485 lambda: f64,3667 lambda: f64,
3486 fctx: &crate::decode::FrameCtx,3668 fctx: &crate::decode::FrameCtx,
3487- recode: impl Fn(u8, usize, &[u8], &[Option<crate::restoration::WienerInfo>]) -> Result<Vec<u8>>,3669+ recode: impl Fn(
3670+ u8,
3671+ usize,
3672+ &[u8],
3673+ &[Option<crate::restoration::WienerInfo>],
3674+ ) -> Result<Vec<Vec<u8>>>,
3488 decode: impl Fn(3675 decode: impl Fn(
3489 &LoopFilterParams,3676 &LoopFilterParams,
3490 &CdefParams,3677 &CdefParams,
3491 &FrameHeader,3678 &FrameHeader,
3492- &[u8],3679+ &[Vec<u8>],
3493 &LoopRestorationParams,3680 &LoopRestorationParams,
3494 ) -> Result<Picture>,3681 ) -> Result<Picture>,
3495 ) -> Result<()> {3682 ) -> Result<()> {
@@ -3516,7 +3703,7 @@ fn pick_and_apply_filters(
3516 return Ok(picture);3703 return Ok(picture);
3517 }3704 }
3518 crate::decode::arm_filter_replay();3705 crate::decode::arm_filter_replay();
3519- decode(lf, cdef, &hdr, tile, &none_lr)3706+ decode(lf, cdef, &hdr, tiles, &none_lr)
3520 },3707 },
3521 source,3708 source,
3522 luma.width,3709 luma.width,
@@ -3547,14 +3734,14 @@ fn pick_and_apply_filters(
3547 fctx.capture_stages.set(lr_on);3734 fctx.capture_stages.set(lr_on);
3548 let mut filtered = if idx_grid.is_empty() {3735 let mut filtered = if idx_grid.is_empty() {
3549 if lr_on {3736 if lr_on {
3550- decode(&lf, &cdef, &hdr, tile, &none_lr)?3737+ decode(&lf, &cdef, &hdr, tiles, &none_lr)?
3551 } else {3738 } else {
3552 picture3739 picture
3553 }3740 }
3554 } else {3741 } else {
3555 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;3742 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
3556 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;3743 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
3557- *tile = coded;3744+ *tiles = coded;
3558 picture3745 picture
3559 };3746 };
3560 fctx.capture_stages.set(false);3747 fctx.capture_stages.set(false);
@@ -3585,7 +3772,7 @@ fn pick_and_apply_filters(
3585 if units.iter().any(Option::is_some) {3772 if units.iter().any(Option::is_some) {
3586 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;3773 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
3587 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;3774 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
3588- *tile = coded;3775+ *tiles = coded;
3589 lr = want;3776 lr = want;
3590 }3777 }
3591 }3778 }
@@ -4716,6 +4903,10 @@ pub(crate) fn encode_inter_frame(
4716 height: picture.height,4903 height: picture.height,
4717 true_width,4904 true_width,
4718 true_height,4905 true_height,
4906+ tile_x0: 0,
4907+ tile_y0: 0,
4908+ tile_x1: picture.width,
4909+ tile_y1: picture.height,
4719 };4910 };
4720 let mut chroma = [4911 let mut chroma = [
4721 Plane {4912 Plane {
@@ -4725,6 +4916,10 @@ pub(crate) fn encode_inter_frame(
4725 height: picture.height / 2,4916 height: picture.height / 2,
4726 true_width: true_width / 2,4917 true_width: true_width / 2,
4727 true_height: true_height / 2,4918 true_height: true_height / 2,
4919+ tile_x0: 0,
4920+ tile_y0: 0,
4921+ tile_x1: picture.width / 2,
4922+ tile_y1: picture.height / 2,
4728 },4923 },
4729 Plane {4924 Plane {
4730 source: &picture_v8,4925 source: &picture_v8,
@@ -4733,6 +4928,10 @@ pub(crate) fn encode_inter_frame(
4733 height: picture.height / 2,4928 height: picture.height / 2,
4734 true_width: true_width / 2,4929 true_width: true_width / 2,
4735 true_height: true_height / 2,4930 true_height: true_height / 2,
4931+ tile_x0: 0,
4932+ tile_y0: 0,
4933+ tile_x1: picture.width / 2,
4934+ tile_y1: picture.height / 2,
4736 },4935 },
4737 ];4936 ];
4738 4937
@@ -4755,6 +4954,12 @@ pub(crate) fn encode_inter_frame(
4755 let (cols, rows) = (cols as usize, rows as usize);4954 let (cols, rows) = (cols as usize, rows as usize);
4756 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));4955 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
4757 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);4956 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
4957+ // This frame's tile grid, as in `encode_key_frame_inner`.
4958+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
4959+ let layout =
4960+ crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
4961+ header.tile_info = tile_info_of(&layout, 1);
4962+ let header_tile_info = header.tile_info.clone();
4758 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is4963 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
4759 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --4964 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
4760 // once per frame (lane-av1rd2), not once per block, which is a whole4965 // once per frame (lane-av1rd2), not once per block, which is a whole
@@ -4765,6 +4970,18 @@ pub(crate) fn encode_inter_frame(
4765 4970
4766 for sb_r in 0..sb_rows {4971 for sb_r in 0..sb_rows {
4767 for sb_c in 0..sb_cols {4972 for sb_c in 0..sb_cols {
4973+ // Neighbour availability -- intra edges and the MV stack's
4974+ // scans alike -- stops at this superblock's own tile, exactly
4975+ // where the decoder stops it (`PlaneBuf::set_tile_origin`,
4976+ // `MiGrid::set_tile_bounds`).
4977+ let rect = layout.rect(layout.index_of_sb(sb_r as u32, sb_c as u32));
4978+ clip_planes_to_tile(&mut luma, &mut chroma, rect);
4979+ grid.set_tile_bounds(
4980+ rect.mi_row0 as usize,
4981+ rect.mi_col0 as usize,
4982+ rect.mi_row1 as usize,
4983+ rect.mi_col1 as usize,
4984+ );
4768 for quadrant in 0..4 {4985 for quadrant in 0..4 {
4769 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);4986 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
4770 // Same filter as the tile writer's: a quadrant whose own mi4987 // Same filter as the tile writer's: a quadrant whose own mi
@@ -5191,21 +5408,58 @@ pub(crate) fn encode_inter_frame(
5191 // next frame's writer starts from them -- exactly what5408 // next frame's writer starts from them -- exactly what
5192 // `crate::stream::stored_cdfs_for` hands the decoder.5409 // `crate::stream::stored_cdfs_for` hands the decoder.
5193 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);5410 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
5194- let mut cdfs = start_cdfs5411+ let cdfs = start_cdfs
5195 .cloned()5412 .cloned()
5196 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));5413 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
5197- let start_cdfs = CdfSnapshot(cdfs.clone());5414+ let start_cdfs = CdfSnapshot(cdfs);
5415+ let reference_select_bit = header.reference_select;
5416+ let order_hint_bits = seq.order_hint_bits;
5417+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
5418+ let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
5419+ // What this frame stores is the LARGEST tile's end-of-tile tables --
5420+ // its own header's `context_update_tile_id` (spec 7.20), which
5421+ // `tile_info_of` set to exactly that tile.
5422+ let store_tile = layout.largest_tile();
5423+ let end_cdfs = std::cell::RefCell::new(None);
5424+ // As in `encode_key_frame_inner`: every tile starts from this frame's
5425+ // own tables, so no tile depends on any other.
5426+ let code_tiles = |bits: u8,
5427+ sb_cols: usize,
5428+ cdef_grid: &[u8],
5429+ units: &[Option<crate::restoration::WienerInfo>]|
5430+ -> Result<Vec<Vec<u8>>> {
5431+ let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
5432+ crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
5433+ crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
5198 crate::tile::arm_sign_bias(sign_bias);5434 crate::tile::arm_sign_bias(sign_bias);
5199- crate::tile::arm_reference_select(header.reference_select);5435+ // Thread-locals: every tile job arms its own worker.
5200- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);5436+ crate::tile::arm_reference_select(reference_select_bit);
5201- let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(5437+ crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
5438+ let mut cdfs = start_cdfs.0.clone();
5439+ // Each tile's own MV grid: a candidate scan never reaches past
5440+ // the tile's bounds, so a grid holding only this tile's own
5441+ // blocks reads exactly as the decoder's frame-wide one does
5442+ // under `MiGrid::set_tile_bounds`.
5443+ let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
5444+ mv_grid.set_sign_bias(sign_bias);
5445+ let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5202 mi_cols,5446 mi_cols,
5203 mi_rows,5447 mi_rows,
5204 base_q_idx,5448 base_q_idx,
5205 &blocks,5449 &blocks,
5206 tx_select,5450 tx_select,
5207 &mut cdfs,5451 &mut cdfs,
5452+ layout.rect(index),
5453+ &mut mv_grid,
5208 )?;5454 )?;
5455+ Ok((bytes, Some(cdfs)))
5456+ })?;
5457+ if let Some(cdfs) = stored {
5458+ *end_cdfs.borrow_mut() = Some(cdfs);
5459+ }
5460+ Ok(out)
5461+ };
5462+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
5209 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs5463 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
5210 // this tile against the same single-slot reference this encoder predicted5464 // this tile against the same single-slot reference this encoder predicted
5211 // from, under each candidate level.5465 // from, under each candidate level.
@@ -5214,7 +5468,6 @@ pub(crate) fn encode_inter_frame(
5214 // reference whose height is not the header's own `frame_height` (spec5468 // reference whose height is not the header's own `frame_height` (spec
5215 // 7.9's compatible-size rule), and the chained-decode round trips prove5469 // 7.9's compatible-size rule), and the chained-decode round trips prove
5216 // the two predict identically.5470 // the two predict identically.
5217- let end_cdfs = std::cell::RefCell::new(cdfs);
5218 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);5471 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
5219 let trial_ref = if (reference.width, reference.height) == (fw, fh) {5472 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
5220 reference.clone()5473 reference.clone()
@@ -5261,12 +5514,6 @@ pub(crate) fn encode_inter_frame(
5261 refs[4] = trial_golden.as_ref();5514 refs[4] = trial_golden.as_ref();
5262 refs[7] = trial_altref.as_ref();5515 refs[7] = trial_altref.as_ref();
5263 let refpix = crate::decode::RefPix::ready(refs);5516 let refpix = crate::decode::RefPix::ready(refs);
5264- // The luma restoration-unit grid this frame's `lr_params` implies
5265- // (`av1_lr_count_units` rounds to nearest, so a short last unit is
5266- // swallowed by the one before it), for the tile writer's own per-unit
5267- // walk.
5268- let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
5269- let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
5270 pick_and_apply_filters(5517 pick_and_apply_filters(
5271 &mut header,5518 &mut header,
5272 &mut luma,5519 &mut luma,
@@ -5277,36 +5524,19 @@ pub(crate) fn encode_inter_frame(
5277 // `TxMode::Select` too (it used to skip and leave every inter frame5524 // `TxMode::Select` too (it used to skip and leave every inter frame
5278 // unfiltered once Select became the default).5525 // unfiltered once Select became the default).
5279 true,5526 true,
5280- &mut tile,5527+ &mut tiles,
5281 search.lambda,5528 search.lambda,
5282 fctx,5529 fctx,
5283 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables5530 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
5284 // are what the NEXT frame writes from, so the winning re-code5531 // are what the NEXT frame writes from, so the winning re-code
5285 // publishes its own into `end_cdfs` -- the first write's are stale5532 // publishes its own into `end_cdfs` -- the first write's are stale
5286 // the moment a second tile is coded.5533 // the moment a second tile is coded.
5287- |bits, sb_cols, grid, units| {5534+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
5288- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());5535+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
5289- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());5536+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
5290- crate::tile::arm_sign_bias(sign_bias);5537+ crate::decode::decode_inter_frame_tiles_lr(
5291- crate::tile::arm_reference_select(reference_select());5538+ &payloads,
5292- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);5539+ &header_tile_info,
5293- let mut cdfs = start_cdfs.0.clone();
5294- let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5295- mi_cols,
5296- mi_rows,
5297- base_q_idx,
5298- &blocks,
5299- tx_select,
5300- &mut cdfs,
5301- );
5302- if coded.is_ok() {
5303- *end_cdfs.borrow_mut() = cdfs;
5304- }
5305- coded
5306- },
5307- |lf, cdef, h, tile, lr| {
5308- crate::decode::decode_inter_frame_tile_lr(
5309- tile,
5310 h.mi_cols,5540 h.mi_cols,
5311 h.mi_rows,5541 h.mi_rows,
5312 base_q_idx,5542 base_q_idx,
@@ -5331,9 +5561,14 @@ pub(crate) fn encode_inter_frame(
5331 )5561 )
5332 },5562 },
5333 )?;5563 )?;
5334- let mut cdfs = end_cdfs.into_inner();5564+ let mut cdfs = end_cdfs
5565+ .into_inner()
5566+ .unwrap_or_else(|| start_cdfs.0.clone());
5335 cdfs.reset_counts();5567 cdfs.reset_counts();
5336 let next_cdfs = CdfSnapshot(cdfs);5568 let next_cdfs = CdfSnapshot(cdfs);
5569+ let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
5570+ header.tile_info.tile_size_bytes = tile_size_bytes;
5571+ let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
5337 let mut stream = temporal_delimiter();5572 let mut stream = temporal_delimiter();
5338 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);5573 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
5339 5574
@@ -8226,6 +8461,8 @@ mod tests {
8226 base_q_idx: q,8461 base_q_idx: q,
8227 gop: source.len(),8462 gop: source.len(),
8228 colour: Colour::Unspecified,8463 colour: Colour::Unspecified,
8464+ tile_cols_log2: 0,
8465+ tile_rows_log2: 0,
8229 };8466 };
8230 let start = std::time::Instant::now();8467 let start = std::time::Instant::now();
8231 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();8468 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
crates/ec-av1/src/encoder.rsmodified+309 -1
@@ -276,6 +276,32 @@ pub struct EncoderConfig {
276 pub gop: usize,276 pub gop: usize,
277 /// The colour the sequence header signals.277 /// The colour the sequence header signals.
278 pub colour: Colour,278 pub colour: Colour,
279+ /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 <<
280+ /// tile_cols_log2` uniformly spaced tile columns, each coded and
281+ /// decodable on its own. `0` -- one tile column -- is the default and
282+ /// is byte for byte the stream this encoder wrote before tiles existed.
283+ pub tile_cols_log2: u32,
284+ /// `TileRowsLog2`, the same down the rows.
285+ pub tile_rows_log2: u32,
286+}
287+
288+impl EncoderConfig {
289+ /// A config at `width`x`height` with one tile, `gop` pictures between
290+ /// key frames and no colour signalling -- what every caller that does
291+ /// not care about tiles writes, so that adding a field here does not
292+ /// rewrite them.
293+ #[must_use]
294+ pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self {
295+ Self {
296+ width,
297+ height,
298+ base_q_idx,
299+ gop,
300+ colour,
301+ tile_cols_log2: 0,
302+ tile_rows_log2: 0,
303+ }
304+ }
279 }305 }
280 306
281 /// One coded picture: its OBUs, in the order a demuxer that just wants bytes307 /// One coded picture: its OBUs, in the order a demuxer that just wants bytes
@@ -510,6 +536,22 @@ impl Av1Encoder {
510 // do, before the first `encode()` call rather than only surfacing it536 // do, before the first `encode()` call rather than only surfacing it
511 // then.537 // then.
512 Picture::grey(config.width, config.height).check_even()?;538 Picture::grey(config.width, config.height).check_even()?;
539+ // A tile is a whole number of superblocks, so a frame cannot carry
540+ // more tile columns (rows) than it has 64x64 superblocks across
541+ // (down) -- the header's own `max_log2_tile_cols` bound (spec
542+ // 5.9.15), refused here rather than at the first `encode()` call.
543+ let sb_cols = config.width.div_ceil(64) as u32;
544+ let sb_rows = config.height.div_ceil(64) as u32;
545+ if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows {
546+ return Err(Error::unsupported(
547+ "AV1 encode",
548+ format!(
549+ "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has",
550+ 1 << config.tile_cols_log2,
551+ 1 << config.tile_rows_log2
552+ ),
553+ ));
554+ }
513 Ok(Self {555 Ok(Self {
514 carried_cdfs: None,556 carried_cdfs: None,
515 golden: None,557 golden: None,
@@ -632,6 +674,7 @@ impl Av1Encoder {
632 /// # Errors674 /// # Errors
633 /// As [`Av1Encoder::encode`], minus the pyramid refusal.675 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
634 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {676 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
677+ crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
635 if (picture.width, picture.height) != (self.config.width, self.config.height) {678 if (picture.width, picture.height) != (self.config.width, self.config.height) {
636 return Err(Error::unsupported(679 return Err(Error::unsupported(
637 "AV1 encode",680 "AV1 encode",
@@ -671,6 +714,7 @@ impl Av1Encoder {
671 /// # Errors714 /// # Errors
672 /// As [`Av1Encoder::encode_frames`].715 /// As [`Av1Encoder::encode_frames`].
673 pub fn flush(&mut self) -> Result<Vec<Packet>> {716 pub fn flush(&mut self) -> Result<Vec<Packet>> {
717+ crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
674 self.drain_pending()718 self.drain_pending()
675 }719 }
676 720
@@ -1029,6 +1073,8 @@ mod tests {
1029 base_q_idx: 100,1073 base_q_idx: 100,
1030 gop: 2,1074 gop: 2,
1031 colour: Colour::Bt709Limited,1075 colour: Colour::Bt709Limited,
1076+ tile_cols_log2: 0,
1077+ tile_rows_log2: 0,
1032 };1078 };
1033 let mut enc = Av1Encoder::new(config).unwrap();1079 let mut enc = Av1Encoder::new(config).unwrap();
1034 for t in 0..5u64 {1080 for t in 0..5u64 {
@@ -1049,6 +1095,8 @@ mod tests {
1049 base_q_idx: 100,1095 base_q_idx: 100,
1050 gop: 3,1096 gop: 3,
1051 colour: Colour::Unspecified,1097 colour: Colour::Unspecified,
1098+ tile_cols_log2: 0,
1099+ tile_rows_log2: 0,
1052 };1100 };
1053 let mut enc = Av1Encoder::new(config).unwrap();1101 let mut enc = Av1Encoder::new(config).unwrap();
1054 let keys: Vec<bool> = (0..7)1102 let keys: Vec<bool> = (0..7)
@@ -1147,6 +1195,8 @@ mod tests {
1147 base_q_idx: 120,1195 base_q_idx: 120,
1148 gop: 15,1196 gop: 15,
1149 colour: Colour::Bt709Limited,1197 colour: Colour::Bt709Limited,
1198+ tile_cols_log2: 0,
1199+ tile_rows_log2: 0,
1150 };1200 };
1151 let mut enc = Av1Encoder::new(config).unwrap();1201 let mut enc = Av1Encoder::new(config).unwrap();
1152 assert_eq!(enc.display_size(), (width, height));1202 assert_eq!(enc.display_size(), (width, height));
@@ -1200,6 +1250,8 @@ mod tests {
1200 base_q_idx: 100,1250 base_q_idx: 100,
1201 gop: 4,1251 gop: 4,
1202 colour: Colour::Bt709Limited,1252 colour: Colour::Bt709Limited,
1253+ tile_cols_log2: 0,
1254+ tile_rows_log2: 0,
1203 };1255 };
1204 let mut enc = Av1Encoder::new(config).unwrap();1256 let mut enc = Av1Encoder::new(config).unwrap();
1205 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();1257 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
@@ -1222,6 +1274,8 @@ mod tests {
1222 base_q_idx: 100,1274 base_q_idx: 100,
1223 gop: 4,1275 gop: 4,
1224 colour: Colour::Bt601Limited,1276 colour: Colour::Bt601Limited,
1277+ tile_cols_log2: 0,
1278+ tile_rows_log2: 0,
1225 };1279 };
1226 let mut enc = Av1Encoder::new(config).unwrap();1280 let mut enc = Av1Encoder::new(config).unwrap();
1227 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();1281 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
@@ -1242,6 +1296,8 @@ mod tests {
1242 base_q_idx: 100,1296 base_q_idx: 100,
1243 gop: 4,1297 gop: 4,
1244 colour: Colour::Bt709Limited,1298 colour: Colour::Bt709Limited,
1299+ tile_cols_log2: 0,
1300+ tile_rows_log2: 0,
1245 };1301 };
1246 let mut enc = Av1Encoder::new(config).unwrap();1302 let mut enc = Av1Encoder::new(config).unwrap();
1247 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();1303 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
@@ -1257,6 +1313,8 @@ mod tests {
1257 base_q_idx: 100,1313 base_q_idx: 100,
1258 gop: 0,1314 gop: 0,
1259 colour: Colour::Bt709Limited,1315 colour: Colour::Bt709Limited,
1316+ tile_cols_log2: 0,
1317+ tile_rows_log2: 0,
1260 };1318 };
1261 let err = Av1Encoder::new(config).unwrap_err();1319 let err = Av1Encoder::new(config).unwrap_err();
1262 assert!(err.to_string().contains("gop"), "{err}");1320 assert!(err.to_string().contains("gop"), "{err}");
@@ -1328,6 +1386,8 @@ mod tests {
1328 base_q_idx: 100,1386 base_q_idx: 100,
1329 gop: 24,1387 gop: 24,
1330 colour: Colour::Bt709Limited,1388 colour: Colour::Bt709Limited,
1389+ tile_cols_log2: 0,
1390+ tile_rows_log2: 0,
1331 };1391 };
1332 let mut enc =1392 let mut enc =
1333 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();1393 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
@@ -1367,6 +1427,8 @@ mod tests {
1367 base_q_idx: 100,1427 base_q_idx: 100,
1368 gop: frames,1428 gop: frames,
1369 colour: Colour::Bt709Limited,1429 colour: Colour::Bt709Limited,
1430+ tile_cols_log2: 0,
1431+ tile_rows_log2: 0,
1370 };1432 };
1371 let rate = RateTarget::Bitrate {1433 let rate = RateTarget::Bitrate {
1372 bits_per_second,1434 bits_per_second,
@@ -1424,6 +1486,8 @@ mod tests {
1424 base_q_idx: 100,1486 base_q_idx: 100,
1425 gop: 24,1487 gop: 24,
1426 colour: Colour::Bt709Limited,1488 colour: Colour::Bt709Limited,
1489+ tile_cols_log2: 0,
1490+ tile_rows_log2: 0,
1427 };1491 };
1428 let mut enc =1492 let mut enc =
1429 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();1493 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
@@ -1499,13 +1563,15 @@ mod tests {
1499 /// display-order list and fails here.1563 /// display-order list and fails here.
1500 #[test]1564 #[test]
1501 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {1565 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
1502- let (width, height) = (128usize, 64usize);1566+ let (width, height) = (128usize, 128usize);
1503 let config = EncoderConfig {1567 let config = EncoderConfig {
1504 width,1568 width,
1505 height,1569 height,
1506 base_q_idx: 120,1570 base_q_idx: 120,
1507 gop: 32,1571 gop: 32,
1508 colour: Colour::Bt709Limited,1572 colour: Colour::Bt709Limited,
1573+ tile_cols_log2: 0,
1574+ tile_rows_log2: 0,
1509 };1575 };
1510 let pyramid = Pyramid {1576 let pyramid = Pyramid {
1511 mini_gop: 4,1577 mini_gop: 4,
@@ -1586,6 +1652,246 @@ mod tests {
1586 }1652 }
1587 }1653 }
1588 1654
1655+ /// Every tile layout this encoder can write decodes SAMPLE-EXACT
1656+ /// through both decoders -- ours and ffmpeg's -- and the frames really
1657+ /// carry the tiles the header claims (the OBU parser locates one payload
1658+ /// per tile, so a stream that quietly stayed single-tile fails here
1659+ /// rather than passing on a green round trip).
1660+ ///
1661+ /// The bytes are what the gate is on: an encoder that clipped its
1662+ /// neighbour availability wrong writes a stream whose two decoders agree
1663+ /// with each other and disagree with nothing -- so the ffmpeg half is
1664+ /// the one that catches a tile boundary the writer respected and the
1665+ /// spec does not, and the parser half catches the reverse.
1666+ #[test]
1667+ fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
1668+ let (width, height) = (640usize, 384usize);
1669+ let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1670+ let mut sizes = Vec::new();
1671+ for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] {
1672+ let config = EncoderConfig {
1673+ width,
1674+ height,
1675+ base_q_idx: 120,
1676+ gop: 4,
1677+ colour: Colour::Bt709Limited,
1678+ tile_cols_log2: cols_log2,
1679+ tile_rows_log2: rows_log2,
1680+ };
1681+ let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
1682+ let mut enc = Av1Encoder::new(config).unwrap();
1683+ let mut stream = Vec::new();
1684+ for (i, picture) in sources.iter().enumerate() {
1685+ let packet = enc
1686+ .encode(picture)
1687+ .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}"));
1688+ stream.extend_from_slice(&packet.data);
1689+ }
1690+ sizes.push((layout.clone(), stream.len()));
1691+
1692+ // The frames carry the tiles their headers claim.
1693+ let mut parser = ec_av1_syntax::Av1Parser::new();
1694+ let mut frames = 0usize;
1695+ let mut offset = 0usize;
1696+ while offset < stream.len() {
1697+ let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap();
1698+ let unit: usize = obus.iter().map(|o| o.total_size).sum();
1699+ for obu in &obus {
1700+ if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
1701+ assert_eq!(
1702+ (parsed.tile_info.cols, parsed.tile_info.rows),
1703+ (1 << cols_log2, 1 << rows_log2),
1704+ "{layout}: the header's own tile grid"
1705+ );
1706+ assert_eq!(
1707+ tiles.len(),
1708+ 1 << (cols_log2 + rows_log2),
1709+ "{layout}: tile payloads located in the tile group"
1710+ );
1711+ frames += 1;
1712+ }
1713+ }
1714+ offset += unit;
1715+ }
1716+ assert_eq!(frames, sources.len(), "{layout}: coded frames");
1717+
1718+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1719+ assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
1720+ if !have_ffmpeg() {
1721+ eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
1722+ continue;
1723+ }
1724+ let theirs = ffmpeg_decode_luma(&stream, width, height);
1725+ assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
1726+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1727+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1728+ assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size");
1729+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1730+ panic!(
1731+ "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
1732+ at % width,
1733+ at / width,
1734+ got[at],
1735+ b[at],
1736+ );
1737+ }
1738+ }
1739+ }
1740+ let base = sizes[0].1 as f64;
1741+ for (layout, bytes) in &sizes {
1742+ eprintln!(
1743+ "{layout}: {bytes} bytes ({:+.2}% vs one tile)",
1744+ (*bytes as f64 / base - 1.0) * 100.0
1745+ );
1746+ }
1747+ }
1748+
1749+ /// What tiles and tile threads are worth at the size the editor exports
1750+ /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall
1751+ /// per cell. Ignored by default (minutes).
1752+ #[test]
1753+ #[ignore = "1080p wall table: minutes, run it with --ignored"]
1754+ fn tile_wall_table_at_1080p() {
1755+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1756+ let (width, height) = (1920usize, 1080usize);
1757+ let Some(sources) = h264_clip_frames(width, height, 8) else {
1758+ eprintln!("SKIP tile_wall_table_at_1080p: no fixture");
1759+ return;
1760+ };
1761+ let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];
1762+ let threadings = [1usize, 2, 4, 8];
1763+ let mut table: Vec<(String, usize, f64, usize)> = Vec::new();
1764+ for pass in 0..2 {
1765+ for &(cols_log2, rows_log2) in &layouts {
1766+ for &threads in &threadings {
1767+ crate::par::set_tile_threads(threads);
1768+ let config = EncoderConfig {
1769+ width,
1770+ height,
1771+ base_q_idx: 120,
1772+ gop: 8,
1773+ colour: Colour::Bt709Limited,
1774+ tile_cols_log2: cols_log2,
1775+ tile_rows_log2: rows_log2,
1776+ };
1777+ let mut enc = Av1Encoder::new(config).unwrap();
1778+ let start = std::time::Instant::now();
1779+ let mut bytes = 0usize;
1780+ for picture in &sources {
1781+ bytes += enc.encode(picture).unwrap().data.len();
1782+ }
1783+ let wall = start.elapsed().as_secs_f64();
1784+ let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2);
1785+ match table.iter_mut().find(|r| r.0 == name && r.1 == threads) {
1786+ Some(row) => row.2 = row.2.min(wall),
1787+ None => table.push((name, threads, wall, bytes)),
1788+ }
1789+ let _ = pass;
1790+ }
1791+ }
1792+ }
1793+ crate::par::set_tile_threads(1);
1794+ eprintln!("| tiles | threads | wall (s, best of 2) | bytes |");
1795+ for (name, threads, wall, bytes) in &table {
1796+ eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |");
1797+ }
1798+ }
1799+
1800+ /// The tiles of a frame are entropy-independent, so the bytes must not
1801+ /// depend on how many workers wrote them: the same stream at one tile
1802+ /// thread and at four, per layout.
1803+ #[test]
1804+ fn tile_bytes_do_not_depend_on_the_thread_count() {
1805+ let _gate_lock = crate::stream::tests::lock_gate_counters();
1806+ let (width, height) = (320usize, 192usize);
1807+ let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();
1808+ let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {
1809+ crate::par::set_tile_threads(threads);
1810+ let config = EncoderConfig {
1811+ width,
1812+ height,
1813+ base_q_idx: 120,
1814+ gop: 3,
1815+ colour: Colour::Bt709Limited,
1816+ tile_cols_log2: cols_log2,
1817+ tile_rows_log2: rows_log2,
1818+ };
1819+ let mut enc = Av1Encoder::new(config).unwrap();
1820+ let mut stream = Vec::new();
1821+ for picture in &sources {
1822+ stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1823+ }
1824+ stream
1825+ };
1826+ for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] {
1827+ let one = coded(1, cols_log2, rows_log2);
1828+ let four = coded(4, cols_log2, rows_log2);
1829+ assert_eq!(
1830+ one,
1831+ four,
1832+ "{}x{} tiles: {} bytes at one thread, {} at four",
1833+ 1 << cols_log2,
1834+ 1 << rows_log2,
1835+ one.len(),
1836+ four.len()
1837+ );
1838+ }
1839+ crate::par::set_tile_threads(1);
1840+ }
1841+
1842+ /// The same round trip at a real 1920x1080 crop of the gate's own clip
1843+ /// -- the size the editor's export actually runs at, where a tile grid
1844+ /// is worth having. Ignored by default only for its wall (a 1080p
1845+ /// encode of three pictures), not for any weakness in the check.
1846+ #[test]
1847+ #[ignore = "1080p encode: minutes, run it with --ignored"]
1848+ fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {
1849+ let (width, height) = (1920usize, 1080usize);
1850+ let Some(sources) = h264_clip_frames(width, height, 3) else {
1851+ eprintln!("SKIP the 1080p tile round trip: no fixture");
1852+ return;
1853+ };
1854+ for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] {
1855+ let config = EncoderConfig {
1856+ width,
1857+ height,
1858+ base_q_idx: 120,
1859+ gop: 3,
1860+ colour: Colour::Bt709Limited,
1861+ tile_cols_log2: cols_log2,
1862+ tile_rows_log2: rows_log2,
1863+ };
1864+ let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
1865+ let mut enc = Av1Encoder::new(config).unwrap();
1866+ let mut stream = Vec::new();
1867+ for (i, picture) in sources.iter().enumerate() {
1868+ let packet = enc
1869+ .encode(picture)
1870+ .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}"));
1871+ stream.extend_from_slice(&packet.data);
1872+ }
1873+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1874+ assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
1875+ if !have_ffmpeg() {
1876+ eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg");
1877+ continue;
1878+ }
1879+ let theirs = ffmpeg_decode_luma(&stream, width, height);
1880+ assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
1881+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1882+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1883+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1884+ panic!(
1885+ "1080p {layout} frame {i}: luma differs first at ({}, {})",
1886+ at % width,
1887+ at / width
1888+ );
1889+ }
1890+ }
1891+ eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len());
1892+ }
1893+ }
1894+
1589 /// [`RateTarget::Quality`] is monotone: a higher quality dial never1895 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
1590 /// produces a smaller stream or a worse mean PSNR than a lower one, on1896 /// produces a smaller stream or a worse mean PSNR than a lower one, on
1591 /// the same real clip.1897 /// the same real clip.
@@ -1609,6 +1915,8 @@ mod tests {
1609 base_q_idx: 100,1915 base_q_idx: 100,
1610 gop: 8,1916 gop: 8,
1611 colour: Colour::Bt709Limited,1917 colour: Colour::Bt709Limited,
1918+ tile_cols_log2: 0,
1919+ tile_rows_log2: 0,
1612 };1920 };
1613 let mut enc =1921 let mut enc =
1614 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();1922 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
crates/ec-av1/src/frame.rsmodified+41 -0
@@ -644,6 +644,47 @@ pub fn show_existing_frame_obu(seq: &SequenceHeader, frame_to_show_map_idx: u8)
644 ))644 ))
645 }645 }
646 646
647+/// How wide a tile group's per-tile size field has to be for these tiles
648+/// (`TileSizeBytes`, spec 5.11.1: every non-last tile carries `size - 1` in
649+/// that many bytes, so the widest of them decides).
650+pub(crate) fn tile_size_bytes_for(tiles: &[Vec<u8>]) -> u32 {
651+ let widest = tiles
652+ .iter()
653+ .rev()
654+ .skip(1)
655+ .map(|t| t.len().saturating_sub(1))
656+ .max()
657+ .unwrap_or(0);
658+ match widest {
659+ 0..=0xFF => 1,
660+ 0x100..=0xFFFF => 2,
661+ 0x1_0000..=0xFF_FFFF => 3,
662+ _ => 4,
663+ }
664+}
665+
666+/// `tile_group_obu()` (spec 5.11.1) for a group holding every tile of the
667+/// frame: `tile_start_and_end_present_flag = 0` (only coded when the frame
668+/// has more than one tile), byte alignment, then each tile's size (all but
669+/// the last, little endian, `tile_size_bytes` wide) ahead of its payload.
670+/// One tile leaves the payload exactly as it was, which is what every
671+/// single-tile stream this crate wrote before tiles existed carries.
672+pub(crate) fn tile_group_payload(tiles: &[Vec<u8>], tile_size_bytes: u32) -> Vec<u8> {
673+ if tiles.len() == 1 {
674+ return tiles[0].clone();
675+ }
676+ // The flag bit plus `byte_alignment()`: one zero byte.
677+ let mut out = vec![0u8];
678+ for (i, tile) in tiles.iter().enumerate() {
679+ if i + 1 < tiles.len() {
680+ let size = (tile.len() - 1) as u32;
681+ out.extend((0..tile_size_bytes).map(|b| (size >> (8 * b)) as u8));
682+ }
683+ out.extend_from_slice(tile);
684+ }
685+ out
686+}
687+
647 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group688 /// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group
648 /// payload the caller supplies.689 /// payload the caller supplies.
649 pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {690 pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {
crates/ec-av1/src/par.rsmodified+29 -0
@@ -55,6 +55,35 @@ pub(crate) fn set_filter_threads(n: usize) {
55 FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);55 FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
56 }56 }
57 57
58+/// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's
59+/// tiles across (default 1 = the shipped single-threaded write). Tiles are
60+/// entropy-independent by construction (each starts from the frame's own
61+/// tables and resets its own contexts), so the bytes a frame comes out as do
62+/// not depend on this -- `encoder::tests::tile_bytes_do_not_depend_on_the_
63+/// thread_count` is the pin.
64+static TILE_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
65+
66+pub(crate) fn tile_threads() -> usize {
67+ match TILE_THREADS.load(std::sync::atomic::Ordering::Relaxed) {
68+ 0 => {
69+ let n = crate::envflags::var("EC_AV1_TILE_THREADS")
70+ .ok()
71+ .and_then(|v| v.trim().parse::<usize>().ok())
72+ .unwrap_or(1)
73+ .clamp(1, 64);
74+ TILE_THREADS.store(n, std::sync::atomic::Ordering::Relaxed);
75+ n
76+ }
77+ n => n,
78+ }
79+}
80+
81+/// Test-only override of [`tile_threads`]; see [`set_filter_threads`].
82+#[cfg(test)]
83+pub(crate) fn set_tile_threads(n: usize) {
84+ TILE_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
85+}
86+
58 /// Splits `units` work units into at most `threads` contiguous, non-empty87 /// Splits `units` work units into at most `threads` contiguous, non-empty
59 /// bands. The caller picks the unit so that a band boundary is always a legal88 /// bands. The caller picks the unit so that a band boundary is always a legal
60 /// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one89 /// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one
crates/ec-av1/src/stream.rsmodified+2 -2
@@ -1900,7 +1900,7 @@ pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
1900 }1900 }
1901 1901
1902 #[cfg(test)]1902 #[cfg(test)]
1903-mod tests {1903+pub(crate) mod tests {
1904 use super::*;1904 use super::*;
1905 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};1905 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
1906 1906
@@ -3131,7 +3131,7 @@ mod tests {
3131 );3131 );
3132 }3132 }
3133 3133
3134- fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {3134+ pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
3135 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())3135 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
3136 }3136 }
3137 3137
crates/ec-av1/src/tile.rsmodified+227 -14
@@ -116,6 +116,150 @@ fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32)
116 /// `crate::decode`), the span [`write_lr`] resolves its units over.116 /// `crate::decode`), the span [`write_lr`] resolves its units over.
117 const SB_MI_W: u32 = 16;117 const SB_MI_W: u32 = 16;
118 118
119+/// One tile's own superblock and mode-info span (spec 5.11.1's tile loop
120+/// bounds): `MiColStarts[i]..MiColStarts[i+1]` and the same down the rows,
121+/// with the superblock indices those mi bounds fall on. The writers walk
122+/// exactly this rect, and everything a block reads outside it -- the
123+/// neighbour bands, the MV grid -- is left at the "unavailable" state a
124+/// tile's own first row and column see, which is how the decoder clips them
125+/// (`MiGrid::set_tile_bounds`, `PlaneBuf::set_tile_origin`).
126+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127+pub(crate) struct TileRect {
128+ pub(crate) sb_col0: u32,
129+ pub(crate) sb_col1: u32,
130+ pub(crate) sb_row0: u32,
131+ pub(crate) sb_row1: u32,
132+ pub(crate) mi_col0: u32,
133+ pub(crate) mi_col1: u32,
134+ pub(crate) mi_row0: u32,
135+ pub(crate) mi_row1: u32,
136+}
137+
138+impl TileRect {
139+ /// The whole frame as one tile -- what every single-tile caller writes.
140+ pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self {
141+ let (cols, rows) = block_grid(mi_cols, mi_rows);
142+ Self {
143+ sb_col0: 0,
144+ sb_col1: cols.div_ceil(2),
145+ sb_row0: 0,
146+ sb_row1: rows.div_ceil(2),
147+ mi_col0: 0,
148+ mi_col1: mi_cols,
149+ mi_row0: 0,
150+ mi_row1: mi_rows,
151+ }
152+ }
153+}
154+
155+/// A frame's uniform tile grid (spec 5.9.15's `uniform_tile_spacing_flag`
156+/// arm, mirrored from `ec_av1_syntax::frame::read_tile_info` so that what
157+/// this encoder writes and what a decoder derives from the same two log2
158+/// fields are the same rects). 64x64 superblocks only, which is the only
159+/// size this encoder's sequence header signals.
160+#[derive(Clone, Debug)]
161+pub(crate) struct TileLayout {
162+ pub(crate) cols_log2: u32,
163+ pub(crate) rows_log2: u32,
164+ /// Tile column starts in superblocks, `cols + 1` entries.
165+ col_starts_sb: Vec<u32>,
166+ /// Tile row starts in superblocks, `rows + 1` entries.
167+ row_starts_sb: Vec<u32>,
168+ mi_cols: u32,
169+ mi_rows: u32,
170+}
171+
172+impl TileLayout {
173+ /// The layout `cols_log2`/`rows_log2` name for this frame's mi grid.
174+ pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self {
175+ let (cols32, rows32) = block_grid(mi_cols, mi_rows);
176+ let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2));
177+ let starts = |total: u32, log2: u32| {
178+ let step = total.div_ceil(1 << log2).max(1);
179+ let mut v: Vec<u32> = (0..total).step_by(step as usize).collect();
180+ v.push(total);
181+ v
182+ };
183+ Self {
184+ cols_log2,
185+ rows_log2,
186+ col_starts_sb: starts(sb_cols, cols_log2),
187+ row_starts_sb: starts(sb_rows, rows_log2),
188+ mi_cols,
189+ mi_rows,
190+ }
191+ }
192+
193+ pub(crate) fn cols(&self) -> u32 {
194+ self.col_starts_sb.len() as u32 - 1
195+ }
196+
197+ pub(crate) fn rows(&self) -> u32 {
198+ self.row_starts_sb.len() as u32 - 1
199+ }
200+
201+ pub(crate) fn count(&self) -> usize {
202+ (self.cols() * self.rows()) as usize
203+ }
204+
205+ /// `MiColStarts`/`MiRowStarts` as the frame header carries them.
206+ pub(crate) fn mi_col_starts(&self) -> Vec<u32> {
207+ let mut v: Vec<u32> = self.col_starts_sb[..self.cols() as usize]
208+ .iter()
209+ .map(|sb| sb * SB_MI_W)
210+ .collect();
211+ v.push(self.mi_cols);
212+ v
213+ }
214+
215+ pub(crate) fn mi_row_starts(&self) -> Vec<u32> {
216+ let mut v: Vec<u32> = self.row_starts_sb[..self.rows() as usize]
217+ .iter()
218+ .map(|sb| sb * SB_MI_W)
219+ .collect();
220+ v.push(self.mi_rows);
221+ v
222+ }
223+
224+ /// Tile `index` (row major, `TileNum`) as a rect.
225+ pub(crate) fn rect(&self, index: usize) -> TileRect {
226+ let (r, c) = (index / self.cols() as usize, index % self.cols() as usize);
227+ let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]);
228+ let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]);
229+ TileRect {
230+ sb_col0,
231+ sb_col1,
232+ sb_row0,
233+ sb_row1,
234+ mi_col0: sb_col0 * SB_MI_W,
235+ mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols),
236+ mi_row0: sb_row0 * SB_MI_W,
237+ mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows),
238+ }
239+ }
240+
241+ /// Which tile the superblock at `(sb_r, sb_c)` belongs to -- what the
242+ /// encoder's frame-raster search consults to clip a block's neighbour
243+ /// availability to its own tile.
244+ pub(crate) fn index_of_sb(&self, sb_r: u32, sb_c: u32) -> usize {
245+ let col = self.col_starts_sb[1..].partition_point(|&s| s <= sb_c);
246+ let row = self.row_starts_sb[1..].partition_point(|&s| s <= sb_r);
247+ row * self.cols() as usize + col
248+ }
249+
250+ /// The largest tile by mi area, `context_update_tile_id`'s own rule
251+ /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both
252+ /// name the biggest tile, whose end-of-tile tables the frame stores).
253+ pub(crate) fn largest_tile(&self) -> usize {
254+ (0..self.count())
255+ .max_by_key(|&i| {
256+ let t = self.rect(i);
257+ ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64)
258+ })
259+ .unwrap_or(0)
260+ }
261+}
262+
119 /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).263 /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
120 struct CdefIdxPlan {264 struct CdefIdxPlan {
121 /// The header's `cdef_bits`; never 0 while armed.265 /// The header's `cdef_bits`; never 0 while armed.
@@ -1134,6 +1278,14 @@ impl Quadrant {
1134 /// What the blocks above and to the left of the one being coded left behind,1278 /// What the blocks above and to the left of the one being coded left behind,
1135 /// kept on the 16x16 grid the smallest block sits on.1279 /// kept on the 16x16 grid the smallest block sits on.
1136 struct Neighbours {1280 struct Neighbours {
1281+ /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/
1282+ /// `MiColStart`): every "is there a neighbour above/left of me" answer is
1283+ /// TILE-relative, not frame-relative -- the decoder's own
1284+ /// `Neighbours::start_tile` sets the same pair, and a writer that asked
1285+ /// `mi_row > 0` instead coded a tile's own first row against a neighbour
1286+ /// the decoder does not have (class: new map ignores tile edge).
1287+ tile_row0_mi: usize,
1288+ tile_col0_mi: usize,
1137 /// Per plane, whether the neighbour coded anything and the sign of its DC.1289 /// Per plane, whether the neighbour coded anything and the sign of its DC.
1138 above: Vec<[Neighbour; 3]>,1290 above: Vec<[Neighbour; 3]>,
1139 /// The same, down the left edge.1291 /// The same, down the left edge.
@@ -1243,6 +1395,8 @@ impl Neighbours {
1243 /// mode-info units.1395 /// mode-info units.
1244 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {1396 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
1245 Self {1397 Self {
1398+ tile_row0_mi: 0,
1399+ tile_col0_mi: 0,
1246 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],1400 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1247 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],1401 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1248 above_mode: vec![DC_PRED; cols],1402 above_mode: vec![DC_PRED; cols],
@@ -1273,6 +1427,23 @@ impl Neighbours {
1273 }1427 }
1274 1428
1275 /// Clears the left edge, which a tile starts every superblock row with.1429 /// Clears the left edge, which a tile starts every superblock row with.
1430+ /// Points this writer's availability answers at one tile
1431+ /// ([`Self::tile_row0_mi`]).
1432+ fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) {
1433+ self.tile_row0_mi = row0_mi;
1434+ self.tile_col0_mi = col0_mi;
1435+ }
1436+
1437+ /// Whether the block at mode-info row `mi_r` has a neighbour above it
1438+ /// INSIDE its own tile, and the same to the left.
1439+ fn has_above(&self, mi_r: usize) -> bool {
1440+ mi_r > self.tile_row0_mi
1441+ }
1442+
1443+ fn has_left(&self, mi_c: usize) -> bool {
1444+ mi_c > self.tile_col0_mi
1445+ }
1446+
1276 fn start_row(&mut self) {1447 fn start_row(&mut self) {
1277 self.left.iter_mut().for_each(|l| *l = Default::default());1448 self.left.iter_mut().for_each(|l| *l = Default::default());
1278 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);1449 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
@@ -1317,7 +1488,7 @@ impl Neighbours {
1317 /// off a CDF row one higher than the decoder's, which is the first1488 /// off a CDF row one higher than the decoder's, which is the first
1318 /// divergence of the inter `TxMode::Select` stream.1489 /// divergence of the inter `TxMode::Select` stream.
1319 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {1490 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
1320- let (has_above, has_left) = (mi_r > 0, mi_c > 0);1491+ let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c));
1321 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;1492 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
1322 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;1493 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
1323 if has_above && self.above_inter[mi_c] {1494 if has_above && self.above_inter[mi_c] {
@@ -1334,8 +1505,8 @@ impl Neighbours {
1334 /// largest transform, plus whether the one to the left is at least as1505 /// largest transform, plus whether the one to the left is at least as
1335 /// tall. A neighbour outside the tile contributes nothing.1506 /// tall. A neighbour outside the tile contributes nothing.
1336 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {1507 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
1337- usize::from(mi_r > 0 && usize::from(self.above_tx[mi_c]) >= max_tx)1508+ usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
1338- + usize::from(mi_c > 0 && usize::from(self.left_tx[mi_r]) >= max_tx)1509+ + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
1339 }1510 }
1340 1511
1341 /// Publishes one block's resolved transform side over every 4x4 unit it1512 /// Publishes one block's resolved transform side over every 4x4 unit it
@@ -1654,7 +1825,15 @@ pub fn sb_coeff_key_frame_tile_tx(
1654 tx_select: bool,1825 tx_select: bool,
1655 ) -> Result<Vec<u8>> {1826 ) -> Result<Vec<u8>> {
1656 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));1827 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1657- sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs)1828+ sb_coeff_key_frame_tile_cdfs(
1829+ mi_cols,
1830+ mi_rows,
1831+ base_q_idx,
1832+ superblocks,
1833+ tx_select,
1834+ &mut cdfs,
1835+ TileRect::whole(mi_cols, mi_rows),
1836+ )
1658 }1837 }
1659 1838
1660 /// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the1839 /// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
@@ -1672,6 +1851,11 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1672 superblocks: &[Superblock],1851 superblocks: &[Superblock],
1673 tx_select: bool,1852 tx_select: bool,
1674 cdfs: &mut Cdfs,1853 cdfs: &mut Cdfs,
1854+ // This tile's own span (spec 5.11.1): the writer walks only these
1855+ // superblocks, and its neighbour bands start blank, so everything
1856+ // outside reads as unavailable exactly as the decoder's own per-tile
1857+ // reset makes it.
1858+ tile: TileRect,
1675 ) -> Result<Vec<u8>> {1859 ) -> Result<Vec<u8>> {
1676 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.1860 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
1677 let _cdef_idx = CdefIdxGuard;1861 let _cdef_idx = CdefIdxGuard;
@@ -1729,15 +1913,16 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1729 mi_cols as usize,1913 mi_cols as usize,
1730 mi_rows as usize,1914 mi_rows as usize,
1731 );1915 );
1916+ neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
1732 1917
1733 // The tile adapts every non-literal CDF it writes, exactly as the decoder1918 // The tile adapts every non-literal CDF it writes, exactly as the decoder
1734 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`1919 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
1735 // off.1920 // off.
1736 let mut cdfs = cdfs;1921 let mut cdfs = cdfs;
1737 let mut enc = SymbolEncoder::new();1922 let mut enc = SymbolEncoder::new();
1738- for sb_r in 0..sb_rows {1923+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
1739 neighbours.start_row();1924 neighbours.start_row();
1740- for sb_c in 0..sb_cols {1925+ for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
1741 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);1926 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
1742 let at = (sb_r as usize * 4, sb_c as usize * 4);1927 let at = (sb_r as usize * 4, sb_c as usize * 4);
1743 let ctx = neighbours.partition_ctx(at, SB);1928 let ctx = neighbours.partition_ctx(at, SB);
@@ -3598,7 +3783,16 @@ pub fn sb_coeff_inter_frame_tile_tx(
3598 tx_select: bool,3783 tx_select: bool,
3599 ) -> Result<Vec<u8>> {3784 ) -> Result<Vec<u8>> {
3600 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));3785 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3601- sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs)3786+ sb_coeff_inter_frame_tile_cdfs(
3787+ mi_cols,
3788+ mi_rows,
3789+ base_q_idx,
3790+ blocks,
3791+ tx_select,
3792+ &mut cdfs,
3793+ TileRect::whole(mi_cols, mi_rows),
3794+ &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
3795+ )
3602 }3796 }
3603 3797
3604 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --3798 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
@@ -3613,6 +3807,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3613 blocks: &[Quadrant],3807 blocks: &[Quadrant],
3614 tx_select: bool,3808 tx_select: bool,
3615 cdfs: &mut Cdfs,3809 cdfs: &mut Cdfs,
3810+ // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
3811+ tile: TileRect,
3812+ // The frame's MV grid, carried across the frame's tiles by the caller
3813+ // (see the comment at `set_tile_bounds` below).
3814+ grid: &mut MiGrid,
3616 ) -> Result<Vec<u8>> {3815 ) -> Result<Vec<u8>> {
3617 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.3816 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3618 let _cdef_idx = CdefIdxGuard;3817 let _cdef_idx = CdefIdxGuard;
@@ -3653,7 +3852,21 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3653 mi_cols as usize,3852 mi_cols as usize,
3654 mi_rows as usize,3853 mi_rows as usize,
3655 );3854 );
3656- let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);3855+ neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
3856+ // The MV grid spans the FRAME and carries every tile written before this
3857+ // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
3858+ // keeps one grid for the whole frame and narrows its read window per
3859+ // tile): the tile bounds below are what stops a candidate scan reaching
3860+ // across the boundary, and a grid that was merely empty out there would
3861+ // not read the same as the decoder's wherever a scan reads the array
3862+ // without asking `MiGrid::get` first.
3863+ let mut grid = &mut *grid;
3864+ grid.set_tile_bounds(
3865+ tile.mi_row0 as usize,
3866+ tile.mi_col0 as usize,
3867+ tile.mi_row1 as usize,
3868+ tile.mi_col1 as usize,
3869+ );
3657 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));3870 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
3658 let mut cdfs = cdfs;3871 let mut cdfs = cdfs;
3659 let mut enc = SymbolEncoder::new();3872 let mut enc = SymbolEncoder::new();
@@ -3681,9 +3894,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3681 vec![0i32; TX16 * TX16],3894 vec![0i32; TX16 * TX16],
3682 ];3895 ];
3683 3896
3684- for sb_r in 0..sb_rows {3897+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
3685 neighbours.start_row();3898 neighbours.start_row();
3686- for sb_c in 0..sb_cols {3899+ for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
3687 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);3900 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
3688 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);3901 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
3689 let sb_ctx = neighbours.partition_ctx(sb_at, SB);3902 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
@@ -3926,9 +4139,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3926 };4139 };
3927 4140
3928 let (r, c) = at;4141 let (r, c) = at;
3929- let has_above = r32 > 0;
3930- let has_left = c32 > 0;
3931 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));4142 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4143+ let has_above = neighbours.has_above(mi_r);
4144+ let has_left = neighbours.has_left(mi_c);
3932 let skip_ctx = usize::from(neighbours.above_skip[mi_c])4145 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
3933 + usize::from(neighbours.left_skip[mi_r]);4146 + usize::from(neighbours.left_skip[mi_r]);
3934 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4147 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
@@ -4165,7 +4378,7 @@ fn write_inter_frame_leaf(
4165 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4378 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
4166 write_cdef_idx(enc, (mi_r, mi_c), block.skip);4379 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
4167 4380
4168- let (has_above, has_left) = (r > 0, c > 0);4381+ let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c));
4169 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);4382 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
4170 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);4383 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
4171 let is_inter = block.inter.is_some();4384 let is_inter = block.inter.is_some();
@@ -4386,7 +4599,7 @@ fn write_inter_frame_leaf8(
4386 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4599 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
4387 write_cdef_idx(enc, leaf_mi, block.skip);4600 write_cdef_idx(enc, leaf_mi, block.skip);
4388 4601
4389- let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);4602+ let (has_above, has_left) = (neighbours.has_above(leaf_mi.0), neighbours.has_left(leaf_mi.1));
4390 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);4603 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
4391 let is_inter = block.inter.is_some();4604 let is_inter = block.inter.is_some();
4392 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);4605 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
tools/ec-bench/src/main.rsmodified+16 -0
@@ -345,12 +345,28 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
345 rows.push(missing("ec-av1", "decode"));345 rows.push(missing("ec-av1", "decode"));
346 return;346 return;
347 }347 }
348+ // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` benches the encoder's tile
349+ // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1`
350+ // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones
351+ // the byte pins carry. `EC_AV1_TILE_THREADS=<n>` (read by `ec_av1::par`)
352+ // spreads those tiles across `n` pool workers; the bytes are the same
353+ // either way, only the wall changes.
354+ let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES")
355+ .ok()
356+ .and_then(|spec| {
357+ let mut f = spec.split(':');
358+ let cols = f.next()?.parse().ok()?;
359+ Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0)))
360+ })
361+ .unwrap_or((0, 0));
348 let cfg = Av1Config {362 let cfg = Av1Config {
349 width: w as usize,363 width: w as usize,
350 height: h as usize,364 height: h as usize,
351 base_q_idx: 100,365 base_q_idx: 100,
352 gop: 10,366 gop: 10,
353 colour: Colour::default(),367 colour: Colour::default(),
368+ tile_cols_log2,
369+ tile_rows_log2,
354 };370 };
355 // `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` benches the371 // `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` benches the
356 // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead372 // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead