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(
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
@@ -2971,6 +2993,126 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
2971 .collect()2993 .collect()
2972 }2994 }
2973 2995
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+
2974 /// Encodes one picture as a key frame.3116 /// Encodes one picture as a key frame.
2975 ///3117 ///
2976 /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer3118 /// `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(
3111 if tx_select {3253 if tx_select {
3112 header.tx_mode = TxMode::Select;3254 header.tx_mode = TxMode::Select;
3113 }3255 }
3256+ let (tile_cols_log2, tile_rows_log2) = armed_tiles();
3114 3257
3115 // Prediction reads no further than this, in each plane's own units --3258 // Prediction reads no further than this, in each plane's own units --
3116 // see `Plane::true_width`/`true_height`.3259 // see `Plane::true_width`/`true_height`.
@@ -3129,6 +3272,10 @@ pub(crate) fn encode_key_frame_inner(
3129 height: picture.height,3272 height: picture.height,
3130 true_width,3273 true_width,
3131 true_height,3274 true_height,
3275+ tile_x0: 0,
3276+ tile_y0: 0,
3277+ tile_x1: picture.width,
3278+ tile_y1: picture.height,
3132 };3279 };
3133 let mut chroma = [3280 let mut chroma = [
3134 Plane {3281 Plane {
@@ -3138,6 +3285,10 @@ pub(crate) fn encode_key_frame_inner(
3138 height: picture.height / 2,3285 height: picture.height / 2,
3139 true_width: true_width / 2,3286 true_width: true_width / 2,
3140 true_height: true_height / 2,3287 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,
3141 },3292 },
3142 Plane {3293 Plane {
3143 source: &picture_v8,3294 source: &picture_v8,
@@ -3146,6 +3297,10 @@ pub(crate) fn encode_key_frame_inner(
3146 height: picture.height / 2,3297 height: picture.height / 2,
3147 true_width: true_width / 2,3298 true_width: true_width / 2,
3148 true_height: true_height / 2,3299 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,
3149 },3304 },
3150 ];3305 ];
3151 3306
@@ -3177,10 +3332,24 @@ pub(crate) fn encode_key_frame_inner(
3177 let mut above_mode = vec![DC_PRED; cols * 2];3332 let mut above_mode = vec![DC_PRED; cols * 2];
3178 let mut left_mode = vec![DC_PRED; rows * 2];3333 let mut left_mode = vec![DC_PRED; rows * 2];
3179 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));3334 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();
3180 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);3344 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
3181 let mut modes = Vec::with_capacity(cols * rows);3345 let mut modes = Vec::with_capacity(cols * rows);
3182 for sb_row in 0..sb_rows {3346 for sb_row in 0..sb_rows {
3183 for sb_col in 0..sb_cols {3347 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+ );
3184 // The quadrants of a superblock are coded in the order the decoder3353 // The quadrants of a superblock are coded in the order the decoder
3185 // walks them, which for a 64x64 split into 32x32 blocks is raster3354 // walks them, which for a 64x64 split into 32x32 blocks is raster
3186 // order among the quadrants that are inside the frame.3355 // order among the quadrants that are inside the frame.
@@ -3376,56 +3545,65 @@ pub(crate) fn encode_key_frame_inner(
3376 // defaults again (spec 7.20's `started_from` arm) -- the first inter3545 // defaults again (spec 7.20's `started_from` arm) -- the first inter
3377 // frame after it therefore starts from the defaults too.3546 // frame after it therefore starts from the defaults too.
3378 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);3547 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));3548+ let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3380- let start_cdfs = CdfSnapshot(cdfs.clone());3549+ let start_cdfs = CdfSnapshot(cdfs);
3381- let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(3550+ // The luma restoration-unit grid this frame's `lr_params` implies
3551+ // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3552+ // swallowed by the one before it), for the tile writer's own per-unit
3553+ // walk.
3554+ let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3555+ 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(
3382 mi_cols,3570 mi_cols,
3383 mi_rows,3571 mi_rows,
3384 base_q_idx,3572 base_q_idx,
3385 &superblocks,3573 &superblocks,
3386 tx_select,3574 tx_select,
3387 &mut cdfs,3575 &mut cdfs,
3576+ layout.rect(index),
3388 )?;3577 )?;
3578+ Ok((bytes, None))
3579+ })?;
3580+ Ok(out)
3581+ };
3582+ let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
3389 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing3583 // 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 (see3584 // the tile just coded back to the decoder under each candidate (see
3391 // `crate::filter_search`), and keep the filtered picture that wins as3585 // `crate::filter_search`), and keep the filtered picture that wins as
3392 // the reconstruction -- what a decoder outputs, and what the next3586 // the reconstruction -- what a decoder outputs, and what the next
3393 // frame predicts from.3587 // frame predicts from.
3394- // The luma restoration-unit grid this frame's `lr_params` implies
3395- // (`av1_lr_count_units` rounds to nearest, so a short last unit is
3396- // swallowed by the one before it), for the tile writer's own per-unit
3397- // walk.
3398- let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
3399- let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
3400 pick_and_apply_filters(3588 pick_and_apply_filters(
3401 &mut header,3589 &mut header,
3402 &mut luma,3590 &mut luma,
3403 &mut chroma,3591 &mut chroma,
3404 [&picture_y8, &picture_u8, &picture_v8],3592 [&picture_y8, &picture_u8, &picture_v8],
3405 true,3593 true,
3406- &mut tile,3594+ &mut tiles,
3407 search.lambda,3595 search.lambda,
3408 fctx,3596 fctx,
3409 // Every re-code starts from this frame's OWN starting tables, never3597 // Every re-code starts from this frame's OWN starting tables, never
3410 // from where the first write left them: the second tile is the same3598 // from where the first write left them: the second tile is the same
3411 // symbol sequence plus new ones, so it must adapt from the same3599 // symbol sequence plus new ones, so it must adapt from the same
3412 // point the decoder will.3600 // point the decoder will.
3413- |bits, sb_cols, grid, units| {3601+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
3414- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());3602+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
3415- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());3603+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
3416- let mut cdfs = start_cdfs.0.clone();3604+ crate::decode::decode_key_frame_tiles_lr(
3417- crate::tile::sb_coeff_key_frame_tile_cdfs(3605+ &payloads,
3418- mi_cols,3606+ &header_tile_info,
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,
3429 h.mi_cols,3607 h.mi_cols,
3430 h.mi_rows,3608 h.mi_rows,
3431 base_q_idx,3609 base_q_idx,
@@ -3443,6 +3621,9 @@ pub(crate) fn encode_key_frame_inner(
3443 )3621 )
3444 },3622 },
3445 )?;3623 )?;
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);
3446 let mut stream = temporal_delimiter();3627 let mut stream = temporal_delimiter();
3447 stream.extend_from_slice(&sequence_header_obu(&seq)?);3628 stream.extend_from_slice(&sequence_header_obu(&seq)?);
3448 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);3629 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3492,19 +3673,25 @@ fn pick_and_apply_filters(
3492 chroma: &mut [Plane<'_>; 2],3673 chroma: &mut [Plane<'_>; 2],
3493 source: [&[u8]; 3],3674 source: [&[u8]; 3],
3494 search: bool,3675 search: bool,
3495- // The coded tile, replaced in place when the search chooses a per-64x643676+ // The coded tiles, one payload per tile of the frame's grid, replaced in
3496- // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile3677+ // place when the search chooses a per-64x64 `cdef_idx` list
3497- // payload, so the tile is written a second time under `recode` and the3678+ // (`cdef_bits > 0`): those literals live in the tile payloads, so every
3498- // winner re-decoded from it.3679+ // tile is written a second time under `recode` and the winner
3499- tile: &mut Vec<u8>,3680+ // re-decoded from them.
3681+ tiles: &mut Vec<Vec<u8>>,
3500 lambda: f64,3682 lambda: f64,
3501 fctx: &crate::decode::FrameCtx,3683 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>>>,
3503 decode: impl Fn(3690 decode: impl Fn(
3504 &LoopFilterParams,3691 &LoopFilterParams,
3505 &CdefParams,3692 &CdefParams,
3506 &FrameHeader,3693 &FrameHeader,
3507- &[u8],3694+ &[Vec<u8>],
3508 &LoopRestorationParams,3695 &LoopRestorationParams,
3509 ) -> Result<Picture>,3696 ) -> Result<Picture>,
3510 ) -> Result<()> {3697 ) -> Result<()> {
@@ -3531,7 +3718,7 @@ fn pick_and_apply_filters(
3531 return Ok(picture);3718 return Ok(picture);
3532 }3719 }
3533 crate::decode::arm_filter_replay();3720 crate::decode::arm_filter_replay();
3534- decode(lf, cdef, &hdr, tile, &none_lr)3721+ decode(lf, cdef, &hdr, tiles, &none_lr)
3535 },3722 },
3536 source,3723 source,
3537 luma.width,3724 luma.width,
@@ -3562,14 +3749,14 @@ fn pick_and_apply_filters(
3562 fctx.capture_stages.set(lr_on);3749 fctx.capture_stages.set(lr_on);
3563 let mut filtered = if idx_grid.is_empty() {3750 let mut filtered = if idx_grid.is_empty() {
3564 if lr_on {3751 if lr_on {
3565- decode(&lf, &cdef, &hdr, tile, &none_lr)?3752+ decode(&lf, &cdef, &hdr, tiles, &none_lr)?
3566 } else {3753 } else {
3567 picture3754 picture
3568 }3755 }
3569 } else {3756 } else {
3570 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;3757 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
3571 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;3758 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
3572- *tile = coded;3759+ *tiles = coded;
3573 picture3760 picture
3574 };3761 };
3575 fctx.capture_stages.set(false);3762 fctx.capture_stages.set(false);
@@ -3600,7 +3787,7 @@ fn pick_and_apply_filters(
3600 if units.iter().any(Option::is_some) {3787 if units.iter().any(Option::is_some) {
3601 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;3788 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
3602 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;3789 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
3603- *tile = coded;3790+ *tiles = coded;
3604 lr = want;3791 lr = want;
3605 }3792 }
3606 }3793 }
@@ -4814,6 +5001,10 @@ pub(crate) fn encode_inter_frame(
4814 height: picture.height,5001 height: picture.height,
4815 true_width,5002 true_width,
4816 true_height,5003 true_height,
5004+ tile_x0: 0,
5005+ tile_y0: 0,
5006+ tile_x1: picture.width,
5007+ tile_y1: picture.height,
4817 };5008 };
4818 let mut chroma = [5009 let mut chroma = [
4819 Plane {5010 Plane {
@@ -4823,6 +5014,10 @@ pub(crate) fn encode_inter_frame(
4823 height: picture.height / 2,5014 height: picture.height / 2,
4824 true_width: true_width / 2,5015 true_width: true_width / 2,
4825 true_height: true_height / 2,5016 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,
4826 },5021 },
4827 Plane {5022 Plane {
4828 source: &picture_v8,5023 source: &picture_v8,
@@ -4831,6 +5026,10 @@ pub(crate) fn encode_inter_frame(
4831 height: picture.height / 2,5026 height: picture.height / 2,
4832 true_width: true_width / 2,5027 true_width: true_width / 2,
4833 true_height: true_height / 2,5028 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,
4834 },5033 },
4835 ];5034 ];
4836 5035
@@ -4853,6 +5052,12 @@ pub(crate) fn encode_inter_frame(
4853 let (cols, rows) = (cols as usize, rows as usize);5052 let (cols, rows) = (cols as usize, rows as usize);
4854 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));5053 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
4855 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);5054 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();
4856 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is5061 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
4857 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --5062 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
4858 // once per frame (lane-av1rd2), not once per block, which is a whole5063 // once per frame (lane-av1rd2), not once per block, which is a whole
@@ -4863,6 +5068,18 @@ pub(crate) fn encode_inter_frame(
4863 5068
4864 for sb_r in 0..sb_rows {5069 for sb_r in 0..sb_rows {
4865 for sb_c in 0..sb_cols {5070 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+ );
4866 for quadrant in 0..4 {5083 for quadrant in 0..4 {
4867 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);5084 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
4868 // Same filter as the tile writer's: a quadrant whose own mi5085 // Same filter as the tile writer's: a quadrant whose own mi
@@ -5289,21 +5506,58 @@ pub(crate) fn encode_inter_frame(
5289 // next frame's writer starts from them -- exactly what5506 // next frame's writer starts from them -- exactly what
5290 // `crate::stream::stored_cdfs_for` hands the decoder.5507 // `crate::stream::stored_cdfs_for` hands the decoder.
5291 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);5508 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
5292- let mut cdfs = start_cdfs5509+ let cdfs = start_cdfs
5293 .cloned()5510 .cloned()
5294 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));5511 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
5295- let start_cdfs = CdfSnapshot(cdfs.clone());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());
5296 crate::tile::arm_sign_bias(sign_bias);5532 crate::tile::arm_sign_bias(sign_bias);
5297- crate::tile::arm_reference_select(header.reference_select);5533+ // Thread-locals: every tile job arms its own worker.
5298- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);5534+ crate::tile::arm_reference_select(reference_select_bit);
5299- let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(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(
5300 mi_cols,5544 mi_cols,
5301 mi_rows,5545 mi_rows,
5302 base_q_idx,5546 base_q_idx,
5303 &blocks,5547 &blocks,
5304 tx_select,5548 tx_select,
5305 &mut cdfs,5549 &mut cdfs,
5550+ layout.rect(index),
5551+ &mut mv_grid,
5306 )?;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, &[], &[])?;
5307 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs5561 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
5308 // this tile against the same single-slot reference this encoder predicted5562 // this tile against the same single-slot reference this encoder predicted
5309 // from, under each candidate level.5563 // from, under each candidate level.
@@ -5312,7 +5566,6 @@ pub(crate) fn encode_inter_frame(
5312 // reference whose height is not the header's own `frame_height` (spec5566 // reference whose height is not the header's own `frame_height` (spec
5313 // 7.9's compatible-size rule), and the chained-decode round trips prove5567 // 7.9's compatible-size rule), and the chained-decode round trips prove
5314 // the two predict identically.5568 // the two predict identically.
5315- let end_cdfs = std::cell::RefCell::new(cdfs);
5316 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);5569 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
5317 let trial_ref = if (reference.width, reference.height) == (fw, fh) {5570 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
5318 reference.clone()5571 reference.clone()
@@ -5359,12 +5612,6 @@ pub(crate) fn encode_inter_frame(
5359 refs[4] = trial_golden.as_ref();5612 refs[4] = trial_golden.as_ref();
5360 refs[7] = trial_altref.as_ref();5613 refs[7] = trial_altref.as_ref();
5361 let refpix = crate::decode::RefPix::ready(refs);5614 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;
5368 pick_and_apply_filters(5615 pick_and_apply_filters(
5369 &mut header,5616 &mut header,
5370 &mut luma,5617 &mut luma,
@@ -5375,36 +5622,19 @@ pub(crate) fn encode_inter_frame(
5375 // `TxMode::Select` too (it used to skip and leave every inter frame5622 // `TxMode::Select` too (it used to skip and leave every inter frame
5376 // unfiltered once Select became the default).5623 // unfiltered once Select became the default).
5377 true,5624 true,
5378- &mut tile,5625+ &mut tiles,
5379 search.lambda,5626 search.lambda,
5380 fctx,5627 fctx,
5381 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables5628 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
5382 // are what the NEXT frame writes from, so the winning re-code5629 // are what the NEXT frame writes from, so the winning re-code
5383 // publishes its own into `end_cdfs` -- the first write's are stale5630 // publishes its own into `end_cdfs` -- the first write's are stale
5384 // the moment a second tile is coded.5631 // the moment a second tile is coded.
5385- |bits, sb_cols, grid, units| {5632+ |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
5386- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());5633+ |lf, cdef, h, tiles: &[Vec<u8>], lr| {
5387- crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());5634+ let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
5388- crate::tile::arm_sign_bias(sign_bias);5635+ crate::decode::decode_inter_frame_tiles_lr(
5389- crate::tile::arm_reference_select(reference_select());5636+ &payloads,
5390- crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);5637+ &header_tile_info,
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,
5408 h.mi_cols,5638 h.mi_cols,
5409 h.mi_rows,5639 h.mi_rows,
5410 base_q_idx,5640 base_q_idx,
@@ -5429,9 +5659,14 @@ pub(crate) fn encode_inter_frame(
5429 )5659 )
5430 },5660 },
5431 )?;5661 )?;
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());
5433 cdfs.reset_counts();5665 cdfs.reset_counts();
5434 let next_cdfs = CdfSnapshot(cdfs);5666 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);
5435 let mut stream = temporal_delimiter();5670 let mut stream = temporal_delimiter();
5436 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);5671 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
5437 5672
@@ -8328,6 +8563,8 @@ mod tests {
8328 base_q_idx: q,8563 base_q_idx: q,
8329 gop: source.len(),8564 gop: source.len(),
8330 colour: Colour::Unspecified,8565 colour: Colour::Unspecified,
8566+ tile_cols_log2: 0,
8567+ tile_rows_log2: 0,
8331 };8568 };
8332 let start = std::time::Instant::now();8569 let start = std::time::Instant::now();
8333 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();8570 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.
@@ -1202,6 +1346,14 @@ impl Quadrant {
1202 /// What the blocks above and to the left of the one being coded left behind,1346 /// What the blocks above and to the left of the one being coded left behind,
1203 /// kept on the 16x16 grid the smallest block sits on.1347 /// kept on the 16x16 grid the smallest block sits on.
1204 struct Neighbours {1348 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,
1205 /// Per plane, whether the neighbour coded anything and the sign of its DC.1357 /// Per plane, whether the neighbour coded anything and the sign of its DC.
1206 above: Vec<[Neighbour; 3]>,1358 above: Vec<[Neighbour; 3]>,
1207 /// The same, down the left edge.1359 /// The same, down the left edge.
@@ -1311,6 +1463,8 @@ impl Neighbours {
1311 /// mode-info units.1463 /// mode-info units.
1312 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {1464 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
1313 Self {1465 Self {
1466+ tile_row0_mi: 0,
1467+ tile_col0_mi: 0,
1314 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],1468 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1315 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],1469 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1316 above_mode: vec![DC_PRED; cols],1470 above_mode: vec![DC_PRED; cols],
@@ -1341,6 +1495,23 @@ impl Neighbours {
1341 }1495 }
1342 1496
1343 /// Clears the left edge, which a tile starts every superblock row with.1497 /// 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+
1344 fn start_row(&mut self) {1515 fn start_row(&mut self) {
1345 self.left.iter_mut().for_each(|l| *l = Default::default());1516 self.left.iter_mut().for_each(|l| *l = Default::default());
1346 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);1517 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
@@ -1385,7 +1556,7 @@ impl Neighbours {
1385 /// off a CDF row one higher than the decoder's, which is the first1556 /// off a CDF row one higher than the decoder's, which is the first
1386 /// divergence of the inter `TxMode::Select` stream.1557 /// divergence of the inter `TxMode::Select` stream.
1387 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {1558 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));
1389 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;1560 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
1390 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;1561 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
1391 if has_above && self.above_inter[mi_c] {1562 if has_above && self.above_inter[mi_c] {
@@ -1402,8 +1573,8 @@ impl Neighbours {
1402 /// largest transform, plus whether the one to the left is at least as1573 /// largest transform, plus whether the one to the left is at least as
1403 /// tall. A neighbour outside the tile contributes nothing.1574 /// tall. A neighbour outside the tile contributes nothing.
1404 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {1575 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)1576+ usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
1406- + usize::from(mi_c > 0 && usize::from(self.left_tx[mi_r]) >= max_tx)1577+ + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
1407 }1578 }
1408 1579
1409 /// Publishes one block's resolved transform side over every 4x4 unit it1580 /// Publishes one block's resolved transform side over every 4x4 unit it
@@ -1722,7 +1893,15 @@ pub fn sb_coeff_key_frame_tile_tx(
1722 tx_select: bool,1893 tx_select: bool,
1723 ) -> Result<Vec<u8>> {1894 ) -> Result<Vec<u8>> {
1724 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));1895 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+ )
1726 }1905 }
1727 1906
1728 /// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the1907 /// [`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(
1740 superblocks: &[Superblock],1919 superblocks: &[Superblock],
1741 tx_select: bool,1920 tx_select: bool,
1742 cdfs: &mut Cdfs,1921 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,
1743 ) -> Result<Vec<u8>> {1927 ) -> Result<Vec<u8>> {
1744 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.1928 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
1745 let _cdef_idx = CdefIdxGuard;1929 let _cdef_idx = CdefIdxGuard;
@@ -1797,15 +1981,16 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1797 mi_cols as usize,1981 mi_cols as usize,
1798 mi_rows as usize,1982 mi_rows as usize,
1799 );1983 );
1984+ neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
1800 1985
1801 // The tile adapts every non-literal CDF it writes, exactly as the decoder1986 // The tile adapts every non-literal CDF it writes, exactly as the decoder
1802 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`1987 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
1803 // off.1988 // off.
1804 let mut cdfs = cdfs;1989 let mut cdfs = cdfs;
1805 let mut enc = SymbolEncoder::new();1990 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) {
1807 neighbours.start_row();1992 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) {
1809 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);1994 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
1810 let at = (sb_r as usize * 4, sb_c as usize * 4);1995 let at = (sb_r as usize * 4, sb_c as usize * 4);
1811 let ctx = neighbours.partition_ctx(at, SB);1996 let ctx = neighbours.partition_ctx(at, SB);
@@ -3666,7 +3851,16 @@ pub fn sb_coeff_inter_frame_tile_tx(
3666 tx_select: bool,3851 tx_select: bool,
3667 ) -> Result<Vec<u8>> {3852 ) -> Result<Vec<u8>> {
3668 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));3853 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+ )
3670 }3864 }
3671 3865
3672 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --3866 /// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
@@ -3681,6 +3875,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3681 blocks: &[Quadrant],3875 blocks: &[Quadrant],
3682 tx_select: bool,3876 tx_select: bool,
3683 cdfs: &mut Cdfs,3877 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,
3684 ) -> Result<Vec<u8>> {3883 ) -> Result<Vec<u8>> {
3685 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.3884 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3686 let _cdef_idx = CdefIdxGuard;3885 let _cdef_idx = CdefIdxGuard;
@@ -3721,7 +3920,21 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3721 mi_cols as usize,3920 mi_cols as usize,
3722 mi_rows as usize,3921 mi_rows as usize,
3723 );3922 );
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+ );
3725 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));3938 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
3726 let mut cdfs = cdfs;3939 let mut cdfs = cdfs;
3727 let mut enc = SymbolEncoder::new();3940 let mut enc = SymbolEncoder::new();
@@ -3749,9 +3962,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3749 vec![0i32; TX16 * TX16],3962 vec![0i32; TX16 * TX16],
3750 ];3963 ];
3751 3964
3752- for sb_r in 0..sb_rows {3965+ for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
3753 neighbours.start_row();3966 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) {
3755 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);3968 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
3756 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);3969 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
3757 let sb_ctx = neighbours.partition_ctx(sb_at, SB);3970 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
@@ -3994,9 +4207,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3994 };4207 };
3995 4208
3996 let (r, c) = at;4209 let (r, c) = at;
3997- let has_above = r32 > 0;
3998- let has_left = c32 > 0;
3999 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));4210 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);
4000 let skip_ctx = usize::from(neighbours.above_skip[mi_c])4213 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
4001 + usize::from(neighbours.left_skip[mi_r]);4214 + usize::from(neighbours.left_skip[mi_r]);
4002 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4215 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
@@ -4233,7 +4446,7 @@ fn write_inter_frame_leaf(
4233 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4446 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
4234 write_cdef_idx(enc, (mi_r, mi_c), block.skip);4447 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
4235 4448
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));
4237 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);4450 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
4238 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);4451 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
4239 let is_inter = block.inter.is_some();4452 let is_inter = block.inter.is_some();
@@ -4454,7 +4667,7 @@ fn write_inter_frame_leaf8(
4454 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);4667 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
4455 write_cdef_idx(enc, leaf_mi, block.skip);4668 write_cdef_idx(enc, leaf_mi, block.skip);
4456 4669
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));
4458 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);4671 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
4459 let is_inter = block.inter.is_some();4672 let is_inter = block.inter.is_some();
4460 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);4673 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