diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 019eba44..8f80d290 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -23882,6 +23882,7 @@ impl<'p> RefPix<'p> { /// (lane-defer8). fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> { refpix.dims(ref_frame).ok_or_else(|| { + eprintln!("TILEDBG missing ref_frame={ref_frame}"); unsupported( "a reference frame selected with no picture at this frame's own \ ref_frame_idx slot for it", @@ -25414,6 +25415,10 @@ fn decode_inter_block( // combinations that don't implement scaled MC yet. frame_width: usize, fctx: &crate::decode::FrameCtx, ) -> Result<()> { + if std::env::var_os("TILEDBG").is_some() { + eprintln!("TILEDBG dec block at={at:?} side={side} tell={}", dec.debug_bitpos()); + } + // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the // few 16-px-granular uses below. @@ -33441,6 +33446,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( let waving = fctx.wave.with(|w| w.borrow().is_some()); let mut wave_job = (0usize, 0usize); for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) { + if std::env::var_os("TILEDBG").is_some() { + eprintln!("TILEDBG dec tile={tile_idx} sb_r={sb_r} sb_c={sb_c} tell={}", dec.debug_bitpos()); + } // lane-wave1: the previous superblock's recorded writes -- handed to // the wavefront workers, or replayed here at one recon thread (where // the queue is empty, every write having run at its push site). diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 7714cf63..b02e6c8c 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -4878,12 +4878,17 @@ pub(crate) fn encode_inter_frame( // own tables, so no tile depends on any other. let code_tiles = |bits: u8, sb_cols: usize, - grid: &[u8], + cdef_grid: &[u8], units: &[Option]| -> Result>> { let mut out = Vec::with_capacity(layout.count()); + // One grid for the whole frame, carried from tile to tile (the + // decoder keeps exactly one too) and rebuilt from nothing on every + // re-code. + let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); + mv_grid.set_sign_bias(sign_bias); for index in 0..layout.count() { - crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); + crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); crate::tile::arm_sign_bias(sign_bias); let mut cdfs = start_cdfs.0.clone(); @@ -4895,6 +4900,7 @@ pub(crate) fn encode_inter_frame( tx_select, &mut cdfs, layout.rect(index), + &mut mv_grid, )?); if index == store_tile { *end_cdfs.borrow_mut() = Some(cdfs); @@ -4977,6 +4983,12 @@ pub(crate) fn encode_inter_frame( |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |lf, cdef, h, tiles: &[Vec], lr| { let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); + eprintln!( + "TILEDBG inter decode tiles={:?} cdef_bits={} lr={}", + tiles.iter().map(Vec::len).collect::>(), + cdef.bits, + lr.uses_lr + ); crate::decode::decode_inter_frame_tiles_lr( &payloads, &header_tile_info, diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 49d699b9..926cbfa0 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -1548,7 +1548,7 @@ mod tests { /// display-order list and fails here. #[test] fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { - let (width, height) = (128usize, 64usize); + let (width, height) = (128usize, 128usize); let config = EncoderConfig { width, height, @@ -1637,6 +1637,100 @@ mod tests { } } + /// Every tile layout this encoder can write decodes SAMPLE-EXACT + /// through both decoders -- ours and ffmpeg's -- and the frames really + /// carry the tiles the header claims (the OBU parser locates one payload + /// per tile, so a stream that quietly stayed single-tile fails here + /// rather than passing on a green round trip). + /// + /// The bytes are what the gate is on: an encoder that clipped its + /// neighbour availability wrong writes a stream whose two decoders agree + /// with each other and disagree with nothing -- so the ffmpeg half is + /// the one that catches a tile boundary the writer respected and the + /// spec does not, and the parser half catches the reverse. + #[test] + fn every_tile_layout_decodes_sample_exact_through_both_decoders() { + let (width, height) = (128usize, 128usize); + let sources: Vec = (0..2).map(|t| test_card(width, height, t * 3)).collect(); + let mut sizes = Vec::new(); + for (cols_log2, rows_log2) in [(0u32, 1u32)] { + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, + }; + let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + for (i, picture) in sources.iter().enumerate() { + let packet = enc + .encode(picture) + .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}")); + stream.extend_from_slice(&packet.data); + } + sizes.push((layout.clone(), stream.len())); + + // The frames carry the tiles their headers claim. + let mut parser = ec_av1_syntax::Av1Parser::new(); + let mut frames = 0usize; + let mut offset = 0usize; + while offset < stream.len() { + let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); + let unit: usize = obus.iter().map(|o| o.total_size).sum(); + for obu in &obus { + if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { + assert_eq!( + (parsed.tile_info.cols, parsed.tile_info.rows), + (1 << cols_log2, 1 << rows_log2), + "{layout}: the header's own tile grid" + ); + assert_eq!( + tiles.len(), + 1 << (cols_log2 + rows_log2), + "{layout}: tile payloads located in the tile group" + ); + frames += 1; + } + } + offset += unit; + } + assert_eq!(frames, sources.len(), "{layout}: coded frames"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg"); + continue; + } + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); + } + } + } + let base = sizes[0].1 as f64; + for (layout, bytes) in &sizes { + eprintln!( + "{layout}: {bytes} bytes ({:+.2}% vs one tile)", + (*bytes as f64 / base - 1.0) * 100.0 + ); + } + } + /// [`RateTarget::Quality`] is monotone: a higher quality dial never /// produces a smaller stream or a worse mean PSNR than a lower one, on /// the same real clip. diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index abd3bf1c..1f54804d 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -3335,6 +3335,7 @@ pub fn sb_coeff_inter_frame_tile_tx( tx_select, &mut cdfs, TileRect::whole(mi_cols, mi_rows), + &mut MiGrid::new(mi_cols as usize, mi_rows as usize), ) } @@ -3352,6 +3353,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( cdfs: &mut Cdfs, // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`]. tile: TileRect, + // The frame's MV grid, carried across the frame's tiles by the caller + // (see the comment at `set_tile_bounds` below). + grid: &mut MiGrid, ) -> Result> { // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. let _cdef_idx = CdefIdxGuard; @@ -3392,7 +3396,14 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( mi_cols as usize, mi_rows as usize, ); - let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); + // The MV grid spans the FRAME and carries every tile written before this + // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs` + // keeps one grid for the whole frame and narrows its read window per + // tile): the tile bounds below are what stops a candidate scan reaching + // across the boundary, and a grid that was merely empty out there would + // not read the same as the decoder's wherever a scan reads the array + // without asking `MiGrid::get` first. + let mut grid = &mut *grid; grid.set_tile_bounds( tile.mi_row0 as usize, tile.mi_col0 as usize, @@ -3432,6 +3443,14 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); let sb_ctx = neighbours.partition_ctx(sb_at, SB); + if std::env::var_os("TILEDBG").is_some() { + eprintln!( + "TILEDBG enc sb at=({}, {}) ctx={sb_ctx} tell={}", + sb_at.0 * 4, + sb_at.1 * 4, + enc.tell() + ); + } // 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 @@ -3465,6 +3484,15 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( } let site = &blocks[(r32 * cols + c32) as usize]; let at = (r32 as usize * 2, c32 as usize * 2); + if std::env::var_os("TILEDBG").is_some() { + eprintln!( + "TILEDBG enc block at=({}, {}) whole={} tell={}", + at.0 * 4, + at.1 * 4, + matches!(site, Quadrant::Whole(_)), + enc.tell() + ); + } let ctx32 = neighbours.partition_ctx(at, BLOCK); // spec `decode_partition`'s hasRows/hasCols recomputed at this // quadrant's own half: a whole 32x32 block cannot be left diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index 4c647f09..247872d5 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -345,12 +345,26 @@ fn bench_av1_encode(rows: &mut Vec) { rows.push(missing("ec-av1", "decode")); return; } + // `EC_AV1_TILES=[:]` benches the encoder's tile + // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1` + // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones + // the byte pins carry. + let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES") + .ok() + .and_then(|spec| { + let mut f = spec.split(':'); + let cols = f.next()?.parse().ok()?; + Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0))) + }) + .unwrap_or((0, 0)); let cfg = Av1Config { width: w as usize, height: h as usize, base_q_idx: 100, gop: 10, colour: Colour::default(), + tile_cols_log2, + tile_rows_log2, }; // `EC_AV1_PYRAMID=[::]` benches the // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead