forge
Explore
Log in

Don't you dare go Hollow

A repeated-pattern key frame codes intrabc blocks, ffmpeg and our own decoder read them back sample-exact

Browse files at this commit

ffa03f8a6ddc3f6c3994a453a7c493241f195262Ahmet Kaan GümüşParent: 41b28fd
  • test
    • a repeated-pattern key frame codes intrabc blocks, ffmpeg and our own decoder read them back sample-exact
Show full message
test(av1): a repeated-pattern key frame codes intrabc blocks, ffmpeg and our own decoder read them back sample-exact
crates/ec-av1/src/encode.rsmodified+101 -40
@@ -2592,9 +2592,12 @@ fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usiz
25922592 /// changes again), plus the last DV chosen, which the RD price uses as its
25932593 /// predictor estimate.
25942594 struct Ibc {
2595+ /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
2596+ /// source repeats exactly where a lossily coded reconstruction only
2597+ /// nearly does, so an exact-match table over the reconstruction finds
2598+ /// almost nothing. The candidate is then SCORED against the
2599+ /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
25952600 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
2596- /// The reconstruction row this table has been filled up to.
2597- filled_to: usize,
25982601 /// The tile's own luma rect, in samples.
25992602 tile: (usize, usize, usize, usize),
26002603 /// The DV the previous intrabc block of this tile took -- the *estimate*
@@ -2611,10 +2614,11 @@ struct Ibc {
26112614 }
26122615
26132616 impl Ibc {
2614- fn new(tile: (usize, usize, usize, usize)) -> Self {
2617+ fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
2618+ let mut table = std::collections::HashMap::new();
2619+ ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
26152620 Self {
2616- table: std::collections::HashMap::new(),
2617- filled_to: tile.1,
2621+ table,
26182622 tile,
26192623 last_dv: None,
26202624 hits: 0,
@@ -2623,26 +2627,6 @@ impl Ibc {
26232627 }
26242628 }
26252629
2626- /// Indexes every reconstruction row above `y_limit` that is not indexed
2627- /// yet. Called once per superblock row, with the row's own top edge.
2628- fn fill_to(&mut self, recon: &[u8], width: usize, y_limit: usize) {
2629- if y_limit <= self.filled_to {
2630- return;
2631- }
2632- // A square straddling the boundary would be half-indexed, so start
2633- // `IBC_HASH - 1` rows back: `ibc_index` re-adds a few positions, and a
2634- // duplicate entry only costs one extra verified candidate.
2635- let from = self.filled_to.saturating_sub(IBC_HASH - 1).max(self.tile.1);
2636- ibc_index(
2637- &mut self.table,
2638- recon,
2639- width,
2640- (self.tile.0, from),
2641- (self.tile.2, y_limit),
2642- );
2643- self.filled_to = y_limit;
2644- }
2645-
26462630 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
26472631 /// (1/8 pel), with this lane's own extra restriction on top: the source
26482632 /// must lie entirely in a COMPLETED superblock row, which is exactly the
@@ -2685,6 +2669,27 @@ impl Ibc {
26852669 }
26862670 }
26872671
2672+/// How many block searches ran, how many found at least one VALID candidate,
2673+/// and how many won on rate-distortion -- the hash hit rate a gate prints
2674+/// (class `gate-blind-to-feature`: "the search ran" and "the search found
2675+/// something" and "the block took it" are three different claims).
2676+static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
2677+ [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
2678+
2679+impl Drop for Ibc {
2680+ fn drop(&mut self) {
2681+ for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
2682+ IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
2683+ }
2684+ }
2685+}
2686+
2687+/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
2688+/// its own encode.
2689+pub(crate) fn take_intrabc_search() -> [usize; 3] {
2690+ std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2691+}
2692+
26882693 /// [`crate::tile::write_dv_component`]'s static price -- the same shape as
26892694 /// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
26902695 /// infers rather than codes.
@@ -2819,12 +2824,19 @@ fn ibc_search(
28192824 };
28202825 ibc.lookups += 1;
28212826 let key = ibc_hash(luma.source, luma.width, x, y);
2822- // Newest first: a nearby copy costs the fewest DV bits, and the table is
2823- // filled in raster order.
2827+ // The table is filled in raster order, so the entries BEFORE this block's
2828+ // own position are exactly the already-coded ones -- and the nearest of
2829+ // them costs the fewest DV bits. Walking backwards from the block's own
2830+ // slot is what makes the search look up-and-left; taking the newest
2831+ // entries outright only ever finds candidates below and to the right,
2832+ // every one of which `dv_valid` rejects.
28242833 let hits: Vec<(u32, u32)> = ibc
28252834 .table
28262835 .get(&key)
2827- .map(|h| h.iter().rev().take(16).copied().collect())
2836+ .map(|h| {
2837+ let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
2838+ h[..end].iter().rev().take(32).copied().collect()
2839+ })
28282840 .unwrap_or_default();
28292841 for (hx, hy) in hits {
28302842 consider(&*ibc, hx as usize, hy as usize, &mut best);
@@ -4296,21 +4308,19 @@ pub(crate) fn encode_key_frame_inner(
42964308 let mut above_mode = vec![DC_PRED; cols * 2];
42974309 let mut left_mode = vec![DC_PRED; rows * 2];
42984310 let mut ibc = allow_intrabc.then(|| {
4299- Ibc::new((
4300- rect.mi_col0 as usize * 4,
4301- rect.mi_row0 as usize * 4,
4302- (rect.mi_col1 as usize * 4).min(true_width),
4303- (rect.mi_row1 as usize * 4).min(true_height),
4304- ))
4311+ Ibc::new(
4312+ (
4313+ rect.mi_col0 as usize * 4,
4314+ rect.mi_row0 as usize * 4,
4315+ (rect.mi_col1 as usize * 4).min(true_width),
4316+ (rect.mi_row1 as usize * 4).min(true_height),
4317+ ),
4318+ &picture_y8,
4319+ frame_width,
4320+ )
43054321 });
43064322 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
43074323 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
4308- // Every superblock row above this one is final (the in-loop filters
4309- // are off on an `allow_intrabc` frame), so it is indexed for the
4310- // block-hash search exactly once, here.
4311- if let Some(ibc) = ibc.as_mut() {
4312- ibc.fill_to(&luma.reconstruction, luma.width, sb_row * 64);
4313- }
43144324 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
43154325 let mut modes = Vec::with_capacity(4);
43164326 // The quadrants of a superblock are coded in the order the decoder
@@ -7381,6 +7391,57 @@ mod tests {
73817391 assert!(!film.screen, "the detector fired on the film-shaped test card");
73827392 }
73837393
7394+ /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
7395+ /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
7396+ /// take a block vector (fire count + DV histogram, class
7397+ /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
7398+ /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
7399+ /// exactly what the encoder did.
7400+ #[test]
7401+ fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
7402+ let fctx = &crate::decode::FrameCtx::new();
7403+ // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
7404+ // superblocks of 64) and tall enough for a source superblock row
7405+ // above the blocks that copy from it.
7406+ let (width, height) = (512usize, 256usize);
7407+ let picture = screen_card(width, height);
7408+ let _ = crate::tile::take_intrabc_hits();
7409+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7410+ assert!(
7411+ encoded.allow_intrabc,
7412+ "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
7413+ intrabc_source_share() * 100.0
7414+ );
7415+ let hits = crate::tile::take_intrabc_hits();
7416+ eprintln!(
7417+ "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
7418+ hits[0],
7419+ &hits[1..],
7420+ intrabc_source_share() * 100.0
7421+ );
7422+ let search = take_intrabc_search();
7423+ eprintln!(
7424+ "intrabc searches {} found-valid {} won-RD {}",
7425+ search[0], search[1], search[2]
7426+ );
7427+ assert!(
7428+ hits[0] > 0,
7429+ "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
7430+ );
7431+ let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
7432+ assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
7433+ assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
7434+ assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
7435+ if !have_ffmpeg() {
7436+ eprintln!("SKIP the ffmpeg half: no ffmpeg");
7437+ return;
7438+ }
7439+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
7440+ assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
7441+ assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
7442+ assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
7443+ }
7444+
73847445 /// The minimal repro that isolated the inter-residual desync: a key frame
73857446 /// followed by one inter frame whose single superblock carries one
73867447 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
crates/ec-av1/src/tile.rsmodified+3 -1
@@ -3058,7 +3058,9 @@ fn write_intrabc_block(
30583058 // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm)
30593059 // for the deblock grid, and `skip` itself for the next block's skip
30603060 // context.
3061- let empty: [Vec<i32>; 3] = [Vec::new(), Vec::new(), Vec::new()];
3061+ // One zero level per plane: `neighbour_state` reads `grid[0]` for the DC
3062+ // sign vote, and a skipped block leaves every context cleared.
3063+ let empty: [Vec<i32>; 3] = [vec![0], vec![0], vec![0]];
30623064 for cell in 0..(side / SUB).max(1) {
30633065 let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI));
30643066 neighbours.above_mode[c + cell] = DC_PRED;