forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1ibc' (5ddbe178): intra block copy on screen-detected key frames, oracle-proven, default OFF

Browse files at this commit

cbbd6e2ef6acafb00aeb55e460423f024126f90fAhmet Kaan GümüşParent: c759b784241847
Ships behind EC_AV1_INTRABC=1: at the gate's 640x384 downscale only 22 of
1200 searches find a valid DV and none win RD, so the frame pays the
in-loop-filter loss for nothing (screen +54.5 -> +59.1 with it on). Default
streams byte-identical. Measure at native capture resolution before any
constant moves (class: gate-recipe confound).
crates/ec-av1/src/decode.rsmodified+10 -6
@@ -37549,8 +37549,8 @@ mod tests {
37549 &encoded.loop_filter,37549 &encoded.loop_filter,
37550 encoded.tx_select,37550 encoded.tx_select,
37551 true,37551 true,
37552- false,37552+ encoded.screen,
37553- false,37553+ encoded.allow_intrabc,
37554 &encoded.loop_restoration, fctx,37554 &encoded.loop_restoration, fctx,
37555 )37555 )
37556 .unwrap();37556 .unwrap();
@@ -37593,8 +37593,8 @@ mod tests {
37593 &encoded.loop_filter,37593 &encoded.loop_filter,
37594 tx_select,37594 tx_select,
37595 true,37595 true,
37596- false,37596+ encoded.screen,
37597- false,37597+ encoded.allow_intrabc,
37598 &encoded.loop_restoration,37598 &encoded.loop_restoration,
37599 fctx,37599 fctx,
37600 )37600 )
@@ -37681,7 +37681,9 @@ mod tests {
37681 // This key frame's own `allow_screen_content_tools`: its intra37681 // This key frame's own `allow_screen_content_tools`: its intra
37682 // blocks carry the palette syntax under it (stale-header class).37682 // blocks carry the palette syntax under it (stale-header class).
37683 key.screen,37683 key.screen,
37684- false,37684+ // ... and its own `allow_intrabc`: every intra block carries a
37685+ // `use_intrabc` symbol under it (stale-header class).
37686+ key.allow_intrabc,
37685 &key.loop_restoration, fctx,37687 &key.loop_restoration, fctx,
37686 )37688 )
37687 .unwrap();37689 .unwrap();
@@ -38021,7 +38023,9 @@ mod tests {
38021 // This key frame's own `allow_screen_content_tools`: its intra38023 // This key frame's own `allow_screen_content_tools`: its intra
38022 // blocks carry the palette syntax under it (stale-header class).38024 // blocks carry the palette syntax under it (stale-header class).
38023 key.screen,38025 key.screen,
38024- false,38026+ // ... and its own `allow_intrabc`: every intra block carries a
38027+ // `use_intrabc` symbol under it (stale-header class).
38028+ key.allow_intrabc,
38025 &key.loop_restoration, fctx,38029 &key.loop_restoration, fctx,
38026 )38030 )
38027 .unwrap();38031 .unwrap();
crates/ec-av1/src/encode.rsmodified+621 -5
@@ -645,6 +645,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
645 next_cdfs: encoded.next_cdfs.clone(),645 next_cdfs: encoded.next_cdfs.clone(),
646 loop_filter: encoded.loop_filter,646 loop_filter: encoded.loop_filter,
647 loop_restoration: encoded.loop_restoration,647 loop_restoration: encoded.loop_restoration,
648+ allow_intrabc: encoded.allow_intrabc,
648 cdef: encoded.cdef,649 cdef: encoded.cdef,
649 }650 }
650 }651 }
@@ -724,6 +725,24 @@ pub struct Encoded {
724 /// filters themselves are coded in `tile`, so a decode of it under a725 /// filters themselves are coded in `tile`, so a decode of it under a
725 /// stale `RESTORE_NONE` header desyncs at the first superblock.726 /// stale `RESTORE_NONE` header desyncs at the first superblock.
726 pub(crate) loop_restoration: LoopRestorationParams,727 pub(crate) loop_restoration: LoopRestorationParams,
728+ /// This frame header's `allow_intrabc` -- every intra block of the tile
729+ /// carries a `use_intrabc` symbol under it, so a raw tile decode that
730+ /// guessed `false` would desync at the first block (same class as
731+ /// `screen`/`tx_select`).
732+ pub(crate) allow_intrabc: bool,
733+}
734+
735+thread_local! {
736+ /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
737+ /// for on the last key frame encoded on this thread -- read by the gates,
738+ /// which print it beside the block counts (class `gate-blind-to-feature`).
739+ static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
740+}
741+
742+/// [`IBC_SHARE`] for the last key frame encoded on this thread.
743+#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
744+pub(crate) fn intrabc_source_share() -> f64 {
745+ IBC_SHARE.with(std::cell::Cell::get)
727 }746 }
728 747
729 thread_local! {748 thread_local! {
@@ -2459,6 +2478,421 @@ fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
2459 }2478 }
2460 2479
2461 #[allow(clippy::too_many_arguments)]2480 #[allow(clippy::too_many_arguments)]
2481+// ---------------------------------------------------------------------------
2482+// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
2483+// validity). A key frame that detected screen content and finds enough exact
2484+// repeats in its own source sets `allow_intrabc`, which the spec forces every
2485+// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
2486+// its place when the copied blocks pay back the deblock/CDEF/LR the frame
2487+// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
2488+// ---------------------------------------------------------------------------
2489+
2490+/// Whether intra block copy is offered at all. **Off by default** --
2491+/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
2492+/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
2493+/// but on the gate's real screen capture it MEASURED WORSE: setting
2494+/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
2495+/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
2496+/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
2497+/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
2498+/// that detected no screen content.
2499+fn intrabc_enabled() -> bool {
2500+ if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
2501+ return forced;
2502+ }
2503+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2504+ *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
2505+}
2506+
2507+thread_local! {
2508+ /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
2509+ /// probe runs both arms in one process, and the suite is one process, so
2510+ /// an environment variable cannot separate them (same reason
2511+ /// [`SCREEN_FORCE`] exists).
2512+ static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2513+}
2514+
2515+#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2516+pub(crate) fn force_intrabc(value: Option<bool>) {
2517+ INTRABC_FORCE.with(|c| c.set(value));
2518+}
2519+
2520+/// How many of a screen frame's 16x16 blocks must have an exact repeat
2521+/// somewhere else in the source before `allow_intrabc` is worth the in-loop
2522+/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
2523+/// constant class: `probe_intrabc_threshold` measures the arm at several
2524+/// values.
2525+fn intrabc_pct() -> usize {
2526+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2527+ *N.get_or_init(|| {
2528+ std::env::var("EC_AV1_INTRABC_PCT")
2529+ .ok()
2530+ .and_then(|v| v.parse().ok())
2531+ .unwrap_or(10)
2532+ })
2533+}
2534+
2535+/// The pixel grid intrabc source positions are hashed on
2536+/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
2537+/// which keeps the block-hash table (and so the search) linear in the frame
2538+/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
2539+/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
2540+/// bilinear interpolation decode.rs applies but this encoder does not.
2541+fn intrabc_step() -> usize {
2542+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2543+ *N.get_or_init(|| {
2544+ let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
2545+ .ok()
2546+ .and_then(|v| v.parse().ok())
2547+ .unwrap_or(4);
2548+ if n % 2 == 0 { n.max(2) } else { 4 }
2549+ })
2550+}
2551+
2552+/// The side of the luma square the block-hash table is keyed on.
2553+const IBC_HASH: usize = 16;
2554+
2555+/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
2556+/// the current one the source's bottom-right corner must already be.
2557+const INTRABC_DELAY_SB64: i32 = 4;
2558+
2559+/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
2560+fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
2561+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
2562+ for row in 0..IBC_HASH {
2563+ let base = (y + row) * width + x;
2564+ for &v in &plane[base..base + IBC_HASH] {
2565+ h ^= u64::from(v);
2566+ h = h.wrapping_mul(0x100_0000_01b3);
2567+ }
2568+ }
2569+ h
2570+}
2571+
2572+/// Every `intrabc_step()`-aligned position of `plane` inside
2573+/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
2574+fn ibc_index(
2575+ table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
2576+ plane: &[u8],
2577+ width: usize,
2578+ (x0, y0): (usize, usize),
2579+ (x1, y1): (usize, usize),
2580+) {
2581+ let step = intrabc_step();
2582+ if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
2583+ return;
2584+ }
2585+ let mut y = y0.next_multiple_of(step);
2586+ while y + IBC_HASH <= y1 {
2587+ let mut x = x0.next_multiple_of(step);
2588+ while x + IBC_HASH <= x1 {
2589+ table
2590+ .entry(ibc_hash(plane, width, x, y))
2591+ .or_default()
2592+ .push((x as u32, y as u32));
2593+ x += step;
2594+ }
2595+ y += step;
2596+ }
2597+}
2598+
2599+/// Whether `screen`-detected source `y` repeats itself enough to be worth
2600+/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
2601+/// content appears at some other position, against [`intrabc_pct`]. Returns
2602+/// the share as well, for the gate's own print.
2603+fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
2604+ if true_width < 4 * 64 || true_height < 2 * 64 {
2605+ return (false, 0.0);
2606+ }
2607+ let mut table = std::collections::HashMap::new();
2608+ ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
2609+ let (mut total, mut matched) = (0usize, 0usize);
2610+ let mut by = 0;
2611+ while by + IBC_HASH <= true_height {
2612+ let mut bx = 0;
2613+ while bx + IBC_HASH <= true_width {
2614+ total += 1;
2615+ if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
2616+ if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
2617+ matched += 1;
2618+ }
2619+ }
2620+ bx += IBC_HASH;
2621+ }
2622+ by += IBC_HASH;
2623+ }
2624+ let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
2625+ (share * 100.0 >= intrabc_pct() as f64, share)
2626+}
2627+
2628+/// One tile's intrabc search state: a block-hash table over the part of the
2629+/// tile's own reconstruction that is already final (whole superblock rows --
2630+/// the in-loop filters are off on this frame, so a coded superblock row never
2631+/// changes again), plus the last DV chosen, which the RD price uses as its
2632+/// predictor estimate.
2633+struct Ibc {
2634+ /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
2635+ /// source repeats exactly where a lossily coded reconstruction only
2636+ /// nearly does, so an exact-match table over the reconstruction finds
2637+ /// almost nothing. The candidate is then SCORED against the
2638+ /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
2639+ table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
2640+ /// The tile's own luma rect, in samples.
2641+ tile: (usize, usize, usize, usize),
2642+ /// The DV the previous intrabc block of this tile took -- the *estimate*
2643+ /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
2644+ /// against. The writer computes the true predictor off its own mi grid
2645+ /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
2646+ /// a slightly mispriced candidate, never a wrong bitstream.
2647+ last_dv: Option<(i32, i32)>,
2648+ /// How many blocks took intrabc, and how many hash lookups found at least
2649+ /// one valid candidate -- the gate's own fire counts.
2650+ hits: usize,
2651+ lookups: usize,
2652+ found: usize,
2653+}
2654+
2655+impl Ibc {
2656+ fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
2657+ let mut table = std::collections::HashMap::new();
2658+ ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
2659+ Self {
2660+ table,
2661+ tile,
2662+ last_dv: None,
2663+ hits: 0,
2664+ lookups: 0,
2665+ found: 0,
2666+ }
2667+ }
2668+
2669+ /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
2670+ /// (1/8 pel), with this lane's own extra restriction on top: the source
2671+ /// must lie entirely in a COMPLETED superblock row, which is exactly the
2672+ /// region [`Self::fill_to`] indexes and a strict subset of what the spec
2673+ /// allows. corner-cut, ceiling named: same-superblock-row sources (the
2674+ /// wavefront's own diagonal) are legal and not searched; the upgrade path
2675+ /// is to index the current row's finished superblocks too.
2676+ fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
2677+ let (dr, dc) = (dv.0 / 8, dv.1 / 8);
2678+ if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
2679+ return false;
2680+ }
2681+ let (tx0, ty0, tx1, ty1) = (
2682+ self.tile.0 as i32,
2683+ self.tile.1 as i32,
2684+ self.tile.2 as i32,
2685+ self.tile.3 as i32,
2686+ );
2687+ let (sx, sy) = (x as i32 + dc, y as i32 + dr);
2688+ let (w, h) = (w as i32, h as i32);
2689+ if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
2690+ return false;
2691+ }
2692+ let active_sb_row = (y as i32 - ty0) >> 6;
2693+ let active_sb_col = (x as i32 - tx0) >> 6;
2694+ let src_sb_row = (sy + h - 1 - ty0) >> 6;
2695+ let src_sb_col = (sx + w - 1 - tx0) >> 6;
2696+ // This lane's own restriction (see the doc comment).
2697+ if src_sb_row >= active_sb_row {
2698+ return false;
2699+ }
2700+ let total = ((tx1 - tx0 - 1) >> 6) + 1;
2701+ if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64
2702+ {
2703+ return false;
2704+ }
2705+ // libaom's wavefront: only the top-left cone of the frame is legal.
2706+ let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row);
2707+ src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf
2708+ }
2709+}
2710+
2711+/// How many block searches ran, how many found at least one VALID candidate,
2712+/// and how many won on rate-distortion -- the hash hit rate a gate prints
2713+/// (class `gate-blind-to-feature`: "the search ran" and "the search found
2714+/// something" and "the block took it" are three different claims).
2715+static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
2716+ [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
2717+
2718+impl Drop for Ibc {
2719+ fn drop(&mut self) {
2720+ for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
2721+ IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
2722+ }
2723+ }
2724+}
2725+
2726+/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
2727+/// its own encode.
2728+#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2729+pub(crate) fn take_intrabc_search() -> [usize; 3] {
2730+ std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2731+}
2732+
2733+/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
2734+/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
2735+/// infers rather than codes.
2736+fn dv_component_bits(diff: i32) -> f64 {
2737+ let z = diff.unsigned_abs() as i32 - 1;
2738+ let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
2739+ let class = mv_class_of(z);
2740+ bits += symbol_bits(&cdf::MV_CLASS, class);
2741+ let local = z - mv_class_base(class);
2742+ if class == 0 {
2743+ bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
2744+ } else {
2745+ let d = local >> 3;
2746+ for i in 0..class {
2747+ bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
2748+ }
2749+ }
2750+ bits
2751+}
2752+
2753+/// What one block vector costs against `pred`, plus the `skip` and
2754+/// `use_intrabc` flags the block carries and the ordinary intra block does
2755+/// not pay in this currency.
2756+fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
2757+ let diff = (dv.0 - pred.0, dv.1 - pred.1);
2758+ let joint = match (diff.0 != 0, diff.1 != 0) {
2759+ (false, false) => 0,
2760+ (false, true) => 1,
2761+ (true, false) => 2,
2762+ (true, true) => 3,
2763+ };
2764+ let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
2765+ if diff.0 != 0 {
2766+ bits += dv_component_bits(diff.0);
2767+ }
2768+ if diff.1 != 0 {
2769+ bits += dv_component_bits(diff.1);
2770+ }
2771+ bits
2772+}
2773+
2774+/// The squared error of copying the `side`-square block at `(sx, sy)` of each
2775+/// plane's reconstruction onto the source block at `(x, y)`, luma and both
2776+/// chroma planes together -- what an intrabc block's whole (residual-free)
2777+/// distortion is.
2778+fn ibc_sse(
2779+ luma: &Plane,
2780+ chroma: &[Plane; 2],
2781+ (x, y): (usize, usize),
2782+ (sx, sy): (usize, usize),
2783+ side: usize,
2784+) -> f64 {
2785+ let mut sse = 0.0f64;
2786+ for row in 0..side {
2787+ let src = &luma.source[(y + row) * luma.width + x..][..side];
2788+ let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..side];
2789+ for (&s, &r) in src.iter().zip(rec) {
2790+ let d = f64::from(i32::from(s) - i32::from(r));
2791+ sse += d * d;
2792+ }
2793+ }
2794+ let half = side / 2;
2795+ for plane in chroma {
2796+ for row in 0..half {
2797+ let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..half];
2798+ let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..half];
2799+ for (&s, &r) in src.iter().zip(rec) {
2800+ let d = f64::from(i32::from(s) - i32::from(r));
2801+ sse += d * d;
2802+ }
2803+ }
2804+ }
2805+ sse
2806+}
2807+
2808+/// Copies the `side`-square block at `(sx, sy)` of each plane's
2809+/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
2810+/// since it carries no residual (`skip`). Full-pel in both planes by
2811+/// construction ([`intrabc_step`] keeps every DV even), which is what makes
2812+/// this a plain copy where decode.rs runs the bilinear kernel over the same
2813+/// samples.
2814+fn ibc_commit(
2815+ luma: &mut Plane,
2816+ chroma: &mut [Plane; 2],
2817+ (x, y): (usize, usize),
2818+ (sx, sy): (usize, usize),
2819+ side: usize,
2820+) {
2821+ for row in 0..side {
2822+ let from = (sy + row) * luma.width + sx;
2823+ let to = (y + row) * luma.width + x;
2824+ let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
2825+ luma.reconstruction[to..to + side].copy_from_slice(&copied);
2826+ }
2827+ let half = side / 2;
2828+ for plane in chroma {
2829+ for row in 0..half {
2830+ let from = (sy / 2 + row) * plane.width + sx / 2;
2831+ let to = (y / 2 + row) * plane.width + x / 2;
2832+ let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
2833+ plane.reconstruction[to..to + half].copy_from_slice(&copied);
2834+ }
2835+ }
2836+}
2837+
2838+/// Searches this block's own DV: every hash-table position whose 16x16 luma
2839+/// square equals the block's source square, plus the previous block's DV as a
2840+/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
2841+/// the winning `(dv, cost)`, or `None` when nothing valid was found.
2842+fn ibc_search(
2843+ ibc: &mut Ibc,
2844+ luma: &Plane,
2845+ chroma: &[Plane; 2],
2846+ (x, y): (usize, usize),
2847+ side: usize,
2848+ lambda: f64,
2849+) -> Option<((i32, i32), f64, (usize, usize))> {
2850+ let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
2851+ let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
2852+ let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
2853+ let dv = (
2854+ (sy as i32 - y as i32) * 8,
2855+ (sx as i32 - x as i32) * 8,
2856+ );
2857+ if !ibc.dv_valid(x, y, side, side, dv) {
2858+ return;
2859+ }
2860+ let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
2861+ if best.as_ref().is_none_or(|b| cost < b.1) {
2862+ *best = Some((dv, cost, (sx, sy)));
2863+ }
2864+ };
2865+ ibc.lookups += 1;
2866+ let key = ibc_hash(luma.source, luma.width, x, y);
2867+ // The table is filled in raster order, so the entries BEFORE this block's
2868+ // own position are exactly the already-coded ones -- and the nearest of
2869+ // them costs the fewest DV bits. Walking backwards from the block's own
2870+ // slot is what makes the search look up-and-left; taking the newest
2871+ // entries outright only ever finds candidates below and to the right,
2872+ // every one of which `dv_valid` rejects.
2873+ let hits: Vec<(u32, u32)> = ibc
2874+ .table
2875+ .get(&key)
2876+ .map(|h| {
2877+ let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
2878+ h[..end].iter().rev().take(32).copied().collect()
2879+ })
2880+ .unwrap_or_default();
2881+ for (hx, hy) in hits {
2882+ consider(&*ibc, hx as usize, hy as usize, &mut best);
2883+ }
2884+ if let Some(dv) = ibc.last_dv {
2885+ let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
2886+ if sx >= 0 && sy >= 0 {
2887+ consider(&*ibc, sx as usize, sy as usize, &mut best);
2888+ }
2889+ }
2890+ if best.is_some() {
2891+ ibc.found += 1;
2892+ }
2893+ best
2894+}
2895+
2462 fn code_square(2896 fn code_square(
2463 luma: &mut Plane,2897 luma: &mut Plane,
2464 chroma: &mut [Plane; 2],2898 chroma: &mut [Plane; 2],
@@ -2469,7 +2903,10 @@ fn code_square(
2469 // The frame header's `tx_mode == TxMode::Select`: the block then searches2903 // The frame header's `tx_mode == TxMode::Select`: the block then searches
2470 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one2904 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
2471 // transform over its whole side.2905 // transform over its whole side.
2472- tx_select: bool, fctx: &crate::decode::FrameCtx,2906+ tx_select: bool,
2907+ // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
2908+ // header did not set `allow_intrabc`.
2909+ ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx,
2473 ) -> (BlockCoeffs, f64) {2910 ) -> (BlockCoeffs, f64) {
2474 let (luma_set, chroma_set) = if side == BLOCK {2911 let (luma_set, chroma_set) = if side == BLOCK {
2475 (TxbSet::Luma32, TxbSet::Chroma16)2912 (TxbSet::Luma32, TxbSet::Chroma16)
@@ -2573,6 +3010,29 @@ fn code_square(
2573 let ([u, v], uv_mode, chroma_cost, palette_uv) =3010 let ([u, v], uv_mode, chroma_cost, palette_uv) =
2574 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);3011 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
2575 cost += chroma_cost;3012 cost += chroma_cost;
3013+
3014+ // The intrabc arm is priced against the WHOLE block -- luma and both
3015+ // chroma planes, residual-free -- so it is compared after the chroma
3016+ // search has added its own cost, not against the luma decision alone.
3017+ if let Some(ibc) = ibc {
3018+ if let Some((dv, cost_ibc, src)) =
3019+ ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
3020+ {
3021+ if cost_ibc < cost {
3022+ ibc_commit(luma, chroma, (x, y), src, side);
3023+ ibc.last_dv = Some(dv);
3024+ ibc.hits += 1;
3025+ return (
3026+ BlockCoeffs {
3027+ skip: true,
3028+ dv: Some(dv),
3029+ ..BlockCoeffs::default()
3030+ },
3031+ cost_ibc,
3032+ );
3033+ }
3034+ }
3035+ }
2576 (3036 (
2577 BlockCoeffs {3037 BlockCoeffs {
2578 u,3038 u,
@@ -2844,6 +3304,7 @@ fn code_square_inter(
2844 search,3304 search,
2845 mode_bits,3305 mode_bits,
2846 tx_select() && tx_select_inter(),3306 tx_select() && tx_select_inter(),
3307+ None,
2847 fctx,3308 fctx,
2848 );3309 );
2849 let luma_set = if side == 8 {3310 let luma_set = if side == 8 {
@@ -3218,6 +3679,7 @@ fn code_square_inter(
3218 uv_mode: DC_PRED,3679 uv_mode: DC_PRED,
3219 skip: skip_new,3680 skip: skip_new,
3220 eight: None,3681 eight: None,
3682+ dv: None,
3221 palette: None,3683 palette: None,
3222 palette_uv: None,3684 palette_uv: None,
3223 tx_depth,3685 tx_depth,
@@ -3249,6 +3711,7 @@ fn code_square_inter(
3249 uv_mode: DC_PRED,3711 uv_mode: DC_PRED,
3250 skip,3712 skip,
3251 eight: None,3713 eight: None,
3714+ dv: None,
3252 palette: None,3715 palette: None,
3253 palette_uv: None,3716 palette_uv: None,
3254 tx_depth,3717 tx_depth,
@@ -3895,8 +4358,30 @@ pub(crate) fn encode_key_frame_inner(
3895 (picture.height).min(render.1),4358 (picture.height).min(render.1),
3896 );4359 );
3897 arm_seq_screen(screen);4360 arm_seq_screen(screen);
4361+ // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
4362+ // forces deblocking, CDEF and loop restoration OFF for this frame
4363+ // (frame.rs:194/210/252/272), so it is only set when the source repeats
4364+ // itself enough for the copied blocks to pay that back
4365+ // ([`intrabc_worth_it`]).
4366+ // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
4367+ // grid across every tile while this writer builds one per tile, so a
4368+ // multi-tile allow_intrabc frame would predict its DVs off a different
4369+ // grid than the decoder does. corner-cut, ceiling named: the upgrade
4370+ // path is a frame-scoped grid shared by the tile writers.
4371+ let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
4372+ intrabc_worth_it(
4373+ &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
4374+ picture.width,
4375+ picture.width.min(render.0),
4376+ picture.height.min(render.1),
4377+ )
4378+ } else {
4379+ (false, 0.0)
4380+ };
4381+ IBC_SHARE.with(|c| c.set(ibc_share));
3898 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;4382 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
3899 header.allow_screen_content_tools = screen;4383 header.allow_screen_content_tools = screen;
4384+ header.allow_intrabc = allow_intrabc;
3900 header.render_width = render.0 as u32;4385 header.render_width = render.0 as u32;
3901 header.render_height = render.1 as u32;4386 header.render_height = render.1 as u32;
3902 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split4387 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
@@ -4021,6 +4506,18 @@ pub(crate) fn encode_key_frame_inner(
4021 clip_planes_to_tile(&mut luma, &mut chroma, rect);4506 clip_planes_to_tile(&mut luma, &mut chroma, rect);
4022 let mut above_mode = vec![DC_PRED; cols * 2];4507 let mut above_mode = vec![DC_PRED; cols * 2];
4023 let mut left_mode = vec![DC_PRED; rows * 2];4508 let mut left_mode = vec![DC_PRED; rows * 2];
4509+ let mut ibc = allow_intrabc.then(|| {
4510+ Ibc::new(
4511+ (
4512+ rect.mi_col0 as usize * 4,
4513+ rect.mi_row0 as usize * 4,
4514+ (rect.mi_col1 as usize * 4).min(true_width),
4515+ (rect.mi_row1 as usize * 4).min(true_height),
4516+ ),
4517+ &picture_y8,
4518+ frame_width,
4519+ )
4520+ });
4024 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();4521 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
4025 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {4522 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
4026 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {4523 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
@@ -4108,7 +4605,8 @@ pub(crate) fn encode_key_frame_inner(
4108 BLOCK,4605 BLOCK,
4109 &search,4606 &search,
4110 &mode_bits(above_mode[c0], left_mode[r0]),4607 &mode_bits(above_mode[c0], left_mode[r0]),
4111- tx_select, fctx,4608+ tx_select,
4609+ ibc.as_mut(), fctx,
4112 );4610 );
4113 cost_whole += search.lambda * partition_bits(BLOCK, false);4611 cost_whole += search.lambda * partition_bits(BLOCK, false);
4114 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);4612 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
@@ -4142,7 +4640,8 @@ pub(crate) fn encode_key_frame_inner(
4142 SUB,4640 SUB,
4143 &search,4641 &search,
4144 &mode_bits(above_mode[sc], left_mode[sr]),4642 &mode_bits(above_mode[sc], left_mode[sr]),
4145- tx_select, fctx,4643+ tx_select,
4644+ ibc.as_mut(), fctx,
4146 );4645 );
4147 cost_split += cost;4646 cost_split += cost;
4148 split_modes.push(block.mode);4647 split_modes.push(block.mode);
@@ -4174,7 +4673,8 @@ pub(crate) fn encode_key_frame_inner(
4174 8,4673 8,
4175 &search,4674 &search,
4176 &leaf_mode_bits,4675 &leaf_mode_bits,
4177- tx_select, fctx,4676+ tx_select,
4677+ None, fctx,
4178 );4678 );
4179 cost_split += cost;4679 cost_split += cost;
4180 split_modes.push(leaf.mode);4680 split_modes.push(leaf.mode);
@@ -4273,6 +4773,7 @@ pub(crate) fn encode_key_frame_inner(
4273 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());4773 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4274 let mut cdfs = start_cdfs.0.clone();4774 let mut cdfs = start_cdfs.0.clone();
4275 crate::tile::arm_screen(screen);4775 crate::tile::arm_screen(screen);
4776+ crate::tile::arm_intrabc(allow_intrabc);
4276 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(4777 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
4277 mi_cols,4778 mi_cols,
4278 mi_rows,4779 mi_rows,
@@ -4297,7 +4798,11 @@ pub(crate) fn encode_key_frame_inner(
4297 &mut luma,4798 &mut luma,
4298 &mut chroma,4799 &mut chroma,
4299 [&picture_y8, &picture_u8, &picture_v8],4800 [&picture_y8, &picture_u8, &picture_v8],
4300- true,4801+ // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
4802+ // and loop restoration off and codes none of their parameters
4803+ // (frame.rs:194/210/252/272) -- there is no filter to search for, and
4804+ // the encoder's reconstruction is already what a decoder produces.
4805+ !allow_intrabc,
4301 &mut tiles,4806 &mut tiles,
4302 search.lambda,4807 search.lambda,
4303 fctx,4808 fctx,
@@ -4358,6 +4863,7 @@ pub(crate) fn encode_key_frame_inner(
4358 loop_filter: header.loop_filter,4863 loop_filter: header.loop_filter,
4359 cdef: header.cdef,4864 cdef: header.cdef,
4360 loop_restoration: header.loop_restoration,4865 loop_restoration: header.loop_restoration,
4866+ allow_intrabc,
4361 })4867 })
4362 }4868 }
4363 4869
@@ -5557,6 +6063,7 @@ fn search_inter_block(
5557 skip: best.skip,6063 skip: best.skip,
5558 inter: best.inter,6064 inter: best.inter,
5559 eight: None,6065 eight: None,
6066+ dv: None,
5560 palette: None,6067 palette: None,
5561 palette_uv: None,6068 palette_uv: None,
5562 tx_depth: 0,6069 tx_depth: 0,
@@ -6459,6 +6966,9 @@ pub(crate) fn encode_inter_frame(
6459 loop_filter: header.loop_filter,6966 loop_filter: header.loop_filter,
6460 cdef: header.cdef,6967 cdef: header.cdef,
6461 loop_restoration: header.loop_restoration,6968 loop_restoration: header.loop_restoration,
6969+ // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
6970+ // intra frames only).
6971+ allow_intrabc: false,
6462 })6972 })
6463 }6973 }
6464 6974
@@ -7067,6 +7577,111 @@ mod tests {
7067 assert!(!film.screen, "the detector fired on the film-shaped test card");7577 assert!(!film.screen, "the detector fired on the film-shaped test card");
7068 }7578 }
7069 7579
7580+ /// The lane's keep-rule measurement: the gate's own screen capture, one
7581+ /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
7582+ /// Setting the bit forces deblocking, CDEF and loop restoration off for
7583+ /// that frame, so the table is exactly the filter loss against the bytes
7584+ /// the copied blocks save.
7585+ #[test]
7586+ #[ignore = "needs the real-library manifest and ffmpeg"]
7587+ fn probe_intrabc_key_frame() {
7588+ let fctx = &crate::decode::FrameCtx::new();
7589+ let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7590+ .join("../../fixtures");
7591+ let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
7592+ eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
7593+ return;
7594+ };
7595+ let Some(clip) = manifest
7596+ .lines()
7597+ .skip(1)
7598+ .filter_map(|l| l.split('\t').next())
7599+ .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
7600+ else {
7601+ eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
7602+ return;
7603+ };
7604+ let (width, height) = (640usize, 384usize);
7605+ let picture = clip_frame(clip, "0", width, height);
7606+ eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
7607+ for q in [5u8, 20, 35, 45] {
7608+ for on in [false, true] {
7609+ force_intrabc(Some(on));
7610+ let _ = crate::tile::take_intrabc_hits();
7611+ let _ = take_intrabc_search();
7612+ let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
7613+ let hits = crate::tile::take_intrabc_hits();
7614+ let search = take_intrabc_search();
7615+ eprintln!(
7616+ "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
7617+ if encoded.allow_intrabc { "on" } else { "off" },
7618+ encoded.stream.len(),
7619+ psnr_all(&encoded.reconstruction, &picture),
7620+ hits[0],
7621+ &hits[1..],
7622+ search[0], search[1], search[2],
7623+ );
7624+ }
7625+ }
7626+ force_intrabc(None);
7627+ }
7628+
7629+ /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
7630+ /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
7631+ /// take a block vector (fire count + DV histogram, class
7632+ /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
7633+ /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
7634+ /// exactly what the encoder did.
7635+ #[test]
7636+ fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
7637+ let fctx = &crate::decode::FrameCtx::new();
7638+ // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
7639+ // superblocks of 64) and tall enough for a source superblock row
7640+ // above the blocks that copy from it.
7641+ let (width, height) = (512usize, 256usize);
7642+ let picture = screen_card(width, height);
7643+ let _ = crate::tile::take_intrabc_hits();
7644+ // The default is OFF (it measured worse on the real screen capture --
7645+ // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
7646+ // the arm on for its own encode and puts it back straight after.
7647+ force_intrabc(Some(true));
7648+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7649+ force_intrabc(None);
7650+ assert!(
7651+ encoded.allow_intrabc,
7652+ "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
7653+ intrabc_source_share() * 100.0
7654+ );
7655+ let hits = crate::tile::take_intrabc_hits();
7656+ eprintln!(
7657+ "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
7658+ hits[0],
7659+ &hits[1..],
7660+ intrabc_source_share() * 100.0
7661+ );
7662+ let search = take_intrabc_search();
7663+ eprintln!(
7664+ "intrabc searches {} found-valid {} won-RD {}",
7665+ search[0], search[1], search[2]
7666+ );
7667+ assert!(
7668+ hits[0] > 0,
7669+ "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
7670+ );
7671+ let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
7672+ assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
7673+ assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
7674+ assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
7675+ if !have_ffmpeg() {
7676+ eprintln!("SKIP the ffmpeg half: no ffmpeg");
7677+ return;
7678+ }
7679+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
7680+ assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
7681+ assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
7682+ assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
7683+ }
7684+
7070 /// The minimal repro that isolated the inter-residual desync: a key frame7685 /// The minimal repro that isolated the inter-residual desync: a key frame
7071 /// followed by one inter frame whose single superblock carries one7686 /// followed by one inter frame whose single superblock carries one
7072 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma7687 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
@@ -7103,6 +7718,7 @@ mod tests {
7103 uv_mode: 0,7718 uv_mode: 0,
7104 skip: false,7719 skip: false,
7105 eight: None,7720 eight: None,
7721+ dv: None,
7106 palette: None,7722 palette: None,
7107 palette_uv: None,7723 palette_uv: None,
7108 tx_depth: 0,7724 tx_depth: 0,
crates/ec-av1/src/stream.rsmodified+2 -1
@@ -3005,7 +3005,8 @@ pub(crate) mod tests {
3005 // `false` desyncs at the first one (class: test asserts3005 // `false` desyncs at the first one (class: test asserts
3006 // against a stale header).3006 // against a stale header).
3007 encoded.screen,3007 encoded.screen,
3008- false,3008+ // ... and its own `allow_intrabc` (stale-header class).
3009+ encoded.allow_intrabc,
3009 &encoded.loop_restoration, fctx,3010 &encoded.loop_restoration, fctx,
3010 )3011 )
3011 .unwrap();3012 .unwrap();
crates/ec-av1/src/tile.rsmodified+279 -1
@@ -314,6 +314,54 @@ fn screen_armed() -> bool {
314 SCREEN.with(std::cell::Cell::get)314 SCREEN.with(std::cell::Cell::get)
315 }315 }
316 316
317+thread_local! {
318+ /// This frame header's `allow_intrabc` (spec 5.9.2), armed exactly like
319+ /// [`SCREEN`]: with it every intra block of the tile carries a
320+ /// `use_intrabc` symbol right after `skip`/`cdef`/`delta_q` (decode.rs
321+ /// `read_intra_mode`), so a tile written without it and read with it
322+ /// desyncs at the first block.
323+ static INTRABC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
324+ /// The mi grid the DV predictor is built off (decode.rs
325+ /// `INTRABC_MI_GRID`/`record_intrabc_mi`): every coded block publishes
326+ /// its own footprint into it, an intrabc one also its DV as an
327+ /// `INTRA_FRAME` candidate. `Some` only while an `allow_intrabc` tile is
328+ /// being written.
329+ static INTRABC_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
330+ const { std::cell::RefCell::new(None) };
331+}
332+
333+/// Arms the frame's `allow_intrabc` bit for the next tile written on this
334+/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
335+pub(crate) fn arm_intrabc(on: bool) {
336+ INTRABC.with(|c| c.set(on));
337+}
338+
339+fn intrabc_armed() -> bool {
340+ INTRABC.with(std::cell::Cell::get)
341+}
342+
343+/// How many blocks this writer coded `use_intrabc == 1`, and the histogram of
344+/// their DV magnitudes in full pels (index 1..=6 = 1, 2, 4, 8, 16, 32 pels
345+/// and up, by the larger component) -- the fire count a gate prints so that
346+/// "intrabc is on" is a measurement rather than a claim (class
347+/// `gate-blind-to-feature`). Index 0 is the block count.
348+static INTRABC_HITS: [std::sync::atomic::AtomicUsize; 7] =
349+ [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
350+
351+fn note_intrabc(dv: (i32, i32)) {
352+ INTRABC_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
353+ let px = (dv.0.abs() / 8).max(dv.1.abs() / 8).max(1) as usize;
354+ let bucket = (usize::BITS - px.leading_zeros()) as usize;
355+ INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
356+}
357+
358+/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts
359+/// to its own encode.
360+#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
361+pub(crate) fn take_intrabc_hits() -> [usize; 7] {
362+ std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
363+}
364+
317 thread_local! {365 thread_local! {
318 /// This frame header's own `reference_select` bit (spec 5.9.22), armed366 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
319 /// the same way `arm_sign_bias` arms the sign-bias table rather than367 /// the same way `arm_sign_bias` arms the sign-bias table rather than
@@ -688,6 +736,8 @@ impl Drop for CdefIdxGuard {
688 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));736 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
689 SCREEN.with(|c| c.set(false));737 SCREEN.with(|c| c.set(false));
690 REFERENCE_SELECT.with(|c| c.set(false));738 REFERENCE_SELECT.with(|c| c.set(false));
739+ INTRABC.with(|c| c.set(false));
740+ INTRABC_GRID.with(|c| *c.borrow_mut() = None);
691 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));741 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
692 }742 }
693 }743 }
@@ -1193,6 +1243,19 @@ pub struct BlockCoeffs {
1193 /// `luma` then carries the whole block's levels in BLOCK coordinates,1243 /// `luma` then carries the whole block's levels in BLOCK coordinates,
1194 /// which the writer slices per transform unit.1244 /// which the writer slices per transform unit.
1195 pub tx_depth: u8,1245 pub tx_depth: u8,
1246+ /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
1247+ /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
1248+ /// an ordinary intra block. Only a key frame whose header set
1249+ /// `allow_intrabc` ([`arm_intrabc`]) may carry one; the block is then
1250+ /// coded `skip` with no residual, no mode, no palette -- exactly what
1251+ /// decode.rs `read_intra_mode` reads back and returns early on.
1252+ ///
1253+ /// lane-av1ibc corner-cut, ceiling named: a residual-carrying intrabc
1254+ /// block needs the INTER coefficient tables plus the var-tx tree
1255+ /// decode.rs `decode_block`'s `intrabc_vartx` arm reads; the upgrade path
1256+ /// is to route the block through [`write_tx_syntax_inter`] instead of
1257+ /// returning early here.
1258+ pub dv: Option<(i32, i32)>,
1196 }1259 }
1197 1260
1198 /// A block's luma palette: its base colours (ascending, only the first1261 /// A block's luma palette: its base colours (ascending, only the first
@@ -2199,6 +2262,20 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
2199 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.2262 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
2200 let _cdef_idx = CdefIdxGuard;2263 let _cdef_idx = CdefIdxGuard;
2201 check_blocks(mi_cols, mi_rows)?;2264 check_blocks(mi_cols, mi_rows)?;
2265+ // The DV predictor's own mi grid, per tile exactly as decode.rs builds it
2266+ // per frame (`decode_key_frame_tile_lr`'s `intrabc_mi_grid`): a tile that
2267+ // allows no intrabc arms none and every `record_intrabc_mi` below is a
2268+ // no-op.
2269+ if intrabc_armed() {
2270+ // No `set_tile_bounds`: decode.rs builds this grid for the WHOLE
2271+ // frame with the default (whole-grid) bounds, so the writer must
2272+ // too. `encode_key_frame_inner` only allows intrabc on a
2273+ // single-tile frame, where the two grids are the same grid.
2274+ let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize);
2275+ INTRABC_GRID.with(|g| {
2276+ *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize));
2277+ });
2278+ }
2202 let (cols, rows) = block_grid(mi_cols, mi_rows);2279 let (cols, rows) = block_grid(mi_cols, mi_rows);
2203 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));2280 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
2204 if superblocks.len() != (sb_cols * sb_rows) as usize {2281 if superblocks.len() != (sb_cols * sb_rows) as usize {
@@ -2852,6 +2929,170 @@ pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 {
2852 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,2929 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
2853 /// the angle a directional mode is steered by, and its chroma mode. Hands back2930 /// the angle a directional mode is steered by, and its chroma mode. Hands back
2854 /// the luma mode, which is what the blocks beside it read.2931 /// the luma mode, which is what the blocks beside it read.
2932+/// The DV predictor decode.rs `read_intrabc_dv` derives, mirrored line for
2933+/// line off the writer's own copy of the intrabc mi grid: the `INTRA_FRAME`
2934+/// stack's `nearest_mv` (or `near_mv` when that is zero), or -- when both are
2935+/// -- `av1_find_ref_dv`'s fallback one superblock up, or 256 pixels plus one
2936+/// superblock to the left on the tile's first superblock row, then floored to
2937+/// full pel. Returns `(0, 0)` when no grid is armed, which no `allow_intrabc`
2938+/// tile ever reaches.
2939+fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) {
2940+ const INTRABC_DELAY_PIXELS: i32 = 256;
2941+ let n4 = side / MI;
2942+ let stack_pred = INTRABC_GRID.with(|g| {
2943+ let g = g.borrow();
2944+ g.as_ref().map(|(grid, mi_cols, mi_rows)| {
2945+ let stack = crate::mvstack::find_mv_stack(
2946+ grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
2947+ *mi_cols, *mi_rows,
2948+ );
2949+ if stack.nearest_mv == (0, 0) {
2950+ stack.near_mv
2951+ } else {
2952+ stack.nearest_mv
2953+ }
2954+ })
2955+ });
2956+ let mut pred = stack_pred.unwrap_or((0, 0));
2957+ if pred == (0, 0) {
2958+ // 64x64 superblocks: the only size this encoder's sequence header
2959+ // signals (`use_128x128_superblock: false`), so `mib_size` is 16 mi.
2960+ // The tile row start is 0, exactly as decode.rs `read_intrabc_dv`
2961+ // takes it -- both are written for the single-tile-row streams this
2962+ // encoder produces.
2963+ let sb_mi = 16i32;
2964+ let sb_px = sb_mi * MI as i32;
2965+ pred = if (mi_r as i32) < sb_mi {
2966+ (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
2967+ } else {
2968+ (-sb_px * 8, 0)
2969+ };
2970+ }
2971+ ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8)
2972+}
2973+
2974+/// Publishes one coded block into [`INTRABC_GRID`], mirroring decode.rs
2975+/// `record_intrabc_mi`: every block contributes its size, an intrabc one also
2976+/// its DV as an `INTRA_FRAME` candidate.
2977+fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
2978+ INTRABC_GRID.with(|g| {
2979+ let mut g = g.borrow_mut();
2980+ let Some((grid, _, _)) = g.as_mut() else {
2981+ return;
2982+ };
2983+ let info = crate::mvstack::MiInfo {
2984+ is_inter: dv.is_some(),
2985+ ref_frame: 0,
2986+ ref_frame1: crate::mvstack::NO_REF1,
2987+ mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))),
2988+ mv1: (0, 0),
2989+ is_new_mv: dv.is_some(),
2990+ is_global_mv0: false,
2991+ is_global_mv1: false,
2992+ size: n4 as u8,
2993+ size_h: n4 as u8,
2994+ };
2995+ for r in mi_r..mi_r + n4 {
2996+ for c in mi_c..mi_c + n4 {
2997+ grid.set(r, c, info);
2998+ }
2999+ }
3000+ });
3001+}
3002+
3003+/// One full-pel block-vector component, [`write_mv_component`]'s
3004+/// `force_integer_mv` twin: decode.rs `read_mv_component` infers `mv_fr`/
3005+/// `mv_class0_fr` as 3 and the high-precision bit as 1 under
3006+/// `force_integer_mv`, so neither symbol is written here -- writing them
3007+/// would leave the decoder two symbols behind from this block on.
3008+fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
3009+ let mag = diff.unsigned_abs() as i32;
3010+ if mag % 8 != 0 {
3011+ return Err(Error::unsupported(
3012+ "AV1 tile",
3013+ "a block vector is coded at full-pel precision only",
3014+ ));
3015+ }
3016+ enc.symbol(usize::from(diff < 0), &mut c.sign);
3017+ let z = mag - 1;
3018+ let class = mv_class_of(z);
3019+ enc.symbol(class, &mut c.class);
3020+ let local = z - mv_class_base(class);
3021+ if class == 0 {
3022+ enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit);
3023+ } else {
3024+ let d = local >> 3;
3025+ for i in 0..class {
3026+ enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
3027+ }
3028+ }
3029+ Ok(())
3030+}
3031+
3032+/// One intrabc block's DV as a residual against [`intrabc_dv_pred`], off the
3033+/// `dv` nmv context (decode.rs `read_intrabc_dv` -> `read_mv`).
3034+fn write_dv(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, dv: (i32, i32), pred: (i32, i32)) -> Result<()> {
3035+ let diff = (dv.0 - pred.0, dv.1 - pred.1);
3036+ let joint = match (diff.0 != 0, diff.1 != 0) {
3037+ (false, false) => 0,
3038+ (false, true) => 1,
3039+ (true, false) => 2,
3040+ (true, true) => 3,
3041+ };
3042+ enc.symbol(joint, &mut cdfs.dv_joint);
3043+ if diff.0 != 0 {
3044+ write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?;
3045+ }
3046+ if diff.1 != 0 {
3047+ write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?;
3048+ }
3049+ Ok(())
3050+}
3051+
3052+/// The mode-info half of an intrabc block (decode.rs `read_intra_mode`'s
3053+/// early return): `skip`, `cdef_idx`, `use_intrabc` and the DV, then nothing
3054+/// -- no y/uv mode, no angle delta, no palette, and (because it is skipped)
3055+/// no transform size and no residual. Publishes the block into every
3056+/// neighbour band an ordinary block leaves behind, at the DC_PRED/uncoded/
3057+/// skipped state a decoder reads back for it.
3058+fn write_intrabc_block(
3059+ enc: &mut SymbolEncoder,
3060+ cdfs: &mut Cdfs,
3061+ neighbours: &mut Neighbours,
3062+ dv: (i32, i32),
3063+ mi: (usize, usize),
3064+ side: usize,
3065+) -> Result<()> {
3066+ let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
3067+ enc.symbol(1, &mut cdfs.skip[skip_ctx]);
3068+ write_cdef_idx(enc, mi, true);
3069+ enc.symbol(1, &mut cdfs.intrabc);
3070+ write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?;
3071+ note_intrabc(dv);
3072+ // The bands: DC_PRED mode (what the decoder forces), no coefficients
3073+ // anywhere (skip), the block's own side for the partition context, the
3074+ // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm)
3075+ // for the deblock grid, and `skip` itself for the next block's skip
3076+ // context.
3077+ // One zero level per plane: `neighbour_state` reads `grid[0]` for the DC
3078+ // sign vote, and a skipped block leaves every context cleared.
3079+ let empty: [Vec<i32>; 3] = [vec![0], vec![0], vec![0]];
3080+ for cell in 0..(side / SUB).max(1) {
3081+ let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI));
3082+ neighbours.above_mode[c + cell] = DC_PRED;
3083+ neighbours.left_mode[r + cell] = DC_PRED;
3084+ neighbours.above_side[c + cell] = side;
3085+ neighbours.left_side[r + cell] = side;
3086+ }
3087+ neighbours.record_mi_planes(mi, side, &empty, true);
3088+ neighbours.record_tx(mi, side, side.min(64));
3089+ for cell in 0..side / MI {
3090+ neighbours.above_skip[mi.1 + cell] = true;
3091+ neighbours.left_skip[mi.0 + cell] = true;
3092+ }
3093+ Ok(())
3094+}
3095+
2855 fn write_intra_mode(3096 fn write_intra_mode(
2856 enc: &mut SymbolEncoder,3097 enc: &mut SymbolEncoder,
2857 cdfs: &mut Cdfs,3098 cdfs: &mut Cdfs,
@@ -2868,8 +3109,18 @@ fn write_intra_mode(
2868 side: usize,3109 side: usize,
2869 ) -> usize {3110 ) -> usize {
2870 let mode = usize::from(block.mode);3111 let mode = usize::from(block.mode);
2871- enc.symbol(0, &mut cdfs.skip[0]);3112+ // `av1_get_skip_txfm_context` (decode.rs `Neighbours::skip_txfm_ctx`):
3113+ // above + left. Every block this writer codes outside an `allow_intrabc`
3114+ // frame is unskipped, so both bands stay false and this stays 0 -- the
3115+ // literal every stream before this lane was written with.
3116+ let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
3117+ enc.symbol(0, &mut cdfs.skip[skip_ctx]);
2872 write_cdef_idx(enc, mi, false);3118 write_cdef_idx(enc, mi, false);
3119+ // `read_intrabc_info` (spec 5.11.13): the flag is read for EVERY intra
3120+ // block of an `allow_intrabc` frame, not only the ones that use it.
3121+ if intrabc_armed() {
3122+ enc.symbol(0, &mut cdfs.intrabc);
3123+ }
2873 enc.symbol(3124 enc.symbol(
2874 mode,3125 mode,
2875 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],3126 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
@@ -3070,6 +3321,11 @@ fn write_block(
3070 ) -> Result<()> {3321 ) -> Result<()> {
3071 let (r, c) = at;3322 let (r, c) = at;
3072 let at_mi = (r * (SUB / MI), c * (SUB / MI));3323 let at_mi = (r * (SUB / MI), c * (SUB / MI));
3324+ if let Some(dv) = block.dv {
3325+ write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?;
3326+ record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv));
3327+ return Ok(());
3328+ }
3073 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);3329 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
3074 let mode = write_intra_mode(3330 let mode = write_intra_mode(
3075 enc,3331 enc,
@@ -3109,9 +3365,24 @@ fn write_block(
3109 tx_select,3365 tx_select,
3110 );3366 );
3111 neighbours.record_planes(at, side, mode, grids, !split);3367 neighbours.record_planes(at, side, mode, grids, !split);
3368+ clear_skip_band(neighbours, at_mi, side);
3369+ record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None);
3112 Ok(())3370 Ok(())
3113 }3371 }
3114 3372
3373+/// An unskipped block's own `skip` publication: only an `allow_intrabc`
3374+/// frame ever sets these bands, so a frame without one leaves them exactly
3375+/// as they were before this lane (all false).
3376+fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) {
3377+ if !intrabc_armed() {
3378+ return;
3379+ }
3380+ for cell in 0..side / MI {
3381+ neighbours.above_skip[mi.1 + cell] = false;
3382+ neighbours.left_skip[mi.0 + cell] = false;
3383+ }
3384+}
3385+
3115 /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own3386 /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
3116 /// luma transform and 4x4 chroma transforms, coded exactly like3387 /// luma transform and 4x4 chroma transforms, coded exactly like
3117 /// [`write_block`] but reading its intra-mode context from the *enclosing*3388 /// [`write_block`] but reading its intra-mode context from the *enclosing*
@@ -3135,6 +3406,11 @@ fn write_leaf8(
3135 all_scans: &[Vec<u16>; 4],3406 all_scans: &[Vec<u16>; 4],
3136 ) -> Result<usize> {3407 ) -> Result<usize> {
3137 let (r, c) = outer_at;3408 let (r, c) = outer_at;
3409+ if let Some(dv) = block.dv {
3410+ write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?;
3411+ record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv));
3412+ return Ok(DC_PRED);
3413+ }
3138 let mut above_mode = neighbours.above_mode[c];3414 let mut above_mode = neighbours.above_mode[c];
3139 let mut left_mode = neighbours.left_mode[r];3415 let mut left_mode = neighbours.left_mode[r];
3140 // The previous leaf sits directly above (same column, two mi rows up)3416 // The previous leaf sits directly above (same column, two mi rows up)
@@ -3184,6 +3460,8 @@ fn write_leaf8(
3184 tx_select,3460 tx_select,
3185 );3461 );
3186 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);3462 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
3463+ clear_skip_band(neighbours, leaf_mi, 8);
3464+ record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None);
3187 Ok(mode)3465 Ok(mode)
3188 }3466 }
3189 3467