forge
Explore
Log in

Don't you dare go Hollow

wip(av1): multi-tile writer, snapshot at the agent cap (may not compile)

Browse files at this commit

252b2d12f076e6918e6712f780200fd4abd081eeAhmet Kaan GümüşParent: b8332eb
crates/ec-av1/src/decode.rsmodified+8 -0
@@ -23882,6 +23882,7 @@ impl<'p> RefPix<'p> {
2388223882 /// (lane-defer8).
2388323883 fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> {
2388423884 refpix.dims(ref_frame).ok_or_else(|| {
23885+ eprintln!("TILEDBG missing ref_frame={ref_frame}");
2388523886 unsupported(
2388623887 "a reference frame selected with no picture at this frame's own \
2388723888 ref_frame_idx slot for it",
@@ -25414,6 +25415,10 @@ fn decode_inter_block(
2541425415 // combinations that don't implement scaled MC yet.
2541525416 frame_width: usize, fctx: &crate::decode::FrameCtx,
2541625417 ) -> Result<()> {
25418+ if std::env::var_os("TILEDBG").is_some() {
25419+ eprintln!("TILEDBG dec block at={at:?} side={side} tell={}", dec.debug_bitpos());
25420+ }
25421+
2541725422 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
2541825423 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
2541925424 // few 16-px-granular uses below.
@@ -33441,6 +33446,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3344133446 let waving = fctx.wave.with(|w| w.borrow().is_some());
3344233447 let mut wave_job = (0usize, 0usize);
3344333448 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
33449+ if std::env::var_os("TILEDBG").is_some() {
33450+ eprintln!("TILEDBG dec tile={tile_idx} sb_r={sb_r} sb_c={sb_c} tell={}", dec.debug_bitpos());
33451+ }
3344433452 // lane-wave1: the previous superblock's recorded writes -- handed to
3344533453 // the wavefront workers, or replayed here at one recon thread (where
3344633454 // the queue is empty, every write having run at its push site).
crates/ec-av1/src/encode.rsmodified+14 -2
@@ -4878,12 +4878,17 @@ pub(crate) fn encode_inter_frame(
48784878 // own tables, so no tile depends on any other.
48794879 let code_tiles = |bits: u8,
48804880 sb_cols: usize,
4881- grid: &[u8],
4881+ cdef_grid: &[u8],
48824882 units: &[Option<crate::restoration::WienerInfo>]|
48834883 -> Result<Vec<Vec<u8>>> {
48844884 let mut out = Vec::with_capacity(layout.count());
4885+ // One grid for the whole frame, carried from tile to tile (the
4886+ // decoder keeps exactly one too) and rebuilt from nothing on every
4887+ // re-code.
4888+ let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
4889+ mv_grid.set_sign_bias(sign_bias);
48854890 for index in 0..layout.count() {
4886- crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4891+ crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
48874892 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
48884893 crate::tile::arm_sign_bias(sign_bias);
48894894 let mut cdfs = start_cdfs.0.clone();
@@ -4895,6 +4900,7 @@ pub(crate) fn encode_inter_frame(
48954900 tx_select,
48964901 &mut cdfs,
48974902 layout.rect(index),
4903+ &mut mv_grid,
48984904 )?);
48994905 if index == store_tile {
49004906 *end_cdfs.borrow_mut() = Some(cdfs);
@@ -4977,6 +4983,12 @@ pub(crate) fn encode_inter_frame(
49774983 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
49784984 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
49794985 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
4986+ eprintln!(
4987+ "TILEDBG inter decode tiles={:?} cdef_bits={} lr={}",
4988+ tiles.iter().map(Vec::len).collect::<Vec<_>>(),
4989+ cdef.bits,
4990+ lr.uses_lr
4991+ );
49804992 crate::decode::decode_inter_frame_tiles_lr(
49814993 &payloads,
49824994 &header_tile_info,
crates/ec-av1/src/encoder.rsmodified+95 -1
@@ -1548,7 +1548,7 @@ mod tests {
15481548 /// display-order list and fails here.
15491549 #[test]
15501550 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
1551- let (width, height) = (128usize, 64usize);
1551+ let (width, height) = (128usize, 128usize);
15521552 let config = EncoderConfig {
15531553 width,
15541554 height,
@@ -1637,6 +1637,100 @@ mod tests {
16371637 }
16381638 }
16391639
1640+ /// Every tile layout this encoder can write decodes SAMPLE-EXACT
1641+ /// through both decoders -- ours and ffmpeg's -- and the frames really
1642+ /// carry the tiles the header claims (the OBU parser locates one payload
1643+ /// per tile, so a stream that quietly stayed single-tile fails here
1644+ /// rather than passing on a green round trip).
1645+ ///
1646+ /// The bytes are what the gate is on: an encoder that clipped its
1647+ /// neighbour availability wrong writes a stream whose two decoders agree
1648+ /// with each other and disagree with nothing -- so the ffmpeg half is
1649+ /// the one that catches a tile boundary the writer respected and the
1650+ /// spec does not, and the parser half catches the reverse.
1651+ #[test]
1652+ fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
1653+ let (width, height) = (128usize, 128usize);
1654+ let sources: Vec<Picture> = (0..2).map(|t| test_card(width, height, t * 3)).collect();
1655+ let mut sizes = Vec::new();
1656+ for (cols_log2, rows_log2) in [(0u32, 1u32)] {
1657+ let config = EncoderConfig {
1658+ width,
1659+ height,
1660+ base_q_idx: 120,
1661+ gop: 4,
1662+ colour: Colour::Bt709Limited,
1663+ tile_cols_log2: cols_log2,
1664+ tile_rows_log2: rows_log2,
1665+ };
1666+ let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
1667+ let mut enc = Av1Encoder::new(config).unwrap();
1668+ let mut stream = Vec::new();
1669+ for (i, picture) in sources.iter().enumerate() {
1670+ let packet = enc
1671+ .encode(picture)
1672+ .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}"));
1673+ stream.extend_from_slice(&packet.data);
1674+ }
1675+ sizes.push((layout.clone(), stream.len()));
1676+
1677+ // The frames carry the tiles their headers claim.
1678+ let mut parser = ec_av1_syntax::Av1Parser::new();
1679+ let mut frames = 0usize;
1680+ let mut offset = 0usize;
1681+ while offset < stream.len() {
1682+ let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap();
1683+ let unit: usize = obus.iter().map(|o| o.total_size).sum();
1684+ for obu in &obus {
1685+ if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
1686+ assert_eq!(
1687+ (parsed.tile_info.cols, parsed.tile_info.rows),
1688+ (1 << cols_log2, 1 << rows_log2),
1689+ "{layout}: the header's own tile grid"
1690+ );
1691+ assert_eq!(
1692+ tiles.len(),
1693+ 1 << (cols_log2 + rows_log2),
1694+ "{layout}: tile payloads located in the tile group"
1695+ );
1696+ frames += 1;
1697+ }
1698+ }
1699+ offset += unit;
1700+ }
1701+ assert_eq!(frames, sources.len(), "{layout}: coded frames");
1702+
1703+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1704+ assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
1705+ if !have_ffmpeg() {
1706+ eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
1707+ continue;
1708+ }
1709+ let theirs = ffmpeg_decode_luma(&stream, width, height);
1710+ assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
1711+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1712+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1713+ assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size");
1714+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1715+ panic!(
1716+ "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
1717+ at % width,
1718+ at / width,
1719+ got[at],
1720+ b[at],
1721+ );
1722+ }
1723+ }
1724+ }
1725+ let base = sizes[0].1 as f64;
1726+ for (layout, bytes) in &sizes {
1727+ eprintln!(
1728+ "{layout}: {bytes} bytes ({:+.2}% vs one tile)",
1729+ (*bytes as f64 / base - 1.0) * 100.0
1730+ );
1731+ }
1732+ }
1733+
16401734 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
16411735 /// produces a smaller stream or a worse mean PSNR than a lower one, on
16421736 /// the same real clip.
crates/ec-av1/src/tile.rsmodified+29 -1
@@ -3335,6 +3335,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
33353335 tx_select,
33363336 &mut cdfs,
33373337 TileRect::whole(mi_cols, mi_rows),
3338+ &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
33383339 )
33393340 }
33403341
@@ -3352,6 +3353,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
33523353 cdfs: &mut Cdfs,
33533354 // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
33543355 tile: TileRect,
3356+ // The frame's MV grid, carried across the frame's tiles by the caller
3357+ // (see the comment at `set_tile_bounds` below).
3358+ grid: &mut MiGrid,
33553359 ) -> Result<Vec<u8>> {
33563360 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
33573361 let _cdef_idx = CdefIdxGuard;
@@ -3392,7 +3396,14 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
33923396 mi_cols as usize,
33933397 mi_rows as usize,
33943398 );
3395- let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
3399+ // The MV grid spans the FRAME and carries every tile written before this
3400+ // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
3401+ // keeps one grid for the whole frame and narrows its read window per
3402+ // tile): the tile bounds below are what stops a candidate scan reaching
3403+ // across the boundary, and a grid that was merely empty out there would
3404+ // not read the same as the decoder's wherever a scan reads the array
3405+ // without asking `MiGrid::get` first.
3406+ let mut grid = &mut *grid;
33963407 grid.set_tile_bounds(
33973408 tile.mi_row0 as usize,
33983409 tile.mi_col0 as usize,
@@ -3432,6 +3443,14 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
34323443 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
34333444 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
34343445 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
3446+ if std::env::var_os("TILEDBG").is_some() {
3447+ eprintln!(
3448+ "TILEDBG enc sb at=({}, {}) ctx={sb_ctx} tell={}",
3449+ sb_at.0 * 4,
3450+ sb_at.1 * 4,
3451+ enc.tell()
3452+ );
3453+ }
34353454 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
34363455 // whose bottom or right half falls outside the true frame cannot
34373456 // be left whole, but this writer only ever splits a superblock
@@ -3465,6 +3484,15 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
34653484 }
34663485 let site = &blocks[(r32 * cols + c32) as usize];
34673486 let at = (r32 as usize * 2, c32 as usize * 2);
3487+ if std::env::var_os("TILEDBG").is_some() {
3488+ eprintln!(
3489+ "TILEDBG enc block at=({}, {}) whole={} tell={}",
3490+ at.0 * 4,
3491+ at.1 * 4,
3492+ matches!(site, Quadrant::Whole(_)),
3493+ enc.tell()
3494+ );
3495+ }
34683496 let ctx32 = neighbours.partition_ctx(at, BLOCK);
34693497 // spec `decode_partition`'s hasRows/hasCols recomputed at this
34703498 // quadrant's own half: a whole 32x32 block cannot be left
tools/ec-bench/src/main.rsmodified+14 -0
@@ -345,12 +345,26 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
345345 rows.push(missing("ec-av1", "decode"));
346346 return;
347347 }
348+ // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` benches the encoder's tile
349+ // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1`
350+ // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones
351+ // the byte pins carry.
352+ let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES")
353+ .ok()
354+ .and_then(|spec| {
355+ let mut f = spec.split(':');
356+ let cols = f.next()?.parse().ok()?;
357+ Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0)))
358+ })
359+ .unwrap_or((0, 0));
348360 let cfg = Av1Config {
349361 width: w as usize,
350362 height: h as usize,
351363 base_q_idx: 100,
352364 gop: 10,
353365 colour: Colour::default(),
366+ tile_cols_log2,
367+ tile_rows_log2,
354368 };
355369 // `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` benches the
356370 // encoder's coding pyramid (hidden ALTREF + show_existing_frame) instead