forge
Explore
Log in

Don't you dare go Hollow

Intra block copy on screen-detected key frames

Browse files at this commit

41b28fd97b483a0736ca4e93c73fc07d4f442025Ahmet Kaan GümüşParent: 691f69e
  • feat
    • intra block copy on screen-detected key frames
Show full message
feat(av1): intra block copy on screen-detected key frames
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+481 -5
@@ -630,6 +630,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
630 next_cdfs: encoded.next_cdfs.clone(),630 next_cdfs: encoded.next_cdfs.clone(),
631 loop_filter: encoded.loop_filter,631 loop_filter: encoded.loop_filter,
632 loop_restoration: encoded.loop_restoration,632 loop_restoration: encoded.loop_restoration,
633+ allow_intrabc: encoded.allow_intrabc,
633 cdef: encoded.cdef,634 cdef: encoded.cdef,
634 }635 }
635 }636 }
@@ -709,6 +710,23 @@ pub struct Encoded {
709 /// filters themselves are coded in `tile`, so a decode of it under a710 /// filters themselves are coded in `tile`, so a decode of it under a
710 /// stale `RESTORE_NONE` header desyncs at the first superblock.711 /// stale `RESTORE_NONE` header desyncs at the first superblock.
711 pub(crate) loop_restoration: LoopRestorationParams,712 pub(crate) loop_restoration: LoopRestorationParams,
713+ /// This frame header's `allow_intrabc` -- every intra block of the tile
714+ /// carries a `use_intrabc` symbol under it, so a raw tile decode that
715+ /// guessed `false` would desync at the first block (same class as
716+ /// `screen`/`tx_select`).
717+ pub(crate) allow_intrabc: bool,
718+}
719+
720+thread_local! {
721+ /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
722+ /// for on the last key frame encoded on this thread -- read by the gates,
723+ /// which print it beside the block counts (class `gate-blind-to-feature`).
724+ static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
725+}
726+
727+/// [`IBC_SHARE`] for the last key frame encoded on this thread.
728+pub(crate) fn intrabc_source_share() -> f64 {
729+ IBC_SHARE.with(std::cell::Cell::get)
712 }730 }
713 731
714 thread_local! {732 thread_local! {
@@ -2444,6 +2462,385 @@ fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
2444 }2462 }
2445 2463
2446 #[allow(clippy::too_many_arguments)]2464 #[allow(clippy::too_many_arguments)]
2465+// ---------------------------------------------------------------------------
2466+// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
2467+// validity). A key frame that detected screen content and finds enough exact
2468+// repeats in its own source sets `allow_intrabc`, which the spec forces every
2469+// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
2470+// its place when the copied blocks pay back the deblock/CDEF/LR the frame
2471+// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
2472+// ---------------------------------------------------------------------------
2473+
2474+/// Whether intra block copy is offered at all. On by default; off on a frame
2475+/// that detected no screen content, and off entirely under `EC_AV1_INTRABC=0`.
2476+fn intrabc_enabled() -> bool {
2477+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2478+ *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() != Some("0"))
2479+}
2480+
2481+/// How many of a screen frame's 16x16 blocks must have an exact repeat
2482+/// somewhere else in the source before `allow_intrabc` is worth the in-loop
2483+/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
2484+/// constant class: `probe_intrabc_threshold` measures the arm at several
2485+/// values.
2486+fn intrabc_pct() -> usize {
2487+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2488+ *N.get_or_init(|| {
2489+ std::env::var("EC_AV1_INTRABC_PCT")
2490+ .ok()
2491+ .and_then(|v| v.parse().ok())
2492+ .unwrap_or(10)
2493+ })
2494+}
2495+
2496+/// The pixel grid intrabc source positions are hashed on
2497+/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
2498+/// which keeps the block-hash table (and so the search) linear in the frame
2499+/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
2500+/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
2501+/// bilinear interpolation decode.rs applies but this encoder does not.
2502+fn intrabc_step() -> usize {
2503+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2504+ *N.get_or_init(|| {
2505+ let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
2506+ .ok()
2507+ .and_then(|v| v.parse().ok())
2508+ .unwrap_or(4);
2509+ if n % 2 == 0 { n.max(2) } else { 4 }
2510+ })
2511+}
2512+
2513+/// The side of the luma square the block-hash table is keyed on.
2514+const IBC_HASH: usize = 16;
2515+
2516+/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
2517+/// the current one the source's bottom-right corner must already be.
2518+const INTRABC_DELAY_SB64: i32 = 4;
2519+
2520+/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
2521+fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
2522+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
2523+ for row in 0..IBC_HASH {
2524+ let base = (y + row) * width + x;
2525+ for &v in &plane[base..base + IBC_HASH] {
2526+ h ^= u64::from(v);
2527+ h = h.wrapping_mul(0x100_0000_01b3);
2528+ }
2529+ }
2530+ h
2531+}
2532+
2533+/// Every `intrabc_step()`-aligned position of `plane` inside
2534+/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
2535+fn ibc_index(
2536+ table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
2537+ plane: &[u8],
2538+ width: usize,
2539+ (x0, y0): (usize, usize),
2540+ (x1, y1): (usize, usize),
2541+) {
2542+ let step = intrabc_step();
2543+ if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
2544+ return;
2545+ }
2546+ let mut y = y0.next_multiple_of(step);
2547+ while y + IBC_HASH <= y1 {
2548+ let mut x = x0.next_multiple_of(step);
2549+ while x + IBC_HASH <= x1 {
2550+ table
2551+ .entry(ibc_hash(plane, width, x, y))
2552+ .or_default()
2553+ .push((x as u32, y as u32));
2554+ x += step;
2555+ }
2556+ y += step;
2557+ }
2558+}
2559+
2560+/// Whether `screen`-detected source `y` repeats itself enough to be worth
2561+/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
2562+/// content appears at some other position, against [`intrabc_pct`]. Returns
2563+/// the share as well, for the gate's own print.
2564+fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
2565+ if true_width < 4 * 64 || true_height < 2 * 64 {
2566+ return (false, 0.0);
2567+ }
2568+ let mut table = std::collections::HashMap::new();
2569+ ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
2570+ let (mut total, mut matched) = (0usize, 0usize);
2571+ let mut by = 0;
2572+ while by + IBC_HASH <= true_height {
2573+ let mut bx = 0;
2574+ while bx + IBC_HASH <= true_width {
2575+ total += 1;
2576+ if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
2577+ if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
2578+ matched += 1;
2579+ }
2580+ }
2581+ bx += IBC_HASH;
2582+ }
2583+ by += IBC_HASH;
2584+ }
2585+ let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
2586+ (share * 100.0 >= intrabc_pct() as f64, share)
2587+}
2588+
2589+/// One tile's intrabc search state: a block-hash table over the part of the
2590+/// tile's own reconstruction that is already final (whole superblock rows --
2591+/// the in-loop filters are off on this frame, so a coded superblock row never
2592+/// changes again), plus the last DV chosen, which the RD price uses as its
2593+/// predictor estimate.
2594+struct Ibc {
2595+ table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
2596+ /// The reconstruction row this table has been filled up to.
2597+ filled_to: usize,
2598+ /// The tile's own luma rect, in samples.
2599+ tile: (usize, usize, usize, usize),
2600+ /// The DV the previous intrabc block of this tile took -- the *estimate*
2601+ /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
2602+ /// against. The writer computes the true predictor off its own mi grid
2603+ /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
2604+ /// a slightly mispriced candidate, never a wrong bitstream.
2605+ last_dv: Option<(i32, i32)>,
2606+ /// How many blocks took intrabc, and how many hash lookups found at least
2607+ /// one valid candidate -- the gate's own fire counts.
2608+ hits: usize,
2609+ lookups: usize,
2610+ found: usize,
2611+}
2612+
2613+impl Ibc {
2614+ fn new(tile: (usize, usize, usize, usize)) -> Self {
2615+ Self {
2616+ table: std::collections::HashMap::new(),
2617+ filled_to: tile.1,
2618+ tile,
2619+ last_dv: None,
2620+ hits: 0,
2621+ lookups: 0,
2622+ found: 0,
2623+ }
2624+ }
2625+
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+
2646+ /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
2647+ /// (1/8 pel), with this lane's own extra restriction on top: the source
2648+ /// must lie entirely in a COMPLETED superblock row, which is exactly the
2649+ /// region [`Self::fill_to`] indexes and a strict subset of what the spec
2650+ /// allows. corner-cut, ceiling named: same-superblock-row sources (the
2651+ /// wavefront's own diagonal) are legal and not searched; the upgrade path
2652+ /// is to index the current row's finished superblocks too.
2653+ fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
2654+ let (dr, dc) = (dv.0 / 8, dv.1 / 8);
2655+ if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
2656+ return false;
2657+ }
2658+ let (tx0, ty0, tx1, ty1) = (
2659+ self.tile.0 as i32,
2660+ self.tile.1 as i32,
2661+ self.tile.2 as i32,
2662+ self.tile.3 as i32,
2663+ );
2664+ let (sx, sy) = (x as i32 + dc, y as i32 + dr);
2665+ let (w, h) = (w as i32, h as i32);
2666+ if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
2667+ return false;
2668+ }
2669+ let active_sb_row = (y as i32 - ty0) >> 6;
2670+ let active_sb_col = (x as i32 - tx0) >> 6;
2671+ let src_sb_row = (sy + h - 1 - ty0) >> 6;
2672+ let src_sb_col = (sx + w - 1 - tx0) >> 6;
2673+ // This lane's own restriction (see the doc comment).
2674+ if src_sb_row >= active_sb_row {
2675+ return false;
2676+ }
2677+ let total = ((tx1 - tx0 - 1) >> 6) + 1;
2678+ if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64
2679+ {
2680+ return false;
2681+ }
2682+ // libaom's wavefront: only the top-left cone of the frame is legal.
2683+ let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row);
2684+ src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf
2685+ }
2686+}
2687+
2688+/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
2689+/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
2690+/// infers rather than codes.
2691+fn dv_component_bits(diff: i32) -> f64 {
2692+ let z = diff.unsigned_abs() as i32 - 1;
2693+ let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
2694+ let class = mv_class_of(z);
2695+ bits += symbol_bits(&cdf::MV_CLASS, class);
2696+ let local = z - mv_class_base(class);
2697+ if class == 0 {
2698+ bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
2699+ } else {
2700+ let d = local >> 3;
2701+ for i in 0..class {
2702+ bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
2703+ }
2704+ }
2705+ bits
2706+}
2707+
2708+/// What one block vector costs against `pred`, plus the `skip` and
2709+/// `use_intrabc` flags the block carries and the ordinary intra block does
2710+/// not pay in this currency.
2711+fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
2712+ let diff = (dv.0 - pred.0, dv.1 - pred.1);
2713+ let joint = match (diff.0 != 0, diff.1 != 0) {
2714+ (false, false) => 0,
2715+ (false, true) => 1,
2716+ (true, false) => 2,
2717+ (true, true) => 3,
2718+ };
2719+ let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
2720+ if diff.0 != 0 {
2721+ bits += dv_component_bits(diff.0);
2722+ }
2723+ if diff.1 != 0 {
2724+ bits += dv_component_bits(diff.1);
2725+ }
2726+ bits
2727+}
2728+
2729+/// The squared error of copying the `side`-square block at `(sx, sy)` of each
2730+/// plane's reconstruction onto the source block at `(x, y)`, luma and both
2731+/// chroma planes together -- what an intrabc block's whole (residual-free)
2732+/// distortion is.
2733+fn ibc_sse(
2734+ luma: &Plane,
2735+ chroma: &[Plane; 2],
2736+ (x, y): (usize, usize),
2737+ (sx, sy): (usize, usize),
2738+ side: usize,
2739+) -> f64 {
2740+ let mut sse = 0.0f64;
2741+ for row in 0..side {
2742+ let src = &luma.source[(y + row) * luma.width + x..][..side];
2743+ let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..side];
2744+ for (&s, &r) in src.iter().zip(rec) {
2745+ let d = f64::from(i32::from(s) - i32::from(r));
2746+ sse += d * d;
2747+ }
2748+ }
2749+ let half = side / 2;
2750+ for plane in chroma {
2751+ for row in 0..half {
2752+ let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..half];
2753+ let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..half];
2754+ for (&s, &r) in src.iter().zip(rec) {
2755+ let d = f64::from(i32::from(s) - i32::from(r));
2756+ sse += d * d;
2757+ }
2758+ }
2759+ }
2760+ sse
2761+}
2762+
2763+/// Copies the `side`-square block at `(sx, sy)` of each plane's
2764+/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
2765+/// since it carries no residual (`skip`). Full-pel in both planes by
2766+/// construction ([`intrabc_step`] keeps every DV even), which is what makes
2767+/// this a plain copy where decode.rs runs the bilinear kernel over the same
2768+/// samples.
2769+fn ibc_commit(
2770+ luma: &mut Plane,
2771+ chroma: &mut [Plane; 2],
2772+ (x, y): (usize, usize),
2773+ (sx, sy): (usize, usize),
2774+ side: usize,
2775+) {
2776+ for row in 0..side {
2777+ let from = (sy + row) * luma.width + sx;
2778+ let to = (y + row) * luma.width + x;
2779+ let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
2780+ luma.reconstruction[to..to + side].copy_from_slice(&copied);
2781+ }
2782+ let half = side / 2;
2783+ for plane in chroma {
2784+ for row in 0..half {
2785+ let from = (sy / 2 + row) * plane.width + sx / 2;
2786+ let to = (y / 2 + row) * plane.width + x / 2;
2787+ let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
2788+ plane.reconstruction[to..to + half].copy_from_slice(&copied);
2789+ }
2790+ }
2791+}
2792+
2793+/// Searches this block's own DV: every hash-table position whose 16x16 luma
2794+/// square equals the block's source square, plus the previous block's DV as a
2795+/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
2796+/// the winning `(dv, cost)`, or `None` when nothing valid was found.
2797+fn ibc_search(
2798+ ibc: &mut Ibc,
2799+ luma: &Plane,
2800+ chroma: &[Plane; 2],
2801+ (x, y): (usize, usize),
2802+ side: usize,
2803+ lambda: f64,
2804+) -> Option<((i32, i32), f64, (usize, usize))> {
2805+ let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
2806+ let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
2807+ let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
2808+ let dv = (
2809+ (sy as i32 - y as i32) * 8,
2810+ (sx as i32 - x as i32) * 8,
2811+ );
2812+ if !ibc.dv_valid(x, y, side, side, dv) {
2813+ return;
2814+ }
2815+ let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
2816+ if best.as_ref().is_none_or(|b| cost < b.1) {
2817+ *best = Some((dv, cost, (sx, sy)));
2818+ }
2819+ };
2820+ ibc.lookups += 1;
2821+ 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.
2824+ let hits: Vec<(u32, u32)> = ibc
2825+ .table
2826+ .get(&key)
2827+ .map(|h| h.iter().rev().take(16).copied().collect())
2828+ .unwrap_or_default();
2829+ for (hx, hy) in hits {
2830+ consider(&*ibc, hx as usize, hy as usize, &mut best);
2831+ }
2832+ if let Some(dv) = ibc.last_dv {
2833+ let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
2834+ if sx >= 0 && sy >= 0 {
2835+ consider(&*ibc, sx as usize, sy as usize, &mut best);
2836+ }
2837+ }
2838+ if best.is_some() {
2839+ ibc.found += 1;
2840+ }
2841+ best
2842+}
2843+
2447 fn code_square(2844 fn code_square(
2448 luma: &mut Plane,2845 luma: &mut Plane,
2449 chroma: &mut [Plane; 2],2846 chroma: &mut [Plane; 2],
@@ -2454,7 +2851,10 @@ fn code_square(
2454 // The frame header's `tx_mode == TxMode::Select`: the block then searches2851 // The frame header's `tx_mode == TxMode::Select`: the block then searches
2455 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one2852 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
2456 // transform over its whole side.2853 // transform over its whole side.
2457- tx_select: bool, fctx: &crate::decode::FrameCtx,2854+ tx_select: bool,
2855+ // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
2856+ // header did not set `allow_intrabc`.
2857+ ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx,
2458 ) -> (BlockCoeffs, f64) {2858 ) -> (BlockCoeffs, f64) {
2459 let (luma_set, chroma_set) = if side == BLOCK {2859 let (luma_set, chroma_set) = if side == BLOCK {
2460 (TxbSet::Luma32, TxbSet::Chroma16)2860 (TxbSet::Luma32, TxbSet::Chroma16)
@@ -2558,6 +2958,29 @@ fn code_square(
2558 let ([u, v], uv_mode, chroma_cost, palette_uv) =2958 let ([u, v], uv_mode, chroma_cost, palette_uv) =
2559 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);2959 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
2560 cost += chroma_cost;2960 cost += chroma_cost;
2961+
2962+ // The intrabc arm is priced against the WHOLE block -- luma and both
2963+ // chroma planes, residual-free -- so it is compared after the chroma
2964+ // search has added its own cost, not against the luma decision alone.
2965+ if let Some(ibc) = ibc {
2966+ if let Some((dv, cost_ibc, src)) =
2967+ ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
2968+ {
2969+ if cost_ibc < cost {
2970+ ibc_commit(luma, chroma, (x, y), src, side);
2971+ ibc.last_dv = Some(dv);
2972+ ibc.hits += 1;
2973+ return (
2974+ BlockCoeffs {
2975+ skip: true,
2976+ dv: Some(dv),
2977+ ..BlockCoeffs::default()
2978+ },
2979+ cost_ibc,
2980+ );
2981+ }
2982+ }
2983+ }
2561 (2984 (
2562 BlockCoeffs {2985 BlockCoeffs {
2563 u,2986 u,
@@ -2824,6 +3247,7 @@ fn code_square_inter(
2824 search,3247 search,
2825 mode_bits,3248 mode_bits,
2826 tx_select() && tx_select_inter(),3249 tx_select() && tx_select_inter(),
3250+ None,
2827 fctx,3251 fctx,
2828 );3252 );
2829 let luma_set = if side == 8 {3253 let luma_set = if side == 8 {
@@ -3037,6 +3461,7 @@ fn code_square_inter(
3037 uv_mode: DC_PRED,3461 uv_mode: DC_PRED,
3038 skip: skip_new,3462 skip: skip_new,
3039 eight: None,3463 eight: None,
3464+ dv: None,
3040 palette: None,3465 palette: None,
3041 palette_uv: None,3466 palette_uv: None,
3042 tx_depth,3467 tx_depth,
@@ -3075,6 +3500,7 @@ fn code_square_inter(
3075 uv_mode: DC_PRED,3500 uv_mode: DC_PRED,
3076 skip,3501 skip,
3077 eight: None,3502 eight: None,
3503+ dv: None,
3078 palette: None,3504 palette: None,
3079 palette_uv: None,3505 palette_uv: None,
3080 tx_depth,3506 tx_depth,
@@ -3721,8 +4147,30 @@ pub(crate) fn encode_key_frame_inner(
3721 (picture.height).min(render.1),4147 (picture.height).min(render.1),
3722 );4148 );
3723 arm_seq_screen(screen);4149 arm_seq_screen(screen);
4150+ // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
4151+ // forces deblocking, CDEF and loop restoration OFF for this frame
4152+ // (frame.rs:194/210/252/272), so it is only set when the source repeats
4153+ // itself enough for the copied blocks to pay that back
4154+ // ([`intrabc_worth_it`]).
4155+ // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
4156+ // grid across every tile while this writer builds one per tile, so a
4157+ // multi-tile allow_intrabc frame would predict its DVs off a different
4158+ // grid than the decoder does. corner-cut, ceiling named: the upgrade
4159+ // path is a frame-scoped grid shared by the tile writers.
4160+ let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
4161+ intrabc_worth_it(
4162+ &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
4163+ picture.width,
4164+ picture.width.min(render.0),
4165+ picture.height.min(render.1),
4166+ )
4167+ } else {
4168+ (false, 0.0)
4169+ };
4170+ IBC_SHARE.with(|c| c.set(ibc_share));
3724 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;4171 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
3725 header.allow_screen_content_tools = screen;4172 header.allow_screen_content_tools = screen;
4173+ header.allow_intrabc = allow_intrabc;
3726 header.render_width = render.0 as u32;4174 header.render_width = render.0 as u32;
3727 header.render_height = render.1 as u32;4175 header.render_height = render.1 as u32;
3728 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split4176 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
@@ -3847,8 +4295,22 @@ pub(crate) fn encode_key_frame_inner(
3847 clip_planes_to_tile(&mut luma, &mut chroma, rect);4295 clip_planes_to_tile(&mut luma, &mut chroma, rect);
3848 let mut above_mode = vec![DC_PRED; cols * 2];4296 let mut above_mode = vec![DC_PRED; cols * 2];
3849 let mut left_mode = vec![DC_PRED; rows * 2];4297 let mut left_mode = vec![DC_PRED; rows * 2];
4298+ 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+ ))
4305+ });
3850 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();4306 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
3851 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {4307 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+ }
3852 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {4314 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
3853 let mut modes = Vec::with_capacity(4);4315 let mut modes = Vec::with_capacity(4);
3854 // The quadrants of a superblock are coded in the order the decoder4316 // The quadrants of a superblock are coded in the order the decoder
@@ -3934,7 +4396,8 @@ pub(crate) fn encode_key_frame_inner(
3934 BLOCK,4396 BLOCK,
3935 &search,4397 &search,
3936 &mode_bits(above_mode[c0], left_mode[r0]),4398 &mode_bits(above_mode[c0], left_mode[r0]),
3937- tx_select, fctx,4399+ tx_select,
4400+ ibc.as_mut(), fctx,
3938 );4401 );
3939 cost_whole += search.lambda * partition_bits(BLOCK, false);4402 cost_whole += search.lambda * partition_bits(BLOCK, false);
3940 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);4403 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
@@ -3968,7 +4431,8 @@ pub(crate) fn encode_key_frame_inner(
3968 SUB,4431 SUB,
3969 &search,4432 &search,
3970 &mode_bits(above_mode[sc], left_mode[sr]),4433 &mode_bits(above_mode[sc], left_mode[sr]),
3971- tx_select, fctx,4434+ tx_select,
4435+ ibc.as_mut(), fctx,
3972 );4436 );
3973 cost_split += cost;4437 cost_split += cost;
3974 split_modes.push(block.mode);4438 split_modes.push(block.mode);
@@ -4000,7 +4464,8 @@ pub(crate) fn encode_key_frame_inner(
4000 8,4464 8,
4001 &search,4465 &search,
4002 &leaf_mode_bits,4466 &leaf_mode_bits,
4003- tx_select, fctx,4467+ tx_select,
4468+ None, fctx,
4004 );4469 );
4005 cost_split += cost;4470 cost_split += cost;
4006 split_modes.push(leaf.mode);4471 split_modes.push(leaf.mode);
@@ -4099,6 +4564,7 @@ pub(crate) fn encode_key_frame_inner(
4099 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());4564 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4100 let mut cdfs = start_cdfs.0.clone();4565 let mut cdfs = start_cdfs.0.clone();
4101 crate::tile::arm_screen(screen);4566 crate::tile::arm_screen(screen);
4567+ crate::tile::arm_intrabc(allow_intrabc);
4102 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(4568 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
4103 mi_cols,4569 mi_cols,
4104 mi_rows,4570 mi_rows,
@@ -4123,7 +4589,11 @@ pub(crate) fn encode_key_frame_inner(
4123 &mut luma,4589 &mut luma,
4124 &mut chroma,4590 &mut chroma,
4125 [&picture_y8, &picture_u8, &picture_v8],4591 [&picture_y8, &picture_u8, &picture_v8],
4126- true,4592+ // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
4593+ // and loop restoration off and codes none of their parameters
4594+ // (frame.rs:194/210/252/272) -- there is no filter to search for, and
4595+ // the encoder's reconstruction is already what a decoder produces.
4596+ !allow_intrabc,
4127 &mut tiles,4597 &mut tiles,
4128 search.lambda,4598 search.lambda,
4129 fctx,4599 fctx,
@@ -4184,6 +4654,7 @@ pub(crate) fn encode_key_frame_inner(
4184 loop_filter: header.loop_filter,4654 loop_filter: header.loop_filter,
4185 cdef: header.cdef,4655 cdef: header.cdef,
4186 loop_restoration: header.loop_restoration,4656 loop_restoration: header.loop_restoration,
4657+ allow_intrabc,
4187 })4658 })
4188 }4659 }
4189 4660
@@ -5383,6 +5854,7 @@ fn search_inter_block(
5383 skip: best.skip,5854 skip: best.skip,
5384 inter: best.inter,5855 inter: best.inter,
5385 eight: None,5856 eight: None,
5857+ dv: None,
5386 palette: None,5858 palette: None,
5387 palette_uv: None,5859 palette_uv: None,
5388 tx_depth: 0,5860 tx_depth: 0,
@@ -6298,6 +6770,9 @@ pub(crate) fn encode_inter_frame(
6298 loop_filter: header.loop_filter,6770 loop_filter: header.loop_filter,
6299 cdef: header.cdef,6771 cdef: header.cdef,
6300 loop_restoration: header.loop_restoration,6772 loop_restoration: header.loop_restoration,
6773+ // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
6774+ // intra frames only).
6775+ allow_intrabc: false,
6301 })6776 })
6302 }6777 }
6303 6778
@@ -6942,6 +7417,7 @@ mod tests {
6942 uv_mode: 0,7417 uv_mode: 0,
6943 skip: false,7418 skip: false,
6944 eight: None,7419 eight: None,
7420+ dv: None,
6945 palette: None,7421 palette: None,
6946 palette_uv: None,7422 palette_uv: None,
6947 tx_depth: 0,7423 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+276 -1
@@ -314,6 +314,53 @@ 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+pub(crate) fn take_intrabc_hits() -> [usize; 7] {
361+ std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
362+}
363+
317 thread_local! {364 thread_local! {
318 /// This frame header's own `reference_select` bit (spec 5.9.22), armed365 /// 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 than366 /// the same way `arm_sign_bias` arms the sign-bias table rather than
@@ -673,6 +720,8 @@ impl Drop for CdefIdxGuard {
673 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));720 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
674 SCREEN.with(|c| c.set(false));721 SCREEN.with(|c| c.set(false));
675 REFERENCE_SELECT.with(|c| c.set(false));722 REFERENCE_SELECT.with(|c| c.set(false));
723+ INTRABC.with(|c| c.set(false));
724+ INTRABC_GRID.with(|c| *c.borrow_mut() = None);
676 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));725 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
677 }726 }
678 }727 }
@@ -1178,6 +1227,19 @@ pub struct BlockCoeffs {
1178 /// `luma` then carries the whole block's levels in BLOCK coordinates,1227 /// `luma` then carries the whole block's levels in BLOCK coordinates,
1179 /// which the writer slices per transform unit.1228 /// which the writer slices per transform unit.
1180 pub tx_depth: u8,1229 pub tx_depth: u8,
1230+ /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
1231+ /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
1232+ /// an ordinary intra block. Only a key frame whose header set
1233+ /// `allow_intrabc` ([`arm_intrabc`]) may carry one; the block is then
1234+ /// coded `skip` with no residual, no mode, no palette -- exactly what
1235+ /// decode.rs `read_intra_mode` reads back and returns early on.
1236+ ///
1237+ /// lane-av1ibc corner-cut, ceiling named: a residual-carrying intrabc
1238+ /// block needs the INTER coefficient tables plus the var-tx tree
1239+ /// decode.rs `decode_block`'s `intrabc_vartx` arm reads; the upgrade path
1240+ /// is to route the block through [`write_tx_syntax_inter`] instead of
1241+ /// returning early here.
1242+ pub dv: Option<(i32, i32)>,
1181 }1243 }
1182 1244
1183 /// A block's luma palette: its base colours (ascending, only the first1245 /// A block's luma palette: its base colours (ascending, only the first
@@ -2184,6 +2246,20 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
2184 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.2246 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
2185 let _cdef_idx = CdefIdxGuard;2247 let _cdef_idx = CdefIdxGuard;
2186 check_blocks(mi_cols, mi_rows)?;2248 check_blocks(mi_cols, mi_rows)?;
2249+ // The DV predictor's own mi grid, per tile exactly as decode.rs builds it
2250+ // per frame (`decode_key_frame_tile_lr`'s `intrabc_mi_grid`): a tile that
2251+ // allows no intrabc arms none and every `record_intrabc_mi` below is a
2252+ // no-op.
2253+ if intrabc_armed() {
2254+ // No `set_tile_bounds`: decode.rs builds this grid for the WHOLE
2255+ // frame with the default (whole-grid) bounds, so the writer must
2256+ // too. `encode_key_frame_inner` only allows intrabc on a
2257+ // single-tile frame, where the two grids are the same grid.
2258+ let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize);
2259+ INTRABC_GRID.with(|g| {
2260+ *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize));
2261+ });
2262+ }
2187 let (cols, rows) = block_grid(mi_cols, mi_rows);2263 let (cols, rows) = block_grid(mi_cols, mi_rows);
2188 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));2264 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
2189 if superblocks.len() != (sb_cols * sb_rows) as usize {2265 if superblocks.len() != (sb_cols * sb_rows) as usize {
@@ -2837,6 +2913,168 @@ pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 {
2837 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,2913 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
2838 /// the angle a directional mode is steered by, and its chroma mode. Hands back2914 /// the angle a directional mode is steered by, and its chroma mode. Hands back
2839 /// the luma mode, which is what the blocks beside it read.2915 /// the luma mode, which is what the blocks beside it read.
2916+/// The DV predictor decode.rs `read_intrabc_dv` derives, mirrored line for
2917+/// line off the writer's own copy of the intrabc mi grid: the `INTRA_FRAME`
2918+/// stack's `nearest_mv` (or `near_mv` when that is zero), or -- when both are
2919+/// -- `av1_find_ref_dv`'s fallback one superblock up, or 256 pixels plus one
2920+/// superblock to the left on the tile's first superblock row, then floored to
2921+/// full pel. Returns `(0, 0)` when no grid is armed, which no `allow_intrabc`
2922+/// tile ever reaches.
2923+fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) {
2924+ const INTRABC_DELAY_PIXELS: i32 = 256;
2925+ let n4 = side / MI;
2926+ let stack_pred = INTRABC_GRID.with(|g| {
2927+ let g = g.borrow();
2928+ g.as_ref().map(|(grid, mi_cols, mi_rows)| {
2929+ let stack = crate::mvstack::find_mv_stack(
2930+ grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
2931+ *mi_cols, *mi_rows,
2932+ );
2933+ if stack.nearest_mv == (0, 0) {
2934+ stack.near_mv
2935+ } else {
2936+ stack.nearest_mv
2937+ }
2938+ })
2939+ });
2940+ let mut pred = stack_pred.unwrap_or((0, 0));
2941+ if pred == (0, 0) {
2942+ // 64x64 superblocks: the only size this encoder's sequence header
2943+ // signals (`use_128x128_superblock: false`), so `mib_size` is 16 mi.
2944+ // The tile row start is 0, exactly as decode.rs `read_intrabc_dv`
2945+ // takes it -- both are written for the single-tile-row streams this
2946+ // encoder produces.
2947+ let sb_mi = 16i32;
2948+ let sb_px = sb_mi * MI as i32;
2949+ pred = if (mi_r as i32) < sb_mi {
2950+ (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
2951+ } else {
2952+ (-sb_px * 8, 0)
2953+ };
2954+ }
2955+ ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8)
2956+}
2957+
2958+/// Publishes one coded block into [`INTRABC_GRID`], mirroring decode.rs
2959+/// `record_intrabc_mi`: every block contributes its size, an intrabc one also
2960+/// its DV as an `INTRA_FRAME` candidate.
2961+fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
2962+ INTRABC_GRID.with(|g| {
2963+ let mut g = g.borrow_mut();
2964+ let Some((grid, _, _)) = g.as_mut() else {
2965+ return;
2966+ };
2967+ let info = crate::mvstack::MiInfo {
2968+ is_inter: dv.is_some(),
2969+ ref_frame: 0,
2970+ ref_frame1: crate::mvstack::NO_REF1,
2971+ mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))),
2972+ mv1: (0, 0),
2973+ is_new_mv: dv.is_some(),
2974+ is_global_mv0: false,
2975+ is_global_mv1: false,
2976+ size: n4 as u8,
2977+ size_h: n4 as u8,
2978+ };
2979+ for r in mi_r..mi_r + n4 {
2980+ for c in mi_c..mi_c + n4 {
2981+ grid.set(r, c, info);
2982+ }
2983+ }
2984+ });
2985+}
2986+
2987+/// One full-pel block-vector component, [`write_mv_component`]'s
2988+/// `force_integer_mv` twin: decode.rs `read_mv_component` infers `mv_fr`/
2989+/// `mv_class0_fr` as 3 and the high-precision bit as 1 under
2990+/// `force_integer_mv`, so neither symbol is written here -- writing them
2991+/// would leave the decoder two symbols behind from this block on.
2992+fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
2993+ let mag = diff.unsigned_abs() as i32;
2994+ if mag % 8 != 0 {
2995+ return Err(Error::unsupported(
2996+ "AV1 tile",
2997+ "a block vector is coded at full-pel precision only",
2998+ ));
2999+ }
3000+ enc.symbol(usize::from(diff < 0), &mut c.sign);
3001+ let z = mag - 1;
3002+ let class = mv_class_of(z);
3003+ enc.symbol(class, &mut c.class);
3004+ let local = z - mv_class_base(class);
3005+ if class == 0 {
3006+ enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit);
3007+ } else {
3008+ let d = local >> 3;
3009+ for i in 0..class {
3010+ enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
3011+ }
3012+ }
3013+ Ok(())
3014+}
3015+
3016+/// One intrabc block's DV as a residual against [`intrabc_dv_pred`], off the
3017+/// `dv` nmv context (decode.rs `read_intrabc_dv` -> `read_mv`).
3018+fn write_dv(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, dv: (i32, i32), pred: (i32, i32)) -> Result<()> {
3019+ let diff = (dv.0 - pred.0, dv.1 - pred.1);
3020+ let joint = match (diff.0 != 0, diff.1 != 0) {
3021+ (false, false) => 0,
3022+ (false, true) => 1,
3023+ (true, false) => 2,
3024+ (true, true) => 3,
3025+ };
3026+ enc.symbol(joint, &mut cdfs.dv_joint);
3027+ if diff.0 != 0 {
3028+ write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?;
3029+ }
3030+ if diff.1 != 0 {
3031+ write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?;
3032+ }
3033+ Ok(())
3034+}
3035+
3036+/// The mode-info half of an intrabc block (decode.rs `read_intra_mode`'s
3037+/// early return): `skip`, `cdef_idx`, `use_intrabc` and the DV, then nothing
3038+/// -- no y/uv mode, no angle delta, no palette, and (because it is skipped)
3039+/// no transform size and no residual. Publishes the block into every
3040+/// neighbour band an ordinary block leaves behind, at the DC_PRED/uncoded/
3041+/// skipped state a decoder reads back for it.
3042+fn write_intrabc_block(
3043+ enc: &mut SymbolEncoder,
3044+ cdfs: &mut Cdfs,
3045+ neighbours: &mut Neighbours,
3046+ dv: (i32, i32),
3047+ mi: (usize, usize),
3048+ side: usize,
3049+) -> Result<()> {
3050+ let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
3051+ enc.symbol(1, &mut cdfs.skip[skip_ctx]);
3052+ write_cdef_idx(enc, mi, true);
3053+ enc.symbol(1, &mut cdfs.intrabc);
3054+ write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?;
3055+ note_intrabc(dv);
3056+ // The bands: DC_PRED mode (what the decoder forces), no coefficients
3057+ // anywhere (skip), the block's own side for the partition context, the
3058+ // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm)
3059+ // for the deblock grid, and `skip` itself for the next block's skip
3060+ // context.
3061+ let empty: [Vec<i32>; 3] = [Vec::new(), Vec::new(), Vec::new()];
3062+ for cell in 0..(side / SUB).max(1) {
3063+ let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI));
3064+ neighbours.above_mode[c + cell] = DC_PRED;
3065+ neighbours.left_mode[r + cell] = DC_PRED;
3066+ neighbours.above_side[c + cell] = side;
3067+ neighbours.left_side[r + cell] = side;
3068+ }
3069+ neighbours.record_mi_planes(mi, side, &empty, true);
3070+ neighbours.record_tx(mi, side, side.min(64));
3071+ for cell in 0..side / MI {
3072+ neighbours.above_skip[mi.1 + cell] = true;
3073+ neighbours.left_skip[mi.0 + cell] = true;
3074+ }
3075+ Ok(())
3076+}
3077+
2840 fn write_intra_mode(3078 fn write_intra_mode(
2841 enc: &mut SymbolEncoder,3079 enc: &mut SymbolEncoder,
2842 cdfs: &mut Cdfs,3080 cdfs: &mut Cdfs,
@@ -2853,8 +3091,18 @@ fn write_intra_mode(
2853 side: usize,3091 side: usize,
2854 ) -> usize {3092 ) -> usize {
2855 let mode = usize::from(block.mode);3093 let mode = usize::from(block.mode);
2856- enc.symbol(0, &mut cdfs.skip[0]);3094+ // `av1_get_skip_txfm_context` (decode.rs `Neighbours::skip_txfm_ctx`):
3095+ // above + left. Every block this writer codes outside an `allow_intrabc`
3096+ // frame is unskipped, so both bands stay false and this stays 0 -- the
3097+ // literal every stream before this lane was written with.
3098+ let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
3099+ enc.symbol(0, &mut cdfs.skip[skip_ctx]);
2857 write_cdef_idx(enc, mi, false);3100 write_cdef_idx(enc, mi, false);
3101+ // `read_intrabc_info` (spec 5.11.13): the flag is read for EVERY intra
3102+ // block of an `allow_intrabc` frame, not only the ones that use it.
3103+ if intrabc_armed() {
3104+ enc.symbol(0, &mut cdfs.intrabc);
3105+ }
2858 enc.symbol(3106 enc.symbol(
2859 mode,3107 mode,
2860 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],3108 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
@@ -3055,6 +3303,11 @@ fn write_block(
3055 ) -> Result<()> {3303 ) -> Result<()> {
3056 let (r, c) = at;3304 let (r, c) = at;
3057 let at_mi = (r * (SUB / MI), c * (SUB / MI));3305 let at_mi = (r * (SUB / MI), c * (SUB / MI));
3306+ if let Some(dv) = block.dv {
3307+ write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?;
3308+ record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv));
3309+ return Ok(());
3310+ }
3058 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);3311 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
3059 let mode = write_intra_mode(3312 let mode = write_intra_mode(
3060 enc,3313 enc,
@@ -3094,9 +3347,24 @@ fn write_block(
3094 tx_select,3347 tx_select,
3095 );3348 );
3096 neighbours.record_planes(at, side, mode, grids, !split);3349 neighbours.record_planes(at, side, mode, grids, !split);
3350+ clear_skip_band(neighbours, at_mi, side);
3351+ record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None);
3097 Ok(())3352 Ok(())
3098 }3353 }
3099 3354
3355+/// An unskipped block's own `skip` publication: only an `allow_intrabc`
3356+/// frame ever sets these bands, so a frame without one leaves them exactly
3357+/// as they were before this lane (all false).
3358+fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) {
3359+ if !intrabc_armed() {
3360+ return;
3361+ }
3362+ for cell in 0..side / MI {
3363+ neighbours.above_skip[mi.1 + cell] = false;
3364+ neighbours.left_skip[mi.0 + cell] = false;
3365+ }
3366+}
3367+
3100 /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own3368 /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
3101 /// luma transform and 4x4 chroma transforms, coded exactly like3369 /// luma transform and 4x4 chroma transforms, coded exactly like
3102 /// [`write_block`] but reading its intra-mode context from the *enclosing*3370 /// [`write_block`] but reading its intra-mode context from the *enclosing*
@@ -3120,6 +3388,11 @@ fn write_leaf8(
3120 all_scans: &[Vec<u16>; 4],3388 all_scans: &[Vec<u16>; 4],
3121 ) -> Result<usize> {3389 ) -> Result<usize> {
3122 let (r, c) = outer_at;3390 let (r, c) = outer_at;
3391+ if let Some(dv) = block.dv {
3392+ write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?;
3393+ record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv));
3394+ return Ok(DC_PRED);
3395+ }
3123 let mut above_mode = neighbours.above_mode[c];3396 let mut above_mode = neighbours.above_mode[c];
3124 let mut left_mode = neighbours.left_mode[r];3397 let mut left_mode = neighbours.left_mode[r];
3125 // The previous leaf sits directly above (same column, two mi rows up)3398 // The previous leaf sits directly above (same column, two mi rows up)
@@ -3169,6 +3442,8 @@ fn write_leaf8(
3169 tx_select,3442 tx_select,
3170 );3443 );
3171 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);3444 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
3445+ clear_skip_band(neighbours, leaf_mi, 8);
3446+ record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None);
3172 Ok(mode)3447 Ok(mode)
3173 }3448 }
3174 3449