diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index a8788ba4..575c891d 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -37549,8 +37549,8 @@ mod tests { &encoded.loop_filter, encoded.tx_select, true, - false, - false, + encoded.screen, + encoded.allow_intrabc, &encoded.loop_restoration, fctx, ) .unwrap(); @@ -37593,8 +37593,8 @@ mod tests { &encoded.loop_filter, tx_select, true, - false, - false, + encoded.screen, + encoded.allow_intrabc, &encoded.loop_restoration, fctx, ) @@ -37681,7 +37681,9 @@ mod tests { // This key frame's own `allow_screen_content_tools`: its intra // blocks carry the palette syntax under it (stale-header class). key.screen, - false, + // ... and its own `allow_intrabc`: every intra block carries a + // `use_intrabc` symbol under it (stale-header class). + key.allow_intrabc, &key.loop_restoration, fctx, ) .unwrap(); @@ -38021,7 +38023,9 @@ mod tests { // This key frame's own `allow_screen_content_tools`: its intra // blocks carry the palette syntax under it (stale-header class). key.screen, - false, + // ... and its own `allow_intrabc`: every intra block carries a + // `use_intrabc` symbol under it (stale-header class). + key.allow_intrabc, &key.loop_restoration, fctx, ) .unwrap(); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 99127ac0..828c1c6b 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -681,6 +681,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En next_cdfs: encoded.next_cdfs.clone(), loop_filter: encoded.loop_filter, loop_restoration: encoded.loop_restoration, + allow_intrabc: encoded.allow_intrabc, cdef: encoded.cdef, } } @@ -760,6 +761,24 @@ pub struct Encoded { /// filters themselves are coded in `tile`, so a decode of it under a /// stale `RESTORE_NONE` header desyncs at the first superblock. pub(crate) loop_restoration: LoopRestorationParams, + /// This frame header's `allow_intrabc` -- every intra block of the tile + /// carries a `use_intrabc` symbol under it, so a raw tile decode that + /// guessed `false` would desync at the first block (same class as + /// `screen`/`tx_select`). + pub(crate) allow_intrabc: bool, +} + +thread_local! { + /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat + /// for on the last key frame encoded on this thread -- read by the gates, + /// which print it beside the block counts (class `gate-blind-to-feature`). + static IBC_SHARE: std::cell::Cell = const { std::cell::Cell::new(0.0) }; +} + +/// [`IBC_SHARE`] for the last key frame encoded on this thread. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub(crate) fn intrabc_source_share() -> f64 { + IBC_SHARE.with(std::cell::Cell::get) } thread_local! { @@ -2495,6 +2514,421 @@ fn palette_candidates(block: &[u8]) -> Vec { } #[allow(clippy::too_many_arguments)] +// --------------------------------------------------------------------------- +// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV +// validity). A key frame that detected screen content and finds enough exact +// repeats in its own source sets `allow_intrabc`, which the spec forces every +// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns +// its place when the copied blocks pay back the deblock/CDEF/LR the frame +// gives up. `EC_AV1_INTRABC=0` turns the whole arm off. +// --------------------------------------------------------------------------- + +/// Whether intra block copy is offered at all. **Off by default** -- +/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against +/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`), +/// but on the gate's real screen capture it MEASURED WORSE: setting +/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop +/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay +/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc, +/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame +/// that detected no screen content. +fn intrabc_enabled() -> bool { + if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) { + return forced; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1")) +} + +thread_local! { + /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation + /// probe runs both arms in one process, and the suite is one process, so + /// an environment variable cannot separate them (same reason + /// [`SCREEN_FORCE`] exists). + static INTRABC_FORCE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub(crate) fn force_intrabc(value: Option) { + INTRABC_FORCE.with(|c| c.set(value)); +} + +/// How many of a screen frame's 16x16 blocks must have an exact repeat +/// somewhere else in the source before `allow_intrabc` is worth the in-loop +/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision- +/// constant class: `probe_intrabc_threshold` measures the arm at several +/// values. +fn intrabc_pct() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("EC_AV1_INTRABC_PCT") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(10) + }) +} + +/// The pixel grid intrabc source positions are hashed on +/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it, +/// which keeps the block-hash table (and so the search) linear in the frame +/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies +/// at `dv / 2` full pel, so an odd DV would land half-pel and need the +/// bilinear interpolation decode.rs applies but this encoder does not. +fn intrabc_step() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + let n: usize = std::env::var("EC_AV1_INTRABC_STEP") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(4); + if n % 2 == 0 { n.max(2) } else { 4 } + }) +} + +/// The side of the luma square the block-hash table is keyed on. +const IBC_HASH: usize = 16; + +/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind +/// the current one the source's bottom-right corner must already be. +const INTRABC_DELAY_SB64: i32 = 4; + +/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`. +fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for row in 0..IBC_HASH { + let base = (y + row) * width + x; + for &v in &plane[base..base + IBC_HASH] { + h ^= u64::from(v); + h = h.wrapping_mul(0x100_0000_01b3); + } + } + h +} + +/// Every `intrabc_step()`-aligned position of `plane` inside +/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`]. +fn ibc_index( + table: &mut std::collections::HashMap>, + plane: &[u8], + width: usize, + (x0, y0): (usize, usize), + (x1, y1): (usize, usize), +) { + let step = intrabc_step(); + if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH { + return; + } + let mut y = y0.next_multiple_of(step); + while y + IBC_HASH <= y1 { + let mut x = x0.next_multiple_of(step); + while x + IBC_HASH <= x1 { + table + .entry(ibc_hash(plane, width, x, y)) + .or_default() + .push((x as u32, y as u32)); + x += step; + } + y += step; + } +} + +/// Whether `screen`-detected source `y` repeats itself enough to be worth +/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact +/// content appears at some other position, against [`intrabc_pct`]. Returns +/// the share as well, for the gate's own print. +fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) { + if true_width < 4 * 64 || true_height < 2 * 64 { + return (false, 0.0); + } + let mut table = std::collections::HashMap::new(); + ibc_index(&mut table, y, width, (0, 0), (true_width, true_height)); + let (mut total, mut matched) = (0usize, 0usize); + let mut by = 0; + while by + IBC_HASH <= true_height { + let mut bx = 0; + while bx + IBC_HASH <= true_width { + total += 1; + if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) { + if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) { + matched += 1; + } + } + bx += IBC_HASH; + } + by += IBC_HASH; + } + let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 }; + (share * 100.0 >= intrabc_pct() as f64, share) +} + +/// One tile's intrabc search state: a block-hash table over the part of the +/// tile's own reconstruction that is already final (whole superblock rows -- +/// the in-loop filters are off on this frame, so a coded superblock row never +/// changes again), plus the last DV chosen, which the RD price uses as its +/// predictor estimate. +struct Ibc { + /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the + /// source repeats exactly where a lossily coded reconstruction only + /// nearly does, so an exact-match table over the reconstruction finds + /// almost nothing. The candidate is then SCORED against the + /// reconstruction ([`ibc_sse`]), which is what a decoder will copy. + table: std::collections::HashMap>, + /// The tile's own luma rect, in samples. + tile: (usize, usize, usize, usize), + /// The DV the previous intrabc block of this tile took -- the *estimate* + /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken + /// against. The writer computes the true predictor off its own mi grid + /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost + /// a slightly mispriced candidate, never a wrong bitstream. + last_dv: Option<(i32, i32)>, + /// How many blocks took intrabc, and how many hash lookups found at least + /// one valid candidate -- the gate's own fire counts. + hits: usize, + lookups: usize, + found: usize, +} + +impl Ibc { + fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self { + let mut table = std::collections::HashMap::new(); + ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3)); + Self { + table, + tile, + last_dv: None, + hits: 0, + lookups: 0, + found: 0, + } + } + + /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv` + /// (1/8 pel), with this lane's own extra restriction on top: the source + /// must lie entirely in a COMPLETED superblock row, which is exactly the + /// region [`Self::fill_to`] indexes and a strict subset of what the spec + /// allows. corner-cut, ceiling named: same-superblock-row sources (the + /// wavefront's own diagonal) are legal and not searched; the upgrade path + /// is to index the current row's finished superblocks too. + fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool { + let (dr, dc) = (dv.0 / 8, dv.1 / 8); + if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 { + return false; + } + let (tx0, ty0, tx1, ty1) = ( + self.tile.0 as i32, + self.tile.1 as i32, + self.tile.2 as i32, + self.tile.3 as i32, + ); + let (sx, sy) = (x as i32 + dc, y as i32 + dr); + let (w, h) = (w as i32, h as i32); + if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 { + return false; + } + let active_sb_row = (y as i32 - ty0) >> 6; + let active_sb_col = (x as i32 - tx0) >> 6; + let src_sb_row = (sy + h - 1 - ty0) >> 6; + let src_sb_col = (sx + w - 1 - tx0) >> 6; + // This lane's own restriction (see the doc comment). + if src_sb_row >= active_sb_row { + return false; + } + let total = ((tx1 - tx0 - 1) >> 6) + 1; + if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64 + { + return false; + } + // libaom's wavefront: only the top-left cone of the frame is legal. + let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row); + src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf + } +} + +/// How many block searches ran, how many found at least one VALID candidate, +/// and how many won on rate-distortion -- the hash hit rate a gate prints +/// (class `gate-blind-to-feature`: "the search ran" and "the search found +/// something" and "the block took it" are three different claims). +static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; + +impl Drop for Ibc { + fn drop(&mut self) { + for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() { + IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed); + } + } +} + +/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to +/// its own encode. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub(crate) fn take_intrabc_search() -> [usize; 3] { + std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// [`crate::tile::write_dv_component`]'s static price -- the same shape as +/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv` +/// infers rather than codes. +fn dv_component_bits(diff: i32) -> f64 { + let z = diff.unsigned_abs() as i32 - 1; + let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); + let class = mv_class_of(z); + bits += symbol_bits(&cdf::MV_CLASS, class); + let local = z - mv_class_base(class); + if class == 0 { + bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize); + } else { + let d = local >> 3; + for i in 0..class { + bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); + } + } + bits +} + +/// What one block vector costs against `pred`, plus the `skip` and +/// `use_intrabc` flags the block carries and the ordinary intra block does +/// not pay in this currency. +fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 { + let diff = (dv.0 - pred.0, dv.1 - pred.1); + let joint = match (diff.0 != 0, diff.1 != 0) { + (false, false) => 0, + (false, true) => 1, + (true, false) => 2, + (true, true) => 3, + }; + let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0; + if diff.0 != 0 { + bits += dv_component_bits(diff.0); + } + if diff.1 != 0 { + bits += dv_component_bits(diff.1); + } + bits +} + +/// The squared error of copying the `side`-square block at `(sx, sy)` of each +/// plane's reconstruction onto the source block at `(x, y)`, luma and both +/// chroma planes together -- what an intrabc block's whole (residual-free) +/// distortion is. +fn ibc_sse( + luma: &Plane, + chroma: &[Plane; 2], + (x, y): (usize, usize), + (sx, sy): (usize, usize), + side: usize, +) -> f64 { + let mut sse = 0.0f64; + for row in 0..side { + let src = &luma.source[(y + row) * luma.width + x..][..side]; + let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..side]; + for (&s, &r) in src.iter().zip(rec) { + let d = f64::from(i32::from(s) - i32::from(r)); + sse += d * d; + } + } + let half = side / 2; + for plane in chroma { + for row in 0..half { + let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..half]; + let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..half]; + for (&s, &r) in src.iter().zip(rec) { + let d = f64::from(i32::from(s) - i32::from(r)); + sse += d * d; + } + } + } + sse +} + +/// Copies the `side`-square block at `(sx, sy)` of each plane's +/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction, +/// since it carries no residual (`skip`). Full-pel in both planes by +/// construction ([`intrabc_step`] keeps every DV even), which is what makes +/// this a plain copy where decode.rs runs the bilinear kernel over the same +/// samples. +fn ibc_commit( + luma: &mut Plane, + chroma: &mut [Plane; 2], + (x, y): (usize, usize), + (sx, sy): (usize, usize), + side: usize, +) { + for row in 0..side { + let from = (sy + row) * luma.width + sx; + let to = (y + row) * luma.width + x; + let copied: Vec = luma.reconstruction[from..from + side].to_vec(); + luma.reconstruction[to..to + side].copy_from_slice(&copied); + } + let half = side / 2; + for plane in chroma { + for row in 0..half { + let from = (sy / 2 + row) * plane.width + sx / 2; + let to = (y / 2 + row) * plane.width + x / 2; + let copied: Vec = plane.reconstruction[from..from + half].to_vec(); + plane.reconstruction[to..to + half].copy_from_slice(&copied); + } + } +} + +/// Searches this block's own DV: every hash-table position whose 16x16 luma +/// square equals the block's source square, plus the previous block's DV as a +/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns +/// the winning `(dv, cost)`, or `None` when nothing valid was found. +fn ibc_search( + ibc: &mut Ibc, + luma: &Plane, + chroma: &[Plane; 2], + (x, y): (usize, usize), + side: usize, + lambda: f64, +) -> Option<((i32, i32), f64, (usize, usize))> { + let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8)); + let mut best: Option<((i32, i32), f64, (usize, usize))> = None; + let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| { + let dv = ( + (sy as i32 - y as i32) * 8, + (sx as i32 - x as i32) * 8, + ); + if !ibc.dv_valid(x, y, side, side, dv) { + return; + } + let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred); + if best.as_ref().is_none_or(|b| cost < b.1) { + *best = Some((dv, cost, (sx, sy))); + } + }; + ibc.lookups += 1; + let key = ibc_hash(luma.source, luma.width, x, y); + // The table is filled in raster order, so the entries BEFORE this block's + // own position are exactly the already-coded ones -- and the nearest of + // them costs the fewest DV bits. Walking backwards from the block's own + // slot is what makes the search look up-and-left; taking the newest + // entries outright only ever finds candidates below and to the right, + // every one of which `dv_valid` rejects. + let hits: Vec<(u32, u32)> = ibc + .table + .get(&key) + .map(|h| { + let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32)); + h[..end].iter().rev().take(32).copied().collect() + }) + .unwrap_or_default(); + for (hx, hy) in hits { + consider(&*ibc, hx as usize, hy as usize, &mut best); + } + if let Some(dv) = ibc.last_dv { + let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8); + if sx >= 0 && sy >= 0 { + consider(&*ibc, sx as usize, sy as usize, &mut best); + } + } + if best.is_some() { + ibc.found += 1; + } + best +} + fn code_square( luma: &mut Plane, chroma: &mut [Plane; 2], @@ -2505,7 +2939,10 @@ fn code_square( // The frame header's `tx_mode == TxMode::Select`: the block then searches // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one // transform over its whole side. - tx_select: bool, fctx: &crate::decode::FrameCtx, + tx_select: bool, + // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose + // header did not set `allow_intrabc`. + ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { let (luma_set, chroma_set) = if side == BLOCK { (TxbSet::Luma32, TxbSet::Chroma16) @@ -2609,6 +3046,29 @@ fn code_square( let ([u, v], uv_mode, chroma_cost, palette_uv) = search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx); cost += chroma_cost; + + // The intrabc arm is priced against the WHOLE block -- luma and both + // chroma planes, residual-free -- so it is compared after the chroma + // search has added its own cost, not against the luma decision alone. + if let Some(ibc) = ibc { + if let Some((dv, cost_ibc, src)) = + ibc_search(ibc, luma, chroma, (x, y), side, search.lambda) + { + if cost_ibc < cost { + ibc_commit(luma, chroma, (x, y), src, side); + ibc.last_dv = Some(dv); + ibc.hits += 1; + return ( + BlockCoeffs { + skip: true, + dv: Some(dv), + ..BlockCoeffs::default() + }, + cost_ibc, + ); + } + } + } ( BlockCoeffs { u, @@ -2923,6 +3383,7 @@ fn code_square_inter( search, mode_bits, tx_select() && tx_select_inter(), + None, fctx, ); let luma_set = if side == 8 { @@ -3376,6 +3837,7 @@ fn code_square_inter( uv_mode: DC_PRED, skip: skip_new, eight: None, + dv: None, palette: None, palette_uv: None, tx_depth, @@ -3407,6 +3869,7 @@ fn code_square_inter( uv_mode: DC_PRED, skip, eight: None, + dv: None, palette: None, palette_uv: None, tx_depth, @@ -4053,8 +4516,30 @@ pub(crate) fn encode_key_frame_inner( (picture.height).min(render.1), ); arm_seq_screen(screen); + // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit + // forces deblocking, CDEF and loop restoration OFF for this frame + // (frame.rs:194/210/252/272), so it is only set when the source repeats + // itself enough for the copied blocks to pay that back + // ([`intrabc_worth_it`]). + // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi + // grid across every tile while this writer builds one per tile, so a + // multi-tile allow_intrabc frame would predict its DVs off a different + // grid than the decoder does. corner-cut, ceiling named: the upgrade + // path is a frame-scoped grid shared by the tile writers. + let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) { + intrabc_worth_it( + &picture.y.iter().map(|&v| v as u8).collect::>(), + picture.width, + picture.width.min(render.0), + picture.height.min(render.1), + ) + } else { + (false, 0.0) + }; + IBC_SHARE.with(|c| c.set(ibc_share)); let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; header.allow_screen_content_tools = screen; + header.allow_intrabc = allow_intrabc; header.render_width = render.0 as u32; header.render_height = render.1 as u32; // `TxMode::Select`: every block codes a `tx_depth` symbol and may split @@ -4179,6 +4664,18 @@ pub(crate) fn encode_key_frame_inner( clip_planes_to_tile(&mut luma, &mut chroma, rect); let mut above_mode = vec![DC_PRED; cols * 2]; let mut left_mode = vec![DC_PRED; rows * 2]; + let mut ibc = allow_intrabc.then(|| { + Ibc::new( + ( + rect.mi_col0 as usize * 4, + rect.mi_row0 as usize * 4, + (rect.mi_col1 as usize * 4).min(true_width), + (rect.mi_row1 as usize * 4).min(true_height), + ), + &picture_y8, + frame_width, + ) + }); let mut coded: Vec<(usize, Superblock, Vec)> = Vec::new(); for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize { for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize { @@ -4266,7 +4763,8 @@ pub(crate) fn encode_key_frame_inner( BLOCK, &search, &mode_bits(above_mode[c0], left_mode[r0]), - tx_select, fctx, + tx_select, + ibc.as_mut(), fctx, ); cost_whole += search.lambda * partition_bits(BLOCK, false); let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); @@ -4300,7 +4798,8 @@ pub(crate) fn encode_key_frame_inner( SUB, &search, &mode_bits(above_mode[sc], left_mode[sr]), - tx_select, fctx, + tx_select, + ibc.as_mut(), fctx, ); cost_split += cost; split_modes.push(block.mode); @@ -4332,7 +4831,8 @@ pub(crate) fn encode_key_frame_inner( 8, &search, &leaf_mode_bits, - tx_select, fctx, + tx_select, + None, fctx, ); cost_split += cost; split_modes.push(leaf.mode); @@ -4431,6 +4931,7 @@ pub(crate) fn encode_key_frame_inner( crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_screen(screen); + crate::tile::arm_intrabc(allow_intrabc); let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( mi_cols, mi_rows, @@ -4455,7 +4956,11 @@ pub(crate) fn encode_key_frame_inner( &mut luma, &mut chroma, [&picture_y8, &picture_u8, &picture_v8], - true, + // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF + // and loop restoration off and codes none of their parameters + // (frame.rs:194/210/252/272) -- there is no filter to search for, and + // the encoder's reconstruction is already what a decoder produces. + !allow_intrabc, &mut tiles, search.lambda, fctx, @@ -4516,6 +5021,7 @@ pub(crate) fn encode_key_frame_inner( loop_filter: header.loop_filter, cdef: header.cdef, loop_restoration: header.loop_restoration, + allow_intrabc, }) } @@ -5715,6 +6221,7 @@ fn search_inter_block( skip: best.skip, inter: best.inter, eight: None, + dv: None, palette: None, palette_uv: None, tx_depth: 0, @@ -6605,6 +7112,9 @@ pub(crate) fn encode_inter_frame( loop_filter: header.loop_filter, cdef: header.cdef, loop_restoration: header.loop_restoration, + // An inter frame never allows intrabc (spec 5.9.2 codes the bit on + // intra frames only). + allow_intrabc: false, }) } @@ -7213,6 +7723,111 @@ mod tests { assert!(!film.screen, "the detector fired on the film-shaped test card"); } + /// The lane's keep-rule measurement: the gate's own screen capture, one + /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers. + /// Setting the bit forces deblocking, CDEF and loop restoration off for + /// that frame, so the table is exactly the filter loss against the bytes + /// the copied blocks save. + #[test] + #[ignore = "needs the real-library manifest and ffmpeg"] + fn probe_intrabc_key_frame() { + let fctx = &crate::decode::FrameCtx::new(); + let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures"); + let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else { + eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest"); + return; + }; + let Some(clip) = manifest + .lines() + .skip(1) + .filter_map(|l| l.split('\t').next()) + .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) + else { + eprintln!("SKIP probe_intrabc_key_frame: no OBS recording"); + return; + }; + let (width, height) = (640usize, 384usize); + let picture = clip_frame(clip, "0", width, height); + eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |"); + for q in [5u8, 20, 35, 45] { + for on in [false, true] { + force_intrabc(Some(on)); + let _ = crate::tile::take_intrabc_hits(); + let _ = take_intrabc_search(); + let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); + let hits = crate::tile::take_intrabc_hits(); + let search = take_intrabc_search(); + eprintln!( + "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |", + if encoded.allow_intrabc { "on" } else { "off" }, + encoded.stream.len(), + psnr_all(&encoded.reconstruction, &picture), + hits[0], + &hits[1..], + search[0], search[1], search[2], + ); + } + } + force_intrabc(None); + } + + /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card + /// sets `allow_intrabc` (so every in-loop filter is off), blocks really + /// take a block vector (fire count + DV histogram, class + /// `gate-blind-to-feature`), and both our own decoder and ffmpeg -- + /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct + /// exactly what the encoder did. + #[test] + fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() { + let fctx = &crate::decode::FrameCtx::new(); + // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4 + // superblocks of 64) and tall enough for a source superblock row + // above the blocks that copy from it. + let (width, height) = (512usize, 256usize); + let picture = screen_card(width, height); + let _ = crate::tile::take_intrabc_hits(); + // The default is OFF (it measured worse on the real screen capture -- + // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns + // the arm on for its own encode and puts it back straight after. + force_intrabc(Some(true)); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + force_intrabc(None); + assert!( + encoded.allow_intrabc, + "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)", + intrabc_source_share() * 100.0 + ); + let hits = crate::tile::take_intrabc_hits(); + eprintln!( + "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%", + hits[0], + &hits[1..], + intrabc_source_share() * 100.0 + ); + let search = take_intrabc_search(); + eprintln!( + "intrabc searches {} found-valid {} won-RD {}", + search[0], search[1], search[2] + ); + assert!( + hits[0] > 0, + "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}" + ); + let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); + assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); + assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); + assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half: no ffmpeg"); + return; + } + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); + } + /// The minimal repro that isolated the inter-residual desync: a key frame /// followed by one inter frame whose single superblock carries one /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma @@ -7249,6 +7864,7 @@ mod tests { uv_mode: 0, skip: false, eight: None, + dv: None, palette: None, palette_uv: None, tx_depth: 0, diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index bebdcd5d..4cc6869d 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3005,7 +3005,8 @@ pub(crate) mod tests { // `false` desyncs at the first one (class: test asserts // against a stale header). encoded.screen, - false, + // ... and its own `allow_intrabc` (stale-header class). + encoded.allow_intrabc, &encoded.loop_restoration, fctx, ) .unwrap(); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index fe4ff5a3..ecf795b9 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -314,6 +314,54 @@ fn screen_armed() -> bool { SCREEN.with(std::cell::Cell::get) } +thread_local! { + /// This frame header's `allow_intrabc` (spec 5.9.2), armed exactly like + /// [`SCREEN`]: with it every intra block of the tile carries a + /// `use_intrabc` symbol right after `skip`/`cdef`/`delta_q` (decode.rs + /// `read_intra_mode`), so a tile written without it and read with it + /// desyncs at the first block. + static INTRABC: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The mi grid the DV predictor is built off (decode.rs + /// `INTRABC_MI_GRID`/`record_intrabc_mi`): every coded block publishes + /// its own footprint into it, an intrabc one also its DV as an + /// `INTRA_FRAME` candidate. `Some` only while an `allow_intrabc` tile is + /// being written. + static INTRABC_GRID: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Arms the frame's `allow_intrabc` bit for the next tile written on this +/// thread; cleared by [`CdefIdxGuard`] when that writer returns. +pub(crate) fn arm_intrabc(on: bool) { + INTRABC.with(|c| c.set(on)); +} + +fn intrabc_armed() -> bool { + INTRABC.with(std::cell::Cell::get) +} + +/// How many blocks this writer coded `use_intrabc == 1`, and the histogram of +/// their DV magnitudes in full pels (index 1..=6 = 1, 2, 4, 8, 16, 32 pels +/// and up, by the larger component) -- the fire count a gate prints so that +/// "intrabc is on" is a measurement rather than a claim (class +/// `gate-blind-to-feature`). Index 0 is the block count. +static INTRABC_HITS: [std::sync::atomic::AtomicUsize; 7] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; + +fn note_intrabc(dv: (i32, i32)) { + INTRABC_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let px = (dv.0.abs() / 8).max(dv.1.abs() / 8).max(1) as usize; + let bucket = (usize::BITS - px.leading_zeros()) as usize; + INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts +/// to its own encode. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub(crate) fn take_intrabc_hits() -> [usize; 7] { + std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + thread_local! { /// This frame header's own `reference_select` bit (spec 5.9.22), armed /// the same way `arm_sign_bias` arms the sign-bias table rather than @@ -708,6 +756,8 @@ impl Drop for CdefIdxGuard { SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS)); SCREEN.with(|c| c.set(false)); REFERENCE_SELECT.with(|c| c.set(false)); + INTRABC.with(|c| c.set(false)); + INTRABC_GRID.with(|c| *c.borrow_mut() = None); ORDER_HINTS.with(|c| c.set((7, 0, [0; 7]))); } } @@ -1213,6 +1263,19 @@ pub struct BlockCoeffs { /// `luma` then carries the whole block's levels in BLOCK coordinates, /// which the writer slices per transform unit. pub tx_depth: u8, + /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` -> + /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for + /// an ordinary intra block. Only a key frame whose header set + /// `allow_intrabc` ([`arm_intrabc`]) may carry one; the block is then + /// coded `skip` with no residual, no mode, no palette -- exactly what + /// decode.rs `read_intra_mode` reads back and returns early on. + /// + /// lane-av1ibc corner-cut, ceiling named: a residual-carrying intrabc + /// block needs the INTER coefficient tables plus the var-tx tree + /// decode.rs `decode_block`'s `intrabc_vartx` arm reads; the upgrade path + /// is to route the block through [`write_tx_syntax_inter`] instead of + /// returning early here. + pub dv: Option<(i32, i32)>, } /// A block's luma palette: its base colours (ascending, only the first @@ -2219,6 +2282,20 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. let _cdef_idx = CdefIdxGuard; check_blocks(mi_cols, mi_rows)?; + // The DV predictor's own mi grid, per tile exactly as decode.rs builds it + // per frame (`decode_key_frame_tile_lr`'s `intrabc_mi_grid`): a tile that + // allows no intrabc arms none and every `record_intrabc_mi` below is a + // no-op. + if intrabc_armed() { + // No `set_tile_bounds`: decode.rs builds this grid for the WHOLE + // frame with the default (whole-grid) bounds, so the writer must + // too. `encode_key_frame_inner` only allows intrabc on a + // single-tile frame, where the two grids are the same grid. + let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize); + INTRABC_GRID.with(|g| { + *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize)); + }); + } let (cols, rows) = block_grid(mi_cols, mi_rows); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); if superblocks.len() != (sb_cols * sb_rows) as usize { @@ -2872,6 +2949,170 @@ pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 { /// skip flag, its luma intra mode against the CDF its neighbours' modes pick, /// the angle a directional mode is steered by, and its chroma mode. Hands back /// the luma mode, which is what the blocks beside it read. +/// The DV predictor decode.rs `read_intrabc_dv` derives, mirrored line for +/// line off the writer's own copy of the intrabc mi grid: the `INTRA_FRAME` +/// stack's `nearest_mv` (or `near_mv` when that is zero), or -- when both are +/// -- `av1_find_ref_dv`'s fallback one superblock up, or 256 pixels plus one +/// superblock to the left on the tile's first superblock row, then floored to +/// full pel. Returns `(0, 0)` when no grid is armed, which no `allow_intrabc` +/// tile ever reaches. +fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) { + const INTRABC_DELAY_PIXELS: i32 = 256; + let n4 = side / MI; + let stack_pred = INTRABC_GRID.with(|g| { + let g = g.borrow(); + g.as_ref().map(|(grid, mi_cols, mi_rows)| { + let stack = crate::mvstack::find_mv_stack( + grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */ + *mi_cols, *mi_rows, + ); + if stack.nearest_mv == (0, 0) { + stack.near_mv + } else { + stack.nearest_mv + } + }) + }); + let mut pred = stack_pred.unwrap_or((0, 0)); + if pred == (0, 0) { + // 64x64 superblocks: the only size this encoder's sequence header + // signals (`use_128x128_superblock: false`), so `mib_size` is 16 mi. + // The tile row start is 0, exactly as decode.rs `read_intrabc_dv` + // takes it -- both are written for the single-tile-row streams this + // encoder produces. + let sb_mi = 16i32; + let sb_px = sb_mi * MI as i32; + pred = if (mi_r as i32) < sb_mi { + (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8) + } else { + (-sb_px * 8, 0) + }; + } + ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8) +} + +/// Publishes one coded block into [`INTRABC_GRID`], mirroring decode.rs +/// `record_intrabc_mi`: every block contributes its size, an intrabc one also +/// its DV as an `INTRA_FRAME` candidate. +fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) { + INTRABC_GRID.with(|g| { + let mut g = g.borrow_mut(); + let Some((grid, _, _)) = g.as_mut() else { + return; + }; + let info = crate::mvstack::MiInfo { + is_inter: dv.is_some(), + ref_frame: 0, + ref_frame1: crate::mvstack::NO_REF1, + mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))), + mv1: (0, 0), + is_new_mv: dv.is_some(), + is_global_mv0: false, + is_global_mv1: false, + size: n4 as u8, + size_h: n4 as u8, + }; + for r in mi_r..mi_r + n4 { + for c in mi_c..mi_c + n4 { + grid.set(r, c, info); + } + } + }); +} + +/// One full-pel block-vector component, [`write_mv_component`]'s +/// `force_integer_mv` twin: decode.rs `read_mv_component` infers `mv_fr`/ +/// `mv_class0_fr` as 3 and the high-precision bit as 1 under +/// `force_integer_mv`, so neither symbol is written here -- writing them +/// would leave the decoder two symbols behind from this block on. +fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> { + let mag = diff.unsigned_abs() as i32; + if mag % 8 != 0 { + return Err(Error::unsupported( + "AV1 tile", + "a block vector is coded at full-pel precision only", + )); + } + enc.symbol(usize::from(diff < 0), &mut c.sign); + let z = mag - 1; + let class = mv_class_of(z); + enc.symbol(class, &mut c.class); + let local = z - mv_class_base(class); + if class == 0 { + enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit); + } else { + let d = local >> 3; + for i in 0..class { + enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]); + } + } + Ok(()) +} + +/// One intrabc block's DV as a residual against [`intrabc_dv_pred`], off the +/// `dv` nmv context (decode.rs `read_intrabc_dv` -> `read_mv`). +fn write_dv(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, dv: (i32, i32), pred: (i32, i32)) -> Result<()> { + let diff = (dv.0 - pred.0, dv.1 - pred.1); + let joint = match (diff.0 != 0, diff.1 != 0) { + (false, false) => 0, + (false, true) => 1, + (true, false) => 2, + (true, true) => 3, + }; + enc.symbol(joint, &mut cdfs.dv_joint); + if diff.0 != 0 { + write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?; + } + if diff.1 != 0 { + write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?; + } + Ok(()) +} + +/// The mode-info half of an intrabc block (decode.rs `read_intra_mode`'s +/// early return): `skip`, `cdef_idx`, `use_intrabc` and the DV, then nothing +/// -- no y/uv mode, no angle delta, no palette, and (because it is skipped) +/// no transform size and no residual. Publishes the block into every +/// neighbour band an ordinary block leaves behind, at the DC_PRED/uncoded/ +/// skipped state a decoder reads back for it. +fn write_intrabc_block( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + dv: (i32, i32), + mi: (usize, usize), + side: usize, +) -> Result<()> { + let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]); + enc.symbol(1, &mut cdfs.skip[skip_ctx]); + write_cdef_idx(enc, mi, true); + enc.symbol(1, &mut cdfs.intrabc); + write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?; + note_intrabc(dv); + // The bands: DC_PRED mode (what the decoder forces), no coefficients + // anywhere (skip), the block's own side for the partition context, the + // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm) + // for the deblock grid, and `skip` itself for the next block's skip + // context. + // One zero level per plane: `neighbour_state` reads `grid[0]` for the DC + // sign vote, and a skipped block leaves every context cleared. + let empty: [Vec; 3] = [vec![0], vec![0], vec![0]]; + for cell in 0..(side / SUB).max(1) { + let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI)); + neighbours.above_mode[c + cell] = DC_PRED; + neighbours.left_mode[r + cell] = DC_PRED; + neighbours.above_side[c + cell] = side; + neighbours.left_side[r + cell] = side; + } + neighbours.record_mi_planes(mi, side, &empty, true); + neighbours.record_tx(mi, side, side.min(64)); + for cell in 0..side / MI { + neighbours.above_skip[mi.1 + cell] = true; + neighbours.left_skip[mi.0 + cell] = true; + } + Ok(()) +} + fn write_intra_mode( enc: &mut SymbolEncoder, cdfs: &mut Cdfs, @@ -2888,8 +3129,18 @@ fn write_intra_mode( side: usize, ) -> usize { let mode = usize::from(block.mode); - enc.symbol(0, &mut cdfs.skip[0]); + // `av1_get_skip_txfm_context` (decode.rs `Neighbours::skip_txfm_ctx`): + // above + left. Every block this writer codes outside an `allow_intrabc` + // frame is unskipped, so both bands stay false and this stays 0 -- the + // literal every stream before this lane was written with. + let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]); + enc.symbol(0, &mut cdfs.skip[skip_ctx]); write_cdef_idx(enc, mi, false); + // `read_intrabc_info` (spec 5.11.13): the flag is read for EVERY intra + // block of an `allow_intrabc` frame, not only the ones that use it. + if intrabc_armed() { + enc.symbol(0, &mut cdfs.intrabc); + } enc.symbol( mode, &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]], @@ -3090,6 +3341,11 @@ fn write_block( ) -> Result<()> { let (r, c) = at; let at_mi = (r * (SUB / MI), c * (SUB / MI)); + if let Some(dv) = block.dv { + write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?; + record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv)); + return Ok(()); + } let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]); let mode = write_intra_mode( enc, @@ -3129,9 +3385,24 @@ fn write_block( tx_select, ); neighbours.record_planes(at, side, mode, grids, !split); + clear_skip_band(neighbours, at_mi, side); + record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None); Ok(()) } +/// An unskipped block's own `skip` publication: only an `allow_intrabc` +/// frame ever sets these bands, so a frame without one leaves them exactly +/// as they were before this lane (all false). +fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) { + if !intrabc_armed() { + return; + } + for cell in 0..side / MI { + neighbours.above_skip[mi.1 + cell] = false; + neighbours.left_skip[mi.0 + cell] = false; + } +} + /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own /// luma transform and 4x4 chroma transforms, coded exactly like /// [`write_block`] but reading its intra-mode context from the *enclosing* @@ -3155,6 +3426,11 @@ fn write_leaf8( all_scans: &[Vec; 4], ) -> Result { let (r, c) = outer_at; + if let Some(dv) = block.dv { + write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?; + record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv)); + return Ok(DC_PRED); + } let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; // The previous leaf sits directly above (same column, two mi rows up) @@ -3204,6 +3480,8 @@ fn write_leaf8( tx_select, ); neighbours.record_mi_planes(leaf_mi, 8, grids, !split); + clear_skip_band(neighbours, leaf_mi, 8); + record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None); Ok(mode) }