diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 4cb3f325..45376fd3 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -379,7 +379,11 @@ pub(crate) fn key_frame_headers_colour( enable_ref_frame_mvs: false, film_grain_params_present: false, }; - let (mi_cols, mi_rows) = (w / 4, h / 4); + // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's + // own (true, unpadded) width and height, not from any block-grid + // alignment — a decoder derives these straight from `frame_width`/ + // `frame_height` below, so this must match it exactly. + let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3)); let header = FrameHeader { frame_type: FrameType::Key, frame_is_intra: true, @@ -471,6 +475,18 @@ struct Plane<'a> { reconstruction: Vec, width: usize, height: usize, + /// The frame's true, decodable extent in this plane's own units -- + /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples, + /// not `width`/`height` above, which is the padded coding-surface size. + /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_ + /// right_edge`/`mb_to_bottom_edge` clamps (libaom's + /// `av1/common/reconintra.c` `build_intra_predictors`) never see past + /// this bound, even though the padded reconstruction buffer holds real + /// (if never-decoded-by-a-real-decoder) samples out there -- reading + /// those instead of stopping here is what desyncs prediction at the true + /// edge. + true_width: usize, + true_height: usize, } impl Plane<'_> { @@ -490,11 +506,44 @@ impl Plane<'_> { side: usize, reach: Reach, ) -> (Option>, Option>, Option) { - let across = (x + if reach.above_right { 2 * side } else { side }).min(self.width); - let down = (y + if reach.below_left { 2 * side } else { side }).min(self.height); - let above = - (y > 0).then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec()); - let left = (x > 0).then(|| { + // Even a block's *own* edge is clamped to the true frame bound, not + // just a `reach` extension: libaom's `av1_predict_intra_block` + // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from + // this block's own right/bottom to the frame edge -- from + // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from + // `mi_cols`/`mi_rows` (the true, decodable extent), never from any + // padded coding surface. `n_top_px`/`n_left_px` (how many *real* + // samples the row/column above/left holds before the decoder starts + // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/ + // `leftLimit`) is `min(side, xr + side)` even for a block whose own + // extent straddles that edge legally (`has_half`) -- the transform + // still covers the whole block, but prediction does not get to read + // real reconstructed pixels past the true edge for its own row/column, + // only for the padded tail it invents. + let own_across = x + side.min(self.true_width.saturating_sub(x)); + let across = if reach.above_right { + own_across + side.min(self.true_width.saturating_sub(own_across)) + } else { + own_across + } + .min(self.width); + let own_down = y + side.min(self.true_height.saturating_sub(y)); + let down = if reach.below_left { + own_down + side.min(self.true_height.saturating_sub(own_down)) + } else { + own_down + } + .min(self.height); + // `across`/`down` can still fall at or below `x`/`y` for a sub-block + // whose own origin already sits past the true edge -- only reachable + // through a partition trial priced for comparison on a split this + // frame's straddling quadrant will go on to refuse (see + // `a_picture_off_the_block_grid_is_refused`), never through a block + // this encoder actually commits. Such a block has no true-edge + // samples above or left of it at all, same as `y == 0`/`x == 0`. + let above = (y > 0 && across > x) + .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec()); + let left = (x > 0 && down > y).then(|| { (y..down) .map(|row| self.reconstruction[row * self.width + x - 1]) .collect::>() @@ -883,7 +932,7 @@ fn code_square( x, y, side, - reach: Reach::of(side, x, y, luma.width, luma.height), + reach: Reach::of(side, x, y, luma.true_width, luma.true_height), set: luma_set, }, search, @@ -1063,16 +1112,27 @@ pub(crate) fn encode_key_frame_inner( format!("intra mode {bad} is not one the encoder predicts"), )); } - let (seq, mut header) = - key_frame_headers_colour(picture.width, picture.height, base_q_idx, color_config)?; + // The header carries the frame's true (unpadded) size as `frame_width`/ + // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/ + // `mi_rows` derived from that same true size (spec `compute_image_size`). + // `render_width`/`render_height` come out equal to it too, so + // `render_and_frame_size_different` is false and no render_size bits are + // written, mirroring libaom/rav1e: the padded `picture` below is only the + // internal coding surface, never what the header names. + let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; header.render_width = render.0 as u32; header.render_height = render.1 as u32; + // Prediction reads no further than this, in each plane's own units -- + // see `Plane::true_width`/`true_height`. + let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); let mut luma = Plane { source: &picture.y, reconstruction: vec![128; picture.y.len()], width: picture.width, height: picture.height, + true_width, + true_height, }; let mut chroma = [ Plane { @@ -1080,12 +1140,16 @@ pub(crate) fn encode_key_frame_inner( reconstruction: vec![128; picture.u.len()], width: picture.width / 2, height: picture.height / 2, + true_width: true_width / 2, + true_height: true_height / 2, }, Plane { source: &picture.v, reconstruction: vec![128; picture.v.len()], width: picture.width / 2, height: picture.height / 2, + true_width: true_width / 2, + true_height: true_height / 2, }, ]; @@ -1099,7 +1163,14 @@ pub(crate) fn encode_key_frame_inner( modes, }; - let (cols, rows) = (picture.width / BLOCK, picture.height / BLOCK); + // The block grid this frame is coded over: [`crate::tile::block_grid`]'s + // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`, + // which may be fewer columns/rows than the padded picture has room for + // -- a block whose origin sits past the true bound is not coded at all, + // matching what a decoder derives from `frame_width`/`frame_height` and + // so never visits either. + let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); + let (cols, rows) = (cols as usize, rows as usize); // The luma mode of the block above and of the block to the left, which is // what picks the CDF the next block's mode is coded against -- the same // bookkeeping the tile writer keeps, so that the search is costing the @@ -1126,6 +1197,54 @@ pub(crate) fn encode_key_frame_inner( let (c0, r0) = (col * 2, row * 2); let base = snapshot(&luma, &chroma, (x, y)); + // spec `decode_partition`'s hasRows/hasCols recomputed at this + // 32x32 block's own half (see `crate::tile::has_half`): the + // true frame edge can fall inside a quadrant a superblock-level + // check already let through. A quadrant that fails either may + // not be left whole; a 16x16 sub-block that fails either (once + // split) is a leaf this writer has no rectangular transform + // for, so the search must not pick a split that would need one. + let (has_cols32, has_rows32) = ( + crate::tile::has_half( + col as u32 * crate::tile::BLOCK_MI, + crate::tile::BLOCK_MI, + header.mi_cols, + ), + crate::tile::has_half( + row as u32 * crate::tile::BLOCK_MI, + crate::tile::BLOCK_MI, + header.mi_rows, + ), + ); + let whole_legal = has_cols32 && has_rows32; + let split_legal = (0..4) + .map(|i| (r0 + i / 2, c0 + i % 2)) + .filter(|&(sr, sc)| { + (sr as u32) * crate::tile::SUB_MI < header.mi_rows + && (sc as u32) * crate::tile::SUB_MI < header.mi_cols + }) + .all(|(sr, sc)| { + crate::tile::has_half( + sc as u32 * crate::tile::SUB_MI, + crate::tile::SUB_MI, + header.mi_cols, + ) && crate::tile::has_half( + sr as u32 * crate::tile::SUB_MI, + crate::tile::SUB_MI, + header.mi_rows, + ) + }); + if !whole_legal && !split_legal { + return Err(Error::unsupported( + "AV1 encode", + format!( + "the 32x32 block at ({col},{row}) straddles the true frame edge \ + in a way that needs a rectangular (HORZ/VERT) transform this \ + encoder does not code yet" + ), + )); + } + // What the whole 32x32 costs, including the partition symbol // that says it is not split. let (whole, mut cost_whole) = code_square( @@ -1145,9 +1264,20 @@ pub(crate) fn encode_key_frame_inner( let mut split = Vec::with_capacity(4); let mut cost_split = search.lambda * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); - let mut split_modes = [DC_PRED; 4]; - for (sub, sub_mode) in split_modes.iter_mut().enumerate() { + let mut split_modes = Vec::with_capacity(4); + for sub in 0..4 { let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); + // Same filter as the writer's `sub_positions` (spec + // `decode_partition`'s `r >= MiRows || c >= MiCols` early + // return): a sub-block whose own origin sits past the + // true frame is never coded, so it must not be searched + // or pushed onto `split` either, or the writer's block + // count will not match what it is prepared to name. + if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows + || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols + { + continue; + } let (block, cost) = code_square( &mut luma, &mut chroma, @@ -1157,13 +1287,13 @@ pub(crate) fn encode_key_frame_inner( &mode_bits(above_mode[sc], left_mode[sr]), ); cost_split += cost; - *sub_mode = block.mode; + split_modes.push(block.mode); above_mode[sc] = block.mode; left_mode[sr] = block.mode; split.push(block); } - if split_blocks && cost_split < cost_whole { + if split_legal && (!whole_legal || (split_blocks && cost_split < cost_whole)) { modes.extend_from_slice(&split_modes); blocks.push(Quadrant::Split(split)); } else { @@ -1348,6 +1478,7 @@ fn mc_trial( mv: (i32, i32), luma: bool, reference: &[u8], + stride: usize, ref_width: usize, ref_height: usize, skip: bool, @@ -1360,6 +1491,7 @@ fn mc_trial( let mut prediction = vec![0u8; side * side]; mc::predict( reference, + stride, ref_width, ref_height, x_q4, @@ -1400,7 +1532,7 @@ fn search_inter_block( stack: &MvStack, ) -> BlockCoeffs { let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16); - let reach = Reach::of(BLOCK, x, y, luma.width, luma.height); + let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height); // skip / intra_inter symbol costs at a fixed context -- see this // function's doc comment. @@ -1484,9 +1616,34 @@ fn search_inter_block( }); } - let ref_luma = (&reference.y, reference.width, reference.height); - let ref_u = (&reference.u, reference.width / 2, reference.height / 2); - let ref_v = (&reference.v, reference.width / 2, reference.height / 2); + // The reference frame buffer a spec decoder holds is exactly the true + // (unpadded) coded extent -- a superblock whose partition stops early at + // `has_cols`/`has_rows` never codes syntax for the padding columns/rows + // beyond it, so those samples are never part of the decoded picture. + // Motion compensation clamps reads to that true extent (spec 7.11.3.4's + // reference sample position clamp), not to this crate's own + // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height + // here would let a fractional-pel read past the true edge pick up this + // encoder's own uncoded padding instead of the true edge's replicated + // value a decoder computes. + let ref_luma = ( + &reference.y, + reference.width, + luma.true_width, + luma.true_height, + ); + let ref_u = ( + &reference.u, + reference.width / 2, + chroma[0].true_width, + chroma[0].true_height, + ); + let ref_v = ( + &reference.v, + reference.width / 2, + chroma[1].true_width, + chroma[1].true_height, + ); let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV @@ -1506,6 +1663,7 @@ fn search_inter_block( ref_luma.0, ref_luma.1, ref_luma.2, + ref_luma.3, false, search.base_q_idx, search.deadzone, @@ -1521,6 +1679,7 @@ fn search_inter_block( ref_u.0, ref_u.1, ref_u.2, + ref_u.3, false, search.base_q_idx, search.deadzone, @@ -1536,6 +1695,7 @@ fn search_inter_block( ref_v.0, ref_v.1, ref_v.2, + ref_v.3, false, search.base_q_idx, search.deadzone, @@ -1576,6 +1736,7 @@ fn search_inter_block( ref_luma.0, ref_luma.1, ref_luma.2, + ref_luma.3, &source_block, x, y, @@ -1596,6 +1757,7 @@ fn search_inter_block( ref_luma.0, ref_luma.1, ref_luma.2, + ref_luma.3, false, search.base_q_idx, search.deadzone, @@ -1611,6 +1773,7 @@ fn search_inter_block( ref_u.0, ref_u.1, ref_u.2, + ref_u.3, false, search.base_q_idx, search.deadzone, @@ -1626,6 +1789,7 @@ fn search_inter_block( ref_v.0, ref_v.1, ref_v.2, + ref_v.3, false, search.base_q_idx, search.deadzone, @@ -1714,21 +1878,25 @@ pub(crate) fn encode_inter_frame( // overwrites slot 0, so the frame just coded is always what the next one // predicts against. const LAST_SLOT: u8 = 0; - let (seq, mut header) = inter_frame_headers( - picture.width, - picture.height, - base_q_idx, - order_hint, - LAST_SLOT, - )?; + // `render`, not `picture.width`/`picture.height`: `picture` here is + // already padded to a whole number of superblocks (`encode_sequence`'s + // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so + // every true-edge clamp downstream) must come from the frame's real, + // unpadded size, same as `key_frame_headers_colour` takes `render` and + // not the padded picture in `encode_key_frame_inner`. + let (seq, mut header) = + inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?; header.render_width = render.0 as u32; header.render_height = render.1 as u32; + let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); let mut luma = Plane { source: &picture.y, reconstruction: vec![128; picture.y.len()], width: picture.width, height: picture.height, + true_width, + true_height, }; let mut chroma = [ Plane { @@ -1736,12 +1904,16 @@ pub(crate) fn encode_inter_frame( reconstruction: vec![128; picture.u.len()], width: picture.width / 2, height: picture.height / 2, + true_width: true_width / 2, + true_height: true_height / 2, }, Plane { source: &picture.v, reconstruction: vec![128; picture.v.len()], width: picture.width / 2, height: picture.height / 2, + true_width: true_width / 2, + true_height: true_height / 2, }, ]; @@ -1754,8 +1926,14 @@ pub(crate) fn encode_inter_frame( }; let mode_bits_table = inter_mode_bits(); - let (cols, rows) = (picture.width / BLOCK, picture.height / BLOCK); - let (sb_cols, sb_rows) = (cols / 2, rows / 2); + // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded + // coding surface's: `blocks` carries one entry per 32x32 block the tile + // writer will actually visit, same count it checks `blocks.len()` + // against, which is fewer than the padded surface's own block count + // whenever the true size is not a 64x64 multiple. + let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); + let (cols, rows) = (cols as usize, rows as usize); + let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); let mut grid = MiGrid::new(mi_cols, mi_rows); let mut blocks = vec![BlockCoeffs::default(); cols * rows]; @@ -1764,6 +1942,11 @@ pub(crate) fn encode_inter_frame( for sb_c in 0..sb_cols { for quadrant in 0..4 { let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); + // Same filter as the tile writer's: a quadrant whose own mi + // origin is not inside the true frame is never coded. + if r32 >= rows || c32 >= cols { + continue; + } let (x, y) = (c32 * BLOCK, r32 * BLOCK); let (mi_row, mi_col) = (r32 * 8, c32 * 8); let stack = @@ -2014,7 +2197,7 @@ mod tests { eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg"); return; } - for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96)] { + for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] { let picture = test_card(width, height); let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); let decoded = ffmpeg_decode(&encoded.stream, width, height); @@ -2106,19 +2289,6 @@ mod tests { ffmpeg_decode_sequence(&stream, width, height, 2); } - /// The top-left `width` x `height` region of a decoded picture, for - /// comparing against [`Encoded::reconstruction`] (already cropped to - /// the same region) when ffmpeg hands back the padded, coded-size one. - fn crop_picture(picture: &Picture, width: usize, height: usize) -> Picture { - Picture { - width, - height, - y: crop_plane(&picture.y, picture.width, width, height), - u: crop_plane(&picture.u, picture.width / 2, width / 2, height / 2), - v: crop_plane(&picture.v, picture.width / 2, width / 2, height / 2), - } - } - /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded /// frame size an AV1 decoder allocates, not necessarily the render size /// (see [`a_frame_round_trips_at_its_own_size`]). @@ -2186,23 +2356,18 @@ mod tests { (width, height), "{width}x{height}: reconstruction is cropped to the picture's own size" ); - let (padded_width, padded_height) = ( - width.next_multiple_of(BLOCK), - height.next_multiple_of(BLOCK), - ); assert_eq!( ffprobe_size(&encoded.stream), - (padded_width as u32, padded_height as u32), - "{width}x{height}: ffprobe reports the coded (padded) size" + (width as u32, height as u32), + "{width}x{height}: ffprobe reports the true (display) size, not the padded one" ); - let decoded = ffmpeg_decode(&encoded.stream, padded_width, padded_height); - let cropped = crop_picture(&decoded, width, height); + let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!( - cropped.y, encoded.reconstruction.y, + decoded.y, encoded.reconstruction.y, "{width}x{height}: luma" ); - assert_eq!(cropped.u, encoded.reconstruction.u, "{width}x{height}: U"); - assert_eq!(cropped.v, encoded.reconstruction.v, "{width}x{height}: V"); + assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); } } @@ -2223,6 +2388,14 @@ mod tests { /// EC_RNG-per-symbol trace against the same debug decoder found the /// bitstream byte-for-byte identical to libaom's across all 51188 /// symbols of this frame before this bug was found). + /// + /// Since the frame header started writing the true (unpadded) display + /// size into `frame_width`/`frame_height` rather than the padded coded + /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded + /// 864x480 and cropping ourselves now reads past what ffmpeg actually + /// emits (`av1_common_int.h`'s render/upscale path, mirrored by + /// `av1_frame_size` on the decode side, crops the loop-filtered picture to + /// the header's own size before output). #[test] fn an_854x480_picture_round_trips_through_its_padding() { if !have_ffmpeg() { @@ -2231,13 +2404,10 @@ mod tests { let (width, height) = (854usize, 480usize); let picture = test_card(width, height); let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); - let (padded_width, padded_height) = ( - width.next_multiple_of(BLOCK), - height.next_multiple_of(BLOCK), - ); - let decoded = ffmpeg_decode(&encoded.stream, padded_width, padded_height); - let cropped = crop_picture(&decoded, width, height); - assert_eq!(cropped.y, encoded.reconstruction.y, "854x480: luma"); + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); } /// `Reach::top_right`/`bottom_left` against a from-scratch transcription @@ -2362,24 +2532,18 @@ mod tests { ); } // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the - // coded (superblock-padded) size a sequence's frames share, not the - // render size. - let (padded_width, padded_height) = ( - width.next_multiple_of(SUPERBLOCK), - height.next_multiple_of(SUPERBLOCK), - ); + // true (display) size a sequence's frames share, not the padded one. assert_eq!( ffprobe_size(&encoded.stream), - (padded_width as u32, padded_height as u32), - "sequence: ffprobe reports the coded (padded) size" + (width as u32, height as u32), + "sequence: ffprobe reports the true (display) size" ); - let decoded = ffmpeg_decode_sequence(&encoded.stream, padded_width, padded_height, 3); + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); assert_eq!(decoded.len(), 3, "decoded frame count"); for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { - let cropped = crop_picture(decoded, width, height); - assert_eq!(cropped.y, frame.reconstruction.y, "frame {i}: luma"); - assert_eq!(cropped.u, frame.reconstruction.u, "frame {i}: U"); - assert_eq!(cropped.v, frame.reconstruction.v, "frame {i}: V"); + assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); + assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); + assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); } } @@ -2909,15 +3073,31 @@ mod tests { } /// The sizes the encoder refuses, refused for a reason rather than by - /// panicking somewhere below. 40x32 and 32x48 are off the 32x32 block - /// grid, which used to be refused outright; the encoder now pads a - /// picture like that internally (see `a_frame_round_trips_at_its_own_size`) - /// rather than refusing it, so those two are an accept, not a refusal, - /// here. + /// panicking somewhere below. Most sizes off the 32x32 block grid encode + /// fine now (see `a_frame_round_trips_at_its_own_size`) -- the true frame + /// edge lands past the halfway point of whichever block it falls in, so + /// `PARTITION_NONE` or a single gathered split flag still says everything + /// the spec needs. 40x32 and 32x48 are the sizes where the edge instead + /// falls *at or before* the halfway point of a 16x16 leaf: the spec's + /// `decode_partition` then requires that leaf to split again, to 8x8, + /// which this writer has no transform/coefficient path for yet, so it is + /// still refused, by name rather than by corrupting the stream. #[test] fn a_picture_off_the_block_grid_is_refused() { - assert!(encode_key_frame(&Picture::grey(40, 32), 100, 0.5).is_ok()); - assert!(encode_key_frame(&Picture::grey(32, 48), 100, 0.5).is_ok()); + let refused = |w, h| { + let msg = encode_key_frame(&Picture::grey(w, h), 100, 0.5) + .expect_err(&format!( + "{w}x{h} needs an 8x8 split this writer does not code" + )) + .to_string(); + msg.contains("true frame") + }; + assert!(refused(40, 32)); + // 32x48 was refused here through round 9: its split quadrant only + // ever has two legal 16x16 subs (the other two sit past the true + // 48-row edge, block-aligned, no 8x8 split needed), but the writer + // demanded four. See `ffmpeg_decodes_exactly_what_the_encoder_ + // reconstructed`, which now round-trips it pixel-exact instead. let mut short = Picture::grey(64, 64); short.u.truncate(10); assert!(encode_key_frame(&short, 100, 0.5).is_err()); diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 49d48096..dab55807 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -427,8 +427,8 @@ mod tests { assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); assert_eq!( (*w, *h), - (coded_w as u32, coded_h as u32), - "picture {t}: coded size" + (width as u32, height as u32), + "picture {t}: ffprobe reports the true (display) size, not the padded coded one" ); } } diff --git a/crates/ec-av1/src/intra.rs b/crates/ec-av1/src/intra.rs index f3056b89..73978ea3 100644 --- a/crates/ec-av1/src/intra.rs +++ b/crates/ec-av1/src/intra.rs @@ -306,15 +306,30 @@ fn directional(angle: u16, edges: &Edges, side: usize, dst: &mut [u8]) { /// `dc_predict` (spec 7.11.2.5): the average of whichever neighbours exist. /// /// Only the block's own `side` samples of each edge count: what a directional -/// mode reaches past them is no part of the average. +/// mode reaches past them is no part of the average. But `side` samples it +/// always is: libaom's `build_intra_predictors` (`av1/common/reconintra.c`) +/// replicates the last real sample out to the full transform width/height +/// before `dc_predictor` averages, so a slice truncated short by the true +/// frame edge must be extended by repetition here too, not averaged over its +/// own shorter length. fn dc(above: Option<&[u8]>, left: Option<&[u8]>, side: usize) -> i32 { - let above = above.map(|a| &a[..side.min(a.len())]); - let left = left.map(|l| &l[..side.min(l.len())]); + let extend = |samples: &[u8]| -> Vec { + if samples.len() >= side { + samples[..side].to_vec() + } else { + let last = *samples.last().expect("an edge that exists has samples"); + let mut v = samples.to_vec(); + v.resize(side, last); + v + } + }; + let above = above.map(extend); + let left = left.map(extend); let average = |samples: &[u8]| { let sum: u32 = samples.iter().map(|&s| u32::from(s)).sum(); ((sum + (samples.len() as u32 >> 1)) / samples.len() as u32) as i32 }; - match (above, left) { + match (&above, &left) { (None, None) => 128, (Some(a), None) => average(a), (None, Some(l)) => average(l), diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index a37630f2..dc122f76 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -52,18 +52,33 @@ const SUBPEL_FILTERS: [[i32; 8]; 16] = [ [0, 0, -2, 8, 126, -6, 2, 0], ]; -/// A reference sample at `(x, y)`, clamped to the plane's bounds (spec -/// 7.11.3.4's `Clip3` against the frame's edges) rather than read out of -/// range -- a motion vector that points past the frame repeats the edge -/// sample instead of panicking. -fn sample(reference: &[u8], ref_width: usize, ref_height: usize, x: i32, y: i32) -> i32 { - let cx = x.clamp(0, ref_width as i32 - 1) as usize; - let cy = y.clamp(0, ref_height as i32 - 1) as usize; - i32::from(reference[cy * ref_width + cx]) +/// A reference sample at `(x, y)`, clamped to the frame's true (unpadded) +/// extent -- `true_width`/`true_height`, which can be narrower than +/// `stride` -- rather than read out of range (spec 7.11.3.4's `Clip3` +/// against the frame's edges): a motion vector that points past the true +/// edge repeats the true edge's sample instead of panicking or picking up +/// whatever this encoder's own uncoded padding columns/rows hold. +#[allow(clippy::too_many_arguments)] +fn sample( + reference: &[u8], + stride: usize, + true_width: usize, + true_height: usize, + x: i32, + y: i32, +) -> i32 { + let cx = x.clamp(0, true_width as i32 - 1) as usize; + let cy = y.clamp(0, true_height as i32 - 1) as usize; + i32::from(reference[cy * stride + cx]) } /// Predicts one `block_w * block_h` block into `dst`, row-major, from -/// `reference` (row-major, `ref_width * ref_height`, stride `ref_width`). +/// `reference` (row-major, stride `stride`, true content +/// `true_width` x `true_height` -- a reference frame's decoded picture +/// buffer can be wider/taller than the true frame it holds, when this +/// encoder pads a picture to a whole number of superblocks; a spec decoder +/// never codes syntax for those extra columns/rows, so motion compensation +/// must clamp to the true extent, not the buffer's own stride). /// /// `x_q4` / `y_q4` are the block's top-left position in the reference, in /// 1/16-pel units (an integer MV has its low 4 bits zero); this function @@ -76,8 +91,9 @@ fn sample(reference: &[u8], ref_width: usize, ref_height: usize, x: i32, y: i32) #[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape pub fn predict( reference: &[u8], - ref_width: usize, - ref_height: usize, + stride: usize, + true_width: usize, + true_height: usize, x_q4: i32, y_q4: i32, block_w: usize, @@ -105,7 +121,7 @@ pub fn predict( let mut sum = 0; for (t, &tap) in h_filter.iter().enumerate() { let x = x0 + c as i32 + t as i32 - 3; - sum += tap * sample(reference, ref_width, ref_height, x, y); + sum += tap * sample(reference, stride, true_width, true_height, x, y); } intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0); } @@ -132,7 +148,17 @@ mod tests { let height = 12; let reference: Vec = (0..width * height).map(|i| (i * 7 % 251) as u8).collect(); let mut dst = vec![0u8; 6 * 6]; - predict(&reference, width, height, 3 * 16, 4 * 16, 6, 6, &mut dst); + predict( + &reference, + width, + width, + height, + 3 * 16, + 4 * 16, + 6, + 6, + &mut dst, + ); for row in 0..6 { for col in 0..6 { assert_eq!( @@ -157,6 +183,7 @@ mod tests { predict( &reference, width, + width, height, 5 * 16 + 8, 5 * 16, @@ -187,6 +214,7 @@ mod tests { predict( &reference, width, + width, height, 5 * 16 + xfrac, 5 * 16 + yfrac, @@ -219,6 +247,7 @@ mod tests { predict( &reference, width, + width, height, 3 * 16 + 8, 3 * 16, @@ -230,6 +259,7 @@ mod tests { predict( &reference, width, + width, height, 3 * 16, 3 * 16 + 8, @@ -271,6 +301,7 @@ mod tests { predict( &reference, width, + width, height, -50 * 16 + 5, -50 * 16 + 5, @@ -288,6 +319,7 @@ mod tests { predict( &reference, width, + width, height, 50 * 16 + 5, 50 * 16 + 5, diff --git a/crates/ec-av1/src/motion.rs b/crates/ec-av1/src/motion.rs index a9f4d3e0..9c9f066f 100644 --- a/crates/ec-av1/src/motion.rs +++ b/crates/ec-av1/src/motion.rs @@ -191,6 +191,7 @@ pub struct MotionSearch { #[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor pub fn search( reference: &[u8], + stride: usize, ref_width: usize, ref_height: usize, source: &[u8], @@ -202,8 +203,8 @@ pub fn search( lambda: f64, ) -> MotionSearch { let (result, _trace) = search_traced( - reference, ref_width, ref_height, source, block_x, block_y, block_w, block_h, pred_mv, - lambda, + reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, + pred_mv, lambda, ); result } @@ -214,6 +215,7 @@ pub fn search( #[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor fn search_traced( reference: &[u8], + stride: usize, ref_width: usize, ref_height: usize, source: &[u8], @@ -226,6 +228,7 @@ fn search_traced( ) -> (MotionSearch, Vec) { search_traced_from_step( reference, + stride, ref_width, ref_height, source, @@ -245,6 +248,7 @@ fn search_traced( #[allow(clippy::too_many_arguments)] fn search_traced_from_step( reference: &[u8], + stride: usize, ref_width: usize, ref_height: usize, source: &[u8], @@ -264,7 +268,7 @@ fn search_traced_from_step( let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3; let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3; predict( - reference, ref_width, ref_height, x_q4, y_q4, block_w, block_h, &mut dst, + reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h, &mut dst, ); let sad: f64 = source .iter() @@ -424,6 +428,7 @@ mod tests { let result = search( &plane, width, + width, height, &block, anchor_x, @@ -470,6 +475,7 @@ mod tests { let result = search( &plane, width, + width, height, &block, anchor_x, @@ -505,6 +511,7 @@ mod tests { let (_result, trace) = search_traced( &plane, width, + width, height, &block, anchor_x, @@ -571,6 +578,7 @@ mod tests { let (result, trace) = search_traced_from_step( &plane, width, + width, height, &block, anchor_x, diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 66ef5d71..efec65a0 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -18,6 +18,30 @@ use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; use crate::msac::SymbolEncoder; use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx}; +/// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the +/// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK` +/// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the +/// same variable, so the two traces line up symbol for symbol. Checked once +/// per process, so unset (the default) costs one atomic load per call and no +/// allocation. Only the real tile writer below calls this -- the mode/rate +/// search's own trial encoders never do -- so the trace does not need the +/// throwaway-encoder gating a whole-encoder trace would. +fn ec_rng_trace(msg: impl FnOnce() -> String) { + use std::sync::atomic::{AtomicU8, Ordering}; + static ON: AtomicU8 = AtomicU8::new(2); // 2 = unknown, 1 = on, 0 = off + let on = match ON.load(Ordering::Relaxed) { + 2 => { + let on = u8::from(std::env::var_os("EC_RNG").is_some()); + ON.store(on, Ordering::Relaxed); + on + } + v => v, + }; + if on == 1 { + eprintln!("{}", msg()); + } +} + /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided. const PARTITION_NONE: usize = 0; /// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants. @@ -34,7 +58,32 @@ const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9]; const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8]; /// Mode-info units across a 32x32 block. -const BLOCK_MI: u32 = SB_MI / 2; +pub(crate) const BLOCK_MI: u32 = SB_MI / 2; + +/// Mode-info units across a 16x16 block, the smallest this crate's key-frame +/// writer codes. +pub(crate) const SUB_MI: u32 = BLOCK_MI / 2; + +/// spec `decode_partition`'s `hasRows`/`hasCols` (5.11.4), recomputed at +/// whichever block size is asking: a block of `side_mi` mode-info units at mi +/// position `pos` may be coded unsplit (its own `PARTITION_NONE`) only when +/// this is true in both directions -- the frame's *true* size can put the +/// boundary inside a superblock, a 32x32 quadrant or (since this writer's +/// smallest block is 16x16) even a leaf, and each level must ask again with +/// its own half, not just once at the superblock. +pub(crate) fn has_half(pos: u32, side_mi: u32, bound: u32) -> bool { + pos + side_mi / 2 < bound +} + +/// The number of 32x32 block columns/rows a frame whose *true* (unpadded) +/// size gives `mi_cols`/`mi_rows` is coded over: every block whose mi origin +/// (`col * BLOCK_MI`) is inside the true bound is coded, so this is a +/// ceiling, not the exact division a block-aligned frame would give. Shared +/// by the tile writer's own iteration and by [`crate::encode`]'s block/ +/// superblock generation, which must agree with it exactly. +pub(crate) fn block_grid(mi_cols: u32, mi_rows: u32) -> (u32, u32) { + (mi_cols.div_ceil(BLOCK_MI), mi_rows.div_ceil(BLOCK_MI)) +} /// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode. const DC_PRED: usize = 0; @@ -468,6 +517,10 @@ const SB: usize = 64; /// Side of the smallest block the writer codes, in samples, which is the grid /// the neighbour bookkeeping is kept on. const SUB: usize = 16; +/// Side of a 4x4 mode-info unit, in samples: the granularity libaom's above +/// and left entropy-context arrays are actually kept on (spec +/// `get_txb_ctx`/`av1_set_entropy_contexts`), finer than [`SUB`]. +const MI: usize = 4; /// What one coded block leaves behind for the blocks that read it as a /// neighbour: whether it coded anything at all, and the sign of its DC. @@ -479,22 +532,18 @@ struct Neighbour { dc: Option, } -/// Rejects a frame the 32x32 block grid cannot tile. +/// Rejects a frame with no mode-info grid at all. /// -/// The frame need not be a whole number of superblocks — a superblock at the -/// right-hand or bottom edge may be half outside it — but every 32x32 block -/// that is coded has to be wholly inside, because a block that hangs over the -/// edge has to be coded as a rectangle this writer has no transform for. +/// `mi_cols`/`mi_rows` are the frame's *true* (unpadded) size in 4x4 units +/// (spec `compute_image_size`), not necessarily a multiple of the 32x32 block +/// grid: a block whose origin sits at or past this bound is not coded (spec's +/// `decode_partition` never visits it), and one that straddles the bound is +/// coded whole, its samples coming from the padded planes. fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> { - if mi_cols == 0 - || mi_rows == 0 - || !mi_cols.is_multiple_of(BLOCK_MI) - || !mi_rows.is_multiple_of(BLOCK_MI) - { + if mi_cols == 0 || mi_rows == 0 { return Err(Error::unsupported( "AV1 tile", - "a coefficient key frame is written only for frames that are a \ - whole number of 32x32 blocks", + "a coefficient key frame needs a nonzero mode-info grid", )); } Ok(()) @@ -567,6 +616,13 @@ struct Neighbours { above_inter: Vec, /// The same, down the left edge. left_inter: Vec, + /// The frame's true (unpadded) width and height, in 4x4 mode-info units, + /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec + /// `av1_set_entropy_contexts`): a block whose row or column run spills + /// past this bound leaves its trailing 4x4 units at their default, + /// mid-cell if need be. + mi_cols: usize, + mi_rows: usize, } /// What one plane's neighbours leave for a block, gathered across every cell @@ -586,11 +642,13 @@ struct Around { impl Neighbours { /// The state a tile starts from: a block outside it reads as `DC_PRED`, - /// as having coded nothing, and as unsplit. - fn new(cols: usize, rows: usize) -> Self { + /// as having coded nothing, and as unsplit. `cols`/`rows` are in [`SUB`] + /// units; `mi_cols`/`mi_rows` are the frame's true (unpadded) size in 4x4 + /// mode-info units. + fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self { Self { - above: vec![[Neighbour::default(); 3]; cols], - left: vec![[Neighbour::default(); 3]; rows], + above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)], + left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)], above_mode: vec![DC_PRED; cols], left_mode: vec![DC_PRED; rows], above_side: vec![SB; cols], @@ -599,6 +657,8 @@ impl Neighbours { left_skip: vec![false; rows], above_inter: vec![false; cols], left_inter: vec![false; rows], + mi_cols, + mi_rows, } } @@ -611,18 +671,56 @@ impl Neighbours { self.left_inter.iter_mut().for_each(|i| *i = false); } - /// Writes one coded block into every 16x16 column and row it covers. + /// Writes one coded block into every 16x16 column and row it covers, and, + /// on the finer 4x4 grid libaom's entropy context arrays are actually + /// kept on, into every unit up to the true frame edge -- the units past + /// it are left at their default (uncoded), even mid-16x16-cell (spec + /// `av1_set_entropy_contexts`, which clamps to `blocks_wide`/`blocks_high` + /// derived from the true `mi_cols`/`mi_rows`, not from this block's own + /// side). fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec; 3]) { let (r, c) = at; let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); for cell in 0..side / SUB { - self.above[c + cell] = states; - self.left[r + cell] = states; self.above_mode[c + cell] = mode; self.left_mode[r + cell] = mode; self.above_side[c + cell] = side; self.left_side[r + cell] = side; } + let (mi_r, mi_c, side_mi) = (r * (SUB / MI), c * (SUB / MI), side / MI); + // libaom rounds the luma edge up to the plane's own 4x4 unit before + // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high, + // subsampling_y)` in av1_write_intra_coeffs_mb, encodetxb.c:456-459): + // a chroma 4x4 unit straddling the true luma edge is still whole in + // chroma's own halved grid, so it stays valid one luma-mi row/col + // past where luma's own edge falls when that edge is odd. + let round_up_even = |n: usize| n.div_ceil(2) * 2; + let bound_h = [ + self.mi_rows, + round_up_even(self.mi_rows), + round_up_even(self.mi_rows), + ]; + let bound_w = [ + self.mi_cols, + round_up_even(self.mi_cols), + round_up_even(self.mi_cols), + ]; + for cell in 0..side_mi { + self.left[mi_r + cell] = std::array::from_fn(|plane| { + if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) { + states[plane] + } else { + Default::default() + } + }); + self.above[mi_c + cell] = std::array::from_fn(|plane| { + if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) { + states[plane] + } else { + Default::default() + } + }); + } } /// Writes one inter-frame block's skip flag and inter/intra state into @@ -643,10 +741,14 @@ impl Neighbours { /// The gathered state of the blocks above and to the left of one block, /// per plane. fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] { + let (mi_r, mi_c, side_mi) = (r * (SUB / MI), c * (SUB / MI), side / MI); std::array::from_fn(|plane| { let mut around = Around::default(); - for cell in 0..side / SUB { - let (above, left) = (&self.above[c + cell][plane], &self.left[r + cell][plane]); + for cell in 0..side_mi { + let (above, left) = ( + &self.above[mi_c + cell][plane], + &self.left[mi_r + cell][plane], + ); around.above_coded |= above.coded; around.left_coded |= left.coded; around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc); @@ -685,7 +787,7 @@ pub fn sb_coeff_key_frame_tile( superblocks: &[Superblock], ) -> Result> { check_blocks(mi_cols, mi_rows)?; - let (cols, rows) = (mi_cols / BLOCK_MI, mi_rows / BLOCK_MI); + let (cols, rows) = block_grid(mi_cols, mi_rows); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); if superblocks.len() != (sb_cols * sb_rows) as usize { return Err(Error::unsupported( @@ -722,7 +824,12 @@ pub fn sb_coeff_key_frame_tile( // The blocks above and to the left, on the 16x16 grid. The left edge is // reset at every superblock row because a tile starts each row with no // left neighbour. - let mut neighbours = Neighbours::new(cols as usize * 2, rows as usize * 2); + let mut neighbours = Neighbours::new( + cols as usize * 2, + rows as usize * 2, + mi_cols as usize, + mi_rows as usize, + ); // The tile adapts every non-literal CDF it writes, exactly as the decoder // adapts the ones it reads, so the frame header leaves `disable_cdf_update` @@ -734,6 +841,15 @@ pub fn sb_coeff_key_frame_tile( for sb_c in 0..sb_cols { let at = (sb_r as usize * 4, sb_c as usize * 4); let ctx = neighbours.partition_ctx(at, SB); + ec_rng_trace(|| { + format!( + "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={}", + at.0 * 4, + at.1 * 4, + ctx, + enc.tell() + ) + }); // A superblock whose bottom or right half is outside the frame // cannot be left unsplit, so the decoder reads a flag instead of // the partition symbol — and reads nothing at all when both halves @@ -778,6 +894,14 @@ pub fn sb_coeff_key_frame_tile( // luma, so its chroma mode reads the table without it. false, ); + ec_rng_trace(|| { + format!( + "EC_TOK mi_row={} mi_col={} tell={}", + at.0 * 4, + at.1 * 4, + enc.tell() + ) + }); } Superblock::Split(quadrants) => { match (has_cols, has_rows) { @@ -802,8 +926,34 @@ pub fn sb_coeff_key_frame_tile( for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) { let at = (r * 2, c * 2); let ctx = neighbours.partition_ctx(at, BLOCK); + // Recomputed at this 32x32 block's own half (spec + // `decode_partition`, called again at every size, not + // just once for the superblock): the true frame edge + // can fall inside this quadrant even when the + // superblock it sits in was itself whole or safely + // split above. + let (has_cols32, has_rows32) = ( + has_half(c as u32 * BLOCK_MI, BLOCK_MI, mi_cols), + has_half(r as u32 * BLOCK_MI, BLOCK_MI, mi_rows), + ); + ec_rng_trace(|| { + format!( + "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={}", + at.0 * 4, + at.1 * 4, + ctx, + enc.tell() + ) + }); match quadrant { Quadrant::Whole(block) => { + if !has_cols32 || !has_rows32 { + return Err(Error::unsupported( + "AV1 tile", + "a 32x32 block that is half outside the true frame \ + cannot be left whole", + )); + } enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]); let grids = [ level_grid(&block.luma, TX32)?, @@ -822,18 +972,92 @@ pub fn sb_coeff_key_frame_tile( [&scans[0], &scans[1], &scans[1]], true, ); + ec_rng_trace(|| { + format!( + "EC_TOK mi_row={} mi_col={} tell={}", + at.0 * 4, + at.1 * 4, + enc.tell() + ) + }); } Quadrant::Split(blocks) => { - enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]); - if blocks.len() != 4 { + // The 16x16 sub-blocks this quadrant's split + // carries: only those whose own mi origin is + // inside the true frame (spec `decode_partition`'s + // `r >= MiRows || c >= MiCols` early return), + // which need not be all four when the true + // edge falls inside this quadrant. + let sub_positions: Vec<(usize, usize)> = (0..4) + .map(|i| (r * 2 + i / 2, c * 2 + i % 2)) + .filter(|&(sr, sc)| { + (sr as u32) * SUB_MI < mi_rows + && (sc as u32) * SUB_MI < mi_cols + }) + .collect(); + if blocks.len() != sub_positions.len() { return Err(Error::unsupported( "AV1 tile", - "a 32x32 block that is split carries four 16x16 blocks", + "a split 32x32 block needs one 16x16 entry per \ + sub-block inside the true frame", )); } - for (i, block) in blocks.iter().enumerate() { - let at = (at.0 + i / 2, at.1 + i % 2); + // Same three-way spec signaling as the + // superblock level above, recomputed at this + // block's own half: a full alphabet symbol + // only when both halves are inside, a single + // gathered bit when just one is, and nothing + // at all (SPLIT is inferred) when neither is. + match (has_cols32, has_rows32) { + (true, true) => { + enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]); + } + (true, false) => { + enc.symbol_fixed( + 1, + &gather(&cdfs.partition_w32[ctx], VERT_ALIKE), + ); + } + (false, true) => { + enc.symbol_fixed( + 1, + &gather(&cdfs.partition_w32[ctx], HORZ_ALIKE), + ); + } + (false, false) => {} + } + for (block, (sr, sc)) in blocks.iter().zip(sub_positions) { + // A 16x16 leaf's own hasRows/hasCols: this + // writer has no smaller partition than + // 16x16 (no 8x8 or rectangular transform), + // so a leaf the true edge itself cuts + // through -- legal in the spec only via a + // `PARTITION_HORZ`/`VERT` this writer does + // not code -- is refused rather than + // silently miscoded. + let (has_cols16, has_rows16) = ( + has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols), + has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows), + ); + if !has_cols16 || !has_rows16 { + return Err(Error::unsupported( + "AV1 tile", + "a 16x16 block the true frame edge cuts through \ + needs a rectangular transform this writer does \ + not code yet", + )); + } + let at = (sr, sc); let ctx = neighbours.partition_ctx(at, SUB); + ec_rng_trace(|| { + format!( + "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={}", + at.0 * 4, + at.1 * 4, + ctx, + enc.tell() + ) + }); enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]); let grids = [ level_grid(&block.luma, TX16)?, @@ -852,6 +1076,14 @@ pub fn sb_coeff_key_frame_tile( [&scans[1], &scans[2], &scans[2]], true, ); + ec_rng_trace(|| { + format!( + "EC_TOK mi_row={} mi_col={} tell={}", + at.0 * 4, + at.1 * 4, + enc.tell() + ) + }); } } } @@ -960,7 +1192,15 @@ fn write_block_planes( scan, skip_ctx, dc_sign_ctx(around[plane].dc_vote), + Some(plane), ); + ec_rng_trace(|| { + format!( + "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}", + grid.iter().filter(|&&l| l != 0).count(), + enc.tell() + ) + }); } } @@ -988,7 +1228,7 @@ pub fn split_coeff_key_frame_tile( blocks: &[BlockCoeffs], ) -> Result> { check_blocks(mi_cols, mi_rows)?; - let (cols, rows) = (mi_cols / BLOCK_MI, mi_rows / BLOCK_MI); + let (cols, rows) = block_grid(mi_cols, mi_rows); if blocks.len() != (cols * rows) as usize { return Err(Error::unsupported( "AV1 tile", @@ -1102,7 +1342,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet) -> f64 { }; let mut enc = SymbolEncoder::new(); enc.reset_bits(); - write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0); + write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); enc.bits() } @@ -1135,6 +1375,7 @@ pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { /// levels the contexts below are read from are the levels of /// coefficients later in the scan, which a decoder walking the scan backwards /// already has. +#[allow(clippy::too_many_arguments)] fn write_coeffs( enc: &mut SymbolEncoder, coding: &mut TxbTables, @@ -1142,13 +1383,26 @@ fn write_coeffs( scan: &[u16], skip_ctx: usize, sign_ctx: usize, + plane: Option, ) { + if let Some(plane) = plane { + ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell())); + } let side = coding.side; let eob = scan .iter() .rposition(|&pos| grid[pos as usize] != 0) .map_or(0, |i| i + 1); enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]); + if plane.is_some() { + ec_rng_trace(|| { + format!( + "EC_TXBSKIP ctx={skip_ctx} eob0={} tell={}", + usize::from(eob == 0), + enc.tell() + ) + }); + } if eob == 0 { return; } @@ -1157,9 +1411,12 @@ fn write_coeffs( // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`. if let Some(tx_type) = coding.tx_type.as_deref_mut() { enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type); + if plane.is_some() { + ec_rng_trace(|| format!("EC_TXTYPE tell={}", enc.tell())); + } } - write_eob(enc, coding, eob); + write_eob(enc, coding, eob, plane); for scan_idx in (0..eob).rev() { let pos = scan[scan_idx] as usize; @@ -1167,16 +1424,29 @@ fn write_coeffs( let level = grid[pos].abs(); if scan_idx == eob - 1 { let ctx = eob_coeff_ctx(scan_idx, side * side); - enc.symbol( - (level.min(NUM_BASE_LEVELS + 1) - 1) as usize, - &mut coding.base_eob[ctx], - ); + let sym = (level.min(NUM_BASE_LEVELS + 1) - 1) as usize; + enc.symbol(sym, &mut coding.base_eob[ctx]); + if plane.is_some() { + ec_rng_trace(|| { + format!( + "EC_BASEEOB scan_idx={scan_idx} ctx={ctx} level={} tell={}", + sym + 1, + enc.tell() + ) + }); + } } else { let ctx = base_ctx(grid, side, row, col); - enc.symbol( - level.min(NUM_BASE_LEVELS + 1) as usize, - &mut coding.base[ctx], - ); + let sym = level.min(NUM_BASE_LEVELS + 1) as usize; + enc.symbol(sym, &mut coding.base[ctx]); + if plane.is_some() { + ec_rng_trace(|| { + format!( + "EC_BASE scan_idx={scan_idx} ctx={ctx} level={sym} tell={}", + enc.tell() + ) + }); + } } if level > NUM_BASE_LEVELS { let ctx = br_ctx(grid, side, row, col); @@ -1185,6 +1455,14 @@ fn write_coeffs( while sent < COEFF_BASE_RANGE { let k = remaining.min(BR_STEP); enc.symbol(k as usize, &mut coding.br[ctx]); + if plane.is_some() { + ec_rng_trace(|| { + format!( + "EC_BR scan_idx={scan_idx} ctx={ctx} k={k} tell={}", + enc.tell() + ) + }); + } if k < BR_STEP { break; } @@ -1203,6 +1481,15 @@ fn write_coeffs( } if pos == 0 { enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]); + if plane.is_some() { + ec_rng_trace(|| { + format!( + "EC_DCSIGN ctx={sign_ctx} neg={} tell={}", + usize::from(level < 0), + enc.tell() + ) + }); + } } else { enc.literal(u32::from(level < 0), 1); } @@ -1210,14 +1497,20 @@ fn write_coeffs( // of itself here, after its own sign (spec 5.11.39). if level.abs() > MAX_BR_LEVEL { write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32); + if plane.is_some() { + ec_rng_trace(|| format!("EC_GOLOMB tell={}", enc.tell())); + } } } + if let Some(plane) = plane { + ec_rng_trace(|| format!("EC_PLANE plane={plane} eob={eob} tell_after={}", enc.tell())); + } } /// The end-of-block position (spec 5.11.39): which group of scan positions the /// last coded coefficient falls in, then its offset inside that group — the /// offset's top bit from a CDF and the rest as raw bits. -fn write_eob(enc: &mut SymbolEncoder, coding: &mut TxbTables, eob: usize) { +fn write_eob(enc: &mut SymbolEncoder, coding: &mut TxbTables, eob: usize, plane: Option) { /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of /// end-of-block positions covers, indexed by the group's own number. const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513]; @@ -1231,14 +1524,34 @@ fn write_eob(enc: &mut SymbolEncoder, coding: &mut TxbTables, eob: usize) { // The groups are numbered from one, and how many of them the transform // reaches is the size of its own end-of-block alphabet. enc.symbol(group - 1, coding.eob_pt); + if let Some(plane) = plane { + ec_rng_trace(|| format!("EC_EOBPT plane={plane} eob_pt={group} tell={}", enc.tell())); + } let bits = OFFSET_BITS[group]; if bits > 0 { let offset = (eob - GROUP_START[group]) as u32; let top = (offset >> (bits - 1)) & 1; enc.symbol(top as usize, &mut coding.eob_extra[group - 3]); + if let Some(plane) = plane { + ec_rng_trace(|| { + format!( + "EC_EOBEXTRA plane={plane} eob_ctx={} top={top} tell={}", + group - 3, + enc.tell() + ) + }); + } if bits > 1 { enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1); + if let Some(plane) = plane { + ec_rng_trace(|| { + format!( + "EC_EOBBITS plane={plane} eob_extra={offset} tell={}", + enc.tell() + ) + }); + } } } } @@ -1380,10 +1693,12 @@ fn write_dc_coeffs( enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]); } -/// One neighbour cell's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for -/// a positive DC, minus one for a negative one, nothing for a cell whose block -/// carried no DC. Every 4x4 unit of a cell votes the same way, so counting -/// cells and counting units differ only by a factor the sign is blind to. +/// One 4x4 unit's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for a +/// positive DC, minus one for a negative one, nothing for a unit whose block +/// carried no DC or that sits past the frame's true edge (spec +/// `av1_set_entropy_contexts`), which is why the vote is gathered per 4x4 +/// unit and not per coded cell -- a unit past the edge does not vote even +/// when the rest of its cell does. fn dc_vote(dc: Option) -> i32 { match dc { None => 0, @@ -1544,12 +1859,16 @@ pub fn sb_coeff_inter_frame_tile( base_q_idx: u8, blocks: &[BlockCoeffs], ) -> Result> { - check_superblocks(mi_cols, mi_rows)?; - let (cols, rows) = (mi_cols / BLOCK_MI, mi_rows / BLOCK_MI); + check_blocks(mi_cols, mi_rows)?; + // `block_grid`'s ceiling, not a plain division: a true frame size that is + // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has + // one more block/superblock whose own origin is inside the true frame, + // same as `sb_coeff_key_frame_tile`. + let (cols, rows) = block_grid(mi_cols, mi_rows); if blocks.len() != (cols * rows) as usize { return Err(Error::unsupported( "AV1 tile", - "an inter frame needs one entry per 32x32 block", + "an inter frame needs one entry per 32x32 block inside the true frame", )); } if let Some(bad) = blocks @@ -1572,8 +1891,13 @@ pub fn sb_coeff_inter_frame_tile( /// writer's single-reference chain ever names. const LAST_FRAME: i8 = 1; - let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI); - let mut neighbours = Neighbours::new(cols as usize * 2, rows as usize * 2); + let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); + let mut neighbours = Neighbours::new( + cols as usize * 2, + rows as usize * 2, + mi_cols as usize, + mi_rows as usize, + ); let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); let mut enc = SymbolEncoder::new(); @@ -1596,14 +1920,57 @@ pub fn sb_coeff_inter_frame_tile( for sb_c in 0..sb_cols { let sb_at = (sb_r as usize * 4, sb_c as usize * 4); let sb_ctx = neighbours.partition_ctx(sb_at, SB); - enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]); + // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock + // whose bottom or right half falls outside the true frame cannot + // be left whole, but this writer only ever splits a superblock + // into its four 32x32 quadrants (never `PARTITION_NONE` at 64x64), + // so the only question is which of the three partition symbols + // that split takes — same three-way signaling as + // `sb_coeff_key_frame_tile`'s superblock level. + let (has_cols, has_rows) = ( + sb_c * SB_MI + SB_MI / 2 < mi_cols, + sb_r * SB_MI + SB_MI / 2 < mi_rows, + ); + match (has_cols, has_rows) { + (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]), + (true, false) => { + enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)); + } + (false, true) => { + enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)); + } + (false, false) => {} + } for quadrant in 0..4 { let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); + // Only a quadrant whose own mi origin is inside the true + // frame is coded at all (spec `decode_partition`'s + // `r >= MiRows || c >= MiCols` early return), same filter as + // `sb_coeff_key_frame_tile`'s `quadrant_positions`. + if r32 >= rows || c32 >= cols { + continue; + } let block = &blocks[(r32 * cols + c32) as usize]; let at = (r32 as usize * 2, c32 as usize * 2); let (r, c) = at; let ctx32 = neighbours.partition_ctx(at, BLOCK); + // This writer has no rectangular (HORZ/VERT) or further-split + // representation for a 32x32 block, so one that itself + // straddles the true edge is refused rather than miscoded -- + // mirroring `sb_coeff_key_frame_tile`'s "cannot be left whole" + // refusal, just with no split arm to fall back to here. + let (has_cols32, has_rows32) = ( + has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols), + has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows), + ); + if !has_cols32 || !has_rows32 { + return Err(Error::unsupported( + "AV1 tile", + "a 32x32 inter-frame block that straddles the true frame edge \ + needs an 8x8 split this writer does not code", + )); + } enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]); let has_above = r32 > 0; @@ -2445,6 +2812,7 @@ mod tests { &scan, 0, 0, + None, ); priced += luma_32_coeff_bits(grid); } @@ -2743,7 +3111,7 @@ mod tests { /// appeared beside a 32x32 one. #[test] fn a_block_gathers_the_cells_its_neighbours_cover() { - let mut neighbours = Neighbours::new(4, 4); + let mut neighbours = Neighbours::new(4, 4, 64, 64); let quiet = [ vec![0i32; TX16 * TX16], vec![0; TX8 * TX8], @@ -2766,8 +3134,9 @@ mod tests { "the one negative DC above the block is what it votes" ); // The same read one cell at a time misses it, which is the bug this - // gate is here for. - assert!(!neighbours.above[2][1].coded); + // gate is here for. `above[8]` is the first 4x4 unit the quiet block + // at `(0, 2)` wrote (2 SUB units * 4 4x4-units-per-SUB). + assert!(!neighbours.above[8][1].coded); } /// samples. @@ -3135,6 +3504,44 @@ mod tests { } } + /// The transpose of [`a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block`]: + /// an odd number of 32x32 block *rows* (superblock hangs off the + /// *bottom*, `has_cols=true, has_rows=false`) rather than an odd number of + /// columns (hangs off the *right*, `has_cols=false, has_rows=true`) -- + /// the two halves of the `(has_cols, has_rows)` match in + /// `sb_coeff_key_frame_tile` gather from different tables + /// (`VERT_ALIKE`/`HORZ_ALIKE`), and only the right-hand-edge direction had + /// a real-decoder test before this one. + #[test] + fn a_frame_that_hangs_off_the_bottom_codes_every_block() { + if !have_ffmpeg() { + eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg"); + return; + } + let blocks: Vec = (0..6) + .map(|i| { + let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) }; + BlockCoeffs::from(vec![Coeff { + row, + col, + level: 12, + }]) + }) + .collect(); + let rows = decode_luma_at(64, 96, &blocks); + for block_row in 0..3 { + for block_col in 0..2 { + let name = format!("block ({block_row},{block_col})"); + let block = block_at(&rows, block_row, block_col); + if (block_row * 2 + block_col) % 2 == 0 { + assert_falls_across(&block, &name); + } else { + assert_falls_down(&block, &name); + } + } + } + } + /// A frame whose blocks do not tile it is refused rather than written as a /// stream a decoder walks off the end of. #[test]