//! Software decoder for this crate's own key-frame tile payloads (spec 5.11), //! the reader half of [`crate::tile`]'s writer. //! //! `tile.rs` is another lane's territory this round (`lane-av1-rect` is //! touching its partition search), so nothing here imports its private //! helpers: the handful of `pub(crate)` items it already exposes //! ([`crate::tile::block_grid`], [`crate::tile::has_half`], //! [`crate::tile::INTRA_MODE_CTX`], [`crate::tile::write_golomb`]) are reused, //! and everything else (the partition/coefficient context arithmetic, the //! scan table) is a from-spec reimplementation kept in step with the writer by //! the gate tests below rather than by sharing code with it. //! //! # Scope (round 1) //! Key frames only, and only the shapes the encoder actually still needs to //! prove itself against: every coded block is `DC_PRED` (this crate's mode //! search names other intra modes, but a decoder for those needs the //! directional-prediction edge-reach plumbing [`crate::intra::predict`] //! already carries; wiring it up is round 2), never skipped, and every //! superblock is a whole number of 64x64 units (a frame whose true edge falls //! inside one, forcing the gathered-CDF partial-superblock path, is round 2 //! too). Anything outside that refuses with [`Error::unsupported`] rather than //! silently miscoding. use crate::hits::{hit, hit_do}; use ec_av1_syntax::{ CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo, }; use ec_core::{Error, Result}; /// Per-frame decode state, one instance per decoded stream (lane-thread1). /// /// Every field here used to be a `thread_local!` static, which made a decode a /// function of the calling THREAD's history rather than of the bitstream alone /// -- and made frame-parallel decoding impossible, since a worker thread sees /// empty state. The cells keep exactly the interior mutability the statics /// had, so every read/write site is byte-identical; what changes is WHERE the /// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down /// the decode call graph. /// /// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to /// exactly one thread's decode, and is never shared between workers. /// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`] /// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF /// (pre-restoration) samples, at the decoder's own plane stride. pub(crate) struct FilterStages { /// Post-deblock, pre-CDEF planes (Y, U, V). pub(crate) deblocked: [Vec; 3], /// Post-CDEF, pre-restoration planes (Y, U, V). pub(crate) cdefed: [Vec; 3], /// Each plane's stride (and so its width in the buffers above). pub(crate) stride: [usize; 3], } /// Takes whatever the last capturing decode left (see /// [`FrameCtx::capture_stages`]). #[allow(dead_code)] // read from the encoder's loop restoration search pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option { fctx.stages.borrow_mut().take() } pub(crate) struct FrameCtx { /// lane-av1lr: when set, the frame filter chain leaves its post-deblock /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop /// restoration search (spec 7.17 reads both: the stripe interior from /// the post-CDEF plane, its 3-row border from the post-deblock one). /// Off for every decode but that search, and off it costs one bool read /// per frame and not a single copy. pub(crate) capture_stages: std::cell::Cell, pub(crate) stages: std::cell::RefCell>, pub(crate) sb128_flag: std::cell::Cell, pub(crate) cdef_bits: std::cell::Cell, pub(crate) bit_depth: std::cell::Cell, pub(crate) superres: std::cell::Cell<(u32, u32)>, pub(crate) cdef_transmitted: std::cell::Cell, pub(crate) cdef_sb_cols: std::cell::Cell, pub(crate) cdef_idx_grid: std::cell::RefCell>, pub(crate) delta_q_present: std::cell::Cell, pub(crate) delta_q_res: std::cell::Cell, pub(crate) current_q_idx: std::cell::Cell, pub(crate) quant_deltas: std::cell::Cell, pub(crate) delta_lf_present: std::cell::Cell, pub(crate) delta_lf_res: std::cell::Cell, pub(crate) delta_lf_multi: std::cell::Cell, pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>, pub(crate) seg: std::cell::RefCell, pub(crate) seg_ids: std::cell::RefCell>, pub(crate) prev_seg_ids: std::cell::RefCell>, pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>, pub(crate) above_seg_pred: std::cell::RefCell>, pub(crate) left_seg_pred: std::cell::RefCell>, pub(crate) cur_segment_id: std::cell::Cell, pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>, pub(crate) tx_select_inter: std::cell::Cell, pub(crate) reduced_tx_set_inter: std::cell::Cell, pub(crate) enable_filter_intra_inter: std::cell::Cell, pub(crate) palette_pred: std::cell::RefCell>>, pub(crate) intrabc_mi_grid: std::cell::RefCell>, pub(crate) intrabc_dv: std::cell::Cell>, pub(crate) luma_tx_type: std::cell::Cell, pub(crate) intrabc_chroma_tx: std::cell::Cell>, pub(crate) intra_in_inter_mode: std::cell::Cell>, pub(crate) inter_strip_chroma: std::cell::Cell>, pub(crate) inter_last_mc: std::cell::Cell>, pub(crate) enable_edge_filter: std::cell::Cell, pub(crate) last_frame_wide_margin: std::cell::RefCell>, pub(crate) reach_sb_px: std::cell::Cell, pub(crate) grain_bit_depth: std::cell::Cell, /// lane-wave1 step (i): this superblock's recorded pixel writes, see /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`]. pub(crate) recon_ops: std::cell::RefCell>, /// The queue buffer [`flush_recon`] just drained, kept for its capacity /// so a superblock's records do not regrow the vector from nothing. pub(crate) recon_spare: std::cell::RefCell>, /// lane-recoparse: the coefficient grids of the recorded ops above, one /// buffer instead of a `Vec` per transform unit -- a recorded unit is /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse /// before the op is published, read only by whoever replays that op, and /// handed over WITH the ops at every drain point ([`wave_submit`], /// [`flush_recon`]), so offsets are always relative to the live arena. pub(crate) coeff_arena: std::cell::RefCell>, /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain /// path (a submitted job's arena travels to its worker instead). pub(crate) coeff_spare: std::cell::RefCell>, /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS /// ([`PredSrc::Owned`]): same lifetime, same drain points. pub(crate) pred_arena: std::cell::RefCell>, pub(crate) pred_spare: std::cell::RefCell>, /// lane-wave1 step (ii): the tile decoder's own planes, registered by /// [`ReconInline`] while reconstruction runs INLINE (one recon thread). /// `None` while the queue is in use (wavefront workers) and outside a /// tile. See [`push_op`]. pub(crate) recon_planes: std::cell::Cell>, /// lane-wave1 step (ii): the superblock wavefront this tile's recorded /// writes are handed to, at more than one reconstruction thread. pub(crate) wave: std::cell::RefCell>>, /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse /// thread last handed a superblock to the wavefront. pub(crate) wave_mark: std::cell::Cell>, } impl std::fmt::Debug for FrameCtx { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("FrameCtx") } } impl FrameCtx { /// A fresh context, every field at the default its thread-local /// predecessor was born with. pub(crate) fn new() -> Self { Self { sb128_flag: std::cell::Cell::new(false), cdef_bits: std::cell::Cell::new(0), bit_depth: std::cell::Cell::new(8), superres: std::cell::Cell::new((0, 8)), cdef_transmitted: std::cell::Cell::new(false), cdef_sb_cols: std::cell::Cell::new(0), capture_stages: std::cell::Cell::new(false), stages: std::cell::RefCell::new(None), cdef_idx_grid: std::cell::RefCell::new(Vec::new()), delta_q_present: std::cell::Cell::new(false), delta_q_res: std::cell::Cell::new(1), current_q_idx: std::cell::Cell::new(0), quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas { y_dc: 0, u_dc: 0, u_ac: 0, v_dc: 0, v_ac: 0, }), delta_lf_present: std::cell::Cell::new(false), delta_lf_res: std::cell::Cell::new(1), delta_lf_multi: std::cell::Cell::new(false), current_delta_lf: std::cell::Cell::new([0; 4]), seg: std::cell::RefCell::new(SegmentationParams::default()), seg_ids: std::cell::RefCell::new(Vec::new()), prev_seg_ids: std::cell::RefCell::new(Vec::new()), seg_mi_dims: std::cell::Cell::new((0, 0)), above_seg_pred: std::cell::RefCell::new(Vec::new()), left_seg_pred: std::cell::RefCell::new(Vec::new()), cur_segment_id: std::cell::Cell::new(0), seg_tile_origin: std::cell::Cell::new((0, 0)), tx_select_inter: std::cell::Cell::new(false), reduced_tx_set_inter: std::cell::Cell::new(true), enable_filter_intra_inter: std::cell::Cell::new(false), palette_pred: std::cell::RefCell::new(None), intrabc_mi_grid: std::cell::RefCell::new(None), intrabc_dv: std::cell::Cell::new(None), luma_tx_type: std::cell::Cell::new(TxType::DctDct), intrabc_chroma_tx: std::cell::Cell::new(None), intra_in_inter_mode: std::cell::Cell::new(None), inter_strip_chroma: std::cell::Cell::new(None), inter_last_mc: std::cell::Cell::new(None), enable_edge_filter: std::cell::Cell::new(false), last_frame_wide_margin: std::cell::RefCell::new(None), reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK), grain_bit_depth: std::cell::Cell::new(8), recon_ops: std::cell::RefCell::new(Vec::new()), recon_spare: std::cell::RefCell::new(Vec::new()), coeff_arena: std::cell::RefCell::new(Vec::new()), coeff_spare: std::cell::RefCell::new(Vec::new()), pred_arena: std::cell::RefCell::new(Vec::new()), pred_spare: std::cell::RefCell::new(Vec::new()), recon_planes: std::cell::Cell::new(None), wave: std::cell::RefCell::new(None), wave_mark: std::cell::Cell::new(None), } } } /// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)` /// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent /// `with` still wins for the scratch pools and gate counters that stay /// thread-local. pub(crate) trait WithRef { fn with(&self, f: impl FnOnce(&Self) -> R) -> R { f(self) } } impl WithRef for T {} /// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads. /// /// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread), /// and the post-decode filter chain reads exactly these fields: the bit depth /// (every kernel's clamp and threshold shift), the segmentation table /// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state /// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s /// default -- a field that turns out to be read after all shows up as a hash /// mismatch in /// `a_real_stream_filters_identically_with_one_and_four_filter_threads`. pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx { let out = FrameCtx::new(); out.bit_depth.set(fctx.bit_depth.get()); out.grain_bit_depth.set(fctx.grain_bit_depth.get()); out.superres.set(fctx.superres.get()); out.seg_mi_dims.set(fctx.seg_mi_dims.get()); out.seg.replace(fctx.seg.borrow().clone()); out.seg_ids.replace(fctx.seg_ids.borrow().clone()); out } use crate::cdf; use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; use crate::encode::{Picture, Reach}; use crate::intra::predict; use crate::mc; use crate::msac::SymbolDecoder; use crate::mvstack::{ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx, find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx, }; use crate::tile::{INTRA_MODE_CTX, block_grid, has_half}; use crate::transform::{TxType, dequant_and_inverse_typed_wh}; const PARTITION_NONE: usize = 0; const PARTITION_HORZ: usize = 1; const PARTITION_VERT: usize = 2; const PARTITION_SPLIT: usize = 3; const PARTITION_HORZ_A: usize = 4; const PARTITION_HORZ_B: usize = 5; const PARTITION_VERT_A: usize = 6; const PARTITION_VERT_B: usize = 7; const PARTITION_HORZ_4: usize = 8; const PARTITION_VERT_4: usize = 9; const SB_MI: u32 = 16; const BLOCK_MI: u32 = 8; // lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1). // Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the // superblock's own top-left mi?", the loop-restoration read's unit span, the // partition tree's own root level) keys off it; `SB_MI` stays the 64x64 // *quadrant* size a 128 superblock is decoded in, which is also what the CDEF // grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64 // inside a 128 superblock). thread_local! { /// lane-frame80: `EC_TRACE_COEFF_FRAME=` narrows the /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream /// prints gigabytes otherwise). Unset = every frame, as before. static COEFF_TRACE_FRAME: std::cell::Cell> = const { std::cell::Cell::new(None) }; static COEFF_TRACE_CUR: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }; } /// Called by [`crate::stream::decode_stream`] before each frame's tiles with /// that frame's DECODE-order index. pub fn set_coeff_trace_frame(idx: usize) { COEFF_TRACE_FRAME.with(|c| { if c.get().is_none() { let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") { Ok(v) => v.parse::().unwrap_or(usize::MAX), // unset: keep tracing every frame, as before this rung existed Err(_) => usize::MAX - 1, }; c.set(Some(want)); } }); COEFF_TRACE_CUR.with(|c| c.set(idx)); if crate::envflags::env_flag!("EC_TRACE_COEFF") { eprintln!("EC_COEFF_FRAME decode_idx={idx}"); } } pub(crate) fn coeff_trace_on() -> bool { if !crate::envflags::env_flag!("EC_TRACE_COEFF") { return false; } match COEFF_TRACE_FRAME.with(|c| c.get()) { // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the // env var unset: trace every frame. None => true, Some(w) if w >= usize::MAX - 1 => true, Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w, } } /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`). pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) { fctx.sb128_flag.with(|c| c.set(v)); crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx); } fn sb128(fctx: &crate::decode::FrameCtx) -> bool { fctx.sb128_flag.with(|c| c.get()) } /// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128). pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 { if sb128(fctx) { SB_MI * 2 } else { SB_MI } } // How many real 128-level partition symbols this decoder has read, and how // many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the // gate's proof a `--sb-size=128` stream exercised the 128 partition root. thread_local! { static PART128_SYMBOLS: std::cell::Cell = const { std::cell::Cell::new(0) }; static PART128_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static PART128_GATHERED_SYMBOLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the /// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec /// 5.11.4), which this decoder used to read and throw away. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn part128_gathered_symbols() -> usize { PART128_GATHERED_SYMBOLS.with(|c| c.get()) } /// Current value of [`PART128_SYMBOLS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn part128_symbols() -> usize { PART128_SYMBOLS.with(|c| c.get()) } /// Current value of [`PART128_SPLIT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn part128_split_hits() -> usize { PART128_SPLIT_HITS.with(|c| c.get()) } /// [`gather`] over an alphabet of any length -- the 128-level partition CDF /// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec /// `partition_cdf_length`), so its forced-split gather sums 5 elements where /// the 64/32 levels sum 6. fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] { let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum(); [32768 - split, 32768, 0] } /// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root. const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7]; const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6]; // How many `use_filter_intra` symbols this decoder has read as `1`, across // every call on the current thread -- the cheap counter [`filter_intra_hits`] gate // tests read (before/after, not the absolute value) to prove a stream // actually exercised the filter-intra predictor rather than silently // skipping it. thread_local! { static FILTER_INTRA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`FILTER_INTRA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn filter_intra_hits() -> usize { FILTER_INTRA_HITS.with(|c| c.get()) } // lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged // to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own // `read_filter_intra_mode_info` call), which no gate exercised before this // round -- every inter gate recipe passed `--enable-filter-intra=0`. thread_local! { static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_in_inter_filter_intra_hits() -> usize { INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get()) } // lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a // nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both // arms refused a nonzero luma delta before this round, and no inter gate // enabled `--enable-angle-delta` (aomenc's own default is 1). thread_local! { static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize { INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get()) } /// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize { INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get()) } // lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside // an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm // read `uv_mode` and then refused everything but `DC_PRED`. Counted here and // nowhere else so the gate's assert cannot be satisfied by a >=16x16 block. thread_local! { static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame /// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize { INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get()) } /// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf /// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) { ( INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()), INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()), INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()), ) } // lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into // [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a // frame-level flag through the recursive block decode -- `0` (the default) // makes every call a true no-op, matching every existing gate stream's // `cdef_bits == 0` behaviour exactly. // lane-realworld r8: the sequence header's `color_config.bit_depth`, set // once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs` // call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still // blocks every non-8-bit stream from reaching a decode call, so this is `8` // on every path that runs today -- threading it now (rather than the literal // `8`) is stage 1 of widening past that refusal without re-deriving every // clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of // depth (this decoder's own internal choice, matches dav1d/libaom). /// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current /// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`. pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 { (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1 } /// The current stream's bit depth, for callers (e.g. dequant) that need the /// raw value rather than the derived clamp bound. pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 { fctx.bit_depth.with(std::cell::Cell::get) } /// Sets [`BIT_DEPTH`] for the current thread, called once per frame from /// [`crate::stream`]'s decode loop. pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) { fctx.bit_depth.with(|c| c.set(bit_depth)); } /// This frame's superres state: `(upscaled_width, superres_denom)`, or /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid, /// `read_lr`'s unit corners and the pixel filters themselves -- works in /// UPSCALED coordinates while deblock and CDEF work in downscaled ones /// (libaom `av1_superres_upscale` in `decodeframe.c`, and /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x` /// superres arms). Set once per frame from [`crate::stream`]'s decode /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame /// so a later frame never inherits it. /// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and /// `denom` 8) for a frame that is not superres-scaled. pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) { fctx.superres.with(|c| c.set((upscaled_width, denom))); } /// `(upscaled_width, superres_denom)` when this frame is superres-scaled /// (libaom `av1_superres_scaled`), else `None`. pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> { let (w, d) = fctx.superres.with(std::cell::Cell::get); (w > 0 && d != 8).then_some((w, d)) } // Whether this superblock's single CDEF unit (this decoder has no 128x128 // SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal // read -- reset to `false` at the top of each superblock in the two tile // loops, spec `read_cdef`'s `cdef_transmitted[index]`. // Number of superblock columns in the current tile's grid, so // [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into // [`CDEF_IDX_GRID`]. // One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select // which of the header's `1 << cdef.bits` strength pairs applies to that // superblock's samples. // How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`] // has read, across every call on the current thread -- the gate's proof that a // `cdef_bits > 0` stream actually reached the new reader rather than every // superblock coincidentally being all-skip. thread_local! { static CDEF_IDX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // How many times a warp was suppressed for one PLANE because that plane's own // block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out, // reconinter.c) -- the gate's proof that a stream really carries the shape, // since the square `side`/`chroma_side` can be 8 or more while the plane's // true block is 4 wide (an 8x16 luma block's 4x8 chroma). thread_local! { static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`WARP_PLANE_SUPPRESS_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn warp_plane_suppress_hits() -> usize { WARP_PLANE_SUPPRESS_HITS.with(|c| c.get()) } /// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and /// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN /// block dimensions decide it -- never the square `side`/`chroma_side`, which /// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is /// bigger than the real block in one axis. pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool { if w >= 8 && h >= 8 { return true; } hit!(WARP_PLANE_SUPPRESS_HITS); false } /// Current value of [`CDEF_IDX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn cdef_idx_hits() -> usize { CDEF_IDX_HITS.with(|c| c.get()) } // lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no // counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the // non-chroma-reference block that must LEAVE its neighbours' chroma coefficient // contexts alone, and the intra-edge filter neighbour pair taken mi-exact // instead of from the coarse 16x16 cell. thread_local! { static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRA_IN_INTER_TXCTX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_in_inter_txctx_hits() -> usize { INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get()) } /// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize { NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get()) } /// Current value of [`EDGE_FILTER_MI_FIX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn edge_filter_mi_fix_hits() -> usize { EDGE_FILTER_MI_FIX_HITS.with(|c| c.get()) } // lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its // actual step (`1 << delta.q_res`, already the real multiplier, not the raw // 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a // true no-op, matching every existing gate stream's `delta_q_present == 0` // behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above. // The running quantizer index (spec `CurrentQIndex`, libaom // `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the // top of every tile (spec `decode_tile`), carried across superblocks within // that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the // dequantization call sites instead of the frame-constant `base_q_idx`. // This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11, // spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not // per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read // back at every dequantization call site keyed on which plane it is doing. // How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has // read, across every call on the current thread -- the gate's proof that a // `delta_q_present` stream actually reached the new reader. thread_local! { static DELTA_Q_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`DELTA_Q_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn delta_q_hits() -> usize { DELTA_Q_HITS.with(|c| c.get()) } /// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 = /// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads /// one), so it is always `0` here. fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) { let d = fctx.quant_deltas.with(|c| c.get()); match plane_idx { 0 => (d.y_dc, 0), 1 => (d.u_dc, d.u_ac), _ => (d.v_dc, d.v_ac), } } /// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom /// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`] /// at every block-decode call site (spec order `skip -> cdef -> delta_q`). /// A no-op when `delta_q_present` is unset, or when this block is not at the /// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in /// libaom, collapsed here to a position check since a partition tree's /// top-left leaf is the only block that can ever land there), or when that /// leaf both *is* the whole superblock and is `skip` (the one case libaom /// itself skips the read, state carrying over unchanged). fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) { if !fctx.delta_q_present.with(|c| c.get()) { return; } let sb_mi = sb_mi_cur(fctx) as usize; if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 { return; } // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, // computed against the sequence's own superblock size (lane-sb128b r1: // it used to be hardcoded against 64 and disabled under `sb128`, which a // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes // wrong). if is_whole_sb && skip { return; } let mut abs = dec.symbol(&mut cdfs.delta_q) as i32; const DELTA_Q_SMALL: i32 = 3; if abs >= DELTA_Q_SMALL { let rem_bits = dec.literal(3) + 1; let thr = (1i32 << rem_bits) + 1; abs = dec.literal(rem_bits) as i32 + thr; } let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true }; let reduced = if sign_negative { -abs } else { abs }; hit!(DELTA_Q_HITS); let res = fctx.delta_q_res.with(|c| c.get()); fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255))); } // lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi` // (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`. // The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`, // `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile, // mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever // updates index 0 and every reader treats that as the value for all 4 // indices (spec `read_delta_lf_params`'s own single-cdf branch). // How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has // read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`]. thread_local! { static DELTA_LF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`DELTA_LF_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn delta_lf_hits() -> usize { DELTA_LF_HITS.with(|c| c.get()) } /// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom /// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as /// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over /// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or /// read once into index 0 otherwise. fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) { if !fctx.delta_lf_present.with(|c| c.get()) { return; } let sb_mi = sb_mi_cur(fctx) as usize; if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 { return; } // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, // computed against the sequence's own superblock size (lane-sb128b r1: // it used to be hardcoded against 64 and disabled under `sb128`, which a // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes // wrong). if is_whole_sb && skip { return; } let multi = fctx.delta_lf_multi.with(|c| c.get()); let res = fctx.delta_lf_res.with(|c| c.get()); let count = if multi { 4 } else { 1 }; let mut cur = fctx.current_delta_lf.with(|c| c.get()); for i in 0..count { let mut abs = if multi { dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32 } else { dec.symbol(&mut cdfs.delta_lf) as i32 }; const DELTA_LF_SMALL: i32 = 3; if abs >= DELTA_LF_SMALL { let rem_bits = dec.literal(3) + 1; let thr = (1i32 << rem_bits) + 1; abs = dec.literal(rem_bits) as i32 + thr; } let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true }; let reduced = if sign_negative { -abs } else { abs }; cur[i] = (cur[i] + reduced * res).clamp(-63, 63); hit!(DELTA_LF_HITS); } fctx.current_delta_lf.with(|c| c.set(cur)); } /// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right /// after `skip` is known at every block-decode call site. A no-op at /// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and /// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/ /// `allow_intrabc`, so neither needs a separate check here. Reads once per /// superblock, at the first non-skip block. fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) { let bits = fctx.cdef_bits.with(|c| c.get()); if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) { return; } let idx = dec.literal(u32::from(bits)) as u8; fctx.cdef_transmitted.with(|c| c.set(true)); hit!(CDEF_IDX_HITS); let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize); let sb_cols = fctx.cdef_sb_cols.with(|c| c.get()); if sb_cols > 0 { fctx.cdef_idx_grid.with(|g| { let mut g = g.borrow_mut(); let i = sb_r * sb_cols + sb_c; if i < g.len() { g[i] = idx; } }); } } // --------------------------------------------------------------------------- // lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`; // this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus // the two consumers a real stream exercises: the per-segment quantizer index // (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level // (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/ // `read_intra_segment_id`/`read_inter_segment_id` and // `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL // PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which // is what the oracle every gate here compares against actually does. thread_local! { /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride). /// `PrevSegmentIds`: the primary reference frame's saved map, empty when /// this frame has no primary reference (spec `load_previous_segment_ids`). /// `(mi_rows, mi_cols)` for both maps above. /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead. /// The block currently being decoded -- read back by [`block_q_idx`]. /// The tile's own top-left mi position, for `AvailU`/`AvailL`. /// How many real `segment_id` symbols were read, and the set of segment /// ids any block ended up with -- the gate's proof the feature fired. static SEG_ID_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SEG_IDS_SEEN: std::cell::Cell = const { std::cell::Cell::new(0) }; /// How many `seg_id_predicted` symbols were read (temporal update). static SEG_PRED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Installs this frame's segmentation parameters and allocates its map, with /// `prev` the primary reference frame's saved map (spec /// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty /// slot). Called once per frame, whether or not segmentation is enabled. pub(crate) fn set_segmentation( seg: SegmentationParams, mi_rows: usize, mi_cols: usize, prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx, ) { fctx.seg.with(|s| *s.borrow_mut() = seg); fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols))); fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]); fctx.prev_seg_ids.with(|m| { let mut m = m.borrow_mut(); m.clear(); if let Some(p) = prev { if p.len() == mi_rows * mi_cols { m.extend_from_slice(p); } } }); fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]); fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]); fctx.cur_segment_id.with(|c| c.set(0)); } /// This frame's decoded segment map, to be stored into whichever reference /// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`). pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec { fctx.seg_ids.with(|m| m.borrow().clone()) } /// How many `segment_id` symbols have been read (never reset per frame). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn segment_id_hits() -> usize { SEG_ID_HITS.with(|c| c.get()) } /// How many distinct segment ids any decoded block has carried. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn segment_ids_seen() -> usize { SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize) } /// How many `seg_id_predicted` symbols have been read (temporal update). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn segment_pred_hits() -> usize { SEG_PRED_HITS.with(|c| c.get()) } /// Resets the segmentation hit counters (gate setup). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_segment_hits() { SEG_ID_HITS.with(|c| c.set(0)); SEG_IDS_SEEN.with(|c| c.set(0)); SEG_PRED_HITS.with(|c| c.set(0)); } /// `seg_feature_active_idx(segment_id, feature)` for the frame currently /// being decoded, with its `FeatureData` value. fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option { fctx.seg.with(|s| { let s = s.borrow(); s.feature_active(segment_id, feature) .then(|| i32::from(s.feature_data[segment_id][feature])) }) } /// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom /// `av1_get_qindex`) for the block currently being decoded: the running /// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data. /// Every dequant call site reads the block's quantizer through here. fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 { let base = fctx.current_q_idx.with(|c| c.get()); let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize; match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) { Some(data) => (base + data).clamp(0, 255), None => base, } } /// The segment id recorded for one mi cell of the current frame's map. fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 { let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); if mi_r >= mi_rows || mi_c >= mi_cols { return 0; } fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c]) } /// `set_segment_id`: stamps `id` over every mi cell this block covers. fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) { let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r))); fctx.seg_ids.with(|m| { let mut m = m.borrow_mut(); for y in 0..y_mis { for x in 0..x_mis { m[(mi_r + y) * mi_cols + mi_c + x] = id; } } }); fctx.cur_segment_id.with(|c| c.set(id)); SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id)); } /// `get_predicted_segment_id` (libaom `dec_get_segment_id` over /// `last_frame_seg_map`): the minimum previous-frame segment id over the /// block's own mi footprint. `0` when there is no previous map. fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 { let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); fctx.prev_seg_ids.with(|m| { let m = m.borrow(); if m.is_empty() { return 0; } let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r))); let mut id = u8::MAX; for y in 0..y_mis { for x in 0..x_mis { id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]); } } if id == u8::MAX { 0 } else { id } }) } /// `av1_neg_deinterleave` (libaom `decodemv.c:258`). fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 { if reference == 0 { return diff; } if reference >= max - 1 { return max - diff - 1; } let half = if 2 * reference < max { diff <= 2 * reference } else { diff <= 2 * (max - reference - 1) }; if half { return if diff & 1 != 0 { reference + ((diff + 1) >> 1) } else { reference - (diff >> 1) }; } if 2 * reference < max { diff } else { max - (diff + 1) } } /// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current /// frame's already-decoded above/left/above-left neighbours. fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) { let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get()); let (avail_u, avail_l) = (mi_r > row0, mi_c > col0); let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx))); let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx))); let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx))); let ctx = match prev_ul { None => 0, Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2, Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1, Some(_) => 0, }; let pred = match (prev_u, prev_l) { (None, l) => l.unwrap_or(0), (Some(u), None) => u, (Some(u), Some(l)) => { if prev_ul == Some(u) { u } else { l } } }; (pred, ctx) } /// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id /// when `skip`, otherwise one `segment_id` symbol de-interleaved against /// that prediction. Does NOT write the map -- callers do. fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 { let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx); if skip { return pred as u8; } let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32; hit!(SEG_ID_HITS); let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id)); neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8 } /// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block /// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the /// caller decides which by passing `pre_skip`). fn intra_segment_id( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, skip: bool, fctx: &crate::decode::FrameCtx, ) { if !fctx.seg.with(|s| s.borrow().enabled) { return; } let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx); write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx); } /// Whether this frame's intra blocks read their `segment_id` before `skip` /// (`SegIdPreSkip`); `false` also when segmentation is off. fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool { fctx.seg.with(|s| { let s = s.borrow(); s.enabled && s.seg_id_pre_skip }) } /// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`). /// Called at both spec positions of an inter frame's block: `pre_skip = true` /// before `skip_mode`/`skip`, and `pre_skip = false` after them. fn inter_segment_id( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, skip: bool, pre_skip: bool, fctx: &crate::decode::FrameCtx, ) { let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| { let s = s.borrow(); (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip) }); if !enabled { return; } if !update_map { // The map is inherited wholesale from the previous frame. let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx); write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx); return; } if pre_skip && !pre_skip_frame { return; } if !pre_skip && skip { // libaom: a skipped block never codes `seg_id_predicted`, and its // segment id is the spatial prediction. stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx); let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx); write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx); return; } let id = if temporal_update { let ctx = seg_pred_ctx(mi_r, mi_c, fctx); let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0; hit!(SEG_PRED_HITS); stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx); if predicted { predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx) } else { read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx) } } else { read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx) }; write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx); } /// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags. fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize { // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and // so contribute 0) outside the tile -- the availability check here is // what keeps a previous tile's stamps out of this tile's context. let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get()); let above = if mi_r > row0 { fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0)) } else { 0 }; let left = if mi_c > col0 { fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0)) } else { 0 }; usize::from(above + left) } /// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update. fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) { fctx.above_seg_pred.with(|m| { let mut m = m.borrow_mut(); for i in 0..w_mi { if let Some(cell) = m.get_mut(mi_c + i) { *cell = value; } } }); fctx.left_seg_pred.with(|m| { let mut m = m.borrow_mut(); for i in 0..h_mi { if let Some(cell) = m.get_mut(mi_r + i) { *cell = value; } } }); } // How many key-frame luma blocks resolved `smooth_neighbor` (spec // `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after // counter, proving a stream actually put a directional block next to a // smooth-predicted neighbour rather than every block reading the (previously // hardcoded `false`) edge-filter strength bucket unchanged. thread_local! { static SMOOTH_LUMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SMOOTH_LUMA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn smooth_luma_hits() -> usize { SMOOTH_LUMA_HITS.with(|c| c.get()) } thread_local! { /// lane-band46 r1: how many split-transform units answered their intra /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the /// palette2 r12 fix) than the standalone-block lookup this decoder used to /// apply to them (class reach-is-per-transform-unit). Every hit is a /// transform unit whose above-right / below-left reference samples would /// be wrong without that fix. static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SPLIT_TU_REACH_FIX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn split_tu_reach_fix_hits() -> usize { SPLIT_TU_REACH_FIX_HITS.with(|c| c.get()) } /// [`Reach::of_tu`] for one transform unit, counting how often that per-unit /// answer differs from the standalone-block answer the call sites used before /// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really /// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent /// block's top-left `(px, py)`. #[allow(clippy::too_many_arguments)] fn tu_reach( bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, block: Reach, px: usize, py: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx, ) -> Reach { let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block); let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx); if fixed != standalone { hit!(SPLIT_TU_REACH_FIX_HITS); } fixed } // How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12), // across every call on the current thread -- lane-chroma r3's own before/after // counter, proving a stream actually exercised chroma's smooth/paeth // predictor (the previously-refused round-2 gap) rather than every block // landing on DC/CFL/directional. thread_local! { static SMOOTH_UV_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SMOOTH_UV_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn smooth_uv_hits() -> usize { SMOOTH_UV_HITS.with(|c| c.get()) } // How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a // full superblock walk over, across every call on the current thread -- // lane-tiles r2's own gate-blind-to-feature guard: a gate over a // multi-tile stream must prove more than one tile actually fired, not just // that the stream carried tile_info.cols > 1. thread_local! { static TILE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`TILE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn tile_hits() -> usize { TILE_HITS.with(|c| c.get()) } // How many 4-pixel deblocking edge groups [`edge_params`] has actually // selected for filtering, across every call on the current thread -- the same // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream // exercised `apply_deblock` rather than every edge landing on level 0. thread_local! { static DEBLOCK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`, /// mirroring stream.rs's `pictures_decoded` so the two dumps index /// identically against aomdec's own `ec_frame_idx` in decodeframe.c. static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// Current value of [`DEBLOCK_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn deblock_hits() -> usize { DEBLOCK_HITS.with(|c| c.get()) } // lane-defon r1: how many COMPOUND_REFERENCE blocks read a // `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side, // spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a // stream built with `--enable-onesided-comp=1` really exercised the // `uni_comp_ref` alphabet rather than only bidirectional pairs. thread_local! { static UNI_COMP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`UNI_COMP_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn uni_comp_hits() -> usize { UNI_COMP_HITS.with(|c| c.get()) } // lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask // (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the // gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted // blend and not only the wedge arm. thread_local! { static DIFFWTD_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`DIFFWTD_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn diffwtd_hits() -> usize { DIFFWTD_HITS.with(|c| c.get()) } // lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm -- // a block size where `av1_is_wedge_used` is false (64x64 is the only such size // this decoder's square inter path reaches), so no `compound_type` symbol is // coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the // coded-symbol DIFFWTD blocks at 8x8/16x16/32x32. thread_local! { static DIFFWTD_INFERRED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`DIFFWTD_INFERRED_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn diffwtd_inferred_hits() -> usize { DIFFWTD_INFERRED_HITS.with(|c| c.get()) } // lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded // with `show_frame == 0`, output later by a `show_existing_frame` header // (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from // `stream::decode_stream`, which is where the frame header is consumed; the // gate's proof that the on-value really reached the bitstream rather than // being dropped by the rate control. thread_local! { static FWD_KF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`FWD_KF_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn fwd_kf_hits() -> usize { FWD_KF_HITS.with(|c| c.get()) } /// Records one decoded forward keyframe (see [`FWD_KF_HITS`]). pub(crate) fn note_fwd_kf() { hit!(FWD_KF_HITS); } // How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than // the block's own side, across every call on the current thread -- the same // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream // actually exercised a *split* transform under `TxMode::Select` rather than // every block coincidentally resolving `depth=0` (indistinguishable from // `TxMode::Largest` pixel-wise). thread_local! { static TX_DEPTH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma // transform smaller than their own side (`tx_depth != 0`) while coding a // chroma prediction other than `DC_PRED` -- the pair the square path's chroma // only exercises with aomenc's tx-size search left ON (its default), which // every older recipe in this file pins off. Counted at the block, so a stream // where RD happened to give every split-transform block a DC chroma mode // reads as zero rather than silently passing for free. thread_local! { static SQ_CHROMA_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SQ_CHROMA_TX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sq_chroma_tx_hits() -> usize { SQ_CHROMA_TX_HITS.with(|c| c.get()) } /// Current value of [`TX_DEPTH_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn tx_depth_hits() -> usize { TX_DEPTH_HITS.with(|c| c.get()) } // lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree // read, and how many of those actually took the split, on the current thread // -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a // stream exercised spec 5.11.17's `read_var_tx_size` rather than every block // coincidentally coding one whole-block transform. thread_local! { static TXFM_SPLIT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; static TXFM_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // lane-inter4 r2: rectangular INTER residual coding -- how many rect // strips coded one whole-block rect transform unit, and how many split // their rect max transform into square sub-transforms. static RECT_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT_INTER_TXSPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // lane-r14 r2: luma transform units of an inter strip with a 64-px axis // (64x32/32x64/64x16/16x64), whose coefficients are coded as the // truncated low-32 corner. static RECT64_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4 // inter strip, `[32x8, 8x32]`. static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32]. static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8] // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip. static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter // frame -- 16x8 and 8x16 inter leaves. static INTER_LEAF16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTER_LEAF16_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits, // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] -- // `decode_inter_block` already carries forty parameters and both are // frame-constant. // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit, // frame-constant like the two above and stashed the same way -- an intra // block inside an inter frame reads `use_filter_intra` under it. } /// Current value of [`TXFM_SPLIT_READS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn txfm_split_reads() -> usize { TXFM_SPLIT_READS.with(|c| c.get()) } /// Current value of [`TXFM_SPLIT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn txfm_split_hits() -> usize { TXFM_SPLIT_HITS.with(|c| c.get()) } /// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn inter_leaf16_horz_hits() -> usize { INTER_LEAF16_HORZ_HITS.with(|c| c.get()) } /// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn inter_leaf16_vert_hits() -> usize { INTER_LEAF16_VERT_HITS.with(|c| c.get()) } /// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2). pub(crate) fn rect_inter_tu_hits() -> usize { RECT_INTER_TU_HITS.with(|c| c.get()) } /// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2). pub(crate) fn rect_inter_txsplit_hits() -> usize { RECT_INTER_TXSPLIT_HITS.with(|c| c.get()) } /// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2). pub(crate) fn rect64_inter_tu_hits() -> usize { RECT64_INTER_TU_HITS.with(|c| c.get()) } /// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]` /// whole-block luma units of a 32x32-level 1:4 inter strip. pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] { RECT32X8_INTER_TU_HITS.with(|c| c.get()) } /// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many /// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`. pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] { VARTX_RECT_LEAF_HITS.with(|c| c.get()) } /// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8 /// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`. pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] { VARTX_RECT_LEAF4_HITS.with(|c| c.get()) } /// Records one rectangular var-tx leaf. fn vartx_rect_leaf_hit(tw: usize, th: usize) { if crate::envflags::env_flag!("EC_VARTXLEAF") { eprintln!("EC_VARTXLEAF tw={tw} th={th}"); } let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS }; cell.with(|c| { let mut h = c.get(); h[usize::from(th > tw)] += 1; c.set(h); }); } /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/ /// [`ENABLE_FILTER_INTRA_INTER`]. pub(crate) fn set_inter_tx_mode( tx_select: bool, reduced_tx_set: bool, enable_filter_intra: bool, fctx: &crate::decode::FrameCtx, ) { fctx.tx_select_inter.with(|c| c.set(tx_select)); fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra)); } // How many `partition_w16` reads (a 16x16 block's own partition symbol, key // intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a // plain default-settings aomenc run over lavfi mandelbrot hits this arm on // frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not // the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real // `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`, // chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8 // path above). thread_local! { static VERT_B_INTRA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`VERT_B_INTRA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn vert_b_intra_hits() -> usize { VERT_B_INTRA_HITS.with(|c| c.get()) } // lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in // `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two // 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`, // the non-skip coefficient path lane-rectx proved); the gate hard-asserts // every arm separately so a run where aomenc's RD only picked one cannot // pass as proof of four. thread_local! { static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } // [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16). thread_local! { /// 4x4 transform units decoded inside an 8x8 square of a /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove /// a real `--enable-tx-size-search=1` stream reaches it. static VERT_AB_TX4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn vert_ab_tx4_hits() -> usize { VERT_AB_TX4_HITS.with(std::cell::Cell::get) } #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn ab16_hits_by_arm() -> [usize; 4] { AB16_HITS.with(std::cell::Cell::get) } fn bump_ab16(arm: usize) { hit_do! { AB16_HITS.with(|c| { let mut v = c.get(); v[arm] += 1; c.set(v); }); } } // How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/ // `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above // showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7), // not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's // very first non-NONE/SPLIT symbol" claim was about decode ORDER within one // superblock's z-order recursion, not raster mi position). thread_local! { static HORZ_VERT_INTRA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`HORZ_VERT_INTRA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn horz_vert_intra_hits() -> usize { HORZ_VERT_INTRA_HITS.with(|c| c.get()) } // How many blocks were decoded as a frame-edge rect strip -- the single // coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge // (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose // height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter // paths share the counter. thread_local! { static EDGE_RECT_STRIP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`EDGE_RECT_STRIP_HITS`]. #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live pub(crate) fn edge_rect_strip_hits() -> usize { EDGE_RECT_STRIP_HITS.with(|c| c.get()) } // lane-interedge r1: frame-edge half strips on the INTER path, per partition // level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The // index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and // `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films // are height mod 16 == 8, so every inter frame crosses these nodes. thread_local! { static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) }; } /// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`]. pub(crate) fn bump_inter_edge_strip(idx: usize) { hit_do! { INTER_EDGE_STRIP_HITS.with(|c| { let mut v = c.get(); v[idx] += 1; c.set(v); }); } } // lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT // forced split -- libaom `decode_partition` (decodeframe.c): // `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one // straddle case that reads NO symbol at all. Indexed by level: // 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it. thread_local! { static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } fn bump_edge_both_cut(level: usize) { hit_do! { EDGE_BOTH_CUT_HITS.with(|c| { let mut v = c.get(); v[level] += 1; c.set(v); }); } } /// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`). pub fn inter_edge_strip_hits() -> [usize; 6] { INTER_EDGE_STRIP_HITS.with(|c| c.get()) } /// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits /// into the next one (class `counter-from-refused-stream`). pub fn reset_inter_edge_strip_hits() { INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6])); } /// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn edge_both_cut_hits() -> [usize; 4] { EDGE_BOTH_CUT_HITS.with(|c| c.get()) } /// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_edge_both_cut_hits() { EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4])); } // How many HORZ/VERT intra strips resolved a SPLIT luma transform // (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) -- // the case every rect path here refused by name before, and the first // refusal the user's ReelB extract (600s in) stops at. thread_local! { static RECT_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_SPLIT_TX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_split_tx_hits() -> usize { RECT_SPLIT_TX_HITS.with(|c| c.get()) } // The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one // side 64) AND split past the first depth, i.e. tiled more than one unit in // each axis -- the only shape with a transform unit that has neighbours on // two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one // no gate fired before lane-rectsplit r2 (the shared counter above also // counts 32x32-level and depth-1 strips, so it cannot prove this case). thread_local! { static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_split_sb_interior_tu_hits() -> usize { RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get()) } // Per-shape hit counts for the rect chroma transforms lane-rectchroma r1 // wired into [`decode_rect_split`] -- the shapes a split-transform strip's // chroma half takes that had no coefficient tables before (index order: // 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only // proves the pair it happens to hit cannot catch a transposed scan/context // table (class scan-weights-cross-axis). thread_local! { static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } /// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] { RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get()) } // How many HORZ/VERT intra strips actually predicted with filter intra // (lane-rectsplit r1) -- the case `decode_block_rect` refused by name // ("this decoder predicts square-only") until `predict_filter_intra` took // `bw`x`bh`. thread_local! { static FILTER_INTRA_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`FILTER_INTRA_RECT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn filter_intra_rect_hits() -> usize { FILTER_INTRA_RECT_HITS.with(|c| c.get()) } // As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips // (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol // was never read at all before that round, so a gate needs to prove the flag // fired at THAT shape and not at a 16x8 one somewhere else in the frame. // Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA` // carry different probabilities (18101 vs 20229), so a transposed pair is // only caught by a gate that sees the flag fire on BOTH shapes (class // scan-weights-cross-axis). thread_local! { static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn filter_intra_rect4_horz_hits() -> usize { FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get()) } /// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn filter_intra_rect4_vert_hits() -> usize { FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get()) } // How many rectangular transform units actually coded coefficients through // [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate // exercised the rect coefficient reader at all rather than passing on // all-skip blocks. thread_local! { static RECT_COEFF_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT_CLASS1_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_COEFF_TU_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_coeff_tu_hits() -> usize { RECT_COEFF_TU_HITS.with(|c| c.get()) } /// Rectangular transform units whose resolved `tx_type` is a 1D class /// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can /// pin that the 1D-class-on-a-RECT-transform path fired rather than settling /// for the square reader's own 1D types. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_class1_hits() -> usize { RECT_CLASS1_HITS.with(|c| c.get()) } // As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16 // (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the // shapes whose `use_filter_intra` symbol had no CDF class before this round. // A gate asserting the wider counter would be satisfied by a 32x16 strip and // prove nothing about the new shapes. thread_local! { static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn filter_intra_rect_sub16_hits() -> usize { FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get()) } // As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down: // 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16 // counter would be satisfied by a 16x8 strip and prove nothing here. thread_local! { static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn filter_intra_rect_sub8_hits() -> usize { FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get()) } // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D` // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every // call on the current thread -- the same before/after counter pattern as // [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split // `eob_pt`/1D-neighbour context path rather than every block coincidentally // landing on `DCT_DCT`. thread_local! { static TX_CLASS1_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // How many `uv_mode` reads resolved to a directional chroma mode (neither // `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream // actually exercised chroma's own directional predictor. thread_local! { static DIRECTIONAL_UV_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`DIRECTIONAL_UV_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn directional_uv_hits() -> usize { DIRECTIONAL_UV_HITS.with(|c| c.get()) } // How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as // something other than [`ANGLE_DELTA_ZERO`], across every call in the // process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`], // proving a stream actually exercised a nonzero angle delta. thread_local! { static ANGLE_DELTA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // How many [`read_single_ref`] reads resolved to a reference other than // `LAST_FRAME`, across every call on the current thread -- the same before/after // counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually // exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's // only other supported one so far) rather than every block coincidentally // resolving `LAST_FRAME`. thread_local! { static NON_LAST_REF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`NON_LAST_REF_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn non_last_ref_hits() -> usize { NON_LAST_REF_HITS.with(|c| c.get()) } // Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter // per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one // specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`) // can prove THAT reference fired rather than any non-`LAST_FRAME` one -- // `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a // `GOLDEN_FRAME` draw it did not ask for. thread_local! { static LAST2_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { static LAST3_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { static GOLDEN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { static BWDREF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { static ALTREF2_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { static ALTREF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp) // -- proves a `reference_select` stream actually reached a block that picked // compound, not just that the header bit was set. Every such block is // refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]), // so this only ever counts attempted reads, never a completed decode. thread_local! { static COMP_MODE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`COMP_MODE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn comp_mode_hits() -> usize { COMP_MODE_HITS.with(|c| c.get()) } // How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y // use for, across every call on the current thread -- the same before/after // counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually // exercised palette reconstruction rather than only reading and refusing the // `palette_y_mode` symbol. thread_local! { static PALETTE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`PALETTE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn palette_hits() -> usize { PALETTE_HITS.with(|c| c.get()) } // lane-tiles r12: of those, how many sat at their own TILE's left column -- // exactly the blocks whose palette cache/ctx must NOT see the previous tile's // colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile // palette gate that never hits one proves nothing about the tile guard. thread_local! { static PALETTE_TILE_LEFT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`PALETTE_TILE_LEFT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn palette_tile_left_hits() -> usize { PALETTE_TILE_LEFT_HITS.with(|c| c.get()) } // lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma // palette use -- proves a stream actually reconstructed UV palette pixels, // not just read and refused the `palette_uv_mode` symbol. thread_local! { static PALETTE_UV_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`PALETTE_UV_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn palette_uv_hits() -> usize { PALETTE_UV_HITS.with(|c| c.get()) } // lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`]) // decoded a real palette-Y use -- proves the rect strip's own palette syntax // (not just the square path's) actually fired. thread_local! { static PALETTE_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`PALETTE_RECT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn palette_rect_hits() -> usize { PALETTE_RECT_HITS.with(|c| c.get()) } // lane-palette2 r6: how many HORZ/VERT rect intra strips ran the // [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] -- // i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in // range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per // RD, almost always refused-on-use because the block doesn't end up USING a // palette -- see r5's report). This is the site the removed refusal // ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it // fired here whether or not the block picked a palette, so this is the // counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost // never observes. thread_local! { static RECT_SCREEN_CONTENT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_SCREEN_CONTENT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_screen_content_hits() -> usize { RECT_SCREEN_CONTENT_HITS.with(|c| c.get()) } // lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a // split luma transform (`logical_tx != side`) -- proves the per-TU index-map // windowing actually ran, not just that the whole-block path stayed exact. // Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16); // first actually incremented in r7, when the refusal it guarded was lifted. thread_local! { static PALETTE_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves /// (16x8/8x16), the two shapes the lifted refusals named. static RECT4_PALETTE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT4_PALETTE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect4_palette_hits() -> usize { RECT4_PALETTE_HITS.with(|c| c.get()) } /// Current value of [`PALETTE_SPLIT_TX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn palette_split_tx_hits() -> usize { PALETTE_SPLIT_TX_HITS.with(|c| c.get()) } thread_local! { /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen` /// stream stopped on, since aomenc palettes square blocks at 8 bit and /// `--min-partition-size=8` puts them on this leaf path. static PALETTE_LEAF8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`PALETTE_LEAF8_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn palette_leaf8_hits() -> usize { PALETTE_LEAF8_HITS.with(|c| c.get()) } /// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_palette_leaf8_hits() { PALETTE_LEAF8_HITS.with(|c| c.set(0)); } thread_local! { /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level) /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette /// block that also carries a real, corner-cropped luma transform. static PALETTE_SB_STRIP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`PALETTE_SB_STRIP_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn palette_sb_strip_hits() -> usize { PALETTE_SB_STRIP_HITS.with(|c| c.get()) } /// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_palette_sb_strip_hits() { PALETTE_SB_STRIP_HITS.with(|c| c.set(0)); } // lane-t900 r22: palette blocks reconstructed inside an INTER frame (the // intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted // apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame // capability rather than the key frame's, which every screen stream also // carries. thread_local! { static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8 // LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the // shared counter too, so only this one proves a gate really reached the leaf // where the refusal used to sit. thread_local! { static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; } /// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`. pub(crate) fn inter8_palette_hits() -> (usize, usize) { INTER8_PALETTE_HITS.with(std::cell::Cell::get) } /// Current values of the two intra-in-inter palette counters, `(y, uv)`. pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) { ( INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()), INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()), ) } // lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform // and which are therefore predicted one transform unit at a time (a skipped // block codes no coefficients, so nothing else in the stream witnesses this // path -- only the pixels do). thread_local! { static SKIP_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units). pub fn skip_split_tx_hits() -> usize { SKIP_SPLIT_TX_HITS.with(|c| c.get()) } /// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt. pub fn reset_skip_split_tx_hits() { SKIP_SPLIT_TX_HITS.with(|c| c.set(0)); } // lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth` // symbol split their luma transform, bucketed by block side (8, 16, 32, 64) -- // the gate's proof that the lifted path actually ran, per size. thread_local! { static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } /// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] { INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get) } /// A just-decoded palette-Y block's own predicted pixels /// (`side*side`, row-major, `colors[map[i]]`), consumed by /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a /// per-block override through `read_plane`'s two dozen call sites is the /// alternative this avoids). Always empty again once that call consumes /// it (`.take()`), so a non-palette block's own `reconstruct` call never /// sees stale state. /// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct` /// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a /// site whose reconstruct never runs would be picked up by the NEXT block's /// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site. #[track_caller] fn set_palette_pred(buf: Vec, fctx: &crate::decode::FrameCtx) { if crate::envflags::env_flag!("EC_DEBUG_PAL") { let stale = fctx.palette_pred.with(|c| c.borrow().is_some()); eprintln!( "PALSET len={} stale={stale} at {}", buf.len(), std::panic::Location::caller() ); } fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf)); } #[track_caller] fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option> { let got = fctx.palette_pred.with(|c| c.borrow_mut().take()); if crate::envflags::env_flag!("EC_DEBUG_PAL") { eprintln!( "PALTAKE len={:?} at {}", got.as_ref().map(Vec::len), std::panic::Location::caller() ); } got } /// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over /// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the /// pixels, because at parse time this block's own luma is still queued. #[derive(Clone, Copy, Debug)] pub(crate) struct CflSrc { px: usize, py: usize, bw: usize, bh: usize, /// Which averager the parse site asked for -- [`cfl_ac_q3_rect`] and /// [`cfl_ac_q3`] are not the same function at `bw == bh`. rect: bool, } fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc { CflSrc { px, py, bw: side, bh: side, rect: false } } fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc { CflSrc { px, py, bw, bh, rect: true } } /// lane-wave1 step (i): the pixel-writing half of block decoding, recorded /// instead of executed. Each variant is the resolved argument tuple of the /// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push /// order performs exactly the same writes in exactly the same order -- /// entropy parsing no longer touches the frame's own planes (except the two /// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run /// the replay on a superblock-row wavefront worker. /// The dequantization + inverse transform of one transform unit, kept as its /// INPUTS so that a recorded write carries the work instead of its result /// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the /// recon worker, not on the parsing thread. `stride == 0` means the dense /// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid /// `reconstruct_mc_rect` reads both of its buffers at. #[derive(Clone, Copy)] pub(crate) struct TxParams { pub(crate) w: usize, pub(crate) h: usize, pub(crate) bit_depth: u8, pub(crate) q_idx: i32, pub(crate) dc_delta: i32, pub(crate) ac_delta: i32, pub(crate) tx_type: TxType, pub(crate) stride: usize, } impl TxParams { /// The one copy of the produce-the-residual code: the inline path calls it /// on the parse thread, the wavefront worker calls it on its own, so both /// are the same function on the same inputs and byte-identical. fn run(self, grid: &[i32]) -> Vec { let residual = dequant_and_inverse_typed_wh( grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta, self.tx_type, ); // An all-zero grid transforms to the empty marker, and a strided copy // of zeros is still zeros: the marker passes straight through. if residual.is_empty() { return residual; } if self.stride == 0 { return residual; } let mut strided = vec![0i32; self.stride * self.stride]; for row in 0..self.h { strided[row * self.stride..][..self.w] .copy_from_slice(&residual[row * self.w..][..self.w]); } strided } } /// A recorded write's residual: already transformed, or the coefficients and /// [`TxParams`] the worker transforms itself. pub(crate) enum Residual { /// An already-transformed residual in the arena, `(offset, len)`; a zero /// `len` is the all-zero marker [`dense_residual`] expands. Done(u32, u32), /// The coefficients live in the pushing tile's arena /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset, /// len)` in it. Coeffs(TxParams, u32, u32), } impl Residual { /// The record for a transform unit whose coefficient grid is all zero: /// the empty marker, so neither the grid nor the residual is cloned and /// the worker never runs the transform (60% of the 4K segment's units). fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self { if is_zero_grid(grid) { return Self::Done(0, 0); } Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32) } /// A residual the parse thread already transformed, kept in the arena /// instead of its own `Vec`. fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self { // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself, // which is exactly the all-zero marker -- one pointer compare instead // of copying up to 64 KB of zeros into the arena per block. if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) { return Self::Done(0, 0); } Self::Done(push_coeffs(residual, fctx), residual.len() as u32) } /// The residual to reconstruct with; `scratch` is where a transform run /// on this thread lands, so the caller owns that buffer. fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec) -> &'a [i32] { match self { Self::Done(off, len) => &arena[off as usize..][..len as usize], Self::Coeffs(p, off, len) => { *scratch = p.run(&arena[off as usize..][..len as usize]); scratch } } } } /// Appends to the tile's coefficient arena, returning the offset the record /// carries; see [`crate::decode::FrameCtx::coeff_arena`]. fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 { fctx.coeff_arena.with(|a| { let mut a = a.borrow_mut(); let off = a.len(); a.extend_from_slice(v); off as u32 }) } /// [`push_coeffs`] for a recorded prediction. fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 { fctx.pred_arena.with(|a| { let mut a = a.borrow_mut(); let off = a.len(); a.extend_from_slice(v); off as u32 }) } /// An all-zero residual, for the transform units that code no coefficient: /// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY, /// and the reconstruction loops below read this instead of a per-unit /// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry /// (a 128-wide inter block's prediction stride). pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128]; /// lane-blockscratch: one plane's coefficient levels as the block-tail /// neighbour writes want them. A plane that coded nothing (a skipped block, a /// strip with no chroma, luma under a var-tx split whose units already wrote /// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and /// zeroing up to 64 KB of its own per block. #[derive(Clone)] enum Grid { Zero(usize), Own(Vec), } /// lane-blockscratch: the mu-chunk chroma collector, allocated by the first /// unit that writes into it. Only a block wider or taller than 64 px codes its /// chroma per 64x64 chunk; every smaller block used to allocate and zero both /// collectors per block and then drop them untouched. fn mu_units(v: &mut Vec, n: usize) -> &mut Vec { if v.is_empty() { *v = vec![0i32; n]; } v } impl std::ops::Deref for Grid { type Target = [i32]; fn deref(&self) -> &[i32] { match self { Grid::Zero(n) => &ZERO_RESIDUAL[..*n], Grid::Own(v) => v, } } } /// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the /// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of /// transform units that code no coefficient without the scan (lane-coefgrid). pub(crate) fn is_zero_grid(grid: &[i32]) -> bool { std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0) } /// `residual`, or `n` zeros when it is the empty all-zero marker. fn dense_residual(residual: &[i32], n: usize) -> &[i32] { if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual } } /// Where a recorded motion-compensated write reads its prediction from. /// /// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is /// the parse thread's single biggest reconstruction cost, so at /// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block /// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker /// runs it into its own three-plane slot, and every transform unit of that /// block then reads its window out of that slot ([`Pred::Cur`]). #[derive(Clone, Copy)] pub(crate) enum Pred<'a> { /// A prediction the parse thread already built, at its own stride /// (`stride == 0` means "the reader's own `stride` argument"). Inline(&'a [u16], usize), /// The current block's deferred prediction: plane, its stride, and this /// unit's offset into it. Cur { plane: usize, stride: usize, off: usize }, } impl<'a> Pred<'a> { /// The same prediction read at an explicit stride. fn view(self, stride: usize) -> Self { match self { Self::Inline(b, _) => Self::Inline(b, stride), Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off }, } } /// The materialised buffer and the stride to read it at (`stride` is the /// reader's own when this prediction was built dense); `None` for a /// deferred prediction, which only a recorded op can carry. fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> { match self { Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })), Self::Cur { .. } => None, } } /// This prediction's window starting `n` samples in. fn offset(self, n: usize) -> Self { match self { Self::Inline(b, s) => Self::Inline(&b[n..], s), Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n }, } } } /// [`Pred`], resolved into what a recorded op carries. pub(crate) enum PredSrc { /// A prediction window in the tile's prediction arena, `(offset, len)`. Owned(u32, u32), /// A window of the block prediction: its plane, its offset, and the /// stride it is read at -- which is the block's, not necessarily the /// op's (a transform unit's residual stays dense, so the worker takes /// its window out of the block prediction itself). Cur { plane: usize, off: usize, src: usize }, } /// One block's whole-block prediction build, deferred to a recon worker. /// /// The closure borrows the tile's reference pictures and its own frame-level /// tables; [`WaveGuard`] joins every worker before the tile decoder returns, /// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once /// here for the closure's `'static`/`Send` laundering in [`push_pred`]. pub(crate) struct PredBuild( Box< dyn FnOnce( &mut PlaneBuf<'static>, &mut PlaneBuf<'static>, &mut PlaneBuf<'static>, &crate::decode::FrameCtx, // lane-blockmem: the previous block's three prediction buffers, // refilled in place -- the build used to return three fresh // `Vec`s per block and drop these. &mut [Vec; 3], ), >, ); // SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference // pictures and frame tables, and the closure runs on exactly one worker. #[allow(unsafe_code)] unsafe impl Send for PredBuild {} /// `true` when this tile's writes are recorded for the wavefront instead of /// performed at the push site, i.e. when a prediction may be deferred. fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool { fctx.recon_planes.with(std::cell::Cell::get).is_none() } /// The previous block's prediction buffer, cleared and zero-filled to `n` /// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced, /// without the per-block allocation and free. fn refill(mut v: Vec, n: usize) -> Vec { // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`) // than resized element by element -- which is every block on the inline // path, where there is no previous buffer to reuse. if v.capacity() < n { return vec![0u16; n]; } v.clear(); v.resize(n, 0); v } /// Records one block's prediction build for the worker that reconstructs it. #[allow(unsafe_code)] fn push_pred<'a>( fctx: &crate::decode::FrameCtx, f: impl FnOnce( &mut PlaneBuf<'static>, &mut PlaneBuf<'static>, &mut PlaneBuf<'static>, &crate::decode::FrameCtx, &mut [Vec; 3], ) + 'a, ) { type Dyn<'x> = dyn FnOnce( &mut PlaneBuf<'static>, &mut PlaneBuf<'static>, &mut PlaneBuf<'static>, &crate::decode::FrameCtx, &mut [Vec; 3], ) + 'x; let boxed: Box> = Box::new(f); // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`] // before the borrows the closure holds go out of scope. let boxed: Box> = unsafe { std::mem::transmute(boxed) }; push_op(fctx, ReconOp::Pred(PredBuild(boxed))); } /// One superblock's recorded writes plus the two arenas they index -- the /// unit a wavefront worker takes off the queue (lane-recoparse). pub(crate) struct ReconJob { ops: Vec, coeffs: Vec, preds: Vec, } pub(crate) enum ReconOp { /// lane-wave4: build this block's prediction into the worker's slot. Pred(PredBuild), Intra { plane: usize, x: usize, y: usize, bw: usize, bh: usize, /// `true` when the parse site called `reconstruct_rect` (whose /// `edges_rect` differs from `edges` even at `bw == bh`). rect: bool, mode: usize, angle_delta: i32, reach: Reach, residual: Residual, cfl: Option<(i32, CflSrc)>, filter_intra: Option, smooth_neighbor: bool, /// The palette/intrabc prediction override, taken off /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read /// from that slot by the replay. pred: Option>, }, Mc { plane: usize, x: usize, y: usize, stride: usize, w: usize, h: usize, prediction: PredSrc, residual: Residual, }, } /// The three planes of the tile currently being decoded, as raw pointers. /// /// corner-cut: at one reconstruction thread a recorded write must cost /// nothing -- deferring it to the end of the superblock is +1.2% /// instructions and +4.5% wall on 4K, because the residual is written at /// parse and read back cache-cold at replay. So the recorded op is performed /// at the push site instead, through the pointers the tile decoder registers /// once ([`ReconInline`]), which is the same thread, the same order and the /// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse /// stack still holds aliases them, exactly the [`crate::par::Shared`] /// trade-off (Miri's stacked borrows would flag both). The upgrade path is /// threading the three planes down every `read_plane`/`read_inter_plane` /// call site (~40) so the push site owns the borrow it writes through. #[derive(Clone, Copy)] pub(crate) struct ReconPlanes( *mut PlaneBuf<'static>, *mut PlaneBuf<'static>, *mut PlaneBuf<'static>, ); // SAFETY: a `FrameCtx` sent to another thread (a frame worker, or // [`filter_ctx_copy`]) is always one whose guard is not installed, so the // value travelling is `None`; the pointers never leave the tile decoder's // own thread. #[allow(unsafe_code)] unsafe impl Send for ReconPlanes {} // SAFETY: the wavefront's workers share one `ReconPlanes` and write provably // disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`] // contract, one superblock per band instead of one row band. #[allow(unsafe_code)] unsafe impl Sync for ReconPlanes {} /// Registers the tile's planes for inline reconstruction and unregisters them /// on every exit from the tile decoder, including the `?` ones -- a stale /// pointer here would outlive the planes, since [`FrameCtx`] outlives the /// tile. pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx); #[allow(unsafe_code)] impl<'a> ReconInline<'a> { /// Installs the guard for this tile when reconstruction is inline /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write /// to the queue instead, for the wavefront workers to replay. fn install( fctx: &'a crate::decode::FrameCtx, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, ) -> Option { if crate::par::recon_threads() != 1 { return None; } // SAFETY: the planes are locals of the tile decoder and outlive the // guard, which is dropped on every exit from it (including `?`); see // [`ReconPlanes`] for the aliasing trade-off. let planes = ReconPlanes( std::ptr::from_mut(y), std::ptr::from_mut(u), std::ptr::from_mut(v), ); fctx.recon_planes.with(|c| c.set(Some(planes))); Some(Self(fctx)) } } impl Drop for ReconInline<'_> { fn drop(&mut self) { self.0.recon_planes.with(|c| c.set(None)); } } #[allow(unsafe_code)] fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) { if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) { // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one // the parse site would have performed itself before lane-wave1. // The inline path never records coefficients (the transform runs at // the push site), so the arena is not read here. unsafe { exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx) }; return; } fctx.recon_ops.with(|c| c.borrow_mut().push(op)); } /// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded /// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`. /// /// The parser keeps parsing and never touches the planes; each superblock's /// drained `Vec` becomes one job, keyed by the superblock's own /// `(row, column)` inside the tile (128x128 superblocks are one job for all /// four of their 64x64 visits, since a 128 block writes across quadrants). /// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and /// `(r, c - 1)` are complete -- the classic wavefront rule, which covers /// every pixel an intra predictor can read (its edges reach one block right /// along the row above and one block down the column to the left, both /// inside those two neighbours) and every CfL AC read (this block's own /// luma, written by this same job). Jobs are handed out in raster order, so /// the oldest outstanding one always has its dependencies met: no deadlock. /// /// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are /// `thread_local!` and miss every worker, which is why the default is 1. pub(crate) struct WaveState { q: std::sync::Mutex, cv: std::sync::Condvar, planes: ReconPlanes, /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op). bit_depth: u8, enable_edge_filter: bool, last_col: usize, } struct WaveQueue { /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a /// row's front job can ever be runnable -- a job waits on its own left /// neighbour -- so a worker takes the lowest row whose front job's /// dependencies are met. Popping the raster-oldest job instead (what /// this replaced) put every worker on the SAME row, where the wavefront /// rule serialises them, which is why 4 workers ran the tile at 1.2x. rows: Vec>, /// Jobs sitting in `rows`, so a worker knows the queue is empty without /// walking it. queued: usize, /// Per superblock row, the last column reconstructed (-1 = none yet). done: Vec, /// Per superblock row, the last column PARSED (submitted, whether or not /// it recorded any write) and the last column actually pushed as a job /// (-1 = none). A row is fully reconstructed once it has been parsed to /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt /// reads that to release the row's filters (see [`wave_rows_complete`]). last_sub: Vec, last_push: Vec, /// Jobs popped but not finished -- what [`wave_barrier`] waits out. active: usize, closed: bool, /// lane-sballoc: the three per-superblock buffers a finished job hands /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no /// first-touch page faults) instead of the `Vec::with_capacity` it used /// to make per superblock -- 3 allocations and 3 frees per superblock, /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives /// inside the queue's own mutex, which both sides already take. free: Vec, free_cap: usize, } /// One recycled set of [`ReconJob`] buffers (lane-sballoc). type JobBufs = (Vec, Vec, Vec); impl WaveQueue { /// The lowest-row queued job whose wavefront dependencies are satisfied, /// or `None` (with the blocking condition counted when instrumented). fn take_runnable( &mut self, last_col: usize, stats: bool, ) -> Option<(usize, usize, ReconJob)> { let mut blocked: Option = None; for r in 0..self.rows.len() { let Some(front) = self.rows[r].front() else { continue; }; let c = front.0; let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize; let left = c == 0 || self.done[r] >= c as isize - 1; if above && left { let (c, job) = self.rows[r].pop_front().expect("front checked above"); self.queued -= 1; return Some((r, c, job)); } if blocked.is_none() { blocked = Some(above); } } if stats { match blocked { Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed), Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed), None => 0, }; } None } } /// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon /// worker's time goes (busy replaying, waiting for a dependency, idle on an /// empty queue), how far ahead the parse thread is, and how often the two /// parse-time pixel reads barrier the wavefront. Cumulative for the process, /// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the /// whole run. const WS_SLOTS: usize = 16; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering::Relaxed; static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS]; static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS]; static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS]; static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS]; static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0); static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0); /// Parse-thread time between two submits, i.e. everything parse still does /// itself (symbol decode plus the predictions not deferred). static WS_PARSE: AtomicU64 = AtomicU64::new(0); /// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`] /// (the intrabc/interintra reads) and at the tile's end. static WS_BARRIER: AtomicU64 = AtomicU64::new(0); static WS_BARRIERS: AtomicU64 = AtomicU64::new(0); static WS_DRAIN: AtomicU64 = AtomicU64::new(0); static WS_TILES: AtomicU64 = AtomicU64::new(0); fn wave_stats() -> bool { static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); match ON.load(Relaxed) { 0 => { let on = crate::envflags::var("EC_AV1_WAVE_STATS") .map(|v| v.trim() == "1") .unwrap_or(false); ON.store(1 + u8::from(on), Relaxed); on } n => n == 2, } } fn wave_stats_dump() { let ms = |n: u64| n as f64 / 1e6; let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed)); for i in 0..WS_SLOTS { let jobs = WS_JOBS[i].load(Relaxed); if jobs == 0 { continue; } s += &format!( " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us", WS_OPS[i].load(Relaxed) as f64 / jobs as f64, ms(WS_BUSY[i].load(Relaxed)), ms(WS_WAIT[i].load(Relaxed)), WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3, ); } s += &format!( " | pipe={}/{}", PIPE_FRAMES.load(Relaxed), PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed), ); s += &format!( " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}", ms(WS_PARSE.load(Relaxed)), ms(WS_BARRIER.load(Relaxed)), WS_BARRIERS.load(Relaxed), ms(WS_DRAIN.load(Relaxed)), WS_BLOCK_ABOVE.load(Relaxed), WS_BLOCK_LEFT.load(Relaxed), ); eprintln!("{s}"); } #[allow(unsafe_code)] fn wave_worker(st: &WaveState, idx: usize) { let fctx = FrameCtx::new(); fctx.bit_depth.set(st.bit_depth); fctx.enable_edge_filter.set(st.enable_edge_filter); let stats = wave_stats(); let slot = idx.min(WS_SLOTS - 1); loop { let t0 = std::time::Instant::now(); let mut q = st.q.lock().unwrap(); let (r, c, job) = loop { if let Some(job) = q.take_runnable(st.last_col, stats) { break job; } if q.closed && q.queued == 0 { return; } q = st.cv.wait(q).unwrap(); }; q.active += 1; drop(q); if stats { WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed); WS_JOBS[slot].fetch_add(1, Relaxed); WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed); } let t1 = std::time::Instant::now(); let ReconPlanes(y, u, v) = st.planes; // SAFETY: this job writes only superblock (r, c)'s own pixels, and // every superblock that could have written or be reading them is // complete by the wavefront rule above. let mut cur: [Vec; 3] = Default::default(); let ReconJob { mut ops, mut coeffs, mut preds } = job; unsafe { for op in ops.drain(..) { exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx); } } if stats { WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed); } coeffs.clear(); preds.clear(); let mut q = st.q.lock().unwrap(); // lane-sballoc: hand the three buffers back for the next submit. if q.free.len() < q.free_cap { q.free.push((ops, coeffs, preds)); } q.done[r] = c as isize; q.active -= 1; st.cv.notify_all(); } } /// Installs the wavefront for one tile and joins its workers on every exit /// from the tile decoder, including the `?` ones -- the jobs hold raw /// pointers into the tile's planes, so no worker may outlive them. /// (lane-pool1: the workers come from this thread's persistent pool, so a /// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads /// with fresh scratch.) pub(crate) struct WaveGuard<'a>( &'a crate::decode::FrameCtx, Option>, ); #[allow(unsafe_code)] impl<'a> WaveGuard<'a> { fn install( fctx: &'a crate::decode::FrameCtx, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, rows: usize, cols: usize, ) -> Option { let threads = crate::par::recon_threads(); if threads == 1 || rows == 0 || cols == 0 { return None; } let st = std::sync::Arc::new(WaveState { q: std::sync::Mutex::new(WaveQueue { rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(), queued: 0, done: vec![-1; rows], last_sub: vec![-1; rows], last_push: vec![-1; rows], active: 0, closed: false, free: Vec::new(), free_cap: threads + 2, }), cv: std::sync::Condvar::new(), // SAFETY: the planes are locals of the tile decoder and outlive // this guard, which joins every worker in `drop`. planes: ReconPlanes( std::ptr::from_mut(y), std::ptr::from_mut(u), std::ptr::from_mut(v), ), bit_depth: fctx.bit_depth.with(std::cell::Cell::get), enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get), last_col: cols - 1, }); let batch = crate::par::Batch::new("ec-av1-recon"); for idx in 0..threads { let st = std::sync::Arc::clone(&st); batch.submit(move || wave_worker(&st, idx)); } fctx.wave.with(|w| *w.borrow_mut() = Some(st)); fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now()))); Some(Self(fctx, Some(batch))) } } impl Drop for WaveGuard<'_> { fn drop(&mut self) { let st = self.0.wave.with(|w| w.borrow_mut().take()); if let Some(st) = st { st.q.lock().unwrap().closed = true; st.cv.notify_all(); } let t0 = std::time::Instant::now(); // Dropping the batch waits every worker out, as the joins did. drop(self.1.take()); if wave_stats() { WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed); WS_TILES.fetch_add(1, Relaxed); wave_stats_dump(); } } } /// An empty buffer for the next superblock: the recycled one when it is at /// least as big as the superblock just parsed, else a fresh sized one /// (lane-sballoc; `v` is always empty). fn reuse(mut v: Vec, cap: usize) -> Vec { if v.capacity() < cap { v.reserve_exact(cap - v.len()); } v } /// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false` /// when there is no wavefront (one reconstruction thread), in which case the /// caller replays them itself. fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool { let st = fctx.wave.with(|w| w.borrow().clone()); let Some(st) = st else { return false }; // lane-blockmem: the op list is replaced sized for the next superblock, // exactly as the two arenas below are -- taking it left a zero-capacity // `Vec` that regrew (and memmoved every recorded op) from nothing on // every superblock. // lane-sballoc: the replacement comes from the finished jobs' free list // when there is one (warm capacity, already faulted in); only the first // superblocks of a tile allocate. let mut q = st.q.lock().unwrap(); let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default(); let ops = fctx.recon_ops.with(|c| { let mut c = c.borrow_mut(); let cap = c.len(); std::mem::replace(&mut *c, reuse(sops, cap)) }); // The job owns its coefficients: the arena is replaced by an empty one // sized for the next superblock, so parse never regrows from nothing and // the worker frees this buffer once, instead of once per unit. let coeffs = fctx.coeff_arena.with(|c| { let mut c = c.borrow_mut(); let cap = c.len(); std::mem::replace(&mut *c, reuse(scoeffs, cap)) }); let preds = fctx.pred_arena.with(|c| { let mut c = c.borrow_mut(); let cap = c.len(); std::mem::replace(&mut *c, reuse(spreds, cap)) }); { if (c as isize) > q.last_sub[r] { q.last_sub[r] = c as isize; } if !ops.is_empty() { q.rows[r].push_back((c, ReconJob { ops, coeffs, preds })); q.queued += 1; q.last_push[r] = c as isize; } drop(q); st.cv.notify_all(); } if wave_stats() { let now = std::time::Instant::now(); if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) { WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed); } } true } /// Waits until every submitted job is reconstructed, so the parser may read /// the planes itself (the intrabc source fetch and the interintra intra /// predictor -- see [`flush_recon`]). fn wave_barrier(fctx: &crate::decode::FrameCtx) { let st = fctx.wave.with(|w| w.borrow().clone()); let Some(st) = st else { return }; let stats = wave_stats(); let t0 = std::time::Instant::now(); let mut q = st.q.lock().unwrap(); while q.queued > 0 || q.active > 0 { q = st.cv.wait(q).unwrap(); } drop(q); if stats { WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed); WS_BARRIERS.fetch_add(1, Relaxed); } } /// Performs an intra write at its push site when the tile registered its /// planes for inline reconstruction ([`ReconPlanes`]); `false` when the /// caller must record it for the wavefront workers instead. #[allow(unsafe_code)] #[allow(clippy::too_many_arguments)] fn inline_intra( plane: usize, x: usize, oy: usize, bw: usize, bh: usize, rect: bool, mode: usize, angle_delta: i32, reach: Reach, residual: &[i32], cfl: Option<(i32, CflSrc)>, filter_intra: Option, smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, ) -> bool { let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else { return false; }; let pred = take_palette_pred(fctx); // SAFETY: see [`ReconPlanes`]. unsafe { exec_intra( &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, pred, fctx, ); } true } /// [`inline_intra`] for a motion-compensated write. #[allow(unsafe_code)] #[allow(clippy::too_many_arguments)] fn inline_mc( plane: usize, x: usize, oy: usize, stride: usize, w: usize, h: usize, prediction: &[u16], residual: &[i32], fctx: &crate::decode::FrameCtx, ) -> bool { let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else { return false; }; // SAFETY: see [`ReconPlanes`]. unsafe { exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx); } true } /// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)). #[allow(clippy::too_many_arguments)] fn push_intra( plane: usize, x: usize, y: usize, side: usize, mode: usize, angle_delta: i32, reach: Reach, residual: &[i32], cfl: Option<(i32, CflSrc)>, filter_intra: Option, smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, ) { if inline_intra( plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, fctx, ) { return; } let pred = take_palette_pred(fctx); push_op(fctx, ReconOp::Intra { plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach, residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred, }); } /// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)). #[allow(clippy::too_many_arguments)] fn push_intra_rect( plane: usize, x: usize, y: usize, bw: usize, bh: usize, mode: usize, angle_delta: i32, reach: Reach, residual: &[i32], cfl: Option<(i32, CflSrc)>, filter_intra: Option, smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, ) { if inline_intra( plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, fctx, ) { return; } let pred = take_palette_pred(fctx); push_op(fctx, ReconOp::Intra { plane, x, y, bw, bh, rect: true, mode, angle_delta, reach, residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred, }); } /// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded. fn push_mc( plane: usize, x: usize, y: usize, side: usize, prediction: Pred<'_>, residual: &[i32], fctx: &crate::decode::FrameCtx, ) { push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx); } /// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)). #[allow(clippy::too_many_arguments)] fn push_mc_rect( plane: usize, x: usize, y: usize, stride: usize, w: usize, h: usize, prediction: Pred<'_>, residual: &[i32], fctx: &crate::decode::FrameCtx, ) { let (src, stride) = match prediction.inline(stride) { Some(v) => v, None => { let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() }; push_op(fctx, ReconOp::Mc { plane, x, y, stride: ss, w, h, prediction: PredSrc::Cur { plane: sp, off, src: ss }, residual: Residual::done(residual, fctx), }); return; } }; if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) { return; } push_op(fctx, ReconOp::Mc { plane, x, y, stride, w, h, // The whole window `reconstruct_mc_rect` reads at `stride`, not // `w * h`: the record keeps exactly what `src.to_vec()` carried. prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32), residual: Residual::done(residual, fctx), }); } /// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction /// thread the transform runs here, exactly as before; on the wavefront it /// travels with the op and runs on the worker (lane-wave3). #[allow(clippy::too_many_arguments)] fn push_intra_tx( plane: usize, x: usize, y: usize, bw: usize, bh: usize, rect: bool, mode: usize, angle_delta: i32, reach: Reach, tx: TxParams, grid: &[i32], cfl: Option<(i32, CflSrc)>, filter_intra: Option, smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, ) { if fctx.recon_planes.with(std::cell::Cell::get).is_some() { inline_intra( plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra, smooth_neighbor, fctx, ); return; } let pred = take_palette_pred(fctx); push_op(fctx, ReconOp::Intra { plane, x, y, bw, bh, rect, mode, angle_delta, reach, residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred, }); } /// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`]. #[allow(clippy::too_many_arguments)] fn push_mc_rect_tx( plane: usize, x: usize, y: usize, stride: usize, w: usize, h: usize, prediction: Pred<'_>, tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx, ) { // lane-wave4: a deferred prediction is not there to be windowed -- the // op carries its offset into the block's prediction instead, and the // residual is laid out at that same stride (`reconstruct_mc_rect` reads // both buffers at one stride). let (prediction, stride) = match prediction.inline(stride) { Some(v) => v, None => { let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() }; let mut tx = tx; tx.stride = 0; push_op(fctx, ReconOp::Mc { plane, x, y, stride: w, w, h, prediction: PredSrc::Cur { plane: sp, off, src: ss }, residual: Residual::coeffs(tx, grid, fctx), }); return; } }; if fctx.recon_planes.with(std::cell::Cell::get).is_some() { // `reconstruct_mc_rect` reads the prediction and the residual at ONE // stride, so a prediction handed over at the block's stride (a var-tx // unit's window, lane-wave4) has to be densified for a dense residual // -- which is exactly what the recorded path below does. let residual = tx.run(grid); let res_stride = if tx.stride == 0 { w } else { tx.stride }; let window; let prediction = if stride == res_stride { prediction } else { debug_assert_eq!(res_stride, w); let mut win = Vec::with_capacity(w * h); for row in 0..h { win.extend_from_slice(&prediction[row * stride..][..w]); } window = win; &window[..] }; inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx); return; } // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the // two buffers at `stride`, so the record carries that window densely // rather than the whole block's prediction: a 4x4 unit of a 64x64 block // copied 64*64 samples on the PARSING thread before. The residual is then // produced dense too (`TxParams::stride = 0`), which is the same numbers // in the same places at stride `w`. let off = fctx.pred_arena.with(|a| { let mut a = a.borrow_mut(); let off = a.len(); for row in 0..h { a.extend_from_slice(&prediction[row * stride..][..w]); } off as u32 }); let mut tx = tx; tx.stride = 0; push_op(fctx, ReconOp::Mc { plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32), residual: Residual::coeffs(tx, grid, fctx), }); } /// Replays every recorded [`ReconOp`] into the frame's planes, in push order, /// and empties the queue (lane-wave1 step (i)). /// /// Called at the top of each superblock visit and at the end of each tile, so /// a whole superblock's parsing runs with no plane access at all; the two /// parse-time pixel READS that survive -- the intrabc source fetch and the /// interintra intra predictor -- flush ahead of themselves instead, which /// keeps them byte-exact and names exactly what step (ii) still has to move. fn flush_recon( fctx: &crate::decode::FrameCtx, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, ) { // lane-wave1 step (ii): a parse-time pixel READ needs every worker's // writes in place, not just this superblock's queue. wave_barrier(fctx); let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut())); fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops)); let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut())); fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs)); let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut())); fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds)); let mut cur: [Vec; 3] = Default::default(); for op in ops.drain(..) { exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx); } coeffs.clear(); preds.clear(); fctx.recon_spare.with(|c| *c.borrow_mut() = ops); fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs); fctx.pred_spare.with(|c| *c.borrow_mut() = preds); } /// Performs one recorded write: the body [`flush_recon`] replays, and the /// body [`push_op`] runs immediately when reconstruction is inline. fn exec_op( op: ReconOp, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, cur: &mut [Vec; 3], coeffs: &[i32], preds: &[u16], fctx: &crate::decode::FrameCtx, ) { let mut scratch = Vec::new(); match op { ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur), ReconOp::Intra { plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, pred, } => exec_intra( y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach, residual.resolve(coeffs, &mut scratch), cfl, filter_intra, smooth_neighbor, pred, fctx, ), ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => { let residual = residual.resolve(coeffs, &mut scratch); match prediction { PredSrc::Owned(off, len) => { let p = &preds[off as usize..][..len as usize]; exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx); } PredSrc::Cur { plane: sp, off, src } => { let block = std::mem::take(&mut cur[sp]); if src == stride { exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx); } else { // A transform unit's residual is dense, so its window // of the block prediction is taken out dense too -- // the copy the parsing thread used to make, made here. let mut window = Vec::with_capacity(w * h); for row in 0..h { window.extend_from_slice(&block[off + row * src..][..w]); } exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx); } cur[sp] = block; } } } } } /// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline /// path ([`push_op`]'s registered planes) reaches it without ever building /// the record -- which is what keeps one reconstruction thread at the cost of /// the pre-lane-wave1 decoder. #[allow(clippy::too_many_arguments)] fn exec_intra( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, plane: usize, x: usize, oy: usize, bw: usize, bh: usize, rect: bool, mode: usize, angle_delta: i32, reach: Reach, residual: &[i32], cfl: Option<(i32, CflSrc)>, filter_intra: Option, smooth_neighbor: bool, pred: Option>, fctx: &crate::decode::FrameCtx, ) { // The CfL AC signal is read HERE, off the luma that has already been // written for this block -- at parse time it would have been the previous // frame's samples. let ac = cfl.map(|(alpha, src)| { let sig = if src.rect { cfl_ac_q3_rect(&*y, src.px, src.py, src.bw, src.bh) } else { cfl_ac_q3(&*y, src.px, src.py, src.bw) }; (alpha, sig) }); let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice())); let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v }; if rect { target.reconstruct_rect( x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, pred, fctx, ); } else { target.reconstruct( x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, pred, fctx, ); } } /// [`ReconOp::Mc`] performed -- see [`exec_intra`]. #[allow(clippy::too_many_arguments)] fn exec_mc( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, plane: usize, x: usize, oy: usize, stride: usize, w: usize, h: usize, prediction: &[u16], residual: &[i32], fctx: &crate::decode::FrameCtx, ) { let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v }; target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx); } thread_local! { /// The current frame's `mi` grid, kept only while a frame header set /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary /// MV stack ([`crate::mvstack::find_mv_stack`]) built against /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that /// does not allow intrabc (so nothing is paid for it). /// /// corner-cut: only [`decode_block`] (the square path) records into it, /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off /// an incomplete grid. Ceiling: the DV *value* (never the parse) would /// be wrong there; upgrade = record from the rect/leaf paths too. /// The block vector [`read_intra_mode`] just decoded, handed to /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`], /// which the alternative -- a tenth tuple member through every caller -- /// already avoids). Always `.take()`n by the block that reads it. /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter. static INTRABC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so // an intrabc block's chroma reads can inherit it (see // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read // through that one arming site. // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also // satisfies (`blockd.h:373`) -- and takes the *colocated luma // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an // intrabc block's two chroma [`read_plane`] calls; the type decides the // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context // -- getting it wrong desyncs the chroma coefficients, it is not a // reconstruction-only detail. /// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is /// `Some` exactly then (set once per frame in `decode_frame`), so the flag /// needs no separate plumbing to reach the rect-strip mode reader. fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool { fctx.intrabc_mi_grid.with(|g| g.borrow().is_some()) } thread_local! { /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many /// times the fix below was exercised) -- the rect-strip gate's hit counter, /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc. static RECT_INTRABC_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_INTRABC_READS`]. pub(crate) fn rect_intrabc_reads() -> usize { RECT_INTRABC_READS.with(|c| c.get()) } /// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_rect_intrabc_reads() { RECT_INTRABC_READS.with(|c| c.set(0)); } thread_local! { /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape. static LEAF8_INTRABC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`LEAF8_INTRABC_HITS`]. pub(crate) fn leaf8_intrabc_hits() -> usize { LEAF8_INTRABC_HITS.with(|c| c.get()) } /// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_leaf8_intrabc_hits() { LEAF8_INTRABC_HITS.with(|c| c.set(0)); } /// Current value of [`INTRABC_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intrabc_hits() -> usize { INTRABC_HITS.with(|c| c.get()) } /// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_hits() { INTRABC_HITS.with(|c| c.set(0)); } thread_local! { /// lane-t900 r32: intrabc blocks whose transform size came off the INTER /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability /// that replaced the refusal "an intrabc block under TxMode::Select". static INTRABC_VARTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRABC_VARTX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intrabc_vartx_hits() -> usize { INTRABC_VARTX_HITS.with(|c| c.get()) } /// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_vartx_hits() { INTRABC_VARTX_HITS.with(|c| c.set(0)); } /// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an /// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`). fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, fctx: &crate::decode::FrameCtx) { fctx.intrabc_mi_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: NO_REF1, mv: 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); } } }); } // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) -- // proves a real `skip_mode_present` stream actually reached a block that // picked it, not just that the frame header bit was set. thread_local! { static SKIP_MODE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SKIP_MODE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn skip_mode_hits() -> usize { SKIP_MODE_HITS.with(|c| c.get()) } // lane-motionmode: how many blocks actually decoded `obmc_selected == true` // (as opposed to just reaching an eligible `read_motion_mode` symbol read) // -- the gate's own proof that a real aomenc `--enable-obmc=1` stream // reached [`obmc_blend`], not just the header bit. thread_local! { static OBMC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the // 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled // reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while // `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have // picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this // decoder used to read with the wrong alphabet, so a gate that asserts this // counter advanced proves the fixed path fired (class // `gate-blind-to-feature`). thread_local! { static FIMV_ALPHABET_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`FIMV_ALPHABET_HITS`]. pub fn fimv_alphabet_hits() -> usize { FIMV_ALPHABET_HITS.with(|c| c.get()) } // lane-fimv r1: how many frame headers this decoder has decoded with // `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate // prove the encoder really produced the header state under test rather than // assume it. thread_local! { static FIMV_FRAME_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`FIMV_FRAME_HITS`]. pub fn fimv_frame_hits() -> usize { FIMV_FRAME_HITS.with(|c| c.get()) } /// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose /// `force_integer_mv` bit is set. pub fn note_force_integer_mv_frame() { hit!(FIMV_FRAME_HITS); } /// Current value of [`OBMC_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn obmc_hits() -> usize { OBMC_HITS.with(|c| c.get()) } // lane-t900 r27: OBMC blends that actually READ a recorded switchable filter // off the neighbour band -- the positive half of the proof for "an OBMC // neighbour whose switchable interp filter was never recorded". A // fixed-filter frame returns before this point (its neighbours legitimately // carry the `[3, 3]` sentinel), so every bump is a neighbour whose own // `interp_filter` symbols were published by `record_inter_rect_mi`. thread_local! { static OBMC_FILTER_BAND_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`OBMC_FILTER_BAND_READS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn obmc_filter_band_reads() -> usize { OBMC_FILTER_BAND_READS.with(|c| c.get()) } // lane-scaledref r1: per-case firing counts for the scaled-reference gate // (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED // reference would pass just as well and prove nothing, so the gate // hard-asserts each combination this round lifts actually occurred: // a compound block with a scaled tap, a warp block whose warp libaom // suppresses because the reference is scaled, an OBMC block, an interintra // block, and an 8x8 leaf. thread_local! { static SCALED_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SCALED_WARP_FALLBACK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SCALED_OBMC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SCALED_INTERINTRA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SCALED_BLOCK8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one /// scaled and one unscaled tap. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn mixed_scale_compound_hits() -> usize { MIXED_SCALE_COMPOUND_HITS.with(|c| c.get()) } /// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have /// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf` /// instead because their reference is scaled (libaom `motion_mode_allowed`, /// `blockd.h:1484`). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn scaled_warp_suppressed_hits() -> usize { SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get()) } /// Current value of [`SCALED_COMPOUND_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn scaled_compound_hits() -> usize { SCALED_COMPOUND_HITS.with(|c| c.get()) } /// Current value of [`SCALED_WARP_FALLBACK_HITS`]. pub fn scaled_warp_fallback_hits() -> usize { SCALED_WARP_FALLBACK_HITS.with(|c| c.get()) } /// Current value of [`SCALED_OBMC_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn scaled_obmc_hits() -> usize { SCALED_OBMC_HITS.with(|c| c.get()) } /// Current value of [`SCALED_INTERINTRA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn scaled_interintra_hits() -> usize { SCALED_INTERINTRA_HITS.with(|c| c.get()) } /// Current value of [`SCALED_BLOCK8_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn scaled_block8_hits() -> usize { SCALED_BLOCK8_HITS.with(|c| c.get()) } // lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to // `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of // [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an // 8x8-leaf OBMC block apart from a 16x16+ one. thread_local! { static OBMC_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; } // lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter` // pair whose two directions differ (`enable_dual_filter` only -- with dual // filter off both directions take the single symbol, so this can never fire). // A gate asserting it proves the stream really carries dual-filter blocks. thread_local! { static DUAL_FILTER_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // lane-interp3 r1: how many COMPOUND 8x8 leaves read their own // `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf // used to skip it entirely, losing a symbol and stamping the `[3, 3]` // no-filter sentinel that made a neighbouring OBMC block panic). thread_local! { static COMPOUND8_FILTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`DUAL_FILTER_DIFF_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn dual_filter_diff_hits() -> usize { DUAL_FILTER_DIFF_HITS.with(|c| c.get()) } /// Current value of [`COMPOUND8_FILTER_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn compound8_filter_hits() -> usize { COMPOUND8_FILTER_HITS.with(|c| c.get()) } // lane-warp round 1: how many blocks resolved `motion_mode_allowed` to // `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under // `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL` // -- the gate's proof that a fixture really exercises the alphabet this // round changed, even though the block itself still refuses (warp // estimation/filter not ported). thread_local! { static WARP_SELECTED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`WARP_SELECTED_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn warp_selected_hits() -> usize { WARP_SELECTED_HITS.with(|c| c.get()) } // lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one // reference predicted through the per-ref GLOBAL warp (`av1_warp_plane` // into the compound intermediate) rather than translationally -- the // gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model // really reached [`crate::warp::warp_affine_compound`]. thread_local! { static COMPOUND_WARP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`COMPOUND_WARP_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn compound_warp_hits() -> usize { COMPOUND_WARP_HITS.with(|c| c.get()) } // lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound // arm ([`decode_inter_block8`]) -- that arm predicted both taps // translationally until r3, so a gate needs to tell a warped 8x8 compound // leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]). thread_local! { static COMPOUND_WARP_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`COMPOUND_WARP_HITS_8`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn compound_warp_hits_8() -> usize { COMPOUND_WARP_HITS_8.with(|c| c.get()) } // lane-gmaffine r1: how many blocks built their prediction from a // SIX-parameter (`AFFINE`) global-motion model through // `crate::warp::global_warp_params` -- the gate's proof that a stream really // carried an AFFINE `global_motion_params` AND that a block was predicted // with it, not merely that the header parsed one. thread_local! { static AFFINE_GM_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`AFFINE_GM_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn affine_gm_hits() -> usize { AFFINE_GM_HITS.with(|c| c.get()) } // lane-t900 r9: rect blocks whose warp-sample top-right probe answers // differently at the block's WIDTH than at libaom's // `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could // pick the wrong motion_mode alphabet. thread_local! { static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`TR_REACH_LONGER_SIDE_HITS`]. pub fn tr_reach_longer_side_hits() -> usize { TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get) } // lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0 // for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block // with a 4-px side is NEVER "non-translational global" and therefore ALWAYS // reads its interp-filter symbol. Counts the blocks where that guard flips // our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model // and a 4-px side, which we used to suppress the interp read on (a pre-mode // entropy desync one symbol wide). thread_local! { static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`]. pub fn gm_nontrans_small_side_hits() -> usize { GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get) } // lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves // coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real // `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented // only once `find_projection` returned a usable model, unlike // `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates' // proof that the leaf path itself fired, not the 16x16+ one. thread_local! { static GLOBALMV_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; static WARP_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`GLOBALMV_HITS_8`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn globalmv_hits_8() -> usize { GLOBALMV_HITS_8.with(|c| c.get()) } /// Current value of [`WARP_HITS_8`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn warp_hits_8() -> usize { WARP_HITS_8.with(|c| c.get()) } // How many blocks decoded `interintra == 1` with the non-wedge blended // prediction applied (lane-interintra r1) -- the gate's proof that a // stream actually exercised interintra. thread_local! { static INTERINTRA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTERINTRA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn interintra_hits() -> usize { INTERINTRA_HITS.with(|c| c.get()) } // lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`) // -- the shape `interintra_blend` used to build a square `side x side` intra // predictor for, with `ii_size_scales`/`edges` taken at the square. Every // pre-existing interintra gate passed with that bug, so the rect arm needs // its own counter to stop being vacuous. thread_local! { static INTERINTRA_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTERINTRA_RECT_HITS`]. pub fn interintra_rect_hits() -> usize { INTERINTRA_RECT_HITS.with(|c| c.get()) } // How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE, // wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/ // `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a // gate fixture actually exercises this alphabet, even though the block // still refuses (the mask blend itself is unported). thread_local! { static MASKED_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`MASKED_COMPOUND_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn masked_compound_hits() -> usize { MASKED_COMPOUND_HITS.with(|c| c.get()) } // lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a // masked-compound block whose true footprint is rectangular, i.e. the case // whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the // square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that // defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it. thread_local! { static RECT_MASKED_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_MASKED_COMPOUND_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_masked_compound_hits() -> usize { RECT_MASKED_COMPOUND_HITS.with(|c| c.get()) } // How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx == // 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture // actually exercised the wedge blend, not just the DIFFWTD half of // `MASKED_COMPOUND_HITS`. thread_local! { static WEDGE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`WEDGE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn wedge_hits() -> usize { WEDGE_HITS.with(|c| c.get()) } // How many blocks decoded a real wedge-INTERINTRA block // (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof // a gate fixture exercised the wedge blend (fixed sign 0), not just the // smooth arm counted by `INTERINTRA_HITS`. thread_local! { static WII_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`WII_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn wii_hits() -> usize { WII_HITS.with(|c| c.get()) } // lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol // NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`: // wide <= 32 && high <= 32). The witness that a gate stream really carries a // 64-axis intra block -- the shape whose 14-symbol read desynced every inter // frame carrying one. thread_local! { static NOCFL_UV_MODE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`NOCFL_UV_MODE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn nocfl_uv_mode_hits() -> usize { NOCFL_UV_MODE_HITS.with(|c| c.get()) } /// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order -- /// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`]. pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] = [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)]; fn rect_wedge_slot(bw: usize, bh: usize) -> Option { RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh)) } // lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a // RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that // the rect wedge masks lifted this round actually fired, not just the square // ones already counted by `WEDGE_HITS`/`WII_HITS`. thread_local! { static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) }; static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) }; } /// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`]. pub(crate) fn rect_wedge_hits() -> [usize; 6] { RECT_WEDGE_HITS.with(|c| c.get()) } /// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`]. pub(crate) fn rect_wii_hits() -> [usize; 6] { RECT_WII_HITS.with(|c| c.get()) } // lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC // blend -- the gate's proof that `--enable-obmc=1` reached this shape (the // r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented // aomdec, neighbour list included). thread_local! { static OBMC_RECT_LEAF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`OBMC_RECT_LEAF_HITS`]. pub(crate) fn obmc_rect_leaf_hits() -> usize { OBMC_RECT_LEAF_HITS.with(|c| c.get()) } // lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of // a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used // to be read from the pair's FIRST mi, which is a different block and, when // that half is intra, carries the `[3, 3]` "no filter" sentinel (the three // 1080p 10-bit film cuts refused there). The gate's proof the shape fired. thread_local! { static OBMC_PAIR_FILTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`OBMC_PAIR_FILTER_HITS`]. pub(crate) fn obmc_pair_filter_hits() -> usize { OBMC_PAIR_FILTER_HITS.with(|c| c.get()) } // lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge // -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's // own side, so a block overhanging the bottom/right still predicts the full // neighbour strip (the destination write is what clips). We used to shrink the // prediction to the visible part, which at 4 chroma rows/cols also swaps the // vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired. thread_local! { static OBMC_EDGE_SPAN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`OBMC_EDGE_SPAN_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn obmc_edge_span_hits() -> usize { OBMC_EDGE_SPAN_HITS.with(|c| c.get()) } /// Current value of [`OBMC_HITS_8`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn obmc_hits_8() -> usize { OBMC_HITS_8.with(|c| c.get()) } // lane-rectgate r1: how many 32x32 quadrants actually decoded a // `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's // inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/ // `VERT_B` all still fall into the generic "a partition type this encoder // never writes" refusal below) -- the gate's proof that a free-partition // aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than // coincidentally never selecting one. thread_local! { static EXTENDED_PARTITION_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`EXTENDED_PARTITION_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn extended_partition_hits() -> usize { EXTENDED_PARTITION_HITS.with(|c| c.get()) } // lane-partitions r1: how many 32x32 quadrants decoded a real // `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike // `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition // gate's proof this round's arms actually fired. thread_local! { static RECT_PARTITION_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_PARTITION_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_partition_hits() -> usize { RECT_PARTITION_HITS.with(|c| c.get()) } // lane-inter8 r1: how many superblocks an inter tile coded as a single // whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for // static content, previously a named refusal). thread_local! { /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile /// path decoded as one whole block (its gate's own witness). pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7). pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta. pub(crate) fn inter_sb128_horz_hits() -> usize { INTER_SB128_HORZ_HITS.with(std::cell::Cell::get) } /// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta. pub(crate) fn inter_sb128_vert_hits() -> usize { INTER_SB128_VERT_HITS.with(std::cell::Cell::get) } /// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta. pub fn inter_sb128_none_hits() -> usize { INTER_SB128_NONE_HITS.with(std::cell::Cell::get) } thread_local! { /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma /// units) -- the gate's witness that the lifted refusal's case fired. pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta. pub fn intra_128_in_inter_hits() -> usize { INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get) } thread_local! { static INTER_SB_NONE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTER_SB_NONE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn inter_sb_none_hits() -> usize { INTER_SB_NONE_HITS.with(|c| c.get()) } // lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter // blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle // path has always run that loop, so only this counter proves the newly-lifted // alphabet value fired. thread_local! { static INTER_SUB16_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTER_SUB16_SPLIT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn inter_sub16_split_hits() -> usize { INTER_SUB16_SPLIT_HITS.with(|c| c.get()) } // lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves // while at least one reference picture was SCALED (superres) -- the counter // behind the lifted "8x8 partition leaf under a scaled reference" refusal. thread_local! { static SCALED_LEAF8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SCALED_LEAF8_HITS`]. pub fn scaled_leaf8_hits() -> usize { SCALED_LEAF8_HITS.with(|c| c.get()) } // lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8 // rect pair) were predicted from a SCALED reference -- the counter behind the // lifted "sub-8x8 inter block under a scaled reference" refusal. thread_local! { static SCALED_SUB8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SCALED_SUB8_HITS`]. pub fn scaled_sub8_hits() -> usize { SCALED_SUB8_HITS.with(|c| c.get()) } // lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded // real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the // rect coefficient reader itself fired, not just the strip-level partition // symbol [`RECT_PARTITION_HITS`] already counts. thread_local! { static RECT_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_COEFF_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_coeff_hits() -> usize { RECT_COEFF_HITS.with(|c| c.get()) } // lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`]) // decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the // charter's real-aomenc gate hard-asserts. thread_local! { static RECT_LEAF_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT_LEAF_COEFF_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_leaf_coeff_hits() -> usize { RECT_LEAF_COEFF_HITS.with(|c| c.get()) } // lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the // INTER block path ([`decode_intra_rect_in_inter`]), per shape class -- // [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16. // Every one of them was the named refusal "an intra-coded HORZ/VERT strip // needs rectangular intra prediction" before this round. thread_local! { static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; } /// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class /// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize { INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class]) } // lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded // (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the // un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of // [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on. // Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT): // a single counter cannot tell an axis swap from a working arm // (class [[scan-weights-cross-axis]]), so the gate asserts both cells. thread_local! { static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; } /// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation /// (0 = 64x32, 1 = 32x64). pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize { RECT64_CORNER_TU_HITS.with(|c| c.get()[orient]) } // lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma // transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0 // is never incremented) -- the gate's proof that the lifted path ran per depth. thread_local! { static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; } // lane-t900 r21: rect intra strips inside an inter frame that read the // screen-content palette syntax (`allow_screen_content_tools` set and the // strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket // refusal used to guard, so this counter is what keeps its witness gate // non-vacuous. thread_local! { static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_rect_in_inter_screen_hits() -> usize { INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get) } /// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intra_rect_in_inter_screen_hits() { INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0)); } /// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] { INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get) } // lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF // ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly // the blocks the key frame's deblock-grid approximation used to mis-read. thread_local! { static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`]. #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize { INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get) } // lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER // block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every // one of them was the named refusal "an intra-coded 1:4 (or other non-2:1) // rect strip on the inter block path" before this round. thread_local! { static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } /// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape /// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32). pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize { INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape]) } // lane-intra14 r1: set while an INTRA block of an INTER frame is decoded // through one of the key-frame rect readers ([`decode_block_rect4`], // [`decode_block_rect64`]). `Some((size_group, skip))` tells // [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were // already read by [`decode_inter_block`] and (b) the luma mode comes off // `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`, // decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair. // lane-rectx r5: how many times a NON-strip `kf_y_mode` reader // ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an // above/left mode from the mi-exact map that DIFFERS from its coarse 16x16 // slot -- i.e. how often the r5 defect would have picked the wrong CDF row. thread_local! { static MODE_MI_OVERRIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`MODE_MI_OVERRIDE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn mode_mi_override_hits() -> usize { MODE_MI_OVERRIDE_HITS.with(|c| c.get()) } // lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a // TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a // mode from the previous tile, where libaom's `up_available`/`left_available` // make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams: // `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode` // per superblock row in `start_row`, so the luma fallback cannot leak the way // lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is // the invariant that makes the coarse fallback safe. thread_local! { static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn mode_tile_edge_coarse_leaks() -> usize { MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get()) } // lane-cfl r1: how many times a chroma intra-edge filter-type read // (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the // mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the // r1 defect would have filtered a chroma edge with the wrong strength. thread_local! { static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`UV_MODE_MI_OVERRIDE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn uv_mode_mi_override_hits() -> usize { UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get()) } // lane-t900 r12: how many chroma edge-filter-type reads took their above/left // `uv_mode` from the mi GRID where the one-slot-per-column map would have // answered differently -- the sub-8x8 pair case where the pair's own first // half had already overwritten the column slot the chroma-ref half reads. thread_local! { static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`]. pub fn uv_mode_grid_override_hits() -> usize { UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get()) } // lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the // INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode // from an earlier block in that pixel row/column while the mi-exact map -- // which an inter block only started writing this round -- correctly says the // neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is // an INTER mode, and its `uv_mode` "is not set for inter blocks"). thread_local! { static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn inter_neighbour_not_smooth_hits() -> usize { INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get()) } // lane-mtfix r1: how many times a chroma intra-edge filter-type read was // suppressed at a TILE edge that is not a frame edge -- the above/left // `uv_mode` neighbour of a block on a tile's first mi row/column lives in // another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The // coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per // tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile // above would decide this tile's chroma edge filter strength. thread_local! { static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn uv_tile_edge_suppressed_hits() -> usize { UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get()) } // lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs` // read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block // shapes the r1 chroma defect showed up on. thread_local! { static CFL_BLOCK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static UV_ANGLE_DELTA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CFL_BLOCK_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn cfl_block_hits() -> usize { CFL_BLOCK_HITS.with(|c| c.get()) } /// Current value of [`UV_ANGLE_DELTA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn uv_angle_delta_hits() -> usize { UV_ANGLE_DELTA_HITS.with(|c| c.get()) } // lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT` // blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the // gate's proof this round's arms actually reached a real block, not just // that `partition_w64` read one of those two symbol values. thread_local! { static SB_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // Current value of [`SB_RECT_HITS`]. // lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a // 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as // SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the // non-SPLIT edge arm actually decoded (before this round the bit was read and // thrown away, so that arm was unreachable). thread_local! { static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } /// Current value of [`EDGE_PART_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn edge_part_hits() -> [usize; 4] { EDGE_PART_HITS.with(|c| c.get()) } /// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_edge_part_hits() { EDGE_PART_HITS.with(|c| c.set([0; 4])); } fn bump_edge_part(slot: usize) { hit_do! { EDGE_PART_HITS.with(|c| { let mut h = c.get(); h[slot] += 1; c.set(h); }); } } #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sb_rect_hits() -> usize { SB_RECT_HITS.with(|c| c.get()) } // lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the // gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level // PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half // is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile // paths (intra and inter) feed the same counter. // // lane-golomb r3: slots 4..7 are the same four facts one level up, at the // SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as // HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with // `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a // bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band, // every SB of the last row), so the 32-level slots stay 0 on that content and // only these prove the arm fired. thread_local! { static EDGE32_HITS: std::cell::Cell<[usize; 8]> = const { std::cell::Cell::new([0; 8]) }; } /// Current value of [`EDGE32_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn edge32_hits() -> [usize; 8] { EDGE32_HITS.with(|c| c.get()) } /// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge /// reads are `if`-conditions, so the counter has to ride the expression. fn bump_edge32_bit(base: usize, bit: usize) -> usize { bump_edge32(base + bit.min(1)); bit } fn bump_edge32(slot: usize) { hit_do! { EDGE32_HITS.with(|c| { let mut h = c.get(); h[slot] += 1; c.set(h) }); } } // lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/ // `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64 // strip) fired. Real aomenc picks these at 64 even with // `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is // the counter the gate hard-asserts. thread_local! { static SB_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } /// Current value of [`SB_AB_HITS`], summed over the four arms. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sb_ab_hits() -> usize { SB_AB_HITS.with(|c| c.get().iter().sum()) } /// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, /// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a /// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as /// proof of all four. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] { SB_AB_HITS.with(std::cell::Cell::get) } // lane-tx64x16: the two 1:4 superblock arms, counted per orientation -- // `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64 // strips). Two counters, not one, because a gate that only proved "some 1:4 // strip fired" would pass on a stream that never coded the other axis, and // every scan/context table this round added comes in a transposed pair. thread_local! { static SB_RECT4_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SB_RECT4_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sb_rect4_horz_hits() -> usize { SB_RECT4_HORZ_HITS.with(|c| c.get()) } /// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sb_rect4_vert_hits() -> usize { SB_RECT4_VERT_HITS.with(|c| c.get()) } // lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation -- // `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32 // strips), the arms the ReelB mid-film extract stops at. thread_local! { static RECT4_32_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_32_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-inter4 r1: the INTER-frame twins of the two counters above -- /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` / /// `PARTITION_VERT_4`. static RECT4_32_HORZ_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_32_VERT_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT` /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64). static INTER_SB_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTER_SB_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTER_SB_HORZ4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTER_SB_VERT4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // How many 32x32-level 1:4 strips actually read coefficients (non-skip): // a gate that only counted strips would pass on an all-skip stream, which // exercises none of the new scan/context tables. thread_local! { static RECT4_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the // per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT // unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in // every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS` // counts the same for a 16x8/8x16 strip below 16x16. thread_local! { static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static SUB16_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect4_split_depth_hits() -> (usize, usize) { ( RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()), RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()), ) } /// Current value of `SUB16_SPLIT_HITS`. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sub16_split_hits() -> usize { SUB16_SPLIT_HITS.with(|c| c.get()) } // lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose // luma transform is SPLIT and which therefore leave through that fn's early // return -- the arm that published no `TXFM_CONTEXT` band until this round. thread_local! { static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect64_split_txfm_publish_hits() -> usize { RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get()) } /// Current value of `RECT4_COEFF_HITS`. pub(crate) fn rect4_coeff_hits() -> usize { RECT4_COEFF_HITS.with(|c| c.get()) } // lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN // INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, // `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is // two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate // asserts the arms it proves separately so a run whose RD only picked one // cannot pass as proof of the others. thread_local! { static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } /// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an /// inter frame). pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] { SB_AB_INTER_HITS.with(std::cell::Cell::get) } // lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER // frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` // order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8 // inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip // (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every // arm separately so a run whose RD only picked one cannot pass as proof of // four. thread_local! { static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } /// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an /// inter frame). pub fn ab16_inter_hits_by_arm() -> [usize; 4] { AB16_INTER_HITS.with(std::cell::Cell::get) } // lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4 // (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS` // counts the odd strips that close a 4:2:0 chroma pair // (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row), // `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from // the PREVIOUS strip's own mv/ref/filters -- libaom // `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached // through `is_sub8x8_inter` (same file, :54). thread_local! { static INTER16_HORZ4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTER16_VERT4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTER16_CHROMA_PAIR_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTER16_SUB8_PIECE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition -- // [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the // pair's single 8x4 (4x8) chroma unit for BOTH strips. thread_local! { static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; } /// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded /// inside an INTER 16x16-level 1:4 partition (lane-intra16x4). pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) { let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get); (v[0], v[1], v[2]) } /// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16 /// strips, chroma pairs closed, chroma pairs built from two different /// strips' motion vectors)`. pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) { ( INTER16_HORZ4_HITS.with(std::cell::Cell::get), INTER16_VERT4_HITS.with(std::cell::Cell::get), INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get), INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get), ) } /// One 16x4 / 4x16 inter strip's chroma situation, handed to /// [`decode_inter_block`] out of band (the same one-shot thread-local idiom /// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites /// that all mean "an ordinary block, chroma of its own". #[derive(Clone, Copy)] pub(crate) struct InterStripChroma { /// `is_chroma_reference` for this strip: false on strips 0 and 2, which /// read and reconstruct NO chroma at all. has_chroma: bool, /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`. horz: bool, /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`, /// i.e. the origin of the 8x4 (4x8) chroma transform. pair_mi: (usize, usize), /// The previous (even) strip's single-reference MC parameters, `None` /// when it was intra or compound -- `is_sub8x8_inter` then returns false /// and the whole chroma block is predicted from THIS strip's mv. prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>, } /// The single-reference MC parameters of the inter block that decoded /// last -- read by the next 1:4 strip to build its pair's chroma. fn bump_ab16_inter(arm: usize) { hit_do! { AB16_INTER_HITS.with(|c| { let mut v = c.get(); v[arm] += 1; c.set(v); }); } } // lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or // 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that // close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual. thread_local! { static RECT4_16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_16_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_16_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_16_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_16_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's /// base mi differs from what the strip's own (odd) mi would have said -- /// the shape that made 4 chroma samples of the ReelB `-ss 1200` /// key frame miss by 1. Zero here means a gate never exercised the fix. static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely. static SKIP_CFL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape /// that reconstructed as flat DC before lane-kf1200 r2). pub fn skip_cfl_hits() -> usize { SKIP_CFL_HITS.with(|c| c.get()) } /// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type` /// from the pair's base mi than the strip's own mi would have given. pub fn rect4_16_uv_pair_filt_hits() -> usize { RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get()) } // lane-reelckf r1: the two chroma defects ReelC's key frames exposed -- // CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED` // (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and // RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose // intra-edge filter type must come from the chroma-reference position). thread_local! { static CHROMA_SKIP_CFL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf. pub fn reelc_chroma_counters() -> (usize, usize) { ( CHROMA_SKIP_CFL_HITS.with(|c| c.get()), RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()), ) } /// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16 /// strips, chroma-reference strips, strips with a coded residual, strips /// whose luma transform is split)`. pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) { ( RECT4_16_HORZ_HITS.with(|c| c.get()), RECT4_16_VERT_HITS.with(|c| c.get()), RECT4_16_CHROMA_HITS.with(|c| c.get()), RECT4_16_COEFF_HITS.with(|c| c.get()), RECT4_16_SPLIT_HITS.with(|c| c.get()), ) } /// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded). pub(crate) fn rect4_32_horz_hits() -> usize { RECT4_32_HORZ_HITS.with(|c| c.get()) } /// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded). pub(crate) fn rect4_32_vert_hits() -> usize { RECT4_32_VERT_HITS.with(|c| c.get()) } /// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded). pub(crate) fn rect4_32_horz_inter_hits() -> usize { RECT4_32_HORZ_INTER_HITS.with(|c| c.get()) } /// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded). pub(crate) fn rect4_32_vert_inter_hits() -> usize { RECT4_32_VERT_INTER_HITS.with(|c| c.get()) } /// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded). pub(crate) fn inter_sb_horz_hits() -> usize { INTER_SB_HORZ_HITS.with(|c| c.get()) } /// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded). pub(crate) fn inter_sb_vert_hits() -> usize { INTER_SB_VERT_HITS.with(|c| c.get()) } /// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded). pub(crate) fn inter_sb_horz4_hits() -> usize { INTER_SB_HORZ4_HITS.with(|c| c.get()) } /// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded). pub(crate) fn inter_sb_vert4_hits() -> usize { INTER_SB_VERT4_HITS.with(|c| c.get()) } // lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane // dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the // running-vs-stale-snapshot bug this round fixed is exercised by a gate, not // just inert-compiled. Zero forever on a passing gate means that gate's // stream never carries `delta_q_present=1` through a rect64 block. thread_local! { static RECT64_QIDX_DRIFT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT64_QIDX_DRIFT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect64_qidx_drift_hits() -> usize { RECT64_QIDX_DRIFT_HITS.with(|c| c.get()) } // lane-partab r1: how many 32x32 quadrants decoded an AB partition // (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one // 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the // free-partition gate's proof this round's arms actually fired. thread_local! { static PARTAB_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`PARTAB_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn partab_hits() -> usize { PARTAB_HITS.with(|c| c.get()) } // lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm, // one counter per arm rather than one shared total -- the gate hard-asserts // each of these individually nonzero so a recipe that only ever fires // HORZ_A can't silently stand in for the whole set. thread_local! { static INTRA_HORZ_A_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTRA_HORZ_B_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTRA_VERT_A_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTRA_VERT_B_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRA_HORZ_A_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_horz_a_hits() -> usize { INTRA_HORZ_A_HITS.with(|c| c.get()) } /// Current value of [`INTRA_HORZ_B_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_horz_b_hits() -> usize { INTRA_HORZ_B_HITS.with(|c| c.get()) } /// Current value of [`INTRA_VERT_A_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_vert_a_hits() -> usize { INTRA_VERT_A_HITS.with(|c| c.get()) } /// Current value of [`INTRA_VERT_B_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intra_vert_b_hits() -> usize { INTRA_VERT_B_HITS.with(|c| c.get()) } // How many [`read_inter_compound_mode`] reads actually happened // (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own // `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound // mvstack build), not just that `comp_mode` fired. Still refused right // after (no MV assignment or MC wired), so this only counts attempted // reads. thread_local! { static COMPOUND_MODE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`COMPOUND_MODE_HITS`]. #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live pub(crate) fn compound_mode_hits() -> usize { COMPOUND_MODE_HITS.with(|c| c.get()) } /// How many query blocks folded in at least one temporal MV candidate /// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the /// temporal-MV gate's own firing counter (lane-av1tmvp). /// /// # HANDOFF (lane-av1tmvp): not yet wired to a live stream /// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in /// this file (`decode_inter_block`) still passes `tpl: None` -- this /// counter compiles and the projection math it counts is unit-tested /// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`] /// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls /// [`crate::motion_field::setup_motion_field`] yet, so this will read `0` /// against any real stream today. See the module doc on /// `crate::motion_field` and this crate's ledger for the remaining wiring. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn tmv_hits() -> usize { crate::mvstack::tmv_hits() } /// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions /// produced on this thread, the 10-bit inter gate's firing proof. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn inter_pred_hits() -> usize { crate::mc::inter_pred_hits() } /// Everything [`decode_inter_block`] needs to fold temporal MV candidates /// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]: /// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s /// output, built by the caller when `header.use_ref_frame_mvs` is set) plus /// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`] /// needs to turn a query block's own resolved `ref_frame` into /// `TplArgs::cur_offset_0` (spec 7.9.3). pub(crate) struct TplFrameArgs<'a> { pub field: &'a crate::motion_field::TplField, pub order_hint_bits: u32, pub order_hint: u32, /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this /// frame's own `ref_frame_idx` names for each single reference. pub ref_order_hints: [u32; 7], } /// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`, /// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully /// decoded `grid`: every 4x4 unit an inter block covers reads the same /// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it /// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is /// exact — every block this crate ever codes is at least 8x8, so no 8x8 /// cell straddles two different blocks' values. #[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages pub(crate) fn build_motion_field( grid: &MiGrid, mi_cols: usize, mi_rows: usize, order_hint: u32, order_hint_bits: u32, ref_order_hints: [u32; 7], fctx: &FrameCtx, ) -> crate::motion_field::MotionField { let mut field = crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false); // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block // referencing one stores only its OTHER side's mv. With // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and // nothing is skipped. // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends // only on the reference frame, so it is 7 table lookups per frame instead // of two per inter unit. let other_side: [bool; 8] = std::array::from_fn(|rf| { let i = rf.wrapping_sub(LAST_FRAME as usize); order_hint_bits != 0 && i < 7 && (crate::motion_field::get_relative_dist(order_hint_bits, ref_order_hints[i], order_hint) > 0 || ref_order_hints[i] == order_hint) }); // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is // capped at 12 bits per component; a longer one is not stored at all. const REFMVS_LIMIT: i32 = (1 << 12) - 1; let (cols, rows, cells) = field.cells_mut(); // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands // never touch each other (an 8x8 cell lives in one cell row, and mi row // `row` writes cell row `row / 2`). let fill = |r0: usize, r1: usize, out: &mut [Option]| { for row in (r0 * 2)..(r1 * 2).min(mi_rows) { let out = &mut out[(row / 2 - r0) * cols..][..cols]; for col in 0..mi_cols { let Some(info) = grid.get_frame(row, col) else { continue; }; // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`), // so an intra block -- or an inter block whose every slot is on the // other side / over the limit -- wipes what an earlier block wrote // into the same 8x8 cell (only reachable from sub-8x8 leaves, which // share a cell). if !info.is_inter { out[col / 2] = None; continue; } // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST // qualifying one wins -- a compound block stores its second // reference's mv, never its first (unless the second is on the // other side or over the limit). Storing slot 0 unconditionally // put the wrong (mv, ref_frame_offset) pair in every compound // block's cell, which a later frame's temporal candidate then // projected with the wrong reference distance. let mut saved: Option = None; for (rf, mv) in [ (info.ref_frame, Some(mv32(info.mv))), (info.ref_frame1.max(0), Some(mv32(info.mv1))), ] { let (Some(mv), true) = (mv, rf > 0) else { continue; }; if other_side[rf as usize] { continue; } if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT { continue; } saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf }); } out[col / 2] = saved; } } }; // lane-mf: the whole-frame pass split over the filter pool in cell-row // bands (same `Shared` corner-cut as the filter stages -- disjointness is // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate). let bands = crate::par::bands(rows, crate::par::filter_threads()); if bands.len() <= 1 { fill(0, rows, cells); } else { let shared = crate::par::Shared::new(cells); crate::par::run_bands(&bands, fctx, |r0, r1, _| { // SAFETY: cell rows `r0..r1` are this band's alone. let cells = unsafe { shared.get() }; fill(r0, r1, &mut cells[r0 * cols..r1 * cols]); }); } if crate::envflags::env_flag!("EC_TRACE_TPL") { eprintln!("EC_TPL_SAVED oh={order_hint}"); for (r, row) in field.occupancy().iter().enumerate() { eprintln!("EC_TPL_SAVED r{r} {row}"); } } field } /// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`; /// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn ref_hits(ref_frame: i8) -> usize { let c = match ref_frame { LAST2_FRAME => &LAST2_HITS, LAST3_FRAME => &LAST3_HITS, GOLDEN_FRAME => &GOLDEN_HITS, BWDREF_FRAME => &BWDREF_HITS, ALTREF2_FRAME => &ALTREF2_HITS, ALTREF_FRAME => &ALTREF_HITS, other => panic!("ref_hits: no per-reference counter for ref_frame {other}"), }; c.with(|v| v.get()) } /// The sequence header's `enable_intra_edge_filter`, set once per /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s /// own read of it, kept off the call stack (see that function's own doc /// comment for why) rather than threaded through every `read_plane`/ /// `decode_block`/`decode_leaf8` call between here and there. /// Set [`ENABLE_EDGE_FILTER`] for this thread. /// /// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile` /// never did -- so an inter frame's intra blocks read whatever value the last /// key frame decoded ON THIS THREAD left behind. Inside one stream that is /// harmless (its own key frame sets it first), but a caller that decodes an /// inter frame directly, or a test harness running several streams on one /// thread, inherits a foreign sequence's bit: decode stops being a pure /// function of the bitstream. `decode_stream` now calls this once per stream /// from the sequence header, which covers every frame including inter ones. pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) { fctx.enable_edge_filter.with(|f| f.set(value)); } /// Current value of [`ANGLE_DELTA_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn angle_delta_hits() -> usize { ANGLE_DELTA_HITS.with(|c| c.get()) } /// Current value of [`TX_CLASS1_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn tx_class1_hits() -> usize { TX_CLASS1_HITS.with(|c| c.get()) } // How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent // `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion // bottom) this thread's decode actually reconstructed -- the same // before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream // genuinely exercised the sub-8x8 leaf path rather than every attempt // coincidentally landing on `PARTITION_NONE`. thread_local! { static SUB8_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter /// sub-blocks (lane-intersub8). static SUB8_INTER_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4), /// `[1] = VERT` (two BLOCK_4X8). static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]` /// MIXED groups whose chroma reference is INTER while its sibling is /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4` /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 -- /// the second lifted refusal's own witness; `[0]`/`[1]` count those too, /// so only this cell separates the split arm from the HORZ/VERT one). static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) }; } /// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference, /// mixed groups, split 4x4 leaves)`. pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) { SUB8_INTRA_RECT_HITS.with(|c| { let h = c.get(); (h[0], h[1], h[2], h[3], h[4]) }) } /// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`. pub fn sub8_inter_rect_hits() -> (usize, usize) { SUB8_INTER_RECT_HITS.with(|c| { let h = c.get(); (h[0], h[1]) }) } // lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all // four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38` // `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how // many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all. // (b) was 0 for every stream before this round -- the leaf path never touched // the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got // filtered where libaom skips it. A gate asserts both are non-zero. thread_local! { static CDEF_SKIPPED_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static INTER8_SKIP_BAND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent // crosses the cropped frame edge -- the only units for which "clamp at // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE" // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame // whose width or height is not a multiple of 8 is the only shape that // produces one; the straddling-band gate arms assert it grew. static CDEF_STRADDLE_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band // (see `Neighbours::skip_written`). static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8, // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip -- // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an // 8-tall strip pair where only one half is skip must still be FILTERED. static RECT_SKIP_BAND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static CDEF_MIXED_SKIP_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of `RECT_SKIP_BAND_HITS`. pub fn rect_skip_band_hits() -> usize { RECT_SKIP_BAND_HITS.with(|c| c.get()) } /// Current value of `CDEF_MIXED_SKIP_UNITS`. pub fn cdef_mixed_skip_units() -> usize { CDEF_MIXED_SKIP_UNITS.with(|c| c.get()) } /// Current value of `CDEF_SKIPPED_UNITS`. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn cdef_skipped_units() -> usize { CDEF_SKIPPED_UNITS.with(|c| c.get()) } /// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded /// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1). pub fn cdef_unwritten_skip_units() -> usize { CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get()) } /// Current value of `INTER8_SKIP_BAND_HITS`. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn inter8_skip_band_hits() -> usize { INTER8_SKIP_BAND_HITS.with(|c| c.get()) } /// Current value of `CDEF_STRADDLE_UNITS`. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn cdef_straddle_units() -> usize { CDEF_STRADDLE_UNITS.with(|c| c.get()) } /// Current value of [`SUB8_SPLIT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sub8_split_hits() -> usize { SUB8_SPLIT_HITS.with(|c| c.get()) } /// Current value of [`SUB8_INTER_SPLIT_HITS`]. pub fn sub8_inter_split_hits() -> usize { SUB8_INTER_SPLIT_HITS.with(|c| c.get()) } // lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a // `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that // tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`, // which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the // first sub-block's type is never the one). Reading it off sub-block 0 // inverted one 4x4 chroma unit on the wrong basis with the entropy stream // perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only // see this rule through this counter. thread_local! { static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`. pub fn sub8_chroma_tx_from_ref_hits() -> usize { SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get()) } fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) { if coeffs && first_sub != chroma_ref { hit!(SUB8_CHROMA_TX_FROM_REF_HITS); } } // How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ` // of an 8x8 block) this thread's decode reconstructed with REAL coefficients // -- a skipped leaf exercises the prediction and the mi bookkeeping but never // the rect transform, the 32-position `eob_pt` or the rect scan, so the gate // asserts on these two rather than a plain leaf count. thread_local! { static TX4X8_CODED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static TX8X4_CODED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's /// two 4x4 transform units, predicted one after the other. A separate /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so /// the gate can prove THIS path fired. static RECT8_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// 16x8/8x16 intra strips whose prediction actually read past the block's /// own width (above-right) or height (below-left) -- the samples /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/ /// `has_bl_*` table row can corrupt (lane-tx4x8 r3). static RECT_STRIP_REACH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Every 16x8/8x16 intra strip predicted, reaching or not -- the /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of. static RECT_STRIP_PRED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT8_SPLIT_TX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect8_split_tx_hits() -> usize { RECT8_SPLIT_TX_HITS.with(|c| c.get()) } /// Current value of [`RECT_STRIP_PRED_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_strip_pred_hits() -> usize { RECT_STRIP_PRED_HITS.with(|c| c.get()) } /// Current value of [`RECT_STRIP_REACH_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_strip_reach_hits() -> usize { RECT_STRIP_REACH_HITS.with(|c| c.get()) } /// Current value of [`TX4X8_CODED_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn tx4x8_coded_hits() -> usize { TX4X8_CODED_HITS.with(|c| c.get()) } /// Current value of [`TX8X4_CODED_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn tx8x4_coded_hits() -> usize { TX8X4_CODED_HITS.with(|c| c.get()) } // How many CHROMA coefficient blocks read their `eob_pt` from the class-1 // (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread. // Chroma never codes a `tx_type` symbol -- it inherits the colocated luma // type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on // an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired // (`eob_pt_{16,64,128,256}_chroma_class1`). thread_local! { static CHROMA_EOB_CLASS1_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA_EOB_CLASS1_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_eob_class1_hits() -> usize { CHROMA_EOB_CLASS1_HITS.with(|c| c.get()) } /// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited /// `tx_type` put this block's `eob_pt` on the class-1 row. fn note_chroma_class1(plane_idx: usize, tx_type: TxType) { if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD { hit!(CHROMA_EOB_CLASS1_HITS); } } const SUB_MI: u32 = 4; const MI: usize = 4; const SB: usize = 64; /// The `above_side`/`left_side` value a cell with no decoded neighbour holds /// (tile start, superblock-row start). /// /// [`Neighbours::partition_ctx_mi`] reads it as libaom's /// `av1_get_partition_plane_context` reads its own zero-initialised /// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at /// least as wide as this block". lane-sb128 r1: the old sentinel was `SB` /// (64), which reads identically at every level up to 64x64 but sets the bit /// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition /// symbol was read off CDF row 3 where libaom uses row 0 (aomdec /// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`). const NO_NEIGHBOUR_SIDE: usize = 128; const BLOCK: usize = 32; const SUB: usize = 16; const TX32: usize = 32; const TX16: usize = 16; const TX8: usize = 8; const TX4: usize = 4; const DC_PRED: usize = 0; /// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that /// carries an angle delta — [`crate::tile`]'s own private copy of the same /// constant. const V_PRED: usize = 1; const H_PRED: usize = 2; /// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec /// `Fimode_To_Intradir`, libaom `blockd.h`). const D157_PRED: usize = 6; /// The last directional mode, `D67_PRED`. const D67_PRED: usize = 8; /// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs /// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never /// codes anything else, so this decoder never reads anything else either. const ANGLE_DELTA_ZERO: usize = 3; const NUM_BASE_LEVELS: i32 = 2; const COEFF_BASE_RANGE: i32 = 12; const BR_STEP: i32 = 3; const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE; /// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types /// whose probability mass a superblock or block half outside the frame /// gathers into its one remaining flag — [`crate::tile`]'s own private copy, /// duplicated here (that module is another lane's territory this round) and /// kept in step with it by the byte-exact round-trip tests below rather than /// by sharing code. const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9]; const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8]; fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) { if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}"); } } fn element_prob(cdf: &[u16], element: usize) -> u16 { cdf[element] - if element > 0 { cdf[element - 1] } else { 0 } } /// The two-symbol CDF a partial superblock/block's forced-split flag is read /// with: the mass of `elements` becomes the probability of the one partition /// the frame edge still allows, mirroring [`crate::tile`]'s own `gather` /// (the encoder's non-adapting counterpart to this read). fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] { let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum(); [32768 - split, 32768, 0] } fn unsupported(what: impl Into) -> Error { Error::unsupported("AV1 tile", what.into()) } /// The coefficient q-context a frame's `base_q_idx` picks its default CDFs /// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the /// same rule. pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize { match base_q_idx { 0..=20 => 0, 21..=60 => 1, 61..=120 => 2, _ => 3, } } /// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk /// [`crate::tile`]'s writer generates its scan tables with. fn default_scan(side: usize) -> &'static [u16] { // One table per transform side (4/8/16/32), built once: this used to be a // fresh heap allocation plus the whole anti-diagonal walk on every // transform block read. static SCANS: std::sync::LazyLock<[Vec; 4]> = std::sync::LazyLock::new(|| { [ default_scan_gen(4), default_scan_gen(8), default_scan_gen(16), default_scan_gen(32), ] }); assert!( matches!(side, 4 | 8 | 16 | 32), "no default scan for a {side}-point transform" ); &SCANS[side.trailing_zeros() as usize - 2] } fn default_scan_gen(side: usize) -> Vec { let mut scan = Vec::with_capacity(side * side); for d in 0..(2 * side - 1) { let lo = d.saturating_sub(side - 1); let hi = d.min(side - 1); let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16); if d % 2 == 0 { scan.extend(diagonal.rev()); } else { scan.extend(diagonal); } } scan } /// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two /// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients /// in, instead of the default zigzag. libaom's own tables are keyed by a /// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its /// physically column-major level buffer, but they decompose to the exact /// same (row, col) walk as a flat row-major traversal of *our* row-major /// `grid`/`levels` (`pos = row * side + col`) once you read them that way: /// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely /// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk /// transposed (column 0 down every row, then column 1, ...). fn class_scan_table(side: usize, class: TxClass) -> Vec { class_scan_table_wh(side, side, class) } /// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against /// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/ /// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding /// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was /// transcribed with -- `mrow` is the plain row-major raster in our indexing /// and `mcol` its transpose, at rect sizes exactly as at square ones. fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec { match class { TxClass::Vert => (0..(w * h) as u16).collect(), TxClass::Horiz => (0..w) .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16)) .collect(), TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"), } } fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize { match scan_idx { 0 => 0, i if i <= area / 8 => 1, i if i <= area / 4 => 2, _ => 3, } } /// One cell of [`read_coeffs`]'s level buffer. /// /// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`, /// `txb_common.h`) -- four zero columns to the right of `side` and four zero /// rows below it, at a fixed `stride = side + 4` -- so the four-away reads /// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real /// zero cells instead of needing the `row >= side || col >= side` edge test /// this used to run five times per coefficient. Nothing writes a padding /// cell, so the values are the same zeros the test returned. #[inline] fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 { grid[row * stride + col] as i32 } /// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom /// `txb_common.h`): everything but the two lone-axis-identity types this /// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`. #[derive(Clone, Copy, PartialEq, Eq)] enum TxClass { TwoD, Horiz, Vert, } impl TxClass { fn of(tx_type: TxType) -> Self { match tx_type { // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`) // key on axis alone -- FLIPADST is still ADST for this purpose. TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert, TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz, _ => Self::TwoD, } } } /// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry /// table (indexed by the position along the transform's *coded* axis -- /// `col` for horiz, `row` for vert) that places their contexts past the 2D /// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total /// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36. fn nz_map_ctx_offset_1d(i: usize) -> usize { match i { 0 => 26, 1 => 31, _ => 36, } } fn base_ctx( grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass, rect_shape: Option<(usize, usize)>, ) -> usize { // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`, // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC // position through the full 1D neighbour sum and offset table. Skipping // that for every class desynced the last (DC) coefficient of a // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as // 0, which then read one extra `BR` symbol at the max and forced a // spurious third Golomb call). if class == TxClass::TwoD && row == 0 && col == 0 { return 0; } let offsets: [(usize, usize); 5] = match class { TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)], TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)], TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)], }; let mag: i32 = offsets .iter() .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3)) .sum(); let ctx = ((mag + 1) >> 1).min(4) as usize; match class { // libaom's CDF *set* for a truncated 64-wide/tall corner resolves // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats` // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT // strip, which own a genuinely different table from the square one // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the // square table vs the real ctx 13 the rect table gives). TxClass::TwoD => { // lane-rectsplit r4: apply libaom's GENERATING RULE // (`txb_common.h:199-209`) directly instead of indexing the // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`), // so 32 consecutive entries are one COLUMN: the [`cdf`] // transcriptions are `[col][row]` and this read had them as // `[row][col]` -- the transpose, i.e. the other shape's rule with // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain` // pins the rule against the tables over their whole 5x5 domain. if let Some((w, h)) = rect_shape { if crate::envflags::env_flag!("EC_NZOFF_DUMP") { eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}"); } if w < h && row < 2 { return ctx + 11; } if w > h && col < 2 { return ctx + 16; } } ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize } TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)), TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)), } } /// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT /// offsets into the padded level frame (lane-coefread): the tap pattern is a /// function of the tx class alone, which is fixed for a whole transform unit, /// so resolving it once per unit takes the class match and the `(dr, dc)` /// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same /// taps as [`base_ctx`]/[`br_ctx`] read, stated once; /// `flat_taps_match_the_row_col_neighbour_reads` pins them against the /// original `(dr, dc)` form. fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) { match class { TxClass::TwoD => ( [stride, 1, stride + 1, 2 * stride, 2], [stride, 1, stride + 1], ), TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]), TxClass::Vert => ( [stride, 1, 2 * stride, 3 * stride, 4 * stride], [stride, 1, 2 * stride], ), } } /// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped /// neighbours) + 1) >> 1`, clamped to 4. #[inline(always)] fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize { let mut mag = 0u32; for &t in taps { mag += u32::from(grid[idx + t]).min(3); } (((mag + 1) >> 1) as usize).min(4) } /// [`br_ctx`]'s neighbour sum, off flat taps. #[inline(always)] fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize { let mut mag = 0u32; for &t in taps { mag += u32::from(grid[idx + t]); } (((mag + 1) >> 1) as usize).min(6) } /// lane-coefread: superseded on the decode path by [`br_mag`] plus the /// origin-offset tail the two coefficient readers state inline; kept as the /// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the /// flat one against. #[cfg(test)] fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize { let extra = match class { TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1), TxClass::Horiz => neighbour(grid, stride, row, col + 2), TxClass::Vert => neighbour(grid, stride, row + 2, col), }; let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra; let mag = (((mag + 1) >> 1).min(6)) as usize; if row == 0 && col == 0 { return mag; } let near_origin = match class { TxClass::TwoD => row < 2 && col < 2, TxClass::Horiz => col == 0, TxClass::Vert => row == 0, }; if near_origin { mag + 7 } else { mag + 14 } } /// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`): /// transposed from libaom's column-major buffer into this decoder's row-major /// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512` /// against the real table). Not the square zigzag formula generalized to /// unequal `w`/`h` -- checked and that does NOT reproduce this table. const SCAN_32X16: [u16; 512] = [ 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447, 510, 479, 511, ]; /// `Default_Scan_16x32`, this decoder's own row-major transcription (see /// [`SCAN_32X16`]'s doc comment). const SCAN_16X32: [u16; 512] = [ 0, 1, 16, 2, 17, 32, 3, 18, 33, 48, 4, 19, 34, 49, 64, 5, 20, 35, 50, 65, 80, 6, 21, 36, 51, 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54, 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71, 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192, 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104, 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256, 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108, 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169, 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230, 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291, 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352, 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189, 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250, 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311, 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372, 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433, 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270, 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331, 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392, 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468, 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380, 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501, 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503, 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476, 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511, ]; /// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major /// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which /// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from /// the same source). const SCAN_4X8: [u16; 32] = [ 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28, 23, 26, 29, 27, 30, 31, ]; /// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`]. const SCAN_8X4: [u16; 32] = [ 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14, 7, 29, 22, 15, 30, 23, 31, ]; /// `Default_Scan_16x8`, this decoder's own row-major transcription (see /// [`SCAN_32X16`]'s doc comment). const SCAN_16X8: [u16; 128] = [ 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 64, 49, 34, 19, 4, 80, 65, 50, 35, 20, 5, 96, 81, 66, 51, 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54, 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87, 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120, 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108, 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127, ]; /// `Default_Scan_8x16`, this decoder's own row-major transcription (see /// [`SCAN_32X16`]'s doc comment). const SCAN_8X16: [u16; 128] = [ 0, 1, 8, 2, 9, 16, 3, 10, 17, 24, 4, 11, 18, 25, 32, 5, 12, 19, 26, 33, 40, 6, 13, 20, 27, 34, 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58, 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82, 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99, 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116, 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127, ]; /// `Default_Scan_32x8`, this decoder's own row-major transcription (see /// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16 /// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its /// scans column-major (`p = col * height + row`), so a naive copy of /// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order /// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes /// are byte-identical to this decoder's [`SCAN_8X16`]. const SCAN_32X8: [u16; 256] = [ 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253, 222, 191, 254, 223, 255, ]; /// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a /// 16x64 `PARTITION_VERT_4` strip). const SCAN_8X32: [u16; 256] = [ 0, 1, 8, 2, 9, 16, 3, 10, 17, 24, 4, 11, 18, 25, 32, 5, 12, 19, 26, 33, 40, 6, 13, 20, 27, 34, 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58, 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82, 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99, 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95, 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132, 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169, 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158, 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195, 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232, 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221, 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252, 239, 246, 253, 247, 254, 255, ]; /// `Default_Scan_16x4`, this decoder's own row-major transcription of /// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA /// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level /// (lane-tx64x16 r3). The transcription rule (`row * w + col` with /// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing /// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two /// were emitted -- a naive copy installs the transpose (class /// reference-layout-not-spec). const SCAN_16X4: [u16; 64] = [ 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 49, 34, 19, 4, 50, 35, 20, 5, 51, 36, 21, 6, 52, 37, 22, 7, 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13, 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63, ]; /// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an /// 8x32 `PARTITION_VERT_4` strip). const SCAN_4X16: [u16; 64] = [ 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28, 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52, 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63, ]; /// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding /// (`stride = w + 4`, four spare rows), so the edge test is the zeros the /// padding already holds. #[inline] fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 { grid[row * stride + col] as i32 } /// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): /// the rect generalization is libaom's own comment in /// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact /// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for /// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs /// [`decode_block_rect`] codes (see that function's own doc comment). fn base_ctx_rect( grid: &[u8], stride: usize, w: usize, h: usize, row: usize, col: usize, class: TxClass, ) -> usize { // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only // the 2D class short-circuits the DC position. if class == TxClass::TwoD && row == 0 && col == 0 { return 0; } let offsets: [(usize, usize); 5] = match class { TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)], TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)], TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)], }; let mag: i32 = offsets .iter() .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3)) .sum(); let ctx = ((mag + 1) >> 1).min(4) as usize; match class { TxClass::TwoD => { if w < h && row < 2 { return ctx + 11; } if w > h && col < 2 { return ctx + 16; } ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize } // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the // position along one axis only). TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)), TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)), } } /// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the /// neighbour-offset math itself is shape-independent, only the boundary /// clamp needs the real bound in each axis. /// lane-coefread: superseded by [`br_mag`] on the rect decode path too -- /// its body was character-for-character [`br_ctx`]'s, which /// `flat_taps_match_the_row_col_neighbour_reads` now asserts. #[cfg(test)] fn br_ctx_rect( grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass, ) -> usize { let extra = match class { TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1), TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2), TxClass::Vert => neighbour_rect(grid, stride, row + 2, col), }; let mag = neighbour_rect(grid, stride, row + 1, col) + neighbour_rect(grid, stride, row, col + 1) + extra; let mag = (((mag + 1) >> 1).min(6)) as usize; if row == 0 && col == 0 { return mag; } let near_origin = match class { TxClass::TwoD => row < 2 && col < 2, TxClass::Horiz => col == 0, TxClass::Vert => row == 0, }; if near_origin { mag + 7 } else { mag + 14 } } fn dc_vote(dc: Option) -> i32 { match dc { None => 0, Some(true) => -1, Some(false) => 1, } } fn dc_sign_ctx(vote: i32) -> usize { match vote.signum() { 0 => 0, -1 => 1, _ => 2, } } /// The `tx_type` a CDF symbol names, given the width of the row it was read /// from. /// /// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` / /// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13 /// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything /// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two /// members are a prefix of the five. /// /// One function rather than a `match` at each reader, so /// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair /// tests the mapping the readers actually use. pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option { match cdf_len { 17 => TxType::from_symbol_all16(t), 13 => TxType::from_symbol_set2_12(t), 8 => TxType::from_symbol_set1(t), _ => TxType::from_symbol(t), } } /// The remainder of a level the base and base-range syntax could not reach /// (spec 5.11.40): its bit length in unary, then that many of its own bits, /// most significant first — the exact inverse of [`crate::tile::write_golomb`]. pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result { // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical // for every tail any encoder writes -- our own writer tops out at 19 zeros // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented // and round-trip tested here (commit ee1f980, reverted in 314ee08). It // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact` // RED: seed 67 stops here today, and with the cap raised it decodes to a // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this // together with that defect's fix, not before. let mut length = 1u32; while dec.literal(1) == 0 { length += 1; if length > 20 { return Err(unsupported("a Golomb tail longer than this decoder reads")); } } let mut x = 1u32; for _ in 1..length { x = (x << 1) | dec.literal(1); } Ok(x - 1) } /// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of /// [`crate::tile`]'s `write_eob`. fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize { const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513]; const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt // a wholly separate CDF from every other tx_type (`decodetxb.c`'s // `eob_multi_ctx`). Missing that split desynced the very first // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught // against a real aomdec trace). let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) { (TxClass::TwoD, _) | (_, None) => coding.eob_pt, (_, Some(class1)) => class1, }; if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { let (range, value) = dec.debug_state(); eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}"); } let group = dec.symbol(eob_pt) + 1; if trace { eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0); } let bits = OFFSET_BITS[group]; let mut offset = 0u32; if bits > 0 { let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32; if trace { eprintln!("TRACE eob_extra ctx={} value={top}", group - 3); } offset = top << (bits - 1); if bits > 1 { offset |= dec.literal(bits - 1); } } GROUP_START[group] + offset as usize } /// One transform block's levels, the inverse of [`crate::tile`]'s /// `write_coeffs`, returned as a `side * side` grid in raster order, along /// with the transform type that grid was coded under (`DCT_DCT` when the /// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and /// 64-point transforms, which never code anything else). /// /// # Errors /// Returns an error if the `tx_type` symbol decodes to a value outside its /// CDF's own set (a corrupt or unsupported bitstream) — every value the /// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can /// produce dispatches to a real inverse transform. /// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its /// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None` /// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so /// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from /// the plane's own predicted mode instead. Every entry this table can /// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two /// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this /// table ever names), so unlike the CDF-coded luma path there is no /// ext-tx-set membership check to fall back from here. pub(crate) fn default_intra_tx_type(mode: u8) -> TxType { use crate::intra::{ D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED, }; match mode { DC_PRED | D45_PRED => TxType::DctDct, V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct, H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst, D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst, other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"), } } /// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED` /// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own /// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth. fn is_smooth_mode(mode: usize) -> bool { (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode) } /// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each. /// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so /// nine of them inside the base/sign loops pinned nine sets of values in the /// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill /// traffic). Out of line, the loop keeps its values in registers and the /// trace output is character-for-character what it was. #[cold] #[inline(never)] fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) { eprintln!("TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"); } #[cold] #[inline(never)] fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) { eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"); } #[cold] #[inline(never)] fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) { eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"); } #[cold] #[inline(never)] fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"); } #[cold] #[inline(never)] fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}"); } #[cold] #[inline(never)] fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32); } #[cold] #[inline(never)] fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}"); } #[cold] #[inline(never)] fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}"); } fn read_coeffs( dec: &mut SymbolDecoder, coding: &mut TxbTables, scan: &[u16], skip_ctx: usize, sign_ctx: usize, // The chroma default (spec `Intra_Mode_To_Tx_Type`, see // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes // nothing at all; `DctDct` for every luma call and every chroma call at // a size the spec forces to `DCT_DCT` regardless of mode (32-point and // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in. default_tx_type: TxType, // `Some((w, h))` with `w != h` when this read is a superblock-level // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8 // root cause, see [`base_ctx`]). `None` everywhere else -- every other // caller's block genuinely is `side` x `side`. rect_shape: Option<(usize, usize)>, ) -> Result<(Grid, TxType)> { let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); let side = coding.side; if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { let (range, value) = dec.debug_state(); eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}"); } let dbg_txbskip = if coeff_trace_on() { coding.txb_skip[skip_ctx] } else { [0; 3] }; let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!( "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}", coding.side, all_zero as i32 ); } if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}", all_zero as u8, dec.debug_bitpos(), dec.debug_state().0 ); } if trace { eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32); } if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { let (range, value) = dec.debug_state(); eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}"); } if all_zero { // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the // shared zero grid instead of allocating and zeroing its own. return Ok((Grid::Zero(side * side), TxType::DctDct)); } let mut grid = vec![0i32; side * side]; let mut tx_type = default_tx_type; if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { // The CDF row's own width names its set (lane-cdffwd2: extended // past the original two-way intra split once wider `reduced_tx_set // == 0` inter sets joined the table): 17 slots (16 symbols) is // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`, // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five). let len = tx_type_cdf.len(); if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 { eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}"); } let t = dec.symbol(tx_type_cdf); if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}"); } if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { let (range, value) = dec.debug_state(); eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}"); } if trace { eprintln!("TRACE tx_type value={t} len={len}"); } tx_type = tx_type_from_symbol(len, t) .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; } let class = TxClass::of(tx_type); if class != TxClass::TwoD { hit!(TX_CLASS1_HITS); hit!(RECT_CLASS1_HITS); } let eob = read_eob(dec, coding, class); if trace { eprintln!("TRACE eob value={eob}"); } let ec_trace_coeff = coeff_trace_on(); if ec_trace_coeff { let (rng, _) = dec.debug_state(); let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" }; eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}"); } let class_scan; let scan: &[u16] = if class == TxClass::TwoD { scan } else { class_scan = class_scan_table(side, class); &class_scan }; // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per- // coefficient `pos / side`, `pos % side` was a hardware divide where a // shift and a mask say the same thing, and the level buffer fits a fixed // 32x32 frame of stack instead of a heap allocation per transform block. debug_assert!(side.is_power_of_two() && side <= 32); let sh = side.trailing_zeros(); let col_mask = side - 1; // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]): // `stride = side + 4` columns and four spare rows, so the widest read // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at // most `36 * 36`. Only `col < side`, `row < side` cells are ever written. let stride = side + 4; let mut levels_buf = [0u8; 36 * 36]; let levels = &mut levels_buf[..stride * stride]; // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the // `pos >> sh` / `& mask` decomposition and load the level back out of the // padded frame just to skip the zeros. The base pass already knows both, // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign // pass walks that list in reverse (the base pass runs in reverse scan // order, so reversing it is forward scan order: the same coefficients, in // the same order, with the same `c` the trace prints). let mut nz_buf = [0u16; 1024]; let mut nz_n = 0usize; let (base_taps, br_taps) = flat_taps(stride, class); for scan_idx in (0..eob).rev() { let pos = scan[scan_idx] as usize; let (row, col) = (pos >> sh, pos & col_mask); let idx = row * stride + col; let level = if scan_idx == eob - 1 { let ctx = eob_coeff_ctx(scan_idx, side * side); let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; if trace { trace_base_eob(scan_idx, pos, row, col, ctx, v); } v } else { let ctx = if class == TxClass::TwoD && rect_shape.is_none() { if row == 0 && col == 0 { 0 } else { base_mag(levels, idx, &base_taps) + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize } } else { base_ctx(levels, stride, row, col, class, rect_shape) }; let v = dec.symbol(&mut coding.base[ctx]) as i32; if ec_trace_coeff { // `pos` in libaom's column-major `coeff_idx` convention, so // the ladder lines up with instrumented `aomdec`. coeff_step_base(dec, scan_idx, col * side + row, ctx, v); } if trace { trace_base(scan_idx, pos, row, col, ctx, v); } v }; let level = if level > NUM_BASE_LEVELS { let ctx = { let mag = br_mag(levels, idx, &br_taps); if row == 0 && col == 0 { mag } else { let near_origin = match class { TxClass::TwoD => row < 2 && col < 2, TxClass::Horiz => col == 0, TxClass::Vert => row == 0, }; if near_origin { mag + 7 } else { mag + 14 } } }; let mut level = level; let mut sent = 0; loop { let k = dec.symbol(&mut coding.br[ctx]) as i32; if ec_trace_coeff { // lane-leaf8tx r3: the `br` rung was missing from THIS // path's trace, so the cross-decoder range ladder was // blind to every base-range symbol and mis-reported the // first divergence (class [[gate-blind-to-feature]]). coeff_step_br(dec, scan_idx, col * side + row, ctx, k); } if trace { trace_br(scan_idx, pos, row, col, ctx, k); } level += k; sent += BR_STEP; if k < BR_STEP || sent >= COEFF_BASE_RANGE { break; } } level } else { level }; if ec_trace_coeff && scan_idx == eob - 1 { coeff_step_base_eob_level(dec, level); } // Every coded level here is a magnitude in `0..=15` (base <= 3 plus // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is // added in the sign pass below, straight into `grid`), so the context // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a // byte gather (lane-coefbuf). debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame"); levels[idx] = level as u8; if level != 0 { nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16; nz_n += 1; } } if ec_trace_coeff { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}"); } for &packed in nz_buf[..nz_n].iter().rev() { let c = (packed >> 4) as usize; let pos = scan[c] as usize; let level = (packed & 15) as i32; let negative = if pos == 0 { let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1; if trace { eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32); } v } else { dec.literal(1) == 1 }; if ec_trace_coeff { coeff_step_sign(dec, c, negative); } let level = if level > MAX_BR_LEVEL { let g = read_golomb(dec)?; if trace { eprintln!("TRACE golomb pos={pos} value={g}"); } level + g as i32 } else { level }; if ec_trace_coeff { coeff_step_post_golomb(dec, c, level); } grid[pos] = if negative { -level } else { level }; } Ok((Grid::Own(grid), tx_type)) } /// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the /// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to /// `TxClass::TwoD` -- the only class any rect size pair this decoder codes /// can ever produce, since every `tx_type` this decoder's rect sets can read /// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name /// rather than guess-decode if a non-2D class ever shows up here, since /// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect /// form for those. fn read_coeffs_rect( dec: &mut SymbolDecoder, coding: &mut TxbTables, scan: &[u16], w: usize, h: usize, skip_ctx: usize, sign_ctx: usize, default_tx_type: TxType, ) -> Result<(Grid, TxType)> { let rect_trace = coeff_trace_on(); let entry_rng = dec.debug_state().0; let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; if rect_trace { eprintln!( "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}", all_zero as i32, dec.debug_state().0 ); } if all_zero { return Ok((Grid::Zero(w * h), TxType::DctDct)); } let mut grid = vec![0i32; w * h]; hit!(RECT_COEFF_TU_HITS); // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and // context offsets -- both of which now have rect forms // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`). // The rect sets that carry no symbol at all still pass `None` here. let mut tx_type = default_tx_type; if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { let len = tx_type_cdf.len(); let t = dec.symbol(tx_type_cdf); tx_type = tx_type_from_symbol(len, t) .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; if rect_trace { eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0); } } let class = TxClass::of(tx_type); if class != TxClass::TwoD { hit!(TX_CLASS1_HITS); } let eob = read_eob(dec, coding, class); if rect_trace { eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0); } let class_scan; let scan: &[u16] = if class == TxClass::TwoD { scan } else { class_scan = class_scan_table_wh(w, h, class); &class_scan }; // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a // stack frame sized to the unit -- same reasoning as [`read_coeffs`]: // `neighbour_rect` returns 0 outside `(w, h)` and every write is // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a // mask rather than a hardware divide. let stride = w + 4; let n = stride * (h + 4); debug_assert!(w.is_power_of_two() && n <= 36 * 36); let (mut b96, mut b256, mut b768); // Byte levels, same `0..=15` bound [`read_coeffs`] states. let levels: &mut [u8] = if n <= 96 { b96 = [0u8; 96]; &mut b96[..n] } else if n <= 256 { b256 = [0u8; 256]; &mut b256[..n] } else { b768 = [0u8; 768]; &mut b768[..n] }; let wsh = w.trailing_zeros(); let wmask = w - 1; // lane-coefread: the non-zero list [`read_coeffs`] documents. let mut nz_buf = [0u16; 1024]; let mut nz_n = 0usize; let (base_taps, br_taps) = flat_taps(stride, class); let (wlt, wgt) = (w < h, w > h); for scan_idx in (0..eob).rev() { let pos = scan[scan_idx] as usize; let (row, col) = (pos >> wsh, pos & wmask); let idx = row * stride + col; // libaom's column-major `coeff_idx`, for ladder comparison. let _apos = col * h + row; let level = if scan_idx == eob - 1 { let ctx = eob_coeff_ctx(scan_idx, w * h); let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; if rect_trace { eprintln!( "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}", dec.debug_state().0 ); } v } else { let ctx = if class == TxClass::TwoD { if row == 0 && col == 0 { 0 } else { let m = base_mag(levels, idx, &base_taps); if wlt && row < 2 { m + 11 } else if wgt && col < 2 { m + 16 } else { m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize } } } else { base_ctx_rect(levels, stride, w, h, row, col, class) }; let v = dec.symbol(&mut coding.base[ctx]) as i32; if rect_trace { eprintln!( "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}", dec.debug_state().0 ); } v }; let level = if level > NUM_BASE_LEVELS { let ctx = { let mag = br_mag(levels, idx, &br_taps); if row == 0 && col == 0 { mag } else { let near_origin = match class { TxClass::TwoD => row < 2 && col < 2, TxClass::Horiz => col == 0, TxClass::Vert => row == 0, }; if near_origin { mag + 7 } else { mag + 14 } } }; let mut level = level; let mut sent = 0; loop { let k = dec.symbol(&mut coding.br[ctx]) as i32; if rect_trace { eprintln!( "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}", dec.debug_state().0 ); } level += k; sent += BR_STEP; if k < BR_STEP || sent >= COEFF_BASE_RANGE { break; } } level } else { level }; debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame"); levels[idx] = level as u8; if level != 0 { nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16; nz_n += 1; } if rect_trace { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}"); } } if rect_trace { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}"); } for &packed in nz_buf[..nz_n].iter().rev() { let pos = scan[(packed >> 4) as usize] as usize; let level = (packed & 15) as i32; let negative = if pos == 0 { dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1 } else { dec.literal(1) == 1 }; if rect_trace { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative)); } let level = if level > MAX_BR_LEVEL { let g = read_golomb(dec)?; level + g as i32 } else { level }; grid[pos] = if negative { -level } else { level }; } Ok((Grid::Own(grid), tx_type)) } /// What one coded block leaves behind for the blocks that read it as a /// neighbour: whether it coded anything at all, and the sign of its DC — /// [`crate::tile`]'s own private `Neighbour`. #[derive(Clone, Copy, Default)] struct Neighbour { /// The transform unit's cumulative coefficient level (spec `cul_level`, /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not" /// boolean (`level != 0`) is enough for every context this decoder read /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`) /// needs the actual magnitude tier of its above/left neighbours, not /// just whether they coded anything. level: u8, dc: Option, } /// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the /// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the /// grid is dropped, never a panic. One `memset` per grid row instead of a /// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers /// is contiguous, so this writes exactly the cells the cell loop did, /// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the /// next row. #[inline] fn fill_span(dst: &mut [T], start: usize, n: usize, v: T) { let end = (start + n).min(dst.len()); if start < end { dst[start..end].fill(v); } } fn neighbour_state(grid: &[i32]) -> Neighbour { // lane-coefgrid: the shared zero grid sums to zero by construction; this // sum has no early exit, so the 60% of units that code nothing used to // walk their whole grid here. if is_zero_grid(grid) { return Neighbour::default(); } let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum(); Neighbour { level: cul.min(7) as u8, dc: (grid[0] != 0).then_some(grid[0] < 0), } } /// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0, /// transform unit smaller than the block it sits in): `top`/`left` are the /// above/left neighbours' magnitude tiers, each already clamped to 4. pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [ [1, 2, 2, 2, 3], [2, 4, 4, 4, 5], [2, 4, 4, 4, 5], [2, 4, 4, 4, 5], [3, 5, 5, 5, 6], ]; /// The `skip` flag, its written-instrument bit, and the covering coded /// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the /// four maps are written together by `Neighbours::fill_skip_grid_rect` and by /// nothing else, so a block's row is one fill instead of four, and the /// deblocker's `pu_edge` reads origin and dims off one cache line. #[derive(Clone, Copy)] struct BlkCell { skip: bool, written: bool, org: [u16; 2], dim: [u8; 2], } /// The neighbour state a block's contexts are read from — a duplicate of /// [`crate::tile`]'s own private `Neighbours` (that module is another lane's /// territory this round), kept at the same two granularities the real writer /// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16 /// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s /// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient /// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a /// chroma transform straddling the true, odd-sized frame edge see its /// neighbour's state clamped at its own subsampled edge rather than luma's. #[derive(Clone)] struct Neighbours { above: Vec<[Neighbour; 3]>, left: Vec<[Neighbour; 3]>, above_mode: Vec, left_mode: Vec, /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the /// luma one -- the same block can (and often does) code a different /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`; /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real /// within-block neighbour finer than this grid) is luma-only -- a known, /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs` /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this). above_uv_mode: Vec, left_uv_mode: Vec, above_side: Vec, left_side: Vec, /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4) /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse /// array cannot tell the second leaf's partition symbol that the first /// one was coded at 8x8. /// lane-publish2: `u8` (a block side is at most 128 px, and so is /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi. above_side_mi: Vec, left_side_mi: Vec, /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column /// / row, with the mi position it was written at /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8 /// leaf whose neighbour is another split group needs that group's leaf 3 /// (bottom-right), not the leaf the coarse slot happens to hold. Written /// and read only by [`decode_leaf_split4`]; the position guard makes it /// fall back to the coarse slot whenever the real neighbour was a block /// of 8x8 or larger (whose one mode is correct for every row it spans). /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes /// per mi per side of publish traffic was pure width. `u16::MAX` is the /// "never written" sentinel (an mi index cannot reach it: AV1's largest /// frame is 65536 px = 16384 mi). sub8_mode_col: Vec<(u16, u8)>, sub8_mode_row: Vec<(u16, u8)>, /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5): /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode` /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves -- /// the leaf above writes the same row slot the block to the left owns. uv_mode_col: Vec<(u16, u8)>, uv_mode_row: Vec<(u16, u8)>, /// Every mi cell's own `uv_mode`, the mi grid libaom's /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`, /// blockd.h). lane-t900 r12: the one-slot-per-column /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half /// overwrote the row the pair's chroma-ref half then wanted to read -- /// the mi-exact match failed and the coarse [`SUB`] band answered instead. /// `u8::MAX` = no block has written this cell yet (fall back to the maps). uv_mode_grid: Vec, /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like /// every other band here). uv_grid_cols: usize, /// Whether the block above/left of this column/row was coded `skip` -- /// an inter frame's own `skip` context (spec `SkipContext`), which the /// key-frame writer never tracks (its skip context is always zero); a /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/ /// `left_skip`. above_skip: Vec, left_skip: Vec, /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in /// pixels last written over each unit by `set_txfm_ctxs`/ /// `txfm_partition_update`, which is what an inter block's `txfm_split` /// symbol reads its context from (lane-txselect, spec 5.11.17). /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left` /// array is exactly libaom's per-superblock-row reset, since each mi row /// is only ever visited inside one superblock row. above_txfm: Vec, left_txfm: Vec, /// Whether the block above/left of this column/row coded `skip_mode` /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup, /// lane-av1comp round 14. above_skip_mode: Vec, left_skip_mode: Vec, /// Whether the block above/left was coded inter -- the `is_inter` /// context (spec `av1_get_intra_inter_context`), a duplicate of /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`. above_inter: Vec, left_inter: Vec, /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME` /// alphabet) the block above/left of this column/row coded, or `-1` for /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context /// functions (`mvstack::ref_ctx` family) need the real reference, not /// just "was it inter" (lane-av1refs: every inter block used to be /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was /// enough). above_ref: Vec, left_ref: Vec, /// The block above/left's *second* reference frame when it was coded /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra -- /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx` /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s /// `i8`, once a compound `read_ref_frames` lands. /// lane-publish2 audit: the "always `None` today" note this doc used to /// carry is long stale -- compound blocks do occur, and /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference /// over their span right after [`Self::record_inter_rect_mi`]'s reset. /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every /// [`crate::mvstack::NeighbourRef`] construction (class /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong). above_ref1: Vec>, left_ref1: Vec>, /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context` /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`): /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a /// single-ref one, or `0` for intra/unavailable -- lane-av1comp. above_comp_group_idx: Vec, left_comp_group_idx: Vec, above_compound_idx: Vec, left_compound_idx: Vec, /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or /// `3` = "no info": an intra neighbour or the frame's own border) of the /// block above/left of this column/row -- spec /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup. above_filter: Vec<[u8; 2]>, left_filter: Vec<[u8; 2]>, mi_cols: usize, mi_rows: usize, /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame, /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec /// 7.15) never filters an 8x8 luma block whose covering coded block read /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the /// grain [`Self::record_mi`] already writes at), read back at 8x8 /// granularity by [`apply_cdef`] since `skip` is constant across every /// mi cell one coded block covers. /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell. /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE /// the `skip` bit at this mi cell during this frame. A fresh /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip` /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and /// unobservable from the pixels alone. Counted by /// [`cdef_unwritten_skip_units`]. /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`, /// which re-enables the loop filter at a prediction boundary between two /// skipped inter blocks (lane-mergefix r4). Written by /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin. /// Per-4x4-mi `(width, height)` in mi units of the coded block covering /// that cell -- the other half of `pu_edge`: libaom tests the edge /// coordinate against the block's size in the FILTERED plane's own /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b). blk_grid: Vec, skip_grid_cols_mi: usize, /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder /// never splits a coded block's transform below its own size (round 2: /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its /// transform size, spec 7.14's `get_transform_size`/`get_filter_level` /// edge-length lookup (`apply_deblock`). tx_grid: Vec, /// The transform HEIGHT companion to [`Self::tx_grid`]'s width -- /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT). tx_h_grid: Vec, /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4. /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the /// largest transform covering the subsampled BLOCK, capped at 32x32. It /// does NOT follow luma's `tx_depth` split, so deriving it as /// `tx_grid / 2` invented chroma transform edges the deblocker then /// filtered (32x16 frames, U plane, seeds 42/47). Written from the /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place /// every caller routes through. uv_tx_grid: Vec, uv_tx_h_grid: Vec, /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` = /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` -- /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2) /// -- the loop filter's ref/mode delta lookup (spec 7.14.4 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs: /// widened from a bare `is_inter` bool, which collapsed every non-`LAST` /// reference onto `LAST_FRAME`'s own delta). ref_grid: Vec, /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`, /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs /// to know which mode produced the value. delta_lf_grid: Vec<[i8; 4]>, /// The block above/left's own palette-Y size (0 = not a palette block) /// and its base colours -- `av1_get_palette_mode_ctx`/ /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette /// r2. UV has no equivalent yet (stage 2, unreconstructed). above_palette_size: Vec, left_palette_size: Vec, above_palette_colors: Vec<[u16; 8]>, left_palette_colors: Vec<[u16; 8]>, /// As the four fields above, for the neighbour's own chroma (U-channel /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`]) /// palette size/colours (lane-palette2 r1). above_palette_uv_size: Vec, left_palette_uv_size: Vec, above_palette_uv_colors: Vec<[u16; 8]>, left_palette_uv_colors: Vec<[u16; 8]>, /// This tile's own top-left corner, in 4x4 mode-info units (spec /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a /// neighbour" check compares against this instead of literal `0`, since a /// block at the tile's own top/left edge has no usable neighbour even /// though a decoded block sits there in the picture (spec `decode_tile`'s /// per-tile `clear_above_context`/`left_available`/`up_available`). /// `0` for a single-tile frame, matching every existing caller exactly. tile_row0_mi: usize, tile_col0_mi: usize, } #[allow(dead_code)] // read only from the `#[cfg(test)]` gates impl Neighbours { /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's /// true (unpadded) size in 4x4 mode-info units. fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self { // lane-sb128c r7: a 128x64 block at the bottom frame edge records its // neighbour state over the whole 64-row extent, past the frame's last // mi row (mi_rows 198, block rows 192..208). libaom's own context // buffers are superblock-aligned for exactly that reason // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the // side arrays to a superblock multiple and leave those cells unread -- // every availability check uses the true `mi_rows`/`mi_cols` below. let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI); let (cols, rows) = ( cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub), ); Self { above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)], left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)], above_mode: vec![DC_PRED; cols], left_mode: vec![DC_PRED; rows], above_uv_mode: vec![DC_PRED; cols], left_uv_mode: vec![DC_PRED; rows], above_side: vec![NO_NEIGHBOUR_SIDE; cols], left_side: vec![NO_NEIGHBOUR_SIDE; rows], above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)], left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)], sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)], sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)], uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)], uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)], uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)], uv_grid_cols: cols * (SUB / MI), above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an // 8x8 inter leaf's left neighbour is the OTHER leaf row of the // 16x16 block beside it, which a SUB-grid slot cannot name // (class context-read-from-one-cell). above_skip: vec![false; cols * (SUB / MI)], left_skip: vec![false; rows * (SUB / MI)], above_skip_mode: vec![false; cols * (SUB / MI)], left_skip_mode: vec![false; rows * (SUB / MI)], above_inter: vec![false; cols * (SUB / MI)], left_inter: vec![false; rows * (SUB / MI)], above_ref: vec![-1; cols * (SUB / MI)], left_ref: vec![-1; rows * (SUB / MI)], above_ref1: vec![None; cols * (SUB / MI)], left_ref1: vec![None; rows * (SUB / MI)], above_comp_group_idx: vec![0; cols * (SUB / MI)], left_comp_group_idx: vec![0; rows * (SUB / MI)], above_compound_idx: vec![0; cols * (SUB / MI)], left_compound_idx: vec![0; rows * (SUB / MI)], above_filter: vec![[3u8; 2]; cols * (SUB / MI)], left_filter: vec![[3u8; 2]; rows * (SUB / MI)], mi_cols, mi_rows, blk_grid: vec![ BlkCell { skip: false, written: false, org: [0; 2], dim: [1; 2] }; cols * (SUB / MI) * rows * (SUB / MI) ], skip_grid_cols_mi: cols * (SUB / MI), tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)], delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)], above_palette_size: vec![0; cols * (SUB / MI)], left_palette_size: vec![0; rows * (SUB / MI)], above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)], left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)], above_palette_uv_size: vec![0; cols * (SUB / MI)], left_palette_uv_size: vec![0; rows * (SUB / MI)], above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)], left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)], tile_row0_mi: 0, tile_col0_mi: 0, } } /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this /// tile's own column span (`col1_mi` exclusive), plus recording /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every /// availability check below. Left context resets every superblock row /// regardless of tile ([`Self::start_row`], already called once per SB /// row by every caller) so it needs no tile-specific reset here. fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) { // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction // are tile-relative, same as every other neighbour lookup here. fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi))); self.tile_row0_mi = row0_mi; self.tile_col0_mi = col0_mi; let end = col1_mi.min(self.above.len()); for i in col0_mi.min(end)..end { self.above[i] = Default::default(); self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8; } let (sc0, sc1) = ( col0_mi / (SUB / MI), (col1_mi / (SUB / MI)).min(self.above_mode.len()), ); for i in sc0.min(sc1)..sc1 { self.above_mode[i] = DC_PRED; self.above_side[i] = NO_NEIGHBOUR_SIDE; } // lane-inter8 r2: the inter bands are mi-granular, so they reset over // the tile's own mi column span directly. let mend = col1_mi.min(self.above_skip.len()); for i in col0_mi.min(mend)..mend { self.above_skip[i] = false; self.above_skip_mode[i] = false; self.above_inter[i] = false; self.above_ref[i] = -1; self.above_ref1[i] = None; self.above_comp_group_idx[i] = 0; self.above_compound_idx[i] = 0; self.above_filter[i] = [3u8; 2]; } // lane-sub8 r6: the mi-granular column maps are per tile too -- a // stale `(row, mode)` from the tile to the LEFT names an mi row this // tile's first block would read as its own above neighbour. let mcol_end = col1_mi.min(self.sub8_mode_col.len()); for i in col0_mi.min(mcol_end)..mcol_end { self.sub8_mode_col[i] = (u16::MAX, 0); self.uv_mode_col[i] = (u16::MAX, 0); } // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`, // not zero) -- without it a second tile column reads the first one's // resolved transform sizes as its own above context. let tend = col1_mi.min(self.above_txfm.len()); for i in col0_mi.min(tend)..tend { self.above_txfm[i] = TXFM_CTX_INIT; } } /// Writes a just-decoded block's own palette-Y size/colours (`size == 0` /// for a non-palette block, clearing any stale neighbour state) into every /// [`SUB`]-grid cell it covers on both the above and left edges -- /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's /// call sites are all square blocks). fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) { self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors); } /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`) /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs /// [`Self::record`]): a true rect strip's above/left neighbour spans /// differ. fn record_palette_y_rect( &mut self, mi: (usize, usize), w: usize, h: usize, size: usize, colors: [u16; 8], ) { let (r, c) = mi; if crate::envflags::env_flag!("EC_PALPUB") { eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}"); } // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size` // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi // cell immediately left of the block, not its 16px [`SUB`] cell. The // old SUB grid let a 16x8 strip pair share one slot, so the second // strip of mi(0,8) read the FIRST strip's palette size and the colour // cache came out one entry short (class [[context-read-from-one-cell]]). for cell in 0..(w / MI).max(1) { if let Some(e) = self.above_palette_size.get_mut(c + cell) { *e = size as u8; // lane-publish2: spec 5.11.46 `get_palette_cache` reads a // neighbour's colours only where its palette size > 0, so a // non-palette block need not stamp 16 bytes of zeroes here. if size > 0 { self.above_palette_colors[c + cell] = colors; } } } for cell in 0..(h / MI).max(1) { if let Some(e) = self.left_palette_size.get_mut(r + cell) { *e = size as u8; if size > 0 { self.left_palette_colors[r + cell] = colors; } } } } /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left /// neighbours that are themselves a palette-Y block, plus /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour /// cache (pred_common.c:73). /// /// The SB-top-row exclusion of the above neighbour (`row % 64` in /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to /// the ctx too made every superblock in the frame's second SB row read /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real /// palette block decoded as "no palette" and the tile desynced from /// there (class [[cdf-row-held-constant]]). fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec) { self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI))) } /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache` /// drops the above neighbour on a 64-px superblock boundary /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of /// every strip in an SB's top cell row, which libaom does not do. fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec) { let (r, c) = mi; let above_ok = r % 16 != 0; // `xd->above_mbmi` exists for every row but the tile's own first. let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0; let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 { (usize::from(self.above_palette_size[c]), self.above_palette_colors[c]) } else { (0, [0u16; 8]) }; // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which // is NULL whenever the block sits at its TILE's own left column // (`left_available`), not the frame's -- without this guard a second // tile column reads the previous tile's palette colours into its cache // and its `palette_y_mode` ctx. let left_ok = c > self.tile_col0_mi; let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 { (usize::from(self.left_palette_size[r]), self.left_palette_colors[r]) } else { (0, [0u16; 8]) }; let ctx = usize::from(above_is_palette) + usize::from(left_n > 0); let mut cache = Vec::with_capacity(16); let push_dedup = |cache: &mut Vec, v: u16| { if cache.last() != Some(&v) { cache.push(v); } }; let (mut ai, mut li) = (0usize, 0usize); while ai < above_n && li < left_n { let (va, vl) = (above_colors[ai], left_colors[li]); if vl < va { push_dedup(&mut cache, vl); li += 1; } else { push_dedup(&mut cache, va); ai += 1; if vl == va { li += 1; } } } while ai < above_n { push_dedup(&mut cache, above_colors[ai]); ai += 1; } while li < left_n { push_dedup(&mut cache, left_colors[li]); li += 1; } (ctx, cache) } /// As [`Self::record_palette_y`], for a just-decoded block's own chroma /// (U-channel) palette size/colours -- `size == 0` clears stale state the /// same way (lane-palette2 r1). fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) { self.record_palette_uv_rect( (at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors, ); } /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`) /// extents, in LUMA pixels (lane-palette2 r4, same convention as /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at /// luma resolution regardless of which plane the recorded state is for). fn record_palette_uv_rect( &mut self, mi: (usize, usize), w: usize, h: usize, size: usize, colors: [u16; 8], ) { let (r, c) = mi; // mi granularity, see [`Self::record_palette_y_rect`]. for cell in 0..(w / MI).max(1) { if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) { *e = size as u8; if size > 0 { self.above_palette_uv_colors[c + cell] = colors; } } } for cell in 0..(h / MI).max(1) { if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) { *e = size as u8; if size > 0 { self.left_palette_uv_colors[r + cell] = colors; } } } } /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs /// no neighbour lookup at all (it is this block's own just-decided Y /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`), /// so only the cache is wanted here. fn palette_uv_cache(&self, at: (usize, usize)) -> Vec { self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI))) } /// [`Self::palette_uv_cache`] with the block's real mi row -- see /// [`Self::palette_ctx_and_cache_mi`]. fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec { let (r, c) = mi; let above_ok = r % 16 != 0; let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 { (usize::from(self.above_palette_uv_size[c]), self.above_palette_uv_colors[c]) } else { (0, [0u16; 8]) }; // Same tile-relative left availability as the luma cache above. let left_ok = c > self.tile_col0_mi; let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 { (usize::from(self.left_palette_uv_size[r]), self.left_palette_uv_colors[r]) } else { (0, [0u16; 8]) }; let mut cache = Vec::with_capacity(16); let push_dedup = |cache: &mut Vec, v: u16| { if cache.last() != Some(&v) { cache.push(v); } }; let (mut ai, mut li) = (0usize, 0usize); while ai < above_n && li < left_n { let (va, vl) = (above_colors[ai], left_colors[li]); if vl < va { push_dedup(&mut cache, vl); li += 1; } else { push_dedup(&mut cache, va); ai += 1; if vl == va { li += 1; } } } while ai < above_n { push_dedup(&mut cache, above_colors[ai]); ai += 1; } while li < left_n { push_dedup(&mut cache, left_colors[li]); li += 1; } cache } /// Marks every 4x4 mi cell a just-decoded coded block covers with its own /// transform width (in pixels) and `is_inter` flag -- the loop filter's /// per-edge lookup (`apply_deblock`), filled at the same call sites and /// units as [`Self::fill_skip_grid`]. fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) { self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx); } /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi` /// != `h_mi`); `tx_px` still names a single scalar (this decoder's /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent). /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a /// transform-unit edge but NOT a prediction-unit edge is not filtered when /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this /// block's published transform extent to its own size is exactly that /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape /// that needs it is the 128 root, whose chroma extent (64) is the one /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is /// never suppressed (libaom's `is_inter_block` term), so this is called /// only from the skipped-inter branch. fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) { let (mi_r, mi_c) = at_mi; let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8); for rr in 0..h_mi { let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w); fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h); } } fn fill_lf_grid_rect( &mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, tx_px: u8, tx_h_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx, ) { let (mi_r, mi_c) = at_mi; // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is // half its luma one (min 4 px, the smallest transform), capped at // TX_32X32 -- independent of this block's luma `tx_depth`. let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8; let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8; if crate::envflags::env_flag!("EC_TXGRID_TRACE") { eprintln!("EC_LFGRID mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}"); } let cur = fctx.current_delta_lf.with(|c| c.get()); let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) { std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8) } else { [cur[0].clamp(-63, 63) as i8; 4] }; for rr in 0..h_mi { let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; fill_span(&mut self.tx_grid, start, w_mi, tx_px); fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px); fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w); fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h); fill_span(&mut self.ref_grid, start, w_mi, ref_frame); fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot); } } /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span. /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform. /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv /// dims from the LEAF span and so invented chroma transform edges the /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid` /// are already correct from the block's own fill over the same span. fn fill_lf_grid_leaf_luma( &mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, tx_px: u8, tx_h_px: u8, ) { let (mi_r, mi_c) = at_mi; if crate::envflags::env_flag!("EC_TXGRID_TRACE") { eprintln!("EC_LFLEAF mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}"); } for rr in 0..h_mi { let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; fill_span(&mut self.tx_grid, start, w_mi, tx_px); fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px); } } /// Marks every 4x4 mi cell a just-decoded coded block covers with its /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s /// own units, not [`Self::record`]'s [`SUB`]-grid ones). fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) { self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip); } /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1). fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) { let (mi_r, mi_c) = at_mi; if skip && w_mi != h_mi { hit!(RECT_SKIP_BAND_HITS); } for rr in 0..h_mi { let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; fill_span( &mut self.blk_grid, start, w_mi, BlkCell { skip, written: true, org: [mi_r as u16, mi_c as u16], dim: [w_mi as u8, h_mi as u8], }, ); } } /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test. /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can /// straddle the region with a mix of skip/non-skip blocks). /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a /// filtered edge's two sides are each exactly one coded block wide. fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool { self.blk_grid .get(mi_r * self.skip_grid_cols_mi + mi_c) .is_some_and(|c| c.skip) } /// The `skip_txfm` context of a block whose top-left mi cell is /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context` /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`, /// with an absent neighbour contributing 0. The mi grid is per tile, so /// row/column 0 is a tile edge and has no neighbour on that axis. fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize { usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c)) + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1)) } fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool { (0..2).all(|rr| { (0..2).all(|cc| { self.blk_grid .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc)) .is_some_and(|c| c.skip) }) }) } fn start_row(&mut self) { self.left.iter_mut().for_each(|l| *l = Default::default()); self.left_mode.iter_mut().for_each(|m| *m = DC_PRED); self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED); self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE); self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8); self.left_skip.iter_mut().for_each(|s| *s = false); self.left_skip_mode.iter_mut().for_each(|s| *s = false); self.left_inter.iter_mut().for_each(|i| *i = false); self.left_ref.iter_mut().for_each(|r| *r = -1); self.left_ref1.iter_mut().for_each(|r| *r = None); self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0); self.left_compound_idx.iter_mut().for_each(|r| *r = 0); self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]); // lane-sub8 r6: mi-granular row maps reset with the rest of the left // context (a tile/SB-row boundary has no left neighbour). self.sub8_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0)); self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0)); // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands // are per-mi maps like every other one here, so they reset with the // row too -- the left guard above is what actually stops a cross-tile // read, this keeps a stale colour out of the arrays at all. self.left_palette_size.iter_mut().for_each(|s| *s = 0); self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]); self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0); self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]); // lane-mergefix r2: `av1_zero_left_context` memsets // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at // every superblock row of every tile -- the var-tx left context does // NOT carry over a tile boundary (its `txfm_partition` ctx read the // previous tile column's last block otherwise). self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); } /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next /// block that reads it as a neighbour -- [`crate::tile`]'s /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec /// `get_ref_filter_type`'s "not this ref frame" case reads the same as /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs /// the real value, not just `is_inter`). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn record_inter( &mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8, filter: [u8; 2], skip_mode: bool, ) { self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode); } /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions /// r1: a true rectangular strip's above-context span (its own width) and /// left-context span (its own height) differ, unlike every caller before /// this round (class neighbour-votes-all-its-fields). #[allow(clippy::too_many_arguments)] #[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn record_inter_rect( &mut self, at: (usize, usize), w_sub: usize, h_sub: usize, skip: bool, is_inter: bool, ref_frame: i8, filter: [u8; 2], skip_mode: bool, ) { let (r, c) = at; self.record_inter_rect_mi( (r * (SUB / MI), c * (SUB / MI)), w_sub / MI, h_sub / MI, skip, is_inter, ref_frame, filter, skip_mode, ); } /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the /// side bands are written (and read) per mi. Every [`SUB`]-unit caller /// routes through the wrapper above. #[allow(clippy::too_many_arguments)] fn record_inter_rect_mi( &mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool, is_inter: bool, ref_frame: i8, filter: [u8; 2], skip_mode: bool, ) { let (r, c) = at_mi; // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY // writes for a whole block class): an INTER block left the luma mode // map untouched, so a later intra block's `get_intra_edge_filter_type` // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the // coarse SUB-row band, which still held a SMOOTH mode from an earlier // block in that pixel row -- the directional edge filter then ran at // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour, // which for an inter block is an INTER mode (>= NEARESTMV) and is // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups // already stamped it). // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for // an inter neighbour ("uv_mode is not set for inter blocks"), so the // uv map must read DC_PRED over an inter block's cells too. if is_inter { self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED); self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED); } let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME; self.above_skip[c..c + w_mi].fill(skip); self.above_skip_mode[c..c + w_mi].fill(skip_mode); self.above_inter[c..c + w_mi].fill(is_inter); self.above_ref[c..c + w_mi].fill(ref_frame); // The single-ref default: `record_compound_ctx_rect_mi` overwrites // this with the block's real second reference for a compound block, // called right after this one (lane-publish2 audit). self.above_ref1[c..c + w_mi].fill(None); // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads // as `3`/`1` even though this block has no second reference. // `record_compound_ctx` overwrites this with the real bit for an // actual compound block's cells, called right after this one. self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 }); self.above_compound_idx[c..c + w_mi].fill(u8::from(altref)); self.above_filter[c..c + w_mi].fill(filter); self.left_skip[r..r + h_mi].fill(skip); self.left_skip_mode[r..r + h_mi].fill(skip_mode); self.left_inter[r..r + h_mi].fill(is_inter); self.left_ref[r..r + h_mi].fill(ref_frame); self.left_ref1[r..r + h_mi].fill(None); self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 }); self.left_compound_idx[r..r + h_mi].fill(u8::from(altref)); self.left_filter[r..r + h_mi].fill(filter); } /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with /// a real compound block's own `comp_group_idx`/`compound_idx` bits /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/ /// `get_comp_index_context`) -- called right after `record_inter` for /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also /// stamps `above_ref1`/`left_ref1` with the block's real second /// reference, which `record_inter` always clears to `None` (lane-av1comp: /// this is the one caller that actually knows it) -- so the next block's /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound /// neighbour instead of `record_inter`'s single-ref default. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn record_compound_ctx( &mut self, at: (usize, usize), side: usize, ref1: i8, comp_group_idx: u8, compound_idx: u8, ) { self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx); } /// [`Self::record_compound_ctx`] with independent above/left extents, /// mirroring [`Self::record_inter_rect`] (lane-partitions r1). #[allow(clippy::too_many_arguments)] #[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn record_compound_ctx_rect( &mut self, at: (usize, usize), w_sub: usize, h_sub: usize, ref1: i8, comp_group_idx: u8, compound_idx: u8, ) { let (r, c) = at; self.record_compound_ctx_rect_mi( (r * (SUB / MI), c * (SUB / MI)), w_sub / MI, h_sub / MI, ref1, comp_group_idx, compound_idx, ); } /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see /// [`Self::record_inter_rect_mi`]). fn record_compound_ctx_rect_mi( &mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, ref1: i8, comp_group_idx: u8, compound_idx: u8, ) { let (r, c) = at_mi; for cell in 0..w_mi { self.above_ref1[c + cell] = Some(ref1); self.above_comp_group_idx[c + cell] = comp_group_idx; self.above_compound_idx[c + cell] = compound_idx; } for cell in 0..h_mi { self.left_ref1[r + cell] = Some(ref1); self.left_comp_group_idx[r + cell] = comp_group_idx; self.left_compound_idx[r + cell] = compound_idx; } } /// The context of a block's partition symbol: delegates to the mi-precise /// reader (same pattern as `around`/`around_mi`) -- `above_side`/ /// `left_side` are only ever advanced in whole-[`SUB`] steps by /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which /// only touches the finer mi arrays -- leaves them stale for the *next* /// sibling's own partition symbol. fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize { let (r, c) = at; self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side) } /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi` /// arrays so the second leaf sees the first leaf's own 8x8 side rather /// than the enclosing 16x16 slot's stale, shared state. fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize { 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side) + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side) } /// The gathered coded/DC-sign state of the blocks above and to the left /// of a block `side` samples across, per plane. fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] { self.around_mi((r * (SUB / MI), c * (SUB / MI)), side) } /// [`Self::around`] taking the block's position directly in 4x4 mode-info /// units, for the same reason [`Self::record_mi`] does. fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] { let side_mi = side / MI; // One pass over the cells accumulating all three planes, not one pass // per plane: the three planes of a cell live in the same // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same // cache lines three times (lane-publish). let mut out = [(false, false, 0i32); 3]; for cell in 0..side_mi { let above = &self.above[mi_c + cell]; let left = &self.left[mi_r + cell]; for (plane, o) in out.iter_mut().enumerate() { o.0 |= above[plane].level != 0; o.1 |= left[plane].level != 0; o.2 += dc_vote(above[plane].dc) + dc_vote(left[plane].dc); } } out } /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric /// extent pattern for a true rectangular strip's own coefficient context. fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] { self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h) } /// [`Self::around_rect`] taking the block's position directly in 4x4 /// mode-info units, mirroring [`Self::around_mi`]. fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] { let (w_mi, h_mi) = (w / MI, h / MI); // [`Self::around_mi`]'s single pass, with the two extents split. let mut out = [(false, false, 0i32); 3]; for cell in 0..w_mi { let above = &self.above[mi_c + cell]; for (plane, o) in out.iter_mut().enumerate() { o.0 |= above[plane].level != 0; o.2 += dc_vote(above[plane].dc); } } for cell in 0..h_mi { let left = &self.left[mi_r + cell]; for (plane, o) in out.iter_mut().enumerate() { o.1 |= left[plane].level != 0; o.2 += dc_vote(left[plane].dc); } } if crate::envflags::env_flag!("EC_DCDUMP") { for (plane, o) in out.iter().enumerate() { let vote = o.2; let ab: Vec = (0..w_mi) .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level)) .collect(); let lf: Vec = (0..h_mi) .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level)) .collect(); eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(",")); } } out } /// The luma `txb_skip_ctx` of a transform unit smaller than its own block /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx` /// is always 0, spec's `plane_bsize == tx_size` branch). fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize { self.luma_skip_ctx_rect(at_mi, side_mi, side_mi) } /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above /// context over `tx_size_wide` and the left one over `tx_size_high`. fn luma_skip_ctx_rect( &self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize, ) -> usize { let side_mi = w_mi; let mut top = 0u8; let mut left = 0u8; for cell in 0..w_mi { top |= self.above[mi_c + cell][0].level; } for cell in 0..h_mi { left |= self.left[mi_r + cell][0].level; } let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)]; if crate::envflags::env_flag!("EC_ECDUMP") { let ab: Vec = (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect(); let lf: Vec = (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect(); eprintln!( "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]", ab.join(","), lf.join(",") ); } if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}", self.left.iter().map(|e| e[0].level).collect::>() ); } ctx } /// Writes one coded block into every cell it covers, on both grids: the /// mode/side arrays up to `side`'s own width, and the coefficient-context /// arrays up to the true frame edge — the units past it are left at their /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`, /// not from this block's own side). fn record( &mut self, at: (usize, usize), side: usize, mode: usize, uv_mode: usize, grids: &[&[i32]; 3], ) { self.record_rect(at, side, side, mode, uv_mode, grids); } /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by /// [`Self::partition_ctx`]) are the neighbour's own width/height per the /// spec's per-edge partition-context rule, so a true rectangular block /// naturally wants two different values here rather than one. /// Writes this block's luma `mode` into the mi-granular /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi /// position a *later* neighbour would read it from: the block's LAST mi /// row for every column it spans (what the block below reads via /// `mi(row-1, col)`) and its LAST mi column for every row (what the /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves /// read these back, and only when the recorded position is exactly their /// own neighbour -- see [`Self::sub8_mode_col`]'s doc. fn record_mode_mi( &mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize, ) { let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16); let mode = mode as u8; for cell in 0..mi_w { if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) { *slot = (last_r, mode); } } for cell in 0..mi_h { if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) { *slot = (last_c, mode); } } } /// The mi-exact above/left neighbour luma mode for a block whose top-left /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact /// mi position (then the coarse [`SUB`]-grid slot is right by /// construction). See [`Self::record_mode_mi`]. fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option { match self.sub8_mode_col.get(mi_c) { Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => Some(usize::from(m)), _ => None, } } fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option { match self.sub8_mode_row.get(mi_r) { Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => Some(usize::from(m)), _ => None, } } /// [`Self::record_mode_mi`] for the block's `uv_mode`, into /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`]. fn record_uv_mode_mi( &mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, uv_mode: usize, ) { let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1); fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r as u16, uv_mode as u8)); fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c as u16, uv_mode as u8)); // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block // covers, so the chroma neighbour read below is a plain grid read. let stride = self.uv_grid_cols; let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c); for row in mi_r..=last_r { fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8); } } /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)` /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no /// block has recorded the exact neighbouring mi. fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool { // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA // REFERENCE block, not off the mi that carries the chroma syntax. // `set_mi_row_col` (`blockd.h`) takes // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and // only then `chroma_above_mbmi = base_mi[-stride]` / // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at // the ODD mi, so without the snap we looked one mi row/column too far // down/right -- the mi-exact slot never matched and the coarse // fallback answered instead. Measured on a 4K 10-bit key frame, chroma // 8x4 at (688, 100) = mi (51, 344): libaom's // `get_intra_edge_filter_type` is 1 (the chroma block above it is // `UV_SMOOTH_PRED`), ours was 0, which flips // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`: // false for type 1, TRUE for type 0) and upsampled an edge libaom // leaves alone -- +1 on rows 2/3 of that block and every chroma block // predicting from it (class `context-read-from-one-cell`). self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c) } /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e. /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness /// counter wants this: it measures how often the snap CHANGES the answer, /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every /// decode path uses the snapping form. fn smooth_uv_neighbour_unsnapped( &self, mi_r: usize, mi_c: usize, r: usize, c: usize, ) -> bool { // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid // array that `start_tile` does not clear, so a block on a tile's first // mi row used to read the uv_mode of the block above it in the tile // ABOVE and filter its chroma edge at that neighbour's strength // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block // at chroma (120, 32), the top-right tile's first block). let have_above = mi_r > self.tile_row0_mi; let have_left = mi_c > self.tile_col0_mi; if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED { hit!(UV_TILE_EDGE_SUPPRESSED_HITS); } // The mi grid is libaom's own read; the two maps below stay as the // fallback for cells no block has written (see [`Self::uv_mode_grid`]). let cell = |grid: &Vec, row: usize, col: usize| -> Option { (col < self.uv_grid_cols) .then(|| grid.get(row * self.uv_grid_cols + col).copied()) .flatten() .filter(|&m| m != u8::MAX) .map(usize::from) }; let above = match self.uv_mode_col.get(mi_c) { _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m, Some(&(row, m)) if have_above && usize::from(row) == mi_r - 1 => usize::from(m), _ if have_above => self.above_uv_mode[c], _ => DC_PRED, }; let left = match self.uv_mode_row.get(mi_r) { _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m, Some(&(col, m)) if have_left && usize::from(col) == mi_c - 1 => usize::from(m), _ if have_left => self.left_uv_mode[r], _ => DC_PRED, }; if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| { !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m) }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| { !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m) }) { hit!(UV_MODE_GRID_OVERRIDE_HITS); } // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would // have been filtered at the wrong strength by the coarse map alone. if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] { hit!(UV_MODE_MI_OVERRIDE_HITS); } if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above)) || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left)) { hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS); } is_smooth_mode(above) || is_smooth_mode(left) } /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them /// holding an OLDER, larger block's mode -- it only ever recorded into the /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip /// whose left neighbour was a 16x8 leaf still read the stale row and picked /// a different CDF for the same mode value). /// lane-rectsplitx r2: availability-correct above/left luma modes for a /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi` /// only when `up_available` and `left_mbmi` only when `left_available`; /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST /// strip's mode as its "left neighbour" (measured on the band fixture at /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row). fn modes_above_left_mi( &self, mi_r: usize, mi_c: usize, fallback: (usize, usize), ) -> (usize, usize) { let above = if mi_r > self.tile_row0_mi { self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0) } else { DC_PRED }; let left = if mi_c > self.tile_col0_mi { self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1) } else { DC_PRED }; (above, left) } /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability /// correct. The mi-exact lookups already refuse to cross a tile edge, but /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset /// per superblock row and never per tile, so the first block column of /// tile 2..N read the previous tile's mode as its left neighbour, and the /// above band survives across a tile ROW boundary the same way lane-mtfix's /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when /// `up_available`/`left_available` and uses DC_PRED otherwise /// ([`Self::modes_above_left_mi`]). fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) { let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); let (above, left) = self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r])); if above != self.above_mode[c] || left != self.left_mode[r] { hit!(MODE_MI_OVERRIDE_HITS); } if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above)) || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left)) { hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS); } // A neighbour the coarse band offered where the tile edge makes it // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`). if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED) || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED) { hit!(MODE_TILE_EDGE_COARSE_LEAKS); } (above, left) } fn record_rect( &mut self, at: (usize, usize), w: usize, h: usize, mode: usize, uv_mode: usize, grids: &[&[i32]; 3], ) { self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids); } /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed /// by the enclosing cell (a sub-16 extent writes none of them, exactly as /// the [`SUB`]-unit path does). fn record_rect_mi( &mut self, at_mi: (usize, usize), w: usize, h: usize, mode: usize, uv_mode: usize, grids: &[&[i32]; 3], ) { let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI)); // lane-inter4 r2: a strip whose own footprint runs past the frame's // last 16-px column/row stamps only the cells that exist (libaom's // arrays are padded past the frame and those cells are never read). for cell in 0..w / SUB { if c + cell >= self.above_mode.len() { break; } self.above_mode[c + cell] = mode; self.above_uv_mode[c + cell] = uv_mode; self.above_side[c + cell] = w; } for cell in 0..h / SUB { if r + cell >= self.left_mode.len() { break; } self.left_mode[r + cell] = mode; self.left_uv_mode[r + cell] = uv_mode; self.left_side[r + cell] = h; } self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode); self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode); self.record_mi_rect(at_mi, w, h, grids); } /// The coefficient-context half of [`Self::record`], taking the block's /// position directly in 4x4 mode-info units rather than [`SUB`]-grid /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name. fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) { self.record_mi_rect(at_mi, side, side, grids); } /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents, /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]). fn record_mi_rect( &mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3], ) { let (mi_r, mi_c) = at_mi; let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane])); let (w_mi, h_mi) = (w / MI, h / MI); if crate::envflags::env_flag!("EC_ECPUB") { eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level); } fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8); fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8); // A chroma 4x4 unit straddling the true luma edge is still whole in // chroma's own halved grid, so libaom rounds the luma bound up to the // plane's own 4x4 unit before clamping a subsampled plane // (`av1_write_intra_coeffs_mb`, encodetxb.c). let round_up_even = |n: usize| n.div_ceil(2) * 2; let bound_h = [ self.mi_rows, round_up_even(self.mi_rows), round_up_even(self.mi_rows), ]; let bound_w = [ self.mi_cols, round_up_even(self.mi_cols), round_up_even(self.mi_cols), ]; // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows // past the padded side arrays (mi_rows 198, block rows 192..208); // libaom's own arrays are superblock-sized, so those cells simply // have no reader -- [`fill_span`] drops them, as the `break` did. // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane // predicate is three contiguous runs: all planes, chroma only, none // (lane-mi). let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r)); let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r)); let uv_only = [Neighbour::default(), states[1], states[2]]; fill_span(&mut self.left, mi_r, luma_h, states); fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only); fill_span( &mut self.left, mi_r + chroma_h, h_mi - chroma_h, [Neighbour::default(); 3], ); let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c)); let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c)); let uv_only_w = [Neighbour::default(), states[1], states[2]]; fill_span(&mut self.above, mi_c, luma_w, states); fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w); fill_span( &mut self.above, mi_c + chroma_w, w_mi - chroma_w, [Neighbour::default(); 3], ); } /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit /// inside a coded block whose luma transform is smaller than its own /// side (`TxMode::Select`): the real per-transform-unit coefficient /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the /// coarse per-block `tx_grid`/`fill_lf_grid` state /// [`Self::record_split_luma`] still writes once for the whole block. /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone -- /// the caller's own [`Self::record_split_luma`] call sets those once, /// at the block's own true side, not this TU's. fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) { self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid); } /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose /// uv plane block is several units (lane-sb128b r2: a 128x128 block's /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`). /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma /// coefficient-context arrays are indexed by luma mi, the convention /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge /// clamp included. fn record_mi_chroma( &mut self, (mi_r, mi_c): (usize, usize), w_px: usize, h_px: usize, plane: usize, grid: &[i32], ) { let round_up_even = |n: usize| n.div_ceil(2) * 2; let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); let state = neighbour_state(grid); for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) { self.left[mi_r + cell][plane] = state; } for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) { self.above[mi_c + cell][plane] = state; } } /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx /// r1): the above context spans the unit's width, the left context its /// height, which for a square unit is the same loop it always was. fn record_mi_luma_rect( &mut self, (mi_r, mi_c): (usize, usize), w_px: usize, h_px: usize, grid: &[i32], ) { let state = neighbour_state(grid); if crate::envflags::env_flag!("EC_ECPUB") { eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level); } for cell in 0..h_px / MI { if mi_r + cell < self.mi_rows { self.left[mi_r + cell][0] = state; } } for cell in 0..w_px / MI { if mi_c + cell < self.mi_cols { self.above[mi_c + cell][0] = state; } } } /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a /// block whose luma was decoded as several transform units through /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single /// whole-block luma write -- everything [`Self::record`] does except /// plane 0, which is already correct per-TU by the time this runs. fn record_split_luma( &mut self, at: (usize, usize), side: usize, mode: usize, uv_mode: usize, chroma_grids: [&[i32]; 2], ) { self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids); } /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`) /// extents in pixels (lane-rectsplit r1), the same relationship /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose /// luma transform split into several square units needs exactly this /// bookkeeping, at its own true rectangular extents. fn record_split_luma_rect( &mut self, at: (usize, usize), w: usize, h: usize, mode: usize, uv_mode: usize, chroma_grids: [&[i32]; 2], ) { let (r, c) = at; self.record_split_luma_rect_mi( (r * (SUB / MI), c * (SUB / MI)), w, h, mode, uv_mode, chroma_grids, ); } /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the /// convention [`decode_block_rect4`] already established for 1:4 strips. fn record_split_luma_rect_mi( &mut self, at_mi: (usize, usize), w: usize, h: usize, mode: usize, uv_mode: usize, chroma_grids: [&[i32]; 2], ) { let (mi_r, mi_c) = at_mi; let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); for cell in 0..w.div_ceil(SUB) { if c + cell >= self.above_mode.len() { break; } self.above_mode[c + cell] = mode; self.above_uv_mode[c + cell] = uv_mode; self.above_side[c + cell] = w; } for cell in 0..h.div_ceil(SUB) { if r + cell >= self.left_mode.len() { break; } self.left_mode[r + cell] = mode; self.left_uv_mode[r + cell] = uv_mode; self.left_side[r + cell] = h; } let (w_mi, h_mi) = (w / MI, h / MI); self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode); self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode); fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8); fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8); let round_up_even = |n: usize| n.div_ceil(2) * 2; let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); for (plane_idx, grid) in chroma_grids.into_iter().enumerate() { let plane = plane_idx + 1; let state = neighbour_state(grid); for cell in 0..h_mi { if cell < h_mi.min(bound_h.saturating_sub(mi_r)) { self.left[mi_r + cell][plane] = state; } } for cell in 0..w_mi { if cell < w_mi.min(bound_w.saturating_sub(mi_c)) { self.above[mi_c + cell][plane] = state; } } } } } /// Reads one coded block's skip flag, luma mode, angle delta (if the mode /// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode` /// exactly — including its skip context, which the real key-frame writer /// always writes at a fixed context of zero (it never tracks a neighbour-based /// one for intra blocks; that is the inter-frame writer's rule instead). /// Refuses a nonzero angle delta: this decoder reconstructs the thirteen /// luma modes at their base angle only. Chroma is DC-only or, where CFL is /// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the /// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for /// plain DC chroma. /// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which /// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's /// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode /// instead (the defect commit 1a89ed9 fixed at the square sites). fn fi_tx_row(mode: usize, filter_intra: Option) -> usize { const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED]; filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi]) } /// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`, /// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32 /// bound (spec `filter_intra_mode_info` never reads a symbol there). fn filter_intra_size_class(side: usize) -> Option { match side { 4 => Some(0), 8 => Some(1), 16 => Some(2), 32 => Some(3), _ => None, } } /// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip /// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize /// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their /// own distinct `cdf::FILTER_INTRA` rows, classes 4/5. fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option { match (bw, bh) { (32, 16) => Some(4), (16, 32) => Some(5), // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= // 32", so a 16x8/8x16 strip reads the flag too -- returning `None` // here dropped that symbol on every DC_PRED strip of that size and // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder: // identical mode/uv_mode values, range 34808 vs the oracle's 40668). (16, 8) => Some(6), (8, 16) => Some(7), // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <= // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0. (4, 8) => Some(8), (8, 4) => Some(9), // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no // `use_filter_intra` symbol on those strips although aomenc writes // one for every DC_PRED block of that shape with // `--enable-filter-intra=1` (its default), silently desyncing the // tile (class symbol-consumption-gap). (32, 8) => Some(10), (8, 32) => Some(11), // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16 // strips), rows 17/16 of `default_filter_intra_cdfs`. (16, 4) => Some(12), (4, 16) => Some(13), _ if bw == bh => filter_intra_size_class(bw), _ => None, } } /// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <= /// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus /// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize] /// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past /// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise. pub(crate) fn palette_bsize_ctx(side: usize) -> Option { palette_bsize_ctx_wh(side, side) } /// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip /// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's /// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes /// for ANY bsize, not just the square ones a hand-picked table happened to /// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned /// row breaks the moment its indexing field moves off the diagonal, and a /// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1 /// block dimension is a power of two, so `bw*bh` always is too and /// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own /// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`). fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option { // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx` // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame. if bw > 64 || bh > 64 || bw * bh < 64 { return None; } Some(((bw * bh) as u32).trailing_zeros() as usize - 6) } /// A just-decoded palette-Y block's own size, base colours (only the first /// `size` entries are real), and per-pixel colour-index map (`side*side`, /// row-major, each entry `< size`). struct PaletteY { size: usize, colors: [u16; 8], map: Vec, } /// As [`PaletteY`], for a just-decoded chroma palette block: one shared /// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is /// shared between U and V, both co-located after 4:2:0 subsampling) plus /// each plane's own base colours. struct PaletteUv { size: usize, u_colors: [u16; 8], v_colors: [u16; 8], map: Vec, } /// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by /// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s /// `get_unsigned_bits`, which is the same formula): smallest `n` with /// `2^n >= x`, `0` for `x <= 1`. pub(crate) fn ceil_log2(x: u32) -> u32 { if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() } } /// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as /// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`. fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize { let l = ceil_log2(n as u32); let m = (1usize << l) - n; let v = dec.literal(l - 1) as usize; if v < m { v } else { (v << 1) - m + dec.literal(1) as usize } } /// `merge_colors` (decodemv.c:462): interleaves the ascending `cached` /// colours (already-known, from the above/left neighbours) with the /// ascending `transmitted` ones (delta-coded off the wire) back into one /// ascending list of `cached.len() + transmitted.len()` colours -- a tied /// value picks the cached copy first, matching the C `<=`. fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec { let mut out = Vec::with_capacity(transmitted.len() + cached.len()); let (mut ci, mut ti) = (0, 0); while ci < cached.len() && ti < transmitted.len() { if cached[ci] <= transmitted[ti] { out.push(cached[ci]); ci += 1; } else { out.push(transmitted[ti]); ti += 1; } } out.extend_from_slice(&cached[ci..]); out.extend_from_slice(&transmitted[ti..]); out } /// `read_palette_colors_y` (decodemv.c:478), at the sequence's real /// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour, /// each delta's width, the `range` bound and the clamp) is sized by /// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every /// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges /// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of /// the msac range, so a cross-decoder range ladder stays bit-identical /// through the whole miscount -- only the decoded VALUE differs (class /// `compare-range-not-tell`'s blind spot). (this /// decoder is 8-bit only): accepts up to `n` colours straight from `cache` /// (one flag bit each, in cache order), then delta-codes the remainder /// (first value raw, each following delta `>= 1` off a shrinking bit width), /// and merges the two ascending lists back together. fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] { let mut cached = Vec::with_capacity(n); for &c in cache { if cached.len() >= n { break; } if dec.literal(1) == 1 { cached.push(c); } } let bd = u32::from(bit_depth(fctx)); let max_val = (1i32 << bd) - 1; let mut colors = [0u16; 8]; let n_cached = cached.len(); if n_cached < n { let mut transmitted = Vec::with_capacity(n - n_cached); let first = dec.literal(bd) as u16; transmitted.push(first); if n_cached + 1 < n { let min_bits = bd - 3; let mut bits = min_bits + dec.literal(2); let mut range = (1i32 << bd) - i32::from(first) - 1; for _ in (n_cached + 1)..n { let delta = dec.literal(bits) as i32 + 1; let prev = *transmitted.last().unwrap(); let val = (i32::from(prev) + delta).clamp(0, max_val) as u16; range -= i32::from(val) - i32::from(prev); bits = bits.min(ceil_log2(range.max(0) as u32)); transmitted.push(val); } } let merged = merge_colors(&transmitted, &cached); colors[..n].copy_from_slice(&merged); } else { colors[..n].copy_from_slice(&cached[..n]); } colors } /// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real /// `bit_depth` (see [`read_palette_colors_y`]): U reads /// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only /// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta` /// unbiased by `+1` -- both differences from Y's own reader, matching the C /// side by side). V never uses a cache: a leading bit picks either `n` raw /// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256 /// rather than clamp. fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) { let mut cached = Vec::with_capacity(n); for &c in cache { if cached.len() >= n { break; } if dec.literal(1) == 1 { cached.push(c); } } let bd = u32::from(bit_depth(fctx)); let max_val = 1i32 << bd; let mut u_colors = [0u16; 8]; let n_cached = cached.len(); if n_cached < n { let mut transmitted = Vec::with_capacity(n - n_cached); let first = dec.literal(bd) as u16; transmitted.push(first); if n_cached + 1 < n { let min_bits = bd - 3; let mut bits = min_bits + dec.literal(2); let mut range = max_val - i32::from(first); for _ in (n_cached + 1)..n { let delta = dec.literal(bits) as i32; let prev = *transmitted.last().unwrap(); let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16; range -= i32::from(val) - i32::from(prev); bits = bits.min(ceil_log2(range.max(0) as u32)); transmitted.push(val); } } let merged = merge_colors(&transmitted, &cached); u_colors[..n].copy_from_slice(&merged); } else { u_colors[..n].copy_from_slice(&cached[..n]); } let mut v_colors = [0u16; 8]; if dec.literal(1) == 1 { let min_bits_v = bd - 4; let bits = min_bits_v + dec.literal(2); v_colors[0] = dec.literal(bd) as u16; for i in 1..n { let mut delta = dec.literal(bits) as i32; if delta != 0 && dec.literal(1) == 1 { delta = -delta; } let mut val = i32::from(v_colors[i - 1]) + delta; if val < 0 { val += max_val; } if val >= max_val { val -= max_val; } v_colors[i] = val as u16; } } else { for i in 0..n { v_colors[i] = dec.literal(bd) as u16; } } (u_colors, v_colors) } /// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a /// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real /// `0..=4` context, `-1` for hashes no real neighbour configuration produces. const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1]; /// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index /// map's own per-pixel context and colour-order permutation, from the /// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3 /// selection sort). `map`'s stride is `side` (this decoder never crops a /// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s /// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the /// actual colour index to store. pub(crate) fn palette_color_index_context( map: &[u8], side: usize, row: usize, col: usize, n: usize, ) -> (usize, [u8; 8]) { let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None }; let up_left = if col >= 1 && row >= 1 { Some(map[(row - 1) * side + col - 1]) } else { None }; let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None }; let mut scores = [0i32; 8]; for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] { if let Some(v) = neighbour { scores[v as usize] += weight; } } let mut color_order = [0u8; 8]; for i in 0..8 { color_order[i] = i as u8; } for i in 0..3 { let mut max = scores[i]; let mut max_idx = i; for j in (i + 1)..n { if scores[j] > max { max = scores[j]; max_idx = j; } } if max_idx != i { let max_score = scores[max_idx]; let max_color = color_order[max_idx]; for k in (i + 1..=max_idx).rev() { scores[k] = scores[k - 1]; color_order[k] = color_order[k - 1]; } scores[i] = max_score; color_order[i] = max_color; } } let hash = scores[0] + scores[1] * 2 + scores[2] * 2; let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize]; (ctx as usize, color_order) } /// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index /// map's wavefront decode over a `side x side` grid -- this decoder's /// palette blocks are always square and never straddle the frame's true /// (possibly odd) edge without already allocating the full `side*side` /// region (every other skip/residual path here does the same), so no /// rows/cols-vs-plane_width/height cropping special case is needed, unlike /// libaom's own non-block-aligned split. fn decode_color_index_map( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: usize, side: usize, uv: bool, ) -> Vec { decode_color_index_map_wh(dec, cdfs, n, side, side, uv) } /// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip /// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal /// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh` /// independently rather than one shared `side` -- the square call above is /// just `bw == bh`. fn decode_color_index_map_wh( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: usize, bw: usize, bh: usize, uv: bool, ) -> Vec { let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); let mut map = vec![0u8; bw * bh]; if trace { let (rng, _) = dec.debug_state(); eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}"); } map[0] = read_uniform(dec, n) as u8; if trace { let (rng, _) = dec.debug_state(); eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]); } for i in 1..(bw + bh - 1) { let j_hi = i.min(bw - 1); let j_lo = i.saturating_sub(bh - 1); for j in (j_lo..=j_hi).rev() { let row = i - j; let col = j; let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n); if trace { let (rng, _) = dec.debug_state(); let row_cdf = if uv { &cdfs.palette_uv_color_index[n - 2][ctx] } else { &cdfs.palette_y_color_index[n - 2][ctx] }; eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]); } let symbol = if uv { dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n]) } else { dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n]) }; map[row * bw + col] = color_order[symbol]; if trace { let (rng, _) = dec.debug_state(); eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}"); } } } map } /// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1, /// palette wired lane-palette2 r4): identical except the `use_filter_intra` /// size class comes from [`filter_intra_size_class_rect`] instead of the /// square-only [`filter_intra_size_class`], and the palette read (when /// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/ /// [`decode_color_index_map_wh`] instead of their square-only counterparts -- /// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`, /// `cfl_alphas`) is indexed by mode or neighbour state, never by block size. #[allow(clippy::too_many_arguments)] fn read_intra_mode_rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_mode: usize, left_mode: usize, cfl: bool, // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's // chroma is coded once, on the closing strip). Every other caller is a // block big enough to own its chroma and passes `true`. has_chroma: bool, bw: usize, bh: usize, enable_filter_intra: bool, skip_ctx: usize, allow_screen_content_tools: bool, // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params: // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y // block here, `None` still reads (and refuses on use) the symbol at ctx 0. palette: Option<(usize, &[u16])>, palette_uv_cache: &[u16], mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx, ) -> Result<( bool, usize, i32, usize, i32, Option<(i32, i32)>, Option, Option, Option, )> { let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); if ec_istep { // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line // (decodemv.c:818), printed at the same point: before the first // mode-info symbol of the block, so a cross-decoder range ladder can // be keyed on the BLOCK, not just on the symbol sequence. eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}", enable_filter_intra as i32, filter_intra_size_class_rect(bw, bh), dec.debug_state().0); } macro_rules! istep { ($name:literal, $val:expr) => { if ec_istep { let (rng, _) = dec.debug_state(); eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}", $name, $val ); } }; } // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at // the one point every rect caller routes through, so no call site can // offer the 14-symbol CFL alphabet on a 64-axis block (class // wrong-alphabet-same-value: same value, wrong interval, silent desync). let cfl = if cfl && bw.max(bh) > 32 { hit!(NOCFL_UV_MODE_HITS); false } else { cfl }; // lane-intra14 r1: on the INTER block path everything up to and including // `is_inter` was already read by [`decode_inter_block`], so this reader // starts at the mode syntax with the `skip` that caller read. let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get); let skip = if let Some((_, skip)) = inter { skip } else { // Same `intra_segment_id` placement as the square reader above. let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4); if seg_id_pre_skip(fctx) { intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx); } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; istep!("skip", skip as i32); if !seg_id_pre_skip(fctx) { intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx); } maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx); istep!("cdef", 0); // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never // both 64 here -- see this fn's own doc), so `is_whole_sb` is always // `false`. maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx); maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx); istep!("dq", 0); // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc` // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so // rect strips read it exactly like square leaves ([`read_intra_mode`], // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic // decoder at the FIRST symbol of the first rect block of every // `--tune-content=screen` key frame. Reconstruction of a real intrabc // block at this shape is out of scope, so the flag is consumed and // refused by name when it fires. if allow_intrabc_frame(fctx) { let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; hit!(RECT_INTRABC_READS); istep!("intrabc", use_intrabc as i32); if use_intrabc { hit!(INTRABC_HITS); return Err(unsupported( "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)", )); } } skip }; // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode` // off `kf_y_mode_cdf[above][left]`). let mode = if let Some((size_group, _)) = inter { dec.symbol(&mut cdfs.y_mode[size_group]) } else { let above_ctx = INTRA_MODE_CTX[above_mode]; let left_ctx = INTRA_MODE_CTX[left_mode]; dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]) }; istep!("mode", mode as i32); let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) } else { 0 }; istep!("angle_y", angle_delta_y); // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)` // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 && // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet // here, from the block's own size, is the single point every caller routes // through -- a caller passing `true` for a >32 strip used to pick the // 14-symbol CFL CDF, same value but a different range (class // wrong-alphabet-same-value). let cfl = cfl && bw <= 32 && bh <= 32; let uv_mode = if !has_chroma { DC_PRED } else if cfl { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; istep!("uv_mode", uv_mode as i32); let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; if has_chroma && (9..=12).contains(&uv_mode) { hit!(SMOOTH_UV_HITS); } let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) { hit!(DIRECTIONAL_UV_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; istep!("angle_uv", angle_delta_uv); if angle_delta_uv != 0 { hit!(UV_ANGLE_DELTA_HITS); } // `read_palette_mode_info` (spec 5.11.13), rect-generalised // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`], // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/ // colours only here, the colour-index maps deferred past `filter_intra` // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette` // runs from the caller, after the whole mode-info read). let mut palette_y_pending: Option<(usize, [u16; 8])> = None; let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) { // r6: this is the exact site the removed blanket refusal used to // guard -- reached for EVERY rect strip in a screen-content frame, // independent of whether the block ends up using a palette. hit!(RECT_SCREEN_CONTENT_HITS); let (mode_ctx, cache) = palette.unwrap_or((0, &[])); let use_palette_y = mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0; if use_palette_y { let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); let colors = read_palette_colors_y(dec, n, cache, fctx); palette_y_pending = Some((n, colors)); } let palette_uv_mode_ctx = usize::from(use_palette_y); // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard. if has_chroma && uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx); palette_uv_pending = Some((n, u_colors, v_colors)); } } let mut filter_intra = None; if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!( "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \ class={:?} rng={rng}", enable_filter_intra as i32, filter_intra_size_class_rect(bw, bh) ); } // As the square path: `av1_filter_intra_allowed` excludes a palette-Y // block (reconintra.h:77), so no `use_filter_intra` symbol exists there. if mode == DC_PRED && enable_filter_intra && palette_y_pending.is_none() && let Some(class) = filter_intra_size_class_rect(bw, bh) { let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0; if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32); } istep!("use_filter_intra", use_filter_intra as i32); if use_filter_intra { hit!(FILTER_INTRA_HITS); let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); istep!("filter_intra_mode", fi_mode as i32); filter_intra = Some(fi_mode); } } // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map), // same order as [`read_intra_mode`]'s own square path. let palette_y = palette_y_pending.map(|(n, colors)| { let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false); hit!(PALETTE_HITS); hit!(PALETTE_RECT_HITS); PaletteY { size: n, colors, map } }); let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to // BLOCK_4X8, both floored at the 4-px transform. Halving the short // axis to 2 read HALF the colour-index symbols of a 1:4 strip's // chroma palette and desynced the tile from there. let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4)); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true); hit!(PALETTE_UV_HITS); PaletteUv { size: n, u_colors, v_colors, map } }); Ok(( skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, )) } /// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays, /// at the strip's REAL mi position. `av1_get_palette_cache` reads /// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the /// block, so each strip owns its own rows and columns and no aliasing rule /// is needed (lane-kf900 r6). #[allow(clippy::too_many_arguments)] fn record_strip_palette( n: &mut Neighbours, mi: (usize, usize), bw: usize, bh: usize, y_size: usize, y_colors: [u16; 8], uv_size: usize, uv_colors: [u16; 8], ) { let (r, c) = mi; // lane-t900 r23 rung: every publication of a block's palette state into // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode // path left a stale `left_palette_size` behind when // `av1_get_palette_mode_ctx` disagrees with libaom's. if crate::envflags::env_flag!("EC_PALPUB") { eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}"); } // lane-kf900 r6: the palette side bands are mi-granular now, so a strip // writes its OWN span on BOTH axes -- the old `last` split-axis rule only // existed because the 16px [`SUB`] cell held one slot for all the strips // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the // real neighbour leaf 1 reads. { for cell in 0..(bw / MI).max(1) { if let Some(e) = n.above_palette_size.get_mut(c + cell) { *e = y_size as u8; n.above_palette_uv_size[c + cell] = uv_size as u8; // lane-publish2, see [`Neighbours::record_palette_y_rect`]: // colours of a size-0 neighbour are never read. if y_size > 0 { n.above_palette_colors[c + cell] = y_colors; } if uv_size > 0 { n.above_palette_uv_colors[c + cell] = uv_colors; } } } } { for cell in 0..(bh / MI).max(1) { if n.left_palette_size.get(r + cell).is_none() { break; } n.left_palette_size[r + cell] = y_size as u8; n.left_palette_uv_size[r + cell] = uv_size as u8; if y_size > 0 { n.left_palette_colors[r + cell] = y_colors; } if uv_size > 0 { n.left_palette_uv_colors[r + cell] = uv_colors; } } } } /// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1): /// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour /// above against this block's own *width* and the neighbour to the left /// against its own *height* -- for a square block those are the same value, /// which is why the square-only version can get away with one `own_side`. fn tx_size_context_rect( n: &Neighbours, (mi_r, mi_c): (usize, usize), own_w: usize, own_h: usize, ) -> usize { // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`, // not the block's own side: no transform is wider or taller than 64, so a // block with a 128 side resolves against 64 (the square path already caps // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root // VERT reads the tx-depth symbol off row 0 where libaom uses row 1. let (own_w, own_h) = (own_w.min(64), own_h.min(64)); let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w; let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h; if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}", if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 }, if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 }, usize::from(above) + usize::from(left) ); } usize::from(above) + usize::from(left) } /// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1). fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec { let (cw, ch) = (bw / 2, bh / 2); let mut ac = vec![0i32; cw * ch]; let mut sum = 0i32; for cy in 0..ch { for cx in 0..cw { let (lx, ly) = (px + cx * 2, py + cy * 2); let q3 = (i32::from(y.data[ly * y.width + lx]) + i32::from(y.data[ly * y.width + lx + 1]) + i32::from(y.data[(ly + 1) * y.width + lx]) + i32::from(y.data[(ly + 1) * y.width + lx + 1])) << 1; ac[cy * cw + cx] = q3; sum += q3; } } let num_pel = (cw * ch) as i32; let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros(); ac.iter_mut().for_each(|v| *v -= avg); ac } /// Everything a rect strip already read out of the stream before its luma /// transform units are decoded -- [`decode_rect_split`]'s own mode bundle /// (nine values that would otherwise be nine more parameters). struct RectStripModes { skip: bool, mode: usize, angle_delta_y: i32, uv_predict_mode: usize, angle_delta_uv: i32, alpha: Option<(i32, i32)>, filter_intra: Option, smooth_neighbor: bool, smooth_neighbor_uv: bool, /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already /// mapped through the colour table), sliced per transform unit below -- /// palette prediction reads no edge pixels, so a unit's slice of the /// whole-block map IS its prediction. Without this a palette strip whose /// transform splits predicted DC and came out flat grey while the entropy /// stream stayed in sync (the coefficients are read either way). palette_y: Option>, /// As `palette_y`, for the un-split chroma transform (U, V). palette_uv: Option<(Vec, Vec)>, } /// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth` /// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times /// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the /// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's /// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 -> /// TX_32X16`) and only the second reaches a square -- the reason /// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is /// already square) mis-tiled 1:4 strips. fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) { let (mut w, mut h) = (bw.min(64), bh.min(64)); for _ in 0..depth { match w.cmp(&h) { std::cmp::Ordering::Greater => w /= 2, std::cmp::Ordering::Less => h /= 2, std::cmp::Ordering::Equal => { w /= 2; h /= 2; } } } (w, h) } /// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma /// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every /// rect path here refused by name until now ("per-unit rect prediction is not /// ported"). /// /// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth` /// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1 /// strip the very first step already lands on a SQUARE transform /// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and /// every further step halves a square) -- so each unit is square and reads /// through the ordinary square [`read_plane`]. What is genuinely rectangular /// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as /// [`decode_block`]'s square split loop assumes) and the chroma plane, whose /// own transform is `av1_get_max_uv_txsize` of the whole strip and is never /// split by luma's depth. /// /// Each unit predicts off whatever the earlier units of this same block /// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block` /// inside `av1_foreach_transformed_block`, raster order), which is exactly /// what predicting the whole strip in one shot got wrong. #[allow(clippy::too_many_arguments)] fn decode_rect_split( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, at_mi: (usize, usize), bw: usize, bh: usize, // The transform unit's own width and height in pixels. Square for every // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`, // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`]. tx_w: usize, tx_h: usize, m: &RectStripModes, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let (mi_r, mi_c) = at_mi; let (px, py) = (mi_c * MI, mi_r * MI); let (cpx, cpy) = (px / 2, py / 2); let (chroma_w, chroma_h) = (bw / 2, bh / 2); // The chroma transform is picked before any symbol is read, so an // unsupported chroma shape refuses before this strip desyncs the tile. let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) { (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])), (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])), (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])), (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])), // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx` // squares a rect transform down to a CDF set by // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set, // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`) // paths already prove for these same shapes. (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])), (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])), (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])), (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])), (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])), (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])), _ => None, }; if !m.skip { if let Some(i) = match (chroma_w, chroma_h) { (32, 8) => Some(0), (8, 32) => Some(1), (8, 4) => Some(2), (4, 8) => Some(3), _ => None, } { hit_do! { RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| { let mut hits = c.get(); hits[i] += 1; c.set(hits); }); } } if chroma.is_none() { // Diagnostic for the next caller that lands here (class // refusal-names-a-correlate: the message names the tool, not the // shape); the refusal below keeps its inventory-pinned wording. eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}"); } } // lane-rectsplit r2 (verifier finding): with both callers wired // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s // 64x32/32x64) every shape that reaches here has a table above, so this // arm is UNREACHABLE today. It stays as the shape guard for the next // caller -- a new strip size would otherwise hit the `expect` below and // panic instead of refusing by name -- and so stays in // `refusal_inventory::REFUSALS`. if !m.skip && chroma.is_none() { return Err(unsupported( "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", )); } hit!(RECT_SPLIT_TX_HITS); if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 { hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS); } // LUMA: `bw/tx` x `bh/tx` square transform units, raster order. // A square unit reads through the ordinary square [`read_plane`]; a rect // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with // the very tables the unsplit 16x8/32x16 paths use. let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) { (w, h) if w == h => None, (16, 8) | (8, 16) => Some(( if reduced_tx_set { TxbSet::LumaRect16x8 } else { TxbSet::LumaRect16x8Set1 }, if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] }, )), (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])), (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])), // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level // strip, read through the `luma_64corner` arm below instead of a rect // table -- a 64-length axis codes only its low 32 coefficients // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own // depth-0 arm already reads on the key-frame path. // // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the // sub-8x8 intra leaves still refused: with those lifted (r2) the // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode // all 33 frames pixel-exact against ffmpeg while this arm fires 90x // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu` // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`. // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact. (64, 32) | (32, 64) => None, _ => { return Err(unsupported(format!( "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \ coefficient tables for that shape here)" ))) } }; // The `None` above that is NOT the square arm. let luma_64corner = tx_w != tx_h; // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole // frame exactly, two sub-16 split strips in it), but the RECT-unit arm -- // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the // per-unit rect walk stay wired above/below; the round that finds that // defect deletes this refusal and nothing else. let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set); let luma_scan = default_scan(tx_w.min(tx_h)); let zero_tu = vec![0i32; tx_w * tx_h]; // The strip's OWN edge availability, the fallback for a transform unit // whose top-right/bottom-left pixels fall outside the strip. let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); for tu_row in 0..bh / tx_h { for tu_col in 0..bw / tx_w { let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI)); let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h); let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h); // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged): // libaom clips `av1_foreach_transformed_block_in_plane` to // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`, // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose // TOP-LEFT sample falls outside the frame is never coded. We read // coefficients for those phantom units and desynced the stream at // the very next symbol. if tu_px >= y.true_width || tu_py >= y.true_height { continue; } // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a // transform unit INSIDE a block, which is a different rule from // the standalone-block table [`Reach::of`] applies -- and the // reason a depth-2 superblock strip came out one sample off // before this: `Reach::of(tx, ..)` answered as if the unit were // its own block at that superblock position. // * top-right: if the unit's right neighbour is still inside the // strip the pixels are already reconstructed (`col_off + // tx_wide < plane_bw`); otherwise only the strip's own top row // of units can reach past it, through the block-level answer. // * bottom-left: a unit that is not in the strip's left column // has none (`col_off > 0` returns 0); inside the strip // (`row_off + tx_high < plane_bh`) they are the left // neighbour's, already reconstructed; the last row falls back // to the block-level answer. let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach); // The unit's own window on the block's palette prediction. if let Some(buf) = &m.palette_y { let tu_buf: Vec = (0..tx_h) .flat_map(|i| { let base = (row_off + i) * bw + col_off; buf[base..base + tx_w].iter().copied() }) .collect(); set_palette_pred(tu_buf, fctx); } if m.skip { push_intra_rect(0, tu_px, tu_py, tx_w, tx_h, m.mode, m.angle_delta_y, tu_reach, &zero_tu, None, m.filter_intra, m.smooth_neighbor, fctx, ); neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu); } else if luma_64corner && luma_rect.is_none() { // The un-split 64-level luma transform: `read_coeffs` on the // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)` // and the real rect shape passed through for // `av1_nz_map_ctx_offset` -- byte for byte // [`decode_block_rect64`]'s depth-0 read, which the key-frame // 64-level strip gate already proves. `tx_type` is not coded // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once // the square-up size is TX_64X64), and this unit covers its // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat. if crate::envflags::env_flag!("EC_RECT64TU") { eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode); } hit_do! { RECT64_CORNER_TU_HITS.with(|c| { let mut v = c.get(); v[usize::from(tx_h > tx_w)] += 1; c.set(v); }); } let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra)); let (corner, tu_tx_type) = read_coeffs( dec, &mut coding, default_scan(TX32), 0, dc_sign_ctx(tu_around.2), TxType::DctDct, Some((tx_w, tx_h)), )?; let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32)); let mut tu_grid = vec![0i32; tx_w * tx_h]; for row in 0..ch { tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]); } let residual = dequant_and_inverse_typed_wh( &tu_grid, tx_w, tx_h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tu_tx_type, ); push_intra_rect(0, tu_px, tu_py, tx_w, tx_h, m.mode, m.angle_delta_y, tu_reach, &residual, None, m.filter_intra, m.smooth_neighbor, fctx, ); neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); } else if let Some((rect_set, rect_scan)) = luma_rect { // The rect-unit twin of the square arm below: same contexts, // same order, through the rect coefficient reader. The // `tx_type` CDF row of a filter-intra block is // `fimode_to_intradir[filter_intra_mode]`, never the block's // own (always DC_PRED) mode -- [`read_plane`] applies that // for the square arm, so this one must too. let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; // libaom `get_txb_ctx`: a LUMA transform that covers its whole // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the // neighbour-magnitude table is for a unit SMALLER than its // block. [`decode_block_rect`]'s own unsplit read passes a // literal 0 for the same reason; this arm applied the table // unconditionally and desynced every depth-0 rect strip that // reached it (lane-intrarect r2: ctx 5 where aomdec read 0). let tu_skip_ctx = if tx_w == bw && tx_h == bh { 0 } else { neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI) }; let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra)); let (tu_grid, tu_tx_type) = read_coeffs_rect( dec, &mut coding, rect_scan, tx_w, tx_h, tu_skip_ctx, dc_sign_ctx(tu_around.2), TxType::DctDct, )?; let residual = dequant_and_inverse_typed_wh( &tu_grid, tx_w, tx_h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tu_tx_type, ); push_intra_rect(0, tu_px, tu_py, tx_w, tx_h, m.mode, m.angle_delta_y, tu_reach, &residual, None, m.filter_intra, m.smooth_neighbor, fctx, ); neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); } else { let tu_around = neighbours.around_mi(tu_mi, tx_w)[0]; // This unit is smaller than the block it sits in, so // `txb_skip_ctx` is the neighbour-magnitude table, not the // lone-TU 0 (spec `get_txb_ctx_general`). let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI); let tu_grid = read_plane( dec, cdfs, luma_set, &luma_scan, 0, tu_around, m.mode, m.mode, m.angle_delta_y, tu_reach, y, tu_px, tu_py, tx_w, tx_w, base_q_idx, None, m.filter_intra, Some(tu_skip_ctx), m.smooth_neighbor, fctx, )?; neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid); } } } // CHROMA: one un-split rect transform for the whole strip. let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh)); let reach = block_reach; let (u_grid, v_grid) = if m.skip { let zero = Grid::Zero(chroma_w * chroma_h); if let Some((ub, _)) = &m.palette_uv { set_palette_pred(ub.clone(), fctx); } push_intra_rect(1, cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &m.palette_uv { set_palette_pred(vb.clone(), fctx); } push_intra_rect(2, cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx, ); (zero.clone(), zero) } else { let (chroma_set, chroma_scan) = chroma.expect("refused above when None"); // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra, // so only the 16x8/8x16 pair takes the mode-indexed default. let default_tx = if chroma_w.max(chroma_h) >= 32 { TxType::DctDct } else { default_intra_tx_type(m.uv_predict_mode as u8) }; let around = neighbours.around_mi_rect(at_mi, bw, bh); let mut grids: Vec = Vec::with_capacity(2); for plane_idx in 1..=2 { let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1); let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, chroma_scan, chroma_w, chroma_h, skip_ctx, dc_sign_ctx(around[plane_idx].2), default_tx, )?; // The same delta_q proof the unsplit rect64 path records // (lane-rectsplit r4: lifting the split-transform refusal moved // superblock strips onto this path, so only counting there would // leave the delta_q gate's counter silent for them). if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) { hit!(RECT64_QIDX_DRIFT_HITS); } let residual = dequant_and_inverse_typed_wh( &levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), fctx.current_q_idx.with(|c| c.get()), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, ); let cfl = m .alpha .zip(ac) .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)); let _plane = if plane_idx == 1 { &mut *u } else { &mut *v }; if let Some((ub, vb)) = &m.palette_uv { let buf = if plane_idx == 1 { ub } else { vb }; set_palette_pred(buf.clone(), fctx); } push_intra_rect(plane_idx, cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &residual, cfl, None, m.smooth_neighbor_uv, fctx, ); grids.push(levels); } let mut it = grids.into_iter(); (it.next().unwrap(), it.next().unwrap()) }; neighbours.record_split_luma_rect_mi( at_mi, bw, bh, m.mode, m.uv_predict_mode, [&u_grid, &v_grid], ); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx); if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!( "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \ tx={tx_w}x{tx_h} rng={rng}" ); } Ok(()) } /// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect /// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name /// because it predicts squares only. Every pixel here goes through the rect /// machinery the key-frame paths already prove: [`decode_rect_split`], which /// at `depth == 0` is the unsplit strip as a single transform unit and /// beyond it the per-unit walk of [`depth_to_tx_wh`]. /// /// What is genuinely different from [`decode_block_rect`] is the mode /// syntax: on an inter frame an intra block reads `y_mode[size_group]` and /// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never /// the key frame's `kf_y_mode` above/left pair. This mirrors the square /// intra-in-inter arm's own reads at the rect footprint, including its /// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe /// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the /// square and this arm) and a nonzero luma angle delta refused by name. /// /// The strip's own neighbour records (luma per transform unit, chroma, skip /// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the /// inter-side bands and the mi map. #[allow(clippy::too_many_arguments)] /// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded /// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for /// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the /// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own /// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1 /// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 -> /// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but /// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a /// table here rather than a shift of `bw.min(bh)`. fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> { Some(match (bw.min(bh), bw.max(bh)) { (8, 16) => (1usize, 1usize), (16, 32) => (2, 2), (32, 64) => (3, 3), (8, 32) => (1, 2), (16, 64) => (2, 3), _ => return None, }) } /// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter /// block path"): the shapes that can reach that arm, enumerated against the /// MEASURED domain of the inter block path /// ([`INTER_BLOCK_SHAPES`], the census the gate /// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable` /// fills from three real streams). /// /// [`decode_intra_rect_in_inter`] is called from one site, under /// `write_w != side || write_h != side`, and only after two earlier arms have /// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16 /// strip WITH a chroma-pair record (the `strip16` branch) or refused by name, /// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is /// left is every rectangular census shape with `8 <= min` and `max <= 64` -- /// and each of those has a row, so the refusal names a shape no measured /// stream can present. #[test] fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() { let mut checked = 0; for &(side, w, h) in &INTER_BLOCK_SHAPES { if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 { continue; } assert!( intra_in_inter_size_row(w, h).is_some(), "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \ the \"no size-group/tx-category row\" refusal" ); checked += 1; } assert_eq!( checked, 10, "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \ lookup, not the 10 this claim was measured over" ); } /// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's /// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which /// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are /// matched before the square arm's `log2` shortcut). /// /// `None` is the refusal "a motion_mode symbol for a block shape with no CDF /// row here"; the enumeration below is what proves no conformant block can /// reach it. pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option { Some(match (write_w, write_h) { // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm // below maps 128 to row 4 (BLOCK_16X32). (64, 128) => 14, (128, 64) => 15, (128, 128) => 16, (w, h) if w == h => (w.trailing_zeros() - 3) as usize, (16, 32) => 4, (32, 16) => 5, (32, 64) => 6, (64, 32) => 7, (8, 32) => 8, (32, 8) => 9, (16, 64) => 10, (64, 16) => 11, // lane-inter4 r3: the 16x16-level rect inter leaves. (8, 16) => 12, (16, 8) => 13, _ => return None, }) } /// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six /// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`, /// `block_size_wide`/`block_size_high`). #[cfg(test)] const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [ (4, 4), (4, 8), (8, 4), (8, 8), (8, 16), (16, 8), (16, 16), (16, 32), (32, 16), (32, 32), (32, 64), (64, 32), (64, 64), (64, 128), (128, 64), (128, 128), (4, 16), (16, 4), (8, 32), (32, 8), (16, 64), (64, 16), ]; /// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block /// shape with no CDF row here" names a shape no conformant stream can present. /// /// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`, /// whose `write_w.min(write_h) >= 8` clause is libaom's /// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable /// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL` /// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those /// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The /// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility /// clause rejects before the lookup. #[test] fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() { let mut rows = std::collections::BTreeSet::new(); let mut excluded = 0; for (w, h) in BLOCK_SIZES_ALL_WH { if w.min(h) < 8 { excluded += 1; assert!( w == 4 || h == 4, "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects" ); continue; } let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| { panic!( "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \ symbol, but has no CDF row -- the refusal is a real gap, not a dead arm" ) }); assert!( row < 17, "{w}x{h} maps to motion_mode row {row}, outside the 17-row table" ); assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}"); } assert_eq!(excluded, 5, "the sub-8 footprint set changed"); assert_eq!( rows.len(), 17, "17 eligible footprints must fill all 17 rows of the motion_mode table" ); } fn decode_intra_rect_in_inter( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, at: (usize, usize), bw: usize, bh: usize, skip: bool, allow_screen_content_tools: bool, // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4). strip16: Option<(bool, bool)>, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, fctx: &crate::decode::FrameCtx, ) -> Result<()> { // `at` is in MI units (the inter path's own unit since lane-inter4); // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands // below are still keyed by. let (mi_r, mi_c) = at; let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat` // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 / // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx // finding -- the category is NOT the same for every strip size). // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so // it is refused by name rather than read from the wrong CDF row. // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup` // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its // tx-depth category is 1 -- but nothing here has to know either, because // the strip decodes through the very body the KEY FRAME path proves for // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all, // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only // inter-frame difference is the mode-info read, which // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s // `y_mode[0]` plus the `skip` this caller already read. if let Some((horz, has_chroma)) = strip16 { // lane-t900 r22: the screen-content refusal here was STALE (class // stale-premise): [`decode_rect4_16_strip`] takes // `allow_screen_content_tools` and reads the whole palette syntax // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi` // pair) -- the key frame proves that body. Lifted with the 10-bit // witness `palette_screen_witness_10bit.obu`, whose inter frames carry // 16x4/4x16 intra strips inside a `--tune-content=screen` frame. debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) }); fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip)))); let res = decode_rect4_16_strip( dec, cdfs, neighbours, (mi_r, mi_c), horz, has_chroma, // The inter strips of the same partition publish their own // mi-exact mode, so the key-frame caller's coarse-cell stand-in // has nothing to add here. None, y, u, v, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), allow_screen_content_tools, base_q_idx, fctx.tx_select_inter.with(std::cell::Cell::get), fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, ); fctx.intra_in_inter_mode.with(|c| c.set(None)); let (mode, uv, (tx_w, tx_h)) = res?; // lane-intra16x4, the same publication the 2:1 intra-in-inter strip // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY // block of an inter frame, intra ones included, and // `txfm_partition_update` for the var-tx context. The key-frame body // writes neither (a key frame has no var-tx tree and its own readers // use the deblock grid), so the block AFTER this strip read a stale // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4 // strips at mi(23,16)/(23,20) exactly and then broke on the very next // 16x16 row. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); for i in 0..bw / MI { if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) { *cell = tx_w as u8; } } for i in 0..bh / MI { if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) { *cell = tx_h as u8; } } // [`decode_rect4_16`]'s own post-loop publication, per strip (the // coarse 16-px cell holds one entry for the whole 16x16 and the last // block to write it wins). neighbours.above_mode[c] = mode; neighbours.left_mode[r] = mode; if let Some(uvm) = uv { neighbours.above_uv_mode[c] = uvm; neighbours.left_uv_mode[r] = uvm; } neighbours.above_side[c] = bw; neighbours.left_side[r] = bh; if crate::envflags::env_flag!("EC_INTRA16X4") { eprintln!( "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}", mi_c * MI, mi_r * MI ); } hit_do! { INTRA16X4_IN_INTER_HITS.with(|h| { let mut v = h.get(); v[usize::from(!horz)] += 1; v[2] += usize::from(has_chroma); h.set(v); }); } return Ok(()); } // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61) // puts BLOCK_128X64/64X128/128X128 in group 3 and // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole // block decodes through the very body the KEY FRAME path proves for this // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk // `Reach` rule and the frame-edge write clip). The only inter-frame // differences live inside that body: the mode-info read // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and // palette (>64) do not exist at this size and are refused by name there. // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness. // `intra128_in_inter_witness2.obu` (gate // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`) // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of // all 15 frames, so the hits are counted out of exact frames (class // `counter-from-refused-stream`). What r16/r17 could not find, and what // that recipe exploits: libaom's RD essentially never PICKS a 128-root // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears // where the frame EDGE forces it: a partial last superblock row has // `has_rows128 == false`, so the 128x64 top half is implied, and a // partial last column implies the 64x128 left half. Put content no // reference holds (a fresh smooth ramp) in exactly those two bands of an // inter frame and the encoder codes those forced halves INTRA. if bw.max(bh) == 128 { // lane-t900 r32: no screen-content refusal here. `av1_allow_palette` // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`, // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\ // palette_syntax`), so a 128-root half consumes no palette syntax and // a screen-content frame's half is syntactically identical to the // non-screen one this arm already decodes byte-exact. if coeff_trace_on() { // lane-t900 r16: which decode-order frame this arm fires in -- // interleaved with the `EC_COEFF_FRAME` markers, this is what // proves the hit is counted out of a frame that compares exact // (class `counter-from-refused-stream`). eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}"); } fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip)))); let res = decode_block_128rect( dec, cdfs, neighbours, (r, c), bw, bh, y, u, v, base_q_idx, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), allow_screen_content_tools, fctx.tx_select_inter.with(std::cell::Cell::get), fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, ); fctx.intra_in_inter_mode.with(|c| c.set(None)); return res; } let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else { if crate::envflags::env_flag!("EC_OBMCREC") { eprintln!( "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}" ); } // lane-obmcrec r1: the message used to name a 16x4/4x16 strip // (class refusal-names-a-correlate). lane-t900 r20: the shapes that // can arrive here are enumerated against the measured block-shape // census ([`INTER_BLOCK_SHAPES`]) by // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`] // -- every one of them has a row, so this arm names a shape no stream // has been able to present. return Err(unsupported(format!( "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)" ))); }; // lane-t900 r21: this arm used to refuse EVERY rect strip of a // screen-content frame ("palette syntax is consumed for square blocks // only"). It is not: [`read_intra_mode_rect`] generalised the palette read // to rect blocks on the key-frame path, and the 1:4 arm below goes through // it, while the 2:1 reader inlined further down now codes the same syntax // itself. A real `--tune-content=screen` inter stream reached this refusal // on 8x16 / 16x8 strips (gate // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`). // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY // FRAME path already proves for this shape ([`decode_block_rect4`] at the // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4 // luma/chroma transform tables, the per-unit split walk and the strip's // own neighbour records). The ONLY difference on an inter frame is the // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip` // this caller already read. `tx_cat` above is the same category those // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in // `decode_block_rect64`), asserted here so a future shape cannot drift. if bw.max(bh) == 4 * bw.min(bh) { debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 }); fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip)))); let res = if bw.max(bh) == 64 { decode_block_rect64( dec, cdfs, neighbours, (mi_r / (SUB / MI), mi_c / (SUB / MI)), bw, bh, y, u, v, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), allow_screen_content_tools, base_q_idx, fctx.tx_select_inter.with(std::cell::Cell::get), fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, ) } else { decode_block_rect4( dec, cdfs, neighbours, (mi_r, mi_c), bw, bh, None, y, u, v, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), allow_screen_content_tools, base_q_idx, fctx.tx_select_inter.with(std::cell::Cell::get), fctx, ) .map(|_| ()) }; fctx.intra_in_inter_mode.with(|c| c.set(None)); res?; let shape = match (bw, bh) { (64, 16) => 0, (16, 64) => 1, (32, 8) => 2, _ => 3, }; hit_do! { INTRA_RECT4_IN_INTER_HITS.with(|h| { let mut v = h.get(); v[shape] += 1; h.set(v); }); } return Ok(()); } let mode = dec.symbol(&mut cdfs.y_mode[size_group]); // lane-t900 r1: this arm read six mode symbols with no ladder rung of its // own, so a cross-decoder bisection could only see the block's first // coefficient. Same names/format as [`read_tx_size`]'s rung. let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); if step_trace { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}", dec.debug_state().0 ); } if mode >= 13 { return Err(unsupported( "an intra mode this decoder does not code (round 2)", )); } // lane-angleinter (merged on main for the square intra-in-inter arm): // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the // directional predictor; this arm refused a nonzero one before the merge. let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) } else { 0 }; if angle_delta_y != 0 { hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS); } // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the // superblock-level strip reads the no-CFL alphabet -- the same split // [`read_intra_mode_rect`] makes for [`decode_block_rect64`]. let cfl_allowed = bw.max(bh) <= 32; let uv_mode = if cfl_allowed { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; if step_trace { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}", u8::from(cfl_allowed), dec.debug_state().0 ); } if (9..=12).contains(&uv_mode) { hit!(SMOOTH_UV_HITS); } let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { hit!(DIRECTIONAL_UV_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; if angle_delta_uv != 0 { hit!(UV_ANGLE_DELTA_HITS); hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS); } // `read_palette_mode_info` (spec 5.11.13), in the position // `read_intra_block_mode_info` writes it: after the chroma mode and // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so // skipping the syntax here desynced the tile at the strip's own symbol. // lane-t900 r22: reconstructed, not refused -- the strip's real mode // context and colour cache at its own mi position, and the two // colour-index maps decoded after `filter_intra` (`av1_visit_palette`), // exactly as [`read_intra_mode_rect`] does on the key-frame path. let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c)); let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c)); let mut palette_y_pending: Option<(usize, [u16; 8])> = None; let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) { hit!(INTRA_RECT_IN_INTER_SCREEN_HITS); let use_palette_y = mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0; if use_palette_y { let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx))); } // A 2:1 strip of at least 8x8 is always a chroma reference, so // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here. let use_palette_uv = uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; if crate::envflags::env_flag!("EC_PALSYN") { eprintln!("EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", use_palette_y as i32, use_palette_uv as i32, dec.debug_state().0); } if use_palette_uv { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx); palette_uv_pending = Some((n, u_colors, v_colors)); } } // lane-fiinter (merged on main for the square intra-in-inter arm): // `read_filter_intra_mode_info` is the tail of // `read_intra_block_mode_info`, after the palette syntax (refused whole // above for this shape), and `av1_filter_intra_allowed_bsize` admits the // 2:1 strips with both sides <= 32 -- their own CDF rows // ([`filter_intra_size_class_rect`]). let mut filter_intra = None; if mode == DC_PRED && fctx.enable_filter_intra_inter.with(std::cell::Cell::get) // `av1_filter_intra_allowed` excludes a palette-Y block. && palette_y_pending.is_none() && let Some(class) = filter_intra_size_class_rect(bw, bh) && dec.symbol(&mut cdfs.filter_intra[class]) != 0 { hit!(FILTER_INTRA_HITS); hit!(INTRA_IN_INTER_FILTER_INTRA_HITS); filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode)); } // `av1_visit_palette`: Y's colour-index map then the shared chroma one. let palette_y = palette_y_pending.map(|(n, colors)| { let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false); hit!(PALETTE_HITS); hit!(PALETTE_RECT_HITS); hit!(INTRA_IN_INTER_PALETTE_Y_HITS); PaletteY { size: n, colors, map } }); let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4)); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true); hit!(PALETTE_UV_HITS); hit!(INTRA_IN_INTER_PALETTE_UV_HITS); PaletteUv { size: n, u_colors, v_colors, map } }); // The intra-edge filter type is the NEIGHBOUR's mode (libaom // `get_filt_type`), luma's off the luma neighbours and chroma's off the // chroma ones -- [`decode_block_rect`]'s own pair. // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST // half. libaom's `above_mbmi`/`left_mbmi` are this block's own // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse // one exactly as [`decode_leaf8`] already does (class // context-read-from-one-cell). let coarse_pair = neighbours.modes_above_left(r, c); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair); if (nb_above_mode, nb_left_mode) != coarse_pair { hit!(EDGE_FILTER_MI_FIX_HITS); } let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c); let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) { // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's // deblock-grid approximation -- [`tx_size_context_txfm_rect`]. let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx); let d = match tx_cat { 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]), 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]), _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]), }; if step_trace { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}", dec.debug_state().0 ); } d } else { 0 }; if depth != 0 { hit!(TX_DEPTH_HITS); // lane-intrasplit r1: a split intra strip in an inter frame walks the // key frame's own per-TU path ([`decode_rect_split`] below); what was // wrong when this refusal was written was the depth SYMBOL, not the walk. hit_do! { INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| { let mut v = h.get(); v[depth.min(2)] += 1; h.set(v); }); } } // lane-intrasplit r3: print EVERY intra strip with its depth, not only the // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and // the two are indistinguishable when the diagnostic fires on splits alone. if crate::envflags::env_flag!("EC_SPLITSTRIP") { eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}"); } let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h, // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block // of an inter frame, intra ones included -- with the skip term 0 it // memsets `above_txfm_context` to `tx_size_wide` over the block's width // and `left_txfm_context` to `tx_size_high` over its height. This strip // wrote neither, so the next block's var-tx `txfm_partition` context read // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at // mi(16,0) and desyncing the tile at that symbol. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); let modes = RectStripModes { skip, mode, angle_delta_y, uv_predict_mode, angle_delta_uv, alpha, filter_intra, smooth_neighbor, smooth_neighbor_uv, palette_y: palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), palette_uv: palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }), }; decode_rect_split( dec, cdfs, neighbours, (mi_r, mi_c), bw, bh, tx_w, tx_h, &modes, y, u, v, base_q_idx, fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, )?; // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in // both `TXFM_CONTEXT` bands -- the above row over the block's width, the // left column over its height. This arm wrote neither before lane-intrasplit // r1, so every later block in the frame read a stale `tx_size`/`txfm_split` // context across the strip's footprint. for i in 0..bw / MI { if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) { *cell = tx_w as u8; } } for i in 0..bh / MI { if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) { *cell = tx_h as u8; } } // The strip's own palette state into the mi-granular neighbour bands, so // the next block's colour cache and `palette_y_mode` context are libaom's. record_strip_palette( neighbours, (mi_r, mi_c), bw, bh, palette_y.as_ref().map_or(0, |p| p.size), palette_y.as_ref().map_or([0u16; 8], |p| p.colors), palette_uv.as_ref().map_or(0, |p| p.size), palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors), ); let class = match bw.max(bh) { 64 => 0, 32 => 1, _ => 2, }; hit_do! { INTRA_RECT_IN_INTER_HITS.with(|h| { let mut v = h.get(); v[class] += 1; h.set(v); }); } Ok(()) } /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/ /// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way /// (so a skip strip elsewhere in the tile stays in sync), but this decoder /// has no rectangular-transform coefficient reader, and a chroma plane here /// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16) /// with no depth-based square-tiling escape the way luma's own resolved /// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) -- /// so a coded (non-skip) strip is refused by name instead of guess-decoded. #[allow(clippy::too_many_arguments)] fn decode_block_rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, at: (usize, usize), bw: usize, bh: usize, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, enable_filter_intra: bool, allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); let palette_uv_cache = neighbours.palette_uv_cache(at); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, nb_above_mode, nb_left_mode, true, true, bw, bh, enable_filter_intra, neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), allow_screen_content_tools, Some((palette_ctx, &palette_cache)), &palette_uv_cache, r * (SUB / MI), c * (SUB / MI), fctx, )?; let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } // lane-chroma r3: chroma's own edge-filter-strength neighbour check // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's // `uv_mode`, not the luma one. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c); // lane-rectsplit r1: `predict_filter_intra` now takes the block's own // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a // rectangle just as happily), so a `use_filter_intra` strip at this level // predicts instead of refusing. The below-16x16 leaf arm // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own. if filter_intra.is_some() { hit!(FILTER_INTRA_RECT_HITS); } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths // gate their `read_tx_size` on `tx_select` for exactly this reason; this // one did not, so with `--enable-tx-size-search=0` -- which several gate // recipes use -- the decoder consumed a symbol the encoder never wrote and // desynced the tile from that point on. That is why both strips of the // pinned HORZ quadrant were wrong from their very first pixel, and why our // range after the read equalled the oracle's range for the whole block. let depth = if tx_select { // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and // the 16x4 intra-in-inter strips already do); the key frame's // deblock-grid approximation is only right where those bands were never // written. Measured on the 10-bit 1920x792 128-superblock stream, // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read // `tx_size_cat2` row 1 where libaom reads row 2. let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() { tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx) } else { tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh) }; let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}", dec.debug_state().0 ); } d } else { 0 }; if depth != 0 { hit!(TX_DEPTH_HITS); // lane-rectsplit r1: a split transform is predicted and reconstructed // per transform unit, each unit taking its edges from the previous // unit's reconstruction inside this same strip (spec 5.11.36) -- // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`]. let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); if crate::envflags::env_flag!("EC_SBPART_DUMP64") { eprintln!( "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \ angle_y={angle_delta_y}" ); } let modes = RectStripModes { skip, mode, angle_delta_y, uv_predict_mode, angle_delta_uv, alpha, filter_intra, smooth_neighbor, smooth_neighbor_uv, palette_y: palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), palette_uv: palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }), }; if palette_y.is_some() || palette_uv.is_some() { hit!(PALETTE_SPLIT_TX_HITS); } decode_rect_split( dec, cdfs, neighbours, (mi_r, mi_c), bw, bh, tx_w, tx_h, &modes, y, u, v, base_q_idx, reduced_tx_set, fctx, )?; // This early return skips this fn's own tail, so the palette // neighbour state has to be stamped HERE too: without it a split-tx // strip left the above/left palette arrays holding a DEAD block's // colours, and the next block's colour cache // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the // wrong VALUE -- same bit count, so the entropy stream stayed in sync // and only those pixels were wrong (lane-palette2 r10). let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors); let (puv_size, puv_colors) = palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); hit!(RECT_PARTITION_HITS); return Ok(()); } let (tx_w, tx_h) = (bw, bh); let (cpx, cpy) = (px / 2, py / 2); let (chroma_w, chroma_h) = (bw / 2, bh / 2); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!( "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \ skip={} tx={depth} rng={rng}", skip as i32 ); } // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV // block's prediction is the reconstructed colour-index map, set fresh // right before each `reconstruct_rect` call below (lane-palette2 r4). if let Some(ref pyv) = palette_y { let buf: Vec = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect(); set_palette_pred(buf, fctx); } let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|puv| { ( puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(), puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), ) }); if skip { push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..bw * bh], None, filter_intra, smooth_neighbor, fctx, ); let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra_rect(1, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..chroma_w * chroma_h], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra_rect(2, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..chroma_w * chroma_h], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); neighbours.record_rect( at, bw, bh, mode, uv_predict_mode, &[ &ZERO_RESIDUAL[..bw * bh], &ZERO_RESIDUAL[..chroma_w * chroma_h], &ZERO_RESIDUAL[..chroma_w * chroma_h], ], ); } else { // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx` // reduces both size pairs to their square-up CDF sets // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own // doc comments); the scan order and 2D context tables are the real // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`). let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 { (&SCAN_32X16, &SCAN_16X8) } else { (&SCAN_16X32, &SCAN_8X16) }; // lane-rectwire r3: real coefficients desync a pixel-exact gate // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's // mi(8,8) HORZ quadrant come out ~100% wrong from their very first // pixel (not a subtle context-table off-by-one), while the sibling // non-rect quadrants of the same frame match. Range-ladder bisection // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started // but the intra key-frame path has no traced symbol between the // partition read and the first coefficient block (mode/skip/tx_depth // reads are all untraced in libaom's decodeframe.c intra path, unlike // the inter EC_TRACE_MODE this round added), so a same-length range // comparison wasn't reachable within budget -- see // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and // dc_sign_ctx's around-index all cross-checked byte-for-byte against // libaom and match). lane-rectwire r4: range-ladder against the // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL) // narrowed the divergence past skip/y_mode/uv_mode (values AND range // both confirmed in sync -- rng=58692 on both sides right after // uv_mode, with `enable_filter_intra=0` on this frame so neither side // reads a filter_intra symbol) to the `tx_size_cat2` depth read // immediately after: ours moves rng 58692 -> 43570, which cannot be // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after* // its own tx_size read) unless oracle's tx symbol is a near-certainty // CDF that barely narrows the range -- i.e. this decoder's // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for // a 32x16/16x32 strip is the first diverging symbol, not the // coefficient-context math r3 already cleared. Not confirmed byte- // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on // `read_tx_size`'s own rng, not attempted this round -- budget), so // r5 CONFIRMED the suspect and it was simpler than the CDF row: the // tx-depth symbol exists only under TX_MODE_SELECT, and this path read // it unconditionally where both square paths gate on `tx_select`. With // --enable-tx-size-search=0 the encoder writes no such symbol, so the // decoder consumed one that was never there. { let around = neighbours.around_rect(at, bw, bh); let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra)); let (luma_levels, luma_tx_type) = read_coeffs_rect( dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct, )?; if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}"); } let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type, ); push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra, smooth_neighbor, fctx, ); let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode); let (u_levels, u_tx_type) = read_coeffs_rect( dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, dc_sign_ctx(around[1].2), u_default_tx, )?; if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}"); } let u_residual = dequant_and_inverse_typed_wh( &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type, ); push_intra_rect(1, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode); let (v_levels, v_tx_type) = read_coeffs_rect( dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, dc_sign_ctx(around[2].2), v_default_tx, )?; if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}"); } let v_residual = dequant_and_inverse_typed_wh( &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type, ); push_intra_rect(2, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]); hit!(RECT_COEFF_HITS); } } let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors); let (puv_size, puv_colors) = palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx); hit!(RECT_PARTITION_HITS); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}"); } Ok(()) } /// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/ /// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but /// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid /// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`: /// the second strip of a HORZ/VERT split sits offset by half the 16x16 /// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't /// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the /// previous strip is directly above (same column, `mi_h` rows up) or /// directly left (same row, `mi_w` cols over), its mode overrides the coarse /// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode /// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour /// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at /// this strip's real position, never the coarse `record_rect` (which the /// caller uses once, after both strips, exactly like the `VERT_B` arm next /// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16` /// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8` /// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level /// under [`decode_block_rect`]'s own 32x16/16x32 strip. #[allow(clippy::too_many_arguments)] fn decode_leaf_rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, outer_at: (usize, usize), leaf_mi: (usize, usize), bw: usize, bh: usize, prev_leaf: Option<((usize, usize), usize)>, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, enable_filter_intra: bool, allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result { let _ = base_q_idx; if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { eprintln!( "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}", dec.debug_state().0 ); } let (r, c) = outer_at; let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; let (mi_w, mi_h) = (bw / MI, bh / MI); if let Some(((pr, pc), pmode)) = prev_leaf { if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h { above_mode = pmode; } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w { left_mode = pmode; } } // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot // cannot hold the modes a split (or a pair of strips) leaves behind, so // when the map holds the block at exactly this strip's above/left mi it // is the neighbour libaom's `above_mi`/`left_mi` reads. // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND // availability-correct -- four 16x8 strips share one coarse 16x16 // `left_mode` cell too, so the fallback must not stand in for an absent // tile-edge neighbour. let (above_mode, left_mode) = neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode)); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } // The palette-Y mode CDF row is picked by the neighbours' palette use // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use // a palette narrows the wrong interval and desyncs the tile even when the // decoded bit is the same. The cell is the 16px-SUB cell containing the // leaf (the palette neighbour arrays have no finer granularity). // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row // exclusion and the neighbour palette lookup itself are mi-granular // (see [`Neighbours::palette_ctx_and_cache_mi`]). let pal_at = leaf_mi; let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at); let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, above_mode, left_mode, true, true, bw, bh, enable_filter_intra, neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1), allow_screen_content_tools, Some((palette_ctx, &palette_cache)), &palette_uv_cache, leaf_mi.0, leaf_mi.1, fctx, )?; // lane-kf900 r4: palette prediction on this shape, the same colour-index // map -> base colours buffer [`decode_block_rect`] hands each // `reconstruct_rect` through [`set_palette_pred`]. if palette_y.is_some() || palette_uv.is_some() { hit!(RECT4_PALETTE_HITS); } let palette_y_buf: Option> = palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }); let (pal_y_size, pal_y_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); let (pal_uv_size, pal_uv_colors) = palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}"); } if filter_intra.is_some() { // lane-fistrip r1: `predict_filter_intra` already walks its 4x2 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an // 8x16/16x8 strip predicts through the same call `reconstruct_rect` // below already makes; this refusal was square-only prose. hit!(FILTER_INTRA_RECT_HITS); hit!(FILTER_INTRA_RECT_SUB16_HITS); } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not // a constant `false`. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); let depth = if tx_select { // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read // every other rect reader now does -- a no-op on a key frame. let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() { tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx) } else { tx_size_context_rect(neighbours, leaf_mi, bw, bh) }; // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`, // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol // count (3), different CDF row: a wrong-table read of a real symbol, // the class that cost lane-rectsplit r1 its 64x32 depth. // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this // function also decodes) sit at depth 2, so they read // `tx_size_cdf[1]` -- the same table a 16x16 square block reads -- // while `tx_size_cat2` belongs to the 32-level shapes // ([`decode_block_rect`]). Both tables carry three symbols, so the // wrong one decodes a plausible depth from the wrong probabilities: // the range diverges silently at the first such leaf and every later // symbol in the tile is read from the wrong place (class // `wrong-alphabet-same-value`, here same alphabet / wrong row). dec.symbol(&mut cdfs.tx_size_cat1[ctx]) } else { 0 }; if depth != 0 { // The same per-transform-unit walk the bigger strips take // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at // depth 2), addressed at this leaf's own mi position. hit!(TX_DEPTH_HITS); hit!(SUB16_SPLIT_HITS); let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); let modes = RectStripModes { skip, mode, angle_delta_y, uv_predict_mode, angle_delta_uv, alpha, filter_intra, smooth_neighbor, // lane-rectsplitx r3: the split arm hard-coded `false` here while // the unsplit arm below passes the real neighbour answer -- chroma // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type. smooth_neighbor_uv, palette_y: palette_y_buf.clone(), palette_uv: palette_uv_bufs.clone(), }; if palette_y.is_some() || palette_uv.is_some() { hit!(PALETTE_SPLIT_TX_HITS); } decode_rect_split( dec, cdfs, neighbours, leaf_mi, bw, bh, tx_w, tx_h, &modes, y, u, v, base_q_idx, reduced_tx_set, fctx, )?; record_strip_palette( neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, ); return Ok(mode); } let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); let (cpx, cpy) = (px / 2, py / 2); let (chroma_w, chroma_h) = (bw / 2, bh / 2); let (luma_levels, u_levels, v_levels); if skip { luma_levels = Grid::Zero(bw * bh); u_levels = Grid::Zero(chroma_w * chroma_h); v_levels = Grid::Zero(chroma_w * chroma_h); if let Some(b) = &palette_y_buf { set_palette_pred(b.clone(), fctx); } push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra, smooth_neighbor, fctx, ); let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra_rect(1, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra_rect(2, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); } else { // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`, // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type` // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`). let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 { (&SCAN_16X8, &SCAN_8X4) } else { (&SCAN_8X16, &SCAN_4X8) }; let around = neighbours.around_mi_rect(leaf_mi, bw, bh); let luma_set = if reduced_tx_set { TxbSet::LumaRect16x8 } else { TxbSet::LumaRect16x8Set1 }; let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra)); let (l_levels, luma_tx_type) = read_coeffs_rect( dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct, )?; if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect(); eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}"); } luma_levels = l_levels; let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, bh, crate::decode::bit_depth(fctx), fctx.current_q_idx.with(|c| c.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type, ); if let Some(b) = &palette_y_buf { set_palette_pred(b.clone(), fctx); } push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra, smooth_neighbor, fctx, ); let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); let (u_l, u_tx_type) = read_coeffs_rect( dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, dc_sign_ctx(around[1].2), u_default_tx, )?; u_levels = u_l; let u_residual = dequant_and_inverse_typed_wh( &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), fctx.current_q_idx.with(|c| c.get()), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type, ); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra_rect(1, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); let (v_l, v_tx_type) = read_coeffs_rect( dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, dc_sign_ctx(around[2].2), v_default_tx, )?; v_levels = v_l; let v_residual = dequant_and_inverse_typed_wh( &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), fctx.current_q_idx.with(|c| c.get()), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra_rect(2, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); hit!(RECT_LEAF_COEFF_HITS); } neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]); neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip); neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx); // The leaf's own palette state (`0` clears, as this site always did // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT // AXIS only until the pair's closing leaf: the coarse cell holds one // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the // real left neighbour leaf 1 reads (lane-kf900 r4). record_strip_palette( neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, ); // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and // rows -- record the whole span, not one cell. neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode); neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode); Ok(mode) } /// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` / /// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling, /// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`] /// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an /// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous /// strip's mode so this one's mode context sees its true above/left /// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention). /// /// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context /// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with /// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the /// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with /// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale -- /// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2 /// (`inverse_transform_2d_typed_wh`'s own `rect_scale`). /// /// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of /// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1 /// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused /// unexamined. #[allow(clippy::too_many_arguments)] fn decode_block_rect4( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, strip_mi: (usize, usize), bw: usize, bh: usize, prev_strip: Option<((usize, usize), usize)>, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, enable_filter_intra: bool, allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(usize, usize)> { let _ = base_q_idx; let (mi_r, mi_c) = strip_mi; let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); let (mi_w, mi_h) = (bw / MI, bh / MI); let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; if let Some(((pr, pc), pmode)) = prev_strip { if pc == mi_c && mi_r == pr + mi_h { above_mode = pmode; } else if pr == mi_r && mi_c == pc + mi_w { left_mode = pmode; } } // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact + // availability-correct neighbour modes (see // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell. let (above_mode, left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode)); // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache. // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count, // wrong interval, so a screen-content tile desynced at the first strip // whose neighbour used a palette (class [[cdf-row-held-constant]]). let pal_at = (mi_r, mi_c); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at); let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at); let ( skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, ) = read_intra_mode_rect( dec, cdfs, above_mode, left_mode, true, true, bw, bh, enable_filter_intra, neighbours.skip_txfm_ctx(mi_r, mi_c), allow_screen_content_tools, Some((palette_ctx, &palette_cache)), &palette_uv_cache, mi_r, mi_c, fctx, )?; // lane-kf900 r4: palette prediction on this shape, exactly as // [`decode_block_rect`] does one aspect ratio up -- the colour-index map // mapped through the base colours IS the prediction (it reads no edge // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`]. if palette_y.is_some() || palette_uv.is_some() { hit!(RECT4_PALETTE_HITS); } let palette_y_buf: Option> = palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }); let (pal_y_size, pal_y_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); let (pal_uv_size, pal_uv_colors) = palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so // `r * (SUB / MI)` names a different mi column and the chroma // edge-filter strength was read from the wrong neighbour (measured: // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch // with luma bit-exact). let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c); if filter_intra.is_some() { hit!(FILTER_INTRA_RECT_HITS); if bw > bh { hit!(FILTER_INTRA_RECT4_HORZ_HITS); } else { hit!(FILTER_INTRA_RECT4_VERT_HITS); } } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let depth = if tx_select { // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and // the 16x4 intra-in-inter strips already do); the key frame's // deblock-grid approximation is only right where those bands were never // written. Measured on the 10-bit 1920x792 128-superblock stream, // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read // `tx_size_cat2` row 1 where libaom reads row 2. let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() { tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx) } else { tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh) }; let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}", dec.debug_state().0 ); } d } else { 0 }; // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`]. publish_txfm_bands_if_in_inter( neighbours, (mi_r, mi_c), depth_to_tx_wh(bw, bh, depth), (bw, bh), fctx, ); if depth != 0 { // lane-rectsplitx r1: the per-transform-unit walk, at this strip's // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8; // both interleave in every real stream. hit!(TX_DEPTH_HITS); let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); // lane-rectsplitx r2: both depths ship together, as the r1 handoff // predicted -- depth 1 fires FIRST in every attempt that splits at // all, so a depth-2-only lift could never be gated. The r1 mismatch // was never the rect unit: it was the neighbour MODE the strip reads // (see `modes_above_left_mi`). let which = if depth == 1 { &RECT4_SPLIT_DEPTH1_HITS } else { &RECT4_SPLIT_DEPTH2_HITS }; hit_do! { which.with(|c| c.set(c.get() + 1)); } let modes = RectStripModes { skip, mode, angle_delta_y, uv_predict_mode, angle_delta_uv, alpha, filter_intra, smooth_neighbor, smooth_neighbor_uv, palette_y: palette_y_buf.clone(), palette_uv: palette_uv_bufs.clone(), }; if palette_y.is_some() || palette_uv.is_some() { hit!(PALETTE_SPLIT_TX_HITS); } decode_rect_split( dec, cdfs, neighbours, (mi_r, mi_c), bw, bh, tx_w, tx_h, &modes, y, u, v, base_q_idx, false, fctx, )?; record_strip_palette( neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, ); if bw > bh { hit!(RECT4_32_HORZ_HITS); } else { hit!(RECT4_32_VERT_HITS); } if !skip { hit!(RECT4_COEFF_HITS); } // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter // frame, so this 1:4 strip -- which is also the INTER frame's reader // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its // transform size in both TXFM_CONTEXT bands. Without it the next block // reads the row's stale value. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); return Ok((mode, uv_predict_mode)); } // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip // that is 8 px tall, so each strip stamps every cell it touches and the // LAST strip wins -- which is the right answer for the block below/right // of the 32x32, the only reader outside it. Written after this strip's // own context read above, never before. for cell in 0..bw.div_ceil(SUB) { neighbours.above_mode[c + cell] = mode; neighbours.above_uv_mode[c + cell] = uv_predict_mode; neighbours.above_side[c + cell] = bw; } for cell in 0..bh.div_ceil(SUB) { neighbours.left_mode[r + cell] = mode; neighbours.left_uv_mode[r + cell] = uv_predict_mode; neighbours.left_side[r + cell] = bh; } // ...and the mi-EXACT maps the coarse cells alias away, exactly as // [`decode_leaf_rect`] does (the split arm above records these through // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left // `sub8_mode_row` holding the previous block, and the next 32x32's // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band // fixture). neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode); neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode); let (px, py) = (mi_c * MI, mi_r * MI); let (cpx, cpy) = (px / 2, py / 2); let (chroma_w, chroma_h) = (bw / 2, bh / 2); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh { (&SCAN_32X8, &SCAN_16X4) } else { (&SCAN_8X32, &SCAN_4X16) }; let (luma_levels, u_levels, v_levels) = if skip { ( vec![0i32; bw * bh], vec![0i32; chroma_w * chroma_h], vec![0i32; chroma_w * chroma_h], ) } else { let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode); let (luma_levels, luma_tx_type) = read_coeffs_rect( dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct, )?; let mut planes = Vec::with_capacity(2); for plane in 1..3 { let default_tx = default_intra_tx_type(uv_predict_mode as u8); let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, chroma_scan, chroma_w, chroma_h, skip_ctx, dc_sign_ctx(around[plane].2), default_tx, )?; planes.push((levels, tx_type)); } let (v_levels, v_tx_type) = planes.pop().expect("plane 2"); let (u_levels, u_tx_type) = planes.pop().expect("plane 1"); hit!(RECT4_COEFF_HITS); let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type, ); if let Some(b) = &palette_y_buf { set_palette_pred(b.clone(), fctx); } push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra, smooth_neighbor, fctx, ); let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); for (plane, _buf, levels, tx_type) in [ (1usize, &mut *u, &u_levels, u_tx_type), (2, &mut *v, &v_levels, v_tx_type), ] { let residual = dequant_and_inverse_typed_wh( levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane, fctx).0, plane_q_delta(plane, fctx).1, tx_type, ); if let Some((ub, vb)) = &palette_uv_bufs { set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx); } push_intra_rect(plane, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &residual, alpha .zip(ac) .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), None, smooth_neighbor_uv, fctx, ); } neighbours.record_mi_rect( (mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]], ); neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx); record_strip_palette( neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, ); if bw > bh { hit!(RECT4_32_HORZ_HITS); } else { hit!(RECT4_32_VERT_HITS); } // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter // frame, so this 1:4 strip -- which is also the INTER frame's reader // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its // transform size in both TXFM_CONTEXT bands. Without it the next block // reads the row's stale value. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh)); return Ok((mode, uv_predict_mode)); }; if let Some(b) = &palette_y_buf { set_palette_pred(b.clone(), fctx); } push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra, smooth_neighbor, fctx, ); let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra_rect(1, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra_rect(2, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]); neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx); record_strip_palette( neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, ); if bw > bh { hit!(RECT4_32_HORZ_HITS); } else { hit!(RECT4_32_VERT_HITS); } // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter // frame, so this 1:4 strip -- which is also the INTER frame's reader // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its // transform size in both TXFM_CONTEXT bands. Without it the next block // reads the row's stale value. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh)); Ok((mode, uv_predict_mode)) } /// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` / /// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level /// down, and the first shape here whose luma block is a single mi row (or /// column). /// /// What is new at this size is CHROMA. `is_chroma_reference` /// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an /// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/ /// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close /// the pair and carry the chroma of the whole 16x8 (8x16) luma pair -- /// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) && /// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma /// transform at the PAIR's origin, with CfL averaging over the pair's luma. /// /// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context /// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is /// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row); /// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is /// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE /// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and /// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this /// shape's own CDF row. /// /// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`) /// refuses by name rather than guess-decode. #[allow(clippy::too_many_arguments)] fn decode_rect4_16( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, at16: (usize, usize), horz: bool, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, enable_filter_intra: bool, allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let (r, c) = at16; let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI)); let (bw, bh) = if horz { (16, 4) } else { (4, 16) }; let (_mi_w, _mi_h) = (bw / MI, bh / MI); let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 }; let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 }; let mut prev: Option<((usize, usize), usize)> = None; let mut last_mode = DC_PRED; let mut last_uv_mode = DC_PRED; for i in 0..4usize { let lmi = if horz { (mi_row0 + i, mi_col0) } else { (mi_row0, mi_col0 + i) }; let has_chroma = i % 2 == 1; let (mode, uv, _tx) = decode_rect4_16_strip( dec, cdfs, neighbours, lmi, horz, has_chroma, prev, y, u, v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; if let Some(m) = uv { last_uv_mode = m; } last_mode = mode; prev = Some((lmi, mode)); } // The coarse 16-px cell holds one entry for the whole 16x16: the last // strip is what a block below (right) sees through it, the mi-exact maps // above answering everything finer. neighbours.above_mode[c] = last_mode; neighbours.left_mode[r] = last_mode; neighbours.above_uv_mode[c] = last_uv_mode; neighbours.left_uv_mode[r] = last_uv_mode; neighbours.above_side[c] = bw; neighbours.left_side[r] = bh; Ok(()) } /// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded -- /// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER /// block path can decode a SINGLE intra strip of a partition whose other /// strips are inter. `prev` is the previous strip's `(mi, mode)` (the /// key-frame caller's coarse-cell stand-in; `None` on the inter path, where /// every strip publishes its own mi-exact mode). Returns /// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`. #[allow(clippy::too_many_arguments)] fn decode_rect4_16_strip( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, lmi: (usize, usize), horz: bool, has_chroma: bool, prev: Option<((usize, usize), usize)>, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, enable_filter_intra: bool, allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(usize, Option, (usize, usize))> { let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI)); let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) }; let (mi_w, mi_h) = (bw / MI, bh / MI); let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 }; let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 }; let mut last_uv_mode: Option = None; // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell // aliases all four strips onto one entry, so the mi-exact map wins and // the previous strip stands in on the split axis. let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; if let Some(((pr, pc), pmode)) = prev { if pc == lmi.1 && lmi.0 == pr + mi_h { above_mode = pmode; } else if pr == lmi.0 && lmi.1 == pc + mi_w { left_mode = pmode; } } let (above_mode, left_mode) = neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode)); // lane-kf900 r4: the strip's real palette ctx + colour cache (see // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode` // off CDF row 0 and every cache hit off an empty cache. let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi); let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi); let ( skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, ) = read_intra_mode_rect( dec, cdfs, above_mode, left_mode, true, has_chroma, bw, bh, enable_filter_intra, neighbours.skip_txfm_ctx(lmi.0, lmi.1), allow_screen_content_tools, Some((palette_ctx, &palette_cache)), &palette_uv_cache, lmi.0, lmi.1, fctx, )?; if palette_y.is_some() || palette_uv.is_some() { hit!(RECT4_PALETTE_HITS); } // The colour-index map through the base colours IS the prediction. // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one // chroma transform this closing strip codes. let palette_y_buf: Option> = palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } if filter_intra.is_some() { hit!(FILTER_INTRA_RECT_HITS); } // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does. let depth = if tx_select { // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what // the 2:1 intra-in-inter strip already does); the key frame's // deblock-grid approximation is only right where those bands were // never written. let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() { tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx) } else { tx_size_context_rect(neighbours, lmi, bw, bh) }; let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}", lmi.0, lmi.1, dec.debug_state().0 ); } d } else { 0 }; if depth != 0 { hit!(TX_DEPTH_HITS); hit!(RECT4_16_SPLIT_HITS); } let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode); if depth != 0 { // [`decode_rect_split`]'s per-unit walk, inlined because the // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to // the strip (that function codes one chroma transform per block). // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each // unit predicts off the units before it in raster order. let rect_unit = tx_w != tx_h; let zero_tu = vec![0i32; tx_w * tx_h]; for tu_row in 0..bh / tx_h { for tu_col in 0..bw / tx_w { let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI)); let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h); let tu_reach = Reach::of_tu( bw, bh, tu_col * tx_w, tu_row * tx_h, tx_w, tx_h, reach, ); if let Some(b) = &palette_y_buf { let tu_buf: Vec = (0..tx_h) .flat_map(|i| { let base = (tu_row * tx_h + i) * bw + tu_col * tx_w; b[base..base + tx_w].iter().copied() }) .collect(); set_palette_pred(tu_buf, fctx); } if skip { push_intra_rect(0, tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu, None, filter_intra, smooth_neighbor, fctx, ); neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu); } else if rect_unit { // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with // 32 coded positions and the `TX_4X4` `tx_type` row: // exactly [`TxbSet::LumaRect4x8`]. let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI); let set = if reduced_tx_set { TxbSet::LumaRect4x8 } else { TxbSet::LumaRect4x8Set1 }; let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 }; let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); let (tu_grid, tu_tx_type) = read_coeffs_rect( dec, &mut coding, tu_scan, tx_w, tx_h, tu_skip_ctx, dc_sign_ctx(tu_around.2), TxType::DctDct, )?; let residual = dequant_and_inverse_typed_wh( &tu_grid, tx_w, tx_h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tu_tx_type, ); push_intra_rect(0, tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual, None, filter_intra, smooth_neighbor, fctx, ); if tu_grid.iter().any(|&l| l != 0) { hit!(RECT4_16_COEFF_HITS); } neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); } else { let tu_around = neighbours.around_mi(tu_mi, tx_w)[0]; let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI); let tu_grid = read_plane( dec, cdfs, txbset_for(tx_w, reduced_tx_set), default_scan(tx_w), 0, tu_around, mode, mode, angle_delta_y, tu_reach, y, tu_px, tu_py, tx_w, tx_w, base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; if tu_grid.iter().any(|&l| l != 0) { hit!(RECT4_16_COEFF_HITS); } neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid); } } } } else { let levels = if skip { let zeros = Grid::Zero(bw * bh); if let Some(b) = &palette_y_buf { set_palette_pred(b.clone(), fctx); } push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra, smooth_neighbor, fctx, ); zeros } else { // The strip's luma TU *is* the strip (`plane_bsize == // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes // `txb_skip_ctx` at 0. let around = neighbours.around_mi_rect(lmi, bw, bh)[0]; let set = if reduced_tx_set { TxbSet::LumaRect16x4 } else { TxbSet::LumaRect16x4Set1 }; let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, scan, bw, bh, 0, dc_sign_ctx(around.2), TxType::DctDct, )?; let residual = dequant_and_inverse_typed_wh( &levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type, ); if let Some(b) = &palette_y_buf { set_palette_pred(b.clone(), fctx); } push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra, smooth_neighbor, fctx, ); hit!(RECT4_16_COEFF_HITS); levels }; neighbours.record_mi_luma_rect(lmi, bw, bh, &levels); } neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip); neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx); // `update_partition_context` writes `partition_context_lookup[ // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on // the left (mirrored under VERT_4). for cell in 0..mi_w { if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) { *slot = bw as u8; } } for cell in 0..mi_h { if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) { *slot = bh as u8; } } if has_chroma { hit!(RECT4_16_CHROMA_HITS); let pair_mi = if horz { (lmi.0 - 1, lmi.1) } else { (lmi.0, lmi.1 - 1) }; let (pw, ph) = if horz { (16, 8) } else { (8, 16) }; let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI); let (cpx, cpy) = (ppx / 2, ppy / 2); let (cw, ch) = (pw / 2, ph / 2); let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; if (V_PRED..=D67_PRED).contains(&uv_predict_mode) { hit!(RECT4_16_CHROMA_DIR_HITS); } let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx); // lane-kf1200 r1: the chroma edge-filter type reads the neighbours // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/ // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e. // the pair's top-left luma mi, never this leaf's odd row/column. // Reading `lmi` here named the leaf directly above (a non-chroma // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a // SMOOTH neighbour: filt_type 0 instead of 1 turned // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a // directional chroma strip, moving 4 samples by 1. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c); if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c) { hit!(RECT4_16_UV_PAIR_FILT_HITS); } let (u_levels, v_levels) = if skip { let zeros = Grid::Zero(cw * ch); // libaom `predict_and_reconstruct_intra_block` (decodeframe.c // ~1000) predicts EVERY plane and only guards the residual on // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still // DC + alpha * luma-AC. Dropping the CfL term here left a // chroma-only bounded box on ReelC's key frames. let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph)); if alpha.is_some() { hit!(CHROMA_SKIP_CFL_HITS); } for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] { if let Some((ub, vb)) = &palette_uv_bufs { set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx); } push_intra_rect(plane, cpx, cpy, cw, ch, uv_predict_mode, angle_delta_uv, pair_reach, &zeros, alpha .zip(ac) .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), None, smooth_neighbor_uv, fctx, ); } (zeros.clone(), zeros) } else { let around = neighbours.around_mi_rect(pair_mi, pw, ph); let mut planes = Vec::with_capacity(2); for plane in 1..3 { let default_tx = default_intra_tx_type(uv_predict_mode as u8); let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, chroma_scan, cw, ch, skip_ctx, dc_sign_ctx(around[plane].2), default_tx, )?; planes.push((levels, tx_type)); } let (v_levels, v_tx_type) = planes.pop().expect("plane 2"); let (u_levels, u_tx_type) = planes.pop().expect("plane 1"); // CfL averages the luma of the WHOLE pair, the region this one // chroma transform covers. let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph)); for (plane, _buf, levels, tx_type) in [ (1usize, &mut *u, &u_levels, u_tx_type), (2, &mut *v, &v_levels, v_tx_type), ] { let residual = dequant_and_inverse_typed_wh( levels, cw, ch, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane, fctx).0, plane_q_delta(plane, fctx).1, tx_type, ); if let Some((ub, vb)) = &palette_uv_bufs { set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx); } push_intra_rect(plane, cpx, cpy, cw, ch, uv_predict_mode, angle_delta_uv, pair_reach, &residual, alpha .zip(ac) .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), None, smooth_neighbor_uv, fctx, ); } (u_levels, v_levels) }; neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode); // The chroma planes' coefficient context, over the PAIR's mi span // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is // the luma one rounded up to its 4x4 unit). let u_state = neighbour_state(&u_levels); let v_state = neighbour_state(&v_levels); let round_up_even = |n: usize| n.div_ceil(2) * 2; let bound_h = round_up_even(neighbours.mi_rows); let bound_w = round_up_even(neighbours.mi_cols); for cell in 0..(ph / MI) { if pair_mi.0 + cell < bound_h && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell) { slot[1] = u_state; slot[2] = v_state; } } for cell in 0..(pw / MI) { if pair_mi.1 + cell < bound_w && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell) { slot[1] = u_state; slot[2] = v_state; } } last_uv_mode = Some(uv_predict_mode); } if horz { hit!(RECT4_16_HORZ_HITS); } else { hit!(RECT4_16_VERT_HITS); } let (pal_y_size, pal_y_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); let (pal_uv_size, pal_uv_colors) = palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); record_strip_palette( neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, ); // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)` // (libaom `decode_token_recon_block`, run for EVERY block of an inter // frame): the above row records `tx_size_wide` over the block's width and // the left column `tx_size_high` over its height. This 1:4 strip reader is // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]), // and it published neither band -- so the block after a 64x16 strip read // the row's init value 64 as its left transform height and took // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware. txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh)); Ok((mode, last_uv_mode, (tx_w, tx_h))) } /// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/ /// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` / /// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike /// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient /// cap, so LUMA needs the same corner truncation [`decode_block`] already /// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx` /// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see /// this function's own charter/report), so both strips read a real 32x32 /// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and /// embed it top-left of a zeroed `bw`x`bh` grid, mirroring /// [`read_plane`]'s `tx_side != side` branch generalized to non-square. /// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated* /// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with /// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/ /// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like /// that function, only the single-transform-unit (`tx_depth == 0`) case is /// supported: a split transform refuses by name rather than guess-decode. #[allow(clippy::too_many_arguments)] fn decode_block_rect64( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, at: (usize, usize), bw: usize, bh: usize, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, enable_filter_intra: bool, allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); let palette_uv_cache = neighbours.palette_uv_cache(at); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, nb_above_mode, nb_left_mode, // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is // correct), CFL must never be offered here -- passing `true` // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile // from this block's very first symbol (lane-sbpart r3 bisect). false, true, bw, bh, enable_filter_intra, neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), allow_screen_content_tools, Some((palette_ctx, &palette_cache)), &palette_uv_cache, r * (SUB / MI), c * (SUB / MI), fctx, )?; if (palette_y.is_some() || palette_uv.is_some()) && !skip { // lane-t900 r34: a non-skip palette block on a superblock-level strip // -- counted so its gate cannot go vacuous (this was a refusal until // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_ // decodes_pixel_exact`). hit!(PALETTE_SB_STRIP_HITS); } let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c); if filter_intra.is_some() { // `filter_intra_size_class_rect` already returns `None` for both // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at // 32 on both axes), so this symbol is never read at this level -- // kept only as the same defensive refusal [`decode_block_rect`] has. return Err(unsupported( "filter intra on a superblock-level HORZ/VERT strip (never expected -- \ av1_filter_intra_allowed_bsize caps at 32x32)", )); } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); let depth = if tx_select { // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and // the 16x4 intra-in-inter strips already do); the key frame's // deblock-grid approximation is only right where those bands were never // written. Measured on the 10-bit 1920x792 128-superblock stream, // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read // `tx_size_cat2` row 1 where libaom reads row 2. let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() { tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx) } else { tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh) }; // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`) // counts `sub_tx_size_map` steps from the block's own max rect // transform down to TX_4X4, minus one -- BLOCK_64X32's chain // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four // steps, so this level's category is 3 (the same one a 64x64 square // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF // here was a wrong-table read of a real symbol. let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}", dec.debug_state().0 ); } d } else { 0 }; // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`]. publish_txfm_bands_if_in_inter( neighbours, (mi_r, mi_c), depth_to_tx_wh(bw, bh, depth), (bw, bh), fctx, ); if depth != 0 { hit!(TX_DEPTH_HITS); // lane-rectsplit r1/r4: the superblock-level strip splits its // transform through the very same per-unit path as its 32x32-level // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1 // measured the old square formula mis-tiling exactly that strip). let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); if bw.max(bh) / bw.min(bh) == 4 { let which = if depth == 1 { &RECT4_SPLIT_DEPTH1_HITS } else { &RECT4_SPLIT_DEPTH2_HITS }; hit_do! { which.with(|c| c.set(c.get() + 1)); } } if crate::envflags::env_flag!("EC_SBPART_DUMP64") { eprintln!( "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \ angle_y={angle_delta_y}" ); } let modes = RectStripModes { skip, mode, angle_delta_y, uv_predict_mode, angle_delta_uv, alpha, filter_intra, smooth_neighbor, smooth_neighbor_uv, palette_y: palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), palette_uv: palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }), }; if palette_y.is_some() || palette_uv.is_some() { hit!(PALETTE_SPLIT_TX_HITS); } decode_rect_split( dec, cdfs, neighbours, (mi_r, mi_c), bw, bh, tx_w, tx_h, &modes, y, u, v, base_q_idx, reduced_tx_set, fctx, )?; // Same early-return palette stamp as [`decode_block_rect`]'s split arm // (lane-palette2 r10): this return skips the fn's own tail, so a // split-tx superblock strip would otherwise leave the above/left // palette arrays holding a dead block's colours. let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors); let (puv_size, puv_colors) = palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early // return skips the fn's own tail, so a SPLIT superblock-level strip // published no TXFM_CONTEXT band and the next block read the row's init // value 64 as its left transform height. Measured on the 10-bit // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The // bands carry the SPLIT unit's size, not the block's. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS); hit!(RECT_PARTITION_HITS); return Ok(()); } let (tx_w, tx_h) = (bw, bh); let (cpx, cpy) = (px / 2, py / 2); let (chroma_w, chroma_h) = (bw / 2, bh / 2); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); if let Some(ref pyv) = palette_y { let buf: Vec = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect(); set_palette_pred(buf, fctx); } let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|puv| { ( puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(), puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), ) }); if skip { push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..bw * bh], None, filter_intra, smooth_neighbor, fctx, ); let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra_rect(1, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..chroma_w * chroma_h], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra_rect(2, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..chroma_w * chroma_h], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); neighbours.record_rect( at, bw, bh, mode, uv_predict_mode, &[ &ZERO_RESIDUAL[..bw * bh], &ZERO_RESIDUAL[..chroma_w * chroma_h], &ZERO_RESIDUAL[..chroma_w * chroma_h], ], ); } else { let around = neighbours.around_rect(at, bw, bh); // LUMA: the coded corner, embedded top-left of the true bw x bh grid // (see this function's own doc comment). A 64-length axis codes only // its low 32 coefficients, so the corner is `min(bw, 32)` x // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16). let (luma_cw, luma_ch) = (bw.min(32), bh.min(32)); let scan32 = default_scan(TX32); if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"); } let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) { let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode); read_coeffs( dec, &mut luma_coding, &scan32, 0, dc_sign_ctx(around[0].2), TxType::DctDct, Some((bw, bh)), )? } else { // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 -> // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders` // (`scan.c`) gives both the very same `default_scan_32x16` / // `default_scan_16x32` the 2:1 sizes use ("Half of the // coefficients of tx64 at higher frequencies are set to zeros. So // tx32's scan order is used"). `get_txsize_entropy_ctx` is // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 + // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a // 512-position eob group) -- BOTH identical to TX_32X16, so the // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is // what `base_ctx_rect` computes at (32, 16). let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 }; let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode); read_coeffs_rect( dec, &mut luma_coding, luma_scan, luma_cw, luma_ch, 0, dc_sign_ctx(around[0].2), TxType::DctDct, )? }; if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}"); } let mut luma_levels = vec![0i32; bw * bh]; for row in 0..luma_ch { luma_levels[row * bw..][..luma_cw] .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]); } { let cur = block_q_idx(fctx); if cur != i32::from(base_q_idx) { hit!(RECT64_QIDX_DRIFT_HITS); } if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}" ); } } let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type, ); push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra, smooth_neighbor, fctx, ); if crate::envflags::env_flag!("EC_SBPART_DUMP64") { let leftcol: Vec = if px > 0 { (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect() } else { vec![] }; eprintln!( "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \ skip={skip} eob_nonzero={} row0={:?} leftcol={:?}", luma_corner.iter().any(|&v| v != 0), &y.data[py * y.width + px..][..bw], leftcol, ); } // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no // corner crop needed (see doc comment). let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); // The chroma plane is never truncated (both axes <= 32 after // subsampling). Under a 1:4 strip it is a true 32x8/8x32: // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 = // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions), // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact // set, and only the scan is new (lane-tx64x16). let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) { (64, 16) => (TxbSet::Chroma16, &SCAN_32X8), (16, 64) => (TxbSet::Chroma16, &SCAN_8X32), (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16), _ => (TxbSet::ChromaRect32x16, &SCAN_16X32), }; let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode); if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}"); } let (u_levels, u_tx_type) = read_coeffs_rect( dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, dc_sign_ctx(around[1].2), TxType::DctDct, )?; if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}"); } { let cur = block_q_idx(fctx); if cur != i32::from(base_q_idx) { hit!(RECT64_QIDX_DRIFT_HITS); } if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}" ); } } let u_residual = dequant_and_inverse_typed_wh( &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type, ); // lane-t900 r34: the UV-palette prediction override, exactly as the // `skip` arm above installs it. The [`PALETTE_PRED`] slot is a // set-then-take, so it must be filled again right before each plane's // own reconstruct; leaving this out of the non-skip arm predicted a // palette block's chroma off its block edges (measured: testsrc2 // 128x128 10-bit cq55 `--tile-columns=1`, the 32x64 strip at px=96 -- // luma exact, both chroma planes wrong over its whole 16x32). if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra_rect(1, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode); if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}"); } let (v_levels, v_tx_type) = read_coeffs_rect( dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, dc_sign_ctx(around[2].2), TxType::DctDct, )?; if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}"); } { let cur = block_q_idx(fctx); if cur != i32::from(base_q_idx) { hit!(RECT64_QIDX_DRIFT_HITS); } if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}" ); } } let v_residual = dequant_and_inverse_typed_wh( &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra_rect(2, cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]); hit!(RECT_COEFF_HITS); } let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors); let (puv_size, puv_colors) = palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx); // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)` // (libaom `decode_token_recon_block`, run for EVERY block of an inter // frame): the above row records `tx_size_wide` over the block's width and // the left column `tx_size_high` over its height. This 1:4 strip reader is // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]), // and it published neither band -- so the block after a 64x16 strip read // the row's init value 64 as its left transform height and took // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); hit!(SB_RECT_HITS); match (bw, bh) { (64, 16) => hit!(SB_RECT4_HORZ_HITS), (16, 64) => hit!(SB_RECT4_VERT_HITS), _ => {} } if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}"); } Ok(()) } /// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus /// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA` /// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever /// it lands away from zero, for gate tests to prove a real stream fired one. fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 { let symbol = dec.symbol(cdf); if symbol != ANGLE_DELTA_ZERO { hit!(ANGLE_DELTA_HITS); } symbol as i32 - ANGLE_DELTA_ZERO as i32 } #[allow(clippy::too_many_arguments)] fn read_intra_mode( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_mode: usize, left_mode: usize, cfl: bool, side: usize, enable_filter_intra: bool, skip_ctx: usize, allow_screen_content_tools: bool, allow_intrabc: bool, // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx` // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]); // `None` at the excluded call sites (the 8x8-leaf path), which still read // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real // decoder reads either way -- but refuse by name the moment it fires, // exactly the old behaviour. palette: Option<(usize, &[u16])>, // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]), // `&[]` at the excluded call sites -- same corner-cut as `palette` above, // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read // `use_palette_y`, not a neighbour lookup). palette_uv_cache: &[u16], mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx, ) -> Result<( bool, usize, i32, usize, i32, Option<(i32, i32)>, Option, Option, Option, )> { let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..." // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for // line against the instrumented aomdec, not just `tell()`. let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); if ec_istep { // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line // (decodemv.c:818), printed at the same point: before the first // mode-info symbol of the block, so a cross-decoder range ladder can // be keyed on the BLOCK, not just on the symbol sequence. eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0); } macro_rules! istep { ($name:literal, $val:expr) => { if ec_istep { let (rng, _) = dec.debug_state(); eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}", $name, $val ); } }; } // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single // point every square caller routes through (see `read_intra_mode_rect`). let cfl = if cfl && side > 32 { hit!(NOCFL_UV_MODE_HITS); false } else { cfl }; // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE // `skip` when `SegIdPreSkip`, and after it otherwise. let (seg_w_mi, seg_h_mi) = (side / 4, side / 4); if seg_id_pre_skip(fctx) { intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx); } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; if trace { eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0); } istep!("skip", skip as i32); if !seg_id_pre_skip(fctx) { intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx); } // spec order (see the comment below on `read_intrabc_info`): `skip`, // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here. maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx); istep!("cdef", 0); // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole // superblock and skips `delta_q` exactly like a 64 one under a 64 root. let whole_sb = side == sb_mi_cur(fctx) as usize * 4; maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx); maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx); istep!("dq", 0); // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an // intra frame whose header set `allow_intrabc`. Actual intra block copy // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`, // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope // draws the line at consuming this one flag symbol and refusing by name // when it fires, so the arithmetic decoder still resyncs for a stream // that merely allows (but never uses) intrabc. if allow_intrabc { let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; if trace { eprintln!("TRACE use_intrabc value={}", use_intrabc as i32); } if use_intrabc { let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side, fctx); if trace { eprintln!("TRACE intrabc dv={dv:?}"); } fctx.intrabc_dv.with(|c| c.set(Some(dv))); hit!(INTRABC_HITS); // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the // moment `is_intrabc_block`: no y/uv mode, angle delta, palette, // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced // `DC_PRED` (which is also what the neighbour mode contexts and // the loop filter then see). return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None)); } } let above_ctx = INTRA_MODE_CTX[above_mode]; let left_ctx = INTRA_MODE_CTX[left_mode]; let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); if trace { eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0); } istep!("mode", mode as i32); let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]); if trace { eprintln!( "TRACE angle_delta value={}", delta + ANGLE_DELTA_ZERO as i32 ); } delta } else { 0 }; istep!("angle_y", angle_delta_y); // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided // here so every `decode_block` caller (64x64 and 128x128 roots included) // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin. let cfl = cfl && side <= 32; let uv_mode = if cfl { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; if trace { eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0); } istep!("uv_mode", uv_mode as i32); let alpha = if cfl && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap // from this lane's directional chroma: a corner block with neither // `above` nor `left` (both `Edges::build`'s no-neighbour fallback, // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched // bug in that fallback this lane's own scope does not cover. Keep it // refused here rather than ship a silently-wrong decode. if (9..=12).contains(&uv_mode) { hit!(SMOOTH_UV_HITS); } // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw, // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes // the `else` branch below and never reads one either way. let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { hit!(DIRECTIONAL_UV_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; istep!("angle_uv", angle_delta_uv); if angle_delta_uv != 0 { hit!(UV_ANGLE_DELTA_HITS); } // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`): // gated by `av1_allow_palette` (blockd.h -- size bound only, // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old // behaviour, bit-identical since a hardcoded ctx-0 read and a real one // read the same CDF row whenever every neighbour really is non-palette). // `palette_uv_mode_ctx` is this block's own just-decided Y palette use, // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a // neighbour lookup at all), so it is exact even at the excluded call // sites once Y decodes real syntax there too. // // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called // inline from `read_palette_mode_info` -- it runs later, from // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`), // after the WHOLE mode-info read for the block, including UV palette // mode_info (`read_palette_mode_info`'s own second half, right below) // and `read_filter_intra_mode_info`. So this branch now only reads // mode/size/colours for both planes (deferring the two colour-index-map // decodes to after `filter_intra`, below) -- r6's range trace pinned // this exact ordering bug (`compare-range-not-tell`: ranges matched // bit-for-bit through the Y colours, diverged only at the old inline // `decode_color_index_map` call). let mut palette_y_pending: Option<(usize, [u16; 8])> = None; let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) { let (mode_ctx, cache) = palette.unwrap_or((0, &[])); if mode == DC_PRED { if trace { let (rng, _) = dec.debug_state(); eprintln!( "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}" ); } } let use_palette_y = mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0; if mode == DC_PRED && trace { let (rng, _) = dec.debug_state(); eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32); } if use_palette_y { let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); if trace { let (rng, _) = dec.debug_state(); eprintln!("TRACE palette_y_size n={n} rng={rng}"); } let colors = read_palette_colors_y(dec, n, cache, fctx); if trace { let (rng, _) = dec.debug_state(); eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]); } palette_y_pending = Some((n, colors)); } // `read_palette_mode_info`'s UV half (decodemv.c:588): read // unconditionally at this bit position whenever `uv_mode == // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's // scope always reconstructs chroma alongside luma (`decode_block` // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref` // is always true here and does not need threading in. let palette_uv_mode_ctx = usize::from(use_palette_y); if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx); palette_uv_pending = Some((n, u_colors, v_colors)); } } // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a // `use_filter_intra` symbol this decoder never read at all until // lane-av1real r10 -- silently skipping it left every bit past a // DC_PRED block at <=32x32 read one symbol short of libaom for the rest // of the tile (the pinned CfL stream's actual bug: partition/skip/mode // matched bit-exact, then `eob_pt` read 5 instead of 6, because this // symbol's bits were never consumed). let mut filter_intra = None; // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO // `use_filter_intra` symbol for a Y-palette block, and reading one here // desynced every screen-content stream from the first palette block on // (it surfaced as a bogus "partition below 8x8" refusal further down the // tile). if mode == DC_PRED && enable_filter_intra && palette_y_pending.is_none() && let Some(class) = filter_intra_size_class(side) { let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0; if trace { eprintln!( "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0, use_filter_intra as i32 ); } istep!("use_filter_intra", use_filter_intra as i32); if use_filter_intra { hit!(FILTER_INTRA_HITS); let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); if trace { eprintln!("TRACE filter_intra_mode value={fi_mode}"); } istep!("filter_intra_mode", fi_mode as i32); filter_intra = Some(fi_mode); } } // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma, // shared U/V map) -- the same order libaom's own loop visits them in. let palette_y = palette_y_pending.map(|(n, colors)| { let map = decode_color_index_map(dec, cdfs, n, side, false); hit!(PALETTE_HITS); if trace { eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]); } PaletteY { size: n, colors, map } }); let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { let map = decode_color_index_map(dec, cdfs, n, side / 2, true); hit!(PALETTE_UV_HITS); if trace { eprintln!( "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}", &u_colors[..n], &v_colors[..n] ); } PaletteUv { size: n, u_colors, v_colors, map } }); Ok(( skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, )) } /// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth /// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary /// intra modes. const UV_CFL_PRED: usize = 13; /// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec /// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol /// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context /// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the /// joint sign the same way. Returns each plane's final signed `alpha_q3` /// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0. fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) { hit!(CFL_BLOCK_HITS); let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32; let sign_u = ((joint_sign + 1) * 11) >> 5; let sign_v = (joint_sign + 1) - 3 * sign_u; let alpha_u = if sign_u == 0 { 0 } else { let ctx_u = (joint_sign + 1 - 3) as usize; let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1; if sign_u == 2 { mag } else { -mag } }; let alpha_v = if sign_v == 0 { 0 } else { let ctx_v = (sign_v * 3 + sign_u - 3) as usize; let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1; if sign_v == 2 { mag } else { -mag } }; (alpha_u, alpha_v) } /// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c): /// the reconstructed luma samples under a `side`-square block, subsampled /// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average /// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`) /// to give the AC values [`cfl_scaled`] scales by alpha. fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec { let cside = side / 2; let mut ac = vec![0i32; cside * cside]; let mut sum = 0i32; for cy in 0..cside { for cx in 0..cside { let (lx, ly) = (px + cx * 2, py + cy * 2); let q3 = (i32::from(y.data[ly * y.width + lx]) + i32::from(y.data[ly * y.width + lx + 1]) + i32::from(y.data[(ly + 1) * y.width + lx]) + i32::from(y.data[(ly + 1) * y.width + lx + 1])) << 1; ac[cy * cside + cx] = q3; sum += q3; } } let num_pel = (cside * cside) as i32; let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros(); ac.iter_mut().for_each(|v| *v -= avg); ac } /// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6 /// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest, /// ties away from zero on the shifted-out sign). fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { let v = alpha_q3 * ac_q3; if v >= 0 { (v + 32) >> 6 } else { -((-v + 32) >> 6) } } /// One plane's reconstruction buffer, `width * height` samples, and the /// prediction/residual reads and writes into it — the decode-side twin of /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly /// (own-edge and reach clamps both), passing what it gathers straight to /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone. /// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written /// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`. /// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of /// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) -- /// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE). /// lane-mc64 r1: the decode-order index the stage dumps below key their file /// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the /// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` -- /// without this every frame overwrote `.f0` and a per-frame bisection silently /// compared the LAST decoded frame (ledger, class stale-output-faked-measurement). #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live fn stage_dump_idx() -> usize { PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1) } fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) { use std::io::Write; // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed // `.f0` name kept only the LAST frame, so a mid-sequence divergence could // not be read out at all. if let Ok(path) = crate::envflags::var(var) && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var))) { for (p, w, h) in [(y, fw, fh), (u, fw.div_ceil(2), fh.div_ceil(2)), (v, fw.div_ceil(2), fh.div_ceil(2))] { for row in 0..h { let mut bytes = Vec::with_capacity(w * 2); for &s in &p.data[row * p.width..][..w] { bytes.extend_from_slice(&s.to_le_bytes()); } let _ = f.write_all(&bytes); } } } } /// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a /// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so /// every frame overwrote the previous one and only the LAST frame survived, /// which silently defeats any per-frame filter-stage bisection. fn dump_stage_idx(var: &str) -> usize { use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; static IDX: OnceLock>> = OnceLock::new(); let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); let e = m.entry(var.to_string()).or_insert(0); let i = *e; *e += 1; i } fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { use std::io::Write; if let Ok(path) = crate::envflags::var(var) && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var))) { for p in [y, u, v] { let narrow: Vec = p.data.iter().map(|&s| s as u8).collect(); let _ = f.write_all(&narrow); } } } /// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no /// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`, /// at most 4095), so a decode that hashes identically under the flag proves /// the output does not depend on the plane buffer's initial content. const PLANE_SENTINEL: u16 = 0xDEAD; /// A frame plane's own backing store, `n` samples, UNINITIALISED. /// /// (lane-picalloc) The SB-padded coding surface is written sample-for-sample /// by the tile walk's reconstruction before anything reads it, so the /// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles /// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at /// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the /// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both /// ways (see the lane report) and the two agree, which is the proof that no /// unwritten sample reaches the output. fn fresh_plane(n: usize) -> Vec { if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") { return vec![PLANE_SENTINEL; n]; } let mut v: Vec = Vec::with_capacity(n); // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the // capacity was just reserved, so the vector owns `n` initialised-or-not // `u16` slots. Every one is written by reconstruction before it is read // (proven by the sentinel gate above). #[allow(unsafe_code)] unsafe { v.set_len(n); } v } #[derive(Clone)] struct PlaneBuf<'a> { data: std::borrow::Cow<'a, [u16]>, width: usize, height: usize, /// The frame's true, decodable extent in this plane's own units — past /// this, samples are the padded coding surface's invented tail, never a /// real decoder's edge or reach reads. true_width: usize, true_height: usize, /// This plane's own tile's top-left pixel origin (spec: intra prediction /// never reaches across a tile boundary even though an earlier-decoded /// tile's real pixels sit right there in the shared buffer) — set via /// [`Self::set_tile_origin`] before each tile's own superblock walk, /// `0` for the single-tile case. lane-tiles r2: only the left/top bound /// is threaded (the two-tile column-split stage 1 fixture's tile always /// ends at the frame's own right/bottom edge); a non-last tile's own /// right/bottom reach bound is still open, tracked in the report. tile_x0: usize, tile_y0: usize, /// lane-tiles r5: this plane's own tile's right/bottom pixel bound /// (exclusive) -- a non-last tile column/row's own reach must stop at /// its own SB-aligned tile boundary. `width`/`height` (this plane's /// full padded extent) for the single-tile/last-tile case, matching the /// old unclipped behaviour exactly. tile_x1: usize, tile_y1: usize, } /// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/ /// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this /// frame's own `ref_frame_idx` names a DPB slot that has a picture in it /// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already /// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/ /// `ALTREF2`/`ALTREF`). impl PlaneBuf<'_> { /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/ /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0` /// are already in this plane's own units (luma pixels for `y`, chroma /// pixels — halved — for `u`/`v`). fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) { self.tile_x0 = x0; self.tile_y0 = y0; self.tile_x1 = x1; self.tile_y1 = y1; } fn edges( &self, x: usize, y: usize, side: usize, reach: Reach, ) -> (Option>, Option>, Option) { let own_across = x + side.min(self.true_width.saturating_sub(x)); let across = if reach.above_right { own_across + side.min(self.true_width.saturating_sub(own_across)) } else { own_across } .min(self.width) .min(self.tile_x1); let own_down = y + side.min(self.true_height.saturating_sub(y)); let down = if reach.below_left { own_down + side.min(self.true_height.saturating_sub(own_down)) } else { own_down } .min(self.height) .min(self.tile_y1); let above = (y > self.tile_y0 && across > x) .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec()); let left = (x > self.tile_x0 && down > y).then(|| { (y..down) .map(|row| self.data[row * self.width + x - 1]) .collect::>() }); let corner = (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]); (above, left, corner) } /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1): /// the above/left reach each extend by their OWN axis (`bw` across, /// `bh` down), not one shared `side`. fn edges_rect( &self, x: usize, y: usize, bw: usize, bh: usize, reach: Reach, ) -> (Option>, Option>, Option) { let own_across = x + bw.min(self.true_width.saturating_sub(x)); let across = if reach.above_right { own_across + bw.min(self.true_width.saturating_sub(own_across)) } else { own_across } .min(self.width) .min(self.tile_x1); let own_down = y + bh.min(self.true_height.saturating_sub(y)); let down = if reach.below_left { own_down + bh.min(self.true_height.saturating_sub(own_down)) } else { own_down } .min(self.height) .min(self.tile_y1); let above = (y > self.tile_y0 && across > x) .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec()); let left = (x > self.tile_x0 && down > y).then(|| { (y..down) .map(|row| self.data[row * self.width + x - 1]) .collect::>() }); let corner = (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]); if matches!((bw, bh), (16, 8) | (8, 16)) { hit!(RECT_STRIP_PRED_HITS); if across > own_across || down > own_down { hit!(RECT_STRIP_REACH_HITS); } } (above, left, corner) } /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1), /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own /// already-rect-capable `(bw, bh)` pair. #[allow(clippy::too_many_arguments)] #[track_caller] fn reconstruct_rect( &mut self, x: usize, y: usize, bw: usize, bh: usize, mode: usize, angle_delta: i32, reach: Reach, residual: &[i32], cfl: Option<(i32, &[i32])>, filter_intra: Option, smooth_neighbor: bool, // lane-wave1 step (i): the palette/intrabc prediction override, taken // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather // than by this replay. pred: Option>, fctx: &crate::decode::FrameCtx, ) { // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override // (lane-palette2 r4): a palette block's prediction is the // reconstructed colour-index map, needing no edge pixels at all. let prediction = if let Some(buf) = pred { buf } else { let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach); if crate::envflags::env_flag!("EC_DEBUG_EDGES") { eprintln!( "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}", above.as_ref().map(|a| (a.len(), a[0])), left.as_ref().map(|l| l.len()), left.as_ref().map(|l| l[0]), self.tile_x0, self.tile_y0, self.true_width, self.true_height ); } let mut prediction = vec![0u16; bw * bh]; if let Some(fi_mode) = filter_intra { crate::intra::predict_filter_intra( fi_mode, above.as_deref(), left.as_deref(), corner, bw, bh, &mut prediction, fctx, ); } else { let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get); predict( mode as u8, angle_delta, above.as_deref(), left.as_deref(), corner, bw, bh, enable_edge_filter, smooth_neighbor, &mut prediction, fctx, ); } prediction }; // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). if crate::envflags::env_flag!("EC_PRED") { let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); let row0: Vec = prediction[..bw.min(8)].to_vec(); let col0: Vec = (0..bh.min(8)).map(|r| prediction[r * bw]).collect(); eprintln!( "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor) ); } let residual = dense_residual(residual, bw * bh); for row in 0..bh { // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame // whose padded width is not superblock aligned hangs past it. if y + row >= self.height { break; } for col in 0..bw { if x + col >= self.width { break; } let idx = row * bw + col; let mut base = i32::from(prediction[idx]); if let Some((alpha_q3, ac_q3)) = cfl { base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx)); } let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16; self.data.to_mut()[(y + row) * self.width + x + col] = sample; } } } /// Predicts under `mode` then adds `residual` (side*side, raster), /// writing the clamped reconstruction back into the plane at `(x, y)`. /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block), /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual /// order (cfl.c). #[track_caller] fn reconstruct( &mut self, x: usize, y: usize, side: usize, mode: usize, angle_delta: i32, reach: Reach, residual: &[i32], cfl: Option<(i32, &[i32])>, filter_intra: Option, // `smooth_neighbor` (spec `get_intra_edge_filter_type` / // libaom `get_filt_type`): true when the block's above OR left // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`). // Callers pass their own plane's neighbour-mode check // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its // callers until a smooth/paeth `uv_mode` can reach this call at all // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which // keeps `false` exact for chroma without this fn needing to know why. smooth_neighbor: bool, // lane-wave1 step (i): the palette/intrabc prediction override, taken // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather // than by this replay. pred: Option>, fctx: &crate::decode::FrameCtx, ) { // A palette block's own [`PALETTE_PRED`] override (lane-palette r2) // takes priority over `predict()`/`predict_filter_intra` entirely -- // palette prediction needs no edge pixels at all. let prediction = if let Some(buf) = pred { buf } else { let (above, left, corner) = self.edges(x, y, side, reach); let mut prediction = vec![0u16; side * side]; if let Some(fi_mode) = filter_intra { crate::intra::predict_filter_intra( fi_mode, above.as_deref(), left.as_deref(), corner, side, side, &mut prediction, fctx, ); } else { // `enable_intra_edge_filter` is the sequence header's own flag // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs` // call, never per-block) -- threading it through every // `read_plane`/`decode_block`/`decode_leaf8` call would touch two // dozen sites for a value that never changes mid-decode, so it // rides a thread-local instead (this decoder is single-threaded // per stream). let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get); predict( mode as u8, angle_delta, above.as_deref(), left.as_deref(), corner, side, side, enable_edge_filter, smooth_neighbor, &mut prediction, fctx, ); } prediction }; // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). if crate::envflags::env_flag!("EC_PRED") { let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); let row0: Vec = prediction[..side.min(8)].to_vec(); let col0: Vec = (0..side.min(8)).map(|r| prediction[r * side]).collect(); eprintln!( "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor) ); } let residual = dense_residual(residual, side * side); for row in 0..side { // lane-sb128c r8: libaom's frame buffer is superblock // aligned; ours is padded to 32 (`block_grid`), so a 64x64 // transform unit of a 128x64 block at the BOTTOM frame edge // can hang past the last padded row (1920x792: a unit at // y=768 wants 832 rows of an 800-row buffer, which panicked // the film's key frames). Those samples are outside the // frame: never output, and no block below ever references // them. if y + row >= self.height { break; } for col in 0..side { if x + col >= self.width { break; } let idx = row * side + col; let mut base = i32::from(prediction[idx]); if let Some((alpha_q3, ac_q3)) = cfl { base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx)); } let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16; self.data.to_mut()[(y + row) * self.width + x + col] = sample; } } } } /// Reads one plane's transform block, reconstructs it into `plane` at /// `(x, y)`/`side`, and records what it leaves behind in `neighbours`. #[allow(clippy::too_many_arguments)] fn read_plane( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, set: TxbSet, scan: &[u16], plane_idx: usize, around: (bool, bool, i32), // The block's own luma mode — [`crate::tile::write_block_planes`] passes // it for every plane's `txb` lookup (it is what an intra transform type's // CDF is indexed by, spec 9.3), never the plane's own predicted mode. tx_mode: usize, predict_mode: usize, angle_delta: i32, reach: Reach, // lane-wave1 step (i): unread -- this reader records its write // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow // stays in the signature so every call site still proves the plane is // exclusively held while its coefficients are parsed. _plane: &mut PlaneBuf<'static>, x: usize, y: usize, side: usize, tx_side: usize, base_q_idx: u8, cfl: Option<(i32, CflSrc)>, filter_intra: Option, // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is // smaller than its own block (spec `get_txb_ctx_general`'s // `plane_bsize != tx_size` branch), carrying the already-looked-up // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours // formula below. luma_skip_ctx: Option, // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check. smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, ) -> Result { let skip_ctx = if plane_idx == 0 { luma_skip_ctx.unwrap_or(0) } else { // libaom `get_txb_ctx`: a chroma unit's context is // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the // plane block is bigger than the transform. Our chroma tables hold the // offset-7 rows first, so the caller adds 3 for the bigger-block case // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3). usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0) }; // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`, // not by the block's ordinary `mode` (which is always DC_PRED whenever // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no // filter-intra in AV1). let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode }; let mut coding = cdfs.txb(set, tx_mode); // Luma's `default_tx_type` is only a fallback for the sizes whose // `TxbSet` carries no symbol at all (32-point and up), which the spec // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is // *never* its own coded symbol (`coding.tx_type` is always `None` for // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of // the plane's own predicted mode (`default_intra_tx_type`) -- except // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8` // and `Chroma16` never hit this — every value `default_intra_tx_type` can // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing // narrows there — only `Chroma32` and up do). let default_tx_type = if plane_idx == 0 || side >= 32 { TxType::DctDct } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) { // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for // `av1_get_tx_type`, so chroma inherits luma's coded type (the // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY` // clamp at `tx_size_sqr_up >= TX_32X32`, matching // [`read_inter_plane`]'s own `side < 32` guard). inherited } else { default_intra_tx_type(predict_mode as u8) }; let (grid, tx_type) = read_coeffs( dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2), default_tx_type, None, )?; note_chroma_class1(plane_idx, tx_type); if plane_idx == 0 { fctx.luma_tx_type.with(|c| c.set(tx_type)); } // A 64x64 luma block's transform covers the whole 64x64 area, but only its // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32` // guard also assumes. // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse` // wants the true `side x side` transform, with dqDenom (spec 7.12.3) // keyed by that true size, not the coded corner's -- so the corner // goes into the top-left of a `side`-sized grid, not the reverse. let levels = extend_corner(grid, tx_side, tx_side, side, side); let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx); let tx = TxParams { w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type, stride: 0, }; if crate::envflags::env_flag!("EC_AV1_TRACE") { let residual = tx.run(&levels); eprintln!( "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels, ); } push_intra_tx( plane_idx, x, y, side, side, false, predict_mode, angle_delta, reach, tx, &levels, cfl, filter_intra, smooth_neighbor, fctx, ); // `record`'s neighbour state only reads whether *the coded grid* (not the // residual) has nonzero entries, so the levels this function already // built are what it wants back -- both arms of the old `tx_side == side` // branch returned exactly that, one of them through a full `to_vec` copy // of the grid per intra transform unit (lane-coefbuf). Ok(levels) } /// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its /// three planes, reconstructing them into `y`/`u`/`v` and updating /// `neighbours`. #[allow(clippy::too_many_arguments)] fn decode_block( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, at: (usize, usize), side: usize, luma_set: TxbSet, chroma_set: TxbSet, luma_tx: usize, chroma_tx: usize, scans: (&[u16], &[u16]), cfl: bool, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, enable_filter_intra: bool, allow_screen_content_tools: bool, allow_intrabc: bool, scan32: &[u16], scan16: &[u16], scan8: &[u16], scan4: &[u16], tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); let palette_uv_cache = neighbours.palette_uv_cache(at); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode( dec, cdfs, nb_above_mode, nb_left_mode, cfl, side, enable_filter_intra, neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), allow_screen_content_tools, allow_intrabc, Some((palette_ctx, &palette_cache)), &palette_uv_cache, r * (SUB / MI), c * (SUB / MI), fctx, )?; if at_tile_left && palette_y.is_some() { hit!(PALETTE_TILE_LEFT_HITS); } let intrabc_dv = fctx.intrabc_dv.with(|c| c.take()); // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED` // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the // actual chroma-from-luma correlation, same as this decoder always did. let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \ angle_delta_uv={angle_delta_uv}" ); } let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra // block, skipped or not. `logical_tx` is what the loop filter's edge // lookup and the next block's own `tx_size_context` want (the *nominal* // transform size -- 64 even for the 64x64 corner-scanned case, spec // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side, // which only differs from it at that one corner case. // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth` // symbol on `allowSelect = !skip || !is_inter`, and libaom's // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED // intrabc block reads NO tx-size symbol at all -- it takes // `maxRectTxSize` -- while every ordinary skipped intra block does read // one. Reading it anyway consumed a symbol libaom never wrote and desynced // the tile from that block on (class `equal-range-means-unread`). // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition // tree instead (`read_var_tx_size`), the same syntax the inter block path // has always read -- libaom's `parse_decode_block` dispatches on // `is_inter_block`, so both branches of `read_block_tx_size` treat an // intrabc block as inter. let intrabc_skip_tx = intrabc_dv.is_some() && skip; let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip; let intrabc_leaves = if intrabc_vartx { let max_tx = side.min(64); // `max_block_wide`/`max_block_high`: the frame's own mi grid // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the // right/bottom edge reads no split symbol for the units outside it. let mi_cols = 2 * y.true_width.div_ceil(8); let mi_rows = 2 * y.true_height.div_ceil(8); let side_mi = side / MI; let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c)); let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r)); let mut leaves = Vec::new(); for row in (0..side_mi).step_by(max_tx / MI) { for col in (0..side_mi).step_by(max_tx / MI) { read_var_tx_size( dec, cdfs, neighbours, (mi_r, mi_c), side, (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves, ); } } hit!(INTRABC_VARTX_HITS); // The luma reconstruct loop below is a UNIFORM grid of one square // transform (the intra `tx_depth` shape), so a tree that resolved to // mixed leaf sizes is refused by name rather than reconstructed at the // wrong stride. let uniform = leaves .first() .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)); if !uniform { return Err(unsupported( "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes", )); } Some(leaves[0].2) } else { None }; let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves { (tx, if tx == 64 { 32 } else { tx }) } else if tx_select && !intrabc_skip_tx { let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None); (resolved, if resolved == 64 { 32 } else { resolved }) } else { // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is // TX_64X64, so a 128x128 block is always FOUR luma transform units // even with `tx_select` off -- the TU loop below, never the // single-unit path. (side.min(64), luma_tx) }; if tx_select && logical_tx < side && uv_mode != DC_PRED { hit!(SQ_CHROMA_TX_HITS); } let luma_set = if tx_select { txbset_for(logical_tx, reduced_tx_set) } else { luma_set }; let luma_set = if intrabc_dv.is_some() { txbset_for_inter(logical_tx, reduced_tx_set) } else { luma_set }; let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4); let reach = Reach::of(side, px, py, y.width, y.height, fctx); let (cpx, cpy) = (px / 2, py / 2); let chroma_side = side / 2; // spec 7.11.3.4 with `use_intrabc`: the reference is the *current* // frame's own pre-loop-filter reconstruction (all loop filters are off // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel // block vector, with the BILINEAR kernel libaom forces for intrabc -- // luma is a straight copy, chroma lands half-pel whenever the luma DV is // odd, which is exactly what the bilinear taps then interpolate. flush_recon(fctx, y, u, v); let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| { let mut yb = vec![0u16; side * side]; mc::predict_with_filter( &y.data, y.width, y.true_width, y.true_height, mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true), side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx, ); let mut ub = vec![0u16; chroma_side * chroma_side]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false), chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; chroma_side * chroma_side]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false), chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx, ); (yb, ub, vb) }); // A palette-Y block's own prediction is the reconstructed colour-index // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it // to [`PlaneBuf::reconstruct`]'s next call rather than threading a // parameter through this function's dozen `y.reconstruct`/`read_plane` // sites. A split luma transform (`tx_select && logical_tx != side`) // would need the map sliced per-TU -- untested against a real // `--enable-palette=1` stream this round, so refuse by name rather than // guess at the slicing (charter's own named-acceptable fallback). let palette_y_buf: Option> = palette_y.as_ref().map(|py| { py.map .iter() .map(|&idx| py.colors[idx as usize]) .collect() }); // lane-t900 r32: the intrabc luma prediction rides the very same // whole-block override slot, so the multi-TU loop below windows it per // transform unit exactly like a palette map -- setting it once up front // handed the whole `side`x`side` buffer to the FIRST unit and left every // later one predicting off block edges (the var-tx tree above is what // first makes `logical_tx < side` reachable for an intrabc block). let palette_y_buf = match &intrabc_bufs { Some((yb, _, _)) => Some(yb.clone()), None => palette_y_buf, }; // With one luma transform unit the whole `side`x`side` map is the // prediction; with several (`logical_tx != side`) each unit takes its own // `logical_tx`-sized window of that same map, set fresh inside the TU loop // below (lane-palette2 r7) -- setting the full-block buffer here would be // taken by the FIRST unit and indexed at the wrong stride. if let Some(buf) = &palette_y_buf && logical_tx == side { set_palette_pred(buf.clone(), fctx); } // A UV-palette block's own chroma prediction override (lane-palette2 r1), // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each // plane's own `reconstruct`/`read_plane` call below (never both planes at // once), since Y's own set-then-take already emptied the slot by the time // either of these run. let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|puv| { ( puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(), puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), ) }); // The chroma half of the intrabc prediction rides the same per-plane // override slot the UV-palette buffers do (set fresh before each plane's // own `reconstruct`/`read_plane` call below). let palette_uv_bufs = match &intrabc_bufs { Some((_, ub, vb)) => Some((ub.clone(), vb.clone())), None => palette_uv_bufs, }; if skip { // A skipped block codes no residual syntax at all (spec 5.11.34): // straight prediction, on every plane. // // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it // is skipped (only an INTER skip forces the largest transform), and // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units // already written left/above of it inside this same block. Predicting // the whole `side`x`side` at once gives a different (uniformly off by // ~1) answer, which is exactly the residue this lane was chasing. // The palette/intrabc override path keeps the single-call shape (its // per-TU windowing is the non-skip loop's own `palette_y_buf` slice, // untested for skip and unreachable in these streams). // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the // per-unit prediction is keyed on the transform being smaller than // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's // narrower meaning (a READ split tx depth). let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none(); if split_tx_skip { if tx_select { hit!(SKIP_SPLIT_TX_HITS); } let n_axis = side / logical_tx; for tu_row in 0..n_axis { for tu_col in 0..n_axis { let tu_px = px + tu_col * logical_tx; let tu_py = py + tu_row * logical_tx; if tu_px >= y.true_width || tu_py >= y.true_height { continue; } let tu_reach = tu_reach( side, side, tu_col * logical_tx, tu_row * logical_tx, logical_tx, reach, px, py, y.width, y.height, fctx, ); push_intra(0, tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_reach, &ZERO_RESIDUAL[..logical_tx * logical_tx], None, filter_intra, smooth_neighbor, fctx, ); } } } else { push_intra(0, px, py, side, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..side * side], None, filter_intra, smooth_neighbor, fctx, ); } let ac = alpha.map(|_| cfl_src(px, py, side)); let cn = (chroma_side / chroma_tx).max(1); for cu_row in 0..cn { for cu_col in 0..cn { let luma_span = chroma_tx * 2; let cu_r = if cn == 1 { reach } else { tu_reach( side, side, cu_col * luma_span, cu_row * luma_span, luma_span, reach, px, py, y.width, y.height, fctx, ) }; let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra(1, cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &ZERO_RESIDUAL[..chroma_tx * chroma_tx], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra(2, cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &ZERO_RESIDUAL[..chroma_tx * chroma_tx], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); } } let luma_grid = vec![0i32; side * side]; let u_grid = vec![0i32; chroma_side * chroma_side]; let v_grid = vec![0i32; chroma_side * chroma_side]; neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); } else if logical_tx == side { // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`. // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so // that arm was redundant -- and wrong at 128, where // `max_txsize_rect_lookup` caps the block's transform at 64 and the // block is four units whether or not `tx_select` is on. // A single luma transform unit -- the old path, unchanged (including // the 64x64 corner case, `logical_tx == side == 64` with // `coeff_tx_side == 32`). let around = neighbours.around(at, side); let luma_grid = read_plane( dec, cdfs, luma_set, luma_scan, 0, around[0], mode, mode, angle_delta_y, reach, y, px, py, side, coeff_tx_side, base_q_idx, None, filter_intra, None, smooth_neighbor, fctx, )?; let ac = alpha.map(|_| cfl_src(px, py, side)); // Armed for exactly this block's two chroma reads (see // [`INTRABC_CHROMA_TX`]); the luma call above just set // [`LUMA_TX_TYPE`] to the type it coded. if intrabc_dv.is_some() { fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get)))); } if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } let u_grid = read_plane( dec, cdfs, chroma_set, scans.1, 1, around[1], mode, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, chroma_side, chroma_tx, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}", &u.data[cpy * u.width + cpx..][..chroma_side] ); } if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } let v_grid = read_plane( dec, cdfs, chroma_set, scans.1, 2, around[2], mode, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, chroma_side, chroma_tx, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; fctx.intrabc_chroma_tx.with(|c| c.set(None)); neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); } else { // Several luma transform units, raster order (spec // `transform_block`'s loop): the block's resolved transform is // genuinely smaller than its own side, so each tile of it predicts // and codes independently, its own context read fresh off whatever // the earlier tiles in this same block already wrote -- the same // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf. let n_axis = side / logical_tx; let cn = (chroma_side / chroma_tx).max(1); // libaom's transform-block loop is over 64x64 luma "mu" chunks // (`decode_token_recon_block`: `mu_blocks_wide/high` = // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk // before moving to the next one. Below 128 a block is a single chunk, // so this is byte-for-byte the all-luma-then-all-chroma order that has // always run; at 128 the four quadrants interleave Y,U,V per quadrant // and reading all four luma units first desyncs the tile at the second // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`). let nchunk = (side / 64).max(1); // `cn > 1` means the uv plane block is larger than the uv transform, // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10. let chroma_ctx_offset = if cn > 1 { Some(3) } else { None }; let tpc = (n_axis / nchunk).max(1); let cpc = (cn / nchunk).max(1); let mut last_grids = [Grid::Zero(0), Grid::Zero(0)]; let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new(); for ch_row in 0..nchunk { for ch_col in 0..nchunk { for tu_row in ch_row * tpc..(ch_row + 1) * tpc { for tu_col in ch_col * tpc..(ch_col + 1) * tpc { let tu_mi = ( mi_r + tu_row * (logical_tx / MI), mi_c + tu_col * (logical_tx / MI), ); let tu_px = px + tu_col * logical_tx; let tu_py = py + tu_row * logical_tx; // Same libaom clip as `decode_rect_split`'s loop above; a // square block only hangs off the frame when the frame's mi // dimensions are odd at the block's own level. if tu_px >= y.true_width || tu_py >= y.true_height { continue; } let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0]; // A transform unit inside a block is NOT a block at that // position (lane-palette2 r12): `Reach::of` granted the // top-right 8x8 unit of a 16x16 D203 block bottom-left // pixels libaom refuses outright (`col_off > 0`), which is // the diagonal wedge seed 46 reconstructed wrong. let tu_reach = tu_reach( side, side, tu_col * logical_tx, tu_row * logical_tx, logical_tx, reach, px, py, y.width, y.height, fctx, ); // This transform unit's own bsize (`logical_tx`) is smaller // than the block it sits in (`side`), so `txb_skip_ctx` is // the neighbour-magnitude table, not the lone-TU 0 (spec // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch). let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI); if let Some(buf) = &palette_y_buf { hit!(PALETTE_SPLIT_TX_HITS); let mut window = vec![0u16; logical_tx * logical_tx]; for row in 0..logical_tx { let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx; window[row * logical_tx..][..logical_tx] .copy_from_slice(&buf[src..][..logical_tx]); } set_palette_pred(window, fctx); } let tu_grid = read_plane( dec, cdfs, luma_set, luma_scan, 0, tu_around, mode, mode, angle_delta_y, tu_reach, y, tu_px, tu_py, logical_tx, // The unit's own COEFFICIENT grid, half its side at // TX_64X64 (a 64-point transform codes nothing past 32); // identical to `logical_tx` at every smaller size // (lane-sb128b r1). coeff_tx_side, base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE tu_bitpos mi=({},{}) tell={}", tu_mi.0, tu_mi.1, dec.debug_bitpos() ); } neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid); } } // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where // this still runs after every luma unit of the block. let ac = alpha.map(|_| cfl_src(px, py, side)); // The block's uv plane block is `chroma_side` across but its uv // transform is `chroma_tx` (`av1_get_max_uv_txsize` = // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`): // identical at every size up to 64x64, but a 128x128 block's 64x64 uv // plane block adjusts TX_64X64 down to TX_32X32, so each plane is // FOUR units (lane-sb128b r2) -- one per mu chunk. for cu_row in ch_row * cpc..(ch_row + 1) * cpc { for cu_col in ch_col * cpc..(ch_col + 1) * cpc { // The chroma context arrays are indexed in LUMA mi, so this // unit's anchor is its own luma quadrant: `chroma_tx` chroma // pixels span `2 * chroma_tx` luma ones. let luma_span = chroma_tx * 2; let cu_mi = ( mi_r + cu_row * (luma_span / MI), mi_c + cu_col * (luma_span / MI), ); let cu_around = neighbours.around_mi(cu_mi, luma_span); let cu_reach = if cn == 1 { reach } else { tu_reach( side, side, cu_col * luma_span, cu_row * luma_span, luma_span, reach, px, py, y.width, y.height, fctx, ) }; let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } let u_grid = read_plane( dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode, uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, chroma_ctx_offset, smooth_neighbor_uv, fctx, )?; if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } let v_grid = read_plane( dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode, uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, chroma_ctx_offset, smooth_neighbor_uv, fctx, )?; if cn > 1 { hit!(CHROMA_SPLIT_TX_HITS); // Immediately, so the NEXT unit of this same block reads // this one's coefficient context (libaom's chroma // `txb_skip_ctx` for the second quadrant is 11, i.e. base // 1 from this left neighbour -- measured against aomdec). // The same writes are replayed after `record_split_luma` // below, which would otherwise clobber them whole-block. neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid); neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid); units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone())); } last_grids = [u_grid, v_grid]; } } } } // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma // context write; at `cn > 1` the per-unit writes above are what the // next block reads, so they run after this (last writer wins). neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]); for (cu_mi, luma_span, u_grid, v_grid) in &units { neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid); neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid); } } // Unconditional, `size == 0` for a non-palette block: clears any stale // neighbour palette state the same way [`Neighbours::record`] always // overwrites `above_mode`/`left_mode` regardless of this block's own mode // (the split-luma-TU branch above always refuses before reaching here // when `palette_y` is `Some`, so it is never live for that branch). let (py_size, py_colors) = palette_y .as_ref() .map_or((0, [0u16; 8]), |p| (p.size, p.colors)); neighbours.record_palette_y(at, side, py_size, py_colors); let (puv_size, puv_colors) = palette_uv .as_ref() .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); neighbours.record_palette_uv(at, side, puv_size, puv_colors); neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip); neighbours.fill_lf_grid( (r * (SUB / MI), c * (SUB / MI)), side / MI, logical_tx as u8, 0, fctx, ); // lane-t900 r32: libaom runs `set_txfm_ctxs` at the end of EVERY // `decode_block`, key frames included, and the intrabc var-tx read above // (`txfm_partition_ctx`) is the only intra-path reader of those bands -- // left at `TXFM_CTX_INIT` it would take the split symbol off the wrong CDF // row. Armed by the frame's own `allow_intrabc` so every other key frame // (whose readers use the deblock-grid approximation) is untouched. if allow_intrabc { set_txfm_ctxs( neighbours, (mi_r, mi_c), logical_tx, side / MI, side / MI, skip && intrabc_dv.is_some(), ); } record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, fctx); Ok(()) } thread_local! { /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128 /// root's HORZ arm, and 64x128 ones at its VERT arm. pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units, /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read. pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; /// lane-inter128intra r1: the same shapes decoded on the INTER block path /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an /// inter frame) -- (128x64, 64x128). pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still /// handed back var-tx leaves, so the per-transform-unit luma publication /// loop never ran and the block has to clear its own luma coefficient /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate /// non-vacuous. pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta. pub fn skip_vartx_luma_reset_hits() -> usize { SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get) } /// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta. pub(crate) fn intra128_in_inter_hits() -> [usize; 2] { INTRA128_IN_INTER_HITS.with(std::cell::Cell::get) } /// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] / /// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta. pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) { ( INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get), INTRA_SB128_VERT_HITS.with(std::cell::Cell::get), INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get), ) } /// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or /// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is /// `decode_inter_block`'s own rect path). /// /// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per /// transform unit, with the 128-specific geometry: /// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit /// is SQUARE and there are at least two of them -- depth 0: 64x64 x2, /// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts /// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the /// same CDF a 64x64 square block reads). /// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size( /// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's /// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per /// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of /// a chunk before moving to the next (the interleave lane-sb128b r3 /// measured at the 128x128 NONE root). /// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so /// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3). /// No CfL, no filter intra (both cap at 32x32) and no palette /// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode /// reader's own size gates already say so, and the guard below is defensive. #[allow(clippy::too_many_arguments)] fn decode_block_128rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, at: (usize, usize), bw: usize, bh: usize, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, enable_filter_intra: bool, allow_screen_content_tools: bool, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); let palette_uv_cache = neighbours.palette_uv_cache(at); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, nb_above_mode, nb_left_mode, // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the // 13-symbol no-CFL CDF here, never the 14-symbol one. false, true, bw, bh, enable_filter_intra, neighbours.skip_txfm_ctx(mi_r, mi_c), allow_screen_content_tools, Some((palette_ctx, &palette_cache)), &palette_uv_cache, mi_r, mi_c, fctx, )?; if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() { return Err(unsupported( "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \ their size gates caps at 64x64 or below, so none of these symbols exists there)", )); } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c); // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc). let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some(); let depth = if tx_select { // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads // the real `TXFM_CONTEXT` bands, and compares them against // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for // every 128-axis block, hence the `min(64)`. let ctx = if in_inter { tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx) } else { tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh) }; dec.symbol(&mut cdfs.tx_size_cat3[ctx]) } else { 0 }; if depth != 0 { hit!(TX_DEPTH_HITS); } hit_do! { INTRA_SB128_DEPTH_HITS.with(|c| { let mut h = c.get(); h[depth.min(2)] += 1; c.set(h); }); } let logical_tx = 64 >> depth; // A 64-point transform codes nothing past its low 32 coefficients. let coeff_tx_side = logical_tx.min(32); let luma_set = txbset_for(logical_tx, reduced_tx_set); let luma_scan = default_scan(coeff_tx_side); let chroma_tx = 32; let chroma_scan = default_scan(chroma_tx); let (cpx, cpy) = (px / 2, py / 2); let (chroma_w, chroma_h) = (bw / 2, bh / 2); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); let (nch_x, nch_y) = (bw / 64, bh / 64); // One 32x32 chroma unit per mu chunk, per plane. debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y)); let tpc = 64 / logical_tx; let zero_tu = vec![0i32; logical_tx * logical_tx]; let zero_cu = vec![0i32; chroma_tx * chroma_tx]; let mut last_grids = [Grid::Zero(0), Grid::Zero(0)]; let mut units: Vec<((usize, usize), Grid, Grid)> = Vec::new(); for ch_row in 0..nch_y { for ch_col in 0..nch_x { for tu_row in ch_row * tpc..(ch_row + 1) * tpc { for tu_col in ch_col * tpc..(ch_col + 1) * tpc { let tu_mi = ( mi_r + tu_row * (logical_tx / MI), mi_c + tu_col * (logical_tx / MI), ); let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx); // libaom clips the transform loop to // `max_blocks_wide/high`: a unit whose top-left sample is // outside the frame is never coded. if tu_px >= y.true_width || tu_py >= y.true_height { continue; } // Edge availability of a unit INSIDE a block, with the // 128 geometry -- `has_top_right` is false for a block // whose largest side is > 64, which [`Reach::of_rect`] // already answered for the block and [`tu_reach`] carries // down to the units on its own top row. let tu_r = tu_reach( bw, bh, tu_col * logical_tx, tu_row * logical_tx, logical_tx, reach, px, py, y.width, y.height, fctx, ); if skip { push_intra(0, tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None, None, smooth_neighbor, fctx, ); neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu); continue; } // The unit is smaller than its block, so `txb_skip_ctx` // is the neighbour-magnitude table, never the lone-TU 0. let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI); let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0]; let tu_grid = read_plane( dec, cdfs, luma_set, &luma_scan, 0, tu_around, mode, mode, angle_delta_y, tu_r, y, tu_px, tu_py, logical_tx, coeff_tx_side, base_q_idx, None, None, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid); } } // The chroma context arrays are indexed in LUMA mi, so this // unit's anchor is its own 64x64 mu chunk. let luma_span = chroma_tx * 2; let cu_mi = ( mi_r + ch_row * (luma_span / MI), mi_c + ch_col * (luma_span / MI), ); let cu_r = tu_reach( bw, bh, ch_col * luma_span, ch_row * luma_span, luma_span, reach, px, py, y.width, y.height, fctx, ); let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx); if skip { push_intra(1, cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None, None, smooth_neighbor_uv, fctx, ); push_intra(2, cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None, None, smooth_neighbor_uv, fctx, ); continue; } let cu_around = neighbours.around_mi(cu_mi, luma_span); let u_grid = read_plane( dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode, angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None, Some(3), smooth_neighbor_uv, fctx, )?; let v_grid = read_plane( dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode, angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None, Some(3), smooth_neighbor_uv, fctx, )?; hit!(CHROMA_SPLIT_TX_HITS); // Immediately, so the NEXT unit of this same block reads this // one's coefficient context; replayed after `record_split_luma_rect` // below, which would otherwise clobber them whole-block. neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid); neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid); units.push((cu_mi, u_grid.clone(), v_grid.clone())); last_grids = [u_grid, v_grid]; } } if skip { neighbours.record_rect( at, bw, bh, mode, uv_predict_mode, &[ &ZERO_RESIDUAL[..bw * bh], &ZERO_RESIDUAL[..chroma_w * chroma_h], &ZERO_RESIDUAL[..chroma_w * chroma_h], ], ); } else { neighbours.record_split_luma_rect( at, bw, bh, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]], ); for (cu_mi, u_grid, v_grid) in &units { neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid); neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid); } } // No palette exists at this size; the unconditional stamp clears any // stale neighbour palette state, as every other block path does. neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]); neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); neighbours.fill_lf_grid_rect( (mi_r, mi_c), bw / MI, bh / MI, logical_tx as u8, logical_tx as u8, 0, fctx, ); if in_inter { // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an // inter frame, intra ones included: an intra block stamps its // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands. // A key frame has no var-tx tree and its readers use the deblock grid, // so this is the inter path's alone. txfm_partition_update_rect( neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh), ); hit_do! { INTRA128_IN_INTER_HITS.with(|c| { let mut h = c.get(); h[usize::from(bw < bh)] += 1; c.set(h); }); } } else if bw > bh { hit!(INTRA_SB128_HORZ_HITS); } else { hit!(INTRA_SB128_VERT_HITS); } Ok(()) } /// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring /// [`crate::tile::write_leaf8`]: its intra-mode context comes from the /// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid), /// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's /// just-decoded mode, not the enclosing slot's stale one, is the true /// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info /// units, which is what its coefficient context (finer than [`SUB`]) is read /// at. Returns the mode this leaf decoded, for the caller's own /// `prev_leaf`/final mode-writeback bookkeeping. #[allow(clippy::too_many_arguments)] /// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one /// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads /// `above_mode[col]`, and its true above neighbour is the mi directly above /// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one /// decoded; the next block RIGHT reads `left_mode[row]`, whose true left /// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf /// (bottom-right) into both, as this path did, is right only when all four /// leaves happen to share a mode. `done` may be short at the true frame edge /// (the straddle caller filters positions off the frame), so each side falls /// back to the last leaf actually decoded. fn write_back_split_modes( neighbours: &mut Neighbours, done: &[((usize, usize), usize)], parent_mi: (usize, usize), slot: (usize, usize), ) { let (sr, sc) = slot; let Some(&(_, last)) = done.last() else { return; }; let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m); neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last); neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last); } fn decode_leaf8( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, outer_at: (usize, usize), leaf_mi: (usize, usize), scans: (&[u16], &[u16]), prev_leaf: Option<((usize, usize), usize)>, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, enable_filter_intra: bool, allow_screen_content_tools: bool, allow_intrabc: bool, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result { let (r, c) = outer_at; // lane-modectx r1: the group's own availability-correct fallback pair, not // the raw coarse bands (which leak across a tile edge -- see // `modes_above_left`). let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c); if let Some(((pr, pc), pmode)) = prev_leaf { if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { above_mode = pmode; } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { left_mode = pmode; } } // The mi-exact neighbour wins over both the coarse 16x16 slot and // `prev_leaf`: one 16x16 slot cannot hold the two different modes its // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left // neighbour sits in a split cell read the wrong `kf_y_mode` row. // lane-rectsplitx r2 swept this arm into // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer // "no neighbour" at a tile edge, where the coarse cell holds the block // above/left of it inside the same 16x16. let (above_mode, left_mode) = neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode)); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode` // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode // this leaf's `smooth_neighbor` is built from -- passing `false` here // filtered a directional chroma block's edge at the wrong strength // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3). // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`), // with the coarse [`SUB`] slot as the fallback when no block recorded // that exact mi cell. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other // `decode_block` caller at 16x16 and up. // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567, // `read_palette_mode_info`), at its REAL mi position -- passing // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the // moment a real 8x8 palette block fired, which is where every 8-bit // `--tune-content=screen --min-partition-size=8` stream stopped. let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi); let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode( dec, cdfs, above_mode, left_mode, true, 8, enable_filter_intra, neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1), allow_screen_content_tools, allow_intrabc, Some((palette_ctx, &palette_cache)), &palette_uv_cache, leaf_mi.0, leaf_mi.1, fctx, )?; // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through // `read_intra_mode` and then decoded the block as if it were ordinary // intra. libaom's `is_inter_block` counts an intrabc block // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`, // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the // same value with a different interval, so the tile desynced at the very // next symbol (class `wrong-alphabet-same-value`). Everything below // mirrors `decode_block`'s own intrabc handling at 16x16 and up. let intrabc_dv = fctx.intrabc_dv.with(|c| c.take()); if intrabc_dv.is_some() { hit!(LEAF8_INTRABC_HITS); } // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour // index map, mapped through the base colours, IS the block's prediction -- // carried to the next `reconstruct`/`read_plane` through the same // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up. let palette_y_buf: Option> = palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }); let (pal_y_size, pal_y_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); let (pal_uv_size, pal_uv_colors) = palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); if palette_y.is_some() || palette_uv.is_some() { hit!(PALETTE_LEAF8_HITS); } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; neighbours.above_uv_mode[c] = uv_predict_mode; neighbours.left_uv_mode[r] = uv_predict_mode; neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1, // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4 // transform units, same raster-order per-TU pattern `decode_block`'s // multi-TU branch runs). // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom // dispatches `read_block_tx_size` on `is_inter_block`, which counts an // intrabc block, so a SKIPPED one takes the largest transform and an // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return). let resolved = if tx_select && intrabc_dv.is_some() && !skip { let mut leaves = Vec::new(); let mi_cols = 2 * y.true_width.div_ceil(8); let mi_rows = 2 * y.true_height.div_ceil(8); read_var_tx_size( dec, cdfs, neighbours, leaf_mi, 8, ( 2usize.min(mi_cols.saturating_sub(leaf_mi.1)), 2usize.min(mi_rows.saturating_sub(leaf_mi.0)), ), (8, 8), 0, 0, 0, &mut leaves, ); hit!(INTRABC_VARTX_HITS); leaves.first().map_or(8, |l| l.2) } else if tx_select && intrabc_dv.is_none() { read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None) } else { 8 }; let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let reach = Reach::of(8, px, py, y.width, y.height, fctx); let (cpx, cpy) = (px / 2, py / 2); // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from // the CURRENT frame's own pre-loop-filter reconstruction (every loop // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at // the full-pel block vector, with the BILINEAR kernel libaom forces. flush_recon(fctx, y, u, v); let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| { let mut yb = vec![0u16; 8 * 8]; mc::predict_with_filter( &y.data, y.width, y.true_width, y.true_height, mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true), 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx, ); let mut ub = vec![0u16; 4 * 4]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false), 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; 4 * 4]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false), 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx, ); (yb, ub, vb) }); // The per-plane prediction override rides the same [`PALETTE_PRED`] slot // `decode_block` uses: set fresh right before each plane's own // `reconstruct`/`read_plane` call (the slot is taken, not copied). // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the // first shape that reaches that loop with an override set). let palette_y_buf = match &intrabc_bufs { Some((yb, _, _)) => Some(yb.clone()), None => palette_y_buf, }; let (luma_grid, u_grid, v_grid); if skip { // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4 // transform units, each off the units already written left/above of // it inside this same leaf -- an intra block's transform size is read // whether or not it is skipped, and spec 7.11.2 predicts per unit. // A palette block's prediction is the whole-block index map, never // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip` // rule) -- so a palette leaf takes the single 8x8 reconstruct below // even when `tx_depth` resolved to TX_4X4. if resolved == 4 && palette_y_buf.is_none() { hit!(SKIP_SPLIT_TX_HITS); for tu_row in 0..2 { for tu_col in 0..2 { let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4); if tu_px >= y.true_width || tu_py >= y.true_height { continue; } let tu_reach = tu_reach( 8, 8, tu_col * 4, tu_row * 4, 4, reach, px, py, y.width, y.height, fctx, ); push_intra(0, tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx, ); } } } else { if let Some(buf) = &palette_y_buf { set_palette_pred(buf.clone(), fctx); } push_intra(0, px, py, 8, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..64], None, filter_intra, smooth_neighbor, fctx, ); } let ac = alpha.map(|_| cfl_src(px, py, 8)); if let Some((_, ub, _)) = &intrabc_bufs { set_palette_pred(ub.clone(), fctx); } else if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, _, vb)) = &intrabc_bufs { set_palette_pred(vb.clone(), fctx); } else if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); luma_grid = Grid::Zero(64); u_grid = Grid::Zero(16); v_grid = Grid::Zero(16); } else if resolved != 4 { let around = neighbours.around_mi(leaf_mi, 8); if let Some(buf) = &palette_y_buf { set_palette_pred(buf.clone(), fctx); } luma_grid = read_plane( dec, cdfs, if intrabc_dv.is_some() { txbset_for_inter(8, reduced_tx_set) } else if reduced_tx_set { TxbSet::Luma8 } else { TxbSet::Luma8Set1 }, scans.0, 0, around[0], mode, mode, angle_delta_y, reach, y, px, py, 8, TX8, base_q_idx, None, filter_intra, None, smooth_neighbor, fctx, )?; // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so // an intrabc block's chroma tx_type is the colocated LUMA transform's // coded type (lane-kf900 r6's own fix, `decode_block`'s line). if intrabc_dv.is_some() { fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get)))); } let ac = alpha.map(|_| cfl_src(px, py, 8)); if let Some((_, ub, _)) = &intrabc_bufs { set_palette_pred(ub.clone(), fctx); } else if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } u_grid = read_plane( dec, cdfs, TxbSet::Chroma4, scans.1, 1, around[1], mode, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; if let Some((_, _, vb)) = &intrabc_bufs { set_palette_pred(vb.clone(), fctx); } else if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } v_grid = read_plane( dec, cdfs, TxbSet::Chroma4, scans.1, 2, around[2], mode, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's // two chroma reads (`decode_block`'s own tail does the same) -- left // set, every later chroma block would inherit this luma tx_type, // which picks the scan and the inverse transform. fctx.intrabc_chroma_tx.with(|c| c.set(None)); } else { // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order // grid of 4x4 transform units, each predicted from the leaf's own // 8x8 `mode` and reading its own fresh context off the earlier // units in this same leaf (the same per-TU pattern `decode_block`'s // multi-TU branch runs at bigger blocks). for tu_row in 0..2 { for tu_col in 0..2 { let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col); let tu_px = px + tu_col * 4; let tu_py = py + tu_row * 4; let tu_around = neighbours.around_mi(tu_mi, 4)[0]; if crate::encode::Reach::in_vert_ab() { hit!(VERT_AB_TX4_HITS); } let tu_reach = tu_reach( 8, 8, tu_col * 4, tu_row * 4, 4, reach, px, py, y.width, y.height, fctx, ); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); // Each 4x4 unit predicts from its own window of the block's // 8x8 colour-index map ([`decode_block`]'s per-TU slice at // 16x16 and up) -- the whole-block buffer would be taken by // the FIRST unit and indexed at the wrong stride. if let Some(buf) = &palette_y_buf { hit!(PALETTE_SPLIT_TX_HITS); let mut window = vec![0u16; 16]; for row in 0..4 { let src = (tu_row * 4 + row) * 8 + tu_col * 4; window[row * 4..][..4].copy_from_slice(&buf[src..][..4]); } set_palette_pred(window, fctx); } let tu_grid = read_plane( dec, cdfs, if intrabc_dv.is_some() { txbset_for_inter(4, reduced_tx_set) } else if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 }, scans.1, 0, tu_around, mode, mode, angle_delta_y, tu_reach, y, tu_px, tu_py, 4, 4, base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE tu_bitpos mi=({},{}) tell={}", tu_mi.0, tu_mi.1, dec.debug_bitpos() ); } neighbours.record_mi_luma(tu_mi, 4, &tu_grid); } } let ac = alpha.map(|_| cfl_src(px, py, 8)); let chroma_around = neighbours.around_mi(leaf_mi, 8); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } u_grid = read_plane( dec, cdfs, TxbSet::Chroma4, scans.1, 1, chroma_around[1], mode, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } v_grid = read_plane( dec, cdfs, TxbSet::Chroma4, scans.1, 2, chroma_around[2], mode, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; // `record_split_luma` expects a `record`-style `(r, c)` position in // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is // already in mi units, so calling it here double-scaled the // position. Plane 0 is already correct per-TU from the // `record_mi_luma` calls above; this inlines `record_mi`'s tail // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this // leaf's own 8x8 side over `MI`). let side_mi = 2; for cell in 0..side_mi { neighbours.left_side_mi[leaf_mi.0 + cell] = 8; neighbours.above_side_mi[leaf_mi.1 + cell] = 8; } let round_up_even = |n: usize| n.div_ceil(2) * 2; let bound_h = round_up_even(neighbours.mi_rows); let bound_w = round_up_even(neighbours.mi_cols); let u_state = neighbour_state(&u_grid); let v_state = neighbour_state(&v_grid); for cell in 0..side_mi { if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) { neighbours.left[leaf_mi.0 + cell][1] = u_state; neighbours.left[leaf_mi.0 + cell][2] = v_state; } if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) { neighbours.above[leaf_mi.1 + cell][1] = u_state; neighbours.above[leaf_mi.1 + cell][2] = v_state; } } // This leaf's own palette state into the mi-granular above/left bands // (sizes 0 when it used none, which is what clears a previous block's // palette out of the next block's ctx and colour cache). { neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors); neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors); } neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx); // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s // own copy; only an intrabc var-tx read consumes these bands on the intra // path, so the write is armed by `allow_intrabc`. if allow_intrabc { set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some()); } neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx); return Ok(mode); } neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); // This leaf's own palette state into the mi-granular above/left bands // (sizes 0 when it used none, which is what clears a previous block's // palette out of the next block's ctx and colour cache). { neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors); neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors); } hit!(INTER8_SKIP_BAND_HITS); neighbours.fill_skip_grid(leaf_mi, 2, skip); // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm && // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to // TX_4X4 still publishes 4 to the next block's `get_tx_size_context` // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet, // wrong CDF row, so the msac range diverged mid-frame with no refusal // (class `wrong-alphabet-same-value`; the ReelB key frame at // -ss 900, first bad luma sample row 186 col 1803). neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx); // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s // own copy; only an intrabc var-tx read consumes these bands on the intra // path, so the write is armed by `allow_intrabc`. if allow_intrabc { set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some()); } neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME` // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to // publish its own cells exactly like `decode_block` does. record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx); Ok(mode) } /// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf /// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8` /// bottom, where no partition symbol is read at all -- `decode_block` runs /// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec /// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always /// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference` /// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf /// of the 2x2 4x4 group carries chroma syntax at all. #[allow(clippy::too_many_arguments)] fn read_intra_mode_sub8( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_mode: usize, left_mode: usize, has_chroma: bool, enable_filter_intra: bool, // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag // from the wrong row is the same VALUE with a different interval, so it // desyncs a block or two later, not here (class `wrong-alphabet-same-value`). fi_class: usize, skip_ctx: usize, allow_intrabc: bool, mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx, ) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option)> { let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0); } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; if trace { eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0); } maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx); maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx); maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx); if allow_intrabc { let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; if use_intrabc { return Err(unsupported( "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)", )); } } let above_ctx = INTRA_MODE_CTX[above_mode]; let left_ctx = INTRA_MODE_CTX[left_mode]; let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); if trace { eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0); } // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/ // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`, // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta // symbol. Reading one consumed a symbol the encoder never wrote and // desynced the tile at the very next element. let angle_delta_y = 0; let chroma = if has_chroma { let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); if trace { eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0); } if (9..=12).contains(&uv_mode) { hit!(SMOOTH_UV_HITS); } let alpha = if uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; if (V_PRED..=D67_PRED).contains(&uv_mode) { hit!(DIRECTIONAL_UV_HITS); } // See the luma comment above: no angle delta below 8x8. let angle_delta_uv = 0; Some((uv_mode, angle_delta_uv, alpha)) } else { None }; let mut filter_intra = None; if mode == DC_PRED && enable_filter_intra { let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0; if trace { eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32); } if use_filter_intra { hit!(FILTER_INTRA_HITS); let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); filter_intra = Some(fi_mode); } } Ok((skip, mode, angle_delta_y, chroma, filter_intra)) } /// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves /// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s /// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode` /// bookkeeping needs no change. Each leaf reads its own luma mode info, /// neighboured off the *previously decoded leaf in this same group* on /// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf` /// pattern, one level deeper); chroma is read and reconstructed exactly /// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4 /// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference` /// derivation. #[allow(clippy::too_many_arguments)] fn decode_leaf_split4( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, outer_at: (usize, usize), leaf_mi: (usize, usize), scan4: &[u16], prev_leaf: Option<((usize, usize), usize)>, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, enable_filter_intra: bool, allow_intrabc: bool, reduced_tx_set: bool, // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx fctx: &crate::decode::FrameCtx, ) -> Result<(usize, usize)> { hit!(SUB8_SPLIT_HITS); let (r, c) = outer_at; let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; if let Some(((pr, pc), pmode)) = prev_leaf { if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { above_mode = pmode; } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { left_mode = pmode; } } // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter // type is the chroma neighbours' `uv_mode`, mi-exact where recorded. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); let mut leaf_modes = [0usize; 4]; let mut leaf_skips = [false; 4]; let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None; for i in 0..4usize { let (dr, dc) = (i / 2, i % 2); let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc); // Neighbour modes at real mi granularity: inside the group the // sibling leaf, outside it the split-leaf map when the adjacent mi // was itself a 4x4 leaf, else the coarse 16x16 slot (see // `sub8_mode_col`'s doc). let leaf_above = if dr == 0 { neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode) } else { leaf_modes[i - 2] }; let leaf_left = if dc == 0 { neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode) } else { leaf_modes[i - 1] }; let has_chroma = i == 3; let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1); let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8( dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"), skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx, )?; leaf_modes[i] = mode; leaf_skips[i] = skip; neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode); let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = Reach::of(4, px, py, y.width, y.height, fctx); if skip { push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx); neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]); } else { let tu_around = neighbours.around_mi(lmi, 4)[0]; // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]` // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table // (`txb_common.h:400`). Reading the table here decoded `all_zero` // off the wrong CDF on the very first leaf and desynced the tile. let tu_grid = read_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 }, scan4, 0, tu_around, mode, mode, angle_delta_y, reach, y, px, py, 4, 4, base_q_idx, None, filter_intra, None, smooth_neighbor, fctx, )?; neighbours.record_mi_luma(lmi, 4, &tu_grid); } neighbours.fill_skip_grid(lmi, 1, skip); neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx); if has_chroma { last_uv = chroma; } } let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let (cpx, cpy) = (gpx / 2, gpy / 2); let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx); let (uv_mode, angle_delta_uv, alpha) = last_uv.expect("i==3 always sets has_chroma, so chroma is always Some"); let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; neighbours.above_uv_mode[c] = uv_predict_mode; neighbours.left_uv_mode[r] = uv_predict_mode; neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] { // A skipped chroma block still gets its CfL contribution: libaom's // `predict_and_reconstruct_intra_block` calls `cfl_predict_block` // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719) // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is // added -- `skip_txfm` only drops the residual, never the alpha. // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the // merge keeps one fix and feeds both lanes' counters so neither of // their gates goes vacuous. let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); if alpha.is_some() { hit!(CHROMA_SKIP_CFL_HITS); hit!(SKIP_CFL_HITS); } push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx); push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx); (Grid::Zero(16), Grid::Zero(16)) } else { let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); let chroma_around = neighbours.around_mi(leaf_mi, 8); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode, angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; let vg = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode, angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; (ug, vg) }; // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s // rescaling is wrong for an already-mi-unit position, so this inlines // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion // bottom). libaom's `update_ext_partition_context` writes // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this // round's bug) makes the very next sibling 8x8's `partition_w8` read // with the wrong context and desync immediately. let side_mi = 2; for cell in 0..side_mi { neighbours.left_side_mi[leaf_mi.0 + cell] = 4; neighbours.above_side_mi[leaf_mi.1 + cell] = 4; } let round_up_even = |n: usize| n.div_ceil(2) * 2; let bound_h = round_up_even(neighbours.mi_rows); let bound_w = round_up_even(neighbours.mi_cols); let u_state = neighbour_state(&u_grid); let v_state = neighbour_state(&v_grid); for cell in 0..side_mi { if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) { neighbours.left[leaf_mi.0 + cell][1] = u_state; neighbours.left[leaf_mi.0 + cell][2] = v_state; } if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) { neighbours.above[leaf_mi.1 + cell][1] = u_state; neighbours.above[leaf_mi.1 + cell][2] = v_state; } } Ok((leaf_modes[2], leaf_modes[1])) } /// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two /// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape /// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for /// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no /// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at /// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for /// every sub-block one mi wide or high but the last) -- differing only where /// the shape does: /// /// * the transform is a true `TX_4X8`/`TX_8X4` /// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and /// `av1_inv_txfm_shift_ls` row already cover this size pair); /// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares /// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type` /// row -- see that variant's doc comment; /// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings /// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`; /// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows /// ([`Reach::of_rect`]); /// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]` /// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a /// `BLOCK_4X4` split writes. /// /// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is /// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes /// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`] /// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's /// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is /// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`. #[allow(clippy::too_many_arguments)] fn decode_leaf_rect8( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, outer_at: (usize, usize), leaf_mi: (usize, usize), vert: bool, scan4: &[u16], y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, enable_filter_intra: bool, allow_intrabc: bool, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(usize, usize)> { let (r, c) = outer_at; // lane-modectx r1: availability-correct fallback pair (see // `modes_above_left`), not the raw coarse bands. let (above_mode, left_mode) = neighbours.modes_above_left(r, c); let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); let (bw, bh) = if vert { (4, 8) } else { (8, 4) }; let (w_mi, h_mi) = (bw / MI, bh / MI); let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 }; let mut leaf_modes = [0usize; 2]; let mut leaf_skips = [false; 2]; let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None; for i in 0..2usize { let lmi = if vert { (leaf_mi.0, leaf_mi.1 + i) } else { (leaf_mi.0 + i, leaf_mi.1) }; // Inside the pair the sibling is the neighbour on the split axis; // outside it the mi-granular map, else the coarse 16x16 slot. let leaf_above = if !vert && i == 1 { leaf_modes[0] } else { neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode) }; let leaf_left = if vert && i == 1 { leaf_modes[0] } else { neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode) }; let has_chroma = i == 1; let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1); let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8( dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, filter_intra_size_class_rect(bw, bh) .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"), skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx, )?; if filter_intra.is_some() { // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the // same `reconstruct_rect`/`reconstruct` calls below -- and under // a split transform, per 4x4 unit with that unit's own edge, // which is exactly what the depth-1 loop already does. hit!(FILTER_INTRA_RECT_HITS); hit!(FILTER_INTRA_RECT_SUB8_HITS); } // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4 // leaf too, and is read for every intra block, skipped or not. Its // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` -- // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol // `tx_size_cat2` the 32x16 strips read -- with the rect context // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh). // Missing this read consumed one symbol fewer than the encoder wrote // and desynced the tile at the very first rect leaf (class // `symbol-consumption-gap`). let depth = if tx_select { // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band // read every other rect reader now does -- a no-op on a key frame. let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() { tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx) } else { tx_size_context_rect(neighbours, lmi, bw, bh) }; dec.symbol(&mut cdfs.tx_size_cat0[ctx]) } else { 0 }; if depth != 0 { hit!(TX_DEPTH_HITS); hit!(RECT8_SPLIT_TX_HITS); } leaf_modes[i] = mode; leaf_skips[i] = skip; neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode); let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into // two 4x4 transform units along its long axis, each predicted from // the previous unit's reconstruction and reading its own `txb_skip` // context -- `decode_leaf8`'s own depth-1 loop, two units instead of // four. The per-TU path writes its own neighbour state, so the // block-level write below is skipped for it. let split = depth != 0; if split { let mut done = 0usize; for tu in 0..2usize { let tu_mi = if vert { (lmi.0 + tu, lmi.1) } else { (lmi.0, lmi.1 + tu) }; let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI); let tu_around = neighbours.around_mi(tu_mi, 4)[0]; // Same per-TU rule as every other split-transform site // (lane-palette2 r12): a transform unit inside a block is not // a block at that position, so its reach comes from the // block's own row, offset by the unit's position. let tu_reach = tu_reach( bw, bh, tu_px - px, tu_py - py, 4, reach, px, py, y.width, y.height, fctx, ); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); if skip { // A skipped leaf still predicts per transform unit: the // second 4x4 takes its above/left edge from the first // one's reconstruction, which is NOT what a single 4x8 // prediction of the same mode produces. let zeros = vec![0i32; 16]; push_intra(0, tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None, filter_intra, smooth_neighbor, fctx, ); neighbours.record_mi_luma(tu_mi, 4, &zeros); continue; } let tu_grid = read_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 }, scan4, 0, tu_around, mode, mode, angle_delta_y, tu_reach, y, tu_px, tu_py, 4, TX4, base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; if tu_grid.iter().any(|&l| l != 0) { done += 1; } neighbours.record_mi_luma(tu_mi, 4, &tu_grid); } if done > 0 { if vert { hit!(TX4X8_CODED_HITS); } else { hit!(TX8X4_CODED_HITS); } } neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx); if has_chroma { last_uv = chroma; } continue; } let grid = if skip { let zeros = Grid::Zero(bw * bh); push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra, smooth_neighbor, fctx, ); zeros } else { // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx` // at 0 -- see `decode_leaf_split4`'s own note. let around = neighbours.around_mi_rect(lmi, bw, bh)[0]; let set = if reduced_tx_set { TxbSet::LumaRect4x8 } else { TxbSet::LumaRect4x8Set1 }; let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, scan, bw, bh, 0, dc_sign_ctx(around.2), TxType::DctDct, )?; if levels.iter().any(|&l| l != 0) { if vert { hit!(TX4X8_CODED_HITS); } else { hit!(TX8X4_CODED_HITS); } } let residual = dequant_and_inverse_typed_wh( &levels, bw, bh, crate::decode::bit_depth(fctx), fctx.current_q_idx.with(|q| q.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type, ); push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra, smooth_neighbor, fctx, ); levels }; // Plane 0's per-TU coefficient context over this leaf's own mi span // (`record_mi_luma`'s rect twin -- the chroma planes are written once // for the whole 8x8 group below). let state = neighbour_state(&grid); for cell in 0..h_mi { if lmi.0 + cell < neighbours.mi_rows { neighbours.left[lmi.0 + cell][0] = state; } } for cell in 0..w_mi { if lmi.1 + cell < neighbours.mi_cols { neighbours.above[lmi.1 + cell][0] = state; } } neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) }; neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx); if has_chroma { last_uv = chroma; } } let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let (cpx, cpy) = (gpx / 2, gpy / 2); let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx); let (uv_mode, angle_delta_uv, alpha) = last_uv.expect("i==1 always sets has_chroma, so chroma is always Some"); let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; neighbours.above_uv_mode[c] = uv_predict_mode; neighbours.left_uv_mode[r] = uv_predict_mode; neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] { // A skipped chroma block still gets its CfL contribution: libaom's // `predict_and_reconstruct_intra_block` calls `cfl_predict_block` // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719) // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is // added -- `skip_txfm` only drops the residual, never the alpha. // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the // merge keeps one fix and feeds both lanes' counters so neither of // their gates goes vacuous. let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); if alpha.is_some() { hit!(CHROMA_SKIP_CFL_HITS); hit!(SKIP_CFL_HITS); } push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx); push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx); (Grid::Zero(16), Grid::Zero(16)) } else { let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); let chroma_around = neighbours.around_mi(leaf_mi, 8); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode, angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; let vg = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode, angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; (ug, vg) }; // `update_partition_context` at the 8x8 level writes // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}` // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which // `partition_ctx_mi` reads back off these side values. for cell in 0..2 { neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8; neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8; } let round_up_even = |n: usize| n.div_ceil(2) * 2; let bound_h = round_up_even(neighbours.mi_rows); let bound_w = round_up_even(neighbours.mi_cols); let u_state = neighbour_state(&u_grid); let v_state = neighbour_state(&v_grid); for cell in 0..2usize { if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) { neighbours.left[leaf_mi.0 + cell][1] = u_state; neighbours.left[leaf_mi.0 + cell][2] = v_state; } if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) { neighbours.above[leaf_mi.1 + cell][1] = u_state; neighbours.above[leaf_mi.1 + cell][2] = v_state; } } // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the // bottom one (the second under HORZ, the left one under VERT), the one a // neighbour to the right sees is the top-right (the second under VERT). Ok(if vert { (leaf_modes[0], leaf_modes[1]) } else { (leaf_modes[1], leaf_modes[0]) }) } /// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary /// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2` /// (mod 8) reuse the same table. const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [ [(-1, 1), (-2, 2)], [(0, 1), (-1, 2)], [(0, 1), (0, 2)], [(0, 1), (1, 2)], [(1, 1), (2, 2)], [(1, 0), (2, 1)], [(1, 0), (2, 0)], [(1, 0), (2, -1)], ]; /// A neighbour tap outside the frame's true extent -- `constrain` reads this /// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`). const CDEF_VERY_LARGE: i32 = 0x4000; const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]]; const CDEF_SEC_TAPS: [i32; 2] = [2, 1]; fn cdef_msb(x: i32) -> i32 { 31 - x.leading_zeros() as i32 } /// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the /// centre sample a filter tap is allowed to contribute. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 { if threshold == 0 { return 0; } cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping)) } /// `constrain`'s damping shift: a function of the block's threshold and /// damping alone, so the filter loop computes it once per block instead of /// the `leading_zeros` + branch it used to do twice per tap read. fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 { (damping - cdef_msb(threshold)).max(0) } /// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is /// non-zero on every call (the caller only filters when its strength is). fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 { let a = diff.abs(); diff.signum() * (threshold - (a >> shift)).clamp(0, a) } /// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads /// lies inside its own samples grown by this much. const CDEF_BORDER: usize = 2; /// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the /// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row /// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops /// index a small contiguous window instead of re-deriving the frame-bounds /// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get /// `CDEF_VERY_LARGE`, exactly as the per-sample closure did. fn cdef_gather( src: &[u16], stride: usize, true_w: usize, true_h: usize, ox: usize, oy: usize, bw: usize, bh: usize, buf: &mut [i16], ) { let bstride = bw + 2 * CDEF_BORDER; let rows = bh + 2 * CDEF_BORDER; if oy >= CDEF_BORDER && ox >= CDEF_BORDER && oy + bh + CDEF_BORDER <= true_h && ox + bw + CDEF_BORDER <= true_w { // Interior block: every tap is inside the frame, so the whole window // is `rows` contiguous runs. for r in 0..rows { let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER); let src_row = &src[s0..s0 + bstride]; let dst_row = &mut buf[r * bstride..r * bstride + bstride]; for (d, &v) in dst_row.iter_mut().zip(src_row) { *d = v as i16; } } return; } for r in 0..rows { let ny = oy as isize + r as isize - CDEF_BORDER as isize; for c in 0..bstride { let nx = ox as isize + c as isize - CDEF_BORDER as isize; buf[r * bstride + c] = if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w { CDEF_VERY_LARGE as i16 } else { src[ny as usize * stride + nx as usize] as i16 }; } } } /// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each /// array takes the row, its reverse, its pairwise sums or its total added /// into consecutive slots, so the 512 scalar read-modify-writes on i64 the /// per-sample form did become a handful of lane-wide adds per row. i32 is /// exact here: every partial is a sum of at most eight values in -128..127, /// and slot 15 exists only so an eight-lane store at offset 7 fits. fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] { fn add_at(dst: &mut [i32; 16], off: usize, src: &[i32; N]) { for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) { *d += x; } } let mut partial = [[0i32; 16]; 8]; for i in 0..8usize { let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER; // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before // accumulating, same as `constrain`'s threshold shift. let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128); let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]); let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]); let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]); let (p, rest) = partial.split_at_mut(1); add_at(&mut p[0], i, &row); // partial[0][i + j] add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2] rest[1][i] = row.iter().sum(); // partial[2][i] add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2] add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j] add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j] add_at(&mut rest[5], 0, &row); // partial[6][j] add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j] } partial } /// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant /// direction of an 8x8 luma window and the variance gap between it and its /// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the /// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`). fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) { const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105]; #[cfg(target_arch = "x86_64")] let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 { // SAFETY: reached only when the CPU reports avx2; the kernel reads // the same eight rows of eight samples the scalar form does. #[allow(unsafe_code)] unsafe { cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift) } } else { cdef_find_dir_partials(win, bstride, coeff_shift) }; #[cfg(not(target_arch = "x86_64"))] let partial = cdef_find_dir_partials(win, bstride, coeff_shift); let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) }; let mut cost = [0i64; 8]; for i in 0..8usize { cost[2] += sq(partial[2][i]); cost[6] += sq(partial[6][i]); } cost[2] *= DIV_TABLE[8]; cost[6] *= DIV_TABLE[8]; for i in 0..7usize { cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1]; cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1]; } cost[0] += sq(partial[0][7]) * DIV_TABLE[8]; cost[4] += sq(partial[4][7]) * DIV_TABLE[8]; for i in (1..8).step_by(2) { for j in 0..5usize { cost[i] += sq(partial[i][3 + j]); } cost[i] *= DIV_TABLE[8]; for j in 0..3usize { cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2]; } } let mut best_cost = 0i64; let mut best_dir = 0usize; for (i, &c) in cost.iter().enumerate() { if c > best_cost { best_cost = c; best_dir = i; } } let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10; (best_dir, var as i32) } /// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8 /// (high variance gap) gets more deringing than a flat or non-directional /// one, only ever applied to the luma primary strength. fn cdef_adjust_strength(strength: i32, var: i32) -> i32 { if var == 0 { return 0; } let i = if var >> 6 != 0 { cdef_msb(var >> 6).min(12) } else { 0 }; (strength * (4 + i) + 8) >> 4 } /// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0 /// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a /// previously-filtered neighbour must never feed this block's own sum). #[allow(clippy::too_many_arguments)] #[allow(unsafe_code)] fn cdef_filter_block( src: &[i16], dst: &mut PlaneBuf<'static>, ox: usize, oy: usize, bw: usize, bh: usize, pri_strength: i32, sec_strength: i32, dir: usize, pri_damping: i32, sec_damping: i32, enable_primary: bool, enable_secondary: bool, coeff_shift: i32, fctx: &crate::decode::FrameCtx, ) { let (stride, smax) = (dst.width, sample_max(fctx)); #[cfg(target_arch = "x86_64")] if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0 { // SAFETY: reached only when the CPU reports avx2; the kernel reads // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the // `bh` runs of `bw` samples the scalar form writes. unsafe { cdef_simd::filter_block_avx2( src, dst.data.to_mut(), stride, ox, oy, bw, bh, pri_strength, sec_strength, dir, pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax, ) }; return; } cdef_filter_block_scalar( src, dst.data.to_mut(), stride, ox, oy, bw, bh, pri_strength, sec_strength, dir, pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax, ); } /// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample, /// the form every non-AVX2 build decodes through and the one /// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against. #[allow(clippy::too_many_arguments)] fn cdef_filter_block_scalar( src: &[i16], dst: &mut [u16], stride: usize, ox: usize, oy: usize, bw: usize, bh: usize, pri_strength: i32, sec_strength: i32, dir: usize, pri_damping: i32, sec_damping: i32, enable_primary: bool, enable_secondary: bool, coeff_shift: i32, smax: i32, ) { let clipping_required = enable_primary && enable_secondary; // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >> // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength` // derivative) carries the bit-depth shift, so the tap-set parity bit // must be read back above that shift, not off the raw low bit. let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize]; // Both damping shifts depend only on this block's strengths (spec 7.15.3's // `constrain`), so they are resolved here rather than per tap read. let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping); let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping); let bstride = bw + 2 * CDEF_BORDER; // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps // reaching +-CDEF_BORDER, so every index below is in range by construction. let at = |i: i32, j: i32| -> i32 { i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize]) }; let (pri_dir, sec_dir0, sec_dir1) = (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]); for i in 0..bh { for j in 0..bw { let (i32i, i32j) = (i as i32, j as i32); let x = at(i32i, i32j); let mut sum = 0i32; let mut max = x; let mut min = x; for k in 0..2usize { if enable_primary { let (tr, tc) = pri_dir[k]; let p0 = at(i32i + tr, i32j + tc); let p1 = at(i32i - tr, i32j - tc); sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift); sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift); if clipping_required { if p0 != CDEF_VERY_LARGE { max = max.max(p0); } if p1 != CDEF_VERY_LARGE { max = max.max(p1); } min = min.min(p0).min(p1); } } if enable_secondary { let (tr0, tc0) = sec_dir0[k]; let (tr1, tc1) = sec_dir1[k]; let s0 = at(i32i + tr0, i32j + tc0); let s1 = at(i32i - tr0, i32j - tc0); let s2 = at(i32i + tr1, i32j + tc1); let s3 = at(i32i - tr1, i32j - tc1); if clipping_required { for s in [s0, s1, s2, s3] { if s != CDEF_VERY_LARGE { max = max.max(s); } } min = min.min(s0).min(s1).min(s2).min(s3); } sum += CDEF_SEC_TAPS[k] * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift) + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift) + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift) + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift)); } } let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4); if clipping_required { y = y.clamp(min, max); } dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16; } } } /// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar /// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic: /// the same taps, the same `constrain`, the same `min`/`max` clamp with the /// `CDEF_VERY_LARGE` sentinel excluded from the max, the same /// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at /// a time in 16-bit lanes. /// /// 16-bit lanes are exact for every value this filter sees: window samples /// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in /// `i16`, a `constrain` result is bounded by the threshold (at most /// `15 << 4`), and the tap-weighted sum by `24 *` that. #[cfg(target_arch = "x86_64")] #[allow(unsafe_code)] #[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract mod cdef_simd { use super::{ cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS, CDEF_VERY_LARGE, }; use std::arch::x86_64::*; /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit /// register (low half = row `i`). /// /// # Safety /// Requires AVX2; `off + bstride + 8` must be inside `w`. #[target_feature(enable = "avx2")] #[inline] unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i { let lo = _mm_loadu_si128(w.offset(off).cast()); let hi = _mm_loadu_si128(w.offset(off + bstride).cast()); _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1) } /// Spec 7.15.3's `constrain`, lane-parallel: /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`. /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the /// clamped magnitude is already 0 where `diff` is). /// /// # Safety /// Requires AVX2. #[target_feature(enable = "avx2")] #[inline] unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i { let diff = _mm256_sub_epi16(p, x); let a = _mm256_abs_epi16(diff); let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift)); let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a); _mm256_sign_epi16(t, diff) } /// [`super::cdef_find_dir_partials`] in AVX2 (libaom /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the /// four the auto-vectorised scalar form gets without the feature. /// /// # Safety /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window /// grown by `CDEF_BORDER` at row stride `bstride`. #[target_feature(enable = "avx2")] pub unsafe fn find_dir_partials_avx2( win: &[i16], bstride: usize, coeff_shift: i32, ) -> [[i32; 16]; 8] { #[target_feature(enable = "avx2")] unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) { let p = dst.as_mut_ptr().add(off) as *mut __m256i; _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v)); } #[target_feature(enable = "avx2")] unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) { let p = dst.as_mut_ptr().add(off) as *mut __m128i; _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v)); } let mut partial = [[0i32; 16]; 8]; let shift = _mm_cvtsi32_si128(coeff_shift); let c128 = _mm256_set1_epi32(128); let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0); let mut p6 = _mm256_setzero_si256(); for i in 0..8usize { let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER; let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i); let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128); let rev = _mm256_permutevar8x32_epi32(row, revidx); // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the // four pairwise sums are the two lanes' low halves joined. let h = _mm256_hadd_epi32(row, row); let pair = _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1)); let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11); let hs = _mm_hadd_epi32(pair, pair); let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs)); add8(&mut partial[0], i, row); add4(&mut partial[1], i, pair); partial[2][i] = total; add4(&mut partial[3], i, rpair); add8(&mut partial[4], i, rev); add8(&mut partial[5], 3 - i / 2, row); p6 = _mm256_add_epi32(p6, row); add8(&mut partial[7], i / 2, row); } _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6); partial } /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for /// `bw == 4` the upper four lanes of each half are window samples read /// past the row (never past the buffer -- `w` is padded to 256 entries), /// computed and then dropped by the 64-bit store. /// /// # Safety /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window /// buffer (the tap loads read up to 152 entries past its start, i.e. past /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows /// of `bw` samples at `(ox, oy)`. #[target_feature(enable = "avx2")] #[allow(clippy::too_many_arguments)] pub unsafe fn filter_block_avx2( src: &[i16], dst: &mut [u16], stride: usize, ox: usize, oy: usize, bw: usize, bh: usize, pri_strength: i32, sec_strength: i32, dir: usize, pri_damping: i32, sec_damping: i32, enable_primary: bool, enable_secondary: bool, coeff_shift: i32, smax: i32, ) { let bstride = bw + 2 * CDEF_BORDER; // The caller's window is already `i16` and 256 entries long, so the // kernel taps it in place: the largest two-row load is // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the // 4x4 chroma one, both inside the buffer's zeroed tail. let w = src; let clipping_required = enable_primary && enable_secondary; let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize]; let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping)); let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping)); let pri_thr = _mm256_set1_epi16(pri_strength as i16); let sec_thr = _mm256_set1_epi16(sec_strength as i16); let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16); let zero = _mm256_setzero_si256(); let eight = _mm256_set1_epi16(8); let smaxv = _mm256_set1_epi16(smax as i16); let (pri_dir, sec_dir0, sec_dir1) = (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]); let wp = w.as_ptr(); let bs = bstride as isize; let dp = dst.as_mut_ptr(); let mut i = 0usize; while i < bh { let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize; let x = ld2(wp, base, bs); let mut sum = zero; let mut max = x; let mut min = x; for k in 0..2usize { if enable_primary { let (tr, tc) = pri_dir[k]; let off = tr as isize * bs + tc as isize; let p0 = ld2(wp, base + off, bs); let p1 = ld2(wp, base - off, bs); let tap = _mm256_set1_epi16(pri_taps[k] as i16); sum = _mm256_add_epi16( sum, _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)), ); sum = _mm256_add_epi16( sum, _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)), ); if clipping_required { // The sentinel is excluded from the max exactly as the // scalar `if p != CDEF_VERY_LARGE` does: masking it to // 0 cannot win a max whose seed `x` is non-negative. max = _mm256_max_epi16( max, _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0), ); max = _mm256_max_epi16( max, _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1), ); min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1)); } } if enable_secondary { let (tr0, tc0) = sec_dir0[k]; let (tr1, tc1) = sec_dir1[k]; let off0 = tr0 as isize * bs + tc0 as isize; let off1 = tr1 as isize * bs + tc1 as isize; let s0 = ld2(wp, base + off0, bs); let s1 = ld2(wp, base - off0, bs); let s2 = ld2(wp, base + off1, bs); let s3 = ld2(wp, base - off1, bs); if clipping_required { for s in [s0, s1, s2, s3] { max = _mm256_max_epi16( max, _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s), ); } min = _mm256_min_epi16( min, _mm256_min_epi16( _mm256_min_epi16(s0, s1), _mm256_min_epi16(s2, s3), ), ); } let c = _mm256_add_epi16( _mm256_add_epi16( constrain(s0, x, sec_thr, sec_shift), constrain(s1, x, sec_thr, sec_shift), ), _mm256_add_epi16( constrain(s2, x, sec_thr, sec_shift), constrain(s3, x, sec_thr, sec_shift), ), ); sum = _mm256_add_epi16( sum, _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c), ); } } // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`. let neg = _mm256_cmpgt_epi16(zero, sum); let mut y = _mm256_add_epi16( x, _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4), ); if clipping_required { y = _mm256_min_epi16(_mm256_max_epi16(y, min), max); } y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv); let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1)); let o0 = ((oy + i) * stride + ox) as isize; let o1 = o0 + stride as isize; if bw == 8 { _mm_storeu_si128(dp.offset(o0).cast(), lo); _mm_storeu_si128(dp.offset(o1).cast(), hi); } else { _mm_storel_epi64(dp.offset(o0).cast(), lo); _mm_storel_epi64(dp.offset(o1).cast(), hi); } i += 2; } } } /// Spec 7.14: the in-loop deblocking filter, applied once per frame after /// tile reconstruction and before [`apply_cdef`]. Uniform-level path only -- /// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so /// every block's level comes from [`LoopFilterParams::level`] plus the /// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's /// `get_filter_level`, precomputed per-block here rather than cached in a /// table the way libaom's `av1_loop_filter_frame_init` does). /// /// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision) /// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels). fn apply_deblock( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, lf: &LoopFilterParams, n: &Neighbours, frame_width: usize, frame_height: usize, fctx: &crate::decode::FrameCtx, ) { // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel // mismatch between the raw reconstruction and post-filter output. if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") { return; } if lf.level[0] != 0 || lf.level[1] != 0 { deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx); } if lf.level[2] != 0 { deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx); } if lf.level[3] != 0 { deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx); } } /// [`apply_deblock`] for ONE pass over ONE band of luma rows /// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three /// planes' vertical passes and then their three horizontal ones is the same /// output as `apply_deblock`'s plane-at-a-time order: the planes are /// separate buffers and neither pass reads another plane. #[allow(clippy::too_many_arguments)] fn deblock_span( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, lf: &LoopFilterParams, n: &Neighbours, frame_width: usize, frame_height: usize, y_lo: usize, y_hi: usize, horz: bool, fctx: &crate::decode::FrameCtx, ) { if lf.level[0] != 0 || lf.level[1] != 0 { deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx); } if lf.level[2] != 0 { deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx); } if lf.level[3] != 0 { deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx); } } /// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls /// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma /// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per /// mi unit under this decoder's assumed 4:2:0 subsampling). /// /// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as /// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz | /// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma /// prediction mode is obtained from the bottom/right mi structure of the /// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col /// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which /// is the same cell for every block 8x8 and larger and a DIFFERENT coded /// block (different tx size, ref frame, skip flag and delta_lf) as soon as /// the group is split into 4x4 luma blocks (class /// `context-read-from-one-cell`). fn plane_to_mi(chroma: bool, coord: usize) -> usize { if chroma { (coord / 2) | 1 } else { coord / 4 } } /// This plane's own transform width in pixels at the covering block, spec /// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma /// width directly; chroma halves it (this decoder's UV transform is always /// half its coded block's luma transform, spec's `av1_get_max_uv_txsize` /// under 4:2:0 and a block that never splits its own transform). fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid }; grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32 } /// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal /// edges step and gate by transform height, which differs from width only /// on rect partition strips. fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid }; grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32 } /// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom /// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each /// present only when its neighbour exists inside the true frame -- whether /// the block immediately above (at this block's own leftmost mi column) or /// to the left (at its own topmost mi row) coded a transform at least as wide /// as `own_side`. fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize { let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side; let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side; usize::from(above) + usize::from(left) } /// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`), /// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays /// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the /// inter path maintains), except that an *inter* neighbour contributes its /// own BLOCK size rather than its transform size -- the two differ the moment /// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid /// approximation coincides with this only while every neighbour codes one /// whole-block transform, which is exactly what `TxMode::Select` ends. /// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit /// r1): `get_tx_size_context` compares the neighbour ABOVE against /// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT /// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1 /// strip are two different numbers. The intra strip inside an inter frame read /// this through [`tx_size_context_rect`] -- the key frame's deblock-grid /// approximation -- so once `TxMode::Select` made the depth symbol exist, it was /// read off the wrong CDF row whenever a neighbour's var-tx tree had split. fn tx_size_context_txfm_rect( n: &Neighbours, (mi_r, mi_c): (usize, usize), own_w: usize, own_h: usize, fctx: &crate::decode::FrameCtx, ) -> usize { hit!(INTRA_IN_INTER_TXCTX_HITS); let has_above = mi_r > n.tile_row0_mi; let has_left = mi_c > n.tile_col0_mi; let mut above = usize::from(n.above_txfm[mi_c]) >= own_w; let mut left = usize::from(n.left_txfm[mi_r]) >= own_h; if has_above && n.above_inter[mi_c] { above = usize::from(n.above_side_mi[mi_c]) >= own_w; } if has_left && n.left_inter[mi_r] { left = usize::from(n.left_side_mi[mi_r]) >= own_h; } if crate::envflags::env_flag!("EC_TXCTX") { eprintln!( "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \ above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \ above={above} left={left}", n.above_txfm[mi_c], n.left_txfm[mi_r], n.above_inter[mi_c], n.left_inter[mi_r], n.above_side_mi[mi_c], n.left_side_mi[mi_r], ); } let ctx = match (has_above, has_left) { (true, true) => usize::from(above) + usize::from(left), (true, false) => usize::from(above), (false, true) => usize::from(left), (false, false) => 0, }; // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect // intra in an inter frame" tally is green on the buggy code too (class // gate-blind-to-feature). if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() { let (cw, ch) = (own_w.min(64), own_h.min(64)); let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw) + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch); if ctx != stale { hit!(INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS); } } ctx } /// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they /// are written and read everywhere else with a raw mi index); the SUB-cell /// division this pair used read a cell four blocks away, so the inter-neighbour /// override above fired on the wrong neighbour -- the first divergence of the /// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1, /// at the intra block right of an inter one). fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize { let has_above = mi_r > n.tile_row0_mi; let has_left = mi_c > n.tile_col0_mi; let mut above = usize::from(n.above_txfm[mi_c]) >= side; let mut left = usize::from(n.left_txfm[mi_r]) >= side; // lane-angledelta r1 (class [[context-read-from-one-cell]]): both // `above_inter`/`left_inter` bands are written per MI unit // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB / // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different // block whenever the neighbour column/row is not the cell's first. A // 16x16 intra block whose left neighbour is an inter block at mi row 4 // then missed libaom's "an inter neighbour contributes its BLOCK size" // override and read `tx_size_cat1` row 1 where aomdec reads row 2. if has_above && n.above_inter[mi_c] { above = usize::from(n.above_side_mi[mi_c]) >= side; } if has_left && n.left_inter[mi_r] { left = usize::from(n.left_side_mi[mi_r]) >= side; } if crate::envflags::env_flag!("EC_TXCTX") { eprintln!( "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \ above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \ above={above} left={left}", n.above_txfm[mi_c], n.left_txfm[mi_r], n.above_inter[mi_c], n.left_inter[mi_r], n.above_side_mi[mi_c], n.left_side_mi[mi_r], ); } match (has_above, has_left) { (true, true) => usize::from(above) + usize::from(left), (true, false) => usize::from(above), (false, true) => usize::from(left), (false, false) => 0, } } /// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under /// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to /// the transform's own side in pixels (`side >> depth`) -- this decoder's /// four square categories (8/16/32/64) each halve at most twice, matching /// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`). fn read_tx_size( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: &Neighbours, at_mi: (usize, usize), side: usize, // lane-txselect: `get_tx_size_context`'s real context, for the callers // that have one -- see [`tx_size_context_txfm`]. `None` keeps the // key-frame path's own deblock-grid approximation. ctx_override: Option, ) -> usize { // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` / // `get_tx_size_context`): a block wider than 64 still tops out at // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth // chain 64->32->16->8->4 is the same four steps) and resolves against 64, // never against its own 128 side (lane-sb128b r1). let max_tx = side.min(64); let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx)); let depth = match max_tx { 8 => { dec.symbol(&mut cdfs.tx_size_cat0[ctx]) } 16 => { dec.symbol(&mut cdfs.tx_size_cat1[ctx]) } 32 => { dec.symbol(&mut cdfs.tx_size_cat2[ctx]) } 64 => { dec.symbol(&mut cdfs.tx_size_cat3[ctx]) } _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"), }; if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { let (rng, _) = dec.debug_state(); let (mi_r, mi_c) = at_mi; eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}" ); } if depth != 0 { hit!(TX_DEPTH_HITS); } max_tx >> depth } /// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's /// `txfm_split` context -- a category from the block's own largest square /// transform and whether this unit already sits below it, times three, plus /// the two neighbour terms (whether the transform last written above/left of /// this unit is narrower/shorter than the unit itself). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize { txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px) } /// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2): /// libaom's `txfm_partition_context` compares the above context against /// `tx_size_wide` and the left one against `tx_size_high`, and takes its /// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one /// side for a square transform, which is why the square form above is a /// special case of this one. pub(crate) fn txfm_partition_ctx_rect( above_px: u8, left_px: u8, blk_max_px: usize, tx_w: usize, tx_h: usize, ) -> usize { let above = usize::from(usize::from(above_px) < tx_w); let left = usize::from(usize::from(left_px) < tx_h); let tx_px = tx_w.max(tx_h); // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as // `log2(px) - 2`. let max_tx = blk_max_px.min(64); let max_idx = max_tx.trailing_zeros() as usize - 2; let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2; category * 3 + above + left } /// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit /// resolves, every mi cell its *parent* unit (`txb_px`) spans records the /// resolved transform's own size. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn txfm_partition_update( n: &mut Neighbours, at_mi: (usize, usize), tx_px: usize, txb_px: usize, ) { txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px)); } /// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2): /// the left column records `tx_size_high` over the parent's own height and /// the above row records `tx_size_wide` over its width. /// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of /// `decode_token_recon_block`): EVERY block of an inter frame publishes its /// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The /// key frame writes neither (its readers use the deblock grid), so the /// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it /// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it /// at the call site (the transform size comes back to them); the 1:4 arms /// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside, /// so they call this where their own depth resolves. A no-op on a key frame /// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all. /// /// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an /// inter frame left `left_txfm[0]` at a stale 32 where libaom's own /// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read /// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF, /// range 39156 where the reference has 54736 (class tx-grid-published-block-side /// / early-return-skips-tail). fn publish_txfm_bands_if_in_inter( n: &mut Neighbours, at_mi: (usize, usize), (tx_w, tx_h): (usize, usize), (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx, ) { if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() { return; } let (mi_r, mi_c) = at_mi; txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); for i in 0..bw / MI { if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { *cell = tx_w as u8; } } for i in 0..bh / MI { if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { *cell = tx_h as u8; } } } fn txfm_partition_update_rect( n: &mut Neighbours, (mi_r, mi_c): (usize, usize), (tx_w, tx_h): (usize, usize), (txb_w, txb_h): (usize, usize), ) { if crate::envflags::env_flag!("EC_TXUPD") { eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c); } for i in 0..txb_h / MI { if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { *cell = tx_h as u8; } } for i in 0..txb_w / MI { if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { *cell = tx_w as u8; } } } /// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the /// same contexts -- a skipped *inter* block records its own block size rather /// than its transform size. fn set_txfm_ctxs( n: &mut Neighbours, (mi_r, mi_c): (usize, usize), tx_px: usize, w_mi: usize, h_mi: usize, skip_inter: bool, ) { if crate::envflags::env_flag!("EC_TXUPD") { eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}"); } let bw = if skip_inter { w_mi * MI } else { tx_px }; let bh = if skip_inter { h_mi * MI } else { tx_px }; for i in 0..w_mi { if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { *cell = bw as u8; } } for i in 0..h_mi { if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { *cell = bh as u8; } } } /// The value libaom initialises both transform contexts to -- NOT zero: /// `av1_zero_above_context` memsets the txfm row to /// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same /// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64 /// pixels, so an unwritten neighbour reads as the *widest* possible /// transform, not the narrowest. pub(crate) const TXFM_CTX_INIT: u8 = 64; /// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most /// twice below its own largest transform. const MAX_VARTX_DEPTH: usize = 2; /// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform /// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes /// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1 /// small ones, square everywhere else. fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) { match (tx_w, tx_h) { (4, 4) => (4, 4), (8, 8) => (4, 4), (16, 16) => (8, 8), (32, 32) => (16, 16), (64, 64) => (32, 32), (4, 8) | (8, 4) => (4, 4), (8, 16) | (16, 8) => (8, 8), (16, 32) | (32, 16) => (16, 16), (32, 64) | (64, 32) => (32, 32), (4, 16) => (4, 8), (16, 4) => (8, 4), (8, 32) => (8, 16), (32, 8) => (16, 8), (16, 64) => (16, 32), (64, 16) => (32, 16), _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"), } } #[test] fn sub_tx_size_map_matches_libaom() { // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order. const TABLE: [((usize, usize), (usize, usize)); 19] = [ ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)), ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)), ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)), ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)), ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)), ]; for (tx, want) in TABLE { assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})"); } } /// The domain of var-tx leaf sizes, enumerated against the two refusals that /// name a leaf "larger than 32x32" / "larger than 64x64". /// /// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is /// either the unit it was entered with or a `sub_tx_size_map` step below it: /// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early /// return. So the leaf set reachable from an entry unit is that unit plus the /// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` -- /// which this test enumerates, and over which no leaf is ever larger than the /// entry. /// /// That closes both refusals: /// /// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit /// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than /// 64x64" names a leaf the tree cannot produce; /// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32 /// below the 128 root. The only entry that exceeds that ceiling is 64x64, /// reached only when `side == 64`, and then the block is ONE unit whose only /// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single` /// case the refusal is guarded by. #[test] fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() { // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h). fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) { out.push((depth, entry.0, entry.1)); if depth == MAX_VARTX_DEPTH { return; } let sub = sub_tx_size_map(entry.0, entry.1); if sub == (4, 4) { out.push((depth + 1, 4, 4)); return; } reachable(sub, depth + 1, out); } for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] { let mut leaves = Vec::new(); reachable(entry, 0, &mut leaves); for (depth, w, h) in &leaves { assert!( w.max(h) <= &entry.0.max(entry.1), "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}", entry.0, entry.1 ); } // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0. if entry == (64, 64) { let above: Vec<&(usize, usize, usize)> = leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect(); assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32"); } } // The entry size and ceiling each caller uses, over the block sides that // reach them (`read_block_tx_size`'s square path; the 128-root rect path // enters at a fixed 64). for side in [8usize, 16, 32, 64, 128] { let max_tx = side.min(64); let ceiling = if side > 64 { 64 } else { 32 }; let units = (side / max_tx) * (side / max_tx); if max_tx <= ceiling { continue; } assert_eq!( (side, units), (64, 1), "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \ {units} units -- an above-ceiling leaf there would NOT be the `single` case" ); } } /// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c` /// `read_tx_size_vartx`): the recursive `txfm_split` tree of one /// max-transform-sized unit of an inter block, collecting the resolved leaf /// transform units into `out` as `(row offset, col offset, side)` in mi units /// -- exactly the order `decode_reconstruct_tx` later reads their /// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block; /// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/ /// `max_block_high`). #[allow(clippy::too_many_arguments)] fn read_var_tx_size( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: &mut Neighbours, at_mi: (usize, usize), blk_max_px: usize, (max_w_mi, max_h_mi): (usize, usize), (tx_w, tx_h): (usize, usize), depth: usize, blk_row: usize, blk_col: usize, out: &mut Vec<(usize, usize, usize, usize)>, ) { if blk_row >= max_h_mi || blk_col >= max_w_mi { return; } let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col); if depth == MAX_VARTX_DEPTH { out.push((blk_row, blk_col, tx_w, tx_h)); txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h)); return; } let ctx = txfm_partition_ctx_rect( n.above_txfm[unit.1], n.left_txfm[unit.0], blk_max_px, tx_w, tx_h, ); let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; hit!(TXFM_SPLIT_READS); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { let (rng, _) = dec.debug_state(); eprintln!( "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}", unit.0, unit.1, u8::from(split) ); } if !split { out.push((blk_row, blk_col, tx_w, tx_h)); txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h)); return; } hit!(TXFM_SPLIT_HITS); let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h); if (sub_w, sub_h) == (4, 4) { // libaom's `sub_txs == TX_4X4` early return: every mi cell of the // unit is marked 4x4 (raster order) without recursing. for row in 0..tx_h / MI { for col in 0..tx_w / MI { if blk_row + row < max_h_mi && blk_col + col < max_w_mi { out.push((blk_row + row, blk_col + col, 4, 4)); } } } txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h)); return; } for row in (0..tx_h / MI).step_by(sub_h / MI) { for col in (0..tx_w / MI).step_by(sub_w / MI) { read_var_tx_size( dec, cdfs, n, at_mi, blk_max_px, (max_w_mi, max_h_mi), (sub_w, sub_h), depth + 1, blk_row + row, blk_col + col, out, ); } } } /// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx /// branch): every block of a `TxMode::Select` inter frame codes its transform /// size right after its own mode info -- an inter non-skip block through the /// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns), /// every other block through the intra `tx_depth` symbol (a skipped inter /// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the /// block's own resolved transform side and the leaf list, the latter only /// when the tree resolved to more than one transform unit. #[allow(clippy::too_many_arguments)] fn read_block_tx_size( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: &mut Neighbours, at_mi: (usize, usize), side: usize, (mi_cols, mi_rows): (usize, usize), is_inter: bool, skip: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(usize, Option>)> { if !fctx.tx_select_inter.with(std::cell::Cell::get) { // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64, // so a 128x128 inter block is FOUR luma units even with `tx_mode == // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back. // lane-sb128c r3: intra too -- an INTRA 128x128 block under // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units. if side > 64 { let step = 64 / MI; let mut leaves = Vec::new(); for row in (0..side / MI).step_by(step) { for col in (0..side / MI).step_by(step) { leaves.push((row, col, 64, 64)); } } return Ok((64, Some(leaves))); } return Ok((side, None)); } let side_mi = side / MI; if is_inter && !skip { let max_tx = side.min(64); let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1)); let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0)); let mut leaves = Vec::new(); let step = max_tx / MI; for row in (0..side_mi).step_by(step) { for col in (0..side_mi).step_by(step) { read_var_tx_size( dec, cdfs, n, at_mi, side, (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves, ); } } let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side; // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves, // which the mu-chunk reader above codes as their 32x32 coded corner. let leaf_ceiling = if side > 64 { 64 } else { 32 }; if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) { // Only a block wider than a superblock's own 64x64 max transform // reaches here; this crate has no 64-point *inter* coefficient // table set ([`inter_txbset_for`] stops at 32). return Err(unsupported( "an inter var-tx tree with a leaf transform larger than 32x32", )); } let resolved = leaves.last().map_or(side, |l| l.2); return Ok((resolved, (!single).then_some(leaves))); } let tx = if is_inter { side.min(64) } else { read_tx_size( dec, cdfs, n, at_mi, side, // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`, // which is 64 for BLOCK_128X128 -- never the block's own 128 side. Some(tx_size_context_txfm(n, at_mi, side.min(64))), ) }; set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter); if !is_inter && tx != side { // lane-intrainter r1: an intra block inside an inter frame whose // `tx_depth` split its luma transform codes exactly the key-frame // split path's transform units (`decode_block`'s multi-TU loop), // raster order over the block. Handed back in the same leaf shape the // inter var-tx tree uses, so the caller's per-TU luma loop, the // `record_split_luma` neighbour write-back and the per-TU deblock // edges are the ones it already runs for a var-tx inter block. A // caller that has no per-TU intra loop (the 8x8 leaf) refuses on // seeing `Some` here. let step = tx / MI; let mut leaves = Vec::new(); for row in (0..side_mi).step_by(step) { for col in (0..side_mi).step_by(step) { leaves.push((row, col, tx, tx)); } } hit_do! { INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| { let mut h = c.get(); h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1; c.set(h); }); } return Ok((tx, Some(leaves))); } Ok((tx, None)) } /// lane-inter4 r2: the shapes whose *rectangular inter* residual this /// decoder codes -- a 2:1 strip whose own max rect transform /// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a /// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient /// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a /// 64-point rect transform, and 16x8/8x16 needs /// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol /// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a /// rect transform), neither of which exists yet -- both stay refused by name. pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool { matches!( (w, h), // 2:1 strips whose transform is coded in full (lane-inter4). (32, 16) | (16, 32) | (16, 8) | (8, 16) // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16 // codes all 64 of its positions, and its chroma pair is an 8x4 / // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4). | (16, 4) | (4, 16) // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes // only the low 32 coefficients of a 64-length axis, so these read // exactly the truncated corner the INTRA superblock-strip path // already reads (`read_intra_mode_rect`), through // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no // `tx_type` symbol is coded at all. | (64, 32) | (32, 64) | (64, 16) | (16, 64) // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves. // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is // refused earlier ("an inter partition below 8x8"). | (8, 4) | (4, 8) // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT // one rectangular transform -- `max_txsize_rect_lookup // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square // TX_64X64 units read through the mu-chunk loop, same as the // 128x128 NONE block's four. | (128, 64) | (64, 128) // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both // 10-bit film cuts and every measured 1080p offset stop on // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else). // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 // positions, and its chroma pair is a 16x4 / 4x16 unit // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4). | (32, 8) | (8, 32) ) } // lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path // actually PRESENTS, as a thread-local bitmask -- the measured domain behind // the "rectangular ... has no ... here" refusals. `side` is the square context // a block reads its CDFs at and `write_w`/`write_h` its true footprint; // `inter_piece!` derives `reject_residual` from exactly that inequality, so // these triples are what decides whether those refusals can fire at all. Bit // 31 is "a triple this table does not list", which is what makes the gate a // census rather than a restatement of its own table. pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [ (16, 16, 16), (32, 32, 32), (32, 16, 32), (32, 32, 16), (16, 8, 16), (16, 16, 8), (32, 8, 32), (64, 64, 64), (32, 32, 8), (64, 16, 64), (128, 128, 128), (64, 32, 64), (64, 64, 32), (16, 4, 16), (64, 64, 16), (16, 16, 4), (128, 128, 64), (128, 64, 128), ]; /// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple /// outside [`INTER_BLOCK_SHAPES`]. pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31; thread_local! { static INTER_BLOCK_SHAPE_MASK: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a /// gate reading it sees only the streams it decoded itself). pub fn inter_block_shape_mask() -> u32 { INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get) } /// Records one block's shape. The table is ordered by measured frequency over /// the three witnesses the census gate decodes, so the common square shapes /// leave the scan on their first comparison. fn census_inter_block_shape(side: usize, w: usize, h: usize) { let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) { Some(i) => 1u32 << i, None => INTER_BLOCK_SHAPE_UNLISTED, }; let seen = inter_block_shape_mask(); if seen & bit == 0 { INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit)); } } /// The luma coefficient/`tx_type` table set of a whole-block rectangular /// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits /// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so /// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of /// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and /// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced /// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF /// row (`txsize_sqr_map`), never the 16x16 one. fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result { Ok(match (w, h) { (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter, // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip. // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up == // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced, // ALL16 otherwise -- both at the TX_4X4 row. (8, 4) | (4, 8) => { if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) { TxbSet::LumaRect8x4Inter } else { TxbSet::LumaRect8x4InterSet1 } } (16, 4) | (4, 16) => { if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) { TxbSet::LumaRect16x4Inter } else { TxbSet::LumaRect16x4Inter1 } } (16, 8) | (8, 16) => { if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) { TxbSet::LumaRect16x8Inter } else { TxbSet::LumaRect16x8InterSet1 } } // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the // adjusted size, so the existing sets are bit-exact. Neither carries a // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot. // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER` // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row. (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter, (64, 32) | (32, 64) => TxbSet::Luma64, (64, 16) | (16, 64) => TxbSet::LumaRect32x16, _ => { return Err(unsupported( "a rectangular inter luma transform unit whose shape has no coefficient table set here", )); } }) } /// The chroma table set of the same block's single rectangular chroma unit /// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8 /// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit /// the luma unit's. fn rect_inter_chroma_set(w: usize, h: usize) -> Result { Ok(match (w, h) { (16, 8) | (8, 16) => TxbSet::ChromaRect16x8, (8, 4) | (4, 8) => TxbSet::ChromaRect8x4, // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma // unit has a 64-px axis, so both are coded in full; `Chroma16` is the // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16, // `txsize_log2_minus4` = 4), same as the intra strip path uses. (32, 16) | (16, 32) => TxbSet::ChromaRect32x16, (32, 8) | (8, 32) => TxbSet::Chroma16, // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8, // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`). (16, 4) | (4, 16) => TxbSet::Chroma8, _ => { return Err(unsupported( "a rectangular inter chroma transform unit whose shape has no coefficient table set here", )); } }) } /// libaom `size_group_lookup[bsize]` for the block shapes this decoder's /// inter path reaches, from the block's TRUE footprint rather than the /// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2, /// everything 32 and above -> 3. fn size_group_wh(w: usize, h: usize) -> usize { // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom // `common_data.h:60`) is 0 for every block with a 4-px side // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0. match w.min(h) { 0..=4 => 0, 8 => 1, 16 => 2, _ => 3, } } #[test] fn size_group_wh_matches_libaom_size_group_lookup() { // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s // transcribed values (common_data.h:60-62). const TABLE: [((usize, usize), usize); 22] = [ ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1), ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3), ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3), ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2), ]; for ((w, h), want) in TABLE { assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})"); } } /// The default (2D) coefficient scan of a rectangular transform. fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> { Ok(match (w, h) { (32, 16) => &SCAN_32X16, (16, 32) => &SCAN_16X32, (16, 8) => &SCAN_16X8, (8, 16) => &SCAN_8X16, (16, 4) => &SCAN_16X4, (4, 16) => &SCAN_4X16, (8, 4) => &SCAN_8X4, (4, 8) => &SCAN_4X8, (32, 8) => &SCAN_32X8, (8, 32) => &SCAN_8X32, _ => { return Err(unsupported( "a rectangular transform unit whose shape has no coefficient scan table here", )); } }) } /// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma /// transform unit whose shape has no coefficient table set here" / "a /// rectangular transform unit whose shape has no coefficient scan table here" /// arms, enumerated against the MEASURED domain of the inter block path /// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate /// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`). /// /// What each helper is actually handed: /// /// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the /// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is /// square for every rect transform except TX_16X4/TX_4X16, whose leaves are /// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8. /// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0 /// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8. /// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect /// unit, and only when that corner is not 32x32 (a square corner goes /// through the square reader with `rect_shape = Some((w, h))`). /// /// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is /// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk /// loop, which is why they are skipped below. #[test] fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() { let fctx = &crate::decode::FrameCtx::new(); let corner_scan = |w: usize, h: usize| { let (cw, ch) = (w.min(32), h.min(32)); if (cw, ch) == (32, 32) { return; // the square coefficient reader, not `rect_scan` } assert!( rect_scan(cw, ch).is_ok(), "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table" ); }; let mut checked = 0; for &(side, w, h) in &INTER_BLOCK_SHAPES { if (w, h) == (side, side) || w.max(h) > 64 { continue; } assert!( rect_inter_luma_set(w, h, fctx).is_ok(), "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one" ); corner_scan(w, h); // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved // footprint for every other shape. let (cw, ch) = match (w, h) { (16, 4) => (8, 4), (4, 16) => (4, 8), _ => (w / 2, h / 2), }; assert!( rect_inter_chroma_set(cw, ch).is_ok(), "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set" ); corner_scan(cw, ch); checked += 1; } assert_eq!( checked, 12, "the block-shape census changed: {checked} rect shapes reach the rect transform \ tables, not the 12 this claim was measured over" ); // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf // shapes, which reach `rect_inter_luma_set` as `(tw, th)`. for (w, h) in [(8usize, 4usize), (4, 8)] { assert!( rect_inter_luma_set(w, h, fctx).is_ok(), "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set" ); corner_scan(w, h); } } /// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2): /// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own /// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The /// depth-0 `txfm_partition` symbol reads its context off the rect transform's /// own width/height; a `0` leaves one whole-block rect transform unit /// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE /// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the /// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so /// every leaf of a split rect block is square and the existing square leaf /// loop reconstructs it unchanged. #[allow(clippy::too_many_arguments)] fn read_block_tx_size_rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: &mut Neighbours, at_mi: (usize, usize), (bw, bh): (usize, usize), (mi_cols, mi_rows): (usize, usize), skip: bool, fctx: &crate::decode::FrameCtx, ) -> Result>> { if skip { // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records // its own BLOCK size -- width above, height left -- not a transform. txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh)); return Ok(None); } // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and // `rect_inter_residual_supported` has already excluded everything above 32. // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block // is TWO square top-level transform units side by side and a 64x128 one is // two stacked -- exactly what libaom `read_block_tx_size` // (decodeframe.c:1140) codes with its `idy/idx` loop over // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its // own `txfm_partition` symbol at depth 0. if bw.max(bh) > 64 { let tx = 64usize; let (max_w_mi, max_h_mi) = ( (bw / MI).min(mi_cols.saturating_sub(at_mi.1)), (bh / MI).min(mi_rows.saturating_sub(at_mi.0)), ); let mut leaves = Vec::new(); if !fctx.tx_select_inter.with(std::cell::Cell::get) { for row in (0..bh / MI).step_by(tx / MI) { for col in (0..bw / MI).step_by(tx / MI) { leaves.push((row, col, tx, tx)); } } for &(row, col, tw, th) in &leaves { txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th)); } return Ok(Some(leaves)); } for row in (0..bh / MI).step_by(tx / MI) { for col in (0..bw / MI).step_by(tx / MI) { read_var_tx_size( dec, cdfs, n, at_mi, bw.max(bh), (max_w_mi, max_h_mi), (tx, tx), 0, row, col, &mut leaves, ); } } if leaves.iter().any(|l| l.2.max(l.3) > 64) { return Err(unsupported( "an inter var-tx tree with a leaf transform larger than 64x64", )); } return Ok(Some(leaves)); } let (tx_w, tx_h) = (bw, bh); if !fctx.tx_select_inter.with(std::cell::Cell::get) { // `TX_MODE_LARGEST`: no symbol at all, the whole block is one // transform, and `set_txfm_ctxs` records exactly what // `txfm_partition_update` would for that same unit. txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); hit!(RECT_INTER_TU_HITS); return Ok(None); } let ctx = txfm_partition_ctx_rect( n.above_txfm[at_mi.1], n.left_txfm[at_mi.0], bw.max(bh), tx_w, tx_h, ); let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; hit!(TXFM_SPLIT_READS); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { let (rng, _) = dec.debug_state(); eprintln!( "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}", at_mi.0, at_mi.1, u8::from(split) ); } if !split { txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); hit!(RECT_INTER_TU_HITS); return Ok(None); } hit!(TXFM_SPLIT_HITS); hit!(RECT_INTER_TXSPLIT_HITS); // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`, // `[TX_16X64] == TX_16X32` -- so the recursion below is the general // rect one and its leaves carry their own width and height. let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h); let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1)); let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0)); let mut leaves = Vec::new(); for row in (0..bh / MI).step_by(sub_h / MI) { for col in (0..bw / MI).step_by(sub_w / MI) { read_var_tx_size( dec, cdfs, n, at_mi, bw.max(bh), (max_w_mi, max_h_mi), (sub_w, sub_h), 1, row, col, &mut leaves, ); } } Ok(Some(leaves)) } /// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2): /// the coefficients are read with the rect coefficient machinery /// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*` /// types), inverted with the rect inverse transform /// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale), /// and added onto the top-left `w x h` of the block's own square-strided /// motion-compensated prediction buffer. Returns the *rect* coefficient grid /// and the coded `tx_type`. /// /// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e. /// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch. #[allow(clippy::too_many_arguments)] fn read_inter_plane_rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, set: TxbSet, (w, h): (usize, usize), stride: usize, plane_idx: usize, around: (bool, bool, i32), tx_mode: usize, // lane-wave1 step (i): unread -- this reader records its write // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow // stays in the signature so every call site still proves the plane is // exclusively held while its coefficients are parsed. _plane: &mut PlaneBuf<'static>, x: usize, y: usize, prediction: Pred<'_>, inherited_luma_tx_type: Option, luma_skip_ctx: Option, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, TxType)> { let skip_ctx = if plane_idx == 0 { // `get_txb_ctx_general`: 0 only when this unit IS the whole plane // block; a var-tx leaf passes its own neighbour-table context. luma_skip_ctx.unwrap_or(0) } else { usize::from(around.0) + usize::from(around.1) }; let mut coding = cdfs.txb(set, tx_mode); // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e. // the *longer* side of this rect transform. let default_tx_type = match inherited_luma_tx_type { Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx), None => TxType::DctDct, }; // lane-r14 r2: a 64-length axis codes only its low 32 coefficients // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)` // corner, zero-extended into the true `w x h` grid before the inverse // transform -- exactly what the intra superblock-strip path does. A // corner that comes out square (32x32, under a 64x32/32x64 strip) reads // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`, // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted // rectangular shape (lane-sbpart r8). let (cw, ch) = (w.min(32), h.min(32)); if plane_idx == 0 && w.max(h) == 64 { hit!(RECT64_INTER_TU_HITS); } if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) { hit_do! { RECT32X8_INTER_TU_HITS.with(|c| { let mut v = c.get(); v[usize::from(w == 8)] += 1; c.set(v); }); } } let (corner, tx_type) = if (cw, ch) == (32, 32) { let scan32 = default_scan(TX32); read_coeffs( dec, &mut coding, &scan32, skip_ctx, dc_sign_ctx(around.2), default_tx_type, Some((w, h)), )? } else { read_coeffs_rect( dec, &mut coding, rect_scan(cw, ch)?, cw, ch, skip_ctx, dc_sign_ctx(around.2), default_tx_type, )? }; let grid = extend_corner(corner, cw, ch, w, h); let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx); if crate::envflags::env_flag!("EC_TRACE_TXTYPE") { eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}"); } // `reconstruct_mc_rect` reads both buffers at the square prediction // stride, so the dense `w x h` residual is re-laid at that stride // (`TxParams::stride`) after the inverse transform. let tx = TxParams { w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type, stride, }; push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx); Ok((grid, tx_type)) } /// The coded `cw x ch` corner of a transform zero-extended into its true /// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A /// corner that coded nothing stays the shared zero grid -- no allocation /// (lane-coefgrid). fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid { if (cw, ch) == (w, h) { return corner; } if let Grid::Zero(_) = corner { return Grid::Zero(w * h); } let mut full = vec![0i32; w * h]; for row in 0..ch { full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]); } Grid::Own(full) } /// A rect coefficient grid re-laid into the square `stride x stride` grid the /// neighbour/deblock stamps downstream of the residual expect. fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec { let mut full = vec![0i32; stride * stride]; for row in 0..h { full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]); } full } /// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8 /// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single /// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in /// raster order, each reading its own coefficient context off the units /// already decoded before it. Returns the block's luma grid (all-zero in the /// split case, whose reconstruction has already happened unit by unit) and /// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup, /// which for a split block lands on the top-left unit. #[allow(clippy::too_many_arguments)] fn read_inter_luma8( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, leaf_mi: (usize, usize), y: &mut PlaneBuf<'static>, px: usize, py: usize, pred_y: Pred<'_>, mode_for_tx: usize, base_q_idx: u8, scan8: &[u16], scan4: &[u16], reduced_tx_set: bool, split: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, TxType)> { if !split { return read_inter_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma8Inter } else { TxbSet::Luma8InterSet1 }, scan8, 0, neighbours.around_mi(leaf_mi, 8)[0], mode_for_tx, y, px, py, 8, base_q_idx, pred_y, None, None, fctx, ); } let mut first = TxType::DctDct; for tu_row in 0..2 { for tu_col in 0..2 { let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col); let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); let (tu_grid, tu_tx_type) = read_inter_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 }, scan4, 0, neighbours.around_mi(tu_mi, 4)[0], mode_for_tx, y, px + tu_col * 4, py + tu_row * 4, 4, base_q_idx, tu_pred, None, Some(tu_skip_ctx), fctx, )?; if tu_row == 0 && tu_col == 0 { first = tu_tx_type; } neighbours.record_mi_luma(tu_mi, 4, &tu_grid); } } Ok((Grid::Zero(64), first)) } /// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its /// coefficient tables from -- the inter counterpart of [`txbset_for`]. /// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`): /// an inter block's chroma transform inherits the *colocated luma* unit's /// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member /// of the extended set the CHROMA transform size selects /// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`, /// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at /// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is /// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads /// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded /// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are /// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in /// sync and only corrupted the inverse transform (one 64x64 superblock of /// high-frequency chroma noise, luma bit-exact). fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType { use TxType::*; let sqr_up = w.max(h); let sqr = w.min(h); let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`. let allowed: &[TxType] = if sqr_up > 32 { // EXT_TX_SET_DCTONLY &[DctDct] } else if sqr_up == 32 || reduced { // EXT_TX_SET_DCT_IDTX &[DctDct, Idtx] } else if sqr == 16 { // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but // the four 1D ADST/FLIPADST types. &[ DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst, AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct, ] } else { // EXT_TX_SET_ALL16 return t; }; if allowed.contains(&t) { t } else { DctDct } } fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet { match tx_px { // lane-sb128c r1: a 128x128 inter block's own luma unit // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`). // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up == // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets // coincide -- exactly the set the whole-64x64 inter block already uses. 64 => TxbSet::Luma64, 32 => TxbSet::Luma32Inter, 16 if reduced_tx_set => TxbSet::Luma16Inter, 16 => TxbSet::Luma16InterSet1, 8 if reduced_tx_set => TxbSet::Luma8Inter, 8 => TxbSet::Luma8InterSet1, 4 if reduced_tx_set => TxbSet::Luma4Inter, 4 => TxbSet::Luma4InterSet1, _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"), } } /// The luma coefficient scan table for a resolved transform side -- 32/16/8/4, /// the only four sizes a `TxMode::Select` block's coded coefficient grid /// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be. fn scan_for<'a>( tx_px: usize, scan32: &'a [u16], scan16: &'a [u16], scan8: &'a [u16], scan4: &'a [u16], ) -> &'a [u16] { match tx_px { 32 => scan32, 16 => scan16, 8 => scan8, 4 => scan4, _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"), } } /// The [`TxbSet`] a resolved luma transform side reads its coefficient tables /// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case /// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching /// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at /// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2` /// regardless of the flag (`av1_get_ext_tx_set_type`'s /// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past /// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a /// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]). /// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which /// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the /// inter `ext_tx` sets, never the mode-indexed intra ones. fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet { match tx_px { 64 => TxbSet::Luma64, 32 => TxbSet::Luma32Inter, 16 if reduced_tx_set => TxbSet::Luma16Inter, 16 => TxbSet::Luma16InterSet1, 8 if reduced_tx_set => TxbSet::Luma8Inter, 8 => TxbSet::Luma8InterSet1, _ => TxbSet::Luma64, } } fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet { match tx_px { 64 => TxbSet::Luma64, 32 => TxbSet::Luma32, 16 => TxbSet::Luma16, 8 if reduced_tx_set => TxbSet::Luma8, 8 => TxbSet::Luma8Set1, 4 if reduced_tx_set => TxbSet::Luma4, 4 => TxbSet::Luma4Set1, _ => unreachable!("read_tx_size never resolves a block's own side to anything else"), } } /// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the /// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on. fn unit_log2(px: u32) -> i32 { if px == 0 { 0 } else { px.trailing_zeros() as i32 - 2 } } /// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's /// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for /// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode /// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell: /// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2: /// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable /// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME` /// block anywhere aborted the whole stream's decode before comparison). fn lf_level( lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8, delta_lf: i32, segment_id: u8, fctx: &crate::decode::FrameCtx, ) -> i32 { let base = i32::from(if plane_idx == 0 { lf.level[dir] } else if plane_idx == 1 { lf.level[2] } else { lf.level[3] }); // spec 7.14.4: the per-superblock `DeltaLF` term applies before the // ref/mode delta scaling below, and regardless of `delta_enabled` // (that flag only gates `ref_deltas`/`mode_deltas`). let base = (base + delta_lf).clamp(0, 63); // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the // per-superblock `DeltaLF` term and before the ref/mode deltas below. // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4) // for chroma. let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 }; // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely // when the frame codes no segmentation (`seg_lf_active`), which is what // spares the deblock loop two thread-local reads per 4x4 edge. let base = match seg_feature(usize::from(segment_id), feature, fctx) { Some(data) => (base + data).clamp(0, 63), None => base, }; if !lf.delta_enabled { return base; } let scale = 1i32 << (base >> 5); let is_inter = ref_frame != 0; let is_globalmv = ref_frame < 0; let ref_idx = ref_frame.unsigned_abs() as usize; let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale; if is_inter { lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale; } lvl.clamp(0, 63) } thread_local! { /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table /// is a pure function of the frame's [`LoopFilterParams`], the plane, the /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one /// build per plane and pass serves the whole frame. The pipeline builds /// an `EdgeCtx` per superblock-row band rather than per frame, which /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each. static LVL_CACHE: std::cell::RefCell< Vec<((usize, usize, LoopFilterParams, Option), [[u8; 15]; 64])>, > = const { std::cell::RefCell::new(Vec::new()) }; } /// `lf_level` over the whole `(base level, ref frame)` domain -- see /// [`LVL_CACHE`]. `lf_level`'s own first step is /// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at /// `b` and the rest of the function is a pure function of `(b, ref_frame)`. fn lvl_table( lf: &LoopFilterParams, plane_idx: usize, dir: usize, base0: i32, fctx: &crate::decode::FrameCtx, ) -> [[u8; 15]; 64] { let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 }; let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx)); if let Some(t) = LVL_CACHE.with(|c| { c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t) }) { return t; } let mut lvl = [[0u8; 15]; 64]; for (b, row) in lvl.iter_mut().enumerate() { for (r, cell) in row.iter_mut().enumerate() { *cell = lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8; } } LVL_CACHE.with(|c| { let mut c = c.borrow_mut(); if c.len() >= 8 { c.remove(0); } c.push((key, lvl)); }); lvl } /// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level, /// no-segmentation, no-delta-LF path and to this decoder's own invariant /// that a coded block's transform is always its own full size -- so a TU /// edge is always also a PU edge, and the "both sides skipped, not a PU /// edge" suppression (which only ever fires at a non-PU-edge TU boundary) /// never applies here, letting this skip the `skip`/`skip_txfm` lookup /// entirely. Returns `None` when this 4-pixel edge group is not filtered. /// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the /// seven values that used to be re-passed per 4-pixel edge group -- half of /// them on the stack, into an `inline(never)` body -- plus libaom's /// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the /// filter level for every `(base level, ref frame)` pair once per frame /// instead of running `av1_get_filter_level`'s delta arithmetic per edge. struct EdgeCtx<'a> { lf: &'a LoopFilterParams, n: &'a Neighbours, fctx: &'a crate::decode::FrameCtx, plane_idx: usize, dir: usize, chroma: bool, seg_lf_active: bool, /// `delta_lf_grid`'s column for this plane and direction. delta_idx: usize, /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for /// chroma. step: usize, /// This pass's own `lf.level[..]`, the LUT's base. base0: i32, /// `lf_level` at `[base level][ref frame + 7]`, with no segment /// override -- the whole domain, since a level is `0..=63` and a ref /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8 /// entries and is indexed by the ref frame's magnitude). lvl: [[u8; 15]; 64], } impl<'a> EdgeCtx<'a> { fn new( lf: &'a LoopFilterParams, n: &'a Neighbours, plane_idx: usize, dir: usize, chroma: bool, seg_lf_active: bool, fctx: &'a crate::decode::FrameCtx, ) -> Self { let base0 = i32::from(if plane_idx == 0 { lf.level[dir] } else if plane_idx == 1 { lf.level[2] } else { lf.level[3] }); let lvl = lvl_table(lf, plane_idx, dir, base0, fctx); Self { lf, n, fctx, plane_idx, dir, chroma, seg_lf_active, delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 }, step: if chroma { 2 } else { 1 }, base0, lvl, } } /// Spec 7.14.4's `get_filter_level`, off the table when no segment can /// override it (which is every frame that codes no segmentation). #[inline(always)] fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 { if self.seg_lf_active { return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx); } let b = (self.base0 + delta_lf).clamp(0, 63) as usize; debug_assert!((-7..=7).contains(&ref_frame)); let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize; i32::from(self.lvl[b][r]) } } /// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level, /// no-segmentation, no-delta-LF path and to this decoder's own invariant /// that a coded block's transform is always its own full size -- so a TU /// edge is always also a PU edge, and the "both sides skipped, not a PU /// edge" suppression (which only ever fires at a non-PU-edge TU boundary) /// never applies here, letting this skip the `skip`/`skip_txfm` lookup /// entirely. Returns `None` when this 4-pixel edge group is not filtered. #[inline(always)] fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> { let (mi_r, mi_c) = (plane_to_mi(c.chroma, y0), plane_to_mi(c.chroma, x0)); let cur_tx = if c.dir == 0 { tx_px_at(c.n, c.chroma, mi_r, mi_c) } else { tx_h_px_at(c.n, c.chroma, mi_r, mi_c) }; // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment // test is a mask, not the hardware `divl` this used to emit (10.7% of // `edge_params`' own samples sat on that divide's result test). // // Most 4-pixel edge groups die right here (a 4-aligned coordinate that // the covering transform does not start at), so this head is inlined // into the deblock loops and only survivors pay the call and the // register-spilling prologue of the body below. if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 { return None; } edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx) } /// [`edge_params`] past its transform-alignment gate. #[inline(never)] fn edge_params_body( c: &EdgeCtx, x0: usize, y0: usize, mi_r: usize, mi_c: usize, cur_tx: u32, ) -> Option<(u8, i32)> { let n = c.n; let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c]; // The previous cell must keep the odd parity `plane_to_mi` just // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group, // not the other half of this one. let (pv_mi_r, pv_mi_c) = if c.dir == 0 { (mi_r, mi_c - c.step) } else { (mi_r - c.step, mi_c) }; let pv_tx = if c.dir == 0 { tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c) } else { tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c) }; let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c]; let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]); let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]); // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two // SKIPPED INTER blocks is filtered only when it is also a prediction // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The // omission of this term (on the stale invariant "a coded block's transform // is always its own full size", which var-tx broke) had us filtering an // interior 8-px lattice the reference never touches: on the pinned 192x68 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0. // libaom prices `pu_edge` in the PLANE's own pixels against the plane's // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] - // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma // edge of a sub-8x8 group is a prediction edge, even though the group's // bottom/right mi does not start there. Comparing mi origins instead is // the same test only while the block's own origin is aligned to its // size, which a 4x4 luma block read at the `| 1` mi is not. let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c]; let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim); let (org_px, dim_mi) = if c.dir == 0 { (usize::from(cur_org[1]), usize::from(cur_dim[0])) } else { (usize::from(cur_org[0]), usize::from(cur_dim[1])) }; let pu_edge = if c.chroma { let plane_dim = (dim_mi * MI / 2).max(4); (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0 } else { plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }) == org_px }; if !pu_edge && cur_ref != 0 && pv_ref != 0 && n.skip_at(mi_r, mi_c) && n.skip_at(pv_mi_r, pv_mi_c) { return None; } let (cur_seg, pv_seg) = if c.seg_lf_active { (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx)) } else { (0, 0) }; let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg); let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg); if cur_level == 0 && pv_level == 0 { return None; } let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize; let len: u8 = if c.chroma { if dim == 0 { 4 } else { 6 } } else { [4, 8, 14, 14, 14][dim] }; let level = if cur_level != 0 { cur_level } else { pv_level }; hit!(DEBLOCK_HITS); Some((len, level)) } /// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple. fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) { let sharpness = i32::from(sharpness); let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4); let mut lim = level >> shift; if sharpness > 0 { lim = lim.min(9 - sharpness); } lim = lim.max(1); (2 * (level + 2) + lim, lim, level >> 4) } #[allow(dead_code)] // read only from the `#[cfg(test)]` gates fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 { // libaom's `signed_char_clamp_high`: the clamp range scales with // `128 << (bit_depth - 8)` alongside the centering constant below. let scale = 1i32 << (bit_depth(fctx) - 8); v.clamp(-128 * scale, 128 * scale - 1) } fn round_pow2(v: i32, n: u32) -> i32 { (v + (1 << (n - 1))) >> n } /// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat /// fallback. fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] { if !mask { return [p1, p0, q0, q1]; } let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh; // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of // this kernel's eight clamps, and this kernel runs per deblocked sample. // Same bound, resolved once. let scale = 1i32 << (bit_depth(fctx) - 8); let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1); let centre = 128i32 * scale; let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre); let outer = if hev { sclamp(ps1 - qs1) } else { 0 }; let filter = sclamp(outer + 3 * (qs0 - ps0)); let filter1 = sclamp(filter + 4) >> 3; let filter2 = sclamp(filter + 3) >> 3; let oq0 = sclamp(qs0 - filter1) + centre; let op0 = sclamp(ps0 + filter2) + centre; let tap = if hev { 0 } else { round_pow2(filter1, 1) }; let oq1 = sclamp(qs1 - tap) + centre; let op1 = sclamp(ps1 + tap) + centre; [op1, op0, oq0, oq1] } /// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over /// `filter4`'s narrow taps. #[allow(clippy::too_many_arguments)] fn filter6( mask: bool, thresh: i32, flat: bool, p2: i32, p1: i32, p0: i32, q0: i32, q1: i32, q2: i32, fctx: &crate::decode::FrameCtx, ) -> [i32; 4] { if flat && mask { [ round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3), round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3), round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3), round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3), ] } else { filter4(mask, thresh, p1, p0, q0, q1, fctx) } } /// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`). #[allow(clippy::too_many_arguments)] fn filter8( mask: bool, thresh: i32, flat: bool, p3: i32, p2: i32, p1: i32, p0: i32, q0: i32, q1: i32, q2: i32, q3: i32, fctx: &crate::decode::FrameCtx, ) -> [i32; 6] { if flat && mask { [ round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3), round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3), round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3), round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3), round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3), round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3), ] } else { let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx); [p2, op1, op0, oq0, oq1, q2] } } /// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform /// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either /// way -- they are only ever taps here, never written). #[allow(clippy::too_many_arguments)] fn filter14( mask: bool, thresh: i32, flat: bool, flat2: bool, p6: i32, p5: i32, p4: i32, p3: i32, p2: i32, p1: i32, p0: i32, q0: i32, q1: i32, q2: i32, q3: i32, q4: i32, q5: i32, q6: i32, fctx: &crate::decode::FrameCtx, ) -> [i32; 12] { if flat2 && flat && mask { [ round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4), round_pow2( p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1, 4, ), round_pow2( p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2, 4, ), round_pow2( p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3, 4, ), round_pow2( p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4, 4, ), round_pow2( p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5, 4, ), round_pow2( p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6, 4, ), round_pow2( p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2, 4, ), round_pow2( p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3, 4, ), round_pow2( p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4, 4, ), round_pow2( p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5, 4, ), round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4), ] } else { let [op2, op1, op0, oq0, oq1, oq2] = filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx); [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5] } } /// Filters one 4-pixel edge group: `base` is the plane-local byte offset of /// the first (`q0`) sample past the edge, `outer_stride` advances to the /// next of the 4 perpendicular samples, `tap_stride` steps from one tap to /// the next along the edge's own filtering direction. #[allow(clippy::too_many_arguments)] fn filter_edge( data: &mut [u16], base: usize, outer_stride: isize, tap_stride: isize, len: u8, level: i32, sharpness: u8, fctx: &crate::decode::FrameCtx, ) { let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness); // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`: // every 8-bit threshold (including the flat masks' fixed `1`) is // compared against a raw pixel difference on the stream's own bit-depth // scale, so each is shifted left by `bit_depth - 8` before use. let shift = bit_depth(fctx) - 8; let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift); let flat_thresh = 1i32 << shift; let smax = sample_max(fctx); for i in 0..4isize { let center = (base as isize + i * outer_stride) as usize; let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize }; let px = |k: isize| -> i32 { i32::from(data[idx(k)]) }; match len { 4 => { let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1)); let mask = (p1 - p0).abs() <= limit && (q1 - q0).abs() <= limit && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx); data[idx(-2)] = op1.clamp(0, smax) as u16; data[idx(-1)] = op0.clamp(0, smax) as u16; data[idx(0)] = oq0.clamp(0, smax) as u16; data[idx(1)] = oq1.clamp(0, smax) as u16; } 6 => { let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2)); let mask = (p2 - p1).abs() <= limit && (p1 - p0).abs() <= limit && (q1 - q0).abs() <= limit && (q2 - q1).abs() <= limit && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; let flat = (p1 - p0).abs() <= flat_thresh && (q1 - q0).abs() <= flat_thresh && (p2 - p0).abs() <= flat_thresh && (q2 - q0).abs() <= flat_thresh; let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx); data[idx(-2)] = op1.clamp(0, smax) as u16; data[idx(-1)] = op0.clamp(0, smax) as u16; data[idx(0)] = oq0.clamp(0, smax) as u16; data[idx(1)] = oq1.clamp(0, smax) as u16; } 8 => { let (p3, p2, p1, p0, q0, q1, q2, q3) = (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3)); let mask = (p3 - p2).abs() <= limit && (p2 - p1).abs() <= limit && (p1 - p0).abs() <= limit && (q1 - q0).abs() <= limit && (q2 - q1).abs() <= limit && (q3 - q2).abs() <= limit && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; let flat = (p1 - p0).abs() <= flat_thresh && (q1 - q0).abs() <= flat_thresh && (p2 - p0).abs() <= flat_thresh && (q2 - q0).abs() <= flat_thresh && (p3 - p0).abs() <= flat_thresh && (q3 - q0).abs() <= flat_thresh; let [op2, op1, op0, oq0, oq1, oq2] = filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx); data[idx(-3)] = op2.clamp(0, smax) as u16; data[idx(-2)] = op1.clamp(0, smax) as u16; data[idx(-1)] = op0.clamp(0, smax) as u16; data[idx(0)] = oq0.clamp(0, smax) as u16; data[idx(1)] = oq1.clamp(0, smax) as u16; data[idx(2)] = oq2.clamp(0, smax) as u16; } _ => { let (p6, p5, p4, p3, p2, p1, p0) = (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1)); let (q0, q1, q2, q3, q4, q5, q6) = (px(0), px(1), px(2), px(3), px(4), px(5), px(6)); let mask = (p3 - p2).abs() <= limit && (p2 - p1).abs() <= limit && (p1 - p0).abs() <= limit && (q1 - q0).abs() <= limit && (q2 - q1).abs() <= limit && (q3 - q2).abs() <= limit && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; let flat = (p1 - p0).abs() <= flat_thresh && (q1 - q0).abs() <= flat_thresh && (p2 - p0).abs() <= flat_thresh && (q2 - q0).abs() <= flat_thresh && (p3 - p0).abs() <= flat_thresh && (q3 - q0).abs() <= flat_thresh; let flat2 = (p4 - p0).abs() <= flat_thresh && (q4 - q0).abs() <= flat_thresh && (p5 - p0).abs() <= flat_thresh && (q5 - q0).abs() <= flat_thresh && (p6 - p0).abs() <= flat_thresh && (q6 - q0).abs() <= flat_thresh; let out = filter14( mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5, q6, fctx, ); for (k, v) in (-6..=5isize).zip(out) { data[idx(k)] = v.clamp(0, smax) as u16; } } } } } /// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a /// 4K decode's self time, spent almost entirely on the per-tap strided /// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the /// arithmetic). Nothing here is spec logic: the same masks, the same /// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same /// rounding, done for 16 edge lines at once. /// /// 16-bit lanes are exact for every value these filters see. Samples are in /// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| + /// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain /// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the /// wide kernels' weights each total 8 or 16, so their sums (at most /// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their /// rounding shift, which is the unsigned shift the scalar's non-negative sum /// takes. #[cfg(target_arch = "x86_64")] #[allow(unsafe_code)] #[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract mod deblock_simd { use std::arch::x86_64::*; /// `a <= b` lane-wise, as a full-width mask. /// /// # Safety /// Requires AVX2. #[target_feature(enable = "avx2")] #[inline] unsafe fn le(a: __m256i, b: __m256i) -> __m256i { _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b) } /// `|a - b|` lane-wise. /// /// # Safety /// Requires AVX2. #[target_feature(enable = "avx2")] #[inline] unsafe fn ad(a: __m256i, b: __m256i) -> __m256i { _mm256_abs_epi16(_mm256_sub_epi16(a, b)) } /// `signed_char_clamp_high`, lane-wise. /// /// # Safety /// Requires AVX2. #[target_feature(enable = "avx2")] #[inline] unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i { _mm256_min_epi16(_mm256_max_epi16(v, lo), hi) } /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the /// 128-bit lane swap AVX2's in-lane unpacks leave behind). /// /// # Safety /// Requires AVX2. #[target_feature(enable = "avx2")] unsafe fn transpose16(t: &mut [__m256i; 16]) { let mut a = [_mm256_setzero_si256(); 16]; for k in 0..8 { a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]); a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]); } let mut b = [_mm256_setzero_si256(); 16]; for g in 0..4 { let s = 4 * g; b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]); b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]); b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]); b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]); } let mut c = [_mm256_setzero_si256(); 16]; for g in 0..2 { let s = 8 * g; for j in 0..4 { c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]); c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]); } } for i in 0..8 { t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20); t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31); } } /// The wide kernels' tap weights, in tap order and with the spec's /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8` /// over `p3..q3`, `filter14` over `p6..q6`. const W6: [[i16; 6]; 4] = [ [3, 2, 2, 1, 0, 0], [1, 2, 2, 2, 1, 0], [0, 1, 2, 2, 2, 1], [0, 0, 1, 2, 2, 3], ]; const W8: [[i16; 8]; 6] = [ [3, 2, 1, 1, 1, 0, 0, 0], [2, 1, 2, 1, 1, 1, 0, 0], [1, 1, 1, 2, 1, 1, 1, 0], [0, 1, 1, 1, 2, 1, 1, 1], [0, 0, 1, 1, 1, 2, 1, 2], [0, 0, 0, 1, 1, 1, 2, 3], ]; #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement const W14: [[i16; 14]; 12] = [ [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0], [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0], [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2], [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3], [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7], ]; /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows, /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and /// below `1 << 16`, so the logical shift is the arithmetic one. /// /// # Safety /// Requires AVX2. /// /// lane-deblock: the tap count, the weights and the shift are all const /// here (they were slice parameters, which left the weight `match` as a /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were /// 34% of this kernel's samples, and the spilled tap slices another 17%). #[target_feature(enable = "avx2")] #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn unsafe fn wsum( taps: &[__m256i; N], w: &[i16; N], ) -> __m256i { let mut s = _mm256_setzero_si256(); for i in 0..N { match w[i] { 0 => {} 1 => s = _mm256_add_epi16(s, taps[i]), 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])), k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))), } } let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1))); if SHIFT == 3 { _mm256_srli_epi16(s, 3) } else { _mm256_srli_epi16(s, 4) } } /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in /// `t[8]`; the filtered taps are written back in place. Returns `false` /// when the filter mask is empty on every one of the 16 lines -- nothing /// was written and the caller can skip the whole write-back. /// /// # Safety /// Requires AVX2. /// /// lane-deblock2: `LEN` is a const parameter, so each edge length gets /// its own kernel holding only its own taps, and every wide row is /// clamped straight into `t` instead of into a shared twelve-entry /// result array (which the register allocator spilled -- 35% of this /// kernel's samples were `vmovdqa` to the stack). #[target_feature(enable = "avx2")] #[allow(clippy::too_many_arguments)] unsafe fn filter16( t: &mut [__m256i; 16], blimit: i32, limit: i32, hev_thr: i32, flat_thresh: i32, scale: i32, smax: i32, ) -> bool { let lim = _mm256_set1_epi16(limit as i16); let blim = _mm256_set1_epi16(blimit as i16); let hthr = _mm256_set1_epi16(hev_thr as i16); let fthr = _mm256_set1_epi16(flat_thresh as i16); let zero = _mm256_setzero_si256(); let smaxv = _mm256_set1_epi16(smax as i16); macro_rules! put { ($i:expr, $v:expr) => { t[$i] = _mm256_min_epi16(_mm256_max_epi16($v, zero), smaxv); }; } let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]); let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]); // `highbd_filter_mask`: the neighbour steps this kernel's length // reaches, plus the shared `blimit` term. let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0)); let mut md = d1; if LEN >= 6 { md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1))); } if LEN >= 8 { md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2))); } let bl = _mm256_add_epi16( _mm256_slli_epi16(ad(p0, q0), 1), _mm256_srli_epi16(ad(p1, q1), 1), ); let mask = _mm256_and_si256(le(md, lim), le(bl, blim)); // lane-deblock2: an empty mask leaves every tap at its loaded value // (the flat masks are `& mask`, so they are empty too, and the final // clamp is the identity on samples that came out of the plane), so // the whole write-back -- including the vertical edge's second // transpose -- is dead. if _mm256_testz_si256(mask, mask) != 0 { return false; } let hev = _mm256_cmpgt_epi16(d1, hthr); // `filter4`, in the centred domain. let centre = _mm256_set1_epi16((128 * scale) as i16); let lo = _mm256_set1_epi16((-128 * scale) as i16); let hi = _mm256_set1_epi16((128 * scale - 1) as i16); let ps1 = _mm256_sub_epi16(p1, centre); let ps0 = _mm256_sub_epi16(p0, centre); let qs0 = _mm256_sub_epi16(q0, centre); let qs1 = _mm256_sub_epi16(q1, centre); let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi)); let f = sclamp( _mm256_add_epi16( outer, _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)), ), lo, hi, ); let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3); let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3); let tap = _mm256_andnot_si256( hev, _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1), ); let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre); let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre); let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre); let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre); let b_p1 = _mm256_blendv_epi8(p1, n_p1, mask); let b_p0 = _mm256_blendv_epi8(p0, n_p0, mask); let b_q0 = _mm256_blendv_epi8(q0, n_q0, mask); let b_q1 = _mm256_blendv_epi8(q1, n_q1, mask); if LEN == 4 { put!(6, b_p1); put!(7, b_p0); put!(8, b_q0); put!(9, b_q1); return true; } // `highbd_flat_mask4`, over the same reach as this length's mask. let mut fl = _mm256_max_epi16( _mm256_max_epi16(ad(p1, p0), ad(q1, q0)), _mm256_max_epi16(ad(p2, p0), ad(q2, q0)), ); if LEN >= 8 { fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0))); } let flat = _mm256_and_si256(le(fl, fthr), mask); let any_flat = _mm256_testz_si256(flat, flat) == 0; if LEN == 6 { if any_flat { let taps = [p2, p1, p0, q0, q1, q2]; put!(6, _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W6[0]), flat)); put!(7, _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W6[1]), flat)); put!(8, _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W6[2]), flat)); put!(9, _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W6[3]), flat)); } else { put!(6, b_p1); put!(7, b_p0); put!(8, b_q0); put!(9, b_q1); } return true; } // `filter8`'s six rows over `p2..q2`, the wide kernel's base. let (o0, o1, o2, o3, o4, o5) = if any_flat { let taps = [p3, p2, p1, p0, q0, q1, q2, q3]; ( _mm256_blendv_epi8(p2, wsum::<_, 3>(&taps, &W8[0]), flat), _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W8[1]), flat), _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W8[2]), flat), _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W8[3]), flat), _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W8[4]), flat), _mm256_blendv_epi8(q2, wsum::<_, 3>(&taps, &W8[5]), flat), ) } else { (p2, b_p1, b_p0, b_q0, b_q1, q2) }; macro_rules! put8 { () => { put!(5, o0); put!(6, o1); put!(7, o2); put!(8, o3); put!(9, o4); put!(10, o5); }; } if LEN == 8 { put8!(); return true; } let fl2 = _mm256_max_epi16( _mm256_max_epi16( _mm256_max_epi16(ad(p4, p0), ad(q4, q0)), _mm256_max_epi16(ad(p5, p0), ad(q5, q0)), ), _mm256_max_epi16(ad(p6, p0), ad(q6, q0)), ); let flat2 = _mm256_and_si256(le(fl2, fthr), flat); if _mm256_testz_si256(flat2, flat2) != 0 { // No line takes the wide rows: `t[2..5]`/`t[11..14]` keep the // taps they were loaded with, exactly as the blend would. put8!(); return true; } // lane-deblock: `filter14`'s twelve rows as a RUNNING sum. // Consecutive `W14` rows differ by three or four taps (row j+1 - row // j is a constant vector with two negative and two positive // entries), so each output costs one add, one sub and the rounding // shift instead of a fresh 14-tap weighted sum -- 168 tap operations // become 44. Exact: every partial sum is taken mod 2^16 by // `add/sub_epi16` and every ROW sum is a real `W14` row, at most // `16 * 4095 + 8 < 2^16`, so the unsigned rounding shift sees the // true value. `deblock_simd_kernel_matches_the_scalar_filter` pins // it against `filter_edge` at 8/10/12-bit. let mut s = _mm256_add_epi16( _mm256_add_epi16( _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)), _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1), ), _mm256_add_epi16( _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)), q0, ), ); let add2 = |a, b| _mm256_add_epi16(a, b); macro_rules! row14 { ($idx:literal, $base:expr) => { put!( $idx, _mm256_blendv_epi8( $base, _mm256_srli_epi16(_mm256_add_epi16(s, _mm256_set1_epi16(8)), 4), flat2, ) ); }; ($idx:literal, $base:expr, $plus:expr, $minus:expr) => { s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus); row14!($idx, $base); }; } row14!(2, p5); row14!(3, p4, add2(p3, q1), _mm256_slli_epi16(p6, 1)); row14!(4, p3, add2(p2, q2), add2(p6, p5)); row14!(5, o0, add2(p1, q3), add2(p6, p4)); row14!(6, o1, add2(p0, q4), add2(p6, p3)); row14!(7, o2, add2(q0, q5), add2(p6, p2)); row14!(8, o3, add2(q1, q6), add2(p6, p1)); row14!(9, o4, add2(q2, q6), add2(p5, p0)); row14!(10, o5, add2(q3, q6), add2(p4, q0)); row14!(11, q3, add2(q4, q6), add2(p3, q1)); row14!(12, q4, add2(q5, q6), add2(p2, q2)); row14!(13, q5, _mm256_slli_epi16(q6, 1), add2(p1, q3)); true } /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's /// 16 lines are 16 consecutive rows and its taps are consecutive samples /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16 /// consecutive columns with each tap a whole row segment. /// /// # Safety /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base % /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`; /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride` /// must be inside it. #[target_feature(enable = "avx2")] #[allow(clippy::too_many_arguments)] pub unsafe fn edge16( data: &mut [u16], base: usize, stride: usize, vertical: bool, len: u8, blimit: i32, limit: i32, hev_thr: i32, flat_thresh: i32, scale: i32, smax: i32, ) { let p = data.as_mut_ptr(); let mut t = [_mm256_setzero_si256(); 16]; // The taps this length reads, as `t` indices. let (lo, hi) = match len { 4 => (6, 10), 6 => (5, 11), 8 => (4, 12), _ => (1, 15), }; if vertical { for j in 0..16 { t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast()); } transpose16(&mut t); } else { let top = base - 8 * stride; for i in lo..hi { t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast()); } } // lane-deblock2: one monomorphised kernel per edge length, and an // empty filter mask returns without any write-back at all. let modified = match len { 4 => filter16::<4>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax), 6 => filter16::<6>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax), 8 => filter16::<8>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax), _ => filter16::<14>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax), }; if !modified { return; } if vertical { transpose16(&mut t); for j in 0..16 { _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]); } } else { let top = base - 8 * stride; let (a, b) = match len { 4 | 6 => (6, 10), 8 => (5, 11), _ => (2, 14), }; for i in a..b { _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]); } } } } /// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`' /// output. Returns `false` when this build or CPU has no kernel, leaving the /// caller on the scalar path. #[allow(unused_variables)] fn filter_edge16( data: &mut [u16], base: usize, stride: usize, vertical: bool, len: u8, level: i32, sharpness: u8, fctx: &crate::decode::FrameCtx, ) -> bool { #[cfg(target_arch = "x86_64")] { if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 { let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness); let shift = bit_depth(fctx) - 8; // SAFETY: the avx2 arm is reached only when the CPU reports it, // and `deblock_plane` checks the kernel's edge bounds. #[allow(unsafe_code)] unsafe { deblock_simd::edge16( data, base, stride, vertical, len, blimit << shift, limit << shift, hev_thr << shift, 1 << shift, 1 << shift, sample_max(fctx), ) }; return true; } } false } /// One plane's worth of spec 7.14: every vertical edge across the plane, /// then every horizontal edge (the order the spec and libaom both use). fn deblock_plane( plane: &mut PlaneBuf<'static>, plane_idx: usize, lf: &LoopFilterParams, n: &Neighbours, frame_width: usize, frame_height: usize, fctx: &crate::decode::FrameCtx, ) { // spec 7.14's order: this plane's whole vertical pass, then its whole // horizontal one. lane-pipefilt split the two into one row-ranged // function so the per-superblock-row pipeline can run them a band at a // time; `0..usize::MAX` is the whole plane, i.e. exactly this call. deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx); deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx); } /// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or /// horizontal ones -- restricted to the plane rows `span_lo..span_hi`. /// /// A row span is a legal cut of either pass because a band boundary is a /// multiple of 16 rows and every edge's kernel stays inside its own /// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are /// what keep the two passes in spec order across bands. #[allow(clippy::too_many_arguments)] fn deblock_plane_span( plane: &mut PlaneBuf<'static>, plane_idx: usize, lf: &LoopFilterParams, n: &Neighbours, frame_width: usize, frame_height: usize, span_lo: usize, span_hi: usize, horz: bool, fctx: &crate::decode::FrameCtx, ) { let chroma = plane_idx != 0; // r7: libaom clips the deblock loop to the CODED frame's own // width/height, not the mi-aligned `true_width`/`true_height` margin // (the padding up to the next 8-pixel/superblock boundary that // reconstruction still fills in but the loop filter never visits). // Confirmed against the superres gate: with the margin included, the // last coded mi column's horizontal edges were filtered when libaom's // real output leaves them untouched (r6's post-deblock diff, 37 px, all // in columns 44-47); clipping here closes it (3/3 frames pixel-exact). // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column // 72 and the vertical edge AT x=68 is a real edge that rewrites the // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels // all in columns 64..67; frame 0 survived because that edge carried no // filter level there). r7's superres measurement is preserved: its frame // was already 8-aligned, so this bound equals `frame_width` there and // still excludes the superblock padding up to `true_width`. let (cw, ch) = if chroma { (frame_width.div_ceil(2), frame_height.div_ceil(2)) } else { (frame_width, frame_height) }; let (tw, th, stride) = ( plane.true_width.min(cw), plane.true_height.min(ch), plane.width, ); if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") { eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height); } // lane-perf8: both passes iterate the edge's OWN direction innermost, so // 4 consecutive 4-sample groups (16 lines) can go through one AVX2 // kernel. The swap is order-preserving: a filtered group overlaps only // groups along the edge it sits on -- the vertical pass's writes at // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the // dependence is on ascending `x0` within a row, which stays the outer // loop's order, and rows remain independent (horizontal pass mirrored). let rows = plane.data.len() / stride.max(1); let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled); // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS` // bands along the axis whose writes are disjoint. A vertical edge's // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so // row bands never touch each other; a horizontal edge's groups write rows // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both // read the mode-info grids immutably. The grouping a band starts with is // free: every 4-row (4-column) group's output is a pure function of that // group, whether it goes through `filter_edge16` with three neighbours or // through `filter_edge` alone. Band boundaries are multiples of 16 so no // group ever straddles one. // lane-perf10 merge: the output plane is owned (perf10 made mutable // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so // the bands below never clone it concurrently. plane.data.to_mut(); let threads = crate::par::filter_threads(); let sp = crate::par::Shared::new(plane); let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th)); let vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi { Vec::new() } else { crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads) .into_iter() .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi))) .collect() }; crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| { // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which // no other band touches (see `Shared`'s own corner-cut note). #[allow(unsafe_code)] let plane = unsafe { sp.get() }; // lane-deblock2: this band's own level table and pass constants, // built once per band instead of re-derived per 4-pixel edge. let vctx = EdgeCtx::new(lf, n, plane_idx, 0, chroma, seg_lf_active, fctx); let mut x0 = 4usize; while x0 < tw { let mut y0 = y_lo; while y0 < y_hi { if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride { let ps: [Option<(u8, i32)>; 4] = std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k)); if let Some((len, level)) = ps[0] { if ps.iter().all(|p| *p == ps[0]) && filter_edge16( plane.data.to_mut(), y0 * stride + x0, stride, true, len, level, lf.sharpness, fctx, ) { y0 += 16; continue; } } for (k, p) in ps.iter().enumerate() { if let Some((len, level)) = *p { filter_edge( plane.data.to_mut(), (y0 + 4 * k) * stride + x0, stride as isize, 1, len, level, lf.sharpness, fctx, ); } } y0 += 16; continue; } if let Some((len, level)) = edge_params(&vctx, x0, y0) { if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 { eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}"); } filter_edge( plane.data.to_mut(), y0 * stride + x0, stride as isize, 1, len, level, lf.sharpness, fctx, ); } y0 += 4; } x0 += 4; } }); // The horizontal pass runs only after the WHOLE vertical pass of this // plane (spec 7.14 order), which `run_bands` guarantees by joining. let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi { Vec::new() } else { crate::par::bands(tw.div_ceil(16), threads) .into_iter() .map(|(a, b)| (a * 16, (b * 16).min(tw))) .collect() }; crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| { // SAFETY: this band writes only columns `x_lo..x_hi`. #[allow(unsafe_code)] let plane = unsafe { sp.get() }; let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx); let mut y0 = sp_lo.max(4); while y0 < sp_hi { let mut x0 = x_lo; while x0 < x_hi { if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows { let ps: [Option<(u8, i32)>; 4] = std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0)); if let Some((len, level)) = ps[0] { if ps.iter().all(|p| *p == ps[0]) && filter_edge16( plane.data.to_mut(), y0 * stride + x0, stride, false, len, level, lf.sharpness, fctx, ) { x0 += 16; continue; } } for (k, p) in ps.iter().enumerate() { if let Some((len, level)) = *p { filter_edge( plane.data.to_mut(), y0 * stride + x0 + 4 * k, 1, stride as isize, len, level, lf.sharpness, fctx, ); } } x0 += 16; continue; } if let Some((len, level)) = edge_params(&hctx, x0, y0) { if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE") && plane_idx == 0 && x0 == 44 { eprintln!( "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}", lf.sharpness ); } filter_edge( plane.data.to_mut(), y0 * stride + x0, 1, stride as isize, len, level, lf.sharpness, fctx, ); } x0 += 4; } y0 += 4; } }); } /// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a /// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop /// restoration is active, and a fresh LR destination per plane -- freshly /// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every /// sample written also takes a first-touch page fault. The buffers are handed /// back here instead and refilled in place. /// /// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not /// stay on one thread: the frame thread allocates the snapshots and a filter /// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes /// into the pool from whichever worker ran it), so a per-thread pool leaked /// whole-plane buffers into every worker it touched -- 19 MB a set, times /// every pool thread the decode ever created. One shared pool with a hard /// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how /// many threads cycle through it; anything over the cap is freed. static PLANE_SCRATCH: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); /// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K /// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in /// flight cycle through far fewer. const SCRATCH_CAP: usize = 32; /// Takes a pooled buffer for a caller that wants `n` samples, best-fit by /// CAPACITY so a chroma-sized request does not permanently promote a /// luma-sized allocation (every pooled buffer would drift to the largest /// size otherwise). `None` when the pool is empty. fn scratch_take(n: usize) -> Option> { let mut p = PLANE_SCRATCH.lock().unwrap(); if p.is_empty() { return None; } let fit = p .iter() .enumerate() .filter(|(_, v)| v.capacity() >= n) .min_by_key(|(_, v)| v.capacity()) .map(|(i, _)| i); let i = match fit { Some(i) => i, // Nothing big enough: grow the largest rather than a small one. None => p .iter() .enumerate() .max_by_key(|(_, v)| v.capacity()) .map(|(i, _)| i) .expect("the pool is not empty"), }; Some(p.swap_remove(i)) } /// A pooled buffer holding a copy of `src`. fn scratch_from(src: &[u16]) -> Vec { let mut v = scratch_take(src.len()).unwrap_or_default(); v.clear(); v.extend_from_slice(src); v } /// An empty pooled buffer, for a caller that fills it itself. fn scratch_empty() -> Vec { let mut v = scratch_take(0).unwrap_or_default(); v.clear(); v } /// A pooled buffer of exactly `n` samples whose contents are NOT cleared -- /// for a caller that writes every element it later reads (lane-copy: the /// post-deblock snapshot writes 4 rows in 64 and reads no other). fn scratch_sized(n: usize) -> Vec { let mut v = scratch_take(n).unwrap_or_default(); if v.len() > n { v.truncate(n); } else if v.len() < n { v.resize(n, 0); } v } /// A plane's post-deblock snapshot, its samples taken from the pool (every /// other field is `usize`). /// /// lane-copy: loop restoration is the only reader, and spec 7.17.2's stripe /// boundary substitution reads the post-deblock plane at just four rows /// around each interior stripe boundary (`row` outside /// `[stripe_v_start, stripe_v_end)` resolves to `stripe_v_start-1`, /// `stripe_v_start-2`, `stripe_v_end` or `stripe_v_end+1` in /// `restoration::lr_src_row`); stripes are `64 >> ss_y` rows offset by /// `RESTORATION_UNIT_OFFSET = 8 >> ss_y`, so the boundaries sit at /// `k*stripe_h - offset`. Copying only those rows turns a full-plane /// memmove per plane per frame into 4 rows in 64 (luma). Every other row of /// the pooled buffer keeps whatever a previous frame left there -- an /// initialised value that no reader ever reaches. fn snap_alloc(p: &PlaneBuf<'_>) -> PlaneBuf<'static> { PlaneBuf { data: std::borrow::Cow::Owned(scratch_sized(p.data.len())), ..*p } } fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> { let mut data = scratch_sized(p.data.len()); let rows = if p.width == 0 { 0 } else { p.data.len() / p.width }; let stripe_h = 64usize >> ss_y; let offset = 8usize >> ss_y; let mut b = stripe_h - offset; while b < rows { let (lo, hi) = (b - 2, (b + 2).min(rows)); data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]); b += stripe_h; } PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p } } /// The pre-filter reconstruction of one coded frame, plus the per-block state /// the loop filters read. /// /// The encoder's filter search ([`crate::filter_search::pick_filters`]) /// decodes the same coded tile under ~25 candidate deblock/CDEF parameter /// sets to score each one, and the entropy decode and reconstruction it /// repeats are identical every time -- both filters run after it, on the /// finished planes. That re-parse was 24% of the encoder's profile. A caller /// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters /// alone through [`replay_filters`]; the result is the same picture the full /// decode would have returned, because it is the same two calls on a copy of /// the same planes. pub(crate) struct FilterReplay { y: PlaneBuf<'static>, u: PlaneBuf<'static>, v: PlaneBuf<'static>, neighbours: Neighbours, frame_width: usize, frame_height: usize, width: usize, height: usize, /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin /// stash the cropped return path leaves behind. true_width: usize, true_height: usize, /// lane-av1fpar: plane buffers this replay is done with. Every candidate /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a /// 1080p frame's wall in allocation, not in filtering. Recycled here /// instead; the pool holds at most the six planes one candidate has live. scratch: Vec>, /// The last deblocked planes and the levels that produced them. /// Deblocking depends on nothing else the search moves, and the search /// fixes the levels before it walks the CDEF strengths, so every /// candidate after the first of a level pair replays CDEF alone. deblocked: Option<(LoopFilterParams, PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>, } thread_local! { /// Set by [`arm_filter_replay`] for the span of one decode. static REPLAY_ARMED: std::cell::Cell = const { std::cell::Cell::new(false) }; /// What that decode captured, until [`clear_filter_replay`]. static REPLAY: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } /// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]). pub(crate) fn arm_filter_replay() { REPLAY_ARMED.set(true); } /// Test-only: force every filter candidate through a full decode, so a gate /// can hold the replay against the decode it stands in for /// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`). #[cfg(test)] static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); #[cfg(test)] pub(crate) fn set_filter_replay_disabled(off: bool) { REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed); } /// Drop the armed flag and anything captured: the tile it belongs to is done. pub(crate) fn clear_filter_replay() { REPLAY_ARMED.set(false); REPLAY.with_borrow_mut(|r| *r = None); } /// The capture itself, called from the decoder's own pre-filter point. Owns /// copies of the planes, since the caller filters them in place. fn capture_filter_replay( y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, neighbours: &Neighbours, frame_width: usize, frame_height: usize, width: usize, height: usize, true_width: usize, true_height: usize, ) { if !REPLAY_ARMED.replace(false) { return; } let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p }; REPLAY.with_borrow_mut(|slot| { *slot = Some(FilterReplay { y: own(y), u: own(u), v: own(v), neighbours: neighbours.clone(), frame_width, frame_height, width, height, true_width, true_height, scratch: Vec::new(), deblocked: None, }); }); } /// One candidate's working copy of a captured plane, off [`FilterReplay`]'s /// own buffer pool: a cleared `Vec` that already has the capacity keeps the /// allocator and the page fault handler out of the filter search. fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec>) -> PlaneBuf<'static> { let mut buf = scratch.pop().unwrap_or_default(); let src: &[u16] = &p.data; let threads = crate::par::filter_threads(); if buf.len() != src.len() || threads <= 1 { buf.clear(); buf.extend_from_slice(src); } else { // A recycled buffer is already the right length, so the copy is a // plain `copy_from_slice` -- and one worth banding: ~6 MB per // candidate is memory bandwidth, not arithmetic, and the halves are // disjoint `&mut` slices (no `par::Shared` needed). let per = src.len().div_ceil(threads); let batch = crate::par::Batch::new("ec-av1-filter"); for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) { batch.submit(move || dst.copy_from_slice(src)); } } PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p } } /// The filter half of a captured decode, under new parameters: exactly the /// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a /// copy of the captured planes. `None` when nothing is captured (the caller /// then decodes for real). pub(crate) fn replay_filters( loop_filter: &LoopFilterParams, cdef: &CdefParams, fctx: &FrameCtx, ) -> Option { #[cfg(test)] if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) { return None; } REPLAY.with_borrow_mut(|slot| { let r = slot.as_mut()?; let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter); let cpt = crate::par::timer(crate::par::S_COPY); let (mut y, mut u, mut v) = if hit { let (deblocked, scratch) = (&r.deblocked, &mut r.scratch); let (_, dy, du, dv) = deblocked.as_ref().expect("just matched"); (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch)) } else { // The levels moved, so the cached deblocked planes are dead: // their buffers are this candidate's working copies. if let Some((_, dy, du, dv)) = r.deblocked.take() { r.scratch.push(dy.data.into_owned()); r.scratch.push(du.data.into_owned()); r.scratch.push(dv.data.into_owned()); } let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch); let (mut y, mut u, mut v) = (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch)); let _t = crate::par::timer(crate::par::S_DEBLOCK); apply_deblock( &mut y, &mut u, &mut v, loop_filter, &r.neighbours, r.frame_width, r.frame_height, fctx, ); let scratch = &mut r.scratch; r.deblocked = Some((*loop_filter, pooled(&y, scratch), pooled(&u, scratch), pooled(&v, scratch))); (y, u, v) }; drop(cpt); let ct = crate::par::timer(crate::par::S_CDEF); apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx); drop(ct); // The capture only happens on the shape whose tail is the two // filter calls and the crop (no superres, no loop restoration), so // what is left is that crop -- byte for byte the cropped return path // of the decode this replaces, wide-margin stash included. // // lane-av1fpar: the crop is why this arm exists at all. The capture // used to demand `frame == plane` dimensions, which no editor size // meets (1080 and 1608 both pad to a superblock row), so every // candidate of every frame at those sizes fell through to a full // re-decode -- 57% of a 1080p frame's wall. let (fw, fh) = (r.frame_width, r.frame_height); if fw == r.width && fh == r.height { fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); return Some(Picture { width: r.width, height: r.height, y: y.data.into_owned(), u: u.data.into_owned(), v: v.data.into_owned(), }); } let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec { let mut out = Vec::with_capacity(w * h); for row in 0..h { out.extend(plane.data[row * plane.width..][..w].iter().copied()); } out }; let (tw, th) = (r.true_width, r.true_height); fctx.last_frame_wide_margin.with(|m| { *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture { width: tw, height: th, y: crop(&y, tw, th), u: crop(&u, tw.div_ceil(2), th.div_ceil(2)), v: crop(&v, tw.div_ceil(2), th.div_ceil(2)), }); }); let out = Picture { width: fw, height: fh, y: crop(&y, fw, fh), u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)), v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)), }; // The working planes outlive the crop, so they go back to the pool. for plane in [y, u, v] { if r.scratch.len() < 6 { r.scratch.push(plane.data.into_owned()); } } Some(out) }) } /// The output crop, taking the plane by value: a frame whose width is /// already superblock-aligned (only its height is padded) has a padded /// buffer whose stride equals the visible width, so the crop is a pure /// truncation of the buffer we already own -- no full-plane copy at all /// (lane-copy: three ~6 MB memmoves per 4K frame on the frame thread's /// serial tail). Any other shape falls back to the row-by-row copy. fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec { let stride = plane.width; let mut data = plane.data.into_owned(); if stride == w { data.truncate(w * h); return data; } let mut out = Vec::with_capacity(w * h); for row in 0..h { out.extend(data[row * stride..][..w].iter().copied()); } out } /// Hands a buffer back to the pool; the capacity is what is worth keeping. /// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is /// what keeps a pool shared by every thread from being an unbounded stash. fn scratch_return(v: Vec) { let mut p = PLANE_SCRATCH.lock().unwrap(); if p.len() < SCRATCH_CAP { p.push(v); } } /// One CDEF mi-row band, as a real function rather than the body of the /// `run_bands` closure: inside the closure the destination planes are /// `&mut` references derived from a `par::Shared` raw pointer in the same /// scope as the `src_*` snapshot reads, so LLVM cannot tell the two apart and /// re-loads through them on every tap. Reference parameters restore `noalias` /// (lane-perf11 (a): -x% instructions at one filter thread). #[allow(clippy::too_many_arguments)] fn cdef_band( r_lo: usize, r_hi: usize, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, src_y: &[u16], src_u: &[u16], src_v: &[u16], cdef: &CdefParams, skip_grid: &Neighbours, idx_grid: &[u8], sb_cols: usize, coeff_shift: i32, damping: i32, damping_uv: i32, (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx, ) { let strength_idx = |mi_r: usize, mi_c: usize| -> usize { if sb_cols == 0 { return 0; } let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize); idx_grid.get(sb_r * sb_cols + sb_c).copied().unwrap_or(0) as usize }; // One scratch window per plane kind, reused by every unit (8x8 luma and // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring). // 256 entries, not the (bw + 4) x (bh + 4) samples themselves: the // AVX2 kernel taps the window in place with two-row loads that reach // past the last sample, and the tail stays zero for every unit. let mut win_y = [0i16; 256]; let mut win_uv = [0i16; 256]; let mut mi_r = r_lo; while mi_r < r_hi { let mut mi_c = 0usize; while mi_c < skip_grid.mi_cols { if skip_grid.is_skip_txfm(mi_r, mi_c) { hit!(CDEF_SKIPPED_UNITS); } if !skip_grid.is_skip_txfm(mi_r, mi_c) { let sidx = strength_idx(mi_r, mi_c); let (ox, oy) = (mi_c * 4, mi_r * 4); // Nothing to do for this unit at all: the direction search is // only ever consumed through a strength, so a unit whose four // strengths are zero never needs its 8x8 window gathered. if cdef.y_pri_strength[sidx] == 0 && cdef.y_sec_strength[sidx] == 0 && cdef.uv_pri_strength[sidx] == 0 && cdef.uv_sec_strength[sidx] == 0 { mi_c += 2; continue; } let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height); cdef_gather(src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y); // lane-cdef r1: the direction search reads the SAME padded // block the taps do -- libaom runs `cdef_find_dir` on the // prepared filter block (`cdef_block.c:296-320` over // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE. // Clamping to the last real sample instead made every straddling // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence // a different `adjust_strength`, hence a +-1 band at the crop edge. let (dir, var) = cdef_find_dir(&win_y, 8 + 2 * CDEF_BORDER, coeff_shift); // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0` // -- each plane zeroes the shared direction when *its own* // frame-level primary strength is 0, independent of the // per-block adjusted `t` and of the other plane's strength. let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift; let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift; let y_dir = if y_pri_strength != 0 { dir } else { 0 }; let t = cdef_adjust_strength(y_pri_strength, var); // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit. if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") { eprintln!( "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}" ); } let enable_primary = t != 0; let enable_secondary = y_sec_strength != 0; if (ox + 8 > frame_w || oy + 8 > frame_h) && (enable_primary || enable_secondary || cdef.uv_pri_strength[sidx] != 0 || cdef.uv_sec_strength[sidx] != 0) { hit!(CDEF_STRADDLE_UNITS); } if enable_primary || enable_secondary { cdef_filter_block( &win_y, y, ox, oy, 8, 8, t, y_sec_strength, y_dir, damping, damping, enable_primary, enable_secondary, coeff_shift, fctx, ); } let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift; let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift; let uv_dir = if t_uv != 0 { dir } else { 0 }; let enable_primary_uv = t_uv != 0; let enable_secondary_uv = uv_sec_strength != 0; if enable_primary_uv || enable_secondary_uv { let (cox, coy) = (ox / 2, oy / 2); for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] { let (tw, th) = (plane.true_width, plane.true_height); let stride = plane.width; cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv); cdef_filter_block( &win_uv, plane, cox, coy, 4, 4, t_uv, uv_sec_strength, uv_dir, damping_uv, damping_uv, enable_primary_uv, enable_secondary_uv, coeff_shift, fctx, ); } } } mi_c += 2; } mi_r += 2; } } // --- lane-pipefilt: the per-superblock-row loop filter pipeline ---------- // // DEPENDENCY SHAPE (derived from this decoder's own whole-frame pass order: // every plane's vertical deblock edges, then every plane's horizontal ones, // then CDEF, then -- unpipelined -- superres and loop restoration). // A band is 64 luma rows, one superblock row (a 128 superblock is two). // // * recon: intra prediction of band r+1 reads the UNFILTERED bottom rows of // band r, so no filter may touch band r before band r+1 is reconstructed. // Hence V(r) waits for `ready >= r + 2`. // * V(r) (vertical edges whose 4-sample groups live in band r's rows) then // H(r-1) (horizontal edges at `y` in band r-1, including the one at its // own top boundary): the edge at `y = r*64` reads/writes 6-7 rows either // side of the band boundary, so H(r-1)'s last edge reaches into band r, // which the whole-frame order has already vertical-filtered -- V(r) // before H(r-1) reproduces exactly that. // * post-deblock finality: band j's own bottom rows are still rewritten by // H(j+1)'s first edge, so band j's post-deblock snapshot (`snap`) may // only be taken after H(j+1). // * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64 // boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1). // // One iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), and the // loop runs k in `0..nbands+3` so the tail drains. Loop restoration (and the // superres upscale, which is a whole-frame refusal for this path) stay in the // frame thread's tail; the snapshot the pipeline built is what LR reads. struct PipeQ { /// Bands whose reconstruction the frame thread has released. ready: usize, abort: bool, } pub(crate) struct PipeSync { m: std::sync::Mutex, cv: std::sync::Condvar, } impl PipeSync { fn new() -> Self { Self { m: std::sync::Mutex::new(PipeQ { ready: 0, abort: false }), cv: std::sync::Condvar::new(), } } fn note(&self, ready: usize) { let mut q = self.m.lock().unwrap(); if ready > q.ready { q.ready = ready; self.cv.notify_all(); } } /// Releases every remaining band (`abort` = the tile decoder is bailing /// out, so the worker returns instead of finishing the frame). fn close(&self, all: usize, abort: bool) { let mut q = self.m.lock().unwrap(); q.ready = q.ready.max(all); q.abort |= abort; self.cv.notify_all(); } /// `false` when the frame was aborted. fn wait_for(&self, want: usize) -> bool { let mut q = self.m.lock().unwrap(); while q.ready < want && !q.abort { q = self.cv.wait(q).unwrap(); } !q.abort } } /// Band `j`'s rows of `src` copied into the pipeline's post-deblock /// snapshot. `full` mirrors [`apply_cdef`]'s whole-plane pre-CDEF copy; /// otherwise only the four rows around each stripe boundary that loop /// restoration reads are taken, exactly [`plane_snapshot`]'s rows. fn snap_band(dst: &mut [u16], src: &PlaneBuf<'_>, ss_y: u32, y_lo: usize, y_hi: usize, full: bool) { let w = src.width; if w == 0 { return; } let rows = src.data.len() / w; let (lo, hi) = (y_lo.min(rows), y_hi.min(rows)); if lo >= hi { return; } if full { dst[lo * w..hi * w].copy_from_slice(&src.data[lo * w..hi * w]); return; } let stripe_h = 64usize >> ss_y; let offset = 8usize >> ss_y; let mut b = stripe_h - offset; while b < rows { let (a, e) = ((b - 2).max(lo), (b + 2).min(rows).min(hi)); if a < e { dst[a * w..e * w].copy_from_slice(&src.data[a * w..e * w]); } b += stripe_h; } } /// Everything the pipeline worker needs that is not a plane or a grid. struct PipeCfg<'a> { lf: &'a LoopFilterParams, cdef: &'a CdefParams, /// `(cdef_idx_grid.as_ptr(), len)` -- the frame thread keeps filling the /// entries of the superblock rows the pipeline has not reached; the Vec /// itself is sized once per frame, so the pointer stays valid. idx_grid: (*const u8, usize), sb_cols: usize, frame_w: usize, frame_h: usize, nbands: usize, cdef_on: bool, snap_on: bool, } // SAFETY: the `*const u8` is a read-only view of a Vec that is allocated once // per frame and only ever written at indices the pipeline is three bands // behind (see this module's dependency note). #[allow(unsafe_code)] unsafe impl Send for PipeCfg<'_> {} #[allow(unsafe_code)] #[allow(clippy::too_many_arguments)] fn pipe_run( sync: &PipeSync, sy: crate::par::Shared<'_, PlaneBuf<'static>>, su: crate::par::Shared<'_, PlaneBuf<'static>>, sv: crate::par::Shared<'_, PlaneBuf<'static>>, sn: crate::par::Shared<'_, Neighbours>, cfg: PipeCfg<'_>, snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>, lr_sync: Option<&PipeSync>, fctx: &crate::decode::FrameCtx, ) { // SAFETY: the frame thread parses (and reconstructs) bands the pipeline // is at least two behind, and the two ranges never meet -- see the // dependency note above and `Shared`'s own corner-cut. let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) }; let n: &Neighbours = unsafe { sn.get() }; let idx_grid = unsafe { std::slice::from_raw_parts(cfg.idx_grid.0, cfg.idx_grid.1) }; let coeff_shift = i32::from(bit_depth(fctx)) - 8; let damping = i32::from(cfg.cdef.damping) + coeff_shift; let damping_uv = (damping - 1).max(0); let (fw, fh) = (cfg.frame_w, cfg.frame_h); let nb = cfg.nbands; for k in 0..nb + 3 { if !sync.wait_for((k + 2).min(nb)) { if let Some(ls) = lr_sync { ls.close(nb, true); } return; } if k < nb { deblock_span(y, u, v, cfg.lf, n, fw, fh, k * 64, (k + 1) * 64, false, fctx); } if k >= 1 && k - 1 < nb { deblock_span(y, u, v, cfg.lf, n, fw, fh, (k - 1) * 64, k * 64, true, fctx); } if cfg.snap_on && k >= 2 && k - 2 < nb { let j = k - 2; if let Some((sy2, su2, sv2)) = snap.as_mut() { snap_band(sy2.data.to_mut(), y, 0, j * 64, (j + 1) * 64, cfg.cdef_on); snap_band(su2.data.to_mut(), u, 1, j * 32, (j + 1) * 32, cfg.cdef_on); snap_band(sv2.data.to_mut(), v, 1, j * 32, (j + 1) * 32, cfg.cdef_on); } } if cfg.cdef_on && k >= 3 && k - 3 < nb { let j = k - 3; if let Some((sy2, su2, sv2)) = snap.as_ref() { cdef_rows( y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols, coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx, ); } } // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release // them to the loop restoration worker. if let Some(ls) = lr_sync { ls.note(k.saturating_sub(2)); } } if let Some(ls) = lr_sync { ls.close(nb, false); } } /// The pipeline's loop restoration worker, a second task alongside /// [`pipe_run`]: restoration-unit row `r` writes `out` rows /// `v_start..v_end`, reads post-CDEF rows only inside that span and the /// post-deblock snapshot at most two rows past `v_end` (see /// `restoration::lr_src_row`), so it is ready as soon as CDEF band /// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own /// iteration `band + 3` and the snapshot band one iteration earlier, so the /// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row /// indices being at most one band apart. Running it as its own worker (not /// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF /// critical path: serialised into that loop it measured ~1% slower than the /// whole-frame form, which at least ran its RU rows across the filter pool. #[allow(unsafe_code)] fn pipe_run_lr( sync: &PipeSync, sy: crate::par::Shared<'_, PlaneBuf<'static>>, su: crate::par::Shared<'_, PlaneBuf<'static>>, sv: crate::par::Shared<'_, PlaneBuf<'static>>, snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>, cfg: LrCfg<'_>, fctx: &crate::decode::FrameCtx, ) { // SAFETY: this worker only reads bands `pipe_run` has finished filtering // and writes its own `out` buffers; the final swap happens after the // last CDEF band, which is `pipe_run`'s last plane write. let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) }; let snap = unsafe { snap.get() }; let grid = unsafe { &*cfg.lr_grid }; let (fw, fh) = (cfg.frame_w, cfg.frame_h); let dims = [ (fw, fh, 0u32, y.width, y.data.len()), (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()), (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()), ]; let mut planes: Vec = Vec::new(); for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() { let rows = crate::restoration::lr_unit_rows( ph, cfg.lr.loop_restoration_size[p], ss, cfg.lr.frame_restoration_type[p], ); if rows.is_empty() { continue; } planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride }); } for band in 0..cfg.nbands { if !sync.wait_for(band + 1) { return; } let Some((sy2, su2, sv2)) = snap.as_ref() else { return }; for lp in &mut planes { let stripe = 64usize >> lp.ss; let r_lo = lp.next; while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band { lp.next += 1; } if lp.next == r_lo { continue; } let (src, deb) = match lp.p { 0 => (&y.data, &sy2.data), 1 => (&u.data, &su2.data), _ => (&v.data, &sv2.data), }; crate::restoration::apply_loop_restoration_plane( src, deb, lp.stride, lp.pw, lp.ph, lp.ss, cfg.lr.frame_restoration_type[lp.p], cfg.lr.loop_restoration_size[lp.p], grid, lp.p, &mut lp.out, Some((r_lo, lp.next)), fctx, ); } } // The RU rows partition `0..plane_h`; the mi-rounded rows below it are // untouched by restoration and copied here, then the restored plane // takes the picture's place (the whole-frame path's own final swap). for mut lp in planes { let buf: &mut PlaneBuf<'static> = match lp.p { 0 => &mut *y, 1 => &mut *u, _ => &mut *v, }; let tail = lp.ph * lp.stride; if tail < buf.data.len() { lp.out[tail..].copy_from_slice(&buf.data[tail..]); } scratch_return( std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(), ); } } /// Everything [`pipe_run_lr`] needs beyond the planes. struct LrCfg<'a> { lr: &'a LoopRestorationParams, /// Sized once per frame by `RestorationGrid::new`; the parse thread is /// many bands ahead of every unit this worker reads. lr_grid: *const crate::restoration::RestorationGrid, frame_w: usize, frame_h: usize, nbands: usize, } // SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation. #[allow(unsafe_code)] unsafe impl Send for LrCfg<'_> {} /// One plane's pipelined loop restoration state (see [`pipe_run`]). struct LrPlane { p: usize, /// The restored plane, built band by band and swapped in at the end. out: Vec, rows: Vec<(u32, u32)>, /// The first RU row not yet restored. next: usize, pw: usize, ph: usize, ss: u32, stride: usize, } /// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases /// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and /// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw /// pointers into the frame's planes, so it may not outlive them). struct PipeGuard<'a> { sync: std::sync::Arc, batch: Option>, nbands: usize, /// The loop restoration worker's own gate, aborted with the first one. lr_sync: Option>, } impl PipeGuard<'_> { fn note(&self, bands: usize) { self.sync.note(bands); } fn finish(&mut self) { self.sync.close(self.nbands, false); // Dropping the batch waits the worker out. self.batch.take(); } } impl Drop for PipeGuard<'_> { fn drop(&mut self) { self.sync.close(self.nbands, true); if let Some(ls) = &self.lr_sync { ls.close(self.nbands, true); } } } /// Leading superblock rows of the live tile's wavefront that are fully /// reconstructed: parsed out to the last column and with every job that /// carried a write finished. 0 when reconstruction is inline (no wavefront), /// where the caller uses the parse position instead. fn wave_rows_complete(fctx: &crate::decode::FrameCtx) -> usize { let st = fctx.wave.with(|w| w.borrow().clone()); let Some(st) = st else { return 0 }; let q = st.q.lock().unwrap(); let mut n = 0; while n < q.rows.len() { if q.last_sub[n] < st.last_col as isize || q.done[n] < q.last_push[n] { break; } n += 1; } n } /// Frames whose loop filters ran pipelined, and frames that took the /// whole-frame path instead (`EC_AV1_WAVE_STATS`). static PIPE_FRAMES: AtomicU64 = AtomicU64::new(0); static PIPE_WHOLE: AtomicU64 = AtomicU64::new(0); /// Whether this frame's filters may run per superblock row. Everything that /// reads the picture out of band order, or the pipeline's own inputs out of /// row order, keeps the whole-frame path: superres (a between-CDEF-and-LR /// whole-plane resample), segmentation (the deblocker reads `seg_ids`, which /// the parse thread is still filling), delta_lf, more than one tile COLUMN (a /// frame row is only complete after the last tile column's own parse), and /// every pixel-dump / stage-skip debug flag, whose whole point is the /// unpipelined stage boundary. The pipeline also stays off unless some /// threading is on -- at (1, 1) the filters would run on a worker thread for /// nothing and the crate's `thread_local!` gate counters would miss them. fn pipe_filters_ok(fctx: &crate::decode::FrameCtx, tile_cols: u32, lf_present: bool) -> bool { if crate::envflags::var("EC_AV1_PIPE_FILTERS").map(|v| v.trim() == "0").unwrap_or(false) { return false; } if crate::par::filter_threads() == 1 && crate::par::recon_threads() == 1 { return false; } if tile_cols != 1 || lf_present || superres(fctx).is_some() { return false; } if fctx.seg.with(|s| s.borrow().enabled) { return false; } !(crate::envflags::is_set("EC_AV1_PREFILT_DUMP") || crate::envflags::is_set("EC_AV1_PREFILT_DUMP16") || crate::envflags::is_set("EC_AV1_PREFILT_WIDE_DUMP") || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP") || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP16") || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP") || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP16") || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_DEBLOCK") || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_CDEF") || crate::envflags::is_set("EC_AV1_DEBUG_CDEF_BAND") || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE") || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE_V")) } /// lane-cdefstrip r1 instrument, run for every frame BEFORE either of /// [`apply_cdef`]'s early returns (lane-pipefilt: the pipelined path /// never enters `apply_cdef`, so it calls this itself). fn cdef_scan_counters(skip_grid: &Neighbours) { let _ = skip_grid; hit_do! { let mut r = 0usize; while r < skip_grid.mi_rows { let mut c = 0usize; while c < skip_grid.mi_cols { if (0..2).any(|rr| { (0..2).any(|cc| { !skip_grid .blk_grid .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc)) .map_or(true, |x| x.written) }) }) { hit!(CDEF_UNWRITTEN_SKIP_UNITS); if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") { eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4); } } let cell = |rr: usize, cc: usize| { skip_grid .blk_grid .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc)) .is_some_and(|x| x.skip) }; let first = cell(0, 0); if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) { hit!(CDEF_MIXED_SKIP_UNITS); } c += 2; } r += 2; } } } /// `true` when this frame's CDEF cannot change a sample: `bits == 0` still /// means "no filtering at all" whenever the single (index 0) strength pair /// is all-zero, the fast path every existing gate stream takes. fn cdef_all_zero(cdef: &CdefParams) -> bool { cdef.bits == 0 && cdef.y_pri_strength[0] == 0 && cdef.y_sec_strength[0] == 0 && cdef.uv_pri_strength[0] == 0 && cdef.uv_sec_strength[0] == 0 } /// [`apply_cdef`]'s band loop over the mi rows `r_lo0..r_hi0` only (the /// whole frame when `0..mi_rows`, which is what `apply_cdef` passes). /// `src_*` are the PRE-CDEF planes every unit reads; the writes are this /// row range's own pixels. #[allow(clippy::too_many_arguments)] fn cdef_rows( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, src_y: &[u16], src_u: &[u16], src_v: &[u16], cdef: &CdefParams, skip_grid: &Neighbours, idx_grid: &[u8], sb_cols: usize, coeff_shift: i32, damping: i32, damping_uv: i32, (frame_w, frame_h): (usize, usize), r_lo0: usize, r_hi0: usize, fctx: &crate::decode::FrameCtx, ) { let mi_rows = skip_grid.mi_rows; let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows)); if lo >= hi { return; } let (sy, su, sv) = ( crate::par::Shared::new(y), crate::par::Shared::new(u), crate::par::Shared::new(v), ); let cbands: Vec<(usize, usize)> = crate::par::bands((hi - lo).div_ceil(2), crate::par::filter_threads()) .into_iter() .map(|(a, b)| (lo + a * 2, (lo + b * 2).min(hi))) .collect(); crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| { // SAFETY: this band writes only the plane rows its own mi rows cover, // disjoint from every other band's (see `Shared`). #[allow(unsafe_code)] let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) }; cdef_band( r_lo, r_hi, y, u, v, src_y, src_u, src_v, cdef, skip_grid, idx_grid, sb_cols, coeff_shift, damping, damping_uv, (frame_w, frame_h), fctx, ); }); } fn apply_cdef( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, cdef: &CdefParams, skip_grid: &Neighbours, // This frame header's own CROPPED luma size, for the straddling-unit // counter only -- CDEF itself walks the mi-rounded plane. (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx, ) { // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling. if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") { return; } cdef_scan_counters(skip_grid); // `cdef.bits == 0` still means "no filtering at all" whenever the single // (index 0) strength pair is all-zero -- the fast path every existing // gate stream takes. A `bits > 0` frame can still be all-zero-strength // at every index, but that is rare enough not to special-case; the // per-superblock lookup below degrades to the same index-0 read anyway // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`). if cdef_all_zero(cdef) { return; } let sb_cols = fctx.cdef_sb_cols.with(|c| c.get()); // One entry per superblock (a few hundred at 4K), so this clone is not // one of the per-frame copies lane-perf6 pooled below. let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone()); let src_y = scratch_from(&y.data); let src_u = scratch_from(&u.data); let src_v = scratch_from(&v.data); // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`, // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`. let coeff_shift = i32::from(bit_depth(fctx)) - 8; let damping = i32::from(cdef.damping) + coeff_shift; let damping_uv = (damping - 1).max(0); // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma / // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2 // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a // disjoint row range of all three planes. cdef_rows( y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift, damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx, ); scratch_return(src_y); scratch_return(src_u); scratch_return(src_v); } /// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop /// restoration on both tile paths: hands the encoder's restoration search the /// two pictures spec 7.17 filters from. `deblocked` is the decoder's own /// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so /// a capture is worth three plane copies and nothing else -- and when the /// capture flag is off (every decode but that search) it is worth a bool. fn capture_stages( y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>, fctx: &FrameCtx, ) { if !fctx.capture_stages.get() { return; } // Without an active restoration type the decoder took no pre-CDEF // snapshot; the post-CDEF plane then stands in for it, which is exact // everywhere but LR's own 3-row stripe borders (the encoder's search // always asks with a type set, so this is the defensive arm). let db = |i: usize, p: &PlaneBuf<'_>| match deblocked { Some((a, b, c)) => [a, b, c][i].data.to_vec(), None => p.data.to_vec(), }; *fctx.stages.borrow_mut() = Some(FilterStages { deblocked: [db(0, y), db(1, u), db(2, v)], cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()], stride: [y.width, u.width, v.width], }); } /// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's /// ordering note: libaom also runs `superres_post_decode` between the two, /// but this decoder never implements super-resolution, so there is nothing /// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF /// buffer (the caller clones it before calling [`apply_cdef`]) -- loop /// restoration's stripe-boundary rows read from it instead of the /// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment. #[allow(clippy::too_many_arguments)] fn apply_loop_restoration( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, deblocked_y: &PlaneBuf<'_>, deblocked_u: &PlaneBuf<'_>, deblocked_v: &PlaneBuf<'_>, lr: &LoopRestorationParams, grid: &crate::restoration::RestorationGrid, // lane-golomb r8: this frame header's own (cropped) luma size. Loop // restoration is the ONE post-decode filter that does NOT run over the // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes // every plane with `av1_get_upsampled_plane_size` -- `plane_w = // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h = // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`) // -- and asserts it equals the buffer's CROP width // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h, // ...)` (`restoration.c:1109`) replicates the right/bottom border from // that cropped edge before any unit is filtered. Deblock and CDEF DO // walk the mi grid, which is why passing `true_width`/`true_height` // here went unnoticed until a frame whose size is not a multiple of 8 // (68 -> mi-rounded 72): the LR taps at the last four real columns then // read this decoder's own decoded samples at columns 68..71 where // libaom reads column 67 replicated -- +-1 over the straddling band // (class av1-truesize-lane: true frame size vs mi-rounded). (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx, ) { let mut out = scratch_empty(); crate::restoration::apply_loop_restoration_plane( &y.data, &deblocked_y.data, y.width, frame_w, frame_h, 0, lr.frame_restoration_type[0], lr.loop_restoration_size[0], grid, 0, &mut out, None, fctx, ); scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned()); let mut out = scratch_empty(); crate::restoration::apply_loop_restoration_plane( &u.data, &deblocked_u.data, u.width, frame_w.div_ceil(2), frame_h.div_ceil(2), 1, lr.frame_restoration_type[1], lr.loop_restoration_size[1], grid, 1, &mut out, None, fctx, ); scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned()); let mut out = scratch_empty(); crate::restoration::apply_loop_restoration_plane( &v.data, &deblocked_v.data, v.width, frame_w.div_ceil(2), frame_h.div_ceil(2), 1, lr.frame_restoration_type[2], lr.loop_restoration_size[2], grid, 2, &mut out, None, fctx, ); scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned()); } /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes, /// returning the picture it reconstructs to. /// /// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by /// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true /// (render) size — a separate field from `mi_cols`/`mi_rows` (spec /// `compute_image_size` derives one from the other, but not losslessly: a /// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) — /// what the reconstruction is cropped to on the way out, mirroring /// [`crate::encode::crop_encoded`]. /// /// # Errors /// Returns an error when a block's partition, mode, skip flag or transform /// type is anything this decoder does not reconstruct (round 2: inter, tx /// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below /// 16x16, a directional mode's angle delta other than zero, chroma-from-luma), /// or when the tile payload runs out of the symbols this decode expects (a /// genuinely foreign stream). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn decode_key_frame_tile( data: &[u8], mi_cols: u32, mi_rows: u32, base_q_idx: u8, frame_width: u32, frame_height: u32, enable_filter_intra: bool, cdef: &CdefParams, loop_filter: &LoopFilterParams, tx_select: bool, reduced_tx_set: bool, allow_screen_content_tools: bool, allow_intrabc: bool, fctx: &crate::decode::FrameCtx, ) -> Result { decode_key_frame_tile_lr( data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra, cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc, &LoopRestorationParams::default(), fctx, ) } /// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec /// 5.9.20) instead of the no-restoration default -- the per-unit filters /// themselves live in the tile payload, so the header is all this needs. #[allow(clippy::too_many_arguments)] pub(crate) fn decode_key_frame_tile_lr( data: &[u8], mi_cols: u32, mi_rows: u32, base_q_idx: u8, frame_width: u32, frame_height: u32, enable_filter_intra: bool, cdef: &CdefParams, loop_filter: &LoopFilterParams, tx_select: bool, reduced_tx_set: bool, allow_screen_content_tools: bool, allow_intrabc: bool, lr: &LoopRestorationParams, fctx: &crate::decode::FrameCtx, ) -> Result { let single_tile = TileInfo { mi_col_starts: vec![0, mi_cols], mi_row_starts: vec![0, mi_rows], ..TileInfo::default() }; decode_key_frame_tiles_lr( &[data], &single_tile, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra, cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc, lr, fctx, ) } /// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the /// encoder's own filter search hands back one payload per tile plus the /// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets /// are the decoder's own (`decode_key_frame_tile_with_cdfs`). #[allow(clippy::too_many_arguments)] pub(crate) fn decode_key_frame_tiles_lr( tiles: &[&[u8]], tile_info: &TileInfo, mi_cols: u32, mi_rows: u32, base_q_idx: u8, frame_width: u32, frame_height: u32, enable_filter_intra: bool, cdef: &CdefParams, loop_filter: &LoopFilterParams, tx_select: bool, reduced_tx_set: bool, allow_screen_content_tools: bool, allow_intrabc: bool, lr: &LoopRestorationParams, fctx: &crate::decode::FrameCtx, ) -> Result { let delta = DeltaParams::default(); decode_key_frame_tile_with_cdfs( tiles, tile_info, mi_cols, mi_rows, base_q_idx, crate::quant::QuantDeltas::default(), frame_width, frame_height, enable_filter_intra, false, cdef, loop_filter, lr, None, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc, delta, fctx, ) .map(|(picture, _)| picture) } /// lane-superres r3: the real decoded margin beyond `frame_width` up to /// the mi-aligned `true_width`, set by the most recent /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10) /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop /// their reconstructed buffer down from the same mi-aligned extent, so /// they share this one slot. See each function's own comment at its /// write site. `None` when there was no margin to save. /// The margin the most recent key- or inter-frame tile decode stashed /// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path /// reads this immediately after the call, before any other frame /// decode can overwrite it. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option { fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take()) } /// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec /// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from /// a prior frame's saved reference slot) when set, or the spec 8.4 defaults /// when `None` (the only case [`decode_key_frame_tile`] itself ever needs, /// since a key frame's own header always forces `primary_ref_frame == /// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table /// alongside the picture, for the caller to save into whichever reference /// slots this frame's `refresh_frame_flags` names. /// The order the 64x64 superblock quadrants of a tile are decoded in. /// /// At `sb_size == 64` this is plain raster order over the tile's own /// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses /// each 128x128 superblock in raster order and visits its four 64x64 /// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the /// 64-level bodies must run in that nested order. `row_start` marks the first /// item of each *superblock* row (where the left neighbour context resets), /// `sb_start` the first item of each superblock (where the 128 root's own /// loop-restoration units and partition symbol are read). fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> { let mut out = Vec::new(); if !sb128 { for r in r0..r1 { for c in c0..c1 { out.push((r, c, c == c0, true)); } } return out; } let mut r = r0; while r < r1 { let mut first_in_row = true; let mut c = c0; while c < c1 { let mut first_in_sb = true; for qr in 0..2 { for qc in 0..2 { let (rr, cc) = (r + qr, c + qc); if rr >= r1 || cc >= c1 { continue; } out.push((rr, cc, first_in_row, first_in_sb)); first_in_row = false; first_in_sb = false; } } c += 2; } r += 2; } out } // lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and // the inter tile loop. Its loop-restoration units are read once for the whole // 128x128 (spec 5.11.57 is called with the superblock's own size), then one // partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4) // decides the root -- only SPLIT recurses into the four 64x64 quadrants this // decoder codes, the other seven arms refuse by name. thread_local! { /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one /// whole 128x128 block (lane-sb128b r1's gate counter). pub(crate) static PART128_NONE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one /// when the bottom half is out of frame) -- lane-sb128c r7. pub(crate) static PART128_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces). pub(crate) static PART128_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Of those, the ones decided by the GATHERED bit at a frame edge -- the /// only shape a 1080p (mi_rows = 270) stream reaches. pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes, /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; } /// [`PART128_AB_HITS`], for a gate's own before/after delta. pub(crate) fn part128_ab_hits() -> [usize; 4] { PART128_AB_HITS.with(std::cell::Cell::get) } /// [`PART128_NONE_HITS`], for a gate's own before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn part128_none_hits() -> usize { PART128_NONE_HITS.with(std::cell::Cell::get) } /// [`PART128_HORZ_HITS`], for a gate's own before/after delta. #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live pub(crate) fn part128_horz_hits() -> usize { PART128_HORZ_HITS.with(std::cell::Cell::get) } /// [`PART128_VERT_HITS`], for a gate's own before/after delta. #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live pub(crate) fn part128_vert_hits() -> usize { PART128_VERT_HITS.with(std::cell::Cell::get) } /// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge. pub(crate) fn part128_edge_horz_hits() -> usize { PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get) } /// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge. pub(crate) fn part128_edge_vert_hits() -> usize { PART128_EDGE_VERT_HITS.with(std::cell::Cell::get) } thread_local! { /// How many CHROMA transform units were coded inside a block whose uv /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128 /// block, four per plane). pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_split_tx_hits() -> usize { CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get) } fn read_sb128_root( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &Neighbours, lr: &LoopRestorationParams, lr_grid: &mut crate::restoration::RestorationGrid, lr_reference: &mut [( crate::restoration::WienerInfo, crate::restoration::SgrprojInfo, ); 3], sb_r: u32, sb_c: u32, mi_cols: u32, mi_rows: u32, fctx: &crate::decode::FrameCtx, ) -> Result { let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI); crate::restoration::read_lr( dec, cdfs, lr, lr_grid, lr_reference, mi_r128, mi_c128, SB_MI * 2, fctx, ); let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize); let ctx128 = neighbours.partition_ctx(at128, 128); let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows); let part128 = if has_cols128 && has_rows128 { hit!(PART128_SYMBOLS); let p = dec.symbol(&mut cdfs.partition_w128[ctx128]); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!("TRACE partition_w128 ctx={ctx128} value={p}"); } p } else { // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the // partition, they are not a forced split -- exactly the discarded-bit // defect the 64 root carries a comment about at `partition_w64`'s // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or // VERT (cols out of frame), which the refusal below then names // instead of silently reconstructing a split. hit!(PART128_GATHERED_SYMBOLS); match (has_cols128, has_rows128) { (true, false) => { if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 { PARTITION_SPLIT } else { hit!(PART128_EDGE_HORZ_HITS); PARTITION_HORZ } } (false, true) => { if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 { PARTITION_SPLIT } else { hit!(PART128_EDGE_VERT_HITS); PARTITION_VERT } } _ => { PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1)); bump_edge_both_cut(3); PARTITION_SPLIT } } }; // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by // the key-frame caller below. The six remaining arms (HORZ/VERT and the // four AB shapes) still need the rect/AB machinery at this size. // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on // both tile paths. The four AB shapes (libaom `decode_partition`'s // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet, // which stops at VERT_B). match part128 { PARTITION_SPLIT => hit!(PART128_SPLIT_HITS), PARTITION_NONE => hit!(PART128_NONE_HITS), PARTITION_HORZ => hit!(PART128_HORZ_HITS), PARTITION_VERT => hit!(PART128_VERT_HITS), // lane-sb128c r9: the four AB shapes at the 128 root -- one // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile // paths below in libaom `decode_partition`'s own visit order. p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => { hit_do! { PART128_AB_HITS.with(|c| { let mut h = c.get(); h[p - PARTITION_HORZ_A] += 1; c.set(h); }); } } _ => { return Err(unsupported( "a 128x128 superblock partition value outside the 8-symbol alphabet", )); } } Ok(part128) } pub(crate) fn decode_key_frame_tile_with_cdfs( tiles: &[&[u8]], tile_info: &TileInfo, mi_cols: u32, mi_rows: u32, base_q_idx: u8, // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every // tile alongside [`CURRENT_Q_IDX`]. deltas: crate::quant::QuantDeltas, frame_width: u32, frame_height: u32, enable_filter_intra: bool, enable_edge_filter: bool, cdef: &CdefParams, loop_filter: &LoopFilterParams, lr: &LoopRestorationParams, initial_cdfs: Option, tx_select: bool, reduced_tx_set: bool, allow_screen_content_tools: bool, allow_intrabc: bool, // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18) // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]); // `stream.rs` still refuses a frame with `lf_present` set before this // function is ever called. delta: DeltaParams, fctx: &crate::decode::FrameCtx, ) -> Result<(Picture, Cdfs)> { // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder // only, so a key frame decoded after an inter frame on this thread would // otherwise inherit it and read its `tx_depth` context off the inter // frame's stale `TXFM_CONTEXT` bands. fctx.tx_select_inter.with(|c| c.set(false)); if mi_cols == 0 || mi_rows == 0 { return Err(unsupported("a frame with no mode-info grid")); } fctx.enable_edge_filter.with(|f| f.set(enable_edge_filter)); let sb128 = sb128(fctx); let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI)); fctx.intrabc_mi_grid.with(|g| { *g.borrow_mut() = allow_intrabc.then(|| { ( crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize), mi_cols as usize, mi_rows as usize, ) }); }); fctx.intrabc_dv.with(|c| c.set(None)); fctx.cdef_bits.with(|c| c.set(cdef.bits)); fctx.cdef_sb_cols.with(|c| c.set(sb_cols as usize)); fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]); fctx.delta_q_present.with(|c| c.set(delta.q_present)); fctx.delta_q_res.with(|c| c.set(1i32 << delta.q_res)); fctx.delta_lf_present.with(|c| c.set(delta.lf_present)); fctx.delta_lf_res.with(|c| c.set(1i32 << delta.lf_res)); fctx.delta_lf_multi.with(|c| c.set(delta.lf_multi)); let (cols32, rows32) = block_grid(mi_cols, mi_rows); let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize); let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK); let mut y = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(width * height)), width, height, true_width, true_height, tile_x0: 0, tile_y0: 0, tile_x1: width, tile_y1: height, }; let mut u = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)), width: width / 2, height: height / 2, true_width: true_width / 2, true_height: true_height / 2, tile_x0: 0, tile_y0: 0, tile_x1: width / 2, tile_y1: height / 2, }; let mut v = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)), width: width / 2, height: height / 2, true_width: true_width / 2, true_height: true_height / 2, tile_x0: 0, tile_y0: 0, tile_x1: width / 2, tile_y1: height / 2, }; let scan32 = default_scan(TX32); let scan16 = default_scan(TX16); let scan8 = default_scan(TX8); let scan4 = default_scan(TX4); let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); let mut result_cdfs = base_cdfs.clone(); let mut neighbours = Neighbours::new( cols32 as usize * 2, rows32 as usize * 2, mi_cols as usize, mi_rows as usize, fctx, ); // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width -- // loop restoration runs after the superres upscale. let mut lr_grid = crate::restoration::RestorationGrid::new( lr, superres(fctx).map_or(frame_width, |(w, _)| w), frame_height, ); // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its // own byte range and its own fresh copy of the frame's initial CDFs // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by // `context_update_tile_id` has its end-of-tile adapted table kept as the // frame's own output (spec `exit_symbol`) -- every other tile's // adaptation is discarded, matching the refusal this replaces. for (tile_idx, &tile_bytes) in tiles.iter().enumerate() { let tile_num = tile_idx as u32; let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols); let mi_row0 = tile_info.mi_row_starts[trow as usize]; let mi_row1 = tile_info.mi_row_starts[trow as usize + 1]; let mi_col0 = tile_info.mi_col_starts[tcol as usize]; let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1]; // Tile boundaries are always superblock-aligned in mi units (spec // 5.9.15's uniform/non-uniform derivation both only ever emit // multiples of the superblock's own mi size), so plain division is // exact here -- no rounding needed. // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior // tile boundary) are always superblock-aligned by spec 5.9.15; the // frame's own true final edge (`mi_row_starts`/`mi_col_starts`' // last entry) is not, so the upper bound needs `div_ceil` the same // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the // trailing partial superblock row/column in scope. let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows)); let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols)); // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` / // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not // once per frame. Carried across a tile boundary, the loop-restoration // coefficients of the next tile decode off the previous tile's // reference -- same symbol count, so entropy and reconstruction stay // exact and only the filtered pixels of every tile after the first // are wrong. let mut lr_reference = [( crate::restoration::WienerInfo::default(), crate::restoration::SgrprojInfo::default(), ); 3]; let mut cdfs = base_cdfs.clone(); // spec `decode_tile`: `CurrentQIndex` resets to the frame's own // `base_q_idx` at the top of every tile, not once per frame. fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx))); fctx.quant_deltas.with(|c| c.set(deltas)); fctx.current_delta_lf.with(|c| c.set([0; 4])); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}", tile_bytes.len(), &tile_bytes[..tile_bytes.len().min(8)] ); } let mut dec = SymbolDecoder::new(tile_bytes); neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx); y.set_tile_origin( mi_col0 as usize * 4, mi_row0 as usize * 4, (mi_col1 as usize * 4).min(y.width), (mi_row1 as usize * 4).min(y.height), ); u.set_tile_origin( mi_col0 as usize * 2, mi_row0 as usize * 2, (mi_col1 as usize * 2).min(u.width), (mi_row1 as usize * 2).min(u.height), ); v.set_tile_origin( mi_col0 as usize * 2, mi_row0 as usize * 2, (mi_col1 as usize * 2).min(v.width), (mi_row1 as usize * 2).min(v.height), ); hit!(TILE_HITS); // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` -- // its one block covers all four 64x64 quadrants, so the remaining three // visits of this superblock code nothing at all. let mut sb128_none = false; // lane-wave1 step (ii): at one reconstruction thread the recorded writes // are performed at their push sites (nothing reaches the queue below). let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v); // lane-wave1 step (ii): one job per superblock (per 128x128 superblock // when `sb128`, since a 128 block writes across its four 64x64 visits). let wave_shift = u32::from(sb128); let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize); let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 { ( ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1, ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1, ) } else { (0, 0) }; let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols); let waving = fctx.wave.with(|w| w.borrow().is_some()); let mut wave_job = (0usize, 0usize); for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) { // lane-wave1: the previous superblock's recorded writes -- handed to // the wavefront workers, or replayed here at one recon thread (where // the queue is empty, every write having run at its push site). if waving { if sb_start { wave_submit(fctx, wave_job.0, wave_job.1); wave_job = ( (sb_r >> wave_shift) as usize - wave_r0, (sb_c >> wave_shift) as usize - wave_c0, ); } } else { flush_recon(fctx, &mut y, &mut u, &mut v); } if row_start { neighbours.start_row(); } if sb_start { sb128_none = false; } if sb128_none { continue; } { // lane-sb128 r1: the 128 root. Its loop-restoration units are read // once for the whole 128x128 (spec 5.11.57 is called with the // superblock's own size), then one partition symbol off the // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT // recurses into the four 64x64 quadrants this decoder codes. if sb128 && sb_start { let part128 = read_sb128_root( &mut dec, &mut cdfs, &neighbours, lr, &mut lr_grid, &mut lr_reference, sb_r, sb_c, mi_cols, mi_rows, fctx, )?; if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) { // lane-sb128c r9: the four AB shapes at the 128 root. // libaom `decode_partition` (decodeframe.c) codes each as // two `bsize2` (64x64) squares plus one `subsize` // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right // half; VERT_B = left half, TR, BR. AB values only come // from the FULL alphabet symbol, which is only read when // both halves of the root are inside the frame, so no // piece needs libaom's `i > 0` frame-edge break (a piece // may still overhang the bottom/right, which // `PlaneBuf::reconstruct`'s r8 clip handles). sb128_none = true; let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); let (br, bc) = (at128.0 + 4, at128.1 + 4); let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize); // Only the VERTICAL arms reorder the squares (TL, BL, TR, // BR), so only they switch libaom's `has_tr_vert_*` / // `has_bl_vert_*` tables (lane-sb128c r6 visit order). let _vert_ab = (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B) .then(crate::encode::Reach::vert_ab_partition); // One `cdef_idx` literal per CODED BLOCK, at the first // non-skip one of each 64x64 CDEF unit; the 128x64 / // 64x128 half covers two units and its read lands in the // unit holding its origin, so that value is copied to the // other one (libaom: every mi of the block points at the // same `MB_MODE_INFO`). let cdef_copy = |src: (usize, usize), dst: (usize, usize)| { fctx.cdef_idx_grid.with(|g| { let mut g = g.borrow_mut(); let cols = fctx.cdef_sb_cols.with(|c| c.get()); if cols == 0 { return; } let (si, di) = ( (q_r + src.0) * cols + q_c + src.1, (q_r + dst.0) * cols + q_c + dst.1, ); if q_c + src.1 < cols && q_c + dst.1 < cols && si < g.len() && di < g.len() { g[di] = g[si]; } }); }; macro_rules! square64 { ($at:expr) => {{ fctx.cdef_transmitted.with(|c| c.set(false)); decode_block( &mut dec, &mut cdfs, &mut neighbours, $at, SB, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, (&scan32, &scan32), false, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )? }}; } macro_rules! half128 { ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{ fctx.cdef_transmitted.with(|c| c.set(false)); decode_block_128rect( &mut dec, &mut cdfs, &mut neighbours, $at, $bw, $bh, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, tx_select, reduced_tx_set, fctx, )?; cdef_copy($src, $dst); }}; } match part128 { PARTITION_HORZ_A => { square64!(at128); square64!((at128.0, bc)); half128!((br, at128.1), 128, 64, (1, 0), (1, 1)); } PARTITION_HORZ_B => { half128!(at128, 128, 64, (0, 0), (0, 1)); square64!((br, at128.1)); square64!((br, bc)); } PARTITION_VERT_A => { square64!(at128); square64!((br, at128.1)); half128!((at128.0, bc), 64, 128, (0, 1), (1, 1)); } _ => { half128!(at128, 64, 128, (0, 0), (1, 0)); square64!((at128.0, bc)); square64!((br, bc)); } } continue; } if matches!(part128, PARTITION_HORZ | PARTITION_VERT) { // lane-sb128c r8: libaom `decode_partition` // (decodeframe.c:1554) codes PARTITION_HORZ at the 128 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col) // plus a second one at (mi_row + hbs, mi_col) only // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2` // = 16 mi. Both halves together cover the whole root, so // the remaining three 64x64 quadrant visits code nothing // (same flag the NONE arm sets). sb128_none = true; let horz = part128 == PARTITION_HORZ; let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) }; for i in 0..2 { let at = if horz { (at128.0 + i * 4, at128.1) } else { (at128.0, at128.1 + i * 4) }; let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI)); if i > 0 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize) { break; } // Each half reads its OWN `cdef_idx` literal // (libaom `read_cdef` keys the `-1` test on the // block's own `MB_MODE_INFO`, and the two halves have // different ones). fctx.cdef_transmitted.with(|c| c.set(false)); decode_block_128rect( &mut dec, &mut cdfs, &mut neighbours, at, bw, bh, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, tx_select, reduced_tx_set, fctx, )?; } // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF // unit it covers (the inter path's own fan-out). let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize); fctx.cdef_idx_grid.with(|g| { let mut g = g.borrow_mut(); let cols = fctx.cdef_sb_cols.with(|c| c.get()); if cols == 0 { return; } for (src, dst) in if horz { [((0, 0), (0, 1)), ((1, 0), (1, 1))] } else { [((0, 0), (1, 0)), ((0, 1), (1, 1))] } { let (si, di) = ( (q_r + src.0) * cols + q_c + src.1, (q_r + dst.0) * cols + q_c + dst.1, ); if q_c + src.1 < cols && q_c + dst.1 < cols && si < g.len() && di < g.len() { g[di] = g[si]; } } }); continue; } if part128 == PARTITION_NONE { // One 128x128 intra block: four TX_64X64 luma units and a // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize` // of a 128x128 block is TX_64X64 over its 64x64 uv plane // block). No CfL, no filter intra, no palette at this size -- // [`read_intra_mode`]'s own size gates already say so. sb128_none = true; fctx.cdef_transmitted.with(|c| c.set(false)); let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); decode_block( &mut dec, &mut cdfs, &mut neighbours, at128, SB * 2, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, (&scan32, &scan32), false, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; // libaom writes one `cdef_strength` into the block's own // `MB_MODE_INFO`, which every mi cell of the block -- // hence all four 64x64 CDEF units -- points at; our grid // is per-unit, so the read (which only ever lands in the // top-left unit, `read_cdef`'s index 0) is copied across. let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize); fctx.cdef_idx_grid.with(|g| { let mut g = g.borrow_mut(); let cols = fctx.cdef_sb_cols.with(|c| c.get()); if cols > 0 && q_r * cols + q_c < g.len() { let idx = g[q_r * cols + q_c]; for (dr, dc) in [(0, 1), (1, 0), (1, 1)] { let i = (q_r + dr) * cols + q_c + dc; if q_c + dc < cols && i < g.len() { g[i] = idx; } } } }); continue; } } if !sb128 { crate::restoration::read_lr( &mut dec, &mut cdfs, lr, &mut lr_grid, &mut lr_reference, sb_r * SB_MI, sb_c * SB_MI, SB_MI, fctx, ); } fctx.cdef_transmitted.with(|c| c.set(false)); let at = (sb_r as usize * 4, sb_c as usize * 4); let ctx = neighbours.partition_ctx(at, SB); let (has_cols, has_rows) = ( sb_c * SB_MI + SB_MI / 2 < mi_cols, sb_r * SB_MI + SB_MI / 2 < mi_rows, ); // Recomputed at this superblock's own half (spec // `decode_partition`): a full alphabet symbol when both halves are // inside the true frame, a single gathered bit when just one is // (the superblock cannot be left whole, so this is forced split), // and nothing at all (SPLIT inferred, no bits) when neither is — // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own // three-way write exactly. let part = if has_cols && has_rows { let p = dec.symbol(&mut cdfs.partition_w64[ctx]); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!("TRACE partition_w64 ctx={ctx} value={p}"); } p } else { // lane-hgkf r1 (class `parsed-then-discarded`, same finding as // the unmerged lane-golomb r1): the gathered bit IS the // partition -- libaom `ec_read_partition_impl` returns // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1. // Forcing SPLIT desynced the last superblock row of every // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0, // the first block of that row. match (has_cols, has_rows) { (true, false) => { trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32); let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)); bump_edge32(4 + b.min(1) as usize); bump_edge_part(b.min(1) as usize); if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } (false, true) => { trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32); let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)); bump_edge32(4 + b.min(1) as usize); bump_edge_part(b.min(1) as usize); if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } _ => { bump_edge_both_cut(2); PARTITION_SPLIT } } }; match part { PARTITION_NONE => { decode_block( &mut dec, &mut cdfs, &mut neighbours, at, SB, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, (&scan32, &scan32), false, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; } PARTITION_SPLIT => { for q in 0..4 { let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2); if r32 >= rows32 || c32 >= cols32 { continue; } let at32 = (r32 as usize * 2, c32 as usize * 2); let ctx32 = neighbours.partition_ctx(at32, BLOCK); let (has_cols32, has_rows32) = ( has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols), has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows), ); let part32 = if has_cols32 && has_rows32 { let p = dec.symbol(&mut cdfs.partition_w32[ctx32]); if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!( "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}", r32 * BLOCK_MI, c32 * BLOCK_MI ); } p } else { // lane-hgkf r1: the 32-level frame-edge bit is the // partition too (same libaom reader as the // superblock level above). match (has_cols32, has_rows32) { (true, false) => { trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32); let b = dec.symbol_fixed(&gather( &cdfs.partition_w32[ctx32], VERT_ALIKE, )); bump_edge32(b.min(1) as usize); bump_edge_part(2 + b.min(1) as usize); if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } (false, true) => { trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32); let b = dec.symbol_fixed(&gather( &cdfs.partition_w32[ctx32], HORZ_ALIKE, )); bump_edge32(b.min(1) as usize); bump_edge_part(2 + b.min(1) as usize); if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } _ => { bump_edge_both_cut(1); PARTITION_SPLIT } } }; match part32 { PARTITION_NONE => { decode_block( &mut dec, &mut cdfs, &mut neighbours, at32, BLOCK, TxbSet::Luma32, TxbSet::Chroma16, TX32, TX16, (&scan32, &scan16), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; } PARTITION_SPLIT => { for sub in 0..4 { let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2); if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols { continue; } let (has_cols16, has_rows16) = ( has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols), has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows), ); let at16 = (sr, sc); let ctx16 = neighbours.partition_ctx(at16, SUB); if has_cols16 && has_rows16 { let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}", at16.0, at16.1 ); } if part16 == PARTITION_NONE { decode_block( &mut dec, &mut cdfs, &mut neighbours, at16, SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; continue; } if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) { // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's // `decode_partition` visit order (decodeframe.c): // HORZ_A: TL 8x8, TR 8x8, bottom 16x8 // HORZ_B: top 16x8, BL 8x8, BR 8x8 // VERT_A: TL 8x8, BL 8x8, right 8x16 // VERT_B: left 8x16, TR 8x8, BR 8x8 // The squares go through `decode_leaf8`, the strip through // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients -- // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm // used refuses the non-skip case at this size). Both writers keep // mi-granular mode/skip/palette records, so a later block's // `above_mi`/`left_mi` sees the real sub-block, not the coarse // 16x16 cell. // // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's // top-right neighbour is the partition's own not-yet-decoded // rectangle: libaom switches those squares onto `has_tr_vert_*`/ // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here). let arm = part16 - PARTITION_HORZ_A; bump_ab16(arm); if part16 == PARTITION_VERT_B { hit!(VERT_B_INTRA_HITS); } let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B { Some(crate::encode::Reach::vert_ab_partition()) } else { None }; let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize); macro_rules! ab_leaf8 { ($mi:expr, $prev:expr) => { decode_leaf8( &mut dec, &mut cdfs, &mut neighbours, at16, $mi, (&scan8, &scan4), $prev, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, tx_select, reduced_tx_set, fctx, )? }; } macro_rules! ab_strip { ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => { decode_leaf_rect( &mut dec, &mut cdfs, &mut neighbours, at16, $mi, $bw, $bh, $prev, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )? }; } let tl = (mi_row0, mi_col0); let tr = (mi_row0, mi_col0 + 2); let bl = (mi_row0 + 2, mi_col0); let br = (mi_row0 + 2, mi_col0 + 2); let mut done: Vec<((usize, usize), usize)> = Vec::new(); match part16 { PARTITION_HORZ_A => { let m_tl = ab_leaf8!(tl, done.last().copied()); done.push((tl, m_tl)); let m_tr = ab_leaf8!(tr, done.last().copied()); done.push((tr, m_tr)); let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl))); done.push((bl, m_bot)); } PARTITION_HORZ_B => { let m_top = ab_strip!(tl, 16, 8, None); done.push((tl, m_top)); let m_bl = ab_leaf8!(bl, done.last().copied()); done.push((bl, m_bl)); let m_br = ab_leaf8!(br, done.last().copied()); done.push((br, m_br)); } PARTITION_VERT_A => { let m_tl = ab_leaf8!(tl, done.last().copied()); done.push((tl, m_tl)); let m_bl = ab_leaf8!(bl, done.last().copied()); done.push((bl, m_bl)); let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl))); done.push((tr, m_right)); } _ => { let m_left = ab_strip!(tl, 8, 16, None); done.push((tl, m_left)); let m_tr = ab_leaf8!(tr, done.last().copied()); done.push((tr, m_tr)); let m_br = ab_leaf8!(br, done.last().copied()); done.push((br, m_br)); } } // Same coarse-slot write-back the real SPLIT path takes: the // 16x16 cell's single `above_mode`/`left_mode` entry gets the // sub-block on the parent's bottom / right edge (the mi-exact map // above wins wherever it has an entry). write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc)); continue; } if part16 == PARTITION_HORZ { hit!(HORZ_VERT_INTRA_HITS); let (mi_row0, mi_col0) = ( sr as u32 * SUB_MI, sc as u32 * SUB_MI, ); let top = (mi_row0 as usize, mi_col0 as usize); let bot = (mi_row0 as usize + 2, mi_col0 as usize); let mode_top = decode_leaf_rect( &mut dec, &mut cdfs, &mut neighbours, at16, top, 16, 8, None, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; let mode_bot = decode_leaf_rect( &mut dec, &mut cdfs, &mut neighbours, at16, bot, 16, 8, Some((top, mode_top)), &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; neighbours.above_mode[sc] = mode_bot; neighbours.left_mode[sr] = mode_bot; continue; } if part16 == PARTITION_VERT { hit!(HORZ_VERT_INTRA_HITS); let (mi_row0, mi_col0) = ( sr as u32 * SUB_MI, sc as u32 * SUB_MI, ); let left = (mi_row0 as usize, mi_col0 as usize); let right = (mi_row0 as usize, mi_col0 as usize + 2); let mode_left = decode_leaf_rect( &mut dec, &mut cdfs, &mut neighbours, at16, left, 8, 16, None, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; let mode_right = decode_leaf_rect( &mut dec, &mut cdfs, &mut neighbours, at16, right, 8, 16, Some((left, mode_left)), &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; neighbours.above_mode[sc] = mode_right; neighbours.left_mode[sr] = mode_right; continue; } if part16 == PARTITION_HORZ_4 || part16 == PARTITION_VERT_4 { decode_rect4_16( &mut dec, &mut cdfs, &mut neighbours, at16, part16 == PARTITION_HORZ_4, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; continue; } // lane-r14 r2 (verifier note): every // one of the 10 symbols this CDF can // produce is handled above, so SPLIT // is the only value that reaches // here -- the refusal that used to // stand here was unreachable and is // gone from `refusal_inventory`. debug_assert_eq!(part16, PARTITION_SPLIT); // A real (non-straddle) SPLIT of a // whole 16x16 into four 8x8 leaves -- // the same recursion the straddle // path below already runs when the // true frame edge forces it, just // over all four positions instead of // the one or two the edge leaves. let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); // Each 8x8 leaf's intra-mode context // must see its own siblings: the // bottom-left leaf's ABOVE neighbour // is leaf 0, not the previously // decoded leaf 1 (and the bottom-right // leaf's above is leaf 1, while // `prev_leaf` only ever carried the // immediately preceding one). The // coarse `above_mode`/`left_mode` // arrays hold one slot per 16x16, so // the sibling modes are swapped in // around each leaf call and restored // after; the loop tail writes the last // leaf's mode as before. let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4]; for i in 0..4 { let (mr, mc) = (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); let leaf_mi = (mr as usize, mc as usize); let li = i as usize; let saved_modes = (neighbours.above_mode[sc], neighbours.left_mode[sr]); if li >= 2 { if let Some((below, _)) = sib_modes[li - 2] { neighbours.above_mode[sc] = below; } } if li % 2 == 1 { if let Some((_, right)) = sib_modes[li - 1] { neighbours.left_mode[sr] = right; } } let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}" ); } let leaf_mode = if part8 == PARTITION_NONE { decode_leaf8( &mut dec, &mut cdfs, &mut neighbours, at16, leaf_mi, (&scan8, &scan4), None, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, tx_select, reduced_tx_set, fctx, ).map(|m| (m, m))? } else if part8 == PARTITION_SPLIT { decode_leaf_split4( &mut dec, &mut cdfs, &mut neighbours, at16, leaf_mi, &scan4, None, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_intrabc, reduced_tx_set, fctx, )? } else if part8 == PARTITION_HORZ || part8 == PARTITION_VERT { decode_leaf_rect8( &mut dec, &mut cdfs, &mut neighbours, at16, leaf_mi, part8 == PARTITION_VERT, &scan4, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_intrabc, tx_select, reduced_tx_set, fctx, )? } else { unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only"); }; neighbours.above_mode[sc] = saved_modes.0; neighbours.left_mode[sr] = saved_modes.1; sib_modes[li] = Some(leaf_mode); } if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) { neighbours.above_mode[sc] = below; } if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) { neighbours.left_mode[sr] = right; } continue; } // The true edge falls inside this 16x16 // leaf itself (mod-32==8 target sizes, // lane-av1-rect): one axis only -- an 8x8 // leaf never itself straddles, so the // block splits cleanly along whichever // axis is short. // lane-edgeboth r1: when the true frame // edge cuts BOTH axes libaom's // `decode_partition` takes // `else if (!has_rows && !has_cols) // partition = PARTITION_SPLIT;` -- no // symbol of any kind is read, and the four // 8x8 children are then visited by the // same loop below, whose // `mr < mi_rows && mc < mi_cols` filter IS // libaom's own // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;` // early return, so the three out-of-frame // quadrants get no neighbour or tx-grid // write. if !has_cols16 && !has_rows16 { bump_edge_both_cut(0); } else { // lane-golomb r1 (class // `parsed-then-discarded`): the gathered // bit IS the partition -- 0 names // PARTITION_HORZ (resp. VERT), only 1 is // SPLIT (libaom `ec_read_partition_impl`). // This path can only walk the four SPLIT // leaves, so a 0 refuses by name instead // of desyncing. trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32); let edge_split = if has_cols16 { dec.symbol_fixed(&gather( &cdfs.partition_w16[ctx16], VERT_ALIKE, )) } else { dec.symbol_fixed(&gather( &cdfs.partition_w16[ctx16], HORZ_ALIKE, )) }; // lane-hgkf r1: slots 2/3 of // [`EDGE_PART_HITS`], the gate's proof the // non-SPLIT edge arm actually decoded. bump_edge_part(if edge_split == 1 { 3 } else { 2 }); if edge_split == 0 { // lane-oddh r1: the strip IS decodable // -- libaom's `decode_partition` codes // only the FIRST half of an edge // HORZ/VERT (the second call is // guarded by the same has_rows/ // has_cols test that made the // partition non-square), so one // 16x8 (resp. 8x16) strip covers the // whole visible band of a frame whose // height (resp. width) is 8 mod 16 -- // the user's 3840x1608 film. hit!(HORZ_VERT_INTRA_HITS); hit!(EDGE_RECT_STRIP_HITS); let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) }; let mode = decode_leaf_rect( &mut dec, &mut cdfs, &mut neighbours, at16, (mi_row0 as usize, mi_col0 as usize), bw, bh, None, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; neighbours.above_mode[sc] = mode; neighbours.left_mode[sr] = mode; continue; } } let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); let leaf_positions: Vec<(u32, u32)> = (0..4) .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2)) .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) .collect(); // See the sibling-mode note in the clean // SPLIT path above. let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4]; for (mr, mc) in leaf_positions { let leaf_mi = (mr as usize, mc as usize); let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2) as usize; let saved_modes = (neighbours.above_mode[sc], neighbours.left_mode[sr]); if li >= 2 { if let Some((below, _)) = sib_modes[li - 2] { neighbours.above_mode[sc] = below; } } if li % 2 == 1 { if let Some((_, right)) = sib_modes[li - 1] { neighbours.left_mode[sr] = right; } } let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); let pre8 = dec.debug_state().0; let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}" ); } let leaf_mode = if part8 == PARTITION_NONE { decode_leaf8( &mut dec, &mut cdfs, &mut neighbours, at16, leaf_mi, (&scan8, &scan4), None, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, tx_select, reduced_tx_set, fctx, ).map(|m| (m, m))? } else if part8 == PARTITION_SPLIT { decode_leaf_split4( &mut dec, &mut cdfs, &mut neighbours, at16, leaf_mi, &scan4, None, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_intrabc, reduced_tx_set, fctx, )? } else if part8 == PARTITION_HORZ || part8 == PARTITION_VERT { decode_leaf_rect8( &mut dec, &mut cdfs, &mut neighbours, at16, leaf_mi, part8 == PARTITION_VERT, &scan4, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_intrabc, tx_select, reduced_tx_set, fctx, )? } else { unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only"); }; neighbours.above_mode[sc] = saved_modes.0; neighbours.left_mode[sr] = saved_modes.1; sib_modes[li] = Some(leaf_mode); } // `record()`'s `above_mode`/`left_mode` // write is a no-op at an 8x8 leaf's own // side, so force the write once the whole // 16x16 slot's leaves are done, from the // last leaf (mirrors the writer's r15 // fix). if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) { neighbours.above_mode[sc] = below; } if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) { neighbours.left_mode[sr] = right; } } } PARTITION_HORZ => { // lane-intradisp r1: two true 32x16 strips. decode_block_rect( &mut dec, &mut cdfs, &mut neighbours, at32, 32, 16, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; if !has_rows32 { bump_edge32(2); } // lane-hgkf r1: at the frame edge only the first half of the strip is // coded (libaom `decode_partition` guards the second half with the same // test that made this partition non-square). if has_rows32 { decode_block_rect( &mut dec, &mut cdfs, &mut neighbours, (at32.0 + 1, at32.1), 32, 16, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; } } PARTITION_VERT => { // lane-intradisp r1: mirror of PARTITION_HORZ // above with width/height swapped. decode_block_rect( &mut dec, &mut cdfs, &mut neighbours, at32, 16, 32, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; if !has_cols32 { bump_edge32(3); } // lane-hgkf r1: at the frame edge only the first half of the strip is // coded (libaom `decode_partition` guards the second half with the same // test that made this partition non-square). if has_cols32 { decode_block_rect( &mut dec, &mut cdfs, &mut neighbours, (at32.0, at32.1 + 1), 16, 32, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; } } PARTITION_HORZ_A => { // lane-part32 r1: two 16x16 squares on top + // a true 32x16 strip below (mirrors // decode_inter_block's cd6cb6d HORZ_A: TL, // TR, bottom strip). hit!(INTRA_HORZ_A_HITS); decode_block( &mut dec, &mut cdfs, &mut neighbours, at32, SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; decode_block( &mut dec, &mut cdfs, &mut neighbours, (at32.0, at32.1 + 1), SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; decode_block_rect( &mut dec, &mut cdfs, &mut neighbours, (at32.0 + 1, at32.1), 32, 16, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; } PARTITION_HORZ_B => { // lane-part32 r1: a true 32x16 strip on top + // two 16x16 squares below (mirrors HORZ_A // with the strip/squares order flipped, same // shape as libaom decode_partition's HORZ_B). hit!(INTRA_HORZ_B_HITS); decode_block_rect( &mut dec, &mut cdfs, &mut neighbours, at32, 32, 16, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; decode_block( &mut dec, &mut cdfs, &mut neighbours, (at32.0 + 1, at32.1), SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; decode_block( &mut dec, &mut cdfs, &mut neighbours, (at32.0 + 1, at32.1 + 1), SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; } PARTITION_VERT_A => { // lane-part32 r1: mirror of HORZ_A with // width/height swapped (TL, BL, right 16x32 // strip). hit!(INTRA_VERT_A_HITS); let _vert_ab = crate::encode::Reach::vert_ab_partition(); decode_block( &mut dec, &mut cdfs, &mut neighbours, at32, SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; decode_block( &mut dec, &mut cdfs, &mut neighbours, (at32.0 + 1, at32.1), SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; decode_block_rect( &mut dec, &mut cdfs, &mut neighbours, (at32.0, at32.1 + 1), 16, 32, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; } PARTITION_VERT_B => { // lane-part32 r1: a true 16x32 strip on the // left + two 16x16 squares on the right // (libaom decode_partition VERT_B: left // strip, TR, BR). hit!(INTRA_VERT_B_HITS); let _vert_ab = crate::encode::Reach::vert_ab_partition(); decode_block_rect( &mut dec, &mut cdfs, &mut neighbours, at32, 16, 32, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; decode_block( &mut dec, &mut cdfs, &mut neighbours, (at32.0, at32.1 + 1), SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; decode_block( &mut dec, &mut cdfs, &mut neighbours, (at32.0 + 1, at32.1 + 1), SUB, TxbSet::Luma16, TxbSet::Chroma8, TX16, TX8, (&scan16, &scan8), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )?; } PARTITION_HORZ_4 | PARTITION_VERT_4 => { // lane-tx64x16 r3: the 1:4 pair at the 32x32 // level -- four 32x8 (or 8x32) strips in // raster order, `quarter_step` = 2 mi, with // libaom `decode_partition`'s own `i > 0` // frame-edge break. let horz = part32 == PARTITION_HORZ_4; let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI)); let mut prev: Option<((usize, usize), usize)> = None; for i in 0..4 { let strip_mi = if horz { (base_mi.0 + i * 2, base_mi.1) } else { (base_mi.0, base_mi.1 + i * 2) }; if i > 0 && (strip_mi.0 >= mi_rows as usize || strip_mi.1 >= mi_cols as usize) { break; } let (bw, bh) = if horz { (32, 8) } else { (8, 32) }; let (mode, _uv) = decode_block_rect4( &mut dec, &mut cdfs, &mut neighbours, strip_mi, bw, bh, prev, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, fctx, )?; prev = Some((strip_mi, mode)); } } _ => { return Err(unsupported(format!( "a 32x32 partition type this decoder does not code (value={part32})" ))); } } } } PARTITION_HORZ => { // lane-sbpart r2: two true 64x32 strips. decode_block_rect64( &mut dec, &mut cdfs, &mut neighbours, at, 64, 32, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; if !has_rows { bump_edge32(6); } // lane-golomb r1: at the frame edge only the first half of the // strip is coded (libaom `decode_partition` guards the second // with the same has_rows test that made this partition non-square). if has_rows { decode_block_rect64( &mut dec, &mut cdfs, &mut neighbours, (at.0 + 2, at.1), 64, 32, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; } } PARTITION_VERT => { // lane-sbpart r2: mirror of PARTITION_HORZ above with // width/height swapped. decode_block_rect64( &mut dec, &mut cdfs, &mut neighbours, at, 32, 64, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; if !has_cols { bump_edge32(7); } // lane-golomb r1: at the frame edge only the first half of the // strip is coded (libaom `decode_partition` guards the second // with the same has_cols test that made this partition non-square). if has_cols { decode_block_rect64( &mut dec, &mut cdfs, &mut neighbours, (at.0, at.1 + 2), 32, 64, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; } } PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => { // lane-part32 r4: the four superblock-level AB arms, each // two 32x32 squares plus one 64x32/32x64 strip, in // libaom's own `decode_partition` order (decodeframe.c: // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL, // BR; VERT_A = TL, BL, right strip; VERT_B = left strip, // TR, BR). The pieces are exactly the ones already proven // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above. hit_do! { SB_AB_HITS.with(|c| { let mut h = c.get(); h[part - PARTITION_HORZ_A] += 1; c.set(h); }); } // lane-part32 r5: only the two VERTICAL arms reorder the // square sub-blocks (TL, BL, TR, BR), so only they switch // libaom's `has_tr`/`has_bl` tables. let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B) .then(crate::encode::Reach::vert_ab_partition); macro_rules! square32 { ($at:expr) => { decode_block( &mut dec, &mut cdfs, &mut neighbours, $at, BLOCK, TxbSet::Luma32, TxbSet::Chroma16, TX32, TX16, (&scan32, &scan16), true, &mut y, &mut u, &mut v, base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, &scan32, &scan16, &scan8, &scan4, tx_select, reduced_tx_set, fctx, )? }; } macro_rules! strip64 { ($at:expr, $bw:expr, $bh:expr) => { decode_block_rect64( &mut dec, &mut cdfs, &mut neighbours, $at, $bw, $bh, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )? }; } let (br, bc) = (at.0 + 2, at.1 + 2); match part { PARTITION_HORZ_A => { square32!(at); square32!((at.0, bc)); strip64!((br, at.1), 64, 32); } PARTITION_HORZ_B => { strip64!(at, 64, 32); square32!((br, at.1)); square32!((br, bc)); } PARTITION_VERT_A => { square32!(at); square32!((br, at.1)); strip64!((at.0, bc), 32, 64); } _ => { strip64!(at, 32, 64); square32!((at.0, bc)); square32!((br, bc)); } } } PARTITION_HORZ_4 | PARTITION_VERT_4 => { // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or // 16x64) strips in raster order. `decode_partition` // (`decodeframe.c`) steps by `quarter_step = mi_size / 4` // (4 mi = 16 px = one SUB unit here) and BREAKS at the // frame edge for `i > 0`, so a partial superblock codes // only the strips whose origin is inside the frame. let horz = part == PARTITION_HORZ_4; for i in 0..4 { let step_mi = i * (SB_MI as usize / 4); let (this_r_mi, this_c_mi) = if horz { (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize) } else { (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi) }; if i > 0 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize) { break; } let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) }; let (bw, bh) = if horz { (64, 16) } else { (16, 64) }; decode_block_rect64( &mut dec, &mut cdfs, &mut neighbours, strip_at, bw, bh, &mut y, &mut u, &mut v, enable_filter_intra, allow_screen_content_tools, base_q_idx, tx_select, reduced_tx_set, fctx, )?; } } _ => { return Err(unsupported( "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4", )); } } } } if waving { wave_submit(fctx, wave_job.0, wave_job.1); } // lane-timeline: this tile's last symbol is read here; its wavefront // workers are drained by `_wave`'s drop at the end of the iteration. crate::timeline::tile_done(); flush_recon(fctx, &mut y, &mut u, &mut v); if tile_num == tile_info.context_update_tile_id { result_cdfs = cdfs; } } crate::timeline::recon_done(); // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders. if crate::envflags::env_flag!("EC_OBMC") || crate::envflags::env_flag!("EC_TRACE_MODE") || crate::envflags::env_flag!("EC_PRED") { eprintln!( "EC_PICT idx={}", PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) ); } dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; let _ = f.write_all(&narrow(&y)); let _ = f.write_all(&narrow(&u)); let _ = f.write_all(&narrow(&v)); } } else { PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); } if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") { use std::io::Write; static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let crop_wide = |plane: &PlaneBuf<'_>| -> Vec { let mut out = Vec::with_capacity(plane.true_width * plane.true_height); for row in 0..plane.true_height { out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8)); } out }; if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { let _ = f.write_all(&crop_wide(&y)); let _ = f.write_all(&crop_wide(&u)); let _ = f.write_all(&crop_wide(&v)); } } // lane-av1fwd: the encoder's filter search re-decodes this same key // frame tile per candidate -- capture it once (see [`FilterReplay`]), // on the shape whose tail is the two filter calls and nothing else. if superres(fctx).is_none() && !(0..3).any(|p| { lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None && lr.loop_restoration_size[p] != 0 }) { capture_filter_replay( &y, &u, &v, &neighbours, frame_width as usize, frame_height as usize, width, height, true_width, true_height, ); } apply_deblock( &mut y, &mut u, &mut v, loop_filter, &neighbours, frame_width as usize, frame_height as usize, fctx, ); // lane-perf4: loop restoration is the only reader of the pre-CDEF planes, // and a frame that restores nothing copied every plane twice for nothing // (three `PlaneBuf` clones here plus the `cdef.to_vec()` inside // [`crate::restoration::apply_loop_restoration_plane`], which returns its // input unchanged when the plane's type is `None`). Clone only when some // plane actually restores. let lr_active = (0..3).any(|p| { lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None && lr.loop_restoration_size[p] != 0 }); let deblocked = lr_active.then(|| (plane_snapshot(&y, 0), plane_snapshot(&u, 1), plane_snapshot(&v, 1))); // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter // dump above these bisect WHICH filter stage introduced a mismatch. dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_cdef( &mut y, &mut u, &mut v, cdef, &neighbours, (frame_width as usize, frame_height as usize), fctx, ); dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); capture_stages(&y, &u, &v, deblocked.as_ref(), fctx); // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`): // the horizontal upscale runs HERE -- after CDEF, before loop // restoration, not after the whole filter chain. Both the post-CDEF // frame and the post-deblock frame that LR substitutes at its stripe // boundaries are upscaled (`save_deblock_boundary_lines` runs // `av1_upscale_normative_rows` over its saved rows when the frame is // scaled), so every LR coordinate from here on is in upscaled space. let mut deblocked = deblocked; let mut lr_w = frame_width as usize; if let Some((upscaled_w, _)) = superres(fctx) { let bd = u32::from(bit_depth(fctx)); let (uw, fw, fh) = (upscaled_w as usize, frame_width as usize, frame_height as usize); let up = |p: &PlaneBuf<'_>, in_w: usize, in_h: usize, out_w: usize| PlaneBuf { data: std::borrow::Cow::Owned(crate::superres::upscale_plane_strided( &p.data, p.width, in_w, in_h, p.true_width, out_w, bd, )), width: out_w, height: in_h, true_width: out_w, true_height: in_h, tile_x0: 0, tile_y0: 0, tile_x1: out_w, tile_y1: in_h, }; let (cw, ch, cuw) = (fw.div_ceil(2), fh.div_ceil(2), uw.div_ceil(2)); y = up(&y, fw, fh, uw); u = up(&u, cw, ch, cuw); v = up(&v, cw, ch, cuw); if let Some((dy, du, dv)) = deblocked.take() { deblocked = Some((up(&dy, fw, fh, uw), up(&du, cw, ch, cuw), up(&dv, cw, ch, cuw))); } lr_w = uw; crate::superres::note_upscaled_picture(); } if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked { apply_loop_restoration( &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid, (lr_w, frame_height as usize), fctx, ); } if let Some((db_y, db_u, db_v)) = deblocked { // LIFO pool: return in reverse so the next frame's `y`/`u`/`v` // snapshots pop buffers of their own size and never resize. scratch_return(db_v.data.into_owned()); scratch_return(db_u.data.into_owned()); scratch_return(db_y.data.into_owned()); } crate::timeline::filters_done(); let (fw, fh) = (lr_w, frame_height as usize); // An upscaled frame is already at its final size with no mi-aligned // margin beyond it (the upscale consumed those columns), so the // wide-margin stash below has nothing left to hand out. let (true_width, true_height) = if superres(fctx).is_some() { (fw, fh) } else { (true_width, true_height) }; if fw == width && fh == height { fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); return Ok(( Picture { width, height, y: y.data.into_owned(), u: u.data.into_owned(), v: v.data.into_owned(), }, result_cdfs, )); } let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec { let mut out = Vec::with_capacity(w * h); for row in 0..h { out.extend(plane.data[row * plane.width..][..w].iter().copied()); } out }; // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4) // is the real reconstructed extent -- columns `[fw, true_width)` hold // genuine decoded samples (the last coding block straddles the frame // edge whenever `frame_width` isn't 8-sample aligned), not padding. // libaom's superres upscale runs on that buffer's own border-extended // margin, so it reads those real columns, not a synthetic replicate of // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real // aomenc 43->64 stream pinned column-by-column against libaom's own // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` -- // `row6-realedgeval` proved the replicate-of-`fw-1` padding this // decoder used before was off by 1 at the columns the tap window // reaches into that real margin; `None` when there is no margin (this // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a // non-superres frame whose width just isn't 32-block aligned). fctx.last_frame_wide_margin.with(|m| { *m.borrow_mut() = if true_width > fw || true_height > fh { let yc = crop(&y, true_width, true_height); if let Ok(path) = crate::envflags::var("EC_AV1_MARGIN_DUMP") { use std::io::Write; static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { // corner-cut: this diagnostic dump stays 8-bit-narrowed // regardless of the stream's real bit depth (debug-only, // never read by a gate); widen if a >8-bit margin dump // is ever needed. let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::>()); } } Some(Picture { width: true_width, height: true_height, y: yc, u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)), v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)), }) } else { None } }); Ok(( Picture { width: fw, height: fh, y: crop_owned(y, fw, fh), u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)), v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)), }, result_cdfs, )) } /// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]` /// -- `above`/`left` are the neighbour's own resolved index for this /// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`). /// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s /// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this* /// block itself has a second reference) -- lane-av1idx: a stale "this /// decoder never codes a compound reference" assumption baked this to /// always-0, which desynced the CDF context bucket (not the decoded value /// outright, hence small pixel deltas rather than a hard desync) the moment /// lane-av1blend unmasked plain-average compound blocks on a Switchable- /// filter frame. fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize { let base = dir * 8 + if is_compound { 4 } else { 0 }; let term = if left == above { left } else if left == 3 { above } else if above == 3 { left } else { 3 }; base + term as usize } /// Resolves the interpolation filter kernel(s) an inter block's motion /// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame /// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame /// (`interp_fixed = None`) reads `interp_filter[0]` and, when /// `enable_dual_filter`, a second `interp_filter[1]` -- unless /// `force_regular` (this block's own `needs_interp_filter() == 0` case: a /// `GLOBALMV` block, whose global motion is always `IDENTITY` in this /// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch), /// which forces `EIGHTTAP` without reading anything. #[allow(clippy::too_many_arguments)] fn resolve_interp_filter( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, interp_fixed: Option, enable_dual_filter: bool, force_regular: bool, above: [u8; 2], left: [u8; 2], is_compound: bool, ) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) { if let Some(kind) = interp_fixed { return (kind, kind, [3, 3]); } if force_regular { return ( mc::InterpFilterKind::Regular, mc::InterpFilterKind::Regular, [0, 0], ); } // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`) // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not // "horizontal then vertical" despite `predict_with_filters`' own // `h_kind`/`v_kind` argument order, which is why this function returns // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`). let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound); if crate::envflags::env_flag!("EC_AV1_IFDBG") { eprintln!( "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}", &cdfs.switchable_interp[ctx0][..3] ); } let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8; let sym1 = if enable_dual_filter { let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound); if crate::envflags::env_flag!("EC_AV1_IFDBG") { eprintln!( "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}", &cdfs.switchable_interp[ctx1][..3] ); } dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8 } else { sym0 }; if enable_dual_filter && sym0 != sym1 { hit!(DUAL_FILTER_DIFF_HITS); } if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}", dec.debug_state().0 ); } ( mc::InterpFilterKind::from_switchable_symbol(sym1 as usize), mc::InterpFilterKind::from_switchable_symbol(sym0 as usize), [sym0, sym1], ) } /// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`), /// duplicating [`crate::tile`]'s private copy of the same rule. pub(crate) fn intra_inter_ctx( has_above: bool, has_left: bool, above_inter: bool, left_inter: bool, ) -> usize { match (has_above, has_left) { (true, true) => { let (above_intra, left_intra) = (!above_inter, !left_inter); if above_intra && left_intra { 3 } else { usize::from(above_intra || left_intra) } } (true, false) => 2 * usize::from(!above_inter), (false, true) => 2 * usize::from(!left_inter), (false, false) => 0, } } /// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private /// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own /// bits start counting from. fn mv_class_base(class: usize) -> i32 { if class == 0 { 0 } else { 2i32 << (class + 2) } } /// One motion vector component's non-zero diff (spec 5.11.32 /// `read_mv_component`), the inverse of [`crate::tile`]'s private /// `write_mv_component`. fn read_mv_component( dec: &mut SymbolDecoder, c: &mut MvComponentCdfs, allow_high_precision_mv: bool, force_integer_mv: bool, ) -> i32 { let sign = dec.symbol(&mut c.sign); let class = dec.symbol(&mut c.class); let local = if class == 0 { let bit = dec.symbol(&mut c.class0_bit); // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame // forces integer motion vectors -- implicitly `3` (the top // fractional value) rather than read, else every symbol after it // in the tile desyncs by one read. let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.class0_fr[bit]) }; // spec 5.11.32 `mv_class0_hp`: read only when the frame allows // high-precision motion vectors, else implicitly 1 (the low bit // stays at half-pel precision) -- this crate's own writer always // leaves the flag off, but a foreign stream can set it per frame. let hp = if allow_high_precision_mv { dec.symbol(&mut c.class0_hp) } else { 1 }; (bit << 3) | (fr << 1) | hp } else { let mut d = 0; for i in 0..class { d |= dec.symbol(&mut c.bit[i]) << i; } // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as // `mv_class0_fr` above. let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) }; let hp = if allow_high_precision_mv { dec.symbol(&mut c.hp) } else { 1 }; (d << 3) | (fr << 1) | hp }; let mag = mv_class_base(class) + local as i32 + 1; if sign == 1 { -mag } else { mag } } /// A motion vector coded as a residual against `pred` (spec 5.11.32 /// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`. fn read_mv( dec: &mut SymbolDecoder, mv_comp: &mut [MvComponentCdfs; 2], mv_joint: &mut [u16; 5], pred: (i32, i32), allow_high_precision_mv: bool, force_integer_mv: bool, ) -> (i32, i32) { let joint = dec.symbol(mv_joint); let mut diff = (0, 0); if joint == 2 || joint == 3 { diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv); } if joint == 1 || joint == 3 { diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv); } (pred.0 + diff.0, pred.1 + diff.1) } /// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` -> /// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`). /// /// The predictor is the ordinary MV stack built against `INTRA_FRAME` /// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv` /// when that is zero, or -- when both are -- the fixed fallback DV one /// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the /// left when this is the tile's first superblock row. The predictor is then /// rounded to full pel, and the difference reads off the *dv* nmv context /// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp` /// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL /// symbol is coded for a DV, so none of this can move the bitstream /// position -- only the reconstructed vector. fn read_intrabc_dv( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, side: usize, fctx: &crate::decode::FrameCtx, ) -> (i32, i32) { const INTRABC_DELAY_PIXELS: i32 = 256; let n4 = side / MI; let stack_pred = fctx.intrabc_mi_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) { // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the // single-tile-row case every intrabc gate stream is). // lane-t900 r34: `av1_find_ref_dv` takes `mib_size` -- the SEQUENCE's // superblock size in mi units -- so a 128x128 superblock stream's // fallback DV is one 128-px superblock up (or 128+256 px left on the // tile's first superblock row), never the 64 this hardcoded. let sb_mi = sb_mi_cur(fctx) as i32; 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) }; } // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel. let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8); read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true) } /// A 1/8-pel motion vector component converted to the 1/16-pel offset /// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4` /// (its own doc comment explains the `*2`/`*1` luma/chroma split). fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 { (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 } } impl PlaneBuf<'_> { /// Adds `residual` onto an already-computed `prediction` (motion /// compensation's output, rather than [`predict`]'s intra one), writing /// the clamped reconstruction into the plane at `(x, y)` -- the inter /// counterpart of [`PlaneBuf::reconstruct`]. /// [`Self::reconstruct_mc_rect`], writing only a `w`x`h` sub-rectangle of the /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/ /// VERT strip is predicted at its enclosing square `side` (matching /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5) /// but only its own true `w`x`h` footprint is committed to the plane, so /// two strips sharing a square's coordinate origin never clobber each /// other's real pixels. fn reconstruct_mc_rect( &mut self, x: usize, y: usize, side: usize, w: usize, h: usize, prediction: &[u16], residual: &[i32], fctx: &crate::decode::FrameCtx, ) { // lane-sb128c r7: a 128x64 half of a 128 root at the BOTTOM frame edge // is the first block shape whose true footprint overhangs the padded // coding surface (mi_rows = 198 -> a plane 800 rows tall, block rows // 768..832). libaom reconstructs those rows into the frame buffer's // border; nothing reads them back, so they are simply dropped here. let (h, w) = (h.min(self.height.saturating_sub(y)), w.min(self.width.saturating_sub(x))); // lane-perf4: one row of each operand at a time. `side` is the // prediction/residual stride and `self.width` the plane's, so the // three row bases are computed once per row instead of a // multiply-add per sample (the samples themselves are unchanged). let max = crate::decode::sample_max(fctx); // lane-recoparse: an all-zero residual (60% of the units) is a plain // prediction copy -- the same arithmetic with `r == 0`, without // reading `side * h` zeros out of [`ZERO_RESIDUAL`]. if residual.is_empty() { for row in 0..h { let src = row * side; let dst = (y + row) * self.width + x; let pred = &prediction[src..src + w]; let out = &mut self.data.to_mut()[dst..dst + w]; for (o, &p) in out.iter_mut().zip(pred) { *o = i32::from(p).clamp(0, max) as u16; } } return; } let residual = dense_residual(residual, side * h); for row in 0..h { let src = row * side; let dst = (y + row) * self.width + x; let pred = &prediction[src..src + w]; let res = &residual[src..src + w]; let out = &mut self.data.to_mut()[dst..dst + w]; for ((o, &p), &r) in out.iter_mut().zip(pred).zip(res) { *o = (i32::from(p) + r).clamp(0, max) as u16; } } } } /// Reads one inter-coded plane's transform block and reconstructs it by /// adding its residual onto a motion-compensated `prediction` -- the inter /// counterpart of [`read_plane`] (every inter transform this decoder reads is /// `side`-square with no oversized-64 case, so there is no padded-grid /// branch to mirror). #[allow(clippy::too_many_arguments)] fn read_inter_plane( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, set: TxbSet, scan: &[u16], plane_idx: usize, around: (bool, bool, i32), tx_mode: usize, // lane-wave1 step (i): unread -- this reader records its write // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow // stays in the signature so every call site still proves the plane is // exclusively held while its coefficients are parsed. _plane: &mut PlaneBuf<'static>, x: usize, y: usize, side: usize, _base_q_idx: u8, prediction: Pred<'_>, // lane-chromau: this block's own luma transform's *actual coded* // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's // chroma plane never codes its own `tx_type` symbol, but (unlike an // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits // the colocated luma transform's coded type, narrowed to the extended // set the CHROMA size selects ([`reduce_inherited_chroma_tx_type`]). // `None` for the luma call itself // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true // `DCT_DCT` default at 32-point+) already resolves it without help. inherited_luma_tx_type: Option, // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size` // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block // transform every non-var-tx caller reads, whose plane-0 context is the // lone-transform-unit 0. luma_skip_ctx: Option, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, TxType)> { let skip_ctx = if plane_idx == 0 { luma_skip_ctx.unwrap_or(0) } else { // lane-sb128c r1: on a CHROMA plane this same parameter carries // `get_txb_ctx`'s own offset instead -- `combine_entropy_contexts(..)` // is +7 normally and +10 when the plane block is LARGER than the // transform (a 128x128 block's 64x64 uv plane block with TX_32X32 // units, AV1's only such case), and the `txb_skip_chroma_32` table // carries the offset-10 rows at +3 (lane-sb128b r3). usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0) }; let mut coding = cdfs.txb(set, tx_mode); let default_tx_type = match inherited_luma_tx_type { Some(t) => reduce_inherited_chroma_tx_type(t, side, side, fctx), None => TxType::DctDct, }; let (grid, tx_type) = read_coeffs( dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2), default_tx_type, None, )?; note_chroma_class1(plane_idx, tx_type); if crate::envflags::env_flag!("EC_TRACE_TXTYPE") { eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} side={side} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}"); } // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the // caller hands the 32-point `scan` there, and the coded corner goes into // the top-left of the true `side`-sized grid before dequantization // (dqDenom is keyed by the true size, not the corner's), mirroring // [`read_plane`]'s own `tx_side != side` branch. Every other transform // this decoder codes has `tx_side == side`, so this is inert below 64. let tx_side = side.min(32); let grid = extend_corner(grid, tx_side, tx_side, side, side); let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx); let tx = TxParams { w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type, stride: 0, }; push_mc_rect_tx(plane_idx, x, y, side, side, side, prediction, tx, &grid, fctx); Ok((grid, tx_type)) } /// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode` /// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with /// `reference_select` set before this is ever called, so that read is never /// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable /// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs). fn read_single_ref( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_ref: i8, above_ref1: Option, left_ref: i8, left_ref1: Option, ) -> i8 { let above = (above_ref > 0).then_some(above_ref); let left = (left_ref > 0).then_some(left_ref); let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]); let ref_frame = if p1 == 1 { let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]); if p2 == 1 { ALTREF_FRAME } else { let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]); if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME } } } else { let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]); if p3 == 1 { let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]); if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME } } else { let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]); if p4 == 1 { LAST2_FRAME } else { LAST_FRAME } } }; if ref_frame != LAST_FRAME { hit!(NON_LAST_REF_HITS); let c = match ref_frame { LAST2_FRAME => &LAST2_HITS, LAST3_FRAME => &LAST3_HITS, GOLDEN_FRAME => &GOLDEN_HITS, BWDREF_FRAME => &BWDREF_HITS, ALTREF2_FRAME => &ALTREF2_HITS, ALTREF_FRAME => &ALTREF_HITS, _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"), }; hit_do! { c.with(|v| v.set(v.get() + 1)); } } ref_frame } /// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads /// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's /// `reference_select` header bit lets a block choose per-block instead of /// fixing the mode. `above`/`left` are `None` for an intra/unavailable /// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s /// own doc. Called from [`decode_inter_block`] once its own `reference_select` /// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same /// way with a coarser (`LAST_FRAME`-only) neighbour shape. /// lane-twostage: this frame's references as DIMENSIONS now and PIXELS on /// demand. An inter tile's parse reads reference SIZES (`mc::scale_factor`) /// only, so the pictures are resolved at the first [`ref_planes`] call /// rather than at frame entry. On the threaded path that resolution is a /// WAIT on the producing frame's pixels, which is what lets a consumer parse /// while its references are still being filtered. /// lane-defer8: at more than one reconstruction thread that first call now /// happens on a recon WORKER -- every whole-block prediction (the 16x16+ /// paths, the 8x8 leaf, OBMC and the sub-8x8 chroma piece) is built inside /// its [`PredBuild`] closure, and the parse thread only ever asks for /// [`ref_dims`]. The sub-8x8 GROUP paths (4xN/Nx4 partitions) still predict /// inline and are the last parse-thread reference readers. pub(crate) struct RefPix<'p> { /// `(width, height)` per `ref_frame` index (`LAST_FRAME` = 1). `None` is /// a slot this frame may not use: empty, or -- for a non-`LAST_FRAME` /// slot -- not the same size as `LAST_FRAME`'s own picture (spec 7.9's /// compatible-size rule, the filter the eager `owned_refs` array applied). dims: [Option<(usize, usize)>; 8], src: RefSrc<'p>, bufs: std::sync::OnceLock<[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]>, /// lane-defer8: a DEFERRED prediction's [`ref_planes`] failure, parked /// here for the frame decoder to take ([`take_err`](Self::take_err)) -- /// a recon worker replaying a recorded op has no `?` of its own. err: std::sync::Mutex>, } /// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait /// the caller owns (`stream.rs`'s reference promises). enum RefSrc<'p> { Ready([Option<&'p Picture>; 8]), Lazy(&'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p)), } /// `LAST_FRAME`'s own index in a [`RefPix`] (spec 6.10.24). const LAST_REF: usize = 1; impl<'p> RefPix<'p> { /// References already decoded: the single-threaded path and the test /// entry points, where [`ref_planes`] never waits. pub(crate) fn ready(refs: [Option<&'p Picture>; 8]) -> Self { let dims = Self::compatible(std::array::from_fn(|i| { refs[i].map(|p| (p.width, p.height)) })); Self { dims, src: RefSrc::Ready(refs), bufs: std::sync::OnceLock::new(), err: std::sync::Mutex::new(None) } } /// References whose sizes are known (from their producers' headers) but /// whose pixels `wait` still has to produce. pub(crate) fn lazy( dims: [Option<(usize, usize)>; 8], wait: &'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p), ) -> Self { Self { dims: Self::compatible(dims), src: RefSrc::Lazy(wait), bufs: std::sync::OnceLock::new(), err: std::sync::Mutex::new(None), } } /// Spec 7.9's compatible-size rule: a non-`LAST_FRAME` slot at a /// different size than `LAST_FRAME`'s is treated as absent, exactly as /// the eager `owned_refs.filter(..)` did. fn compatible(mut dims: [Option<(usize, usize)>; 8]) -> [Option<(usize, usize)>; 8] { let last = dims[LAST_REF]; for (i, d) in dims.iter_mut().enumerate() { if i != LAST_REF && *d != last { *d = None; } } dims } /// This slot's picture size, without touching its pixels. pub(crate) fn dims(&self, ref_frame: i8) -> Option<(usize, usize)> { self.dims.get(ref_frame as usize).copied().flatten() } /// Parks a deferred prediction's failure (first one wins). fn park_err(&self, e: Error) { let mut slot = self.err.lock().expect("the parked-error slot is never poisoned"); if slot.is_none() { *slot = Some(e); } } /// The first failure any deferred prediction parked, taken once every /// recon worker of the frame has been joined. pub(crate) fn take_err(&self) -> Result<()> { match self.err.lock().expect("the parked-error slot is never poisoned").take() { Some(e) => Err(e), None => Ok(()), } } /// Every usable slot's three planes, resolving (and, on the threaded /// path, waiting for) the pictures on the first call. fn planes(&self) -> Result<&[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]> { if let Some(bufs) = self.bufs.get() { return Ok(bufs); } let pics = match &self.src { RefSrc::Ready(refs) => *refs, RefSrc::Lazy(wait) => wait()?, }; let dims = self.dims; let bufs = std::array::from_fn(|i| { dims[i].and(pics[i]).map(|g| { ( whole_plane(&g.y, g.width, g.height), whole_plane(&g.u, g.width / 2, g.height / 2), whole_plane(&g.v, g.width / 2, g.height / 2), ) }) }); let _ = self.bufs.set(bufs); Ok(self.bufs.get().expect("the plane array was just set")) } } /// This slot's picture SIZE, with [`ref_planes`]' own error when the slot /// carries no usable picture -- `dims` is `None` exactly when `planes()` /// would have nothing there, so the parse thread keeps refusing the same /// streams at the same block WITHOUT waiting for a producer's pixels /// (lane-defer8). fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> { refpix.dims(ref_frame).ok_or_else(|| { unsupported( "a reference frame selected with no picture at this frame's own \ ref_frame_idx slot for it", ) }) } /// [`ref_planes`] from inside a DEFERRED prediction, where there is no `?` /// to take: the error is parked on the [`RefPix`] and taken by the frame /// decoder once the workers are joined ([`RefPix::take_err`]). The block's /// prediction is left zeroed -- the frame is failing either way. fn ref_planes_deferred<'a, 'p>( ref_frame: i8, refpix: &'a RefPix<'p>, ) -> Option<(&'a PlaneBuf<'p>, &'a PlaneBuf<'p>, &'a PlaneBuf<'p>)> { match ref_planes(ref_frame, refpix) { Ok(planes) => Some(planes), Err(e) => { refpix.park_err(e); None } } } /// A whole reference plane as a [`PlaneBuf`]: no tile window, no margin. fn whole_plane(data: &[u16], width: usize, height: usize) -> PlaneBuf<'_> { PlaneBuf { data: std::borrow::Cow::Borrowed(data), width, height, true_width: width, true_height: height, tile_x0: 0, tile_y0: 0, tile_x1: width, tile_y1: height, } } /// Resolves a reference's own planes -- the `ref_frame -> picture` lookup /// [`decode_inter_block`]'s single-ref path does, factored out so the /// compound path can call it twice (lane-av1comp), and the point where /// lane-twostage's pixel wait happens. fn ref_planes<'a, 'p>( ref_frame: i8, refpix: &'a RefPix<'p>, ) -> Result<(&'a PlaneBuf<'p>, &'a PlaneBuf<'p>, &'a PlaneBuf<'p>)> { match refpix.planes()?.get(ref_frame as usize).and_then(Option::as_ref) { Some((y, u, v)) => Ok((y, u, v)), None => Err(unsupported( "a reference frame selected with no picture at this frame's own \ ref_frame_idx slot for it", )), } } /// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row /// directly above this block's own column span, one bordering block at a /// time (stepping by that neighbour's own `MiInfo::size`, which is always /// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting /// every *inter* neighbour found (an intra or unset cell is skipped, one mi /// unit at a time, and does not itself count as a step). `max_neighbors` /// caller-bounds the scan: `1` for the eligibility check (any hit at all), /// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the /// real blend pass. lane-intra16x4 r2: libaom's own "4-wide block, treat as /// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) IS /// ported below -- the round-1 note that no block is narrower than 8px stopped /// being true when the 1:4 partitions landed. A 16x4 / 4x16 strip has /// `mi_size_high`/`mi_size_wide` 1, so libaom snaps the walk back to the pair's /// even index, reads the ODD (chroma-carrying) half as the neighbour and steps /// by 2. Measured: the 16x16 block right of a 16x16-level HORZ_4 partition /// whose strip 0 is inter and strips 1..3 intra counted that inter strip as /// overlappable here, while libaom's pair merge reads the INTRA strip 1 and /// counts none -- so we read a `motion_mode` symbol libaom never wrote (class /// `symbol-consumption-gap`), desyncing the tile at the next coefficient. fn overlappable_above( grid: &MiGrid, mi_row: usize, mi_col: usize, bw4: usize, mi_cols: usize, max_neighbors: usize, ) -> Vec<(usize, usize, MiInfo, usize)> { // lane-alloc: bounded by `max_neighbors`, so size it once. let mut out = Vec::with_capacity(max_neighbors); if mi_row == 0 { return out; } let end_col = (mi_col + bw4).min(mi_cols); let mut col = mi_col; while col < end_col && out.len() < max_neighbors { let cell = grid.get(mi_row - 1, col); let mut step = cell.map_or(1, |c| c.size as usize).max(1).min(SB_MI as usize); let mut nb = cell; // lane-obmcrec r1: the mi the neighbour's `MiInfo` is actually taken // from -- the pair merge below moves it, and libaom reads that same // `mbmi`'s `interp_filters` (`av1_setup_build_prediction_by_above_pred`). let mut src = col; if step == 1 { // The pair merge: the walk snaps back to the pair's even column // and the ODD half (the chroma-carrying one) is the neighbour for // both -- a 4-wide 1:4 strip is never an OBMC source on its own. col &= !1; src = col + 1; nb = grid.get(mi_row - 1, src); step = 2; } if let Some(info) = nb { if info.is_inter { if src != col { hit!(OBMC_PAIR_FILTER_HITS); } // lane-t900 r14: libaom passes `AOMMIN(xd->width, mi_step)` // as `op_mi_size` -- the block's OWN width, never the // frame-edge clamp `end_col` carries. Clamping here shrank the // neighbour PREDICTION at a frame edge, which picks the // 4-tap kernel below 8 px (class narrow-block-sharp-kernel); // the destination clip stays in `obmc_blend`. out.push((col - mi_col, step.min(bw4), info, src - mi_col)); } } col += step; } out } /// `foreach_overlappable_nb_left`'s left-column mirror of /// [`overlappable_above`] -- see its doc for the shared corner-cut. fn overlappable_left( grid: &MiGrid, mi_row: usize, mi_col: usize, bh4: usize, mi_rows: usize, max_neighbors: usize, ) -> Vec<(usize, usize, MiInfo, usize)> { // lane-alloc: bounded by `max_neighbors`, so size it once. let mut out = Vec::with_capacity(max_neighbors); if mi_col == 0 { return out; } let end_row = (mi_row + bh4).min(mi_rows); let mut row = mi_row; while row < end_row && out.len() < max_neighbors { let cell = grid.get(row, mi_col - 1); // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's // width (8) would swallow the strip below it. let mut step = cell.map_or(1, |c| c.size_h as usize).max(1).min(SB_MI as usize); let mut nb = cell; // lane-obmcrec r1: see `overlappable_above`'s `src`. let mut src = row; if step == 1 { // The pair merge, left-column mirror: a 4-TALL neighbour (a 16x4 // strip) is half of a chroma pair and the pair's SECOND row is the // neighbour for both. row &= !1; src = row + 1; nb = grid.get(src, mi_col - 1); step = 2; } if let Some(info) = nb { if info.is_inter { if src != row { hit!(OBMC_PAIR_FILTER_HITS); } // lane-t900 r14: `AOMMIN(xd->height, mi_step)` -- see // `overlappable_above`. out.push((row - mi_row, step.min(bh4), info, src - mi_row)); } } row += step; } out } /// libaom `motion_mode_allowed`'s neighbour term: does ANY bordering inter /// block sit on this block's above row or left column ("check_num_overlappable /// _neighbors", `obmc.h`). The single source of truth for the DECODER's own /// `motion_mode_eligible` and for the tile WRITER's (`tile::write_motion_mode`) /// -- the two disagreeing by one block writes a `motion_mode` symbol the /// decoder never reads (class `symbol-consumption-gap`). pub(crate) fn has_overlappable_neighbour( grid: &MiGrid, mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, mi_cols: usize, mi_rows: usize, ) -> bool { !overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, 1).is_empty() || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, 1).is_empty() } /// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples` /// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2: /// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128` /// libaom's mask loop runs one level further and strips the top-right sample /// off blocks whose neighbour IS decoded, so a warped 128-superblock frame /// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates /// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is /// the block's own side in 4x4 (`mi`) units (square inter leaves only here). fn has_top_right(mi_row: usize, mi_col: usize, bs: usize, fctx: &crate::decode::FrameCtx) -> bool { crate::mvstack::has_top_right(mi_row, mi_col, bs, bs, fctx) } /// `av1_findSamples` (`mvref_common.c`), full port: the up to /// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour /// samples (`record_samples`) that share this block's own single reference /// frame and are themselves single-ref -- `mbmi->num_proj_ref` is /// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units /// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in /// libaom are also mi units of that same square side here). Each sample's /// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula) /// come from the *neighbour* cell's own coded size, not this block's. #[allow(clippy::too_many_arguments)] pub(crate) fn find_samples( grid: &MiGrid, mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, mi_cols: usize, mi_rows: usize, ref_frame: i8, fctx: &crate::decode::FrameCtx, ) -> Vec { const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX; let up_available = mi_row > 0; let left_available = mi_col > 0; let mut samples = Vec::with_capacity(MAX); // lane-t900 r9: `EC_PROJ_MI=,` lists this block's warp // sample candidates in libaom's own order (above, left, top-left, // top-right) -- `num_proj_ref >= 1` is what picks the 3-symbol // motion_mode alphabet over the 2-symbol obmc one. // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on // every warp block; the flag itself is a process constant. let proj_dbg = crate::envflags::env_flag!("EC_PROJ_MI") && crate::envflags::var("EC_PROJ_MI") .is_ok_and(|v| v == format!("{mi_row},{mi_col}")); let single_ref_match = |info: &MiInfo| { let m = info.ref_frame == ref_frame && info.ref_frame1 == NO_REF1; if proj_dbg { eprintln!( "EC_PROJ cand ref={} ref1={:?} size={} size_h={} is_inter={} want={ref_frame} match={m}", info.ref_frame, info.ref_frame1, info.size, info.size_h, info.is_inter ); } m }; let mut do_tl = true; let mut do_tr = true; let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| { let nb_bw = (info.size * 4) as i32; // lane-rect r2: the neighbour's own true height -- a rect strip // neighbour donates its sample at ITS center (aom pts y=-72 for a // 32x16 above strip; the square assumption put it at -136). let nb_bh = (info.size_h * 4) as i32; crate::warp::record_sample(nb_bw, nb_bh, mv32(info.mv), row_offset, sign_r, col_offset, sign_c) }; 'outer: { if up_available { let above = grid.get(mi_row - 1, mi_col); let superblock_width = above.map_or(1, |c| c.size as usize).max(1); if bw4 <= superblock_width { let col_offset = -((mi_col % superblock_width) as isize); if col_offset < 0 { do_tl = false; } if col_offset + superblock_width as isize > bw4 as isize { do_tr = false; } if let Some(info) = above { if single_ref_match(&info) { samples.push(rec(&info, 0, -1, col_offset as i32, 1)); if samples.len() >= MAX { break 'outer; } } } } else { let mut i = 0usize; let limit = bw4.min(mi_cols.saturating_sub(mi_col)); while i < limit { let cell = grid.get(mi_row - 1, mi_col + i); let sw = cell.map_or(1, |c| c.size as usize).max(1); if let Some(info) = cell { if single_ref_match(&info) { samples.push(rec(&info, 0, -1, i as i32, 1)); if samples.len() >= MAX { break 'outer; } } } i += sw; } } } if left_available { let left = grid.get(mi_row, mi_col - 1); let superblock_height = left.map_or(1, |c| c.size_h as usize).max(1); if bh4 <= superblock_height { let row_offset = -((mi_row % superblock_height) as isize); if row_offset < 0 { do_tl = false; } if let Some(info) = left { if single_ref_match(&info) { samples.push(rec(&info, row_offset as i32, 1, 0, -1)); if samples.len() >= MAX { break 'outer; } } } } else { let mut i = 0usize; let limit = bh4.min(mi_rows.saturating_sub(mi_row)); while i < limit { let cell = grid.get(mi_row + i, mi_col - 1); let sh = cell.map_or(1, |c| c.size_h as usize).max(1); if let Some(info) = cell { if single_ref_match(&info) { samples.push(rec(&info, i as i32, 1, 0, -1)); if samples.len() >= MAX { break 'outer; } } } i += sh; } } } if do_tl && left_available && up_available { if let Some(info) = grid.get(mi_row - 1, mi_col - 1) { if single_ref_match(&info) { samples.push(rec(&info, 0, -1, 0, -1)); if samples.len() >= MAX { break 'outer; } } } } // lane-t900 r9: libaom passes `AOMMAX(xd->width, xd->height)` here // (`mvref_common.c:1235`), NOT the block's width -- a rect block's // top-right reach is probed at its LONGER side. With `bw4` a 64x128 // block found a top-right sample libaom never sees, so // `num_proj_ref >= 1` picked the 3-symbol `motion_mode_cdf` where // libaom reads the 2-symbol `obmc_cdf` (class // wrong-alphabet-same-value). let tr_reach = crate::mvstack::has_top_right(mi_row, mi_col, bw4, bh4, fctx); if do_tr && bw4 != bh4 && tr_reach != has_top_right(mi_row, mi_col, bw4, fctx) { hit!(TR_REACH_LONGER_SIDE_HITS); } if do_tr && tr_reach { let tr_col = mi_col + bw4; if mi_row > 0 && tr_col < mi_cols { if let Some(info) = grid.get(mi_row - 1, tr_col) { if single_ref_match(&info) { samples.push(rec(&info, 0, -1, bw4 as i32, 1)); } } } } } samples } /// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that /// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over /// the 2-symbol `obmc_cdf` (spec 5.11.24). #[allow(clippy::too_many_arguments)] pub(crate) fn num_proj_ref( grid: &MiGrid, mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, mi_cols: usize, mi_rows: usize, ref_frame: i8, fctx: &crate::decode::FrameCtx, ) -> u8 { find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx).len() as u8 } /// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight /// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own /// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr + /// 32) >> 6`, low near the shared border (heavier neighbour weight) rising /// to 64 (no neighbour contribution) away from it. Only the lengths this /// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16) /// are transcribed. fn obmc_mask(len: usize) -> &'static [u8] { // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c` // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so // its overlap is 2 (and 1 at a half-block edge). Unreachable until this // round wired interior 16x16 splits down to real 8x8 leaves, where the // old `unreachable!()` below fired as a hard panic. const M1: [u8; 1] = [64]; // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2 // chroma), which only became live once 8x8 inter leaves stopped being // refused. const M2: [u8; 2] = [45, 64]; const M4: [u8; 4] = [39, 50, 59, 64]; const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64]; const M16: [u8; 16] = [ 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64, ]; const M32: [u8; 32] = [ 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60, 61, 62, 64, 64, 64, 64, 64, 64, 64, 64, ]; match len { 1 => &M1, 2 => &M2, 4 => &M4, 8 => &M8, 16 => &M16, 32 => &M32, _ => unreachable!("obmc overlap length outside this decoder's own block-size range"), } } /// A bordering block's own resolved interp filter kernel, `(h, v)` -- /// mirrors [`resolve_interp_filter`]'s own return order from its stored /// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` = /// `[v_sym, h_sym]`). The `[3, 3]` sentinel is only ever stored for an intra /// neighbour (excluded by [`overlappable_above`]/[`overlappable_left`]'s /// `is_inter` gate) or when `interp_fixed` is `Some` for the whole frame /// (handled here first) -- so a sentinel reaching the kernel lookup means the /// stream desynced upstream, and this refuses instead of panicking. fn neighbour_filter( interp_fixed: Option, sym: [u8; 2], ) -> Result<(mc::InterpFilterKind, mc::InterpFilterKind)> { if let Some(kind) = interp_fixed { return Ok((kind, kind)); } // lane-golomb r9: this used to hand the sentinel straight to // `from_switchable_symbol`, which PANICS on any value above 2 -- a crash // on stream data (measured on a real 192x68 cq40 aomenc stream, where an // inter leaf below 8x8 desyncs upstream and leaves an unrecorded filter // behind). A decoder must refuse such a stream by name, never abort the // process; the desync that produces the sentinel belongs to lane-intersub8. if sym[0] > 2 || sym[1] > 2 { return Err(unsupported( "an OBMC neighbour whose switchable interp filter was never recorded", )); } hit!(OBMC_FILTER_BAND_READS); Ok(( mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize), mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize), )) } /// lane-obmcrec r1 MEASUREMENT rung (`EC_OBMCREC=1`): every OBMC neighbour whose /// recorded switchable-filter symbols are the `[3, 3]` "never recorded" sentinel /// -- names the neighbour's own position/shape/reference so the decode path that /// failed to record its filter can be identified. Read-only, off by default. #[allow(clippy::too_many_arguments)] fn obmcrec_probe( dir: &str, mi_row: usize, mi_col: usize, write_w: usize, write_h: usize, off4: usize, span4: usize, nb: &MiInfo, syms: [u8; 2], cell: Option, fixed: bool, ) { if (syms[0] <= 2 && syms[1] <= 2) || !crate::envflags::env_flag!("EC_OBMCREC") { return; } eprintln!( "OBMCREC {dir} cur_mi=({mi_row},{mi_col}) cur_wh=({write_w}x{write_h}) off4={off4} \ span4={span4} syms={syms:?} fixed={fixed} nb_size=({}x{}) nb_ref={} nb_ref1={:?} nb_mv=({},{}) \ nb_newmv={} cell_size={:?} cell_inter={:?} cell_ref={:?} sb_row_off={} sb_col_off={}", nb.size * 4, nb.size_h * 4, nb.ref_frame, nb.ref_frame1, nb.mv.0, nb.mv.1, nb.is_new_mv, cell.map(|c| (c.size * 4, c.size_h * 4)), cell.map(|c| c.is_inter), cell.map(|c| c.ref_frame), mi_row % 32, mi_col % 32, ); } /// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh /// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor` /// under `av1_setup_build_prediction_by_{above,left}_pred`). #[allow(clippy::too_many_arguments)] fn obmc_neighbour_pred( refplane: &PlaneBuf<'_>, x: usize, y: usize, mv: (i32, i32), w: usize, h: usize, luma: bool, h_kind: mc::InterpFilterKind, v_kind: mc::InterpFilterKind, // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own // reference (derived from luma widths, applied unchanged to chroma whose // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes // the ordinary stride-1 path bit-exact. x_scale_fp: i64, // lane-alloc: the caller keeps one buffer per plane and reuses it across // every neighbour of both passes -- this was a fresh `vec![0u16; w * h]` // per neighbour per plane. out: &mut Vec, fctx: &crate::decode::FrameCtx, ) { out.clear(); out.resize(w * h, 0); if x_scale_fp == mc::REF_NO_SCALE { mc::predict_with_filters( &refplane.data, refplane.width, refplane.true_width, refplane.true_height, mv_to_q4(x, mv.1, luma), mv_to_q4(y, mv.0, luma), w, h, h_kind, v_kind, out, fctx, ); } else { mc::predict_scaled( &refplane.data, refplane.width, refplane.true_width, refplane.true_height, mv_to_q4(x, mv.1, luma), mv_to_q4(y, mv.0, luma), x_scale_fp, w, h, h_kind, v_kind, out, fctx, ); } } /// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by /// row (the above-neighbour pass, `aom_blend_a64_vmask`). /// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff. const II_WEIGHTS_1D: [u8; 128] = [ 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16, 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ]; /// lane-interintra r1: non-wedge interintra prediction for one plane /// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` + /// `build_smooth_interintra_mask`). Builds the intra predictor for the /// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s /// own decoded edges at `(x, y)`, then blends it over the inter prediction /// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6` /// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]` /// reduces to `128 / side` for the square plane sizes this decoder reaches. /// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge /// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma). fn interintra_blend( plane: &PlaneBuf<'_>, x: usize, y: usize, bw: usize, bh: usize, stride: usize, ii_mode: u8, wedge: Option<(&'static [u8], usize)>, pred: &mut [u16], fctx: &crate::decode::FrameCtx, ) { // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH. let intra_mode = match ii_mode { 0 => crate::intra::DC_PRED, 1 => crate::intra::V_PRED, 2 => crate::intra::H_PRED, _ => crate::intra::SMOOTH_PRED, }; let (above, left, corner) = plane.edges_rect( x, y, bw, bh, crate::encode::Reach { above_right: false, below_left: false, }, ); let mut intra = vec![0u16; bw * bh]; // Edge filtering never applies here: V/H at delta 0 are plain edge // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no // angle at all. predict( intra_mode, 0, above.as_deref(), left.as_deref(), corner, bw, bh, false, false, &mut intra, fctx, ); // `ii_size_scales[bsize]` is keyed on the block's LONGER side // (`MAX_SB_SIZE >> max(bw,bh)` order), not on the square this decoder // builds the predictor buffer at. let scale = 128 / bw.max(bh); for i in 0..bh { for j in 0..bw { let m = u32::from(match wedge { // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask // over the wedge codebook, intra as src0, fixed sign 0). // Luma plane: mask rows are luma-resolution, ms == side. // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 -- // subw == subh == 1). Some((mask, ms)) if ms == stride => mask[i * stride + j], Some((mask, ms)) => { let t = 2 * i * ms + 2 * j; ((u32::from(mask[t]) + u32::from(mask[t + 1]) + u32::from(mask[t + ms]) + u32::from(mask[t + ms + 1]) + 2) >> 2) as u8 } None => match ii_mode { 0 => 32, 1 => II_WEIGHTS_1D[i * scale], 2 => II_WEIGHTS_1D[j * scale], _ => II_WEIGHTS_1D[i.min(j) * scale], }, }); let idx = i * stride + j; pred[idx] = ((m * u32::from(intra[i * bw + j]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u16; } } } /// `w` is the number of columns actually written (clipped to the block's own /// buffer at a frame edge); `ts` is `tmp`'s own stride, the neighbour /// prediction's full width. #[allow(clippy::too_many_arguments)] fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, ts: usize, tmp: &[u16]) { let mask = obmc_mask(h); for row in 0..h { let m = u32::from(mask[row]); for col in 0..w { let d = &mut dst[(oy + row) * stride + ox + col]; let t = u32::from(tmp[row * ts + col]); *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16; } } } /// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the /// left-neighbour pass, `aom_blend_a64_hmask`). fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) { let mask = obmc_mask(w); for row in 0..h { for col in 0..w { let m = u32::from(mask[col]); let d = &mut dst[(oy + row) * stride + ox + col]; let t = u32::from(tmp[row * w + col]); *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16; } } } /// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block -- /// only for the `EC_OBMC` trace rung below, so it reads byte-identical to /// the instrumented aomdec's `backup_mbmi.bsize`. fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 { match (w4, h4) { (1, 1) => 0, (1, 2) => 1, (2, 1) => 2, (2, 2) => 3, (2, 4) => 4, (4, 2) => 5, (4, 4) => 6, (4, 8) => 7, (8, 4) => 8, (8, 8) => 9, (8, 16) => 10, (16, 8) => 11, (16, 16) => 12, (1, 4) => 16, (4, 1) => 17, (2, 8) => 18, (8, 2) => 19, (4, 16) => 20, (16, 4) => 21, _ => -1, } } /// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented /// aomdec's own byte format (`decodeframe.c` /// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC /// neighbour lists diff line for line. `filt` is libaom's packed /// `interp_filters.as_int` = `y_filter | (x_filter << 16)`. #[allow(clippy::too_many_arguments)] fn ec_obmc_trace( dir: &str, mi_row: usize, mi_col: usize, write_w: usize, write_h: usize, rel: usize, op: usize, nb: &MiInfo, h_kind: mc::InterpFilterKind, v_kind: mc::InterpFilterKind, ) { if !crate::envflags::env_flag!("EC_OBMC") { return; } let sym = |k: mc::InterpFilterKind| match k { mc::InterpFilterKind::Smooth => 1u32, mc::InterpFilterKind::Sharp => 2, _ => 0, }; eprintln!( "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \ nbmv=({},{}) nbref={} nbbsize={} filt={}", nb.mv.0, nb.mv.1, nb.ref_frame, ec_obmc_bsize(nb.size as usize, nb.size_h as usize), sym(v_kind) | (sym(h_kind) << 16), ); } /// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts /// the overlap strip against each bordering above/left inter neighbour's own /// mv/ref/filter and blends it into this block's just-built single-reference /// prediction, luma then both 4:2:0 chroma planes -- above pass first, then /// left, each reading only the *original* prediction this function was /// handed (never the other pass's own output), matching libaom's own /// independence between the two. `max_neighbor_obmc`'s own cap table /// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this /// decoder's own square blocks always index the same value both ways) bounds /// how many bordering blocks actually get blended, separate from the /// eligibility scan's own unbounded ("any at all") walk. #[allow(clippy::too_many_arguments)] pub(crate) fn obmc_plan( grid: &MiGrid, // The two switchable-filter bands (`Neighbours::above_filter`/ // `left_filter`), read only when `interp_fixed` is `None`. The ENCODER // (`encode.rs`'s OBMC candidate) codes a fixed interpolation filter and // has no `Neighbours` of its own, so it passes both empty; the reads // below fall back to the `[3, 3]` never-recorded sentinel, which // `neighbour_filter` never reaches under a fixed filter. // corner-cut: ceiling is a switchable-filter ENCODER -- it must build and // pass the real bands here, exactly as the decoder does. above_filter: &[[u8; 2]], left_filter: &[[u8; 2]], mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, mi_rows: usize, mi_cols: usize, side: usize, write_w: usize, write_h: usize, chroma_side: usize, px: usize, py: usize, cpx: usize, cpy: usize, refpix: &RefPix<'_>, interp_fixed: Option, // lane-scaledref r1: this frame's own coded luma width -- each OBMC // neighbour is re-predicted against ITS OWN reference, which may be // scaled differently from this block's (spec 7.11.3.3 / libaom // `av1_setup_build_prediction_by_above_pred` passing that ref's own // `scale_factors`). frame_width: usize, ) -> Result { // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has // its OWN neighbour cap (width-log2 for above, height-log2 for left) and // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was // right only for square blocks. // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left): // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old // `1..=4 => 2` row was right only for blocks at least 16 px on that axis // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where // libaom walks one, blending an extra 8-px-tall neighbour into every // rect leaf with two of them on its left edge (class table-narrowed-to- // the-reachable-sizes; the square gates could never expose it). let max_nb = |n4: usize| match n4 { 0..=1 => 0, 2 => 1, 3..=4 => 2, 5..=8 => 3, _ => 4, }; // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf; re-measured // byte-exact against an instrumented aomdec, the refusal is gone and the // counter below is what the gate's `--enable-obmc=1` arm reads. if matches!((write_w, write_h), (16, 8) | (8, 16)) { hit!(OBMC_RECT_LEAF_HITS); } // lane-sb128c r1: libaom caps the overlap strip at a 64x64 block's own // half (`reconinter.c` 860/899), inert below 128. let overlap_above = write_h.min(64) / 2; let overlap_left = write_w.min(64) / 2; // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc` // (`reconinter.c` 820) returns `dir == 0` when the chroma plane's own // block is BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): // the ABOVE pass skips chroma entirely, the LEFT pass still blends it. let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16)); let mut above = Vec::new(); for (off4, span4, nb, src4) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4)) { // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns, // one step coarser than the mi(4px) units `overlappable_above` walks // in -- divide back down to that column. lane-gmaffine r2: the // neighbour's OWN mi-granular filter (libaom // `av1_setup_build_prediction_by_above_pred` reads // `above_mbmi->interp_filters`). let above_syms = above_filter.get(mi_col + src4).copied().unwrap_or([3; 2]); obmcrec_probe( "above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, above_syms, grid.get(mi_row - 1, mi_col + src4), interp_fixed.is_some(), ); let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?; ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind); let (nb_width, _) = ref_dims(nb.ref_frame, refpix)?; if mi_col + off4 + span4 > mi_cols { hit!(OBMC_EDGE_SPAN_HITS); } above.push(ObmcNb { off4, span4, mv: mv32(nb.mv), ref_frame: nb.ref_frame, h_kind, v_kind, scale: mc::scale_factor(nb_width, frame_width), }); } let mut left = Vec::new(); for (off4, span4, nb, src4) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) { let left_syms = left_filter.get(mi_row + src4).copied().unwrap_or([3; 2]); obmcrec_probe( "left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, left_syms, grid.get(mi_row + src4, mi_col - 1), interp_fixed.is_some(), ); let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?; ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind); let (nb_width, _) = ref_dims(nb.ref_frame, refpix)?; if mi_row + off4 + span4 > mi_rows { hit!(OBMC_EDGE_SPAN_HITS); } left.push(ObmcNb { off4, span4, mv: mv32(nb.mv), ref_frame: nb.ref_frame, h_kind, v_kind, scale: mc::scale_factor(nb_width, frame_width), }); } Ok(ObmcPlan { above, left, side, chroma_side, write_w, write_h, px, py, cpx, cpy, overlap_above, overlap_left, skip_chroma_above, }) } /// One OBMC neighbour as the PARSE thread resolved it (lane-defer8): every /// value [`obmc_run`] needs that lives in the mode-info grid or the /// neighbour bands, which the parse keeps overwriting as it walks on. struct ObmcNb { off4: usize, span4: usize, mv: (i32, i32), ref_frame: i8, h_kind: mc::InterpFilterKind, v_kind: mc::InterpFilterKind, /// spec 7.11.3.3's `x_scale_fp` for THIS neighbour's own reference. scale: i64, } /// [`obmc_plan`]'s result: the two neighbour passes plus this block's own /// geometry, everything [`obmc_run`] reads apart from reference PIXELS. pub(crate) struct ObmcPlan { above: Vec, left: Vec, side: usize, chroma_side: usize, write_w: usize, write_h: usize, px: usize, py: usize, cpx: usize, cpy: usize, overlap_above: usize, overlap_left: usize, skip_chroma_above: bool, } /// The reference-pixel half of OBMC: re-predicts every planned neighbour /// over this block's own edge strips and blends it into the prediction /// (libaom `av1_build_obmc_inter_prediction`). Reads nothing but reference /// pixels and the plan, so it runs wherever the block's prediction is built /// -- on a recon worker when that prediction is deferred (lane-defer8). pub(crate) fn obmc_run( plan: &ObmcPlan, refpix: &RefPix<'_>, pred_y: &mut [u16], pred_u: &mut [u16], pred_v: &mut [u16], fctx: &crate::decode::FrameCtx, ) { let &ObmcPlan { side, chroma_side, write_w, write_h, px, py, cpx, cpy, overlap_above, overlap_left, skip_chroma_above, .. } = plan; // lane-alloc: one neighbour-prediction buffer per plane for the whole // block, reused by every neighbour of the above and left passes. let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new()); // lane-t900 r13 rung: EC_MCB="::[:]" (chroma plane // 1 only) prints this block's chroma prediction rows before and after the // OBMC blend, matching the instrumented aomdec's EC_MCB dump. let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::env_flag!("EC_MCB") .then(|| crate::envflags::var("EC_MCB").ok()) .flatten() .and_then(|v| { let f: Vec<&str> = v.split(':').collect(); if f.len() < 3 || f[0] != "1" { return None; } let (x, y) = (f[1].parse::().ok()?, f[2].parse::().ok()?); let fr = f.get(3).and_then(|s| s.parse::().ok()).unwrap_or(-1); let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) as i64; if x >= cpx && x < cpx + write_w / 2 && y >= cpy && y < cpy + write_h / 2 && (fr < 0 || fr == idx) { Some((x, y, idx)) } else { None } }); if let Some((_, _, idx)) = ec_mcb { eprintln!( "OUR_MCB pre f={idx} cpx={cpx} cpy={cpy} cw={} ch={}", write_w / 2, write_h / 2 ); for r in 0..write_h / 2 { let row: Vec = (0..write_w / 2).map(|c| pred_u[r * chroma_side + c]).collect(); eprintln!("OUR_MCB prerow{r}: {row:?}"); } } for nb in &plan.above { let Some((ny, nu, nv)) = ref_planes_deferred(nb.ref_frame, refpix) else { return; }; let (bw, bh, ox) = (nb.span4 * 4, overlap_above, nb.off4 * 4); // lane-t900 r14: the prediction is `op_mi_size` wide (kernel choice // included); only the WRITE is clipped to this block's own buffer. obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, nb.h_kind, nb.v_kind, nb.scale, &mut tmp_y, fctx); obmc_blend_v(pred_y, side, ox, 0, bw.min(write_w - ox), bh, bw, &tmp_y); if !skip_chroma_above { // lane-t900 r13 (measured, NOT a defect): libaom's min-4 clamp // sizes only the OBMC PREDICTION buffer; the blend length is the // plain half (`build_obmc_inter_pred_above`: `overlap >> ss_y`). let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2); let cw = cbw.min(write_w / 2 - cox); obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, nb.h_kind, nb.v_kind, nb.scale, &mut tmp_u, fctx); obmc_blend_v(pred_u, chroma_side, cox, 0, cw, cbh, cbw, &tmp_u); obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, nb.h_kind, nb.v_kind, nb.scale, &mut tmp_v, fctx); obmc_blend_v(pred_v, chroma_side, cox, 0, cw, cbh, cbw, &tmp_v); } } for nb in &plan.left { let Some((ny, nu, nv)) = ref_planes_deferred(nb.ref_frame, refpix) else { return; }; let (bw, bh, oy) = (overlap_left, nb.span4 * 4, nb.off4 * 4); obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, nb.h_kind, nb.v_kind, nb.scale, &mut tmp_y, fctx); obmc_blend_h(pred_y, side, 0, oy, bw, bh.min(write_h - oy), &tmp_y); let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2); obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, nb.h_kind, nb.v_kind, nb.scale, &mut tmp_u, fctx); if let Some((_, _, idx)) = ec_mcb { eprintln!( "OUR_MCB left f={idx} off4={} span4={} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}", nb.off4, nb.span4, nb.mv.0, nb.mv.1, nb.ref_frame ); for r in 0..cbh { let row: Vec = (0..cbw).map(|c| tmp_u[r * cbw + c]).collect(); eprintln!("OUR_MCB lrow{r}: {row:?}"); } } let ch = cbh.min(write_h / 2 - coy); obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, ch, &tmp_u); obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, nb.h_kind, nb.v_kind, nb.scale, &mut tmp_v, fctx); obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, ch, &tmp_v); } if let Some((_, _, idx)) = ec_mcb { for r in 0..write_h / 2 { let row: Vec = (0..write_w / 2).map(|c| pred_u[r * chroma_side + c]).collect(); eprintln!("OUR_MCB post f={idx} row{r}: {row:?}"); } } } /// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to /// the square block sizes this decoder ever decodes (32/16/8, all /// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then /// always `is_interinter_compound_used`, so the function is always `true` /// for `side` -- kept as a named call (rather than inlined `true`) so a /// future sub-8 block size does not silently misdecode a real stream. fn is_any_masked_compound_used_here(bw: usize, bh: usize) -> bool { // lane-inter16ab r4 (class sweep of the r3 CDF-row defect): // `is_comp_ref_allowed(bsize)` is `AOMMIN(block_size_wide, block_size_high) // >= 8` on the block's TRUE footprint -- a 16x4/4x16 strip is NOT allowed, // so libaom writes no `comp_group_idx` symbol there at all. Keyed off the // square `side` we read one the reference never wrote. bw.min(bh) >= 8 } /// The `BLOCK_SIZES_ALL` index of a `bw x bh` block (libaom `enum BLOCK_SIZE`, /// `blockd.h`) -- the row every size-indexed inter CDF table /// (`compound_type_cdf`, `wedge_idx_cdf`) is keyed by. Our `decode_inter_block` /// carries the enclosing SQUARE `side` for context purposes (the accepted /// strip corner-cut), so a 16x8 / 8x16 PARTITION_HORZ/VERT strip that reads /// one of those symbols off `side` alone takes BLOCK_16X16's row and desyncs /// (lane-inter16ab r3: a real 16x8 compound strip with `comp_group_idx == 1`, /// decode-order frame 5, our range 64901 vs the oracle's 47271 at the very /// next block's mode read). fn bsize_all_index(bw: usize, bh: usize) -> Option { Some(match (bw, bh) { (4, 4) => 0, (4, 8) => 1, (8, 4) => 2, (8, 8) => 3, (8, 16) => 4, (16, 8) => 5, (16, 16) => 6, (16, 32) => 7, (32, 16) => 8, (32, 32) => 9, (32, 64) => 10, (64, 32) => 11, (64, 64) => 12, (64, 128) => 13, (128, 64) => 14, (128, 128) => 15, (4, 16) => 16, (16, 4) => 17, (8, 32) => 18, (32, 8) => 19, (16, 64) => 20, (64, 16) => 21, _ => return None, }) } /// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`): /// the block sizes that carry a wedge codebook at all. A `compound_type` /// symbol is written only for these; every other size infers /// `COMPOUND_DIFFWTD`. fn wedge_used_bsize(bw: usize, bh: usize) -> bool { matches!( (bw, bh), (8, 8) | (8, 16) | (16, 8) | (16, 16) | (16, 32) | (32, 16) | (32, 32) | (8, 32) | (32, 8) ) } /// Whether a compound reference pair is unidirectional (both references on /// the same temporal side of the current frame) -- `has_uni_comp_refs` /// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition: /// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is /// backward-while-the-other-is-forward, i.e. `is_backward(ref0) == /// is_backward(ref1)`). Used to build a real /// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching /// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls. fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool { let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r); backward(ref0) == backward(ref1) } /// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the /// above/left neighbour contributions [`Neighbours::record_inter`]/ /// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5. /// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units -- /// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four /// leaves read the same neighbour cell (class context-read-from-one-cell). fn get_comp_group_idx_context( neighbours: &Neighbours, at_mi: (usize, usize), side: usize, ) -> usize { let _ = side; let (rmi, cmi) = at_mi; (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize) .min(5) } /// `get_comp_index_context` (libaom `pred_common.h`): the above/left /// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this /// block's own two references' distances from the current frame (spec /// 7.11.3.15's `get_relative_dist`, same convention /// [`crate::compound::dist_wtd_comp_weight_assign`] uses). #[allow(clippy::too_many_arguments)] fn get_comp_index_context( neighbours: &Neighbours, at_mi: (usize, usize), side: usize, order_hint_bits: u32, cur_order_hint: u32, ref0_order_hint: u32, ref1_order_hint: u32, ) -> usize { let _ = side; let (rmi, cmi) = at_mi; let fwd = crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint) .abs(); let bck = crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint) .abs(); let offset = usize::from(fwd == bck); neighbours.above_compound_idx[cmi] as usize + neighbours.left_compound_idx[rmi] as usize + 3 * offset } fn read_comp_mode( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above: Option, left: Option, ) -> bool { let ctx = reference_mode_ctx(above, left); let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1; if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_RCM ctx={ctx} val={} a={:?} l={:?} rng={}", usize::from(compound), above.map(|n| (n.is_inter, n.ref0, n.ref1)), left.map(|n| (n.is_inter, n.ref0, n.ref1)), dec.debug_state().0 ); } if compound { hit!(COMP_MODE_HITS); } compound } /// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/ /// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound /// arm), reached once [`read_comp_mode`] has already returned /// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`. /// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef` /// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1` /// convention [`read_single_ref`] already uses, for every downstream binary /// decision. libaom `pred_common.c`'s own compound context functions /// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`, /// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`].. /// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name /// (same vote-the-neighbours-above-left shape, same forward/backward and /// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one /// against the C source rather than porting six near-duplicate functions. /// Its caller today only needs the symbols consumed, correctly, to keep the /// arithmetic decoder's own state in sync before refusing the block by name /// -- the returned pair is not yet threaded into any motion-compensation /// path. fn read_compound_ref_frames( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above: Option, left: Option, above_ref: i8, left_ref: i8, ) -> (i8, i8) { let a = (above_ref > 0).then_some(above_ref); let l = (left_ref > 0).then_some(left_ref); // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound // neighbour's references, not just its first -- `a1`/`l1` carry that // second reference through to every vote below (lane-av1blend r6: a // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF // row for a block sitting under a skip_mode-forced compound neighbour). let a1 = above.and_then(|n| n.ref1); let l1 = left.and_then(|n| n.ref1); let type_ctx = comp_reference_type_ctx(above, left); let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0; if unidir { hit!(UNI_COMP_HITS); // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_- // uni_comp_ref_p is single_ref_p1's own forward/backward vote. let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]); if bit == 1 { (BWDREF_FRAME, ALTREF_FRAME) } else { let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]); if p1 == 1 { // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5. let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]); if p2 == 1 { (LAST_FRAME, GOLDEN_FRAME) } else { (LAST_FRAME, LAST3_FRAME) } } else { (LAST_FRAME, LAST2_FRAME) } } } else { // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3. let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]); let ref0 = if bit0 == 0 { // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4. let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]); if p1 == 1 { LAST2_FRAME } else { LAST_FRAME } } else { // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5. let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]); if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME } }; // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2. let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]); let ref1 = if bit1 == 0 { // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6. let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]); if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME } } else { ALTREF_FRAME }; (ref0, ref1) } } /// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight /// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as /// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once /// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is /// libaom's `av1_mode_context_analyzer`'s compound branch -- /// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS /// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack:: /// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol /// is not yet turned into an assigned MV pair or motion-compensated -- /// lane-av1comp. fn read_inter_compound_mode( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, new_mv_ctx: usize, ref_mv_ctx: usize, ) -> u8 { let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)]; hit!(COMPOUND_MODE_HITS); dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8 } /// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of /// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is /// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`.. /// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads /// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any /// non-`IDENTITY` global motion model before a tile is ever decoded. /// /// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the /// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its /// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV` /// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching /// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode". fn assign_compound_mv( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, comp_stack: &crate::mvstack::CompoundMvStack, mode: u8, allow_high_precision_mv: bool, force_integer_mv: bool, // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment. global_mv: ((i32, i32), (i32, i32)), ) -> ((i32, i32), (i32, i32)) { const NEAREST_NEARESTMV: u8 = 0; const NEAR_NEARMV: u8 = 1; const NEAREST_NEWMV: u8 = 2; const NEW_NEARESTMV: u8 = 3; const NEAR_NEWMV: u8 = 4; const NEW_NEARMV: u8 = 5; const GLOBAL_GLOBALMV: u8 = 6; const NEW_NEWMV: u8 = 7; let mut ref_mv_idx = 0usize; if mode == NEW_NEWMV { let mut idx = 0usize; while idx < 2 && comp_stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } ref_mv_idx = idx; } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) { let mut idx = 1usize; while idx < 3 && comp_stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } ref_mv_idx = idx - 1; } let near = comp_stack .entries .get(ref_mv_idx + 1) .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1)); let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) { ref_mv_idx + 1 } else { ref_mv_idx }; let new_pred = comp_stack .entries .get(new_idx) .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1)); let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| { read_mv( dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, base, allow_high_precision_mv, force_integer_mv, ) }; match mode { NEAREST_NEARESTMV => comp_stack.nearest_mv, NEAR_NEARMV => near, NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)), NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1), NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)), NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1), GLOBAL_GLOBALMV => global_mv, _ => ( read_new(dec, cdfs, new_pred.0), read_new(dec, cdfs, new_pred.1), ), } } /// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one /// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at /// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the /// table is always computed at the *querying* block's position, never a /// donating neighbour's). fn build_gm_mv_table( global_motion: &[ec_av1_syntax::WarpParams; 7], mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, allow_high_precision_mv: bool, force_integer_mv: bool, ) -> crate::mvstack::GmMvTable { std::array::from_fn(|i| { let gm = &global_motion[i]; crate::warp::gm_get_motion_vector( gm.model, &gm.params, mi_row, mi_col, bw4, bh4, allow_high_precision_mv, force_integer_mv, ) }) } /// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip, /// `is_inter`, then either the single-reference/MV-stack/motion-vector chain /// and motion-compensated reconstruction, or the inter frame's own intra /// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring /// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its /// private `write_inter_frame_leaf` -- both share this one function here, /// parameterised by `side`/the transform sets/scan tables/size group they /// each use. /// /// # Errors /// Returns an error when a symbol names anything this decoder does not /// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3; /// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra /// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already /// refuse. #[allow(clippy::too_many_arguments)] /// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit /// [`decode_inter_block`]'s `at` now takes. const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) { (t.0 * (SUB / MI), t.1 * (SUB / MI)) } fn decode_inter_block( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, grid: &mut MiGrid, at: (usize, usize), side: usize, mi_cols: u32, mi_rows: u32, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, refpix: &RefPix<'_>, // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]` // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME` // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the // slot's still empty (an error-resilient stream, or too early in the // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below. sign_bias_table: &SignBiasTable, // lane-gm r2: this frame header's own `global_motion` table (spec // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table` // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV` // assignment and the mv-stack's neighbour substitution. global_motion: &[ec_av1_syntax::WarpParams; 7], base_q_idx: u8, luma_set_intra: TxbSet, luma_set_inter: TxbSet, chroma_set: TxbSet, luma_tx: usize, chroma_tx: usize, scan_luma: &[u16], scan_chroma: &[u16], // lane-inter4 r3: superseded by `size_group_wh(write_w, write_h)` at the // one site that read it (`y_mode`) -- a rect strip's group comes from its // true footprint, not the caller's square `side`. Kept in the signature // rather than editing twenty call sites. _size_group: usize, allow_high_precision_mv: bool, force_integer_mv: bool, interp_fixed: Option, enable_dual_filter: bool, tpl_frame: Option<&TplFrameArgs>, // lane-av1comp: this frame header's own `reference_select` bit -- `false` // means every block is `SINGLE_REFERENCE` by construction and `comp_mode` // is never read (spec 5.11.25); `true` reads `comp_mode` per block and // refuses (rather than silently misdecoding) the ones that pick // `COMPOUND_REFERENCE`, since two-reference motion compensation is not // wired yet. reference_select: bool, // lane-av1comp: `seq_params`' own masked-compound/distance-weighted- // compound enable bits, gating `comp_group_idx`/`compound_idx` // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the // compound blend weights need this frame's own order hint regardless // of `use_ref_frame_mvs`. enable_masked_compound: bool, // lane-sb128 r4: this sequence header's own `enable_interintra_compound` // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c` // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv` // and before `read_motion_mode` on the single-ref path below, gated by // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and // every mode this single-ref branch can produce is already in // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal // (inter+intra blended prediction unimplemented) rather than a // mis-decode. enable_interintra_compound: bool, enable_jnt_comp: bool, order_hint_bits: u32, order_hint: u32, ref_order_hints: [u32; 7], // lane-av1comp round 14: this frame header's own `skip_mode_present` bit // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) -- // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip` // when this is `true` (every block this decoder reaches is >= 8x8, so // `is_comp_ref_allowed` never gates it further); a `true` result forces // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/ // DRL symbol read, and a plain average blend with no `comp_group_idx`/ // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509). skip_mode_present: bool, skip_mode_frame: [u8; 2], // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/ // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`). switchable_motion_mode: bool, allow_warped_motion: bool, // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded // as a square 32x32 block, which over-reads a residual unless coded // `skip`; a non-skip strip must refuse cleanly instead of desyncing. reject_residual: bool, // lane-partitions r1: the strip's own true width/height in pixels -- // `side` keeps governing every syntax/CDF/prediction-buffer decision // (matching `HORZ_B`'s already-accepted square-context corner-cut), but // the final pixel write and this block's own neighbour-context stamp // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a // PARTITION_HORZ/VERT strip only claims its own true footprint. `side` // for every existing (square) caller. write_w: usize, write_h: usize, // lane-screen r2: this frame header's own `allow_screen_content_tools` // bit, threaded to the intra-sub-block branch below -- libaom's // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf` // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on // `frame_is_intra_only`), but it still calls `read_palette_mode_info` // under the same `av1_allow_palette` gate as the key-frame path. allow_screen_content_tools: bool, // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) -- // compared against each reference's stored picture width to decide // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary // stride-1 one (`mc::predict_with_filters`) applies per reference, and to // refuse (rather than mis-decode) the warp/OBMC/interintra/compound // combinations that don't implement scaled MC yet. frame_width: usize, fctx: &crate::decode::FrameCtx, ) -> Result<()> { // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the // few 16-px-granular uses below. let (r, c) = (at.0 / (SUB / MI), at.1 / (SUB / MI)); // lane-inter8 r2: the inter side bands are mi-granular; this block's own // above/left neighbour is the mi cell at its top-left corner (libaom // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads // exactly what it read before. let (rmi, cmi) = at; let (px, py) = (at.1 * MI, at.0 * MI); census_inter_block_shape(side, write_w, write_h); // lane-inter16ab r2: a 16x4 / 4x16 inter strip's chroma is the PAIR's // (8x4 / 4x8 at the even strip's origin) and is coded only by the odd // strip (`is_chroma_reference`); every other block keeps its own. let strip_chroma = fctx.inter_strip_chroma.with(std::cell::Cell::take); fctx.inter_last_mc.with(|c| c.set(None)); let has_chroma = strip_chroma.is_none_or(|s| s.has_chroma); let (cpx, cpy) = match strip_chroma { Some(s) if s.has_chroma => (s.pair_mi.1 * MI / 2, s.pair_mi.0 * MI / 2), _ => (px / 2, py / 2), }; let chroma_side = side / 2; let (write_chroma_w, write_chroma_h) = match strip_chroma { Some(s) if s.has_chroma => { if s.horz { (8, 4) } else { (4, 8) } } _ => (write_w / 2, write_h / 2), }; // lane-midcut r3 (same rule as lane-t900 r5's `warp_plane_allowed`, one // copy kept at the merge): `av1_init_warp_params` (libaom reconinter.c) // bails per PLANE at `block_width < 8 || block_height < 8` -- on the // block's own dims, never on the square prediction buffer this reader // allocates. if crate::envflags::env_flag!("EC_MC_TRACE") { eprintln!("EC_IB px={px} py={py} side={side} w={write_w} h={write_h}"); } if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}", rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } let skip_mode_ctx = usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]); // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read // MSAC tell so it can be diffed against an equivalent hook in libaom's // own `read_skip_mode`/`av1_get_skip_mode_context`. if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") { eprintln!( "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}", dec.debug_bitpos() ); } // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before // `skip_mode`/`skip`, `inter_segment_id(0)` after them. let (seg_mi_r, seg_mi_c) = (rmi, cmi); let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4); inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true, fctx); // libaom `read_skip_mode` (decodemv.c): `if (!is_comp_ref_allowed(bsize)) // return 0` -- a 16x4 / 4x16 strip (min(bw, bh) == 4, blockd.h:65) reads // no `skip_mode` symbol at all. let comp_allowed = write_w.min(write_h) >= 8; let skip_mode = skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") { eprintln!( "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}", dec.debug_bitpos() ); } if skip_mode { hit!(SKIP_MODE_HITS); } let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false, fctx); maybe_read_cdef_idx(dec, rmi, cmi, skip, fctx); // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip // is NOT the whole superblock, so its `skip` never suppresses the read. // lane-sb128c r7: `sbSize` is 128 under `--sb-size=128`, so the whole-block // test is against the sequence's own superblock side, not a hardcoded 64. let sb_px = sb_mi_cur(fctx) as usize * 4; let whole_sb = side == sb_px && write_w == sb_px && write_h == sb_px; maybe_read_delta_q(dec, cdfs, rmi, cmi, whole_sb, skip, fctx); maybe_read_delta_lf(dec, cdfs, rmi, cmi, whole_sb, skip, fctx); let (has_above, has_left) = ( rmi > neighbours.tile_row0_mi, cmi > neighbours.tile_col0_mi, ); let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; // lane-sb128c r1: this round wires the INTER half of a 128x128 block (four // TX_64X64 luma units and four TX_32X32 chroma units interleaved per mu // chunk). An INTRA block at that size inside an inter frame takes the // intra tail below, which still codes one whole-block chroma unit and one // `read_tx_size` at 128 -- refuse by name instead of mis-decoding it. if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE mi_row={} mi_col={} rng={} is_inter={} skip={} side={side}", rmi, cmi, dec.debug_state().0, u8::from(is_inter), u8::from(skip) ); } // lane-warp r5: see `reject_residual` -- a square-block decode of a // HORZ_B strip is symbol-exact only for `skip` (no residual, no // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just // after the `skip` read to here, past `is_inter` (class // [[refusal-short-circuits-its-own-code]]: at the old place it refused // 24/24 attempts of this lane's own gate before the intra arm below // could run). An INTRA strip with its true `write_w`x`write_h` footprint // now codes its residual rectangularly ([`decode_intra_rect_in_inter`]); // an INTER one, and a strip decoded with square dimensions anyway, still // cannot. // merge b51719f+lane-intrarect: main's `rect_inter_residual_supported` // term stays -- lane-inter4's 16x8/8x16 inter leaves DO code a // rectangular residual, and the lane's condition (written before that // landed) refused every one of them. if reject_residual && !skip && !rect_inter_residual_supported(write_w, write_h) && (is_inter || (write_w == side && write_h == side)) { if crate::envflags::env_flag!("EC_RECTRES") { eprintln!( "EC_RECTRES w={write_w} h={write_h} side={side} skip={} is_inter={} mi_row={rmi} mi_col={cmi}", u8::from(skip), u8::from(is_inter) ); } return Err(unsupported( "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", )); } if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}", rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } let mode_for_tx; let uv_predict_mode; let (luma_grid, u_grid, v_grid); let block_filter; let ref_frame_for_lf; let globalmv_for_lf; // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the // common `record_inter` call below (which would otherwise stamp the // single-ref ALTREF-special-case default over it). let mut compound_ctx: Option<(i8, u8, u8)> = None; // lane-txselect: `read_block_tx_size`'s leaf transform units (spec // 5.11.17), `Some` only when this block's var-tx tree resolved to more // than one luma transform -- read back by the residual loop, the // coefficient-context write-back and the loop-filter grid fill below. let vartx_leaves: Option>; // lane-t900 r22: this block's own palette state, stamped into the // mi-granular neighbour bands at the tail below for EVERY block -- // libaom's `MB_MODE_INFO.palette_size` is 0 on an inter block, and // `av1_get_palette_cache`/`av1_get_palette_mode_ctx` read those cells, so // leaving a previous palette block's colours standing here would feed the // next intra block a cache libaom never builds. let mut palette_record: (usize, [u16; 8], usize, [u16; 8]) = (0, [0u16; 8], 0, [0u16; 8]); let at_mi = at; // lane-vert46 r1: set when this block's chroma was coded as one 32x32 unit // per 64x64 "mu" chunk (any side above 64), so the end-of-block record // below must NOT re-stamp the chroma neighbour context from the assembled // whole-block grid. let mut mu_chroma = false; if is_inter { let above_nbr = has_above.then(|| NeighbourRef { is_inter: above_inter, ref0: if above_inter { neighbours.above_ref[cmi] } else { 0 }, ref1: neighbours.above_ref1[cmi], uni: neighbours.above_ref1[cmi] .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)), }); let left_nbr = has_left.then(|| NeighbourRef { is_inter: left_inter, ref0: if left_inter { neighbours.left_ref[rmi] } else { 0 }, ref1: neighbours.left_ref1[rmi], uni: neighbours.left_ref1[rmi] .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)), }); if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") { eprintln!( "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}", dec.debug_bitpos() ); } let is_compound = skip_mode || (reference_select // `is_comp_ref_allowed` (blockd.h:65) gates the // `comp_mode` read exactly as it gates `skip_mode`. && comp_allowed && read_comp_mode(dec, cdfs, above_nbr, left_nbr)); if is_compound { let (ref0, ref1) = if skip_mode { (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8) } else { read_compound_ref_frames( dec, cdfs, above_nbr, left_nbr, neighbours.above_ref[cmi], neighbours.left_ref[rmi], ) }; let (mi_row, mi_col) = (rmi, cmi); // lane-rect r2: true footprint, mirroring the single-ref path below. let bw4 = write_w / 4; let bh4 = write_h / 4; // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same // `use_ref_frame_mvs` gating as the single-ref `tpl` build // below, just one `get_relative_dist` per reference. let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs { field: t.field, cur_offset_0: crate::motion_field::get_relative_dist( t.order_hint_bits, t.order_hint, t.ref_order_hints[(ref0 - LAST_FRAME) as usize], ), cur_offset_1: crate::motion_field::get_relative_dist( t.order_hint_bits, t.order_hint, t.ref_order_hints[(ref1 - LAST_FRAME) as usize], ), allow_high_precision_mv, }); let gm_table = build_gm_mv_table( global_motion, mi_row, mi_col, bw4, bh4, allow_high_precision_mv, force_integer_mv, ); let comp_stack = crate::mvstack::find_mv_stack_compound( grid, mi_row, mi_col, bw4, bh4, (ref0, ref1), mi_cols as usize, mi_rows as usize, sign_bias_table, &gm_table, comp_tpl, ); let compound_mode = if skip_mode { 0 // NEAREST_NEARESTMV, forced -- no mode symbol read } else { read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx) }; let (mv0, mv1) = assign_compound_mv( dec, cdfs, &comp_stack, compound_mode, allow_high_precision_mv, force_integer_mv, (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]), ); if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}", compound_mode + 17, mv0.0, mv0.1, comp_stack.entries.len(), dec.debug_state().0 ); for (i, e) in comp_stack.entries.iter().enumerate() { eprintln!( "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}", e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight ); } } let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV // spec `is_nontrans_global_motion`: ALL active refs' models must // be non-TRANSLATION (IDENTITY counts) for the compound block's // interp-filter read to be suppressed. let gm_nontrans_models = is_globalmv && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation; // lane-t900 r9: `is_nontrans_global_motion` bails at // `AOMMIN(mi_size_wide, mi_size_high) < 2` before it looks at any // model, so a 4-px-sided block still reads its interp filter. let gm_nontrans = gm_nontrans_models && bw4.min(bh4) >= 2; if gm_nontrans_models && !gm_nontrans { hit!(GM_NONTRANS_SMALL_SIDE_HITS); } // lane-defer8: both slots' pictures are resolved inside the // prediction closure; the parse only needs their SIZES. // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from // the write extent below, so recompute the size bound from // `side` here (the block's own size, what libaom's `bsize` // is). let is_global_mv0 = is_globalmv && side >= 8 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1; let is_global_mv1 = is_globalmv && side >= 8 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1; // libaom `av1_init_warp_params` + `allow_warp`'s // `global_warp_allowed` branch, run once per reference for a // compound block exactly as for a single-ref one (reconinter.c // `build_inter_predictors_8x8_and_bigger` loops over `ref` and // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL // never reaches here (spec 5.11.27 / libaom `read_motion_mode`: // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp // arm of `allow_warp` is dead on this path and only the global // one applies. `force_integer_mv` short-circuits // `av1_init_warp_params` before `allow_warp`. let compound_warp = |ref_frame: i8, eligible: bool| { if eligible && !force_integer_mv && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid { crate::warp::global_warp_params( global_motion[(ref_frame - LAST_FRAME) as usize].params, ) } else { None } }; // lane-t900 r28 (class branch-dropped-as-unreachable, swept out // of the scaled-ref lift): libaom `allow_warp` // (av1/common/reconinter.c:41) opens with `if (av1_is_scaled(sf)) // return 0;` PER SLOT, so a compound tap whose own reference is // scaled (superres) is predicted translationally while its // sibling may still warp. let ref_unscaled = |rf: i8| { refpix .dims(rf) .is_some_and(|(w, _)| mc::scale_factor(w, frame_width) == mc::REF_NO_SCALE) }; let warp0 = compound_warp(ref0, is_global_mv0).filter(|_| ref_unscaled(ref0)); let warp1 = compound_warp(ref1, is_global_mv1).filter(|_| ref_unscaled(ref1)); if warp0.is_some() || warp1.is_some() { hit!(COMPOUND_WARP_HITS); } // spec `get_ref_filter_type`: matches when EITHER of the // neighbour's two references equals this block's own ref0 -- // `above_ref1`/`left_ref1` is the neighbour's real second // reference (`record_compound_ctx`) when it was itself a // compound block; checking `above_ref`/`left_ref` alone drops a // real filter match down to the "no neighbour" sentinel // whenever the shared reference sits in the neighbour's SECOND // slot (lane-av1idx r2). let above_filter_ctx = if neighbours.above_ref[cmi] == ref0 || neighbours.above_ref1[cmi] == Some(ref0) { neighbours.above_filter[cmi] } else { [3, 3] }; let left_filter_ctx = if neighbours.left_ref[rmi] == ref0 || neighbours.left_ref1[rmi] == Some(ref0) { neighbours.left_filter[rmi] } else { [3, 3] }; globalmv_for_lf = is_globalmv; ref_frame_for_lf = ref0; mode_for_tx = 0; uv_predict_mode = DC_PRED; // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from // `neighbours`) must be stamped with the block's true footprint // too -- a square `bw4`x`bw4` stamp here claims a rect strip's // NEXT strip's own rows/cols before it decodes, corrupting // every later mvstack scan that reads this cell back. grid.fill_rect( mi_row, mi_col, bh4, bw4, MiInfo { is_inter: true, ref_frame: ref0, ref_frame1: ref1, mv1: mv16(mv1), mv: mv16(mv0), is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), size: bw4 as u8, size_h: bh4 as u8, // libaom `is_global_mv_block`: per-ref-slot, mode // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's // own gm model > TRANSLATION (IDENTITY excluded // too -- the two-predicate trap, distinct from // `gm_nontrans` above which allows IDENTITY). is_global_mv0, is_global_mv1, }, ); // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when // masked compound / distance-weighted compound are actually // enabled for this stream -- `is_any_masked_compound_used_here` // is `true` for every block size this decoder ever reaches // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible // there), so the gate reduces to the sequence header bit; kept // as an explicit call so a future smaller block size is not // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`). let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side); let comp_group_idx = if !skip_mode && enable_masked_compound && is_any_masked_compound_used_here(write_w, write_h) { dec.symbol(&mut cdfs.comp_group_idx[group_ctx]) } else { 0 }; if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_CGI mi_row={rmi} mi_col={cmi} ctx={group_ctx} val={comp_group_idx} rng={}", dec.debug_state().0 ); } // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup) // for a `COMPOUND_WEDGE` block -- exactly one of the two is set // when `comp_group_idx == 1`. let mut diffwtd_mask_type: Option = None; let mut wedge_mask: Option<&'static [u8]> = None; if comp_group_idx == 1 { // lane-maskcomp r1: `read_compound_type` (spec 5.11.25, // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`, // `av1_wedge_params_lookup`) is true for every square bsize // this leaf reaches (8x8/16x16/32x32 all have // `wedge_types > 0`), so `compound_type` always reads a real // symbol here -- no alphabet collapse to worry about at this // block-size family. // lane-mcomp64 r1: `av1_is_wedge_used` is false at 64x64 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`), // so libaom's `read_compound_type` (decodemv.c 1634-1656) // writes NO `compound_type` symbol there and INFERS // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal // follows. `None` here is exactly that inferred arm. // lane-inter16ab r3: the row is this block's TRUE // `BLOCK_SIZES_ALL` index, not the enclosing square `side`'s // -- a 16x8 strip reads `compound_type_cdf[BLOCK_16X8]`. let wedge_bsize = bsize_all_index(write_w, write_h).filter(|_| wedge_used_bsize(write_w, write_h)); let compound_type = match wedge_bsize { Some(b) => dec.symbol(&mut cdfs.compound_type[b]), None => 1, }; if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) { // COMPOUND_WEDGE: lane-wedge r3, codebook checksum- // verified vs independent C dump (wedge.rs). let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]); let wedge_sign = dec.literal(1); hit!(WEDGE_HITS); if let Some(k) = rect_wedge_slot(write_w, write_h) { hit_do! { RECT_WEDGE_HITS.with(|c| { let mut a = c.get(); a[k] += 1; c.set(a); }); } } // lane-inter16ab r5: the codebook row is this block's TRUE // footprint (`av1_wedge_params_lookup[bsize]`: hgtw for // h>w, hltw for h>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0), // the common case a lag-in-frames GOP's hidden altref frames // hit) reproduces aomdec's own pre-deblock dump byte-for-byte // for several consecutive frames. // // The real defect a live gate run isolated (seed 49, // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0 // (keyframe) and frame 1 (first hidden altref, `ref1 == // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for // byte; decode-order frame 2 -- same shape, same zero MV, only // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` -- // is the *first* frame to diverge (881/6144 luma+chroma bytes). // Every later frame up through decode-order 9 also mismatches, // *including* frame 8, whose four blocks are back to // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC // math is wrong" (that block's own math is proven exact) in // favour of "the picture sitting in some DPB slot is already // wrong by the time frame 2 reads it, and the corruption // propagates through refresh_frame_flags into every later // reference regardless of which named ref a later block picks". // Frames 10 through 18 (once the GOP's lineage stops tracing // back through the bad slot) are bit-exact again. This points at // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags` // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB // indexing feeding `dist_wtd_comp_weight_assign`) around // BWDREF_FRAME specifically, not at the MC/blend arithmetic in // mc.rs. Not isolated further within lane-av1blend's budget -- // refuse by name rather than ship a blend that is right only // sometimes. Ceiling: r13/r14's MC plumbing above this line // stays -- only the plain-average reconstruct is masked off // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags` // per decode-order frame (which slot each `Frame` OBU refreshes, // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]` // reads) against aomdec's own `RefCntBuffer` bookkeeping on // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order // frame 2. // // r2 (fresh fixture, seed 45, same recipe -- the original r1 // fixture is gitignored and could not be regenerated byte-exact): // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/ // `cdf_slots` bookkeeping and the `show_existing_frame` refresh // arm (spec 7.21: only refreshes on a shown KEY frame, which the // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags` // is forced 0 on every non-key `show_existing_frame`) turned up // nothing wrong; `other_refs`/`ref_planes` slot indexing for // `BWDREF_FRAME` is spec-correct too. A live unmasked run // isolated a *different, smaller* shape than r1's: decode-order // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average // compound block) is the first to diverge from ffmpeg (worst // delta 1, luma only, clustered at 32-pixel block edges) even // though BOTH its compound inputs -- the key frame and // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`, // itself proven bit-exact: it is later re-shown via // `show_existing_frame` and matches ffmpeg exactly) -- are // independently pixel-exact, and the blend arithmetic is the // same proven-exact formula. That rules out "wrong slot"/"stale // picture" for this fixture: the inputs are right, so the defect // is in decode-order frame 3's *own* per-block decode (entropy // desync from compound-CDF adaptation carried across a slot, or // the compound mode/MV read itself) -- not in `ref_slots`/ // `refresh_frame_flags`. Not isolated further within budget. // Upgrade: bisect decode-order frame 3's tile decode against a // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49) // -- the pre-deblock dump frame-index alignment between this // crate and that aomdec build is NOT 1:1 on this fixture (23 // dumps here vs 24 there), so calibrate that first. // r3 (this round): pre-deblock buffers were bisected byte-for-byte // against an instrumented aomdec build (frame-index alignment // recalibrated via content-hash matching rather than the raw // dump count -- the keyframe never calls a pre-deblock dump at // all, since only `decode_inter_frame_tile` does, which is the // whole "23 vs 24" gap, not a real bug). // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`, // seed 45) is still the first divergence: PRE-deblock differs // from aomdec's own pre-deblock dump by up to 1, on ~20% of // luma pixels, clustered where its two compound inputs' pixel // values disagree by more than a couple of levels -- both // inputs (the keyframe and decode-order frame 2's own picture) // are independently proven bit-exact (pre- and post-deblock) // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip) // matches this decoder's block loop exactly for every block in // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for // every mismatching pixel against `key`/`bwd` (both known-exact) // picks out `w0=9, w1=7` for the majority (525/846) with zero // matches for the plain average this decoder actually emits or // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when // the real bitstream encoded `0` (`COMPOUND_DISTWTD`, // `dist_wtd_comp_weight_assign`'s own weights for this frame's // order-hint distances 2/3 land on exactly `(9, 7)` -- this // decoder's own `dist_wtd_comp_weight_assign` was independently // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE` // by hand for these distances and gives the same `(9, 7)`). // `get_comp_index_context` was checked line-for-line against // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback, // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf` // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s // `default_compound_idx_cdfs` value-for-value; the read is // gated on `!skip_mode && enable_jnt_comp`, matching libaom's // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus // `order_hint_info.enable_dist_wtd_comp` inner guard. The // remaining 321/846 mismatched pixels do NOT fit `(9, 7)` // either -- some blocks in this frame plausibly decode a // genuinely different (correct, context-dependent) compound_idx // than block (0,0)'s own -- so this is not simply "always wrong // the same way": table/context/gate are all individually // verified correct, yet the decoded VALUE at this specific // symbol is wrong at least once in this frame. Not isolated // further within budget. Upgrade: instrument `dec.symbol`'s own // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART // trace fields) immediately before and after the `compound_idx` // read specifically, not just the surrounding mode/mv/skip // trace which does match -- the desync (if any) is local to // this one read, not a wider stream desync. // // r5 (this round): the `resolve_interp_filter` call used to sit // right here, ahead of `comp_group_idx`/`compound_idx` -- spec // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER // `read_compound_type`, not before, so that was a genuine // ordering bug for a Switchable-filter frame (moved below, past // the `compound_ctx = Some(...)` line). It does NOT explain this // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s // header carries a *fixed* interpolation filter // (`interp_fixed = Some(Regular)`, confirmed live via a // one-off dump), so `resolve_interp_filter` never read a symbol // in either position -- zero bits moved, decoded values // unchanged before and after the reorder. Kept anyway: it is a // real spec-order fix for the next Switchable-filter compound // stream, independently correct regardless of this fixture. // // Also ruled out this round: comparing this crate's own // `SymbolDecoder::debug_bitpos()` against aomdec's // `aom_reader_tell()` at the block boundary is NOT a valid // desync probe -- they are different quantities (raw consumed // input bits vs. an entropy-cost estimate that advances without // a literal byte fetch), so equal/unequal bitpos proves nothing // either way. Do not repeat that comparison; instead trace // `range`/`value` (this crate) against libaom's own internal // `dif`/`rng` (needs new instrumentation in both) immediately // after each read *upstream* of this one in the same block: // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/ // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`, // and the DRL loop. All of those independently decoded the SAME // values this crate and aomdec both show (ref0=1, ref1=5, mode // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context* // miscomputation can still decode the identical symbol value off // a slightly different CDF, narrowing `range` by a different // amount than aomdec without changing the decoded value itself, // and only surface as a wrong decode a few reads later exactly // like this. `get_comp_index_context` and the `COMPOUND_IDX` // table were independently re-verified again this round and are // still correct; the four candidates above were not re-audited // this round. Refusing here (rather than shipping a value-exact- // most-of-the-time blend) until one of them is found wrong. // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family // undercounted compound neighbours in the single_ref_p*/comp_ref*/ // comp_bwdref* context reads -- kept, real fix). Unmasking on // that fix alone and running the wide gate sweep (many seeds, // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/ // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`, // cq-level=45) still mismatches roughly half the time, at // different frames each run for the SAME seed -- aomenc's own // cpu-used=0 RD search is run-to-run nondeterministic (noted // above), so this is a second, still-unfound compound_idx defect, // not the one r6/r7 fixed. r6's own residual-mismatch note (321/ // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis // either) already flagged more than one bug here. Re-masking: // do not ship a blend that is right only sometimes. // lane-av1idx r1: fixed one real bug this round // (`switchable_interp_ctx` never folded in libaom's // `INTER_FILTER_COMP_OFFSET` for a compound block's own // interp_filter context -- kept). Pinned // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select // gate) still mismatches after that fix (decode-order frame 8 // first, small deltas, worst 1-2, propagating through later // frames via DPB reference) -- a second, still-unfound bug. // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch` // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`) // for the next round's starting point. // lane-maskcomp r2: `compound_idx` is only read when // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked // (wedge/diffwtd) block never also carries a distance-weighted // split. This gate was missing before r2 (dead code: the masked // path always refused earlier, so it never executed with // `comp_group_idx == 1` in practice). let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0 && !skip_mode && enable_jnt_comp { let idx_ctx = get_comp_index_context( neighbours, (rmi, cmi), side, order_hint_bits, order_hint, ref_order_hints[(ref0 - LAST_FRAME) as usize], ref_order_hints[(ref1 - LAST_FRAME) as usize], ); let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]); if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_CIDX mi_row={rmi} mi_col={cmi} ctx={idx_ctx} val={idx} rng={}", dec.debug_state().0 ); } if idx == 1 { (8, 8, 1u8) } else { let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign( order_hint_bits, order_hint, ref_order_hints[(ref0 - LAST_FRAME) as usize], ref_order_hints[(ref1 - LAST_FRAME) as usize], ); (fwd, bck, 0u8) } } else { (8, 8, 1u8) }; compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx)); if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") { eprintln!( "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize={side} mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}", mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos() ); } // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter` // comes AFTER `read_compound_type` (the `comp_group_idx`/ // `compound_idx` reads just above), not before -- moved here // (lane-av1blend r5) from its old position ahead of those reads, // which stole their bits for a Switchable-filter compound block // and desynced every symbol read after it in the tile. // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the // filter is derived (Regular), never read -- same // conditional-read contract as the WARPED_CAUSAL suppression on // the single-ref path below. let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, cdfs, interp_fixed, enable_dual_filter, gm_nontrans || skip_mode, above_filter_ctx, left_filter_ctx, true, ); block_filter = resolved_filter; // lane-scaledref r1: each compound tap scales INDEPENDENTLY off // its own stored reference's luma width (spec 7.11.3.3 derives // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds // one `scale_factors` per `ref_frame`), so the two taps can carry // different ratios in the same block. `REF_NO_SCALE` reduces // `predict_compound_intermediate`'s walk to the ordinary // stride-1 one, so the unscaled case is unchanged. let scale0 = mc::scale_factor(ref_dims(ref0, refpix)?.0, frame_width); let scale1 = mc::scale_factor(ref_dims(ref1, refpix)?.0, frame_width); if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE { hit!(SCALED_COMPOUND_HITS); } // lane-scaledref r2: the MIXED case -- one tap scaled, the other // not -- is the one an all-frames-scaled recipe never produces, // and the one a single shared scale factor would get wrong. if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) { hit!(MIXED_SCALE_COMPOUND_HITS); } // lane-wave4 (the compound arm's half): this block's whole // prediction -- both references, the wedge/diffwtd/distance // blend, every plane -- as a closure, run here at one // reconstruction thread and on the wavefront worker otherwise // (see the single-reference arm below). A compound block reads // neither `motion_mode` nor `interintra`, so nothing but the // blend itself lives in here. let build = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let (Some((py0, pu0, pv0)), Some((py1, pu1, pv1))) = (ref_planes_deferred(ref0, refpix), ref_planes_deferred(ref1, refpix)) else { return; }; let mut inter0_y = vec![0i32; side * side]; mc::predict_compound_intermediate_kern( &py0.data, py0.width, py0.true_width, py0.true_height, mv_to_q4(px, mv0.1, true), mv_to_q4(py, mv0.0, true), scale0, side, side, write_w, write_h, h_filter, v_filter, &mut inter0_y, ); // lane-cwarp r1: this reference's own GLOBAL warp replaces the // translational tap (libaom `av1_warp_plane` with // `conv_params->is_compound`); the blend below is unchanged. if let Some(wp) = warp0.as_ref().filter(|_| warp_plane_allowed(write_w, write_h)) { crate::warp::warp_affine_compound( wp, &py0.data, py0.true_width as i32, py0.true_height as i32, py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32, side as i32, side as i32, 0, 0, fctx, ); } let mut inter1_y = vec![0i32; side * side]; mc::predict_compound_intermediate_kern( &py1.data, py1.width, py1.true_width, py1.true_height, mv_to_q4(px, mv1.1, true), mv_to_q4(py, mv1.0, true), scale1, side, side, write_w, write_h, h_filter, v_filter, &mut inter1_y, ); // lane-cwarp r1: this reference's own GLOBAL warp replaces the // translational tap (libaom `av1_warp_plane` with // `conv_params->is_compound`); the blend below is unchanged. if let Some(wp) = warp1.as_ref().filter(|_| warp_plane_allowed(write_w, write_h)) { crate::warp::warp_affine_compound( wp, &py1.data, py1.true_width as i32, py1.true_height as i32, py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32, side as i32, side as i32, 0, 0, fctx, ); } let mut pred_y = refill(std::mem::take(&mut out[0]), side * side); let mut diffwtd_mask_y; // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR // the wedge codebook lookup (comp_group_idx==1's two mutually // exclusive branches) -- same [`mc::blend_masked_compound`] call // either way, only the mask source differs. let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type { diffwtd_mask_y = vec![0u8; side * side]; hit!(DIFFWTD_HITS); mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y, fctx); Some(diffwtd_mask_y.as_slice()) } else { wedge_mask }; if let Some(mask_y) = mask_y { mc::blend_masked_compound( &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y, fctx, ); } else { mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y, fctx); } let mut inter0_u = vec![0i32; chroma_side * chroma_side]; mc::predict_compound_intermediate_kern( &pu0.data, pu0.width, pu0.true_width, pu0.true_height, mv_to_q4(cpx, mv0.1, false), mv_to_q4(cpy, mv0.0, false), scale0, chroma_side, chroma_side, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut inter0_u, ); // `av1_init_warp_params` bails when the PLANE's block is // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma // block of an 8x8 luma block stays translational. if let Some(wp) = &warp0 { if warp_plane_allowed(write_chroma_w, write_chroma_h) { crate::warp::warp_affine_compound( wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32, pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32, chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1, fctx, ); } } let mut inter1_u = vec![0i32; chroma_side * chroma_side]; mc::predict_compound_intermediate_kern( &pu1.data, pu1.width, pu1.true_width, pu1.true_height, mv_to_q4(cpx, mv1.1, false), mv_to_q4(cpy, mv1.0, false), scale1, chroma_side, chroma_side, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut inter1_u, ); // `av1_init_warp_params` bails when the PLANE's block is // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma // block of an 8x8 luma block stays translational. if let Some(wp) = &warp1 { if warp_plane_allowed(write_chroma_w, write_chroma_h) { crate::warp::warp_affine_compound( wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32, pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32, chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1, fctx, ); } } let mut pred_u = refill(std::mem::take(&mut out[1]), chroma_side * chroma_side); if let Some(mask_y) = mask_y { mc::blend_masked_compound( &inter0_u, &inter1_u, mask_y, side, chroma_side, chroma_side, true, &mut pred_u, fctx, ); } else { mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u, fctx); } let mut inter0_v = vec![0i32; chroma_side * chroma_side]; mc::predict_compound_intermediate_kern( &pv0.data, pv0.width, pv0.true_width, pv0.true_height, mv_to_q4(cpx, mv0.1, false), mv_to_q4(cpy, mv0.0, false), scale0, chroma_side, chroma_side, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut inter0_v, ); // `av1_init_warp_params` bails when the PLANE's block is // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma // block of an 8x8 luma block stays translational. if let Some(wp) = &warp0 { if warp_plane_allowed(write_chroma_w, write_chroma_h) { crate::warp::warp_affine_compound( wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32, pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32, chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1, fctx, ); } } let mut inter1_v = vec![0i32; chroma_side * chroma_side]; mc::predict_compound_intermediate_kern( &pv1.data, pv1.width, pv1.true_width, pv1.true_height, mv_to_q4(cpx, mv1.1, false), mv_to_q4(cpy, mv1.0, false), scale1, chroma_side, chroma_side, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut inter1_v, ); // `av1_init_warp_params` bails when the PLANE's block is // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma // block of an 8x8 luma block stays translational. if let Some(wp) = &warp1 { if warp_plane_allowed(write_chroma_w, write_chroma_h) { crate::warp::warp_affine_compound( wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32, pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32, chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1, fctx, ); } } let mut pred_v = refill(std::mem::take(&mut out[2]), chroma_side * chroma_side); if let Some(mask_y) = mask_y { mc::blend_masked_compound( &inter0_v, &inter1_v, mask_y, side, chroma_side, chroma_side, true, &mut pred_v, fctx, ); } else { mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v, fctx); } // lane-inter4 r2: a rectangular strip's transform tree starts from // its own rect `max_txsize_rect_lookup` entry, not a square one. *out = [pred_y, pred_u, pred_v]; }; let (pred_y, pred_u, pred_v): (Vec, Vec, Vec); let (sy, su, sv) = if recon_deferred(fctx) { push_pred(fctx, build); ( Pred::Cur { plane: 0, stride: side, off: 0 }, Pred::Cur { plane: 1, stride: chroma_side, off: 0 }, Pred::Cur { plane: 2, stride: chroma_side, off: 0 }, ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, fctx, &mut built); let [by, bu, bv] = built; (pred_y, pred_u, pred_v) = (by, bu, bv); ( Pred::Inline(&pred_y, side), Pred::Inline(&pred_u, chroma_side), Pred::Inline(&pred_v, chroma_side), ) }; let rect_tu = (write_w, write_h) != (side, side); vartx_leaves = if rect_tu { read_block_tx_size_rect( dec, cdfs, neighbours, at_mi, (write_w, write_h), (mi_cols as usize, mi_rows as usize), skip, fctx, )? } else { read_block_tx_size( dec, cdfs, neighbours, at_mi, side, (mi_cols as usize, mi_rows as usize), true, skip, fctx, )? .1 }; if skip { push_mc_rect(0, px, py, side, write_w, write_h, sy, &ZERO_RESIDUAL[..side * side], fctx, ); push_mc_rect(1, cpx, cpy, chroma_side, write_chroma_w, write_chroma_h, su, &ZERO_RESIDUAL[..chroma_side * chroma_side], fctx, ); push_mc_rect(2, cpx, cpy, chroma_side, write_chroma_w, write_chroma_h, sv, &ZERO_RESIDUAL[..chroma_side * chroma_side], fctx, ); luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(chroma_side * chroma_side); v_grid = Grid::Zero(chroma_side * chroma_side); } else { // lane-inter4 r2: a rect strip's coefficient context spans its // OWN width above and height left -- reading `side` cells both // ways indexes past the tile's last mi row for a bottom strip. let around = if rect_tu { neighbours.around_mi_rect(at_mi, write_w, write_h) } else { neighbours.around_mi(at, side) }; let luma_tx_type; // lane-sb128c r1: a 128x128 inter block's four chroma units // are read INSIDE the luma leaf loop (one per 64x64 mu chunk); // these collect them for the block-level neighbour write-back. let mut u_units: Vec = Vec::new(); let mut v_units: Vec = Vec::new(); if let Some(leaves) = vartx_leaves.as_ref() { // spec 5.11.17's transform tree, leaf by leaf in the order // `read_var_tx_size` coded it: each unit reads its own // coefficients against the neighbour magnitudes the // earlier units already wrote, and reconstructs over its // own slice of the block's motion-compensated predictor. let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); let mut first_tx_type = TxType::DctDct; for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() { let tu_mi = (at_mi.0 + row, at_mi.1 + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); let (tu_grid, tu_tx_type) = if tw == th { let tx_px = tw; let tu_pred = sy.offset(row * MI * side + col * MI); let scan = default_scan(tx_px.min(32)); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI); read_inter_plane( dec, cdfs, inter_txbset_for(tx_px, reduced), &scan, 0, neighbours.around_mi(tu_mi, tx_px)[0], mode_for_tx, y, tu_px, tu_py, tx_px, base_q_idx, tu_pred, None, Some(tu_skip_ctx), fctx, )? } else { // lane-r14 r3: a 1:4 strip's `sub_tx_size_map` // sub-transform is RECTANGULAR (TX_64X16 -> // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is // read with the rect coefficient machinery, at its // own `txb_skip_ctx`/neighbour spans -- the unit is // smaller than its block, so `get_txb_ctx_general`'s // neighbour table applies, not the lone-TU 0. vartx_rect_leaf_hit(tw, th); let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI); let start = row * MI * side + col * MI; read_inter_plane_rect( dec, cdfs, rect_inter_luma_set(tw, th, fctx)?, (tw, th), side, 0, neighbours.around_mi_rect(tu_mi, tw, th)[0], mode_for_tx, y, tu_px, tu_py, sy.offset(start), None, Some(tu_skip_ctx), fctx, )? }; if idx == 0 { first_tx_type = tu_tx_type; } neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid); // lane-sb128c r1: libaom's `decode_token_recon_block` // walks 64x64 "mu" chunks (`mu_blocks_wide/high = // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of // a chunk before the next one, so a 128x128 block // interleaves Y,U,V per quadrant -- the same order the // intra 128 path reads (lane-sb128b r3, measured // against aomdec's `EC_TRACE_COEFF`). Below 128 a block // is a single chunk and this never fires. if side > 64 { let chunk = (row / 16, col / 16); let done = idx + 1 == leaves.len() || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk; if done { let (cr, cc) = chunk; // `av1_get_max_uv_txsize(BLOCK_128X128)` = // `av1_get_adjusted_tx_size(TX_64X64)` = // TX_32X32: one 32x32 chroma unit per chunk. let cu_tx = 32usize; let luma_span = cu_tx * 2; let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16); let cu_around = neighbours.around_mi(cu_mi, luma_span); let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx); let cu_scan = default_scan(cu_tx); for plane_idx in 1..3 { let (src, buf) = if plane_idx == 1 { (su, &mut *u) } else { (sv, &mut *v) }; let cu_pred = src.offset(cr * cu_tx * chroma_side + cc * cu_tx); let cu_grid = read_inter_plane( dec, cdfs, chroma_set, &cu_scan, plane_idx, cu_around[plane_idx], mode_for_tx, buf, cu_x, cu_y, cu_tx, base_q_idx, cu_pred, Some(first_tx_type), Some(3), fctx, )? .0; // Immediately, so the NEXT chunk's unit // reads this one's coefficient context. neighbours.record_mi_chroma( cu_mi, luma_span, luma_span, plane_idx, &cu_grid, ); hit!(CHROMA_SPLIT_TX_HITS); mu_chroma = true; let dst = mu_units( if plane_idx == 1 { &mut u_units } else { &mut v_units }, chroma_side * chroma_side, ); for rr in 0..cu_tx { let start = (cr * cu_tx + rr) * chroma_side + cc * cu_tx; dst[start..start + cu_tx] .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]); } } } } } // `av1_get_tx_type`'s chroma lookup scales the chroma // position back to luma, so an inter block's chroma // inherits the *first* (top-left) luma unit's coded type. luma_tx_type = first_tx_type; luma_grid = Grid::Zero(side * side); } else if rect_tu { // The whole-block rectangular transform unit // (`txfm_partition` said 0 at depth 0). let (grid, tx_type) = read_inter_plane_rect( dec, cdfs, rect_inter_luma_set(write_w, write_h, fctx)?, (write_w, write_h), side, 0, around[0], mode_for_tx, y, px, py, sy, None, None, fctx, )?; luma_tx_type = tx_type; luma_grid = Grid::Own(embed_rect_grid(&grid, write_w, write_h, side)); } else { { let coded = read_inter_plane( dec, cdfs, luma_set_inter, scan_luma, 0, around[0], mode_for_tx, y, px, py, side, base_q_idx, sy, None, None, fctx, )?; luma_grid = coded.0; luma_tx_type = coded.1; } } if side > 64 { // Already read inside the mu-chunk loop above -- at the 128 // root a rect (128x64/64x128) block's chroma is per mu // chunk too, so this test comes BEFORE the `rect_tu` one. u_grid = if u_units.is_empty() { Grid::Zero(chroma_side * chroma_side) } else { Grid::Own(std::mem::take(&mut u_units)) }; v_grid = if v_units.is_empty() { Grid::Zero(chroma_side * chroma_side) } else { Grid::Own(std::mem::take(&mut v_units)) }; } else if rect_tu { // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a // 2:1 strip is the strip's own rect chroma size (16x8 / // 8x16), one unit for the whole block, and it codes no // `tx_type` symbol -- it inherits the luma unit's. let (uw, uh) = (write_chroma_w, write_chroma_h); u_grid = Grid::Own(embed_rect_grid( &read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(write_chroma_w, write_chroma_h)?, (uw, uh), chroma_side, 1, around[1], mode_for_tx, u, cpx, cpy, su, Some(luma_tx_type), None, fctx, )? .0, uw, uh, chroma_side, )); v_grid = Grid::Own(embed_rect_grid( &read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(write_chroma_w, write_chroma_h)?, (uw, uh), chroma_side, 2, around[2], mode_for_tx, v, cpx, cpy, sv, Some(luma_tx_type), None, fctx, )? .0, uw, uh, chroma_side, )); } else { u_grid = read_inter_plane( dec, cdfs, chroma_set, scan_chroma, 1, around[1], mode_for_tx, u, cpx, cpy, chroma_side, base_q_idx, su, Some(luma_tx_type), None, fctx, )? .0; v_grid = read_inter_plane( dec, cdfs, chroma_set, scan_chroma, 2, around[2], mode_for_tx, v, cpx, cpy, chroma_side, base_q_idx, sv, Some(luma_tx_type), None, fctx, )? .0; } } } else { let ref_frame = read_single_ref( dec, cdfs, neighbours.above_ref[cmi], neighbours.above_ref1[cmi], neighbours.left_ref[rmi], neighbours.left_ref1[rmi], ); ref_frame_for_lf = ref_frame; if crate::envflags::env_flag!("EC_AV1_TELL") { let (mi_row, mi_col) = (rmi, cmi); eprintln!( "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}", dec.debug_bitpos(), dec.debug_state().0 ); } // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own // stacked defects (lf_level ref/mode-delta forwarding, the // switchable_interp ref-frame ctx gate, and a film-grain synthesis // gap that looked like a GOLDEN MC bug by survivor bias -- see the // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs` // below same as every other non-`LAST_FRAME` reference. lane-av1refs // widens this from GOLDEN alone to every reference `read_single_ref` // can name. // lane-defer8: SIZE here (spec 7.11.3.3's scale factor), pixels // inside the prediction closure -- the parse thread of a threaded // decode must never wait on a reference picture. let (ref_width, _) = ref_dims(ref_frame, refpix)?; let (mi_row, mi_col) = (rmi, cmi); // lane-rect r2: the mv stack must be queried with the block's // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from // xd->width/xd->height, not a square guess) -- `write_w`/ // `write_h` already name the true HORZ/VERT/HORZ_B strip // footprint (r1's plumbing), so derive bw4/bh4 from those // instead of the old `side`-square (HORZ_B-only) heuristic. let bw4 = write_w / 4; let bh4 = write_h / 4; // spec 7.10.2.8: only reached when the frame header set // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None` // otherwise) -- `cur_offset_0` is this query block's own resolved // `ref_frame`'s distance from the current frame (spec 7.9.3), // recomputed per block since different blocks pick different refs. let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { field: t.field, cur_offset_0: crate::motion_field::get_relative_dist( t.order_hint_bits, t.order_hint, t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, }); let gm_table = build_gm_mv_table( global_motion, mi_row, mi_col, bw4, bh4, allow_high_precision_mv, force_integer_mv, ); let stack = find_mv_stack_with_sign_bias( grid, mi_row, mi_col, bw4, bh4, ref_frame, mi_cols as usize, mi_rows as usize, sign_bias_table, &gm_table, tpl, ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; // lane-interbis r1: which single-ref mode this block resolved to, // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for // the `EC_MODE_VAL` value ladder below. let mut dbg_mode = 16u32; let (mv, is_new_mv) = if !not_new { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): // read at most two `drl_mode` bits, one per stack entry past the // first, stopping at the first `0`. The chosen index selects // which stack entry `read_mv`'s base predictor comes from // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`) // -- entry 0 (`stack.pred_mv`) only when the loop never advances. let mut idx = 0usize; while idx < 2 && stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); ( read_mv( dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, base_mv, allow_high_precision_mv, force_integer_mv, ), true, ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; is_globalmv = !not_zero; let mv = if !not_zero { // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already // computed at this block's own position in `gm_table`. dbg_mode = 15; gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; dbg_mode = if nearest { 13 } else { 14 }; if nearest { stack.nearest_mv } else { // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting // at 1): read at most two more `drl_mode` bits, one per stack // entry past the second, stopping at the first `0`. // `drl_ctx[idx]` is the context between `entries[idx]` and // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is // exactly the pair this index is choosing between. let mut idx = 1usize; while idx < 3 && stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) } }; (mv, false) }; if crate::envflags::env_flag!("EC_TRACE_MODE") { for (i, e) in stack.entries.iter().enumerate() { eprintln!( "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}", e.mv.0, e.mv.1, e.weight ); } eprintln!( "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}", mv.0, mv.1, stack.entries.len(), dec.debug_state().0 ); } // lane-gm r2: the two libaom predicates single-ref GLOBALMV // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and // `is_nontrans_global_motion` (reconinter.h:420-425, model != // TRANSLATION -- IDENTITY counts here -- gating the interp // filter suppress below). Do NOT unify these. let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model; let min_bw_bh4 = bw4.min(bh4); let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2; let gm_nontrans = is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2; if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}", dec.debug_bitpos(), dec.debug_state().0 ); } // lane-sb128 r4: `interintra` (spec 5.11.24; libaom // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed // right after `assign_mv` and before `read_motion_mode` below -- // libaom's own sequential order. `is_interintra_allowed_bsize` // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this // single-ref path: `is_interintra_allowed_ref` always holds here // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and // `is_interintra_allowed_mode` always holds (every mode this // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is // `SINGLE_INTER_MODE_START..END` by construction). // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3. let mut interintra_mode: Option = None; let mut wedge_mask: Option<(&'static [u8], usize)> = None; // lane-inter4 r1: `is_interintra_allowed_bsize` is // `BLOCK_8X8..=BLOCK_32X32` in libaom's enum ORDER, which excludes // every 1:4 shape (BLOCK_8X32 = 18, BLOCK_32X8 = 19) even though // both dimensions are in range -- reading this symbol on a 1:4 // strip is a symbol the reference never wrote. let interintra_shape = write_w.max(write_h) <= 32 && write_w.max(write_h) / write_w.min(write_h) <= 2; if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) && interintra_shape { // lane-inter4 r3: `size_group_lookup` reads the block's // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip // group 2, not their square `side`'s 2/3. let bsize_group = size_group_wh(write_w, write_h); let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1; if interintra { // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode, // then -- gated on block size ALONE, never the // `enable_interintra_wedge` seq bit -- the wedge flag // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32). let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8; // lane-inter16ab r3 (same class as the compound // `compound_type` row below): the row is the block's TRUE // `BLOCK_SIZES_ALL` index -- a 16x8 / 32x16 interintra // strip is BLOCK_16X8 / BLOCK_32X16, not its square // `side`'s BLOCK_16X16 / BLOCK_32X32. let wedge_bsize = bsize_all_index(write_w, write_h) .expect("interintra shape is a BLOCK_SIZES_ALL size"); let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1; if wedge { // lane-wii r2 (spec 5.11.25): `wedge_index` is an // ADAPTING CDF symbol over the same `wedge_bsize` row; // NO sign symbol follows -- libaom fixes // INTERINTRA_WEDGE_SIGN 0 (blockd.h). let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]); hit!(WII_HITS); if let Some(k) = rect_wedge_slot(write_w, write_h) { hit_do! { RECT_WII_HITS.with(|c| { let mut a = c.get(); a[k] += 1; c.set(a); }); } } // lane-inter16ab r5: true-footprint codebook row, // mask padded to stride `max(bw,bh) == side` -- see // the compound site's own comment. wedge_mask = Some(( crate::wedge::wedge_masks() .codebook(write_w, write_h) .mask(0, wedge_index as usize), side, )); } else { hit!(INTERINTRA_HITS); } interintra_mode = Some(ii); } } if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}", dec.debug_bitpos(), dec.debug_state().0 ); } // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24; // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528), // placed right after MV assignment and before the switchable // interp filter read below (`read_mb_interp_filter`, decodemv.c // ~1600) -- libaom's own sequential order. `motion_mode_allowed` // (`reconinter.h`) reduces, for every block this single-ref path // reaches, to "does an inter neighbour border the above row or // left column": `is_motion_variation_allowed_bsize` always holds // (`side` is never below 16px on this path), `ref_frame[1] != // INTRA_FRAME` always holds (no interintra reader here), // `is_motion_variation_allowed_compound` always holds (this is // the single-ref branch), and `is_global_mv_block` never // triggers (this decoder's global motion is always `IDENTITY`, // so its warp `type` is never `> TRANSLATION`). A stream with // `allow_warped_motion=1` is refused right at an eligible block // rather than guessed at: `av1_findSamples`/`num_proj_ref` is // not ported, so this decoder cannot tell a real // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`) // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever // the header allows warp -- reading the wrong alphabet desyncs // the tile. // An interintra block has `ref_frame[1] == INTRA_FRAME`, which // fails libaom's `is_motion_variation_allowed_compound`: the // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied). let motion_mode_eligible = switchable_motion_mode && !skip_mode // `is_motion_variation_allowed_bsize` (blockd.h:1455): // min(bw, bh) >= 8, false for a 16x4 / 4x16 strip. && write_w.min(write_h) >= 8 && interintra_mode.is_none() && has_overlappable_neighbour( grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ) // libaom `motion_mode_allowed`: a GLOBALMV block whose model // is non-IDENTITY-non-TRANSLATION under free (non-integer) // mv reads no motion_mode/obmc symbol at all -- implicit // SIMPLE_TRANSLATION. && !(is_global_mv_block && !force_integer_mv); // lane-t900 r9: the eligibility terms themselves, on the same rung // as aomdec's `EC_ISTEP2 name=motion_mode` -- an eligibility // mismatch is otherwise invisible (a skipped symbol prints // nothing). if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_MM mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} \ ab={} lf={} sw={} skipmode={} ii={} gmb={} rng={}", motion_mode_eligible as u8, overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).len(), overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1).len(), switchable_motion_mode as u8, skip_mode as u8, interintra_mode.is_some() as u8, is_global_mv_block as u8, dec.debug_state().0, ); } let mut obmc_selected = false; // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL // *and* the local warp estimate is valid (`!wm_params.invalid`, // `av1_find_projection`) -- an invalid estimate falls back to // this block's own translational mv, same as any other block // (spec `allow_warp`/`reconinter.c` -- global warp is never the // fallback here since this decoder's global motion is always // IDENTITY). let mut warp_params: Option = None; // Tracks the SYMBOL value, not projection validity: libaom's // `av1_is_interp_needed` suppresses the interp-filter read for // `motion_mode == WARPED_CAUSAL` even when the projection later // falls back to translation. Its third suppressor, // `is_nontrans_global_motion`, matches our unconditional // `is_globalmv` only because this decoder codes global motion as // IDENTITY (non-TRANSLATION) and never reads switchable filters // below 8x8 -- porting TRANSLATION global motion must add the // wmtype check here. let mut warped_selected = false; if motion_mode_eligible { // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4, // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's // strip motion_mode read diverged on the square row. // lane-inter4 r1: every rect shape this decoder can now // reach reads its OWN libaom bsize row (the packed order is // documented on `cdf::MOTION_MODE`); a wrong row is a wrong // interval narrowing, not a wrong value (class // wrong-alphabet-same-value). let bsize_idx = motion_mode_cdf_row(write_w, write_h).ok_or_else(|| { unsupported("a motion_mode symbol for a block shape with no CDF row here") })?; // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf` // instead of the 2-symbol `obmc_cdf` exactly when // `num_proj_ref >= 1` under `allow_warped_motion`. // lane-scaledref r2 + lane-fimv r1: libaom // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH // `!av1_is_scaled(block_ref_scale_factors[0])` and // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL -- // under a scaled reference (superres) OR on a frame whose // header set `force_integer_mv` (screen content) the block // reads the 2-symbol `obmc_cdf`, never the 3-symbol // `motion_mode_cdf`. Reading the wrong alphabet here narrows // the arithmetic coder by the wrong amount and predicts the // rest of the tile off a diverged state: silently wrong // pixels, not a desync error. `force_integer_mv` is the // per-frame value (spec 5.9.2: coded per frame only when // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from // `FrameHeader::force_integer_mv`). // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE || // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here // because a reference whose height differs from this frame's // true size is refused before any tile decodes ("a reference // picture whose height does not match this frame's own true // size", ~14681). Whoever lifts that refusal adds the y term. let ref_is_scaled = mc::scale_factor(ref_width, frame_width) != mc::REF_NO_SCALE; let proj_ok = num_proj_ref( grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame, fctx, ) >= 1; let warp_eligible = allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok; if allow_warped_motion && proj_ok && ref_is_scaled { hit!(SCALED_WARP_SUPPRESSED_HITS); } if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv { hit!(FIMV_ALPHABET_HITS); } if warp_eligible { let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]); match mode { 0 => {} 1 => { obmc_selected = true; hit!(OBMC_HITS); } _ => { warped_selected = true; hit!(WARP_SELECTED_HITS); let mut samples = find_samples( grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame, fctx, ); if crate::envflags::env_flag!("EC_WARP_DEBUG") { eprintln!( "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}", samples.len() ); for (i, s) in samples.iter().enumerate() { eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2); } } if samples.len() > 1 { crate::warp::select_samples(mv, &mut samples, side as i32, side as i32); } warp_params = crate::warp::find_projection( &samples, // lane-rect r2: the block's TRUE dims -- a // 32x16 strip's model center is not a // 32x32's (aom av1_find_projection bw/bh). write_w as i32, write_h as i32, mv.1, mv.0, mi_row as i32, mi_col as i32, ); if crate::envflags::env_flag!("EC_WARP_DEBUG") { eprintln!( "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}", samples.len(), mv.0, mv.1, warp_params ); for (i, s) in samples.iter().enumerate() { eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2); } } } } } else { obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1; if obmc_selected { hit!(OBMC_HITS); } } // lane-t900 r9: which ALPHABET this block read (3-symbol // motion_mode vs 2-symbol obmc) and the range after -- the // two give the same value with a different narrowing (class // wrong-alphabet-same-value). if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_MM2 mi_row={mi_row} mi_col={mi_col} row={bsize_idx} warp_elig={} \ scaled={} fimv={} obmc={} warped={} rng={}", warp_eligible as u8, ref_is_scaled as u8, force_integer_mv as u8, obmc_selected as u8, warped_selected as u8, dec.debug_state().0, ); } } // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` -- // libaom's `av1_init_warp_params` runs for every inter // predictor build, not just a `WARPED_CAUSAL`-selected one. Only // reachable when `warp_params` is still `None` here: a block // that read (and got) local `WARPED_CAUSAL` above already has // `local_warp_allowed && !wm_params.invalid`, which `allow_warp` // checks FIRST and short-circuits on -- the global branch is an // `else if`, never layered on top. `is_global_mv_block` already // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e. // >=8px both dims, matching `av1_init_warp_params`'s // `block_height < 8 || block_width < 8` early return) and, via // `motion_mode_eligible`'s own suppression above, the // `force_integer_mv` case never reads a motion_mode symbol at // all -- checked again here directly since this branch fires // independent of `motion_mode_eligible`. let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid { warp_params = crate::warp::global_warp_params(gm_ref.params); if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine { hit!(AFFINE_GM_HITS); } } if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}", motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0 ); } // spec `get_ref_filter_type`: a neighbour's own filter only feeds // this block's switchable_interp context when that neighbour coded // the SAME reference frame this block is about to read -- a // different-ref neighbour reads as "no neighbour" ([3, 3], the // sentinel `Neighbours::new` already seeds unset slots with), // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME // block next to a LAST_FRAME one inherits that neighbour's filter // choice into its own context, corrupting the symbol it reads. // lane-av1idx r2: also match on the neighbour's SECOND reference // (`above_ref1`/`left_ref1`, real for a compound neighbour) -- // see the 16x16 leaf's own comment above for the spec citation. let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame || neighbours.above_ref1[cmi] == Some(ref_frame) { neighbours.above_filter[cmi] } else { [3, 3] }; let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame || neighbours.left_ref1[rmi] == Some(ref_frame) { neighbours.left_filter[rmi] } else { [3, 3] }; let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, cdfs, interp_fixed, enable_dual_filter, gm_nontrans || warped_selected, above_filter_ctx, left_filter_ctx, false, ); block_filter = resolved_filter; globalmv_for_lf = is_globalmv; if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}", dec.debug_bitpos(), dec.debug_state().0 ); } if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?} motion_mode_eligible={} obmc_selected={} warped={} tell={}", skip as u8, mv.0, mv.1, block_filter, motion_mode_eligible as u8, obmc_selected as u8, warp_params.is_some() as u8, dec.debug_bitpos() ); } // lane-rect r2: see the compound path's matching comment above -- // `grid` must be stamped with the block's true bh4/bw4 span, not // a square `bw4`x`bw4` guess. grid.fill_rect( mi_row, mi_col, bh4, bw4, MiInfo { is_inter: true, ref_frame, // An interintra block records ref_frame[1] == // INTRA_FRAME (0): warp-sample gathering // (libaom av1_findSamples, mvref_common.c:1155) // requires ref_frame[1] == NONE_FRAME, so such a // neighbour must not donate samples or count in // num_proj_ref. ref_frame1: if interintra_mode.is_some() { 0 } else { NO_REF1 }, mv1: (0, 0), mv: mv16(mv), is_new_mv, size: bw4 as u8, size_h: bh4 as u8, is_global_mv0: is_global_mv_block, is_global_mv1: false, }, ); mode_for_tx = 0; uv_predict_mode = DC_PRED; // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA // widths only (r8's derivation) and applies unchanged to the // chroma calls below (their x_q4 is already in the chroma // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC // /interintra counterpart -- those three combinations are refused // by name instead of silently sampling a scaled reference wrong // (warp_params/obmc_selected/interintra_mode are all resolved by // this point, every symbol for this block already read). let luma_scale = mc::scale_factor(ref_width, frame_width); if luma_scale != mc::REF_NO_SCALE { // lane-scaledref r1: libaom `allow_warp` // (av1/common/reconinter.c:41) suppresses BOTH local and // global warp under a scaled reference and predicts // translationally instead -- the fallback below. lane-t900 // r28 LIFTED the refusal that sat here: the mismatch r1 // measured was the 16x4/4x16 strip's sub-8x8 chroma piece, // which this file used to SKIP under a scaled reference // (fixed in the same commit), not the warp fallback. if warp_params.is_some() { hit!(SCALED_WARP_FALLBACK_HITS); } if obmc_selected { hit!(SCALED_OBMC_HITS); } if interintra_mode.is_some() { hit!(SCALED_INTERINTRA_HITS); } } // lane-inter16ab r2: `is_sub8x8_inter`'s neighbour walk reads the // PREVIOUS strip's `mv`/`ref_frame`/`interp_filters` // (reconinter_template.inc:75-82); record them for the next 1:4 // strip, which is the only reader. fctx.inter_last_mc.with(|c| c.set(Some((ref_frame, mv, h_filter, v_filter)))); // lane-defer8: the sub-8x8 chroma piece's own reference resolved to // a SIZE here and to pixels inside the closure, like the block's own. let sub8 = match strip_chroma.filter(|s| s.has_chroma).and_then(|s| s.prev.map(|p| (s.horz, p))) { Some((horz, (prev_ref, prev_mv, prev_h, prev_v))) => { let (prev_width, _) = ref_dims(prev_ref, refpix)?; hit!(INTER16_SUB8_PIECE_HITS); Some(( horz, prev_ref, prev_mv, prev_h, prev_v, mc::scale_factor(prev_width, frame_width), )) } None => None, }; // lane-wave4: the whole-block prediction (motion compensation + // warp + the interintra blend) as a closure, so it runs where the // writes it feeds run. At one reconstruction thread that is right // here on the parsing thread, exactly as before; on the wavefront // it travels with the block's recorded ops and runs on the worker // ([`push_pred`]), which is what takes mc off the parse thread. // OBMC and the sub-8x8 chroma piece stay here: both can fail, and // a recorded op has no way to report it. // lane-defer8: OBMC's neighbour walk reads the mode-info grid and // the neighbour bands, both of which the parse keeps rewriting -- // so the walk happens here and the blend inside the closure. let obmc = if obmc_selected { Some(obmc_plan( grid, &neighbours.above_filter, &neighbours.left_filter, mi_row, mi_col, bw4, bh4, mi_rows as usize, mi_cols as usize, side, write_w, write_h, chroma_side, px, py, cpx, cpy, refpix, interp_fixed, frame_width, )?) } else { None }; let build = move |y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let Some((py_ref, pu_ref, pv_ref)) = ref_planes_deferred(ref_frame, refpix) else { return; }; let mut pred_y = refill(std::mem::take(&mut out[0]), side * side); let mut pred_u = refill(std::mem::take(&mut out[1]), chroma_side * chroma_side); let mut pred_v = refill(std::mem::take(&mut out[2]), chroma_side * chroma_side); if luma_scale == mc::REF_NO_SCALE { mc::predict_with_filters_kern( &py_ref.data, py_ref.width, py_ref.true_width, py_ref.true_height, mv_to_q4(px, mv.1, true), mv_to_q4(py, mv.0, true), side, side, write_w, write_h, h_filter, v_filter, &mut pred_y, fctx, ); mc::predict_with_filters_kern( &pu_ref.data, pu_ref.width, pu_ref.true_width, pu_ref.true_height, mv_to_q4(cpx, mv.1, false), mv_to_q4(cpy, mv.0, false), chroma_side, chroma_side, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut pred_u, fctx, ); mc::predict_with_filters_kern( &pv_ref.data, pv_ref.width, pv_ref.true_width, pv_ref.true_height, mv_to_q4(cpx, mv.1, false), mv_to_q4(cpy, mv.0, false), chroma_side, chroma_side, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut pred_v, fctx, ); } else { mc::predict_scaled_kern( &py_ref.data, py_ref.width, py_ref.true_width, py_ref.true_height, mv_to_q4(px, mv.1, true), mv_to_q4(py, mv.0, true), luma_scale, side, side, write_w, write_h, h_filter, v_filter, &mut pred_y, fctx, ); mc::predict_scaled_kern( &pu_ref.data, pu_ref.width, pu_ref.true_width, pu_ref.true_height, mv_to_q4(cpx, mv.1, false), mv_to_q4(cpy, mv.0, false), luma_scale, chroma_side, chroma_side, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut pred_u, fctx, ); mc::predict_scaled_kern( &pv_ref.data, pv_ref.width, pv_ref.true_width, pv_ref.true_height, mv_to_q4(cpx, mv.1, false), mv_to_q4(cpy, mv.0, false), luma_scale, chroma_side, chroma_side, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut pred_v, fctx, ); } // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41) // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local // (`wm_params`) and global warp fall back to the translational // prediction above when the reference is scaled, even though the // motion_mode symbol was still read and warp_params still // resolved. Suppress the warp, keep every symbol read. if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) { // `av1_init_warp_params` is per PLANE: the luma plane's // own block is `write_w`x`write_h` (a PARTITION_HORZ/VERT // strip is not `side`x`side`), so a strip under 8 px in // either direction keeps the translational prediction too. if warp_plane_allowed(write_w, write_h) { crate::warp::warp_affine( params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32, py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32, side as i32, side as i32, 0, 0, fctx, ); } // libaom `av1_init_warp_params` (reconinter.c): warp is // per PLANE and bails out at `block_width < 8 || // block_height < 8`, so a plane whose own block is under // 8x8 keeps the translational prediction built above -- // in 420 that is every chroma plane whose own width or // height is under 8 -- `write_chroma_w`/`write_chroma_h`, // NOT the square `chroma_side` (lane-t900 r5: an 8x16 luma // block has `chroma_side == 8` but a 4x8 chroma block, so // the square side warped chroma libaom predicts // translationally; lane-gmaffine r4 for the 8x8 leaf). if warp_plane_allowed(write_chroma_w, write_chroma_h) { crate::warp::warp_affine( params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32, pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1, fctx, ); crate::warp::warp_affine( params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32, pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1, fctx, ); } } // Mutually exclusive with warp/OBMC (motion_mode is not read for // an interintra block): blend the intra predictor over the MC // result, all planes (reconinter.c av1_build_interintra_predictor // plane loop). if let Some(ii) = interintra_mode { if write_w != write_h { hit!(INTERINTRA_RECT_HITS); } interintra_blend(y, px, py, write_w, write_h, side, ii, wedge_mask, &mut pred_y, fctx); interintra_blend( u, cpx, cpy, write_chroma_w, write_chroma_h, chroma_side, ii, wedge_mask, &mut pred_u, fctx, ); interintra_blend( v, cpx, cpy, write_chroma_w, write_chroma_h, chroma_side, ii, wedge_mask, &mut pred_v, fctx, ); } if let Some(plan) = &obmc { obmc_run(plan, refpix, &mut pred_y, &mut pred_u, &mut pred_v, fctx); } // lane-inter16ab r2: libaom `build_inter_predictors_sub8x8` // (reconinter_template.inc:87-160). A 4:2:0 chroma block under a // 16x4 (4x16) luma pair covers TWO luma blocks, so it is built in // `b4_w x b4_h` = 8x2 (2x8) pieces, each from its own strip's // mv/ref/filters. The bottom (right) piece is this strip's own mv // over its own rows, which the whole-block prediction above // already wrote there (MC is position-invariant for a fixed mv), // so only the FIRST piece has to be rebuilt -- and only when // `is_sub8x8_inter` holds. lane-t900 r28: it scales off the // PREVIOUS strip's own reference, not this block's. if let Some((horz, prev_ref, prev_mv, prev_h, prev_v, prev_scale)) = sub8 { let Some((_, prev_u, prev_v_plane)) = ref_planes_deferred(prev_ref, refpix) else { return; }; let (piece_w, piece_h) = if horz { (8usize, 2usize) } else { (2usize, 8usize) }; for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] { let mut piece = vec![0u16; piece_w * piece_h]; mc::predict_maybe_scaled( &src.data, src.width, src.true_width, src.true_height, mv_to_q4(cpx, prev_mv.1, false), mv_to_q4(cpy, prev_mv.0, false), prev_scale, piece_w, piece_h, prev_h, prev_v, &mut piece, fctx, ); for row in 0..piece_h { dst[row * chroma_side..row * chroma_side + piece_w] .copy_from_slice(&piece[row * piece_w..(row + 1) * piece_w]); } } } *out = [pred_y, pred_u, pred_v]; }; // OBMC and interintra are mutually exclusive (`motion_mode` is // never read for an interintra block), so blending interintra // inside `build` and OBMC after it is still the coded order. debug_assert!(!(obmc_selected && interintra_mode.is_some())); // lane-defer8: OBMC and the sub-8x8 piece now live inside `build`, // so nothing about this block keeps its prediction on this thread. let deferred = recon_deferred(fctx); let (pred_y, pred_u, pred_v): (Vec, Vec, Vec); let (sy, su, sv) = if deferred { // The interintra predictor inside `build` reads this block's // own above/left edges: by the wavefront rule ((r-1, c+1) and // (r, c-1) complete) and this superblock's own ops replaying // in push order ahead of it, they are written by the time the // worker runs it -- which retires the `flush_recon` barrier // this arm used to take for interintra. push_pred(fctx, build); ( Pred::Cur { plane: 0, stride: side, off: 0 }, Pred::Cur { plane: 1, stride: chroma_side, off: 0 }, Pred::Cur { plane: 2, stride: chroma_side, off: 0 }, ) } else { if interintra_mode.is_some() { flush_recon(fctx, y, u, v); } let mut built: [Vec; 3] = Default::default(); build(y, u, v, fctx, &mut built); let [by, bu, bv] = built; (pred_y, pred_u, pred_v) = (by, bu, bv); // lane-inter16ab r2: libaom `build_inter_predictors_sub8x8` // (reconinter_template.inc:87-160). A 4:2:0 chroma block under a // 16x4 (4x16) luma pair covers TWO luma blocks, so it is built in // `b4_w x b4_h` = 8x2 (2x8) pieces, each from its own strip's // mv/ref/filters. The bottom (right) piece is this strip's own mv // over its own rows, which the whole-block prediction above // already wrote there (MC is position-invariant for a fixed mv), // so only the FIRST piece has to be rebuilt -- and only when // `is_sub8x8_inter` holds, i.e. the previous strip was itself a // single-reference inter block (`prev`), else libaom falls // through to the ordinary whole-block predictor. ( Pred::Inline(&pred_y, side), Pred::Inline(&pred_u, chroma_side), Pred::Inline(&pred_v, chroma_side), ) }; // lane-inter4 r2: a rectangular strip's transform tree starts from // its own rect `max_txsize_rect_lookup` entry, not a square one. let rect_tu = (write_w, write_h) != (side, side); vartx_leaves = if rect_tu { read_block_tx_size_rect( dec, cdfs, neighbours, at_mi, (write_w, write_h), (mi_cols as usize, mi_rows as usize), skip, fctx, )? } else { read_block_tx_size( dec, cdfs, neighbours, at_mi, side, (mi_cols as usize, mi_rows as usize), true, skip, fctx, )? .1 }; if skip { push_mc_rect(0, px, py, side, write_w, write_h, sy, &ZERO_RESIDUAL[..side * side], fctx, ); if has_chroma { push_mc_rect(1, cpx, cpy, chroma_side, write_chroma_w, write_chroma_h, su, &ZERO_RESIDUAL[..chroma_side * chroma_side], fctx, ); push_mc_rect(2, cpx, cpy, chroma_side, write_chroma_w, write_chroma_h, sv, &ZERO_RESIDUAL[..chroma_side * chroma_side], fctx, ); } luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(chroma_side * chroma_side); v_grid = Grid::Zero(chroma_side * chroma_side); } else { // lane-inter4 r2: a rect strip's coefficient context spans its // OWN width above and height left -- reading `side` cells both // ways indexes past the tile's last mi row for a bottom strip. let around = if rect_tu { neighbours.around_mi_rect(at_mi, write_w, write_h) } else { neighbours.around_mi(at, side) }; // lane-inter16ab r2: the pair's chroma transform sits at the // EVEN strip's mi origin and spans both strips, so its // above/left coefficient context is the pair's, not this // strip's row. let around_c = match strip_chroma { Some(s) if s.has_chroma => neighbours.around_mi_rect( s.pair_mi, if s.horz { 16 } else { 8 }, if s.horz { 8 } else { 16 }, ), _ => around, }; let luma_tx_type; // lane-sb128c r1: a 128x128 inter block's four chroma units // are read INSIDE the luma leaf loop (one per 64x64 mu chunk); // these collect them for the block-level neighbour write-back. let mut u_units: Vec = Vec::new(); let mut v_units: Vec = Vec::new(); if let Some(leaves) = vartx_leaves.as_ref() { // spec 5.11.17's transform tree, leaf by leaf in the order // `read_var_tx_size` coded it: each unit reads its own // coefficients against the neighbour magnitudes the // earlier units already wrote, and reconstructs over its // own slice of the block's motion-compensated predictor. let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); let mut first_tx_type = TxType::DctDct; for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() { let tu_mi = (at_mi.0 + row, at_mi.1 + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); let (tu_grid, tu_tx_type) = if tw == th { let tx_px = tw; let tu_pred = sy.offset(row * MI * side + col * MI); let scan = default_scan(tx_px.min(32)); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI); read_inter_plane( dec, cdfs, inter_txbset_for(tx_px, reduced), &scan, 0, neighbours.around_mi(tu_mi, tx_px)[0], mode_for_tx, y, tu_px, tu_py, tx_px, base_q_idx, tu_pred, None, Some(tu_skip_ctx), fctx, )? } else { // lane-r14 r3: a 1:4 strip's `sub_tx_size_map` // sub-transform is RECTANGULAR (TX_64X16 -> // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is // read with the rect coefficient machinery, at its // own `txb_skip_ctx`/neighbour spans -- the unit is // smaller than its block, so `get_txb_ctx_general`'s // neighbour table applies, not the lone-TU 0. vartx_rect_leaf_hit(tw, th); let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI); let start = row * MI * side + col * MI; read_inter_plane_rect( dec, cdfs, rect_inter_luma_set(tw, th, fctx)?, (tw, th), side, 0, neighbours.around_mi_rect(tu_mi, tw, th)[0], mode_for_tx, y, tu_px, tu_py, sy.offset(start), None, Some(tu_skip_ctx), fctx, )? }; if idx == 0 { first_tx_type = tu_tx_type; } neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid); // lane-sb128c r1: libaom's `decode_token_recon_block` // walks 64x64 "mu" chunks (`mu_blocks_wide/high = // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of // a chunk before the next one, so a 128x128 block // interleaves Y,U,V per quadrant -- the same order the // intra 128 path reads (lane-sb128b r3, measured // against aomdec's `EC_TRACE_COEFF`). Below 128 a block // is a single chunk and this never fires. if side > 64 { let chunk = (row / 16, col / 16); let done = idx + 1 == leaves.len() || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk; if done { let (cr, cc) = chunk; // `av1_get_max_uv_txsize(BLOCK_128X128)` = // `av1_get_adjusted_tx_size(TX_64X64)` = // TX_32X32: one 32x32 chroma unit per chunk. let cu_tx = 32usize; let luma_span = cu_tx * 2; let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16); let cu_around = neighbours.around_mi(cu_mi, luma_span); let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx); let cu_scan = default_scan(cu_tx); for plane_idx in 1..3 { let (src, buf) = if plane_idx == 1 { (su, &mut *u) } else { (sv, &mut *v) }; let cu_pred = src.offset(cr * cu_tx * chroma_side + cc * cu_tx); let cu_grid = read_inter_plane( dec, cdfs, chroma_set, &cu_scan, plane_idx, cu_around[plane_idx], mode_for_tx, buf, cu_x, cu_y, cu_tx, base_q_idx, cu_pred, Some(first_tx_type), Some(3), fctx, )? .0; // Immediately, so the NEXT chunk's unit // reads this one's coefficient context. neighbours.record_mi_chroma( cu_mi, luma_span, luma_span, plane_idx, &cu_grid, ); hit!(CHROMA_SPLIT_TX_HITS); mu_chroma = true; let dst = mu_units( if plane_idx == 1 { &mut u_units } else { &mut v_units }, chroma_side * chroma_side, ); for rr in 0..cu_tx { let start = (cr * cu_tx + rr) * chroma_side + cc * cu_tx; dst[start..start + cu_tx] .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]); } } } } } // `av1_get_tx_type`'s chroma lookup scales the chroma // position back to luma, so an inter block's chroma // inherits the *first* (top-left) luma unit's coded type. luma_tx_type = first_tx_type; luma_grid = Grid::Zero(side * side); } else if rect_tu { // The whole-block rectangular transform unit // (`txfm_partition` said 0 at depth 0). let (grid, tx_type) = read_inter_plane_rect( dec, cdfs, rect_inter_luma_set(write_w, write_h, fctx)?, (write_w, write_h), side, 0, around[0], mode_for_tx, y, px, py, sy, None, None, fctx, )?; luma_tx_type = tx_type; luma_grid = Grid::Own(embed_rect_grid(&grid, write_w, write_h, side)); } else { { let coded = read_inter_plane( dec, cdfs, luma_set_inter, scan_luma, 0, around[0], mode_for_tx, y, px, py, side, base_q_idx, sy, None, None, fctx, )?; luma_grid = coded.0; luma_tx_type = coded.1; } } if !has_chroma { // `is_chroma_reference` is false for this strip: libaom's // plane loop (decodeframe.c // `predict_and_reconstruct_intra_block`/ // `reconstruct_inter_block`'s `for (plane...)` guarded by // `xd->is_chroma_ref`) codes NO chroma transform here, so // neither symbol nor context exists. u_grid = Grid::Zero(chroma_side * chroma_side); v_grid = Grid::Zero(chroma_side * chroma_side); } else if side > 64 { // Already read inside the mu-chunk loop above -- at the 128 // root a rect (128x64/64x128) block's chroma is per mu // chunk too, so this test comes BEFORE the `rect_tu` one. u_grid = if u_units.is_empty() { Grid::Zero(chroma_side * chroma_side) } else { Grid::Own(std::mem::take(&mut u_units)) }; v_grid = if v_units.is_empty() { Grid::Zero(chroma_side * chroma_side) } else { Grid::Own(std::mem::take(&mut v_units)) }; } else if rect_tu { // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a // 2:1 strip is the strip's own rect chroma size (16x8 / // 8x16), one unit for the whole block, and it codes no // `tx_type` symbol -- it inherits the luma unit's. let (uw, uh) = (write_chroma_w, write_chroma_h); u_grid = Grid::Own(embed_rect_grid( &read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(write_chroma_w, write_chroma_h)?, (uw, uh), chroma_side, 1, around_c[1], mode_for_tx, u, cpx, cpy, su, Some(luma_tx_type), None, fctx, )? .0, uw, uh, chroma_side, )); v_grid = Grid::Own(embed_rect_grid( &read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(write_chroma_w, write_chroma_h)?, (uw, uh), chroma_side, 2, around_c[2], mode_for_tx, v, cpx, cpy, sv, Some(luma_tx_type), None, fctx, )? .0, uw, uh, chroma_side, )); } else { u_grid = read_inter_plane( dec, cdfs, chroma_set, scan_chroma, 1, around[1], mode_for_tx, u, cpx, cpy, chroma_side, base_q_idx, su, Some(luma_tx_type), None, fctx, )? .0; v_grid = read_inter_plane( dec, cdfs, chroma_set, scan_chroma, 2, around[2], mode_for_tx, v, cpx, cpy, chroma_side, base_q_idx, sv, Some(luma_tx_type), None, fctx, )? .0; } } } } else { // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs // its own true-width/height edge/predict math, unlike the inter // skip path above (which only needed a clipped write of an // already-square-predicted buffer). Named refusal instead of a // silently wrong square-shaped intra prediction. // lane-inter16ab r2: `decode_intra_rect_in_inter` has no chroma-pair // path (it predicts and codes chroma at the strip's own halved // footprint), so an INTRA 16x4 / 4x16 strip inside a 1:4 partition is // refused by name rather than decoded with a 8x2 chroma transform // libaom never coded. // lane-intra16x4 r1: the strip DECODES through the key frame's own // per-strip body, [`decode_rect4_16_strip`]. // lane-sub8x4 r3: pixel-proven, so the decode opt-in was lifted. r1 // and r2 found no witness because every firing film frame ALSO carried // a sub-8x8 intra block, which refused until r2 lifted it; on this tip // the first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode // all 33 frames pixel-exact while this arm fires 31x 16x4 + 17x 4x16 // (23 of them chroma-paired). Pinned as // `fixtures/reelb_rect64_intra16x4_witness.obu` -- MEASURED WRONG, see // the lane-wit16x4 note below. // The refusal below is NARROWED, not deleted: it still stands for a // 16x4/4x16 strip with no chroma-pair record and for every other // sub-8 shape. // // lane-wit16x4 r1: RE-WIDENED to the whole shape, because r3's witness // was a PHANTOM (class `counter-from-refused-stream`): the pinned // fixture was measured while decode-order frame 33 was desynced, and // on the merged tip (lane-frame36 r2 fixed that desync) the very same // fixture decodes all 33 frames pixel-exact with `intra16x4_in_inter` // 16x4=0 4x16=0 chroma_ref=0 -- the 31/17/23 were counted out of a // wrong decode. Re-measured this round: NO stream anywhere decodes // exactly while this arm fires. Two 2 s 10-bit film cuts (3840x1608 at // 0 s: OK, 48 frames exact, 0 hits; at 300 s: 138/559 hits but frames // 1 and 2 mismatch ffmpeg by 14105680 / 12470780 bytes), four 1920x792 // 128-SB cuts (hits only inside frames that refuse or are never shown // -- the 6300 s cut's key frame is exact with 0 hits and its no-show // frame 1 carries 169/445 with no display frame reachable before the // 128x64-intra-on-inter refusal), and the aomenc gate // `a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact` // (run `--include-ignored` on this tip: FAILED, 0 pixel-exact attempts // carrying the strip, per-arm [0, 0, 0]). A lifted refusal with no // witness is a capability claim (class `refusal-lifted-without-a-gate`), // so the decode path stayed behind an opt-in for the round that found // a witness. // // lane-t900 r6: THAT WITNESS EXISTS, so the opt-in was lifted (the path decodes by default) // and the refusal is narrowed back to "no chroma-pair record". The // witness is a REAL 10-bit 1920x792 128-superblock film stream, not an // aomenc recipe: `fixtures/reelc_sb128_inter_witness.obu` (177773 bytes, // 23 frame-carrying OBUs, 16 decode-order frames, extended from 14 in // lane-t900 r7) decodes all 16 decode-order frames byte-exact against // instrumented aomdec // (`EC_AV1_FINAL_DUMP`) and all 15 shown frames pixel-exact against // ffmpeg, while this arm fires 78x 16x4 + 149x 4x16 (108 of them // chroma-paired). Unlike lane-sub8x4 r3's phantom (class // `counter-from-refused-stream`) every one of those hits lies inside a // frame that was decoded AND compared exact. Gate // `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact`. let strip16 = strip_chroma .filter(|_| write_w.min(write_h) == 4 && write_w.max(write_h) == 16) .map(|s| (s.horz, s.has_chroma)); if write_w.min(write_h) < 8 && strip16.is_none() { if crate::envflags::env_flag!("EC_INTRA16X4") { let (idx, hc, prev_inter) = match strip_chroma { Some(s) => ( if s.horz { rmi - s.pair_mi.0 } else { cmi - s.pair_mi.1 }, s.has_chroma, s.prev.is_some(), ), None => (9, true, false), }; eprintln!( "EC_INTRA16X4 w={write_w} h={write_h} pair_parity={idx} has_chroma={hc} prev_single_inter={prev_inter} skip={skip} mi={rmi},{cmi} tx_select={} scr={}", fctx.tx_select_inter.with(std::cell::Cell::get), allow_screen_content_tools, ); } return Err(unsupported( "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)", )); } if write_w != side || write_h != side { // lane-intrarect r1: the strip decodes through its own rect // machinery ([`decode_intra_rect_in_inter`] -> the key-frame // paths' [`decode_rect_split`]) instead of refusing. That call // already writes everything the shared tail below would for a // square block EXCEPT the inter-side bands and the mi map, so // this arm returns rather than falling through (a second // `record_rect`/`fill_lf_grid_rect` at block granularity would // overwrite the per-transform-unit records it just made). decode_intra_rect_in_inter( dec, cdfs, neighbours, at, write_w, write_h, skip, allow_screen_content_tools, strip16, y, u, v, base_q_idx, fctx, )?; // merge b51719f+lane-intrarect: `at` is in MI units on this path // (lane-inter4), so the strip's mi origin is `at` itself -- the // lane's `r * SUB_MI` re-derivation would snap a sub-SUB strip to // its enclosing 16-px cell. let (mi_r0, mi_c0) = (rmi, cmi); grid.fill_rect( mi_r0, mi_c0, write_h / MI, write_w / MI, MiInfo { is_inter: false, ref_frame: -1, ref_frame1: NO_REF1, mv1: (0, 0), mv: (0, 0), is_new_mv: false, size: (write_w / MI) as u8, size_h: (write_h / MI) as u8, is_global_mv0: false, is_global_mv1: false, }, ); neighbours.record_inter_rect_mi( at, write_w / MI, write_h / MI, skip, false, 0, [3, 3], skip_mode, ); return Ok(()); } let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]); if crate::envflags::env_flag!("EC_IIS") { eprintln!( "TRACE iis px={px} py={py} side={side} w={write_w} h={write_h} sg={} mode={mode} skip={skip}", size_group_wh(write_w, write_h) ); } if mode >= 13 { return Err(unsupported( "an intra mode this decoder does not code (round 2)", )); } // lane-angleinter r1: `read_intra_angle_info` (libaom `decodemv.c`, // inside `read_intra_block_mode_info`) -- an intra block in an inter // frame reads `angle_delta_y` off the same // `angle_delta_cdf[mode - V_PRED]` row a key-frame block does, and // the delta feeds the directional predictor (and the edge // filter/upsample decision derived from the delta'd angle) unchanged. // The symbol was read and then refused before this round even though // aomenc enables `--enable-angle-delta` by default. let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) } else { 0 }; if angle_delta_y != 0 { hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS); } // The delta'd angle decides whether the intra edge filter runs at // all, so this block needs the same luma edge-filter-type neighbour // check a key-frame block does (`get_intra_edge_filter_type`, spec // 7.11.2) -- this arm passed a hardcoded `false` while every // directional intra-in-inter block was refused above. let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); // lane-sbrect10 r1 (class wrong-alphabet-same-value, second instance // after lane-sbpart r3's rect strips): `is_cfl_allowed` (libaom // `blockd.h` -- `block_size_wide[bsize] <= 32 && block_size_high[bsize] // <= 32`, spec 5.11.5) caps CFL at 32x32, so a 64x64 intra block inside // an INTER frame reads the 13-symbol `uv_mode_no_cfl` alphabet. Reading // the 14-symbol CFL one gave the same DC_PRED VALUE but narrowed the // arithmetic coder by the wrong interval, desyncing the tile from this // block on. let cfl_allowed = write_w.max(write_h) <= 32; if !cfl_allowed { hit!(NOCFL_UV_MODE_HITS); } let uv_mode = if cfl_allowed { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; if (9..=12).contains(&uv_mode) { hit!(SMOOTH_UV_HITS); } let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for // the angle-delta question, same as [`read_intra_mode`]'s own copy // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the // `else` branch below is exact for it either way. let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { hit!(DIRECTIONAL_UV_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; if angle_delta_uv != 0 { hit!(UV_ANGLE_DELTA_HITS); hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS); } uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; // lane-chroma r4: same chroma edge-filter-strength neighbour check // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA // neighbour's own `uv_mode`, not the luma one. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c); // `read_palette_mode_info` (decodemv.c:567, called from // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same // gating and same corner-cut as `read_intra_mode`'s own copy above // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably // safe since a nonzero neighbour `palette_size` would already have // refused the decode that produced it. // lane-inter16ab r4 (class sweep): `av1_get_palette_bsize_ctx` is keyed // by the block's TRUE footprint -- a rect strip's row is not its // enclosing square's, and a 16x4 strip (64 pixels) reads no palette // symbol at all. // lane-t900 r22: reconstructed, not refused. Same syntax and same // deferral of the colour-index maps past `filter_intra` // (`av1_visit_palette` runs from `parse_decode_block`, after the whole // mode-info read) as the key frame's [`read_intra_mode`]; the mode // context and colour cache are this block's real above/left ones, at // its own mi position (`av1_get_palette_mode_ctx`/ // `av1_get_palette_cache`), not the hardcoded 0/empty pair the refusal // could get away with while no neighbour could ever be a palette. let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((rmi, cmi)); let palette_uv_cache = neighbours.palette_uv_cache_mi((rmi, cmi)); let mut palette_y_pending: Option<(usize, [u16; 8])> = None; let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(write_w, write_h) { let use_palette_y = mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0; if use_palette_y { let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx))); } if crate::envflags::env_flag!("EC_PALSYN") { eprintln!("EC_PALSYN_PRE sq mi={rmi},{cmi} bw={write_w} bh={write_h} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} rng={}", palette_y_pending.map_or(0, |(n, _)| n), dec.debug_state().0); } let use_palette_uv = uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; if crate::envflags::env_flag!("EC_PALSYN") { eprintln!("EC_PALSYN sq mi={rmi},{cmi} bw={write_w} bh={write_h} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", use_palette_y as i32, use_palette_uv as i32, dec.debug_state().0); } if use_palette_uv { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx); palette_uv_pending = Some((n, u_colors, v_colors)); } } // lane-fiinter r1: `read_filter_intra_mode_info` (libaom `decodemv.c`, // the tail of `read_intra_block_mode_info`) -- an intra block inside // an INTER frame reads `use_filter_intra` in exactly the same place a // key-frame block does, right after the palette syntax. Nothing read // it here before this round, and aomenc enables filter intra by // default, so every inter frame carrying one desynced at this symbol. // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied: // a real palette-Y block already returned above. let mut filter_intra = None; if mode == DC_PRED && fctx.enable_filter_intra_inter.with(std::cell::Cell::get) // `av1_filter_intra_allowed` (reconintra.h:77) excludes a // palette-Y block, so no `use_filter_intra` symbol exists there. && palette_y_pending.is_none() // lane-inter16ab r4 (class sweep): `cdf::FILTER_INTRA`'s row is the // true `BLOCK_SIZES_ALL` class of this strip, not its square side's. && let Some(class) = filter_intra_size_class_rect(write_w, write_h) && dec.symbol(&mut cdfs.filter_intra[class]) != 0 { hit!(FILTER_INTRA_HITS); hit!(INTRA_IN_INTER_FILTER_INTRA_HITS); filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode)); } // `av1_visit_palette`: the two colour-index maps, Y then the shared // chroma one, after the WHOLE mode-info read. let palette_y = palette_y_pending.map(|(n, colors)| { let map = decode_color_index_map_wh(dec, cdfs, n, write_w, write_h, false); hit!(PALETTE_HITS); hit!(INTRA_IN_INTER_PALETTE_Y_HITS); PaletteY { size: n, colors, map } }); let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { // `av1_get_plane_block_size(bsize, 1, 1)` floors at the 4-px // transform, as the rect reader's own copy. let (cw, ch) = ((write_w / 2).max(4), (write_h / 2).max(4)); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true); hit!(PALETTE_UV_HITS); hit!(INTRA_IN_INTER_PALETTE_UV_HITS); PaletteUv { size: n, u_colors, v_colors, map } }); palette_record = ( palette_y.as_ref().map_or(0, |p| p.size), palette_y.as_ref().map_or([0u16; 8], |p| p.colors), palette_uv.as_ref().map_or(0, |p| p.size), palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors), ); // A palette block predicts from its own colour-index map, never from // the block edge (spec 7.11.2/7.11.4) -- these ride the [`PALETTE_PRED`] // slot into each `reconstruct`/`read_plane` call below, exactly as the // key-frame paths do. let palette_y_buf: Option> = palette_y.as_ref().map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }); mode_for_tx = mode; block_filter = [3, 3]; ref_frame_for_lf = 0; globalmv_for_lf = false; let (mi_row, mi_col) = (rmi, cmi); grid.fill_rect( mi_row, mi_col, side / 4, side / 4, MiInfo { is_inter: false, ref_frame: -1, ref_frame1: NO_REF1, mv1: (0, 0), mv: (0, 0), is_new_mv: false, size: (side / 4) as u8, size_h: (side / 4) as u8, is_global_mv0: false, is_global_mv1: false, }, ); // lane-intrainter r1: an intra block in an inter frame reads the same // `tx_depth` symbol a key-frame block does, and when it splits, the // block codes one intra prediction + one coefficient set PER // transform unit (`decode_block`'s multi-TU branch), not one for the // whole block. The leaf list rides the existing `vartx_leaves` slot, // whose tail already does the split-block neighbour write-back // (`record_split_luma`) and the per-TU deblock edges. vartx_leaves = read_block_tx_size( dec, cdfs, neighbours, at_mi, side, (mi_cols as usize, mi_rows as usize), false, skip, fctx, )? .1; let reach = Reach::of(side, px, py, y.width, y.height, fctx); let split_luma = vartx_leaves.is_some(); // lane-sb128c r3: a 128x128 INTRA block inside an inter frame codes // its chroma per 64x64 mu chunk, exactly as the inter half above -- // `decode_token_recon_block` walks `mu_blocks_wide/high` and codes // every plane of a chunk before the next chunk's luma. These collect // the four TX_32X32 units per plane for the block-level write-back. let mut u_units: Vec = Vec::new(); let mut v_units: Vec = Vec::new(); if let Some(leaves) = vartx_leaves.as_ref() { let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); for (idx, &(row, col, tx_px, _)) in leaves.iter().enumerate() { let tu_mi = (at_mi.0 + row, at_mi.1 + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); // A transform unit inside a block is not a block at that // position (class from lane-palette2 r12): top-right / // bottom-left availability is the block's, narrowed by the // unit's own offset inside it. let tu_reach = Reach::of_tu(side, side, col * MI, row * MI, tx_px, tx_px, reach); // This unit's own window on the block's palette prediction // (the whole-block buffer would be indexed at the wrong // stride by the first unit). if let Some(buf) = &palette_y_buf { hit!(PALETTE_SPLIT_TX_HITS); let window: Vec = (0..tx_px) .flat_map(|i| { let base = (row * MI + i) * side + col * MI; buf[base..base + tx_px].iter().copied() }) .collect(); set_palette_pred(window, fctx); } let tu_grid = if skip { push_intra(0, tu_px, tu_py, tx_px, mode, angle_delta_y, tu_reach, &ZERO_RESIDUAL[..tx_px * tx_px], None, filter_intra, smooth_neighbor, fctx, ); Grid::Zero(tx_px * tx_px) } else { // The unit's bsize is smaller than the block it sits in, // so `txb_skip_ctx` is the neighbour-magnitude table, not // the lone-TU 0 (`get_txb_ctx_general`). let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI); read_plane( dec, cdfs, txbset_for(tx_px, reduced), // lane-sb128c r5: a TX_64X64 unit codes only its // top-left 32x32 of frequencies (spec 5.11.40), so // the scan and `tx_side` are the CODED corner while // `side` stays the transform's true 64. default_scan(tx_px.min(32)), 0, neighbours.around_mi(tu_mi, tx_px)[0], mode, mode, angle_delta_y, tu_reach, y, tu_px, tu_py, tx_px, tx_px.min(32), base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )? }; neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid); if side > 64 { let chunk = (row / 16, col / 16); let done = idx + 1 == leaves.len() || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk; if !done { continue; } let (cr, cc) = chunk; // `av1_get_max_uv_txsize(BLOCK_128X128)` = // `av1_get_adjusted_tx_size(TX_64X64)` = TX_32X32. let cu_tx = 32usize; let luma_span = cu_tx * 2; let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16); let cu_around = neighbours.around_mi(cu_mi, luma_span); let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx); let cu_reach = crate::decode::tu_reach( side, side, cc * luma_span, cr * luma_span, luma_span, reach, px, py, y.width, y.height, fctx, ); let cu_scan = default_scan(cu_tx); for plane_idx in 1..3 { let buf: &mut PlaneBuf<'static> = if plane_idx == 1 { &mut *u } else { &mut *v }; let cu_grid = if skip { push_intra(plane_idx, cu_x, cu_y, cu_tx, uv_predict_mode, angle_delta_uv, cu_reach, &ZERO_RESIDUAL[..cu_tx * cu_tx], None, None, smooth_neighbor_uv, fctx, ); Grid::Zero(cu_tx * cu_tx) } else { read_plane( dec, cdfs, chroma_set, &cu_scan, plane_idx, cu_around[plane_idx], mode, uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y, cu_tx, cu_tx, base_q_idx, // CfL is refused above 32x32 // (`is_cfl_allowed`), so never here. None, None, // The uv plane block (64x64) is larger than // the unit (32x32): `get_txb_ctx`'s offset-10 // rows, +3 on the `txb_skip_chroma_32` table // (lane-sb128b r3). Some(3), smooth_neighbor_uv, fctx, )? }; // Immediately, so the NEXT chunk's unit reads this // one's coefficient context. neighbours.record_mi_chroma( cu_mi, luma_span, luma_span, plane_idx, &cu_grid, ); hit!(CHROMA_SPLIT_TX_HITS); let dst = mu_units( if plane_idx == 1 { &mut u_units } else { &mut v_units }, chroma_side * chroma_side, ); for rr in 0..cu_tx { let start = (cr * cu_tx + rr) * chroma_side + cc * cu_tx; dst[start..start + cu_tx] .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]); } } } } } if side > 64 { // Chroma is already coded and reconstructed per mu chunk above. luma_grid = Grid::Zero(side * side); u_grid = if u_units.is_empty() { Grid::Zero(chroma_side * chroma_side) } else { Grid::Own(std::mem::take(&mut u_units)) }; v_grid = if v_units.is_empty() { Grid::Zero(chroma_side * chroma_side) } else { Grid::Own(std::mem::take(&mut v_units)) }; hit!(INTRA_128_IN_INTER_HITS); } else if skip { if !split_luma { if let Some(buf) = &palette_y_buf { set_palette_pred(buf.clone(), fctx); } push_intra(0, px, py, side, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..side * side], None, filter_intra, smooth_neighbor, fctx, ); } let ac = alpha.map(|_| cfl_src(px, py, side)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra(1, cpx, cpy, chroma_side, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..chroma_side * chroma_side], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra(2, cpx, cpy, chroma_side, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..chroma_side * chroma_side], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(chroma_side * chroma_side); v_grid = Grid::Zero(chroma_side * chroma_side); } else { let around = neighbours.around_mi(at, side); if split_luma { // Already coded and reconstructed unit by unit above; the // block-level grid is only the neighbour write-back's input, // which `record_split_luma` ignores for plane 0. luma_grid = Grid::Zero(side * side); } else { if let Some(buf) = &palette_y_buf { set_palette_pred(buf.clone(), fctx); } luma_grid = read_plane( dec, cdfs, luma_set_intra, scan_luma, 0, around[0], mode, mode, angle_delta_y, reach, y, px, py, side, luma_tx, base_q_idx, None, filter_intra, None, smooth_neighbor, fctx, )?; } let ac = alpha.map(|_| cfl_src(px, py, side)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } u_grid = read_plane( dec, cdfs, chroma_set, scan_chroma, 1, around[1], mode, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, chroma_side, chroma_tx, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } v_grid = read_plane( dec, cdfs, chroma_set, scan_chroma, 2, around[2], mode, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, chroma_side, chroma_tx, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; } } // lane-comppin r9: end-of-block checkpoint -- everything between // post_assign_mv and here (interintra, motion_mode, interp_filter, then // every plane's coeffs) is unproven; a range mismatch here vs aomdec's // equivalent post-content point (added at the matching call site) // narrows the ladder to this block's own tail instead of the next // block's partition read. if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL mi_row={} mi_col={} label=block_end tell={} range={}", rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } // lane-inter16ab r2: the pair's chroma coefficient context spans BOTH // strips (mirroring the intra `decode_rect4_16` path), and the even // strip's own record wrote empty chroma state over those cells -- this // rewrite is what libaom's single `av1_set_contexts` call for the 8x4 // (4x8) chroma unit leaves behind. let pair_chroma = strip_chroma .filter(|s| s.has_chroma) .map(|s| (s, neighbour_state(&u_grid), neighbour_state(&v_grid))); // lane-vert46 r1: libaom stamps the chroma entropy context PER TRANSFORM // UNIT (`av1_set_entropy_contexts` inside `decode_reconstruct_tx`'s mu-chunk // loop). Above 64 a block's chroma is two or four 32x32 units, so the // whole-block re-stamp in the record below overwrote every unit's own DC // sign and level with the TOP-LEFT unit's -- the next block then read a // stale `dc_sign_ctx` (192x256 --sb-size=128 stream: the 64x128 block at // the partial right superblock read row 1 where libaom reads row 2). The // units are collected here and re-stamped after that record, in mu-chunk // order so a later unit still wins over an earlier one. let mu_chroma_units: Vec<((usize, usize), usize, Grid)> = if mu_chroma { let cu = 32usize; let mut units = Vec::new(); for cr in 0..(write_h / 64).max(1) { for cc in 0..(write_w / 64).max(1) { let cu_mi = (at.0 + cr * 16, at.1 + cc * 16); for (plane, grid) in [(1usize, &u_grid), (2usize, &v_grid)] { let mut unit = Vec::with_capacity(cu * cu); for rr in 0..cu { let start = (cr * cu + rr) * chroma_side + cc * cu; unit.extend_from_slice(&grid[start..start + cu]); } units.push((cu_mi, plane, Grid::Own(unit))); } } } units } else { Vec::new() }; // libaom `av1_reset_entropy_context` / `av1_set_entropy_contexts`: // `nplanes = 1 + (num_planes - 1) * xd->is_chroma_ref` -- a block that is // NOT the chroma reference of its 4:2:0 pair codes no chroma transform at // all, so it leaves its neighbours' CHROMA coefficient contexts exactly as // it found them. `record_rect_mi`/`record_split_luma_rect_mi` below write // all three planes unconditionally, and for such a strip the chroma grids // are all-zero (see the `!has_chroma` arm above) -- that wiped the real // left-neighbour chroma state, so the PAIR's own `all_zero` then read // `txb_skip_ctx` one row low (lane-t900 r3, 10-bit 1920x792 stream, // mi(40,220): base 1 where libaom gathers 2). Snapshot and restore is // equivalent to not writing them, without threading a flag through both // recorders. // lane-t900 r22: every block stamps its palette state (all-zero for an // inter block, real for a palette one) into the mi-granular neighbour // bands, so the next intra block's `av1_get_palette_mode_ctx` and colour // cache see exactly what libaom's mode-info grid holds. record_strip_palette( neighbours, at, write_w, write_h, palette_record.0, palette_record.1, palette_record.2, palette_record.3, ); let saved_chroma_ctx = (!has_chroma).then(|| { hit!(NON_CHROMA_REF_CTX_SKIP_HITS); let (w_mi, h_mi) = (write_w / MI, write_h / MI); let left: Vec<[Neighbour; 2]> = (0..h_mi) .filter_map(|k| neighbours.left.get(at.0 + k).map(|s| [s[1], s[2]])) .collect(); let above: Vec<[Neighbour; 2]> = (0..w_mi) .filter_map(|k| neighbours.above.get(at.1 + k).map(|s| [s[1], s[2]])) .collect(); (left, above) }); if vartx_leaves.is_some() { // lane-t900 r17 root cause (class early-return-skips-tail): the // "plane 0 is already correct per transform unit" premise below holds // only when the per-TU luma loop RAN. A SKIP inter block takes the // `if skip` arm above, which reconstructs straight from the predictor // and never enters that loop -- yet `read_block_tx_size` still hands // back four TX_64X64 leaves for a 128 root under `TX_MODE_LARGEST` // (and for any block under it), so `vartx_leaves` is `Some` and the // luma coefficient contexts were left at the PREVIOUS block's values. // libaom calls `av1_reset_entropy_context` for every skipped block, // zeroing all three planes over its own footprint; `luma_grid` is the // all-zero grid on this arm, so publishing it is exactly that reset. // Witnessed on a 10-bit 512x512 --sb-size=128 stream: the 128x128 // block at mi(32,64) of decode-order frame 1 read `txb_skip_ctx` 2 // where aomdec reads 1, because the skipped 128x128 block at // mi(32,32) never cleared `left[32..48]`. if skip { hit!(SKIP_VARTX_LUMA_RESET_HITS); neighbours.record_mi_luma_rect(at, write_w, write_h, &luma_grid); } // Plane 0 is already correct per transform unit // ([`Neighbours::record_mi_luma`] above); this writes everything else // [`Neighbours::record_rect`] would. // // lane-sbab r1: this used to pass `side, side` on the premise that "a // var-tx block is always square". That stopped being true the moment // the SB-level rect strips landed (lane-inter4): a 64x32 / 32x64 // strip keeps `side = SB` for syntax but is NOT square, and stamping // its neighbour bands 64x64 wrote `above_side_mi = 64` where libaom's // `update_partition_context` writes `partition_context_lookup[ // BLOCK_32X64]`. The next superblock row then read the partition // context one value low (ctx 2 where aomdec says 3) and desynced. // The true footprint is `write_w`/`write_h`, exactly as the // non-var-tx arm below uses. // Plane 0 is already correct per transform unit // ([`Neighbours::record_mi_luma`] above); this writes everything else // [`Neighbours::record_rect`] would. lane-vert46 r1: the block's OWN // width/height, not `side` -- var-tx is no longer square-only (the 128 // root's HORZ/VERT arm decodes 128x64 / 64x128 var-tx blocks), and // `side` there stamped `above_side`/`left_side` = 128, so the NEXT // superblock's 128-root partition context read 16 where libaom reads 19. neighbours.record_split_luma_rect_mi(at, write_w, write_h, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]); } else { neighbours.record_rect_mi( at, write_w, write_h, mode_for_tx, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]], ); } if let Some((left, above)) = saved_chroma_ctx { for (k, v) in left.into_iter().enumerate() { if let Some(slot) = neighbours.left.get_mut(at.0 + k) { slot[1] = v[0]; slot[2] = v[1]; } } for (k, v) in above.into_iter().enumerate() { if let Some(slot) = neighbours.above.get_mut(at.1 + k) { slot[1] = v[0]; slot[2] = v[1]; } } } if let Some((s, u_state, v_state)) = pair_chroma { let (pw, ph) = if s.horz { (16usize, 8usize) } else { (8, 16) }; let round_up_even = |n: usize| n.div_ceil(2) * 2; let (bound_h, bound_w) = ( round_up_even(neighbours.mi_rows), round_up_even(neighbours.mi_cols), ); for cell in 0..(ph / MI) { if s.pair_mi.0 + cell < bound_h && let Some(slot) = neighbours.left.get_mut(s.pair_mi.0 + cell) { slot[1] = u_state; slot[2] = v_state; } } for cell in 0..(pw / MI) { if s.pair_mi.1 + cell < bound_w && let Some(slot) = neighbours.above.get_mut(s.pair_mi.1 + cell) { slot[1] = u_state; slot[2] = v_state; } } neighbours.record_uv_mode_mi(s.pair_mi.0, s.pair_mi.1, pw / MI, ph / MI, uv_predict_mode); hit!(INTER16_CHROMA_PAIR_HITS); } for (cu_mi, plane, unit) in &mu_chroma_units { neighbours.record_mi_chroma(*cu_mi, 64, 64, *plane, unit); } neighbours.record_inter_rect_mi( at, write_w / MI, write_h / MI, skip, is_inter, ref_frame_for_lf, block_filter, skip_mode, ); if let Some((ref1, group_idx, idx)) = compound_ctx { neighbours.record_compound_ctx_rect_mi(at, write_w / MI, write_h / MI, ref1, group_idx, idx); } neighbours.fill_skip_grid_rect( (rmi, cmi), write_w / MI, write_h / MI, skip, ); neighbours.fill_lf_grid_rect( (rmi, cmi), write_w / MI, write_h / MI, // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the // single-scalar corner-cut deblocked the strip seam with the wrong // edge length (1-px chroma drift on rect-flake-1 f17+). write_w as u8, write_h as u8, // ref_grid's packed convention (lf_level): sign carries GLOBALMV, // whose mode_lf_lut row is 0, not the 1 every other inter mode gets. if globalmv_for_lf { -ref_frame_for_lf } else { ref_frame_for_lf }, fctx, ); // lane-txselect: a var-tx block's deblock edges follow its own transform // units, not the block -- for LUMA only (lane-golomb r6): the chroma // grids keep the block's own `av1_get_max_uv_txsize`, which is what // libaom's `get_transform_size` reads for `plane != AOM_PLANE_Y`. // lane-sb128c r4: libaom `set_one_param_for_line_luma` suppresses every // edge that is a TU edge but not a PU edge when // `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`, so a SKIP // inter block's internal transform edges are never filtered even though // `get_transform_size` still reports TX_64X64 for it. The only block that // reaches here skipped is the 128 root (`read_block_tx_size` hands back // four TX_64X64 leaves for `side > 64` regardless of `skip`); leaving its // block-level 128 publication in place is exactly that suppression. // lane-sb128c r6: narrowed to the 128 root. Below it `read_block_tx_size` // hands a skipped inter block a single leaf equal to the block, so the // per-leaf write is the block-level one and this branch is a no-op either // way; only the 128 root gets four TX_64X64 leaves regardless of `skip`. let skip_inter_128 = skip && is_inter && write_w.max(write_h) > 64; if skip_inter_128 { neighbours.suppress_internal_lf_edges((rmi, cmi), write_w / MI, write_h / MI); } if let Some(leaves) = (!skip_inter_128).then_some(()).and(vartx_leaves.as_ref()) { for &(row, col, tw, th) in leaves { neighbours.fill_lf_grid_leaf_luma( (at_mi.0 + row, at_mi.1 + col), tw / MI, th / MI, tw as u8, th as u8, ); } } Ok(()) } /// Decodes one 8x8 group that an inter frame's `partition_w8` symbol split /// into four `BLOCK_4X4` inter blocks (lane-intersub8: `PARTITION_SPLIT` /// below 8x8 -- traced live against the oracle `aomdec`'s own `EC_PART_VAL`, /// which reads `bsize=3 value=3` on real inter frames, so the refusal this /// replaces was NOT our own desync). /// /// The inter counterpart of [`decode_leaf_split4`], and a `BLOCK_4X4`-only /// cut of [`decode_inter_block8`]: at `min(bw, bh) < 8` libaom switches off /// half the inter syntax, and every one of those is a symbol NOT read here /// (`decodemv.c` / `blockd.h`, oracle tree): /// * `skip_mode`: `read_skip_mode` returns 0 without a symbol when /// `!is_comp_ref_allowed(bsize)` (`AOMMIN(bw, bh) >= 8`, blockd.h). /// * `comp_mode`: `read_block_reference_mode` returns `SINGLE_REFERENCE` on /// the same predicate, so a sub-8x8 block is always single-reference. /// * `interintra`: `is_interintra_allowed_bsize` starts at `BLOCK_8X8`. /// * `motion_mode` / `obmc`: `motion_mode_allowed` returns /// `SIMPLE_TRANSLATION` for `block_size_wide < 8 || block_size_high < 8`, /// and `is_global_mv_block`'s own size term fails, so no warp either. /// * tx size: `block_signals_txsize(bsize)` is `bsize > BLOCK_4X4` /// (blockd.h:1027), so a `BLOCK_4X4` reads neither `tx_depth` nor a /// `txfm_partition` bit even in `TX_MODE_SELECT` -- the transform is /// `max_txsize_rect_lookup[BLOCK_4X4]` = `TX_4X4` /// (`decodeframe.c:1164-1177`). /// /// Chroma is coded ONCE for the whole 8x8 group, on the last sub-block /// (`is_chroma_reference`: `(mi_row & 1) && (mi_col & 1)` in 4:2:0), as one /// `TX_4X4` unit per plane -- same rule and same neighbour-context tail as /// [`decode_leaf_split4`]. Its PREDICTION is the sub8x8 one /// (`dec_build_inter_predictors`'s `is_sub8x8` branch, `decodeframe.c`; spec /// 7.11.3.1's `candRow`/`candCol` loop): four 2x2 chroma pieces, each built /// from its own luma sub-block's reference, motion vector and interpolation /// filters, never from the last sub-block's mv alone. #[allow(clippy::too_many_arguments)] fn decode_inter_sub8_split4( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, grid: &mut MiGrid, group_mi: (usize, usize), mi_cols: u32, mi_rows: u32, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, refpix: &RefPix<'_>, sign_bias_table: &SignBiasTable, global_motion: &[ec_av1_syntax::WarpParams; 7], base_q_idx: u8, scan4: &[u16], allow_high_precision_mv: bool, force_integer_mv: bool, interp_fixed: Option, enable_dual_filter: bool, tpl_frame: Option<&TplFrameArgs>, reduced_tx_set: bool, frame_width: usize, fctx: &crate::decode::FrameCtx, ) -> Result<()> { const LAST_FRAME: i8 = 1; const B4: usize = 4; hit!(SUB8_INTER_SPLIT_HITS); let (gr, gc) = group_mi; let (gpx, gpy) = (gc * MI, gr * MI); let (cpx, cpy) = (gpx / 2, gpy / 2); // Per-sub-block state the group's chroma prediction needs (spec // 7.11.3.1's candRow/candCol loop reads each sub-block's OWN mv/ref/ // filters), indexed `dr * 2 + dc`. let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 4] = [None; 4]; let mut first_tx_type = TxType::DctDct; let mut sub0_tx_type = TxType::DctDct; let mut last_skip = true; // Set when the chroma-reference (last) sub-block is INTRA: it coded the // group's one chroma unit itself. let mut intra_chroma = false; for i in 0..4usize { let (dr, dc) = (i / 2, i % 2); let lmi = (gr + dr, gc + dc); if lmi.0 >= mi_rows as usize || lmi.1 >= mi_cols as usize { continue; } let (rmi, cmi) = lmi; let (px, py) = (cmi * MI, rmi * MI); inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, false, true, fctx); // No `skip_mode` symbol: `is_comp_ref_allowed(BLOCK_4X4)` is false. let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false, fctx); maybe_read_cdef_idx(dec, rmi, cmi, skip, fctx); maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx); maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip, fctx); let (has_above, has_left) = ( rmi > neighbours.tile_row0_mi, cmi > neighbours.tile_col0_mi, ); let ii_ctx = intra_inter_ctx( has_above, has_left, neighbours.above_inter[cmi], neighbours.left_inter[rmi], ); let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; if !is_inter { if crate::envflags::env_flag!("EC_SUB8INTRA") { eprintln!( "EC_SUB8INTRA shape=4x4 sub={i} has_chroma={} skip={skip} mi={rmi},{cmi} tx_select={}", i == 3, fctx.tx_select_inter.with(std::cell::Cell::get), ); } // lane-sub8x4 r2: the refusal and its `EC_SUB8INTRA_DECODE` bypass // are gone -- `a_real_aomenc_inter_sequence_with_intra_sub8x8_ // leaves_decodes_pixel_exact` (stream.rs) decodes 12 real aomenc // streams carrying this arm pixel-exact vs ffmpeg. hit_do! { SUB8_INTRA_RECT_HITS.with(|h| { let mut st = h.get(); st[4] += 1; h.set(st); }); } // lane-sub8intra: the `BLOCK_4X4` twin of the HORZ/VERT arm -- // same [`decode_intra_sub8_leaf`], no tx-depth symbol, chroma on // the LAST sub-block (`is_chroma_reference` under 4:2:0). decode_intra_sub8_leaf( dec, cdfs, neighbours, grid, group_mi, lmi, (B4, B4), i == 3, skip, scan4, y, u, v, base_q_idx, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), fctx.tx_select_inter.with(std::cell::Cell::get), reduced_tx_set, fctx, )?; if i == 3 { intra_chroma = true; } continue; } // Same print point as the oracle's `EC_MODE` (entry of // `read_inter_block_mode_info`, i.e. after skip / is_inter), so the // two range ladders line up element for element. if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE mi_row={rmi} mi_col={cmi} rng={}", dec.debug_state().0 ); } let ref_frame = read_single_ref( dec, cdfs, neighbours.above_ref[cmi], neighbours.above_ref1[cmi], neighbours.left_ref[rmi], neighbours.left_ref1[rmi], ); // lane-sub8group: this piece's reference SIZE at parse, its pictures // inside the prediction closure below. let (ref_width, _) = ref_dims(ref_frame, refpix)?; // lane-t900 r28: refusal lifted -- this sub-block's own reference may // be scaled (superres); spec 7.11.3.3's walk is per reference, and // each of the group's pieces (luma and its 2x2 chroma) carries its // OWN factor because each can name a different `ref_frame`. let luma_scale = mc::scale_factor(ref_width, frame_width); if luma_scale != mc::REF_NO_SCALE { hit!(SCALED_SUB8_HITS); } let gm_table = build_gm_mv_table( global_motion, rmi, cmi, 1, 1, allow_high_precision_mv, force_integer_mv, ); let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { field: t.field, cur_offset_0: crate::motion_field::get_relative_dist( t.order_hint_bits, t.order_hint, t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, }); let stack = crate::mvstack::find_mv_stack_with_sign_bias( grid, rmi, cmi, 1, 1, ref_frame, mi_cols as usize, mi_rows as usize, sign_bias_table, &gm_table, tpl, ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; let (mv, is_new_mv) = if !not_new { let mut idx = 0usize; while idx < 2 && stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); ( read_mv( dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, base_mv, allow_high_precision_mv, force_integer_mv, ), true, ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; is_globalmv = !not_zero; let mv = if !not_zero { gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; if nearest { stack.nearest_mv } else { let mut idx = 1usize; while idx < 3 && stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) } }; (mv, false) }; // Same print point as the oracle's `EC_MODE_MV` (right after // `assign_mv`), the second rung of the sub-8x8 range ladder. if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}", mv.0, mv.1, dec.debug_state().0 ); } // No `interintra` and no `motion_mode`/`obmc` symbol below 8x8 (see // this function's own doc); `read_mb_interp_filter` still runs. let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame || neighbours.above_ref1[cmi] == Some(ref_frame) { neighbours.above_filter[cmi] } else { [3, 3] }; let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame || neighbours.left_ref1[rmi] == Some(ref_frame) { neighbours.left_filter[rmi] } else { [3, 3] }; if crate::envflags::env_flag!("EC_AV1_IFDBG") { eprintln!( "IFDBG4 mi=({rmi},{cmi}) ref={ref_frame} above_ref={} above_ref1={:?} \ above_filt={:?} left_ref={} left_ref1={:?} left_filt={:?}", neighbours.above_ref[cmi], neighbours.above_ref1[cmi], neighbours.above_filter[cmi], neighbours.left_ref[rmi], neighbours.left_ref1[rmi], neighbours.left_filter[rmi], ); } // lane-t900 r9: this reader's sub-blocks have a 4-px side, and libaom // `is_nontrans_global_motion` returns 0 for // `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE testing any model -- // so a GLOBALMV sub-block here always reads its interp filter. if is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation { hit!(GM_NONTRANS_SMALL_SIDE_HITS); } let gm_nontrans = false; let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, cdfs, interp_fixed, enable_dual_filter, gm_nontrans, above_filter_ctx, left_filter_ctx, false, ); if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE_VAL4 mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \ ref0={ref_frame} mv0=({},{}) stack={} rng={}", mv.0, mv.1, stack.entries.len(), dec.debug_state().0 ); } grid.set( rmi, cmi, MiInfo { is_inter: true, ref_frame, ref_frame1: NO_REF1, mv1: (0, 0), mv: mv16(mv), is_new_mv, size: 1, size_h: 1, is_global_mv0: false, is_global_mv1: false, }, ); piece[i] = Some((ref_frame, mv, h_filter, v_filter)); // lane-sub8group: this piece's prediction as a closure, so it runs // where its writes run -- on a recon worker at more than one // reconstruction thread, exactly like the 8x8 leaf's. let build = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let Some((sref_y, _, _)) = ref_planes_deferred(ref_frame, refpix) else { return; }; let mut pred_y = refill(std::mem::take(&mut out[0]), B4 * B4); mc::predict_maybe_scaled( &sref_y.data, sref_y.width, sref_y.true_width, sref_y.true_height, mv_to_q4(px, mv.1, true), mv_to_q4(py, mv.0, true), luma_scale, B4, B4, h_filter, v_filter, &mut pred_y, fctx, ); out[0] = pred_y; }; let pred_y: Vec; let sy = if recon_deferred(fctx) { push_pred(fctx, build); Pred::Cur { plane: 0, stride: B4, off: 0 } } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, fctx, &mut built); let [by, _, _] = built; pred_y = by; Pred::Inline(&pred_y, B4) }; // `BLOCK_4X4` never signals a transform size, so the luma unit is the // whole block and `get_txb_ctx` takes its `plane_bsize == // txsize_to_bsize[tx_size]` branch (`txb_skip_ctx = 0`, which // `read_inter_plane`'s `plane_idx == 0` arm already assumes). if skip { push_mc(0, px, py, B4, sy, &ZERO_RESIDUAL[..B4 * B4], fctx); neighbours.record_mi_luma_rect(lmi, B4, B4, &ZERO_RESIDUAL[..B4 * B4]); } else { let around = neighbours.around_mi(lmi, B4); let (luma_grid, tx_type) = read_inter_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 }, scan4, 0, around[0], 0, y, px, py, B4, base_q_idx, sy, None, None, fctx, )?; if i == 0 { sub0_tx_type = tx_type; } if i == 3 { // `av1_get_tx_type`'s chroma tail scales `blk_row`/`blk_col` // back by the subsampling, but it indexes `xd->tx_type_map`, // which `set_mi_offsets` (av1_common_int.h:1679) re-points to // the CURRENT sub-block's own mi -- so the group's one chroma // unit inherits the CHROMA-REFERENCE (last) sub-block's // tx_type, never the group's first. lane-t900 r7: reading it // off sub-block 0 left the entropy stream in sync (no symbol // is coded for chroma) and inverted one 4x4 chroma unit on the // wrong basis. first_tx_type = tx_type; } neighbours.record_mi_luma_rect(lmi, B4, B4, &luma_grid); } neighbours.record_mode_mi(rmi, cmi, 1, 1, DC_PRED); neighbours.record_inter_rect_mi(lmi, 1, 1, skip, true, ref_frame, resolved_filter, false); // lane-inter16ab r8 (same-shape sweep of the intra-strip band gap): // a BLOCK_4X4 codes no `txfm_partition` symbol, but libaom still runs // `set_txfm_ctxs(TX_4X4, 1, 1, skip && is_inter, xd)` for it -- both // arms give 4 -- so the sub-block must publish 4 to the next block's // var-tx context instead of leaving whatever the previous block left. set_txfm_ctxs(neighbours, lmi, B4, 1, 1, false); neighbours.fill_skip_grid_rect(lmi, 1, 1, skip); neighbours.fill_lf_grid_rect(lmi, 1, 1, B4 as u8, B4 as u8, ref_frame.max(LAST_FRAME), fctx); last_skip = skip; } // lane-sub8intra: when the chroma-reference sub-block was INTRA it coded // and reconstructed the group's one chroma unit itself. if !intra_chroma { // Chroma, once for the whole group, on the last sub-block's own `skip` // flag -- prediction from all four sub-blocks (2x2 pieces), residual as // one TX_4X4 unit per plane. // `is_sub8x8_inter` (reconinter_template.inc:54) is false as soon as ANY // mi of the group is intra: the group's 4x4 chroma is then predicted WHOLE // from the chroma-reference (last) sub-block's own mv, not in 2x2 pieces. let mixed = piece.iter().any(Option::is_none); if mixed { hit_do! { SUB8_INTRA_RECT_HITS.with(|h| { let mut st = h.get(); st[3] += 1; h.set(st); }); } } // lane-sub8group: the group's chroma pieces, built on the worker that // writes them -- the pieces' refs/mvs/filters travel by value. let build = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let mut pred_u = refill(std::mem::take(&mut out[1]), B4 * B4); let mut pred_v = refill(std::mem::take(&mut out[2]), B4 * B4); for i in 0..4usize { let (dr, dc) = (i / 2, i % 2); if mixed && i != 3 { continue; } let Some((ref_frame, mv, h_filter, v_filter)) = piece[i] else { continue; }; let Some((piece_ref_y, sref_u, sref_v)) = ref_planes_deferred(ref_frame, refpix) else { continue; }; let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width); let (ox, oy) = if mixed { (cpx, cpy) } else { (cpx + dc * 2, cpy + dr * 2) }; let (pw, ph) = if mixed { (B4, B4) } else { (2, 2) }; let (row0, col0) = if mixed { (0, 0) } else { (dr * 2, dc * 2) }; for (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] { let mut buf = vec![0u16; pw * ph]; mc::predict_maybe_scaled( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(ox, mv.1, false), mv_to_q4(oy, mv.0, false), piece_scale, pw, ph, h_filter, v_filter, &mut buf, fctx, ); for row in 0..ph { for col in 0..pw { dst[(row0 + row) * B4 + col0 + col] = buf[row * pw + col]; } } } } out[1] = pred_u; out[2] = pred_v; }; let (pred_u, pred_v): (Vec, Vec); let (su, sv) = if recon_deferred(fctx) { push_pred(fctx, build); ( Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 }, ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, fctx, &mut built); let [_, bu, bv] = built; (pred_u, pred_v) = (bu, bv); (Pred::Inline(&pred_u, B4), Pred::Inline(&pred_v, B4)) }; let (u_grid, v_grid) = if last_skip { push_mc(1, cpx, cpy, B4, su, &ZERO_RESIDUAL[..B4 * B4], fctx); push_mc(2, cpx, cpy, B4, sv, &ZERO_RESIDUAL[..B4 * B4], fctx); (Grid::Zero(B4 * B4), Grid::Zero(B4 * B4)) } else { let around = neighbours.around_mi(group_mi, 8); let ug = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], 0, u, cpx, cpy, B4, base_q_idx, su, Some(first_tx_type), None, fctx, )? .0; let vg = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], 0, v, cpx, cpy, B4, base_q_idx, sv, Some(first_tx_type), None, fctx, )? .0; let coded = ug.iter().chain(vg.iter()).any(|&c| c != 0); note_sub8_chroma_tx(sub0_tx_type, first_tx_type, coded); (ug, vg) }; neighbours.record_uv_mode_mi(gr, gc, 2, 2, DC_PRED); // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map // needs EVERY writer): a sub-8x8 group published no palette state, so // once an 8x8 leaf of the same row can BE a palette block, the group // left the row's band holding that earlier block's size and the next // intra block read `av1_get_palette_mode_ctx` one too high (measured: // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette` // needs `bsize >= BLOCK_8X8`), so the group always clears. record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]); let round_up_even = |n: usize| n.div_ceil(2) * 2; let bound_h = round_up_even(neighbours.mi_rows); let bound_w = round_up_even(neighbours.mi_cols); let u_state = neighbour_state(&u_grid); let v_state = neighbour_state(&v_grid); for cell in 0..2usize { if cell < 2usize.min(bound_h.saturating_sub(gr)) { neighbours.left[gr + cell][1] = u_state; neighbours.left[gr + cell][2] = v_state; } if cell < 2usize.min(bound_w.saturating_sub(gc)) { neighbours.above[gc + cell][1] = u_state; neighbours.above[gc + cell][2] = v_state; } } } // Same two neighbour tails [`decode_leaf_split4`] runs: the partition // context of a `BLOCK_4X4` subsize (`partition_context_lookup` bit 0 = 1, // reached by `side_mi = 4` here) and the group's chroma coefficient state. for cell in 0..2usize { neighbours.left_side_mi[gr + cell] = 4; neighbours.above_side_mi[gc + cell] = 4; } Ok(()) } /// One INTRA 8x4/4x8 leaf inside an INTER frame's sub-8x8 HORZ/VERT partition /// (lane-sub8intra) -- the shape [`decode_inter_sub8_rect2`] refused by name. /// Mode syntax is `read_intra_block_mode_info`'s (decodemv.c:1065), not the key /// frame's above/left pair: `y_mode[size_group_lookup[BLOCK_8X4] == 0]`, NO /// angle delta (`av1_use_angle_delta` needs `bsize >= BLOCK_8X8`), `uv_mode` + /// CfL alphas only on the chroma-reference sub-block (`is_chroma_reference`: /// the SECOND one under 4:2:0), then `filter_intra` off BLOCK_8X4/BLOCK_4X8's /// own class row (`av1_filter_intra_allowed_bsize` is `wide <= 32 && high <= /// 32`, so this shape is allowed). Everything below the mode read -- the tx /// depth symbol, the whole-leaf `TX_8X4`/`TX_4X8` or split `TX_4X4` walk, the /// 4x4 chroma unit at the group's origin -- is [`decode_leaf_rect8`]'s body for /// the same shape; the INTER-frame differences are the tx-depth context /// (`above_txfm`/`left_txfm`, not the key frame's deblock-grid approximation), /// `set_txfm_ctxs` publication, and the inter-side bands + mi map the caller's /// inter leaves also write (`is_inter = 0`, ref `INTRA_FRAME`, no interp /// filter). #[allow(clippy::too_many_arguments)] fn decode_intra_sub8_leaf( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, grid: &mut MiGrid, group_mi: (usize, usize), lmi: (usize, usize), // `(bw, bh)`: 8x4 / 4x8 under HORZ/VERT, 4x4 under SPLIT. (bw, bh): (usize, usize), has_chroma: bool, skip: bool, scan4: &[u16], y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, enable_filter_intra: bool, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result { let vert = bw < bh; let (w_mi, h_mi) = (bw / MI, bh / MI); let (gr, gc) = group_mi; let (r, c) = (gr / (SUB / MI), gc / (SUB / MI)); let (above_mode, left_mode) = neighbours.modes_above_left(r, c); let leaf_above = neighbours .mode_above_mi(lmi.0, lmi.1) .unwrap_or(above_mode); let leaf_left = neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode); let step = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); // `size_group_lookup[BLOCK_8X4] == size_group_lookup[BLOCK_4X8] == 0` // (libaom common_data.h:61). let mode = dec.symbol(&mut cdfs.y_mode[0]); if step { eprintln!( "EC_ISTEP mi_row={} mi_col={} name=mode val={mode} rng={}", lmi.0, lmi.1, dec.debug_state().0 ); } // No angle delta below 8x8 (`av1_use_angle_delta`), for luma or chroma. let angle_delta_y = 0; let (uv_mode, alpha) = if has_chroma { // `is_cfl_allowed` is `wide <= 32 && high <= 32` -- true for this // shape, so the 14-symbol CFL alphabet is the right one. let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); if (9..=12).contains(&uv_mode) { hit!(SMOOTH_UV_HITS); } let alpha = if uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; if (V_PRED..=D67_PRED).contains(&uv_mode) { hit!(DIRECTIONAL_UV_HITS); } (uv_mode, alpha) } else { (DC_PRED, None) }; let mut filter_intra = None; if mode == DC_PRED && enable_filter_intra { let fi_class = if bw == bh { filter_intra_size_class(bw).expect("BLOCK_4X4 has its own filter_intra row") } else { filter_intra_size_class_rect(bw, bh) .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize") }; let use_fi = dec.symbol(&mut cdfs.filter_intra[fi_class]); if step { eprintln!( "EC_ISTEP mi_row={} mi_col={} name=use_filter_intra val={use_fi} rng={}", lmi.0, lmi.1, dec.debug_state().0 ); } if use_fi != 0 { hit!(FILTER_INTRA_HITS); hit!(FILTER_INTRA_RECT_HITS); hit!(FILTER_INTRA_RECT_SUB8_HITS); let fi = dec.symbol(&mut cdfs.filter_intra_mode); if step { eprintln!( "EC_ISTEP mi_row={} mi_col={} name=filter_intra_mode val={fi} rng={}", lmi.0, lmi.1, dec.debug_state().0 ); } filter_intra = Some(fi); } } // `read_block_tx_size`' non-var-tx arm: an INTRA block of an inter frame // reads `read_tx_size(allow_select = 1)` -- `bsize_to_tx_size_cat // (BLOCK_4X8) == 0` (blockd.h:1344, depth table entry 1), the same // 2-symbol category [`decode_leaf_rect8`] reads -- with the var-tx // context bands, which on an inter frame are live. // `block_signals_txsize(BLOCK_4X4)` is false (blockd.h:1027): the 4x4 leaf // codes no depth symbol at all, its transform is its own size. let depth = if tx_select && bw != bh { let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); let d = dec.symbol(&mut cdfs.tx_size_cat0[ctx]); if step { eprintln!( "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=0 rng={}", lmi.0, lmi.1, dec.debug_state().0 ); } d } else { 0 }; if depth != 0 { hit!(TX_DEPTH_HITS); hit!(RECT8_SPLIT_TX_HITS); } let split = depth != 0; let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = if bw == bh { Reach::of(bw, px, py, y.width, y.height, fctx) } else { Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx) }; let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); if smooth_neighbor { hit!(SMOOTH_LUMA_HITS); } neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode); let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 }; if split { // `sub_tx_size_map[TX_4X8] == TX_4X4`: two 4x4 units along the long // axis, each predicted off the previous one's reconstruction. for tu in 0..2usize { let tu_mi = if vert { (lmi.0 + tu, lmi.1) } else { (lmi.0, lmi.1 + tu) }; let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI); let tu_reach = tu_reach( bw, bh, tu_px - px, tu_py - py, 4, reach, px, py, y.width, y.height, fctx, ); if skip { let zeros = vec![0i32; 16]; push_intra(0, tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None, filter_intra, smooth_neighbor, fctx, ); neighbours.record_mi_luma(tu_mi, 4, &zeros); continue; } let tu_around = neighbours.around_mi(tu_mi, 4)[0]; let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); let tu_grid = read_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 }, scan4, 0, tu_around, mode, mode, angle_delta_y, tu_reach, y, tu_px, tu_py, 4, TX4, base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; neighbours.record_mi_luma(tu_mi, 4, &tu_grid); } } else if bw == bh { // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so `get_txb_ctx` // fixes `txb_skip_ctx` at 0 (`luma_skip_ctx: None`) -- the same square // reader [`decode_leaf_split4`] uses. if skip { push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx, ); neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]); } else { let tu_around = neighbours.around_mi(lmi, 4)[0]; let tu_grid = read_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 }, scan4, 0, tu_around, mode, mode, angle_delta_y, reach, y, px, py, 4, TX4, base_q_idx, None, filter_intra, None, smooth_neighbor, fctx, )?; neighbours.record_mi_luma(lmi, 4, &tu_grid); } } else { let grid_levels = if skip { let zeros = Grid::Zero(bw * bh); push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra, smooth_neighbor, fctx, ); zeros } else { // The leaf's luma TU *is* the leaf, so `get_txb_ctx` fixes // `txb_skip_ctx` at 0. let around = neighbours.around_mi_rect(lmi, bw, bh)[0]; let set = if reduced_tx_set { TxbSet::LumaRect4x8 } else { TxbSet::LumaRect4x8Set1 }; let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, scan, bw, bh, 0, dc_sign_ctx(around.2), TxType::DctDct, )?; let residual = dequant_and_inverse_typed_wh( &levels, bw, bh, crate::decode::bit_depth(fctx), fctx.current_q_idx.with(|q| q.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type, ); push_intra_rect(0, px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra, smooth_neighbor, fctx, ); levels }; let state = neighbour_state(&grid_levels); for cell in 0..h_mi { if lmi.0 + cell < neighbours.mi_rows { neighbours.left[lmi.0 + cell][0] = state; } } for cell in 0..w_mi { if lmi.1 + cell < neighbours.mi_cols { neighbours.above[lmi.1 + cell][0] = state; } } } let (tx_w, tx_h) = if split { (4, 4) } else { (bw, bh) }; neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w as u8, tx_h as u8, 0, fctx); // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter == 0, xd)`: an // intra block of an inter frame publishes its TRANSFORM dims, never its // block dims (blockd.h). Missing this left the next block reading the // previous block's band (the lane-intra16x4 finding for the 16x4 strip). for i in 0..w_mi { if let Some(cell) = neighbours.above_txfm.get_mut(lmi.1 + i) { *cell = tx_w as u8; } } for i in 0..h_mi { if let Some(cell) = neighbours.left_txfm.get_mut(lmi.0 + i) { *cell = tx_h as u8; } } neighbours.above_mode[c] = mode; neighbours.left_mode[r] = mode; // The inter-side bands and the mi map, exactly as the square // intra-in-inter block writes them: `is_inter = 0`, `INTRA_FRAME` ref, no // interpolation filter, no skip mode. neighbours.record_inter_rect_mi(lmi, w_mi, h_mi, skip, false, 0, [3, 3], false); grid.fill_rect( lmi.0, lmi.1, h_mi, w_mi, MiInfo { is_inter: false, ref_frame: -1, ref_frame1: NO_REF1, mv1: (0, 0), mv: (0, 0), is_new_mv: false, size: w_mi as u8, size_h: h_mi as u8, is_global_mv0: false, is_global_mv1: false, }, ); hit_do! { SUB8_INTRA_RECT_HITS.with(|h| { let mut s = h.get(); s[usize::from(vert)] += 1; s[2] += usize::from(has_chroma); h.set(s); }); } if !has_chroma { return Ok(mode); } // The group's single 4x4 chroma unit, intra-predicted from THIS // (chroma-reference) sub-block's own `uv_mode` -- `is_sub8x8_inter` // (reconinter_template.inc:54) returns false as soon as any mi of the // group is intra, and the decoder reconstructs chroma with the // chroma-reference block's own type. Same body as [`decode_leaf_rect8`]'s // post-loop chroma. let (gpx, gpy) = (gc * MI, gr * MI); let (cpx, cpy) = (gpx / 2, gpy / 2); let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx); let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(gr, gc, r, c); let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let angle_delta_uv = 0; neighbours.above_uv_mode[c] = uv_predict_mode; neighbours.left_uv_mode[r] = uv_predict_mode; neighbours.record_uv_mode_mi(gr, gc, 2, 2, uv_predict_mode); // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map // needs EVERY writer): a sub-8x8 group published no palette state, so // once an 8x8 leaf of the same row can BE a palette block, the group // left the row's band holding that earlier block's size and the next // intra block read `av1_get_palette_mode_ctx` one too high (measured: // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette` // needs `bsize >= BLOCK_8X8`), so the group always clears. record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]); let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); let (u_grid, v_grid): (Grid, Grid) = if skip { if alpha.is_some() { hit!(CHROMA_SKIP_CFL_HITS); hit!(SKIP_CFL_HITS); } push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx); push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx); (Grid::Zero(16), Grid::Zero(16)) } else { let chroma_around = neighbours.around_mi(group_mi, 8); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode, angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; let vg = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode, angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; (ug, vg) }; let round_up_even = |n: usize| n.div_ceil(2) * 2; let bound_h = round_up_even(neighbours.mi_rows); let bound_w = round_up_even(neighbours.mi_cols); let u_state = neighbour_state(&u_grid); let v_state = neighbour_state(&v_grid); for cell in 0..2usize { if cell < 2usize.min(bound_h.saturating_sub(gr)) { neighbours.left[gr + cell][1] = u_state; neighbours.left[gr + cell][2] = v_state; } if cell < 2usize.min(bound_w.saturating_sub(gc)) { neighbours.above[gc + cell][1] = u_state; neighbours.above[gc + cell][2] = v_state; } } Ok(mode) } /// Decodes a `PARTITION_HORZ`/`PARTITION_VERT` of one 8x8 INTER block into two /// `BLOCK_8X4`/`BLOCK_4X8` inter leaves (lane-intersub8 r3) -- the inter twin of /// [`decode_leaf_rect8`] and the rectangular sibling of /// [`decode_inter_sub8_split4`], whose element order it follows exactly. /// Per sub-block, in libaom `decodemv.c` `read_inter_frame_mode_info` order: /// /// * `segment_id`, `skip`, `cdef`/`delta_q`/`delta_lf`, `intra_inter`; /// * NO `skip_mode` symbol: `is_comp_ref_allowed(BLOCK_8X4)` is false /// (`av1_is_comp_ref_allowed` needs both sides >= 8), so /// `read_skip_mode` returns 0 without reading and `comp_mode` is never read /// either (`read_ref_frames`' `is_comp_ref_allowed` guard) -- single /// reference only; /// * NO `interintra` and NO `motion_mode`/OBMC/warp symbol: every one of those /// gates needs `block_size_wide >= 8 && block_size_high >= 8` /// (`is_interintra_allowed_bsize`, `motion_mode_allowed`), and one side is 4; /// * `read_mb_interp_filter` DOES run for both sub-blocks. /// /// The shape's own differences from the four-way split: /// /// * `block_signals_txsize(BLOCK_8X4)` is true (`bsize > BLOCK_4X4`, /// blockd.h:1027), so a non-skipped sub-block reads ONE `txfm_partition` /// symbol under `TX_MODE_SELECT` at `max_txsize_rect_lookup[BLOCK_8X4] == /// TX_8X4` ([`read_var_tx_size`]); split resolves to two `TX_4X4` units /// (`sub_tx_size_map[TX_8X4] == TX_4X4`, libaom's early return), no split to /// the whole-leaf `TX_8X4`; /// * the luma coefficient set is [`TxbSet::LumaRect8x4Inter`] (the 8x8 /// coefficient class with a 32-position `eob_pt` and the INTER `TX_4X4` /// `tx_type` row) for the whole-leaf unit, and the square /// [`TxbSet::Luma4Inter`] for a split `TX_4X4` unit; /// * chroma is coded ONCE, on the sub-block that is the chroma reference: /// `is_chroma_reference` (`av1_common_int.h`) is /// `((mi_row & 1) || !(bh4 & 1) || !ss_y) && ((mi_col & 1) || !(bw4 & 1) || /// !ss_x)`, i.e. under 4:2:0 the BOTTOM 8x4 (`bh4 == 1`, odd) and the RIGHT /// 4x8 (`bw4 == 1`) -- always the second sub-block here; /// * that chroma unit's prediction is the sub8x8 one (`reconinter.c` /// `build_inter_predictors_sub8x8`: `row_start = -(block_size_high == 4 && /// ss_y)`, `col_start = -(block_size_wide == 4 && ss_x)`), two 4x2 (HORZ) or /// 2x4 (VERT) chroma pieces, each from its OWN sub-block's reference, mv and /// interpolation filters. #[allow(clippy::too_many_arguments)] fn decode_inter_sub8_rect2( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, grid: &mut MiGrid, group_mi: (usize, usize), vert: bool, mi_cols: u32, mi_rows: u32, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, refpix: &RefPix<'_>, sign_bias_table: &SignBiasTable, global_motion: &[ec_av1_syntax::WarpParams; 7], base_q_idx: u8, scan4: &[u16], allow_high_precision_mv: bool, force_integer_mv: bool, interp_fixed: Option, enable_dual_filter: bool, tpl_frame: Option<&TplFrameArgs>, reduced_tx_set: bool, frame_width: usize, fctx: &crate::decode::FrameCtx, ) -> Result<()> { const LAST_FRAME: i8 = 1; // The 8x8 group's own square stride: both leaves' prediction buffers are // laid out at it, as every other rect inter unit here is. const SIDE: usize = 8; let (bw, bh) = if vert { (4usize, 8usize) } else { (8usize, 4usize) }; let (w_mi, h_mi) = (bw / MI, bh / MI); hit_do! { SUB8_INTER_RECT_HITS.with(|c| { let mut h = c.get(); h[usize::from(vert)] += 1; c.set(h); }); } let (gr, gc) = group_mi; let (gpx, gpy) = (gc * MI, gr * MI); let (cpx, cpy) = (gpx / 2, gpy / 2); // Per-sub-block state the group's one chroma unit predicts from. let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 2] = [None; 2]; let mut first_tx_type = TxType::DctDct; let mut sub0_tx_type = TxType::DctDct; let mut last_skip = true; // Set when the chroma-reference sub-block is INTRA: it coded the group's // one chroma unit itself. let mut intra_chroma = false; for i in 0..2usize { let lmi = if vert { (gr, gc + i) } else { (gr + i, gc) }; if lmi.0 >= mi_rows as usize || lmi.1 >= mi_cols as usize { continue; } // libaom's `xd->above_mbmi`/`xd->left_mbmi` are the neighbour block as // DECODED, so leaf 1 sees leaf 0's own `bsize` -- the group tail below // publishes the side bands only once both leaves are done, which left // leaf 1 reading whatever block preceded the GROUP. `get_tx_size_context` // (pred_common.h:342) takes `block_size_wide[above_mbmi->bsize]` from it, // so an intra 8x4 leaf 1 read `tx_size_cat0` row 1 where aomdec reads // row 2 (class tx-grid-published-block-side). if i == 1 { if vert { for cell in 0..h_mi { neighbours.left_side_mi[gr + cell] = bh as u8; } neighbours.above_side_mi[gc] = bw as u8; } else { for cell in 0..w_mi { neighbours.above_side_mi[gc + cell] = bw as u8; } neighbours.left_side_mi[gr] = bh as u8; } } let (rmi, cmi) = lmi; let (px, py) = (cmi * MI, rmi * MI); inter_segment_id(dec, cdfs, rmi, cmi, w_mi, h_mi, false, true, fctx); let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; inter_segment_id(dec, cdfs, rmi, cmi, w_mi, h_mi, skip, false, fctx); maybe_read_cdef_idx(dec, rmi, cmi, skip, fctx); maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx); maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip, fctx); let (has_above, has_left) = ( rmi > neighbours.tile_row0_mi, cmi > neighbours.tile_col0_mi, ); let ii_ctx = intra_inter_ctx( has_above, has_left, neighbours.above_inter[cmi], neighbours.left_inter[rmi], ); let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; if !is_inter { if crate::envflags::env_flag!("EC_SUB8INTRA") { eprintln!( "EC_SUB8INTRA shape={}x{} sub={i} has_chroma={} skip={skip} mi={rmi},{cmi} tx_select={}", bw, bh, i == 1, fctx.tx_select_inter.with(std::cell::Cell::get), ); } // lane-sub8x4 r2: refusal and bypass lifted -- see the split arm's // note above for the gate that proves this leaf. // Its chroma rule is `is_sub8x8_inter`'s: when the // chroma-reference (second) sub-block is the intra one, the // group's 4x4 chroma is coded and predicted INTRA there and the // inter chroma tail below is skipped entirely. decode_intra_sub8_leaf( dec, cdfs, neighbours, grid, group_mi, lmi, (bw, bh), i == 1, skip, scan4, y, u, v, base_q_idx, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), fctx.tx_select_inter.with(std::cell::Cell::get), reduced_tx_set, fctx, )?; if i == 1 { intra_chroma = true; } continue; } if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE mi_row={rmi} mi_col={cmi} rng={}", dec.debug_state().0 ); } let ref_frame = read_single_ref( dec, cdfs, neighbours.above_ref[cmi], neighbours.above_ref1[cmi], neighbours.left_ref[rmi], neighbours.left_ref1[rmi], ); // lane-sub8group: this piece's reference SIZE at parse, its pictures // inside the prediction closure below. let (ref_width, _) = ref_dims(ref_frame, refpix)?; // lane-t900 r28: refusal lifted -- see the split arm above. let luma_scale = mc::scale_factor(ref_width, frame_width); if luma_scale != mc::REF_NO_SCALE { hit!(SCALED_SUB8_HITS); } let gm_table = build_gm_mv_table( global_motion, rmi, cmi, w_mi, h_mi, allow_high_precision_mv, force_integer_mv, ); let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { field: t.field, cur_offset_0: crate::motion_field::get_relative_dist( t.order_hint_bits, t.order_hint, t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, }); let stack = crate::mvstack::find_mv_stack_with_sign_bias( grid, rmi, cmi, w_mi, h_mi, ref_frame, mi_cols as usize, mi_rows as usize, sign_bias_table, &gm_table, tpl, ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; let (mv, is_new_mv) = if !not_new { let mut idx = 0usize; while idx < 2 && stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); ( read_mv( dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, base_mv, allow_high_precision_mv, force_integer_mv, ), true, ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; is_globalmv = !not_zero; let mv = if !not_zero { gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; if nearest { stack.nearest_mv } else { let mut idx = 1usize; while idx < 3 && stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) } }; (mv, false) }; if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}", mv.0, mv.1, dec.debug_state().0 ); } let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame || neighbours.above_ref1[cmi] == Some(ref_frame) { neighbours.above_filter[cmi] } else { [3, 3] }; let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame || neighbours.left_ref1[rmi] == Some(ref_frame) { neighbours.left_filter[rmi] } else { [3, 3] }; // lane-t900 r9: this reader's sub-blocks have a 4-px side, and libaom // `is_nontrans_global_motion` returns 0 for // `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE testing any model -- // so a GLOBALMV sub-block here always reads its interp filter. if is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation { hit!(GM_NONTRANS_SMALL_SIDE_HITS); } let gm_nontrans = false; let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, cdfs, interp_fixed, enable_dual_filter, gm_nontrans, above_filter_ctx, left_filter_ctx, false, ); // `read_block_tx_size` (libaom `decodeframe.c`): unlike a `BLOCK_4X4`, // this shape signals its transform size. A non-skipped inter block // walks the var-tx tree from `max_txsize_rect_lookup[BLOCK_8X4]`; a // skipped one codes nothing and records its BLOCK size in both txfm // contexts (`set_txfm_ctxs`' `skip_inter` arm). let mut leaves: Vec<(usize, usize, usize, usize)> = Vec::new(); if fctx.tx_select_inter.with(std::cell::Cell::get) && !skip { let max_w_mi = w_mi.min((mi_cols as usize).saturating_sub(cmi)); let max_h_mi = h_mi.min((mi_rows as usize).saturating_sub(rmi)); read_var_tx_size( dec, cdfs, neighbours, lmi, SIDE, (max_w_mi, max_h_mi), (bw, bh), 0, 0, 0, &mut leaves, ); } else { leaves.push((0, 0, bw, bh)); set_txfm_ctxs(neighbours, lmi, bw.max(bh), w_mi, h_mi, skip); } if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE_VALR mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \ ref0={ref_frame} mv0=({},{}) stack={} leaves={} rng={}", mv.0, mv.1, stack.entries.len(), leaves.len(), dec.debug_state().0 ); } grid_stamp_rect(grid, rmi, cmi, w_mi, h_mi, ref_frame, mv, is_new_mv); piece[i] = Some((ref_frame, mv, h_filter, v_filter)); // Prediction over the leaf's true footprint, laid out at the group's // square stride (what `reconstruct_mc_rect` and `read_inter_plane_rect` // index with). // lane-sub8group: this piece's prediction as a closure, so it runs // where its writes run -- on a recon worker at more than one // reconstruction thread, exactly like the 8x8 leaf's. let build = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let Some((sref_y, _, _)) = ref_planes_deferred(ref_frame, refpix) else { return; }; let mut pred_y = refill(std::mem::take(&mut out[0]), SIDE * SIDE); let mut dense = vec![0u16; bw * bh]; mc::predict_maybe_scaled( &sref_y.data, sref_y.width, sref_y.true_width, sref_y.true_height, mv_to_q4(px, mv.1, true), mv_to_q4(py, mv.0, true), luma_scale, bw, bh, h_filter, v_filter, &mut dense, fctx, ); for row in 0..bh { pred_y[row * SIDE..][..bw].copy_from_slice(&dense[row * bw..][..bw]); } out[0] = pred_y; }; let pred_y: Vec; let sy = if recon_deferred(fctx) { push_pred(fctx, build); Pred::Cur { plane: 0, stride: SIDE, off: 0 } } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, fctx, &mut built); let [by, _, _] = built; pred_y = by; Pred::Inline(&pred_y, SIDE) }; if skip { push_mc_rect(0, px, py, SIDE, bw, bh, sy, &ZERO_RESIDUAL[..SIDE * SIDE], fctx); neighbours.record_mi_luma_rect(lmi, bw, bh, &ZERO_RESIDUAL[..bw * bh]); neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, bw as u8, bh as u8, ref_frame.max(LAST_FRAME), fctx); } else { let (mut last_tw, mut last_th) = (bw, bh); for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() { let tu_mi = (rmi + row, cmi + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); // This unit's offset into the block prediction (lane-sub8group). let start = row * MI * SIDE + col * MI; let (tu_grid, tu_tx_type) = if tw == th { // A split `TX_4X4` unit: square reader, its own // `get_txb_ctx_general` neighbour context (the unit is // smaller than its plane block, so the lone-TU 0 does not // apply). // lane-sub8group: the unit's window of the block // prediction, at the block's stride -- the dense copy the // parse thread used to make is the recorded op's own // ([`push_mc_rect_tx`]), and a deferred prediction has no // buffer here to copy out of. let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI); read_inter_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 }, scan4, 0, neighbours.around_mi(tu_mi, tw)[0], 0, y, tu_px, tu_py, tw, base_q_idx, sy.offset(start), None, Some(tu_skip_ctx), fctx, )? } else { // The whole leaf as one `TX_8X4`/`TX_4X8` unit: it IS the // plane block, so `get_txb_ctx_general` fixes `txb_skip_ctx` // at 0 (`luma_skip_ctx: None`). read_inter_plane_rect( dec, cdfs, if reduced_tx_set { TxbSet::LumaRect8x4Inter } else { TxbSet::LumaRect8x4InterSet1 }, (tw, th), SIDE, 0, neighbours.around_mi_rect(tu_mi, tw, th)[0], 0, y, tu_px, tu_py, sy.offset(start), None, None, fctx, )? }; if idx == 0 && i == 0 { sub0_tx_type = tu_tx_type; } if idx == 0 && i == 1 { // `av1_get_tx_type` indexes `xd->tx_type_map`, which // `set_mi_offsets` (av1_common_int.h:1679) re-points to the // CURRENT sub-block: the group's one chroma unit inherits // the CHROMA-REFERENCE (second) sub-block's first transform // unit, never the first sub-block's (lane-t900 r7). first_tx_type = tu_tx_type; } neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid); (last_tw, last_th) = (tw, th); } neighbours.fill_lf_grid_rect( lmi, w_mi, h_mi, last_tw as u8, last_th as u8, ref_frame.max(LAST_FRAME), fctx, ); } neighbours.record_mode_mi(rmi, cmi, w_mi, h_mi, DC_PRED); neighbours.record_inter_rect_mi(lmi, w_mi, h_mi, skip, true, ref_frame, resolved_filter, false); neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); last_skip = skip; } // lane-sub8intra: when the chroma-reference sub-block was INTRA it coded // and reconstructed the group's one chroma unit itself. if !intra_chroma { // The group's single 4x4 chroma unit per plane, on the chroma-reference // (second) sub-block's own skip flag. const B4: usize = 4; // `is_sub8x8_inter` (reconinter_template.inc:54) is false as soon as ANY // mi of the group is intra, so a group whose chroma reference is inter but // whose sibling is INTRA does NOT get the two-piece sub8x8 prediction: the // ordinary 8x8-and-bigger path predicts the WHOLE 4x4 chroma unit from the // chroma-reference block's own mv, at the group's chroma origin // (`row_start`/`col_start` shift `pre_x`/`pre_y` there either way). let mixed = piece[0].is_none(); if mixed { hit_do! { SUB8_INTRA_RECT_HITS.with(|h| { let mut s = h.get(); s[3] += 1; h.set(s); }); } } let (piece_w, piece_h) = match (mixed, vert) { (true, _) => (B4, B4), (false, true) => (2usize, 4usize), (false, false) => (4usize, 2usize), }; // lane-sub8group: the group's chroma pieces, built on the worker that // writes them -- the pieces' refs/mvs/filters travel by value. let build = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let mut pred_u = refill(std::mem::take(&mut out[1]), B4 * B4); let mut pred_v = refill(std::mem::take(&mut out[2]), B4 * B4); for i in 0..2usize { let Some((ref_frame, mv, h_filter, v_filter)) = piece[i] else { continue; }; let Some((piece_ref_y, sref_u, sref_v)) = ref_planes_deferred(ref_frame, refpix) else { continue; }; let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width); let (ox, oy) = if mixed { (cpx, cpy) } else if vert { (cpx + i * piece_w, cpy) } else { (cpx, cpy + i * piece_h) }; let (dc, dr) = if mixed { (0, 0) } else if vert { (i * piece_w, 0) } else { (0, i * piece_h) }; for (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] { let mut buf = vec![0u16; piece_w * piece_h]; mc::predict_maybe_scaled( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(ox, mv.1, false), mv_to_q4(oy, mv.0, false), piece_scale, piece_w, piece_h, h_filter, v_filter, &mut buf, fctx, ); for row in 0..piece_h { for col in 0..piece_w { dst[(dr + row) * B4 + dc + col] = buf[row * piece_w + col]; } } } } out[1] = pred_u; out[2] = pred_v; }; let (pred_u, pred_v): (Vec, Vec); let (su, sv) = if recon_deferred(fctx) { push_pred(fctx, build); ( Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 }, ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, fctx, &mut built); let [_, bu, bv] = built; (pred_u, pred_v) = (bu, bv); (Pred::Inline(&pred_u, B4), Pred::Inline(&pred_v, B4)) }; let (u_grid, v_grid) = if last_skip { push_mc(1, cpx, cpy, B4, su, &ZERO_RESIDUAL[..B4 * B4], fctx); push_mc(2, cpx, cpy, B4, sv, &ZERO_RESIDUAL[..B4 * B4], fctx); (Grid::Zero(B4 * B4), Grid::Zero(B4 * B4)) } else { let around = neighbours.around_mi(group_mi, 8); let ug = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], 0, u, cpx, cpy, B4, base_q_idx, su, Some(first_tx_type), None, fctx, )? .0; let vg = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], 0, v, cpx, cpy, B4, base_q_idx, sv, Some(first_tx_type), None, fctx, )? .0; let coded = ug.iter().chain(vg.iter()).any(|&c| c != 0); note_sub8_chroma_tx(sub0_tx_type, first_tx_type, coded); (ug, vg) }; neighbours.record_uv_mode_mi(gr, gc, 2, 2, DC_PRED); // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map // needs EVERY writer): a sub-8x8 group published no palette state, so // once an 8x8 leaf of the same row can BE a palette block, the group // left the row's band holding that earlier block's size and the next // intra block read `av1_get_palette_mode_ctx` one too high (measured: // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette` // needs `bsize >= BLOCK_8X8`), so the group always clears. record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]); let round_up_even = |n: usize| n.div_ceil(2) * 2; let bound_h = round_up_even(neighbours.mi_rows); let bound_w = round_up_even(neighbours.mi_cols); let u_state = neighbour_state(&u_grid); let v_state = neighbour_state(&v_grid); for cell in 0..2usize { if cell < 2usize.min(bound_h.saturating_sub(gr)) { neighbours.left[gr + cell][1] = u_state; neighbours.left[gr + cell][2] = v_state; } if cell < 2usize.min(bound_w.saturating_sub(gc)) { neighbours.above[gc + cell][1] = u_state; neighbours.above[gc + cell][2] = v_state; } } } // `update_partition_context` writes `partition_context_lookup[subsize]` // over the whole 8x8 span -- BLOCK_4X8's width above and height left, the // same values [`decode_leaf_rect8`] writes for the intra shape. for cell in 0..2usize { neighbours.above_side_mi[gc + cell] = bw as u8; neighbours.left_side_mi[gr + cell] = bh as u8; } Ok(()) } /// Stamps one sub-8x8 inter leaf into every mi cell of its true `w_mi`x`h_mi` /// footprint (class: a rect block's grid span is its own, never a square guess). fn grid_stamp_rect( grid: &mut MiGrid, mi_row: usize, mi_col: usize, w_mi: usize, h_mi: usize, ref_frame: i8, mv: (i32, i32), is_new_mv: bool, ) { grid.fill_rect( mi_row, mi_col, h_mi, w_mi, MiInfo { is_inter: true, ref_frame, ref_frame1: NO_REF1, mv1: (0, 0), mv: mv16(mv), is_new_mv, size: w_mi as u8, size_h: h_mi as u8, is_global_mv0: false, is_global_mv1: false, }, ); } /// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block /// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s /// exact symbol order: its own skip flag, intra/inter choice and (when /// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack /// window, or (when intra) `Y_MODE`, then its own luma and two chroma /// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`], /// same as [`decode_leaf8`]'s coefficient layer but with /// motion-compensated prediction instead of intra prediction when inter. /// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's /// skip/intra-inter context, overridden by `prev_leaf` exactly as /// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays /// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag /// and intra/inter choice, for the next leaf or the caller's final /// write-back. #[allow(clippy::too_many_arguments)] fn decode_inter_block8( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, grid: &mut MiGrid, mi_cols: u32, mi_rows: u32, outer_at: (usize, usize), leaf_mi: (usize, usize), y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, refpix: &RefPix<'_>, base_q_idx: u8, scan8: &[u16], scan4: &[u16], allow_high_precision_mv: bool, force_integer_mv: bool, // lane-gmaffine r1: this frame header's own `global_motion` table (spec // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing // candidates with the gm mv (gm r6's root cause) and build a global // warp prediction. global_motion: &[ec_av1_syntax::WarpParams; 7], // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit, // for the leaf's own `read_mb_interp_filter` below. enable_dual_filter: bool, // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s // context uses that same approximation. reference_select: bool, enable_masked_compound: bool, // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate // drops the `side` check entirely. enable_interintra_compound: bool, enable_jnt_comp: bool, order_hint_bits: u32, order_hint: u32, ref_order_hints: [u32; 7], // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either, // so its `skip_mode` context reuses the same [`SUB`]-grid // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation // just above). skip_mode_present: bool, skip_mode_frame: [u8; 2], // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see // [`decode_inter_frame_tile_with_cdfs`]'s own doc. reduced_tx_set: bool, // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/ // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own // prediction is always `Regular` (documented corner-cut, `mc::predict` // has no filter param), but an OBMC neighbour can be a real 16x16+ // block that DID resolve a switchable filter. interp_fixed: Option, switchable_motion_mode: bool, allow_warped_motion: bool, // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own // `compound_ctx` local, just handed back instead of applied here (this // fn's `neighbours` recording happens once for the whole straddling // 16x16 block, after every leaf). // lane-screen r2: see [`decode_inter_block`]'s own copy of this param -- // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`- // eligible (`bsize >= BLOCK_8X8`). allow_screen_content_tools: bool, // lane-inter8 r1: the leaf's mv stacks used to be built without the // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`] // one level up passed it -- it changes the candidate list and with it // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read. // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot // 8x8-split gate). sign_bias_table: &SignBiasTable, // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which // [`decode_inter_block`] one level up has always passed and this leaf // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds // fewer candidates here than in the reference decoder, which changes the // mode contexts AND the number of `drl_mode` bits read (class parsed // then discarded). tpl_frame: Option<&TplFrameArgs>, // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3), // for the scaled-reference MC this leaf's own single-ref/compound/OBMC // predictions take when a stored reference was coded at another width // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param. frame_width: usize, fctx: &crate::decode::FrameCtx, ) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option))> { const LAST_FRAME: i8 = 1; // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back // so the caller stamps them into `Neighbours` instead of the `[3, 3]` // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an // OBMC blend that picks such a neighbour up feeds it to // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) -- // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]` // on the intra and compound paths. let mut leaf_filter_syms = [3u8; 2]; // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's // missing-candidate fallback both come from the frame's global motion // evaluated at THIS block's centre (gm r6's root cause). let gm_table = build_gm_mv_table( global_motion, leaf_mi.0, leaf_mi.1, 2, 2, allow_high_precision_mv, force_integer_mv, ); /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`). const SIZE_GROUP_8: usize = 1; let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let (cpx, cpy) = (px / 2, py / 2); // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) -- // read back by the luma residual read and the tail's neighbour/loop-filter // bookkeeping. Always `false` outside a `TxMode::Select` inter frame. let split8; const SIDE: usize = 8; const CHROMA_SIDE: usize = 4; let (r, c) = outer_at; // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's -- // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the // left column of a 16x16's second leaf ROW is the previous 16x16 block's // bottom leaf, neither of which a SUB-grid slot can name. let (rmi, cmi) = leaf_mi; // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps // its own 2x2-mi span into the bands right after it decodes (the caller's // `record_inter_rect_mi`), so a plain mi read already names the correct // neighbour, including one belonging to the previous 16x16 block. let above_skip = neighbours.above_skip[cmi]; let left_skip = neighbours.left_skip[rmi]; let above_inter = neighbours.above_inter[cmi]; let left_inter = neighbours.left_inter[rmi]; let above_ref0 = neighbours.above_ref[cmi]; let above_ref1 = neighbours.above_ref1[cmi]; let left_ref0 = neighbours.left_ref[rmi]; let left_ref1 = neighbours.left_ref1[rmi]; let skip_mode_ctx = usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]); // Same two `inter_segment_id` positions as [`decode_inter_block`]; this // leaf is always `BLOCK_8X8`, i.e. 2x2 mi. inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true, fctx); let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; if skip_mode { hit!(SKIP_MODE_HITS); } let skip_ctx = usize::from(above_skip) + usize::from(left_skip); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false, fctx); maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip, fctx); // Always a `BLOCK_8X8` leaf here, never the whole superblock. maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip, fctx); maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip, fctx); let (has_above, has_left) = ( leaf_mi.0 > neighbours.tile_row0_mi, leaf_mi.1 > neighbours.tile_col0_mi, ); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4, // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder // diffs line for line against a real aomdec. if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE mi_row={} mi_col={} rng={}", leaf_mi.0, leaf_mi.1, dec.debug_state().0 ); } let mode_for_tx; // lane-uv8 r1: this leaf's chroma prediction mode (`get_uv_mode` of the // coded `uv_mode`), for the neighbour bands at the tail. An INTER leaf // stores `UV_DC_PRED`, exactly as [`decode_inter_block`] one level up. let mut uv_predict_mode = DC_PRED; let (luma_grid, u_grid, v_grid); let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None; // lane-inter8 r1: this leaf's own resolved references, handed back so the // NEXT leaf of the same 16x16 can use them as its real above/left // neighbour (`Neighbours`' arrays only move once per 16x16 block). // `(0, None)` is intra. let mut leaf_refs: (i8, Option) = (0, None); // lane-t900 r23: this leaf's own palette state for the neighbour bands // (`(y_size, y_colors, uv_size, uv_colors)`), all-zero for an inter leaf // and for an intra one that codes no palette -- same publication the // >=16 intra-in-inter block makes through [`record_strip_palette`]. let mut palette_record8: (usize, [u16; 8], usize, [u16; 8]) = (0, [0u16; 8], 0, [0u16; 8]); if is_inter { if reference_select || skip_mode { // lane-inter8 r1: the REAL neighbour references, not a // `LAST_FRAME`-or-intra stand-in. `av1_get_reference_mode_context` // and `read_compound_ref_frames`' own contexts both ask whether a // neighbour is COMPOUND, so pretending every inter neighbour is // single-ref LAST picked the wrong `comp_mode` CDF row -- measured // as an 8x8 leaf reading single-ref where aomdec read compound // NEAR_NEWMV (mi 4,14). let above_nbr = has_above.then(|| NeighbourRef { is_inter: above_inter, ref0: if above_inter { above_ref0 } else { 0 }, ref1: above_ref1, uni: above_ref1.is_some_and(|r1| is_uni_comp_ref(above_ref0, r1)), }); let left_nbr = has_left.then(|| NeighbourRef { is_inter: left_inter, ref0: if left_inter { left_ref0 } else { 0 }, ref1: left_ref1, uni: left_ref1.is_some_and(|r1| is_uni_comp_ref(left_ref0, r1)), }); if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) { let (ref0, ref1) = if skip_mode { (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8) } else { // lane-interp3 r2 (class twin-functions-drift): this leaf // passed a hard-coded `LAST_FRAME` for every inter // neighbour -- the old "coarse LAST_FRAME-or-intra" // approximation -- while the side bands have carried the // neighbour's REAL reference per mi since lane-inter8 r2. // Every `av1_collect_neighbors_ref_counts` vote below // (`uni_comp_ref_p1`, `comp_ref`, `comp_bwdref`, ...) was // therefore taken off the wrong CDF row. Same two args // [`decode_inter_block`]'s own compound arm passes // (`-1` when the band is unavailable is start_tile's / // start_row's own reset value, so no `has_above` guard). read_compound_ref_frames( dec, cdfs, above_nbr, left_nbr, above_ref0, left_ref0, ) }; leaf_refs = (ref0, Some(ref1)); let (mi_row, mi_col) = leaf_mi; // spec 7.10.2.8, mirroring [`decode_inter_block`]'s own // `comp_tpl` build (`use_ref_frame_mvs` frames only). let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs { field: t.field, cur_offset_0: crate::motion_field::get_relative_dist( t.order_hint_bits, t.order_hint, t.ref_order_hints[(ref0 - LAST_FRAME) as usize], ), cur_offset_1: crate::motion_field::get_relative_dist( t.order_hint_bits, t.order_hint, t.ref_order_hints[(ref1 - LAST_FRAME) as usize], ), allow_high_precision_mv, }); // lane-av1comp: this leaf path has neither a real sign-bias // table nor `tpl_frame` (see this function's own doc on the // coarse `LAST_FRAME`-or-intra neighbour approximation // already in force above), matching the plain `find_mv_stack` // (no bias, no tpl) the leaf's single-ref arm below already // uses. let comp_stack = crate::mvstack::find_mv_stack_compound( grid, mi_row, mi_col, 2, 2, (ref0, ref1), mi_cols as usize, mi_rows as usize, sign_bias_table, &gm_table, comp_tpl, ); let compound_mode = if skip_mode { 0 // NEAREST_NEARESTMV, forced -- no mode symbol read } else { read_inter_compound_mode( dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx, ) }; if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}", leaf_mi.0, leaf_mi.1, compound_mode + 17, comp_stack.entries.len(), comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx, dec.debug_state().0 ); } let (mv0, mv1) = assign_compound_mv( dec, cdfs, &comp_stack, compound_mode, allow_high_precision_mv, force_integer_mv, // lane-inter8 r1: the real per-ref gm mvs, same as // [`decode_inter_block`]'s own compound arm. ( gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize], ), ); // lane-inter8 r3: byte-format-identical to the oracle's // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder // diffs line for line against a real aomdec. if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}", leaf_mi.0, leaf_mi.1, compound_mode + 17, ref0, ref1, mv0.0, mv0.1, dec.debug_state().0 ); } // spec 5.11.25: same gating [`decode_inter_block`]'s own // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid // slot -- the only granularity `Neighbours`' comp_group_idx/ // compound_idx arrays track. let group_ctx = get_comp_group_idx_context(neighbours, leaf_mi, SIDE); let comp_group_idx = if !skip_mode && enable_masked_compound && is_any_masked_compound_used_here(SIDE, SIDE) { dec.symbol(&mut cdfs.comp_group_idx[group_ctx]) } else { 0 }; // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32 // leaf's own comment. let mut diffwtd_mask_type: Option = None; let mut wedge_mask: Option<&'static [u8]> = None; if comp_group_idx == 1 { // lane-maskcomp r1: see the 16x16 leaf's own comment // above -- SIDE==8 here, `wedge_bsize` index 3 // (BLOCK_8X8, `wedge_types > 0`). let compound_type = dec.symbol(&mut cdfs.compound_type[3]); if compound_type == 0 { // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32 // leaf's own comment. let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]); let wedge_sign = dec.literal(1); hit!(WEDGE_HITS); wedge_mask = Some( crate::wedge::wedge_masks() .codebook(SIDE, SIDE) .mask(wedge_sign as usize, wedge_index as usize), ); } else { let mask_type = dec.literal(1); diffwtd_mask_type = Some(mask_type as u8); } hit!(MASKED_COMPOUND_HITS); } // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same // reference-slot defect as the 16x16 leaf's own mask above // (r1: falsified as an MC/blend math bug, isolated to a DPB // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see // that comment. // r3: same defect as the 16x16 leaf's own mask above -- see // that comment (compound_idx's decoded value, not the blend // math or reference-slot bookkeeping). r6/r7: same re-mask // as the 16x16 leaf above -- one real bug found and fixed // (mvstack.rs ref_ctx family), a second, still-unfound // compound_idx defect surfaces on the wide gate sweep. // lane-av1idx r1: same re-mask as the 16x16 leaf above -- // see that comment. let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0 && !skip_mode && enable_jnt_comp { let idx_ctx = get_comp_index_context( neighbours, leaf_mi, SIDE, order_hint_bits, order_hint, ref_order_hints[(ref0 - LAST_FRAME) as usize], ref_order_hints[(ref1 - LAST_FRAME) as usize], ); let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]); if idx == 1 { (8, 8, 1u8) } else { let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign( order_hint_bits, order_hint, ref_order_hints[(ref0 - LAST_FRAME) as usize], ref_order_hints[(ref1 - LAST_FRAME) as usize], ); (fwd, bck, 0u8) } } else { (8, 8, 1u8) }; compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx)); if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") { eprintln!( "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize=8 mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}", mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos() ); } // lane-interp3 r1: `read_mb_interp_filter` (libaom // `decodemv.c` 1575, the tail of // `read_inter_block_mode_info`) runs for EVERY inter block, // compound included, right AFTER `read_compound_type` -- this // leaf read no filter symbol at all, so a SWITCHABLE-filter // stream lost one symbol (two under `enable_dual_filter`) at // every compound 8x8 leaf, and the leaf recorded the `[3, 3]` // "no filter" sentinel, which made a neighbouring OBMC block's // `neighbour_filter` PANIC instead of blending. // `av1_is_interp_needed` suppression terms for this arm: // `skip_mode`, and `is_nontrans_global_motion` (mode // GLOBAL_GLOBALMV with BOTH refs' models non-TRANSLATION) -- // WARPED_CAUSAL cannot occur on a compound block. let gm_nontrans_c = compound_mode == 6 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation; // spec `get_ref_filter_type`, keyed on this block's ref0 and // matching EITHER of the neighbour's references -- same shape // as [`decode_inter_block`]'s compound arm. Same corner-cut as // this leaf's single-ref arm below: the context comes from the // enclosing 16x16's coarse slot. let above_filter_ctx = if neighbours.above_ref[cmi] == ref0 || neighbours.above_ref1[cmi] == Some(ref0) { neighbours.above_filter[cmi] } else { [3, 3] }; let left_filter_ctx = if neighbours.left_ref[rmi] == ref0 || neighbours.left_ref1[rmi] == Some(ref0) { neighbours.left_filter[rmi] } else { [3, 3] }; let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, cdfs, interp_fixed, enable_dual_filter, gm_nontrans_c || skip_mode, above_filter_ctx, left_filter_ctx, true, ); leaf_filter_syms = resolved_filter; if interp_fixed.is_none() && !(gm_nontrans_c || skip_mode) { hit!(COMPOUND8_FILTER_HITS); } // lane-defer8: both slots' SIZES at parse, pictures in the closure. let scale0 = mc::scale_factor(ref_dims(ref0, refpix)?.0, frame_width); let scale1 = mc::scale_factor(ref_dims(ref1, refpix)?.0, frame_width); if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE { hit!(SCALED_COMPOUND_HITS); hit!(SCALED_BLOCK8_HITS); } // lane-interp3 r2 (class twin-functions-drift): both slots // used to be stamped `false`, while [`decode_inter_block`]'s // compound arm computes libaom's PER-SLOT `is_global_mv_block` // (blockd.h:421-429 -- mode GLOBAL_GLOBALMV, block >= 8x8 // (always true for this leaf) and THAT slot's own gm model > // TRANSLATION). A neighbour carrying the flag makes // `setup_ref_mv_list` substitute the READER's global mv for // the neighbour's stored one, so a cleared flag fed the next // block's stack a stored mv where libaom has the global // candidate -- a wrong mv stack, wrong mode contexts, and a // desync one block later. let is_globalmv_c = compound_mode == 6; let is_global_mv0_c = is_globalmv_c && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1; let is_global_mv1_c = is_globalmv_c && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1; // lane-interp3 r3 (class twin-functions-drift, second // instance): libaom applies `allow_warp`'s GLOBAL branch // (`reconinter.c:33-55`, reached from `av1_init_warp_params` // inside `build_inter_predictors_8x8_and_bigger`'s per-`ref` // loop) to EVERY `is_global_mv_block` slot, compound // included and independently of `motion_mode` -- the 16x16+ // compound arm has done this since lane-cwarp r1, this leaf // predicted both taps translationally, so a GLOBAL_GLOBALMV // 8x8 compound leaf under a non-TRANSLATION model drifted by // a few luma levels, growing away from the block origin. // `force_integer_mv` short-circuits `av1_init_warp_params` // before `allow_warp`; chroma is 4x4 here, below // `av1_init_warp_params`'s own 8px per-plane bound, so only // luma warps (same rule as this leaf's single-ref arm). let leaf_compound_warp = |ref_frame: i8, eligible: bool| { if eligible && !force_integer_mv && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid { crate::warp::global_warp_params( global_motion[(ref_frame - LAST_FRAME) as usize].params, ) } else { None } }; // lane-t900 r28: same per-slot `allow_warp` scale bail-out as // the 16x16-and-bigger compound path above. let leaf_ref_unscaled = |rf: i8| { refpix .dims(rf) .is_some_and(|(w, _)| mc::scale_factor(w, frame_width) == mc::REF_NO_SCALE) }; let warp0_c = leaf_compound_warp(ref0, is_global_mv0_c).filter(|_| leaf_ref_unscaled(ref0)); let warp1_c = leaf_compound_warp(ref1, is_global_mv1_c).filter(|_| leaf_ref_unscaled(ref1)); if warp0_c.is_some() || warp1_c.is_some() { hit!(COMPOUND_WARP_HITS); hit!(COMPOUND_WARP_HITS_8); } grid.fill_rect( mi_row, mi_col, 2, 2, MiInfo { is_inter: true, ref_frame: ref0, ref_frame1: ref1, mv1: mv16(mv1), mv: mv16(mv0), is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), size: 2, size_h: 2, is_global_mv0: is_global_mv0_c, is_global_mv1: is_global_mv1_c, }, ); mode_for_tx = 0; // lane-defer8: this leaf's whole prediction as a closure, so it runs // where its writes run -- on a recon worker at more than one // reconstruction thread, exactly like [`decode_inter_block`]'s. let build = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let (Some((py0, pu0, pv0)), Some((py1, pu1, pv1))) = (ref_planes_deferred(ref0, refpix), ref_planes_deferred(ref1, refpix)) else { return; }; let mut inter0_y = vec![0i32; SIDE * SIDE]; mc::predict_compound_intermediate( &py0.data, py0.width, py0.true_width, py0.true_height, mv_to_q4(px, mv0.1, true), mv_to_q4(py, mv0.0, true), scale0, SIDE, SIDE, h_filter, v_filter, &mut inter0_y, ); if let Some(wp) = &warp0_c { crate::warp::warp_affine_compound( wp, &py0.data, py0.true_width as i32, py0.true_height as i32, py0.width as i32, &mut inter0_y, px as i32, py as i32, SIDE as i32, SIDE as i32, SIDE as i32, 0, 0, fctx, ); } let mut inter1_y = vec![0i32; SIDE * SIDE]; mc::predict_compound_intermediate( &py1.data, py1.width, py1.true_width, py1.true_height, mv_to_q4(px, mv1.1, true), mv_to_q4(py, mv1.0, true), scale1, SIDE, SIDE, h_filter, v_filter, &mut inter1_y, ); if let Some(wp) = &warp1_c { crate::warp::warp_affine_compound( wp, &py1.data, py1.true_width as i32, py1.true_height as i32, py1.width as i32, &mut inter1_y, px as i32, py as i32, SIDE as i32, SIDE as i32, SIDE as i32, 0, 0, fctx, ); } let mut pred_y = refill(std::mem::take(&mut out[0]), SIDE * SIDE); let mut diffwtd_mask_y; let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type { diffwtd_mask_y = vec![0u8; SIDE * SIDE]; hit!(DIFFWTD_HITS); mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y, fctx); Some(diffwtd_mask_y.as_slice()) } else { wedge_mask }; if let Some(mask_y) = mask_y { mc::blend_masked_compound( &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y, fctx, ); } else { mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y, fctx); } let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; mc::predict_compound_intermediate( &pu0.data, pu0.width, pu0.true_width, pu0.true_height, mv_to_q4(cpx, mv0.1, false), mv_to_q4(cpy, mv0.0, false), scale0, CHROMA_SIDE, CHROMA_SIDE, h_filter, v_filter, &mut inter0_u, ); let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; mc::predict_compound_intermediate( &pu1.data, pu1.width, pu1.true_width, pu1.true_height, mv_to_q4(cpx, mv1.1, false), mv_to_q4(cpy, mv1.0, false), scale1, CHROMA_SIDE, CHROMA_SIDE, h_filter, v_filter, &mut inter1_u, ); let mut pred_u = refill(std::mem::take(&mut out[1]), CHROMA_SIDE * CHROMA_SIDE); if let Some(mask_y) = mask_y { mc::blend_masked_compound( &inter0_u, &inter1_u, mask_y, SIDE, CHROMA_SIDE, CHROMA_SIDE, true, &mut pred_u, fctx, ); } else { mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u, fctx); } let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; mc::predict_compound_intermediate( &pv0.data, pv0.width, pv0.true_width, pv0.true_height, mv_to_q4(cpx, mv0.1, false), mv_to_q4(cpy, mv0.0, false), scale0, CHROMA_SIDE, CHROMA_SIDE, h_filter, v_filter, &mut inter0_v, ); let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; mc::predict_compound_intermediate( &pv1.data, pv1.width, pv1.true_width, pv1.true_height, mv_to_q4(cpx, mv1.1, false), mv_to_q4(cpy, mv1.0, false), scale1, CHROMA_SIDE, CHROMA_SIDE, h_filter, v_filter, &mut inter1_v, ); let mut pred_v = refill(std::mem::take(&mut out[2]), CHROMA_SIDE * CHROMA_SIDE); if let Some(mask_y) = mask_y { mc::blend_masked_compound( &inter0_v, &inter1_v, mask_y, SIDE, CHROMA_SIDE, CHROMA_SIDE, true, &mut pred_v, fctx, ); } else { mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v, fctx); } *out = [pred_y, pred_u, pred_v]; }; let deferred = recon_deferred(fctx); let (pred_y, pred_u, pred_v): (Vec, Vec, Vec); let (sy, su, sv) = if deferred { push_pred(fctx, build); ( Pred::Cur { plane: 0, stride: SIDE, off: 0 }, Pred::Cur { plane: 1, stride: CHROMA_SIDE, off: 0 }, Pred::Cur { plane: 2, stride: CHROMA_SIDE, off: 0 }, ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, fctx, &mut built); let [by, bu, bv] = built; (pred_y, pred_u, pred_v) = (by, bu, bv); ( Pred::Inline(&pred_y, SIDE), Pred::Inline(&pred_u, CHROMA_SIDE), Pred::Inline(&pred_v, CHROMA_SIDE), ) }; split8 = read_block_tx_size( dec, cdfs, neighbours, leaf_mi, SIDE, (mi_cols as usize, mi_rows as usize), true, skip, fctx, )? .1 .is_some(); if skip { push_mc(0, px, py, SIDE, sy, &ZERO_RESIDUAL[..SIDE * SIDE], fctx); push_mc(1, cpx, cpy, CHROMA_SIDE, su, &ZERO_RESIDUAL[..CHROMA_SIDE * CHROMA_SIDE], fctx, ); push_mc(2, cpx, cpy, CHROMA_SIDE, sv, &ZERO_RESIDUAL[..CHROMA_SIDE * CHROMA_SIDE], fctx, ); luma_grid = Grid::Zero(SIDE * SIDE); u_grid = Grid::Zero(CHROMA_SIDE * CHROMA_SIDE); v_grid = Grid::Zero(CHROMA_SIDE * CHROMA_SIDE); } else { let around = neighbours.around_mi(leaf_mi, 8); let (grid8, luma_tx_type) = read_inter_luma8( dec, cdfs, neighbours, leaf_mi, y, px, py, sy, mode_for_tx, base_q_idx, scan8, scan4, reduced_tx_set, split8, fctx, )?; luma_grid = grid8; u_grid = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], mode_for_tx, u, cpx, cpy, CHROMA_SIDE, base_q_idx, su, Some(luma_tx_type), None, fctx, )? .0; v_grid = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], mode_for_tx, v, cpx, cpy, CHROMA_SIDE, base_q_idx, sv, Some(luma_tx_type), None, fctx, )? .0; } // lane-inter8 r2: the COMPOUND leaf used to return here // WITHOUT the end-of-function `record_mi`/`fill_lf_grid` the // single-ref path falls through to -- so a compound 8x8 leaf // left `above_side_mi`/`left_side_mi` (the next block's // partition context), the per-plane coefficient level state // and the loop-filter grid describing whatever block was // there before. Every leaf of the gate's stream is compound, // so the 16x16 below a split block read partition ctx 0 // instead of 1 and mis-read PARTITION_SPLIT as NONE. // lane-sub8x4 r1: the same plane-0 save/restore the fall-through // (single-ref) path runs below -- a `split8` leaf's plane-0 // neighbour context is per 4x4 transform unit (written by // `record_mi_luma` inside `read_inter_luma8`), and `record_mi` // rewrites all three planes from the whole-block grid, which is // all-zero in the split case. Missing here, a compound var-tx 8x8 // leaf published level 0 to its right/below neighbours: the next // block's first TU read `skip_contexts[4][0] = 3` where aomdec // reads `[4][4] = 6` (class early-return-skips-tail). let saved_luma_ctx = split8.then(|| { ( [ neighbours.left[leaf_mi.0][0], neighbours.left[leaf_mi.0 + 1][0], ], [ neighbours.above[leaf_mi.1][0], neighbours.above[leaf_mi.1 + 1][0], ], ) }); // lane-t900 r23: every leaf stamps its palette state (all-zero for an // inter leaf or a non-palette intra one, real for a palette block) into // the mi-granular neighbour bands, so the next intra block's // `av1_get_palette_mode_ctx` and colour cache see exactly what libaom's // mode-info grid holds. record_strip_palette( neighbours, leaf_mi, 8, 8, palette_record8.0, palette_record8.1, palette_record8.2, palette_record8.3, ); neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); if let Some((left, above)) = saved_luma_ctx { for (cell, state) in left.into_iter().enumerate() { neighbours.left[leaf_mi.0 + cell][0] = state; } for (cell, state) in above.into_iter().enumerate() { neighbours.above[leaf_mi.1 + cell][0] = state; } } // lane-cdef r1: ... and the CDEF skip band too. `apply_cdef`'s // `is_8x8_block_skip` (libaom `cdef.c:29-38`) reads all four mi // cells of the 8x8; this leaf wrote none of them, so a 64x64 // whose bottom-right 16x16 is an all-skip 8x8-leaf group kept // the PREVIOUS frame's flags and got filtered where libaom's // dlist excludes it (3 luma samples on a 192x128 inter frame). hit!(INTER8_SKIP_BAND_HITS); neighbours.fill_skip_grid(leaf_mi, 2, skip); // lane-sub8x4 r2: `split8` is this leaf's OWN var-tx split, so // the deblock grid must publish the TX_4X4 leaves' width the // same way the fall-through arm below does (libaom // `get_transform_size`, av1_loopfilter.c:207, reads the per-TU // `inter_tx_size` for a non-skip inter luma block). Hardcoding // 8 here left a compound var-tx 8x8 leaf's interior vertical // edge at x % 8 == 4 unfiltered -- class early-return-skips-tail, // third instance in this same arm. neighbours.fill_lf_grid( leaf_mi, 2, if split8 { 4 } else { 8 }, if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 }, fctx, ); return Ok(( skip, is_inter, skip_mode, compound_ctx8, leaf_filter_syms, leaf_refs, )); } } // lane-gmaffine r1: the leaf reads the FULL `single_ref` tree // ([`read_single_ref`], the same one the 16x16+ leaf uses, with the // real per-neighbour p1..p6 contexts) instead of the old three-symbol // LAST-only probe plus a refusal -- aomenc picks GOLDEN/ALTREF for // 8x8 leaves constantly, so that refusal was what every 8x8 gate // actually stopped at. let ref_frame = read_single_ref( dec, cdfs, neighbours.above_ref[cmi], neighbours.above_ref1[cmi], neighbours.left_ref[rmi], neighbours.left_ref1[rmi], ); leaf_refs = (ref_frame, None); // lane-defer8: this leaf's reference SIZE at parse, its pictures // inside the prediction closure below. let (ref_width, _) = ref_dims(ref_frame, refpix)?; let (mi_row, mi_col) = leaf_mi; // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS // leaf's own reference (lane-gmaffine r1 taught it non-LAST refs). let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { field: t.field, cur_offset_0: crate::motion_field::get_relative_dist( t.order_hint_bits, t.order_hint, t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, }); let stack = crate::mvstack::find_mv_stack_with_sign_bias( grid, mi_row, mi_col, 2, 2, ref_frame, mi_cols as usize, mi_rows as usize, sign_bias_table, &gm_table, tpl, ); // lane-interp3 r2: same per-entry EC_STACK ladder // [`decode_inter_block`]'s single-ref arm prints, so this leaf's stack // diffs line for line against the oracle's. if crate::envflags::env_flag!("EC_TRACE_MODE") { for (i, e) in stack.entries.iter().enumerate() { eprintln!( "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}", e.mv.0, e.mv.1, e.weight ); } } let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; let (mv, is_new_mv) = if !not_new { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): // read at most two `drl_mode` bits, one per stack entry past the // first, stopping at the first `0`. The chosen index selects // which stack entry `read_mv`'s base predictor comes from // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`) // -- entry 0 (`stack.pred_mv`) only when the loop never advances. let mut idx = 0usize; while idx < 2 && stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); ( read_mv( dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, base_mv, allow_high_precision_mv, force_integer_mv, ), true, ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; is_globalmv = !not_zero; let mv = if !not_zero { // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same // `gm_get_motion_vector` value the 16x16+ leaf reads out of // its own `gm_table`, computed at this block's centre. hit!(GLOBALMV_HITS_8); gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; if nearest { stack.nearest_mv } else { let mut idx = 1usize; while idx < 3 && stack.entries.len() > idx + 1 { if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { break; } idx += 1; } stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) } }; (mv, false) }; // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too -- // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always // `is_interintra_allowed_bsize`-eligible, single-ref-only branch // (compound already returned above), GLOBALMV already refused // (round 3), so the only real gate left is the header enable bit. let mut interintra_mode: Option = None; let mut wedge_mask: Option<(&'static [u8], usize)> = None; if enable_interintra_compound && !skip_mode { let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1; if interintra { // lane-interintra r1: same read pair as the 16/32 site; // wedge cdf row = BLOCK_8X8 (index 3), read on block size // alone, never the `enable_interintra_wedge` seq bit. let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8; let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1; if wedge { // lane-wii r2: same adapting `wedge_index` symbol as the // 16/32 leaf, fixed sign 0 -- see that site's comment. let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]); hit!(WII_HITS); wedge_mask = Some(( crate::wedge::wedge_masks() .codebook(SIDE, SIDE) .mask(0, wedge_index as usize), SIDE, )); } else { hit!(INTERINTRA_HITS); } interintra_mode = Some(ii); } } // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8 // is the spec's own minimum eligible size, single-ref-only branch, // no interintra reader, `IDENTITY`-only global motion). Mirrors the // 16x16 leaf's own `decode_inter_block` read (see its doc above) -- // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1` // refusal (warp needs `av1_findSamples`, not ported at either leaf). // lane-gmaffine r1: the two libaom predicates, exactly as the // 16x16+ leaf resolves them (see [`decode_inter_block`]'s own doc): // `is_global_mv_block` (mode GLOBAL*, model > TRANSLATION, block // >= 8x8 -- BLOCK_8X8 IS the 8px minimum, so the size predicate is // always true here) suppresses the motion_mode read entirely and // turns on the global warp below. let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; let is_global_mv_block = is_globalmv && gm_ref.model as u8 > 1; let motion_mode_eligible = switchable_motion_mode && !skip_mode && interintra_mode.is_none() && !(is_global_mv_block && !force_integer_mv) && has_overlappable_neighbour( grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ); let mut warp_params: Option = None; let mut warped_selected = false; let mut obmc_selected = false; if motion_mode_eligible { // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf // (see its own doc) -- this leaf is always `LAST_FRAME`-only // (grid.set below hardcodes it). // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`) // when the reference is scaled. Not gated here because an 8x8 // leaf under a scaled reference is refused before this function // runs (see the block8 refusal below, ~12500) -- whoever lifts // that refusal must add `&& !ref_is_scaled` here too. // lane-fimv r1: libaom `motion_mode_allowed` also requires // `!xd->cur_frame_force_integer_mv`, so a screen-content frame // that set `force_integer_mv` reads the 2-symbol `obmc_cdf` here // (class wrong-alphabet-same-value). let proj_ok = num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame, fctx) >= 1; // lane-t900 r28: the `&& !ref_is_scaled` the note above asked the // lifter of the 8x8-leaf refusal to add. libaom // `motion_mode_allowed` (blockd.h) makes WARPED_CAUSAL eligible // only `if (mbmi->num_proj_ref >= 1 && (allow_warped_motion && // !av1_is_scaled(xd->block_ref_scale_factors[0])))`, so under a // scaled reference the ALPHABET shrinks to the 2-symbol obmc one // -- and with OBMC off no symbol is read at all (class // wrong-alphabet-same-value: reading the 3-symbol row here // desynced every warped-motion superres stream at its first // eligible 8x8 leaf). let ref_is_scaled = mc::scale_factor(ref_width, frame_width) != mc::REF_NO_SCALE; let warp_eligible = allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok; if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_MM8 mi_row={mi_row} mi_col={mi_col} proj={} warp_elig={} awm={}", proj_ok as u8, warp_eligible as u8, allow_warped_motion as u8 ); } if allow_warped_motion && proj_ok && ref_is_scaled { hit!(SCALED_WARP_SUPPRESSED_HITS); } if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv { hit!(FIMV_ALPHABET_HITS); } if warp_eligible { let mode = dec.symbol(&mut cdfs.motion_mode[0]); match mode { 0 => {} 1 => { obmc_selected = true; hit!(OBMC_HITS); hit!(OBMC_HITS_8); } _ => { // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf -- // the same findSamples -> select_samples -> // av1_find_projection chain the 16x16+ leaf runs, // with BLOCK_8X8's own 8x8 model centre; an // unusable projection falls back to the block's // translational mv (libaom `av1_find_projection` // returning 1 leaves `wm_params` invalid and // `build_inter_predictors` skips the warp). hit!(WARP_SELECTED_HITS); let mut samples = find_samples( grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame, fctx, ); if samples.len() > 1 { crate::warp::select_samples(mv, &mut samples, SIDE as i32, SIDE as i32); } warp_params = crate::warp::find_projection( &samples, SIDE as i32, SIDE as i32, mv.1, mv.0, mi_row as i32, mi_col as i32, ); warped_selected = true; if warp_params.is_some() { hit!(WARP_HITS_8); } } } } else { // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3. obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1; if obmc_selected { hit!(OBMC_HITS); hit!(OBMC_HITS_8); } } } // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8 // leaf, in libaom's own order (interintra, motion_mode, THEN the // filter). Until this round the leaf read no filter symbol at all and // predicted Regular unconditionally -- correct only for a frame with a // fixed `interp_filter`, and a silent entropy DESYNC for every // SWITCHABLE-filter stream that reaches an 8x8 leaf (which is what // made the interior-split wiring above unusable at first). // corner-cut: the neighbour filter context is the enclosing 16x16 // block's own coarse `above_filter`/`left_filter` entry (this leaf // path keeps no per-leaf neighbour array), so all four siblings read // the same context row. Ceiling: a stream whose 8x8 siblings pick // DIFFERENT filters decodes the second..fourth leaf's symbol from the // wrong CDF row. Upgrade: give `Neighbours` a real 8x8-granular // filter array, same shape as the `[3, 3]` approximation the caller // records after the leaf loop. let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame || neighbours.above_ref1[cmi] == Some(ref_frame) { neighbours.above_filter[cmi] } else { [3, 3] }; let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame || neighbours.left_ref1[rmi] == Some(ref_frame) { neighbours.left_filter[rmi] } else { [3, 3] }; let gm_nontrans = is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation; let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, cdfs, interp_fixed, enable_dual_filter, gm_nontrans || warped_selected || skip_mode, above_filter_ctx, left_filter_ctx, false, ); leaf_filter_syms = resolved_filter; if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}", leaf_mi.0, leaf_mi.1, mv.0, mv.1, stack.entries.len(), dec.debug_state().0 ); } // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` -- // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model // wins (`is_none()` guard); BLOCK_8X8 already satisfies the >=8px // size predicate baked into `is_global_mv_block`. if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid { warp_params = crate::warp::global_warp_params(gm_ref.params); if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine { hit!(AFFINE_GM_HITS); } } if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}", leaf_mi.0, leaf_mi.1, warp_params.is_some(), ); } grid.fill_rect( mi_row, mi_col, 2, 2, MiInfo { is_inter: true, ref_frame, // INTRA_FRAME marker for interintra blocks -- keeps // them out of warp-sample gathering (see 16/32 site). ref_frame1: if interintra_mode.is_some() { 0 } else { NO_REF1 }, mv1: (0, 0), mv: mv16(mv), is_new_mv, size: 2, size_h: 2, is_global_mv0: is_global_mv_block, is_global_mv1: false, }, ); mode_for_tx = 0; // lane-scaledref r1: this leaf's own prediction is always `Regular` // (documented corner-cut above); under a scaled reference the same // fixed kernel runs through spec 7.11.3.3's scaled walk instead. let luma_scale = mc::scale_factor(ref_width, frame_width); if luma_scale != mc::REF_NO_SCALE { hit!(SCALED_BLOCK8_HITS); } let obmc = if obmc_selected { Some(obmc_plan( grid, &neighbours.above_filter, &neighbours.left_filter, mi_row, mi_col, 2, 2, mi_rows as usize, mi_cols as usize, SIDE, SIDE, SIDE, CHROMA_SIDE, px, py, cpx, cpy, refpix, interp_fixed, frame_width, )?) } else { None }; // lane-defer8: this leaf's whole prediction as a closure, so it runs // where its writes run -- on a recon worker at more than one // reconstruction thread, exactly like [`decode_inter_block`]'s. let build = move |y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let Some((sref_y, sref_u, sref_v)) = ref_planes_deferred(ref_frame, refpix) else { return; }; let mut pred_y = refill(std::mem::take(&mut out[0]), SIDE * SIDE); let mut pred_u = refill(std::mem::take(&mut out[1]), CHROMA_SIDE * CHROMA_SIDE); let mut pred_v = refill(std::mem::take(&mut out[2]), CHROMA_SIDE * CHROMA_SIDE); // Merge of lane-gmaffine (this leaf's own switchable filters) with // lane-scaledref (spec 7.11.3.3's scaled walk): same kernels either // way, only the sample walk differs. for (plane, x, y, dim, dst) in [ (sref_y, px, py, SIDE, &mut pred_y), (sref_u, cpx, cpy, CHROMA_SIDE, &mut pred_u), (sref_v, cpx, cpy, CHROMA_SIDE, &mut pred_v), ] { let luma = std::ptr::eq(plane, sref_y); if luma_scale == mc::REF_NO_SCALE { mc::predict_with_filters( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(x, mv.1, luma), mv_to_q4(y, mv.0, luma), dim, dim, h_filter, v_filter, dst, fctx, ); } else { mc::predict_scaled( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(x, mv.1, luma), mv_to_q4(y, mv.0, luma), luma_scale, dim, dim, h_filter, v_filter, dst, fctx, ); } } // lane-gmaffine r1: the warp filter REPLACES the translational // prediction just built (libaom builds one or the other), same as // the 16x16+ leaf's own call trio. // lane-t900 r28: `allow_warp`'s scaled-reference bail-out, which this // leaf was missing -- it is the defect the 8x8-leaf refusal hid (a // warped 8x8 leaf over a superres reference; libaom predicts it // translationally, every symbol still read). if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) { crate::warp::warp_affine( params, &sref_y.data, sref_y.true_width as i32, sref_y.true_height as i32, sref_y.width as i32, &mut pred_y, px as i32, py as i32, SIDE as i32, SIDE as i32, SIDE as i32, 0, 0, fctx, ); // `av1_init_warp_params`'s per-plane `block_width/height < 8` // bail-out: an 8x8 leaf's chroma plane is 4x4 in 420, so it is // predicted translationally even when the luma warps. #[allow(clippy::absurd_extreme_comparisons)] if CHROMA_SIDE >= 8 { crate::warp::warp_affine( params, &sref_u.data, sref_u.true_width as i32, sref_u.true_height as i32, sref_u.width as i32, &mut pred_u, cpx as i32, cpy as i32, CHROMA_SIDE as i32, CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1, fctx, ); crate::warp::warp_affine( params, &sref_v.data, sref_v.true_width as i32, sref_v.true_height as i32, sref_v.width as i32, &mut pred_v, cpx as i32, cpy as i32, CHROMA_SIDE as i32, CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1, fctx, ); } } if let Some(plan) = &obmc { obmc_run(plan, refpix, &mut pred_y, &mut pred_u, &mut pred_v, fctx); } // Non-wedge interintra blend, mutually exclusive with OBMC (the // motion_mode symbol is not read for an interintra block). if let Some(ii) = interintra_mode { interintra_blend(y, px, py, SIDE, SIDE, SIDE, ii, wedge_mask, &mut pred_y, fctx); interintra_blend( u, cpx, cpy, CHROMA_SIDE, CHROMA_SIDE, CHROMA_SIDE, ii, wedge_mask, &mut pred_u, fctx, ); interintra_blend( v, cpx, cpy, CHROMA_SIDE, CHROMA_SIDE, CHROMA_SIDE, ii, wedge_mask, &mut pred_v, fctx, ); } *out = [pred_y, pred_u, pred_v]; }; let deferred = recon_deferred(fctx); let (pred_y, pred_u, pred_v): (Vec, Vec, Vec); let (sy, su, sv) = if deferred { push_pred(fctx, build); ( Pred::Cur { plane: 0, stride: SIDE, off: 0 }, Pred::Cur { plane: 1, stride: CHROMA_SIDE, off: 0 }, Pred::Cur { plane: 2, stride: CHROMA_SIDE, off: 0 }, ) } else { // The interintra predictor reads this block's own above/left // edges: deferred, the wavefront rule has them written by the time // the worker runs; inline, the queue has to drain first. if interintra_mode.is_some() { flush_recon(fctx, y, u, v); } let mut built: [Vec; 3] = Default::default(); build(y, u, v, fctx, &mut built); let [by, bu, bv] = built; (pred_y, pred_u, pred_v) = (by, bu, bv); ( Pred::Inline(&pred_y, SIDE), Pred::Inline(&pred_u, CHROMA_SIDE), Pred::Inline(&pred_v, CHROMA_SIDE), ) }; split8 = read_block_tx_size( dec, cdfs, neighbours, leaf_mi, SIDE, (mi_cols as usize, mi_rows as usize), true, skip, fctx, )? .1 .is_some(); if skip { push_mc(0, px, py, SIDE, sy, &ZERO_RESIDUAL[..SIDE * SIDE], fctx); push_mc(1, cpx, cpy, CHROMA_SIDE, su, &ZERO_RESIDUAL[..CHROMA_SIDE * CHROMA_SIDE], fctx, ); push_mc(2, cpx, cpy, CHROMA_SIDE, sv, &ZERO_RESIDUAL[..CHROMA_SIDE * CHROMA_SIDE], fctx, ); luma_grid = Grid::Zero(SIDE * SIDE); u_grid = Grid::Zero(CHROMA_SIDE * CHROMA_SIDE); v_grid = Grid::Zero(CHROMA_SIDE * CHROMA_SIDE); } else { let around = neighbours.around_mi(leaf_mi, 8); let (grid8, luma_tx_type) = read_inter_luma8( dec, cdfs, neighbours, leaf_mi, y, px, py, sy, mode_for_tx, base_q_idx, scan8, scan4, reduced_tx_set, split8, fctx, )?; luma_grid = grid8; u_grid = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], mode_for_tx, u, cpx, cpy, CHROMA_SIDE, base_q_idx, su, Some(luma_tx_type), None, fctx, )? .0; v_grid = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], mode_for_tx, v, cpx, cpy, CHROMA_SIDE, base_q_idx, sv, Some(luma_tx_type), None, fctx, )? .0; } } else { let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]); if mode >= 13 { return Err(unsupported( "an intra mode this decoder does not code (round 2)", )); } // lane-angleinter r1: `read_intra_angle_info` (libaom `decodemv.c`, // inside `read_intra_block_mode_info`) -- an intra block in an inter // frame reads `angle_delta_y` off the same // `angle_delta_cdf[mode - V_PRED]` row a key-frame block does, and // the delta feeds the directional predictor (and the edge // filter/upsample decision derived from the delta'd angle) unchanged. // The symbol was read and then refused before this round even though // aomenc enables `--enable-angle-delta` by default. let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) } else { 0 }; if angle_delta_y != 0 { hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS); // lane-leaf8tx r1: `av1_use_angle_delta(BLOCK_8X8)` is true // (`bsize >= BLOCK_8X8`), so this leaf codes `angle_delta_y` off // `angle_delta_cdf[mode - V_PRED]` exactly as a key-frame block // does (libaom `read_intra_angle_info` inside // `read_intra_block_mode_info`, decodemv.c), and the delta feeds // the directional predictor + the edge filter/upsample decision // through the same `reconstruct` argument below. Counted // separately from the >=16x16 arm so the gate cannot be satisfied // by a bigger block. hit!(INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS); } // lane-uv8 r1: the delta'd angle decides the intra edge filter, and a // directional luma mode is already legal on this leaf -- the arm // passed a hardcoded `false` where [`decode_leaf8`] reads the // mi-exact neighbour modes (`get_intra_edge_filter_type`, spec // 7.11.2). let (above_mode, left_mode) = neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, neighbours.modes_above_left(r, c)); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); // lane-uv8 r1: libaom `read_intra_block_mode_info` (decodemv.c:1198-1207) // -- `uv_mode` over the CFL-allowed alphabet (`is_cfl_allowed`: a // BLOCK_8X8 leaf is inside the 32x32 bound), then `read_cfl_alphas` // for `UV_CFL_PRED`, then `angle_delta_uv` off the MAPPED uv mode's // row (`get_uv_mode`, identity over `V_PRED..=D67_PRED`). Every value // but `DC_PRED` was refused here, which is what blocked the low-cq // CDEF arms and the 10-bit gates. let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_ISTEP8 mi_row={} mi_col={} name=modes y={mode} uv={uv_mode} fi_enabled={} rng={}", leaf_mi.0, leaf_mi.1, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), dec.debug_state().0 ); } if (9..=12).contains(&uv_mode) { hit!(SMOOTH_UV_HITS); hit!(INTRA_IN_INTER8_UV_SMOOTH_HITS); } let alpha = if uv_mode == UV_CFL_PRED { hit!(INTRA_IN_INTER8_UV_CFL_HITS); Some(read_cfl_alphas(dec, cdfs)) } else { None }; let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { hit!(DIRECTIONAL_UV_HITS); hit!(INTRA_IN_INTER8_UV_DIR_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; if angle_delta_uv != 0 { hit!(UV_ANGLE_DELTA_HITS); hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS); } // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED`. uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; // The CHROMA neighbour's own `uv_mode` decides the chroma edge filter // strength (`get_intra_edge_filter_type`, reconintra.c:974), never the // luma one -- same read [`decode_leaf8`] does. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/ // `uv_mode` are both effectively `DC_PRED`-gated already on this // leaf (a nonzero `mode` still passes, but `uv_mode` is forced // `DC_PRED` by the refusal just above), same order as libaom's // `read_palette_mode_info` call right after `xd->cfl.store_y`. // lane-t900 r23: reconstructed, not refused. Same syntax, same // deferral of the colour-index maps past `use_filter_intra` // (`av1_visit_palette` runs from `parse_decode_block`, after the whole // mode-info read) as the >=16 intra-in-inter block's own copy in // [`decode_inter_block`]; the mode context, the colour cache and the // `palette_uv_mode` context are this leaf's REAL ones, not the // hardcoded 0/empty pair the refusal could get away with while no // neighbour could ever be a palette (class // [[cdf-row-held-constant]]). `av1_get_palette_bsize_ctx(BLOCK_8X8)` // = `num_pels_log2_lookup[BLOCK_8X8] - 6` = row 0. let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi); let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi); let mut palette_y_pending: Option<(usize, [u16; 8])> = None; let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(SIDE) { let use_palette_y = mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0; if use_palette_y { let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx))); } // lane-uv8 r1: `read_palette_mode_info` reads the UV symbol only // when `uv_mode == UV_DC_PRED` (decodemv.c). let use_palette_uv = uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; if crate::envflags::env_flag!("EC_PALSYN") { eprintln!( "EC_PALSYN leaf8 mi={},{} bw=8 bh=8 mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", leaf_mi.0, leaf_mi.1, palette_y_pending.map_or(0, |(n, _)| n), u8::from(use_palette_uv), dec.debug_state().0 ); } if use_palette_uv { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx); palette_uv_pending = Some((n, u_colors, v_colors)); } } // lane-fiinter r1: `read_filter_intra_mode_info` (libaom `decodemv.c`, // the tail of `read_intra_block_mode_info`) -- an intra block inside // an INTER frame reads `use_filter_intra` in exactly the same place a // key-frame block does, right after the palette syntax. Nothing read // it here before this round, and aomenc enables filter intra by // default, so every inter frame carrying one desynced at this symbol. // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied: // a real palette-Y block already returned above. let mut filter_intra = None; // lane-uv8 r2: the oracle's `EC_ISTEP` ladder (`EC_TRACE_MODE_STEP`) // prints `use_filter_intra` for an intra block inside an INTER frame // and nothing else, so this leaf needs the same two lines for a // range-ladder diff against it. let ec_istep8 = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); if mode == DC_PRED && fctx.enable_filter_intra_inter.with(std::cell::Cell::get) // `av1_filter_intra_allowed` (reconintra.h:77) excludes a // palette-Y block, so no `use_filter_intra` symbol exists there. && palette_y_pending.is_none() && let Some(class) = filter_intra_size_class(SIDE) { let use_fi = dec.symbol(&mut cdfs.filter_intra[class]) != 0; if ec_istep8 { eprintln!( "EC_ISTEP mi_row={} mi_col={} name=use_filter_intra val={} rng={}", leaf_mi.0, leaf_mi.1, u8::from(use_fi), dec.debug_state().0 ); } if use_fi { hit!(FILTER_INTRA_HITS); hit!(INTRA_IN_INTER_FILTER_INTRA_HITS); let fi = dec.symbol(&mut cdfs.filter_intra_mode); if ec_istep8 { eprintln!( "EC_ISTEP mi_row={} mi_col={} name=filter_intra_mode val={fi} rng={}", leaf_mi.0, leaf_mi.1, dec.debug_state().0 ); } filter_intra = Some(fi); } } // lane-t900 r23: `av1_visit_palette` -- the two colour-index maps, Y // then the shared chroma one, after the WHOLE mode-info read. let palette_y = palette_y_pending.map(|(n, colors)| { let map = decode_color_index_map_wh(dec, cdfs, n, SIDE, SIDE, false); hit!(PALETTE_HITS); hit!(INTRA_IN_INTER_PALETTE_Y_HITS); hit_do! { INTER8_PALETTE_HITS.with(|c| { let mut v = c.get(); v.0 += 1; c.set(v); }); } PaletteY { size: n, colors, map } }); let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { // `av1_get_plane_block_size(BLOCK_8X8, 1, 1)` = BLOCK_4X4. let map = decode_color_index_map_wh(dec, cdfs, n, CHROMA_SIDE, CHROMA_SIDE, true); hit!(PALETTE_UV_HITS); hit!(INTRA_IN_INTER_PALETTE_UV_HITS); hit_do! { INTER8_PALETTE_HITS.with(|c| { let mut v = c.get(); v.1 += 1; c.set(v); }); } PaletteUv { size: n, u_colors, v_colors, map } }); palette_record8 = ( palette_y.as_ref().map_or(0, |p| p.size), palette_y.as_ref().map_or([0u16; 8], |p| p.colors), palette_uv.as_ref().map_or(0, |p| p.size), palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors), ); // A palette block predicts from its own colour-index map, never from // the block edge (spec 7.11.2/7.11.4) -- these ride the // [`PALETTE_PRED`] slot into each `reconstruct`/`read_plane` call // below, exactly as the key-frame and >=16 intra-in-inter paths do. let palette_y_buf: Option> = palette_y.as_ref().map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|p| { ( p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), ) }); mode_for_tx = mode; let (mi_row, mi_col) = leaf_mi; grid.fill_rect( mi_row, mi_col, 2, 2, MiInfo { is_inter: false, ref_frame: -1, ref_frame1: NO_REF1, mv1: (0, 0), mv: (0, 0), is_new_mv: false, size: 2, size_h: 2, is_global_mv0: false, is_global_mv1: false, }, ); // lane-leaf8tx r1: the 8x8 leaf's own intra `tx_depth` (libaom // `read_tx_size` -> `read_selected_tx_size`, max depth 1 at // BLOCK_8X8) resolves to TX_4X4, and `decode_block` // (`decodeframe.c`) then codes one intra prediction + one // coefficient set PER 4x4 transform unit in raster order, each unit // predicting off the units reconstructed before it -- the same loop // the >=16x16 intra-in-inter arm runs. Chroma stays one 4x4 unit // (`av1_get_max_uv_txsize`). let intra_leaves = read_block_tx_size( dec, cdfs, neighbours, leaf_mi, SIDE, (mi_cols as usize, mi_rows as usize), false, skip, fctx, )? .1; // lane-leaf8tx r4: the per-TU loop below is entropy- and pixel-exact // against aomdec once `tx_size_context_txfm` stopped reading // `above_inter`/`left_inter` four mi away (r3), so the refusal that // used to sit here is lifted; gate // `a_real_aomenc_{,10bit_}inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact`. split8 = intra_leaves.is_some(); let reach = Reach::of(SIDE, px, py, y.width, y.height, fctx); if let Some(leaves) = intra_leaves { for &(row, col, tx_px, _) in &leaves { let tu_mi = (leaf_mi.0 + row, leaf_mi.1 + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); // A transform unit inside a block is not a block at that // position: top-right / bottom-left availability is the // block's, narrowed by the unit's offset inside it. let tu_reach = Reach::of_tu(SIDE, SIDE, col * MI, row * MI, tx_px, tx_px, reach); // This unit's own window on the block's palette prediction // (the whole-block buffer would be indexed at the wrong // stride by the first unit). if let Some(buf) = &palette_y_buf { hit!(PALETTE_SPLIT_TX_HITS); let window: Vec = (0..tx_px) .flat_map(|i| { let base = (row * MI + i) * SIDE + col * MI; buf[base..base + tx_px].iter().copied() }) .collect(); set_palette_pred(window, fctx); } let tu_grid = if skip { push_intra(0, tu_px, tu_py, tx_px, mode, angle_delta_y, tu_reach, &ZERO_RESIDUAL[..tx_px * tx_px], None, filter_intra, smooth_neighbor, fctx, ); Grid::Zero(tx_px * tx_px) } else { // The unit is smaller than the block it sits in, so // `txb_skip_ctx` is the neighbour-magnitude table, not // the lone-TU 0 (`get_txb_ctx_general`). let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI); read_plane( dec, cdfs, // Intra 4x4 luma: seven-type // `EXT_TX_SET_DTT4_IDTX_1DDCT` unless reduced, whose // CDF row is the intra dir (`fi_tx_row` inside // `read_plane` maps a filter-intra block's). txbset_for(tx_px, reduced_tx_set), default_scan(tx_px), 0, neighbours.around_mi(tu_mi, tx_px)[0], mode, mode, angle_delta_y, tu_reach, y, tu_px, tu_py, tx_px, tx_px, base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )? }; neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid); } } if skip { if !split8 { if let Some(buf) = &palette_y_buf { set_palette_pred(buf.clone(), fctx); } push_intra(0, px, py, SIDE, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..SIDE * SIDE], None, filter_intra, smooth_neighbor, fctx, ); } // CfL's AC contribution is the luma this leaf just reconstructed, // averaged over the 4x4 chroma block (`cfl_ac_q3`, spec 7.11.5). let ac = alpha.map(|_| cfl_src(px, py, SIDE)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } push_intra(1, cpx, cpy, CHROMA_SIDE, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..CHROMA_SIDE * CHROMA_SIDE], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } push_intra(2, cpx, cpy, CHROMA_SIDE, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..CHROMA_SIDE * CHROMA_SIDE], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); luma_grid = Grid::Zero(SIDE * SIDE); u_grid = Grid::Zero(CHROMA_SIDE * CHROMA_SIDE); v_grid = Grid::Zero(CHROMA_SIDE * CHROMA_SIDE); } else { let around = neighbours.around_mi(leaf_mi, 8); luma_grid = if split8 { // Already coded and reconstructed unit by unit above; the // block-level grid only feeds the neighbour write-back, // which the `saved_luma_ctx` restore below keeps per-TU. Grid::Zero(SIDE * SIDE) } else { if let Some(buf) = &palette_y_buf { set_palette_pred(buf.clone(), fctx); } read_plane( dec, cdfs, // lane-uv8 r3: an intra leaf inside an inter frame is // `is_inter == 0` in `av1_get_ext_tx_set_type`, so its 8x8 // luma reads the INTRA set -- seven-type // `EXT_TX_SET_DTT4_IDTX_1DDCT` when `reduced_tx_set == 0`, // five-type `EXT_TX_SET_DTT4_IDTX` when it is 1. Hardcoding // the reduced set read the wrong ALPHABET (class // [[wrong-alphabet-same-value]]) and desynced at the leaf's // first `tx_type`. txbset_for(8, reduced_tx_set), scan8, 0, around[0], mode, mode, angle_delta_y, reach, y, px, py, SIDE, TX8, base_q_idx, None, filter_intra, None, smooth_neighbor, fctx, )? }; let ac = alpha.map(|_| cfl_src(px, py, SIDE)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } u_grid = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], mode, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, CHROMA_SIDE, TX4, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } v_grid = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], mode, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, CHROMA_SIDE, TX4, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; } } // lane-txselect: a split leaf's plane-0 neighbour context is per 4x4 // transform unit (written by `record_mi_luma` inside `read_inter_luma8`), // but `record_mi` rewrites all three planes of these cells at once -- so // save plane 0 across it, exactly as `record_split_luma` leaves plane 0 // alone at the bigger block sizes. let saved_luma_ctx = split8.then(|| { ( [ neighbours.left[leaf_mi.0][0], neighbours.left[leaf_mi.0 + 1][0], ], [ neighbours.above[leaf_mi.1][0], neighbours.above[leaf_mi.1 + 1][0], ], ) }); // lane-t900 r23: every leaf stamps its palette state (all-zero for an // inter leaf or a non-palette intra one, real for a palette block) into // the mi-granular neighbour bands, so the next intra block's // `av1_get_palette_mode_ctx` and colour cache see exactly what libaom's // mode-info grid holds. record_strip_palette( neighbours, leaf_mi, 8, 8, palette_record8.0, palette_record8.1, palette_record8.2, palette_record8.3, ); neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); // lane-uv8 r1: this leaf never stamped a mode band at all, so the block // below/right of it read whatever block last wrote the coarse [`SUB`] // slot -- now that an intra leaf here can code a smooth/directional // `uv_mode`, its chroma neighbours must see it (and an inter leaf must // stamp `DC_PRED`, what libaom stores for a non-intra block). Same pair // [`decode_leaf8`] writes, plus the coarse fallback slots. neighbours.above_uv_mode[c] = uv_predict_mode; neighbours.left_uv_mode[r] = uv_predict_mode; neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode_for_tx); neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); if let Some((left, above)) = saved_luma_ctx { for (cell, state) in left.into_iter().enumerate() { neighbours.left[leaf_mi.0 + cell][0] = state; } for (cell, state) in above.into_iter().enumerate() { neighbours.above[leaf_mi.1 + cell][0] = state; } } // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test). // lane-cdef r1: the fall-through twin of the compound arm's skip-band // write above -- `skip` is one flag for the whole 8x8 leaf (read at // `decode.rs`'s `skip_ctx` site), `split8` only splits its transform. // lane-intersub8 r5: ... and it counts too. r1 incremented the counter in // the COMPOUND early-return arm only, so the gate's assert really read // "a COMPOUND 8x8 leaf wrote the band"; once main's inter16ab/r14 routing // landed, the 10-bit cq12 arm's leaves come through here instead and the // gate failed on an instrumentation gap, with the band written either way. hit!(INTER8_SKIP_BAND_HITS); neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid( leaf_mi, 2, if split8 { 4 } else { 8 }, if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 }, fctx, ); Ok(( skip, is_inter, skip_mode, compound_ctx8, leaf_filter_syms, leaf_refs, )) } /// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes, /// against `reference` (the previous frame's own decoded picture, at this /// frame's true size -- a decoder's single-slot DPB, matching what this /// crate's encoder always predicts from), returning the picture it /// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract /// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header, /// `frame_width`/`frame_height` its true render size). /// /// # Errors /// Returns an error under the same conditions [`decode_inter_block`] does, /// or when `reference` is not this frame's own true size, or when the tile /// codes a 16x16 leaf whose own true edge cuts through it (round 2, same /// refusal [`crate::tile`]'s writer gives its encoder). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn decode_inter_frame_tile( data: &[u8], mi_cols: u32, mi_rows: u32, base_q_idx: u8, frame_width: u32, frame_height: u32, refpix: &RefPix<'_>, cdef: &CdefParams, loop_filter: &LoopFilterParams, allow_high_precision_mv: bool, force_integer_mv: bool, interp_fixed: Option, enable_dual_filter: bool, reference_select: bool, // This frame header's `tx_mode == TxMode::Select`: `Encoded::tx_select`. // Hard-coding `false` here desynced at the first `tx_depth` symbol once // inter frames coded Select by default (class: test asserts against a // stale header, second instance). tx_select: bool, // The CDF state this frame's tile was WRITTEN from (`Encoded::start_cdfs`): // an inter frame whose header leaves `disable_frame_end_update_cdf` off // starts from what the previous frame stored, not from the defaults. Same // class as `tx_select` above, third instance. initial_cdfs: Option, // lane-av1obmc: this frame header's own `is_motion_mode_switchable` // (spec 5.9.2). Hard-coding `false` here desynced every stream this // crate's own encoder writes once inter blocks started carrying a // `motion_mode` symbol (class: test asserts against a stale header). switchable_motion_mode: bool, fctx: &crate::decode::FrameCtx, ) -> Result { decode_inter_frame_tile_lr( data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, reference_select, tx_select, &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, switchable_motion_mode, false, fctx, ) } /// [`decode_inter_frame_tile`] with this frame header's own `lr_params`, the /// inter sibling of [`decode_key_frame_tile_lr`]. #[allow(clippy::too_many_arguments)] pub(crate) fn decode_inter_frame_tile_lr( data: &[u8], mi_cols: u32, mi_rows: u32, base_q_idx: u8, frame_width: u32, frame_height: u32, refpix: &RefPix<'_>, cdef: &CdefParams, loop_filter: &LoopFilterParams, allow_high_precision_mv: bool, force_integer_mv: bool, interp_fixed: Option, enable_dual_filter: bool, reference_select: bool, tx_select: bool, lr: &LoopRestorationParams, initial_cdfs: Option, // spec 5.9.2's `ref_frame_sign_bias`, derived by a real decoder from the // order hints its DPB slots hold. A raw tile decode cannot derive it (it // is handed planes, not slots), and hard-coding `NO_SIGN_BIAS` here // desyncs the encoder's own filter-search re-decode of any frame with a // BACKWARD reference -- a pyramid leaf reading its group's hidden // `ALTREF_FRAME` -- since the writer's MV-stack scans flip borrowed // candidates across the bias boundary and this one's did not. Same class // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile // decode has to be told. sign_bias: crate::mvstack::SignBiasTable, // This frame header's own `allow_screen_content_tools`: its intra blocks // then carry the palette syntax (spec 5.11.46), which a raw tile decode // that guessed `false` reads one symbol short of. Placed after // `sign_bias` rather than beside the other bools on purpose (the // `adjacent-same-typed-args` class). allow_screen_content_tools: bool, // lane-av1obmc: this frame header's own `is_motion_mode_switchable` // (spec 5.9.2). Hard-coding `false` here desynced every stream this // crate's own encoder writes once inter blocks started carrying a // `motion_mode` symbol (class: test asserts against a stale header). switchable_motion_mode: bool, // lane-av1obmc2: this frame header's own `allow_warped_motion` (spec // 5.9.2) -- what picks the 3-symbol `motion_mode_cdf` alphabet over the // 2-symbol `obmc_cdf` one at a block with a warp sample. Hard-coding // `false` here desynced every stream this crate's encoder writes with the // warp knob on: the same stale-header class as the parameter above. allow_warped_motion: bool, fctx: &crate::decode::FrameCtx, ) -> Result { let single_tile = TileInfo { mi_col_starts: vec![0, mi_cols], mi_row_starts: vec![0, mi_rows], ..TileInfo::default() }; decode_inter_frame_tiles_lr( &[data], &single_tile, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, reference_select, tx_select, lr, initial_cdfs, sign_bias, allow_screen_content_tools, switchable_motion_mode, allow_warped_motion, fctx, ) } /// [`decode_inter_frame_tile_lr`] for a frame coded as SEVERAL tiles; see /// [`decode_key_frame_tiles_lr`]. #[allow(clippy::too_many_arguments)] pub(crate) fn decode_inter_frame_tiles_lr( tiles: &[&[u8]], tile_info: &TileInfo, mi_cols: u32, mi_rows: u32, base_q_idx: u8, frame_width: u32, frame_height: u32, refpix: &RefPix<'_>, cdef: &CdefParams, loop_filter: &LoopFilterParams, allow_high_precision_mv: bool, force_integer_mv: bool, interp_fixed: Option, enable_dual_filter: bool, reference_select: bool, tx_select: bool, lr: &LoopRestorationParams, initial_cdfs: Option, sign_bias: crate::mvstack::SignBiasTable, // This frame header's own `allow_screen_content_tools` (see the // single-tile wrapper): the palette syntax its intra blocks carry. allow_screen_content_tools: bool, // lane-av1obmc: this frame header's own `is_motion_mode_switchable` // (spec 5.9.2). Hard-coding `false` here desynced every stream this // crate's own encoder writes once inter blocks started carrying a // `motion_mode` symbol (class: test asserts against a stale header). switchable_motion_mode: bool, // lane-av1obmc2: this frame header's own `allow_warped_motion` (spec // 5.9.2) -- what picks the 3-symbol `motion_mode_cdf` alphabet over the // 2-symbol `obmc_cdf` one at a block with a warp sample. Hard-coding // `false` here desynced every stream this crate's encoder writes with the // warp knob on: the same stale-header class as the parameter above. allow_warped_motion: bool, fctx: &crate::decode::FrameCtx, ) -> Result { decode_inter_frame_tile_with_cdfs( tiles, tile_info, mi_cols, mi_rows, base_q_idx, crate::quant::QuantDeltas::default(), frame_width, frame_height, refpix, cdef, loop_filter, lr, initial_cdfs, allow_high_precision_mv, force_integer_mv, sign_bias, [ec_av1_syntax::WarpParams::default(); 7], interp_fixed, enable_dual_filter, 0, 0, [0; 7], None, reference_select, false, false, false, false, [0; 2], true, tx_select, switchable_motion_mode, allow_warped_motion, allow_screen_content_tools, DeltaParams::default(), // `enable_filter_intra`: this crate's own encoder never writes the // sequence bit (`encode.rs`), so no intra-in-inter block of a stream // reaching this entry point reads a `use_filter_intra` symbol. false, None, fctx, ) .map(|(picture, _, _)| picture) } /// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see /// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned /// end-of-tile table. An inter frame's own header can name /// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream), /// so `None` is a real case here, not only a convenience default. pub(crate) fn decode_inter_frame_tile_with_cdfs( tiles: &[&[u8]], tile_info: &TileInfo, mi_cols: u32, mi_rows: u32, base_q_idx: u8, // lane-sbpart r11: see [`decode_key_frame_tile_with_cdfs`]'s own `deltas`. deltas: crate::quant::QuantDeltas, frame_width: u32, frame_height: u32, refpix: &RefPix<'_>, cdef: &CdefParams, loop_filter: &LoopFilterParams, lr: &LoopRestorationParams, initial_cdfs: Option, allow_high_precision_mv: bool, force_integer_mv: bool, sign_bias_table: SignBiasTable, // lane-gm r2: this frame header's own `global_motion` table (spec // 5.9.24), threaded to every `decode_inter_block` call below. global_motion: [ec_av1_syntax::WarpParams; 7], interp_fixed: Option, enable_dual_filter: bool, // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are // always needed (this frame's own saved [`crate::motion_field::MotionField`] // carries them for a *later* frame's projection, spec 7.9); `tpl_field` // is `Some` only when this frame's own header set `use_ref_frame_mvs` // and the caller ([`crate::stream::decode_stream`]) projected one. order_hint_bits: u32, order_hint: u32, ref_order_hints: [u32; 7], tpl_field: Option<&crate::motion_field::TplField>, // lane-av1comp: this frame header's own `reference_select` bit, threaded // to every `decode_inter_block`/`decode_inter_block8` call below. reference_select: bool, // lane-av1comp: `seq_params`' own compound-blend enable bits. enable_masked_compound: bool, enable_jnt_comp: bool, // lane-sb128 r3: this sequence header's own `enable_interintra_compound` // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call // below (spec 5.11.24's `interintra` read). enable_interintra_compound: bool, // lane-av1comp round 14: this frame header's own `skip_mode_present`/ // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/ // `decode_inter_block8` call below. skip_mode_present: bool, skip_mode_frame: [u8; 2], // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to // every inter `tx_type` read below (`false` needs the 12-/16-symbol // `Set1` coefficient tables at 16x16/8x8 rather than the reduced // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]). reduced_tx_set: bool, // lane-txselect: this frame header's own `tx_mode == TxMode::Select` // bit (spec 5.9.14). Together with `reduced_tx_set` it is stashed in a // thread-local by [`set_inter_tx_mode`] rather than threaded through // `decode_inter_block`'s forty parameters -- both are frame-constant, and // only [`read_block_tx_size`]/the var-tx residual loop read them. tx_select: bool, // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/ // `allow_warped_motion` bits, threaded to every `decode_inter_block`/ // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`). switchable_motion_mode: bool, allow_warped_motion: bool, // lane-screen r2: this frame header's own `allow_screen_content_tools` // bit, threaded to every `decode_inter_block`/`decode_inter_block8` // call below -- consumes (never reconstructs) the intra-sub-block // palette syntax libaom's `read_intra_block_mode_info` reads under the // same `av1_allow_palette` gate as the key-frame path. allow_screen_content_tools: bool, // lane-realworld r5: this frame header's own `delta` (spec 5.9.17/5.9.18), // same contract as [`decode_key_frame_tile_with_cdfs`]'s own `delta` // param -- only `q_present`/`q_res` are read. delta: DeltaParams, // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than // threaded through `decode_inter_block`'s fifty parameters -- read by the // intra-in-inter arms' `read_filter_intra_mode_info`. enable_filter_intra: bool, // lane-twostage: called with this frame's own end-of-tile CDFs, motion // field and picture size the moment its last tile symbol is read -- // BEFORE its filters run, so a frame that references this one can start // parsing while this one is still being deblocked/CDEF'd/restored (it // waits for the pixels themselves at its first prediction). `None`, and // the motion field comes back in the return tuple as it always did: // the single-threaded path, and a superres frame (whose final width is // only known after the upscale). stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>, fctx: &crate::decode::FrameCtx, ) -> Result<(Picture, Cdfs, Option)> { set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra, fctx); let tpl_frame = tpl_field.map(|field| TplFrameArgs { field, order_hint_bits, order_hint, ref_order_hints, }); if mi_cols == 0 || mi_rows == 0 { return Err(unsupported("a frame with no mode-info grid")); } let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize); // lane-superres r10: a width mismatch alone is no longer refused here -- // `mc::predict_scaled` (spec 7.11.3.3, threaded through // `decode_inter_block`'s single-ref branch) exists precisely for a // `use_superres` reference at a different width than this frame's own // true size. Height must still match: AV1 superres never scales height // (r8's derivation, `mc.rs`'s own doc), and nothing in this decode path // has a vertical scaling pass. // lane-golomb r8: the comparison is against the header's own frame // height, NOT the mi-rounded `true_height`. libaom compares references // on the CROPPED dimensions -- `av1_setup_scale_factors_for_frame(&sf, // ref->y_crop_width, ref->y_crop_height, cm->width, cm->height)` // (`av1/common/reconinter.c`), and a reference is "scaled" only when // those differ (`av1_is_scaled`). A decoded `Picture` is cropped to // `fw`/`fh`, so for any height that is not a multiple of 8 (68 -> // mi_rows 18 -> `true_height` 72) this test compared 68 against 72 and // refused every same-size reference (class av1-truesize-lane: true // frame size vs mi-rounded). Height must still MATCH: AV1 superres // never scales height, and no path here has a vertical scaling pass. if refpix.dims(1).is_none_or(|(_, h)| h != frame_height as usize) { return Err(unsupported( "a reference picture whose height does not match this frame's own true size", )); } let (cols, rows) = block_grid(mi_cols, mi_rows); let sb128 = sb128(fctx); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); fctx.cdef_bits.with(|c| c.set(cdef.bits)); fctx.cdef_sb_cols.with(|c| c.set(sb_cols as usize)); fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]); let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK); let mut y = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(width * height)), width, height, true_width, true_height, tile_x0: 0, tile_y0: 0, tile_x1: width, tile_y1: height, }; let mut u = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)), width: width / 2, height: height / 2, true_width: true_width / 2, true_height: true_height / 2, tile_x0: 0, tile_y0: 0, tile_x1: width / 2, tile_y1: height / 2, }; let mut v = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)), width: width / 2, height: height / 2, true_width: true_width / 2, true_height: true_height / 2, tile_x0: 0, tile_y0: 0, tile_x1: width / 2, tile_y1: height / 2, }; let scan32 = default_scan(TX32); let scan16 = default_scan(TX16); let scan8 = default_scan(TX8); let scan4 = default_scan(TX4); let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); let mut result_cdfs = base_cdfs.clone(); // spec `decode_tile`: `CurrentQIndex`/`DeltaLF` reset to the frame's own // `base_q_idx`/zero at the top of every tile, not once per frame (mirrors // `decode_key_frame_tile_with_cdfs`'s per-tile reset below); the // delta_q/delta_lf presence/resolution flags themselves are frame-level // and set once here. fctx.delta_q_present.with(|c| c.set(delta.q_present)); fctx.delta_q_res.with(|c| c.set(1i32 << delta.q_res)); fctx.delta_lf_present.with(|c| c.set(delta.lf_present)); fctx.delta_lf_res.with(|c| c.set(1i32 << delta.lf_res)); fctx.delta_lf_multi.with(|c| c.set(delta.lf_multi)); let mut neighbours = Neighbours::new( cols as usize * 2, rows as usize * 2, mi_cols as usize, mi_rows as usize, fctx, ); let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width -- // loop restoration runs after the superres upscale. let mut lr_grid = crate::restoration::RestorationGrid::new( lr, superres(fctx).map_or(frame_width, |(w, _)| w), frame_height, ); // lane-pipefilt: the loop filters of superblock row r run as soon as row // r+1 is reconstructed, on the filter pool, so the frame thread's latency // is the parse plus the last rows' filters instead of parse plus the // whole frame's filter chain. See `pipe_run` for the row lags. let lr_active = (0..3).any(|p| { lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None && lr.loop_restoration_size[p] != 0 }); let pipe_on = pipe_filters_ok(fctx, tile_info.cols, delta.lf_present); let cdef_on = !cdef_all_zero(cdef); let snap_on = pipe_on && (cdef_on || lr_active); let mut pipe_snap = snap_on.then(|| (snap_alloc(&y), snap_alloc(&u), snap_alloc(&v))); let mut pipe = pipe_on.then(|| { if wave_stats() { PIPE_FRAMES.fetch_add(1, Relaxed); } let nbands = (mi_rows as usize).div_ceil(16); let sync = std::sync::Arc::new(PipeSync::new()); let batch = crate::par::Batch::new("ec-av1-filter"); // SAFETY (all four): the pipeline only ever touches superblock rows // the frame thread has finished reconstructing and will not revisit // -- the row-lag argument in `pipe_run`'s module note, checked // end to end by the byte-exact gate. #[allow(unsafe_code)] let (sy, su, sv, sn) = unsafe { ( crate::par::Shared::from_ptr(std::ptr::from_mut(&mut y)), crate::par::Shared::from_ptr(std::ptr::from_mut(&mut u)), crate::par::Shared::from_ptr(std::ptr::from_mut(&mut v)), crate::par::Shared::from_ptr(std::ptr::from_mut(&mut neighbours)), ) }; let cfg = PipeCfg { lf: loop_filter, cdef, idx_grid: fctx.cdef_idx_grid.with(|g| { let g = g.borrow(); (g.as_ptr(), g.len()) }), sb_cols: fctx.cdef_sb_cols.with(std::cell::Cell::get), frame_w: frame_width as usize, frame_h: frame_height as usize, nbands, cdef_on, snap_on, }; let ctx = crate::decode::filter_ctx_copy(fctx); let sync2 = std::sync::Arc::clone(&sync); // lane-pipefilt2: loop restoration is a SECOND worker, chained one // CDEF band behind the first (see `pipe_run_lr`). let lr_sync = lr_active.then(|| std::sync::Arc::new(PipeSync::new())); let lr_sync2 = lr_sync.clone(); #[allow(unsafe_code)] let ssnap = unsafe { crate::par::Shared::from_ptr(std::ptr::from_mut(&mut pipe_snap)) }; let snap = &mut pipe_snap; batch.submit(move || { pipe_run(&sync2, sy, su, sv, sn, cfg, snap, lr_sync2.as_deref(), &ctx) }); if let Some(ls) = lr_sync.clone() { let lcfg = LrCfg { lr, lr_grid: std::ptr::from_mut(&mut lr_grid), frame_w: frame_width as usize, frame_h: frame_height as usize, nbands, }; let ctx2 = crate::decode::filter_ctx_copy(fctx); batch.submit(move || pipe_run_lr(&ls, sy, su, sv, ssnap, lcfg, &ctx2)); } PipeGuard { sync, batch: Some(batch), nbands, lr_sync } }); if !pipe_on && wave_stats() { PIPE_WHOLE.fetch_add(1, Relaxed); } // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets // its own fresh SymbolDecoder over its own byte range and its own fresh // copy of the frame's initial CDFs; only context_update_tile_id's own // end-of-tile adapted table becomes the frame's own output. for (tile_idx, &data) in tiles.iter().enumerate() { let tile_num = tile_idx as u32; let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols); let mi_row0 = tile_info.mi_row_starts[trow as usize]; let mi_row1 = tile_info.mi_row_starts[trow as usize + 1]; let mi_col0 = tile_info.mi_col_starts[tcol as usize]; let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1]; let (sb_r0, sb_r1) = ( (mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows), ); let (sb_c0, sb_c1) = ( (mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols), ); // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` / // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not // once per frame. Carried across a tile boundary, the loop-restoration // coefficients of the next tile decode off the previous tile's // reference -- same symbol count, so entropy and reconstruction stay // exact and only the filtered pixels of every tile after the first // are wrong. let mut lr_reference = [( crate::restoration::WienerInfo::default(), crate::restoration::SgrprojInfo::default(), ); 3]; let mut cdfs = base_cdfs.clone(); fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx))); fctx.quant_deltas.with(|c| c.set(deltas)); fctx.current_delta_lf.with(|c| c.set([0; 4])); let mut dec = SymbolDecoder::new(data); // lane-comppin r9: tile-entry range, the earliest point comparable // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the // first ladder rung before any symbol (partition or otherwise) is read. if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL label=tile_init tell={} range={}", dec.debug_bitpos(), dec.debug_state().0 ); } neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx); y.set_tile_origin( mi_col0 as usize * 4, mi_row0 as usize * 4, (mi_col1 as usize * 4).min(y.width), (mi_row1 as usize * 4).min(y.height), ); u.set_tile_origin( mi_col0 as usize * 2, mi_row0 as usize * 2, (mi_col1 as usize * 2).min(u.width), (mi_row1 as usize * 2).min(u.height), ); v.set_tile_origin( mi_col0 as usize * 2, mi_row0 as usize * 2, (mi_col1 as usize * 2).min(v.width), (mi_row1 as usize * 2).min(v.height), ); // lane-tiles r6: an MV candidate scan (mvstack.rs's grid.get) must // not reach across a tile boundary any more than intra prediction's // PlaneBuf reach does -- bounding the shared grid's own read window // per tile is equivalent to threading tile bounds through every // find_mv_stack* call site (all four read through this one grid). grid.set_tile_bounds( mi_row0 as usize, mi_col0 as usize, mi_row1 as usize, mi_col1 as usize, ); hit!(TILE_HITS); // lane-sb128 r2: at `sb_size == 128` the tile walks each 128x128 // superblock's four 64x64 quadrants in libaom `decode_partition` order // (TL, TR, BL, BR) and reads the 128 root's own loop-restoration units and // partition symbol once per superblock -- exactly what the key-frame tile // loop does; the 64-level body below is unchanged, `read_cdef`'s // per-64x64-quadrant reset (`CDEF_TRANSMITTED`) already matches libaom's // `cdef_idx[(mi_row & 16) >> 4 * 2 + (mi_col & 16) >> 4]` slot per quadrant. // lane-sb128c r1: set when the 128 root resolved to `PARTITION_NONE` -- its // one 128x128 inter block covers all four 64x64 quadrants, so the remaining // three items of this superblock carry no syntax at all (same skip the // key-frame tile loop runs). let mut sb128_none = false; // lane-wave1 step (ii): at one reconstruction thread the recorded writes // are performed at their push sites (nothing reaches the queue below). let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v); // lane-wave1 step (ii): one job per superblock (per 128x128 superblock // when `sb128`, since a 128 block writes across its four 64x64 visits). let wave_shift = u32::from(sb128); let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize); let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 { ( ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1, ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1, ) } else { (0, 0) }; let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols); let waving = fctx.wave.with(|w| w.borrow().is_some()); let mut wave_job = (0usize, 0usize); for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) { // lane-wave1: the previous superblock's recorded writes -- handed to // the wavefront workers, or replayed here at one recon thread (where // the queue is empty, every write having run at its push site). if waving { if sb_start { wave_submit(fctx, wave_job.0, wave_job.1); wave_job = ( (sb_r >> wave_shift) as usize - wave_r0, (sb_c >> wave_shift) as usize - wave_c0, ); } } else { flush_recon(fctx, &mut y, &mut u, &mut v); } if row_start { if let Some(p) = &pipe { // Reconstruction complete through this pixel row: the parse // position itself when reconstruction is inline, the // wavefront's own leading completed rows otherwise. let px = if waving { ((wave_r0 + wave_rows_complete(fctx)) << wave_shift) * 64 } else { sb_r as usize * 64 }; p.note(px / 64); } neighbours.start_row(); } if sb_start { sb128_none = false; } if sb128_none { continue; } { let mut sb128_rect = None; let mut sb128_ab = None; if sb128 && sb_start { let part128 = read_sb128_root( &mut dec, &mut cdfs, &neighbours, lr, &mut lr_grid, &mut lr_reference, sb_r, sb_c, mi_cols, mi_rows, fctx, )?; if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) { // lane-sb128c r9: an AB shape at the 128 root -- one // 128x64/64x128 half plus two 64x64 quadrants, same visit // order as the key-frame path. sb128_none = true; sb128_ab = Some(part128); } if matches!(part128, PARTITION_HORZ | PARTITION_VERT) { // Two 128x64 (HORZ) or two 64x128 (VERT) inter blocks; the // whole 128x128 root is consumed here, so the remaining // three 64-quadrant visits of this superblock carry no // syntax (same skip the NONE arm runs). sb128_none = true; sb128_rect = Some(part128); fctx.cdef_transmitted.with(|c| c.set(false)); } if part128 == PARTITION_NONE { // One 128x128 inter block. Its luma transform is // `max_txsize_rect_lookup[BLOCK_128X128]` = TX_64X64 (four // units, read as var-tx leaves), its uv plane block is // 64x64 with TX_32X32 units (`av1_get_max_uv_txsize`), and // `size_group_lookup[BLOCK_128X128]` is 3, same as 64x64. sb128_none = true; fctx.cdef_transmitted.with(|c| c.set(false)); } } if !sb128 { crate::restoration::read_lr( &mut dec, &mut cdfs, lr, &mut lr_grid, &mut lr_reference, sb_r * SB_MI, sb_c * SB_MI, SB_MI, fctx, ); } fctx.cdef_transmitted.with(|c| c.set(false)); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); // lane-inter4 r1: every rect inter piece below is the same // `decode_inter_block` call with only position / true footprint / // transform-set differing; the macro keeps the new arms readable // instead of six more 60-line copies of the argument list. macro_rules! inter_piece { ($at_mi:expr, $side:expr, $li:expr, $lt:expr, $ch:expr, $ltx:expr, $ctx:expr, $sl:expr, $sc:expr, $sg:expr, $ww:expr, $wh:expr) => { decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, $at_mi, $side, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, $li, $lt, $ch, $ltx, $ctx, $sl, $sc, $sg, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, // lane-sb128c r3: `reject_residual` is about a // RECTANGULAR strip decoded with square dimensions -- // the 128x128 NONE root is square, and a hardcoded // `true` refused every one of them at its first // non-skip block. $ww != $side || $wh != $side, $ww, $wh, allow_screen_content_tools, frame_width as usize, fctx, )? }; } // lane-inter16ab r1: one 8x8 inter leaf of a 16x16-level AB // partition (libaom `decode_partition` PARTITION_HORZ_A/_B/ // VERT_A/_B at BLOCK_16X16 code `bsize2` = BLOCK_8X8 for two of // their three pieces, decodeframe.c ~1900). Same body the // PARTITION_SPLIT arm runs per leaf, minus its own partition // symbol (an AB piece carries none) and its `prev_leaves` // bookkeeping. macro_rules! inter_leaf8 { ($outer:expr, $leaf:expr) => {{ let leaf_mi = $leaf; let ( skip, is_inter, skip_mode_leaf, compound_ctx8, leaf_filter, leaf_refs, ) = decode_inter_block8( &mut dec, &mut cdfs, &mut neighbours, &mut grid, mi_cols, mi_rows, $outer, leaf_mi, &mut y, &mut u, &mut v, refpix, base_q_idx, &scan8, &scan4, allow_high_precision_mv, force_integer_mv, &global_motion, enable_dual_filter, reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, reduced_tx_set, interp_fixed, switchable_motion_mode, allow_warped_motion, allow_screen_content_tools, &sign_bias_table, tpl_frame.as_ref(), frame_width as usize, fctx, )?; neighbours.record_inter_rect_mi( leaf_mi, 2, 2, skip, is_inter, leaf_refs.0, leaf_filter, skip_mode_leaf, ); if let Some(ref1) = leaf_refs.1 && let Some((_, _, group_idx, idx)) = compound_ctx8 { neighbours.record_compound_ctx_rect_mi( leaf_mi, 2, 2, ref1, group_idx, idx, ); } }}; } if let Some(part128) = sb128_ab { // libaom `decode_partition` (decodeframe.c): HORZ_A = TL, TR, // bottom half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, // right half; VERT_B = left half, TR, BR. AB only comes from // the full alphabet symbol (both halves in frame), so there is // no `i > 0` edge break to mirror. let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); let base_mi = sub16_to_mi(at128); let (br_mi, bc_mi) = (base_mi.0 + 16, base_mi.1 + 16); let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize); let _vert_ab = (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B) .then(crate::encode::Reach::vert_ab_partition); let cdef_copy = |src: (usize, usize), dst: (usize, usize)| { fctx.cdef_idx_grid.with(|g| { let mut g = g.borrow_mut(); let cols = fctx.cdef_sb_cols.with(|c| c.get()); if cols == 0 { return; } let (si, di) = ( (q_r + src.0) * cols + q_c + src.1, (q_r + dst.0) * cols + q_c + dst.1, ); if q_c + src.1 < cols && q_c + dst.1 < cols && si < g.len() && di < g.len() { g[di] = g[si]; } }); }; macro_rules! square64_inter { ($at_mi:expr) => {{ fctx.cdef_transmitted.with(|c| c.set(false)); inter_piece!( $at_mi, SB, TxbSet::Luma64, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, &scan32, &scan32, 3, SB, SB ); }}; } macro_rules! half128_inter { ($at_mi:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{ fctx.cdef_transmitted.with(|c| c.set(false)); inter_piece!( $at_mi, SB * 2, TxbSet::Luma64, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, &scan32, &scan32, 3, $bw, $bh ); cdef_copy($src, $dst); }}; } match part128 { PARTITION_HORZ_A => { square64_inter!(base_mi); square64_inter!((base_mi.0, bc_mi)); half128_inter!((br_mi, base_mi.1), 128, 64, (1, 0), (1, 1)); } PARTITION_HORZ_B => { half128_inter!(base_mi, 128, 64, (0, 0), (0, 1)); square64_inter!((br_mi, base_mi.1)); square64_inter!((br_mi, bc_mi)); } PARTITION_VERT_A => { square64_inter!(base_mi); square64_inter!((br_mi, base_mi.1)); half128_inter!((base_mi.0, bc_mi), 64, 128, (0, 1), (1, 1)); } _ => { half128_inter!(base_mi, 64, 128, (0, 0), (1, 0)); square64_inter!((base_mi.0, bc_mi)); square64_inter!((br_mi, bc_mi)); } } continue; } if let Some(part128) = sb128_rect { // lane-sb128c r7: libaom `decode_partition` (decodeframe.c:1554) // codes PARTITION_HORZ at the 128 root as `subsize = // BLOCK_128X64` at (mi_row, mi_col) and a second one at // (mi_row + hbs, mi_col) only `if (mi_row + hbs < mi_rows)`; // PARTITION_VERT mirrors it on the column. `hbs` here is // `mi_size_high[BLOCK_128X128] / 2` = 16 mi. let horz = part128 == PARTITION_HORZ; let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); let base_mi = sub16_to_mi(at128); let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) }; for i in 0..2 { let at_mi = if horz { (base_mi.0 + i * 16, base_mi.1) } else { (base_mi.0, base_mi.1 + i * 16) }; if i > 0 && (at_mi.0 >= mi_rows as usize || at_mi.1 >= mi_cols as usize) { break; } // Each half reads its OWN `cdef_idx` literal: libaom keeps // `cdef_transmitted[4]`, one flag per 64x64 CDEF unit of a // 128x128 superblock (`read_cdef`, decodemv.c:50-81), and // the two halves of a 128-root HORZ/VERT sit in different // units (index `col_in_sb != 0` + 2 * `row_in_sb != 0`). // The key-frame 128 loop already resets here; without it // the second half skipped a `cdef_bits`-wide literal that // libaom reads, desyncing the tile at that block. fctx.cdef_transmitted.with(|c| c.set(false)); inter_piece!( at_mi, SB * 2, TxbSet::Luma64, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, &scan32, &scan32, 3, bw, bh ); if horz { hit!(INTER_SB128_HORZ_HITS); } else { hit!(INTER_SB128_VERT_HITS); } } // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF unit it // covers -- both halves of the root read their own, and the // first one's read lands in the top-left unit while the // second's lands in the bottom-left (HORZ) / top-right (VERT). let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize); fctx.cdef_idx_grid.with(|g| { let mut g = g.borrow_mut(); let cols = fctx.cdef_sb_cols.with(|c| c.get()); if cols == 0 { return; } for (src, dst) in if horz { [((0, 0), (0, 1)), ((1, 0), (1, 1))] } else { [((0, 0), (1, 0)), ((0, 1), (1, 1))] } { let (si, di) = ( (q_r + src.0) * cols + q_c + src.1, (q_r + dst.0) * cols + q_c + dst.1, ); if q_c + src.1 < cols && q_c + dst.1 < cols && si < g.len() && di < g.len() { g[di] = g[si]; } } }); continue; } if sb128_none { hit!(INTER_SB128_NONE_HITS); let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); // lane-sb128c r3: `at128` is in SUB16 units like `sb_at`; // `decode_inter_block` takes MI. Unconverted it was (0,0) for // the first 128 root and a quarter-position for every other // one -- the whole-frame gate never got past superblock 1. inter_piece!( sub16_to_mi(at128), SB * 2, TxbSet::Luma64, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, &scan32, &scan32, 3, SB * 2, SB * 2 ); // libaom writes one `cdef_strength` into the block's own // `MB_MODE_INFO`, which all four 64x64 CDEF units point at // (mirrors the key-frame 128 NONE block). let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize); fctx.cdef_idx_grid.with(|g| { let mut g = g.borrow_mut(); let cols = fctx.cdef_sb_cols.with(|c| c.get()); if cols > 0 && q_r * cols + q_c < g.len() { let idx = g[q_r * cols + q_c]; for (dr, dc) in [(0, 1), (1, 0), (1, 1)] { let i = (q_r + dr) * cols + q_c + dc; if q_c + dc < cols && i < g.len() { g[i] = idx; } } } }); continue; } let sb_ctx = neighbours.partition_ctx(sb_at, SB); let (has_cols, has_rows) = ( sb_c * SB_MI + SB_MI / 2 < mi_cols, sb_r * SB_MI + SB_MI / 2 < mi_rows, ); // The straddle cases (one or both halves outside the true // frame) never carry a real alphabet symbol -- spec forces // SPLIT there (mirrors the intra key-frame tile's own // three-way write above). Only the (true, true) case can name // a non-SPLIT value, and this loop below only ever recurses as // SPLIT -- so a real non-SPLIT part64 here must refuse by name // instead of silently decoding as SPLIT and desyncing. let part64 = match (has_cols, has_rows) { (true, true) => { let pre_rng = dec.debug_state().0; if crate::envflags::env_flag!("EC_TRACE_PART") { eprintln!("EC_PART mi_row={} mi_col={} bsize=12 ctx={} rng={}", sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize, sb_ctx, dec.debug_state().0); } let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p} pre_rng={pre_rng}", sb_r * SB_MI, sb_c * SB_MI ); } p } (true, false) => { // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT // (libaom `ec_read_partition_impl`). if crate::envflags::env_flag!("EC_TRACE_PART") { eprintln!("EC_PARTG mi_row={} mi_col={} bsize=12 ctx={} rng={}", sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize, sb_ctx, dec.debug_state().0); } if bump_edge32_bit( 4, dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)), ) == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } (false, true) => { // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT // (libaom `ec_read_partition_impl`). if bump_edge32_bit( 4, dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)), ) == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } (false, false) => { bump_edge_both_cut(2); PARTITION_SPLIT } }; if part64 == PARTITION_NONE { // lane-inter8 r1: the whole superblock as one 64x64 inter // block. `SB`-sized syntax throughout (size_group 3, same as // 32x32 -- `size_group_lookup[BLOCK_64X64] == 3`), luma // coefficients through `TxbSet::Luma64` with the 32-point // scan (TX_64X64 codes only its top-left corner, spec // 5.11.40 -- `read_inter_plane` widens the corner back to // 64x64 before the inverse transform), chroma as a plain // 32x32 `TxbSet::Chroma32`. TX_64X64 carries no `tx_type` // symbol at all, so the intra/inter luma sets coincide. hit!(INTER_SB_NONE_HITS); decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(sb_at), SB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma64, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, &scan32, &scan32, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SB, SB, allow_screen_content_tools, frame_width as usize, fctx, )?; continue; } if matches!( part64, PARTITION_HORZ | PARTITION_VERT | PARTITION_HORZ_4 | PARTITION_VERT_4 ) { // lane-inter4 r1: the superblock-level rect + 1:4 pairs as // inter blocks -- two 64x32 / 32x64 strips, or four 64x16 / // 16x64 ones. Each piece keeps `side = SB` for every // syntax/CDF/prediction-buffer decision (the square-context // corner-cut PARTITION_HORZ already ships at the 32 level) // but names its own true footprint through `write_w`/ // `write_h`, which is what `motion_mode`'s bsize row, the // mv-stack's bw4/bh4, the delta-q `bSize == sbSize` test and // every neighbour stamp read. `reject_residual = true`: a // non-skip strip refuses by name rather than over-read a // square residual (rectangular inter residual coding is not // ported -- see lanes/inter4-r1.report.md). let horz = matches!(part64, PARTITION_HORZ | PARTITION_HORZ_4); let four = matches!(part64, PARTITION_HORZ_4 | PARTITION_VERT_4); let base_mi = ( sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize, ); let (n_pieces, step_mi) = if four { (4usize, 4usize) } else { (2usize, 8usize) }; let (bw, bh) = match (horz, four) { (true, false) => (64usize, 32usize), (false, false) => (32, 64), (true, true) => (64, 16), (false, true) => (16, 64), }; for i in 0..n_pieces { let at_mi = if horz { (base_mi.0 + i * step_mi, base_mi.1) } else { (base_mi.0, base_mi.1 + i * step_mi) }; // libaom `decode_partition`'s own `i > 0` frame-edge break. if i > 0 && (at_mi.0 >= mi_rows as usize || at_mi.1 >= mi_cols as usize) { break; } inter_piece!( at_mi, SB, TxbSet::Luma64, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, &scan32, &scan32, 3, bw, bh ); if !four && i == 0 && ((horz && !has_rows) || (!horz && !has_cols)) { bump_inter_edge_strip(if horz { 0 } else { 1 }); } match (horz, four) { (true, false) => hit!(INTER_SB_HORZ_HITS), (false, false) => hit!(INTER_SB_VERT_HITS), (true, true) => hit!(INTER_SB_HORZ4_HITS), (false, true) => hit!(INTER_SB_VERT4_HITS), } } continue; } if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part64) { // lane-sbab r1: the four superblock-level AB arms on the // INTER path -- two 32x32 inter squares plus one true // 64x32/32x64 inter strip, in libaom `decode_partition`'s own // order (decodeframe.c: HORZ_A = TL, TR, bottom strip; // HORZ_B = top strip, BL, BR; VERT_A = TL, BL, right strip; // VERT_B = left strip, TR, BR). Every piece is one this // decoder already proves elsewhere: the 32x32 square is the // `PARTITION_NONE`-under-SPLIT block below, the strip is the // `PARTITION_HORZ`/`VERT` piece above (`inter_piece!`, which // keeps `side = SB` for syntax/CDF and names its true // footprint through `write_w`/`write_h`). The intra-frame // twin of this arm is lane-part32 r4's `SB_AB_HITS` block. hit_do! { SB_AB_INTER_HITS.with(|c| { let mut h = c.get(); h[part64 - PARTITION_HORZ_A] += 1; c.set(h); }); } // lane-part32 r5 / class visit-order-changes-availability: // only the two VERTICAL arms visit TL, BL, TR, BR, so only // they switch libaom's `has_tr`/`has_bl` tables. let _vert_guard = (part64 == PARTITION_VERT_A || part64 == PARTITION_VERT_B) .then(crate::encode::Reach::vert_ab_partition); let (mi_row0, mi_col0) = ( sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize, ); // 32 px = 8 MI units. let tl = (mi_row0, mi_col0); let tr = (mi_row0, mi_col0 + 8); let bl = (mi_row0 + 8, mi_col0); let br = (mi_row0 + 8, mi_col0 + 8); macro_rules! ab_strip64 { ($mi:expr, $ww:expr, $wh:expr) => { inter_piece!( $mi, SB, TxbSet::Luma64, TxbSet::Luma64, TxbSet::Chroma32, TX32, TX32, &scan32, &scan32, 3, $ww, $wh ) }; } // The 32x32 squares carry a full square residual, so unlike // `inter_piece!` (which hardcodes `reject_residual = true` // for its strips) they pass `false`. macro_rules! ab_square32 { ($mi:expr) => { decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, $mi, BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, BLOCK, BLOCK, allow_screen_content_tools, frame_width as usize, fctx, )? }; } match part64 { PARTITION_HORZ_A => { ab_square32!(tl); ab_square32!(tr); ab_strip64!(bl, 64, 32); } PARTITION_HORZ_B => { ab_strip64!(tl, 64, 32); ab_square32!(bl); ab_square32!(br); } PARTITION_VERT_A => { ab_square32!(tl); ab_square32!(bl); ab_strip64!(tr, 32, 64); } _ => { ab_strip64!(tl, 32, 64); ab_square32!(tr); ab_square32!(br); } } continue; } // Every value of the 10-symbol `partition_w64` alphabet is now // handled above except SPLIT, which falls through to the quadrant // loop below (lane-sbab r1 took the AB four; the rect/1:4 arms // and NONE `continue` earlier). debug_assert_eq!(part64, PARTITION_SPLIT); for quadrant in 0..4 { let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); if r32 >= rows || c32 >= cols { continue; } let at = (r32 as usize * 2, c32 as usize * 2); let ctx32 = neighbours.partition_ctx(at, BLOCK); let (has_cols32, has_rows32) = ( has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols), has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows), ); let part32 = if has_cols32 && has_rows32 { if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE part32_pre mi=({},{}) rng={}", r32 * BLOCK_MI, c32 * BLOCK_MI, dec.debug_state().0 ); } if crate::envflags::env_flag!("EC_TRACE_PART") { eprintln!("EC_PART mi_row={} mi_col={} bsize=9 ctx={} rng={}", (r32 as usize), (c32 as usize), ctx32, dec.debug_state().0); } let p = dec.symbol(&mut cdfs.partition_w32[ctx32]); if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}", r32 * BLOCK_MI, c32 * BLOCK_MI ); } p } else { match (has_cols32, has_rows32) { (true, false) => { // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT // (libaom `ec_read_partition_impl`). if crate::envflags::env_flag!("EC_TRACE_PART") { eprintln!("EC_PARTG mi_row={} mi_col={} bsize=9 ctx={} rng={}", r32 as usize * BLOCK_MI as usize, c32 as usize * BLOCK_MI as usize, ctx32, dec.debug_state().0); } if { let b = dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE)); bump_edge32(b.min(1) as usize); b } == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } (false, true) => { // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT // (libaom `ec_read_partition_impl`). if { let b = dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE)); bump_edge32(b.min(1) as usize); b } == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } _ => { bump_edge_both_cut(1); PARTITION_SPLIT } } }; match part32 { PARTITION_NONE => { decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(at), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, BLOCK, BLOCK, allow_screen_content_tools, frame_width as usize, fctx, )?; } PARTITION_SPLIT => { for sub in 0..4 { let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2); if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols { continue; } let (has_cols16, has_rows16) = ( has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols), has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows), ); let at16 = (sr, sc); let ctx16 = neighbours.partition_ctx(at16, SUB); // lane-inter8 r1: a straddling 16x16 cannot name a // value (spec forces SPLIT, one gathered bit); an // interior one reads the real alphabet, and // `PARTITION_SPLIT` now recurses into four 8x8 // inter leaves through the very same loop the // straddling case has always used. let part16 = if has_cols16 && has_rows16 { if crate::envflags::env_flag!("EC_TRACE_PART") { eprintln!("EC_PART mi_row={} mi_col={} bsize=6 ctx={} rng={}", (sr as usize*SUB_MI as usize), (sc as usize*SUB_MI as usize), ctx16, dec.debug_state().0); } let p = dec.symbol(&mut cdfs.partition_w16[ctx16]); if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!( "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={p} rng={rng}", sr as u32 * SUB_MI, sc as u32 * SUB_MI ); } p } else if !has_cols16 && !has_rows16 { // lane-edgeboth r1: both axes cut by the true // frame edge -- libaom `decode_partition` // forces PARTITION_SPLIT and reads NO symbol; // the leaf loop below already drops the // out-of-frame quadrants. bump_edge_both_cut(0); PARTITION_SPLIT } else { if has_cols16 { // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT // (libaom `ec_read_partition_impl`). if crate::envflags::env_flag!("EC_TRACE_PART") { eprintln!("EC_PARTG mi_row={} mi_col={} bsize=6 ctx={} rng={}", sr as usize * SUB_MI as usize, sc as usize * SUB_MI as usize, ctx16, dec.debug_state().0); } if dec.symbol_fixed(&gather(&cdfs.partition_w16[ctx16], VERT_ALIKE)) == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } else { // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT // (libaom `ec_read_partition_impl`). if dec.symbol_fixed(&gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE)) == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } }; if part16 == PARTITION_NONE { decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(at16), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; } else if part16 == PARTITION_HORZ || part16 == PARTITION_VERT { // lane-inter4 r3: the 16x16-level rect inter // leaves -- two true 16x8 (HORZ) or 8x16 // (VERT) inter blocks. Same shape as the // 32-level HORZ/VERT arm above: `side = SUB` // keeps every CDF/prediction-buffer decision // square, `write_w`/`write_h` carry the true // footprint into the mv stack, the motion-mode // row, the neighbour stamps and the rectangular // residual path (`rect_inter_residual_supported` // covers 16x8/8x16 since this round). let horz = part16 == PARTITION_HORZ; if horz { hit!(INTER_LEAF16_HORZ_HITS); } else { hit!(INTER_LEAF16_VERT_HITS); } let base_mi = sub16_to_mi(at16); let (ww, wh) = if horz { (16, 8) } else { (8, 16) }; for piece in 0..2 { let piece_mi = if horz { (base_mi.0 + piece * 2, base_mi.1) } else { (base_mi.0, base_mi.1 + piece * 2) }; // libaom `decode_partition`'s own second- // half frame-edge break. if piece > 0 && (piece_mi.0 >= mi_rows as usize || piece_mi.1 >= mi_cols as usize) { bump_inter_edge_strip(if horz { 4 } else { 5 }); break; } decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, piece_mi, SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 1, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, ww, wh, allow_screen_content_tools, frame_width as usize, fctx, )?; } } else if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) { // lane-inter16ab r1: the four AB (T-shaped) // partitions at the 16x16 level of an INTER // frame -- two 8x8 inter leaves plus one true // 16x8/8x16 inter strip. libaom // `decode_partition` (decodeframe.c ~5040, // `bsize2 = get_partition_subsize(bsize, // PARTITION_SPLIT)` = BLOCK_8X8 here) visits: // HORZ_A: TL 8x8, TR 8x8, bottom 16x8 // HORZ_B: top 16x8, BL 8x8, BR 8x8 // VERT_A: TL 8x8, BL 8x8, right 8x16 // VERT_B: left 8x16, TR 8x8, BR 8x8 // Every piece is inside the frame by // construction: an AB value can only be read // from the (has_cols16 && has_rows16) branch // above, i.e. mi_row+2 < mi_rows and // mi_col+2 < mi_cols, which is exactly // libaom's own `has_rows`/`has_cols`. // // VERT_A/VERT_B visit TL,BL,TR,BR, so a // bottom-left square's top-right neighbour is // the partition's own not-yet-decoded // rectangle: libaom switches those squares // onto `has_tr_vert_*`/`has_bl_vert_*` // (`reconintra.c get_has_tr_table`) -- // `Reach::vert_ab_partition()`, the same // guard the intra 16-level arm and the // 32-level inter AB arms take (class // `visit-order-changes-availability`). // // OBMC/warp and compound stay legal here: // every piece is >= 8x8, so libaom's // `is_motion_variation_allowed_bsize` // (min(bw,bh) >= 8, blockd.h) and // `is_comp_ref_allowed` (block_size_wide + // block_size_high >= 16, blockd.h) both hold // and the leaf/strip decoders' own gates // apply unchanged. bump_ab16_inter(part16 - PARTITION_HORZ_A); let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B { Some(crate::encode::Reach::vert_ab_partition()) } else { None }; let (mi_row0, mi_col0) = sub16_to_mi(at16); let tl = (mi_row0, mi_col0); let tr = (mi_row0, mi_col0 + 2); let bl = (mi_row0 + 2, mi_col0); let br = (mi_row0 + 2, mi_col0 + 2); macro_rules! ab_strip16 { ($mi:expr, $ww:expr, $wh:expr) => { inter_piece!( $mi, SUB, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 1, $ww, $wh ) }; } match part16 { PARTITION_HORZ_A => { inter_leaf8!(at16, tl); inter_leaf8!(at16, tr); ab_strip16!(bl, 16, 8); } PARTITION_HORZ_B => { ab_strip16!(tl, 16, 8); inter_leaf8!(at16, bl); inter_leaf8!(at16, br); } PARTITION_VERT_A => { inter_leaf8!(at16, tl); inter_leaf8!(at16, bl); ab_strip16!(tr, 8, 16); } _ => { ab_strip16!(tl, 8, 16); inter_leaf8!(at16, tr); inter_leaf8!(at16, br); } } } else if part16 == PARTITION_HORZ_4 || part16 == PARTITION_VERT_4 { // lane-inter16ab r2: four 16x4 (4x16) INTER // strips. libaom `decode_partition` // (decodeframe.c, PARTITION_HORZ_4/VERT_4) // walks them top to bottom (left to right) // with its own `i > 0` frame-edge break. // // Each strip is >= 8 in one dimension only, // so `is_comp_ref_allowed`, // `is_motion_variation_allowed_bsize` // (blockd.h:65/1455, min(bw, bh) >= 8) and // `is_interintra_allowed_bsize` (BLOCK_8X8.. // BLOCK_32X32 in enum order, which excludes // BLOCK_16X4 = 17) are all false: no // skip_mode, no comp_mode, no OBMC/warp and // no interintra symbol is read -- gated in // `decode_inter_block` off `write_w`/ // `write_h`. // // CHROMA is the pair's: // `is_chroma_reference` // (av1_common_int.h:1454) is false on the // even strips, and the odd one codes one 8x4 // (4x8) chroma transform at the pair's // origin, built from BOTH strips' motion // (`is_sub8x8_inter`). let horz = part16 == PARTITION_HORZ_4; let (mi_row0, mi_col0) = sub16_to_mi(at16); let (bw, bh) = if horz { (16usize, 4usize) } else { (4usize, 16usize) }; for i in 0..4usize { let at_mi = if horz { (mi_row0 + i, mi_col0) } else { (mi_row0, mi_col0 + i) }; if i > 0 && (at_mi.0 >= mi_rows as usize || at_mi.1 >= mi_cols as usize) { break; } let strip_has_chroma = i % 2 == 1; let pair_mi = if !strip_has_chroma { at_mi } else if horz { (at_mi.0 - 1, at_mi.1) } else { (at_mi.0, at_mi.1 - 1) }; fctx.inter_strip_chroma.with(|c| { c.set(Some(InterStripChroma { has_chroma: strip_has_chroma, horz, pair_mi, prev: if strip_has_chroma { fctx.inter_last_mc.with(std::cell::Cell::get) } else { None }, })) }); inter_piece!( at_mi, SUB, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 1, bw, bh ); if horz { hit!(INTER16_HORZ4_HITS); } else { hit!(INTER16_VERT4_HITS); } } } else if part16 != PARTITION_SPLIT { return Err(unsupported( "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4", )); } else { if has_cols16 && has_rows16 { hit!(INTER_SUB16_SPLIT_HITS); } let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); let leaf_positions: Vec<(u32, u32)> = (0..4) .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2)) .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) .collect(); // lane-t900 r28: the 8x8-leaf refusal under a // scaled reference is LIFTED -- // `decode_inter_block8`'s single-ref, // compound and OBMC MC all take spec // 7.11.3.3's scaled walk. The counter is what // proves a gate actually reached a scaled // leaf rather than a same-size reference. if (1..8).any(|rf| { refpix.dims(rf).is_some_and(|(w, _)| { w != frame_width as usize }) }) { hit!(SCALED_LEAF8_HITS); } let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option)> = Vec::new(); for (mr, mc) in leaf_positions { let leaf_mi = (mr as usize, mc as usize); let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); if crate::envflags::env_flag!("EC_TRACE_PART") { eprintln!("EC_PART mi_row={} mi_col={} bsize=3 ctx={} rng={}", leaf_mi.0, leaf_mi.1, leaf_ctx, dec.debug_state().0); } let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); if part8 == PARTITION_SPLIT { // lane-intersub8: four BLOCK_4X4 inter // sub-blocks, chroma once per 8x8. decode_inter_sub8_split4( &mut dec, &mut cdfs, &mut neighbours, &mut grid, leaf_mi, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, &scan4, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reduced_tx_set, frame_width as usize, fctx, )?; continue; } if part8 == PARTITION_VERT || part8 == PARTITION_HORZ { // lane-intersub8 r3/r4/r5: two // BLOCK_8X4 (HORZ) / BLOCK_4X8 (VERT) // inter leaves, chroma once per 8x8 on // the second of them. HORZ was refused // by name through r4 over a |d| <= 2 // luma band; r5 merged lane-cdef // 8c6065e, whose `decode_inter_block8` // skip-band write is that band's root // cause, and the 56-arm sweep went 3 // mismatching arms -> 0. decode_inter_sub8_rect2( &mut dec, &mut cdfs, &mut neighbours, &mut grid, leaf_mi, part8 == PARTITION_VERT, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, &scan4, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reduced_tx_set, frame_width as usize, fctx, )?; continue; } // `partition_w8` is a 4-symbol alphabet // (NONE/HORZ/VERT/SPLIT), all four handled. let ( skip, is_inter, skip_mode_leaf, compound_ctx8, leaf_filter, leaf_refs, ) = decode_inter_block8( &mut dec, &mut cdfs, &mut neighbours, &mut grid, mi_cols, mi_rows, at16, leaf_mi, &mut y, &mut u, &mut v, refpix, base_q_idx, &scan8, &scan4, allow_high_precision_mv, force_integer_mv, &global_motion, enable_dual_filter, reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, reduced_tx_set, interp_fixed, switchable_motion_mode, allow_warped_motion, allow_screen_content_tools, &sign_bias_table, tpl_frame.as_ref(), frame_width as usize, fctx, )?; prev_leaves.push((leaf_mi, skip, is_inter, leaf_refs.0, leaf_refs.1)); // lane-inter8 r2: stamp THIS leaf's own // 2x2-mi span before the next leaf reads // it as a neighbour -- the whole-16x16 // stamp below only ever described the // last leaf, so three quarters of the // block carried the wrong skip/ref/inter // state into the next block's contexts // (class context-read-from-one-cell). // lane-gmaffine r3: with the mi-granular // band, the leaf's OWN switchable-filter // symbols go in here -- the `[3, 3]` // ("intra, no filter") sentinel this used // to stamp made `obmc_blend`'s // `neighbour_filter` PANIC as soon as a // sibling leaf blended one of these. neighbours.record_inter_rect_mi( leaf_mi, 2, 2, skip, is_inter, leaf_refs.0, leaf_filter, skip_mode_leaf, ); if let Some(ref1) = leaf_refs.1 && let Some((_, _, group_idx, idx)) = compound_ctx8 { neighbours.record_compound_ctx_rect_mi( leaf_mi, 2, 2, ref1, group_idx, idx, ); } } // lane-inter8 r2: the four per-leaf // `record_inter_rect_mi` stamps above replace // the single whole-16x16 one that used to run // here with the LAST leaf's state. } } } PARTITION_HORZ_B => { // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip + // 16x16 bottom-left + 16x16 bottom-right. aomenc // carves static regions into it; the strip is // decoded as a square 32x32 block: for a `skip` // block the symbol stream is identical to the true // 32x16 coding (no residual, no motion_mode/warp // symbol), and the square stamps it leaves over the // bottom half (neighbour arrays, skip/lf grids) are // re-stamped by the C/D leaves right after. The // mi-granular `left_side_mi` rows of a last-block-in- // tile strip leak 32-vs-16 only until the per-tile // `Neighbours::new` reset. hit!(EXTENDED_PARTITION_HITS); let at32 = at; decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(at32), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, // lane-rect r2: the top strip's TRUE 32x16 // footprint (was BLOCK,BLOCK -- the same square // corner-cut rect-flake-1 exposed on HORZ). BLOCK, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows { decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols { decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; } } } PARTITION_HORZ => { // lane-rect r2: two true 32x16 strips. Both read at // `side=BLOCK` (CDF/size-class selection stays square, // matching HORZ_B's accepted corner-cut) but bw4/bh4 // (mvstack.rs, `motion_mode_eligible`) now derive from // `write_w`/`write_h`'s true 32x16 footprint -- the // pin's fix (r1's finding). hit!(RECT_PARTITION_HITS); decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(at), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, BLOCK, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; if !has_rows32 { bump_edge32(2); } // lane-golomb r2: at the frame edge only the first half of the // strip is coded (libaom `decode_partition` guards the second // with the same has_rows32 test that made this partition non-square). if has_rows32 { decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, BLOCK, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; } else { bump_inter_edge_strip(2); } } PARTITION_VERT => { // lane-rect r2: mirror of PARTITION_HORZ above with // width/height swapped. hit!(RECT_PARTITION_HITS); decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(at), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, SUB, BLOCK, allow_screen_content_tools, frame_width as usize, fctx, )?; if !has_cols32 { bump_edge32(3); } // lane-golomb r2: at the frame edge only the first half of the // strip is coded (libaom `decode_partition` guards the second // with the same has_cols32 test that made this partition non-square). if has_cols32 { decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, SUB, BLOCK, allow_screen_content_tools, frame_width as usize, fctx, )?; } else { bump_inter_edge_strip(3); } } PARTITION_HORZ_A => { // lane-partab r1: two 16x16 squares on top + a true // 32x16 strip below (libaom decode_partition // PARTITION_HORZ_A: TL, TR, bottom strip). hit!(PARTAB_HITS); decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(at), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, BLOCK, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; } PARTITION_VERT_A => { // lane-partab r1: mirror of PARTITION_HORZ_A with // width/height swapped (TL, BL, right 16x32 strip). hit!(PARTAB_HITS); let _vert_ab = crate::encode::Reach::vert_ab_partition(); decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(at), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, SUB, BLOCK, allow_screen_content_tools, frame_width as usize, fctx, )?; } PARTITION_VERT_B => { // lane-partab r1: true 16x32 strip on the left + two // 16x16 squares on the right (libaom decode_partition // PARTITION_VERT_B: left strip, TR, BR). hit!(PARTAB_HITS); let _vert_ab = crate::encode::Reach::vert_ab_partition(); decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi(at), BLOCK, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, true, SUB, BLOCK, allow_screen_content_tools, frame_width as usize, fctx, )?; decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &sign_bias_table, &global_motion, base_q_idx, TxbSet::Luma16, if reduced_tx_set { TxbSet::Luma16Inter } else { TxbSet::Luma16InterSet1 }, TxbSet::Chroma8, TX16, TX8, &scan16, &scan8, 2, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, tpl_frame.as_ref(), reference_select, enable_masked_compound, enable_interintra_compound, enable_jnt_comp, order_hint_bits, order_hint, ref_order_hints, skip_mode_present, skip_mode_frame, switchable_motion_mode, allow_warped_motion, false, SUB, SUB, allow_screen_content_tools, frame_width as usize, fctx, )?; } PARTITION_HORZ_4 | PARTITION_VERT_4 => { // lane-inter4 r1: four 32x8 / 8x32 inter strips, // `quarter_step` = 2 mi -- the arm ReelC's first inter // frame stops at (`value=9` = PARTITION_VERT_4). // `at` is in 16-px cells and cannot name an 8-px // offset, which is why `decode_inter_block` takes mi // coordinates now. let horz = part32 == PARTITION_HORZ_4; let base_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI)); let (bw, bh) = if horz { (32usize, 8usize) } else { (8, 32) }; for i in 0..4 { let strip_mi = if horz { (base_mi.0 + i * 2, base_mi.1) } else { (base_mi.0, base_mi.1 + i * 2) }; if i > 0 && (strip_mi.0 >= mi_rows as usize || strip_mi.1 >= mi_cols as usize) { break; } inter_piece!( strip_mi, BLOCK, TxbSet::Luma32, TxbSet::Luma32Inter, TxbSet::Chroma16, TX32, TX16, &scan32, &scan16, 3, bw, bh ); if horz { hit!(RECT4_32_HORZ_INTER_HITS); } else { hit!(RECT4_32_VERT_INTER_HITS); } } } _ => { return Err(unsupported(format!( "an INTER 32x32 partition type this decoder does not code (value={part32})" ))); } } } } } if waving { wave_submit(fctx, wave_job.0, wave_job.1); } // lane-timeline: this tile's last symbol is read here; its wavefront // workers are drained by `_wave`'s drop at the end of the iteration. crate::timeline::tile_done(); flush_recon(fctx, &mut y, &mut u, &mut v); if tile_num == tile_info.context_update_tile_id { result_cdfs = cdfs; } } // lane-defer8: every tile's recon workers are joined by its own // `WaveGuard`, so a deferred prediction's parked failure is complete here. refpix.take_err()?; crate::timeline::recon_done(); // lane-twostage: the motion field is built from the mode-info grid alone // (no pixel), so it moves up here with the CDFs -- everything a // consuming frame's SETUP needs, published before this frame's filters. let mut motion_field = Some(build_motion_field( &grid, mi_cols as usize, mi_rows as usize, order_hint, order_hint_bits, ref_order_hints, fctx, )); if let Some(stage1) = stage1 && superres(fctx).is_none() { stage1( result_cdfs.clone(), motion_field.take().expect("the motion field was just built"), frame_width as usize, frame_height as usize, ); } // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders. if crate::envflags::env_flag!("EC_OBMC") || crate::envflags::env_flag!("EC_TRACE_MODE") || crate::envflags::env_flag!("EC_PRED") { eprintln!( "EC_PICT idx={}", PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) ); } dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; let _ = f.write_all(&narrow(&y)); let _ = f.write_all(&narrow(&u)); let _ = f.write_all(&narrow(&v)); } } else { PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); } // lane-pipefilt: release the rows still pending and wait the pipeline // out; from here the picture is deblocked and CDEF-filtered exactly as // the whole-frame path leaves it. let pipelined = pipe.is_some(); crate::timeline::note_pipe(pipelined); if let Some(p) = &mut pipe { p.finish(); } drop(pipe); // lane-av1fwd: the encoder scores ~25 filter candidates against this // same coded tile ([`FilterReplay`]). Capture the reconstruction here, // before either filter has touched it -- but only on the shape whose // tail is exactly `apply_deblock` + `apply_cdef` and nothing else. if !pipelined && !lr_active && superres(fctx).is_none() { capture_filter_replay( &y, &u, &v, &neighbours, frame_width as usize, frame_height as usize, width, height, true_width, true_height, ); } if pipelined { cdef_scan_counters(&neighbours); } else { apply_deblock( &mut y, &mut u, &mut v, loop_filter, &neighbours, frame_width as usize, frame_height as usize, fctx, ); } // lane-perf4: loop restoration is the only reader of the pre-CDEF planes, // and a frame that restores nothing copied every plane twice for nothing // (three `PlaneBuf` clones here plus the `cdef.to_vec()` inside // [`crate::restoration::apply_loop_restoration_plane`], which returns its // input unchanged when the plane's type is `None`). Clone only when some // plane actually restores. let deblocked = if pipelined { // The pipeline already snapshotted every band on its way past it. let snap = pipe_snap.take(); match (lr_active, snap) { (true, snap) => snap, (false, Some((a, b, c))) => { scratch_return(c.data.into_owned()); scratch_return(b.data.into_owned()); scratch_return(a.data.into_owned()); None } (false, None) => None, } } else { lr_active.then(|| (plane_snapshot(&y, 0), plane_snapshot(&u, 1), plane_snapshot(&v, 1))) }; // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter // dump above these bisect WHICH filter stage introduced a mismatch. dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if !pipelined { apply_cdef( &mut y, &mut u, &mut v, cdef, &neighbours, (frame_width as usize, frame_height as usize), fctx, ); } dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); capture_stages(&y, &u, &v, deblocked.as_ref(), fctx); // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`): // the horizontal upscale runs HERE -- after CDEF, before loop // restoration, not after the whole filter chain. Both the post-CDEF // frame and the post-deblock frame that LR substitutes at its stripe // boundaries are upscaled (`save_deblock_boundary_lines` runs // `av1_upscale_normative_rows` over its saved rows when the frame is // scaled), so every LR coordinate from here on is in upscaled space. let mut deblocked = deblocked; let mut lr_w = frame_width as usize; if let Some((upscaled_w, _)) = superres(fctx) { let bd = u32::from(bit_depth(fctx)); let (uw, fw, fh) = (upscaled_w as usize, frame_width as usize, frame_height as usize); let up = |p: &PlaneBuf<'_>, in_w: usize, in_h: usize, out_w: usize| PlaneBuf { data: std::borrow::Cow::Owned(crate::superres::upscale_plane_strided( &p.data, p.width, in_w, in_h, p.true_width, out_w, bd, )), width: out_w, height: in_h, true_width: out_w, true_height: in_h, tile_x0: 0, tile_y0: 0, tile_x1: out_w, tile_y1: in_h, }; let (cw, ch, cuw) = (fw.div_ceil(2), fh.div_ceil(2), uw.div_ceil(2)); y = up(&y, fw, fh, uw); u = up(&u, cw, ch, cuw); v = up(&v, cw, ch, cuw); if let Some((dy, du, dv)) = deblocked.take() { deblocked = Some((up(&dy, fw, fh, uw), up(&du, cw, ch, cuw), up(&dv, cw, ch, cuw))); } lr_w = uw; crate::superres::note_upscaled_picture(); } if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked { // lane-pipefilt2: the pipeline already restored every RU row on its // way past it (its LR step runs in the same iteration as the CDEF // band that completes the row's last line). if !pipelined { apply_loop_restoration( &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid, (lr_w, frame_height as usize), fctx, ); } } if let Some((db_y, db_u, db_v)) = deblocked { // LIFO pool: return in reverse so the next frame's `y`/`u`/`v` // snapshots pop buffers of their own size and never resize. scratch_return(db_v.data.into_owned()); scratch_return(db_u.data.into_owned()); scratch_return(db_y.data.into_owned()); } crate::timeline::filters_done(); let (fw, fh) = (lr_w, frame_height as usize); // An upscaled frame is already at its final size with no mi-aligned // margin beyond it (the upscale consumed those columns), so the // wide-margin stash below has nothing left to hand out. let (true_width, true_height) = if superres(fctx).is_some() { (fw, fh) } else { (true_width, true_height) }; if fw == width && fh == height { fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); return Ok(( Picture { width, height, y: y.data.into_owned(), u: u.data.into_owned(), v: v.data.into_owned(), }, result_cdfs, motion_field, )); } let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec { let mut out = Vec::with_capacity(w * h); for row in 0..h { out.extend(plane.data[row * plane.width..][..w].iter().copied()); } out }; // lane-superres r10 (fixed r9): same real-margin stash as // `decode_key_frame_tile_with_cdfs` (see that function's comment) -- the // real reconstructed extent is the mi-aligned `true_width`/`true_height` // (`mi_cols`/`mi_rows` * 4), NOT the superblock-padded `width`/`height` // this branch was reading before: columns `[true_width, width)` were // never actually coded (the last partial superblock stops at // `true_width`), so stashing out to `width` handed the chroma upscale's // right-edge replicate a slice of uninitialized/stale buffer one column // early -- the same shorten-vs-replicate shape as `av1-truesize`. The // key-frame branch above already used `true_width`/`true_height`; this // just matches it. fctx.last_frame_wide_margin.with(|m| { *m.borrow_mut() = if true_width > fw || true_height > fh { Some(Picture { width: true_width, height: true_height, y: crop(&y, true_width, true_height), u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)), v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)), }) } else { None } }); Ok(( Picture { width: fw, height: fh, y: crop_owned(y, fw, fh), u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)), v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)), }, result_cdfs, motion_field, )) } #[cfg(test)] mod tests { /// lane-twostage: the reference bank these gates decode against -- /// `LAST_FRAME` alone, already in hand (`ref_frame` index 1). fn last_only(reference: &Picture) -> RefPix<'_> { let mut refs: [Option<&Picture>; 8] = [None; 8]; refs[1] = Some(reference); RefPix::ready(refs) } /// [`last_only`] plus `GOLDEN_FRAME` (index 4 of the name-keyed array) /// and `ALTREF_FRAME` (index 7, the frame two back, which the encoder /// keeps in the slot the current frame refreshes): what a frame this /// encoder writes needs, since its blocks may name any of the three. fn last_golden_altref<'a>( last: &'a Picture, golden: &'a Picture, altref: Option<&'a Picture>, ) -> RefPix<'a> { let mut refs: [Option<&Picture>; 8] = [None; 8]; refs[1] = Some(last); refs[4] = Some(golden); refs[7] = altref; RefPix::ready(refs) } /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and /// a pre-resolved damping shift instead of a bounds-testing closure and a /// per-tap `msb`. Both replacements must be value-identical to the spec /// forms they came from, over the whole strength/damping/diff domain. #[test] fn cdef_gather_and_shifted_constrain_match_the_spec_forms() { for damping in 3..=9i32 { for threshold in 1..=64i32 { let shift = super::cdef_constrain_shift(threshold, damping); for diff in -300..=300i32 { assert_eq!( super::cdef_constrain(diff, threshold, damping), super::cdef_constrain_shifted(diff, threshold, shift), "diff={diff} threshold={threshold} damping={damping}" ); } } } // `cdef_gather`'s interior fast path and its bounds-testing slow path // must agree with the per-sample closure the filter used to call, at // every block position including the three that straddle the crop. let (stride, tw, th) = (24usize, 21usize, 19usize); let src: Vec = (0..stride * 24).map(|i| (i * 7 % 1024) as u16).collect(); for &(ox, oy, bw, bh) in &[(0, 0, 8, 8), (8, 8, 8, 8), (16, 16, 8, 8), (4, 12, 4, 4)] { let bstride = bw + 2 * super::CDEF_BORDER; let mut win = vec![0i16; bstride * (bh + 2 * super::CDEF_BORDER)]; super::cdef_gather(&src, stride, tw, th, ox, oy, bw, bh, &mut win); for r in -(super::CDEF_BORDER as i32)..(bh + super::CDEF_BORDER) as i32 { for c in -(super::CDEF_BORDER as i32)..(bw + super::CDEF_BORDER) as i32 { let (ny, nx) = (oy as i32 + r, ox as i32 + c); let want = if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw { super::CDEF_VERY_LARGE as i16 } else { src[ny as usize * stride + nx as usize] as i16 }; let got = win[(r + super::CDEF_BORDER as i32) as usize * bstride + (c + super::CDEF_BORDER as i32) as usize]; assert_eq!(got, want, "({ox},{oy}) r={r} c={c}"); } } } } /// lane-cdef: the row-at-a-time direction search (and its AVX2 twin) must /// be value-identical to a literal transcription of libaom /// `cdef_find_dir_c`'s per-sample accumulation, over random windows at /// every bit depth -- including the `CDEF_VERY_LARGE` sentinel rows a /// crop-straddling 8x8 gathers. #[test] fn cdef_find_dir_matches_the_per_sample_reference() { const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105]; fn reference(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) { let mut partial = [[0i64; 15]; 8]; for i in 0..8i64 { for j in 0..8i64 { let s = i64::from( win[(i as usize + super::CDEF_BORDER) * bstride + j as usize + super::CDEF_BORDER], ); let x = (s >> coeff_shift) - 128; partial[0][(i + j) as usize] += x; partial[1][(i + j / 2) as usize] += x; partial[2][i as usize] += x; partial[3][(3 + i - j / 2) as usize] += x; partial[4][(7 + i - j) as usize] += x; partial[5][(3 - i / 2 + j) as usize] += x; partial[6][j as usize] += x; partial[7][(i / 2 + j) as usize] += x; } } let mut cost = [0i64; 8]; for i in 0..8usize { cost[2] += partial[2][i] * partial[2][i]; cost[6] += partial[6][i] * partial[6][i]; } cost[2] *= DIV_TABLE[8]; cost[6] *= DIV_TABLE[8]; for i in 0..7usize { cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i]) * DIV_TABLE[i + 1]; cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i]) * DIV_TABLE[i + 1]; } cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8]; cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8]; for i in (1..8).step_by(2) { for j in 0..5usize { cost[i] += partial[i][3 + j] * partial[i][3 + j]; } cost[i] *= DIV_TABLE[8]; for j in 0..3usize { cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j]) * DIV_TABLE[2 * j + 2]; } } let (mut best_cost, mut best_dir) = (0i64, 0usize); for (i, &c) in cost.iter().enumerate() { if c > best_cost { best_cost = c; best_dir = i; } } (best_dir, ((best_cost - cost[(best_dir + 4) & 7]) >> 10) as i32) } let mut rng = 0x0bad_c0de_dead_beefu64; let mut next = move || { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; rng }; let bstride = 8 + 2 * super::CDEF_BORDER; for &(bit_depth, coeff_shift) in &[(8u8, 0i32), (10, 2), (12, 4)] { let smax = (1u64 << bit_depth) - 1; for trial in 0..256 { let sentinels = trial % 4; let mut win = [0i16; 256]; for (k, w) in win[..bstride * bstride].iter_mut().enumerate() { let (r, c) = (k / bstride, k % bstride); *w = if sentinels > 0 && (r < sentinels || c < sentinels || r + sentinels >= bstride || c + sentinels >= bstride) { super::CDEF_VERY_LARGE as i16 } else { (next() % (smax + 1)) as i16 }; } let want = reference(&win, bstride, coeff_shift); assert_eq!( super::cdef_find_dir(&win, bstride, coeff_shift), want, "bd={bit_depth} trial={trial}" ); let partial = super::cdef_find_dir_partials(&win, bstride, coeff_shift); #[cfg(target_arch = "x86_64")] if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 { // SAFETY: the avx2 arm was probed above. #[allow(unsafe_code)] let simd = unsafe { super::cdef_simd::find_dir_partials_avx2(&win, bstride, coeff_shift) }; assert_eq!(simd, partial, "bd={bit_depth} trial={trial} partials"); } } } } /// lane-perf7 step 1: the AVX2 CDEF kernel must be value-identical to /// [`super::cdef_filter_block_scalar`] over the whole input domain -- /// every direction, every enable pair, both block shapes, the 8/10/12-bit /// strength and damping ranges, and windows that mix real samples with /// the `CDEF_VERY_LARGE` out-of-frame sentinel (which must stay out of /// the max clamp). #[test] #[cfg(target_arch = "x86_64")] fn cdef_simd_kernel_matches_the_scalar_filter() { if crate::mc::simd_level() != crate::mc::SimdLevel::Avx2 { eprintln!("SKIP cdef simd: no avx2"); return; } let mut rng = 0x1234_5678_9abc_def0u64; let mut next = move || { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; rng }; for &(bit_depth, coeff_shift) in &[(8u8, 0i32), (10, 2), (12, 4)] { let smax = (1i32 << bit_depth) - 1; for &(bw, bh) in &[(8usize, 8usize), (4, 4)] { let bstride = bw + 2 * super::CDEF_BORDER; let rows = bh + 2 * super::CDEF_BORDER; let stride = bw + 5; for trial in 0..64 { // Every fourth window seeds sentinels, in a growing // border ring, so the straddling-block case is covered. let sentinels = trial % 4; // 256 entries, as `cdef_band`'s own scratch is: the // kernel taps the window in place and reads past the last // sample into the zeroed tail. let mut win: Vec = (0..rows * bstride) .map(|k| { let (r, c) = (k / bstride, k % bstride); if sentinels > 0 && (r < sentinels || c < sentinels || r + sentinels >= rows || c + sentinels >= bstride) { super::CDEF_VERY_LARGE as i16 } else { (next() % (smax as u64 + 1)) as i16 } }) .collect(); win.resize(256, 0); for dir in 0..8usize { for &pri in &[0i32, 1, 3, 15] { for &sec in &[0i32, 1, 2, 4] { for &damping in &[3i32, 5, 6, 9] { let (pri, sec) = (pri << coeff_shift, sec << coeff_shift); let (ep, es) = (pri != 0, sec != 0); if !ep && !es { continue; } let seed: Vec = (0..stride * (bh + 2)).map(|k| (k % 97) as u16).collect(); let mut a = seed.clone(); let mut b = seed; super::cdef_filter_block_scalar( &win, &mut a, stride, 1, 1, bw, bh, pri, sec, dir, damping, damping, ep, es, coeff_shift, smax, ); // SAFETY: the avx2 arm was probed above. #[allow(unsafe_code)] unsafe { super::cdef_simd::filter_block_avx2( &win, &mut b, stride, 1, 1, bw, bh, pri, sec, dir, damping, damping, ep, es, coeff_shift, smax, ) }; assert_eq!( a, b, "bd={bit_depth} bw={bw} trial={trial} dir={dir} \ pri={pri} sec={sec} damping={damping}" ); } } } } } } } } /// lane-perf8: the AVX2 deblock kernel must be sample-identical to /// [`super::filter_edge`] over the whole input domain -- every bit depth, /// every filter length, every level and sharpness, and sample patterns /// that put each of `mask`, `flat` and `flat2` on both sides of its /// threshold (uniform, flat-with-step, small-noise and full-range /// random), on both edge directions. #[test] #[cfg(target_arch = "x86_64")] fn deblock_simd_kernel_matches_the_scalar_filter() { let fctx = &crate::decode::FrameCtx::new(); if crate::mc::simd_level() != crate::mc::SimdLevel::Avx2 { eprintln!("SKIP deblock simd: no avx2"); return; } let mut rng = 0x9e37_79b9_7f4a_7c15u64; let mut next = move || { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; rng }; let (stride, rows) = (64usize, 64usize); for &bd in &[8u8, 10, 12] { super::set_bit_depth(bd, fctx); let smax = (1u64 << bd) - 1; for pattern in 0..4u32 { for trial in 0..8 { let seed: Vec = (0..stride * rows) .map(|k| { let base = ((k / stride) as u64 * 7 + trial) % (smax + 1); (match pattern { // Uniform-ish: every mask and both flats pass. 0 => base, // A step across the edge column/row. 1 => (base + if k % stride >= 32 { smax / 2 } else { 0 }) % (smax + 1), // Small noise: flat passes at 8-bit, not always higher. 2 => (base + next() % 4) % (smax + 1), _ => next() % (smax + 1), }) as u16 }) .collect(); for &len in &[4u8, 6, 8, 14] { for &level in &[0i32, 1, 7, 23, 40, 63] { for sharpness in 0..8u8 { for &vertical in &[true, false] { let (base, outer, tap) = if vertical { (32 * stride + 32, stride as isize, 1isize) } else { (32 * stride + 32, 1isize, stride as isize) }; let mut a = seed.clone(); for g in 0..4usize { let b = if vertical { base + 4 * g * stride } else { base + 4 * g }; super::filter_edge( &mut a, b, outer, tap, len, level, sharpness, fctx, ); } let mut b = seed.clone(); assert!(super::filter_edge16( &mut b, base, stride, vertical, len, level, sharpness, fctx, )); assert_eq!( a, b, "bd={bd} pattern={pattern} trial={trial} len={len} \ level={level} sharp={sharpness} vert={vertical}" ); } } } } } } } super::set_bit_depth(8, fctx); } /// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce /// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]` /// (libaom `av1/common/blockd.h:1036`/`1097`) exactly -- the g35 residue /// was one 64x64 inter superblock whose 32x32 chroma units are /// `EXT_TX_SET_DCT_IDTX`, where IDTX survives and we forced `DCT_DCT`. #[test] fn an_inter_chroma_transform_narrows_its_inherited_tx_type_to_its_own_set() { let fctx = &crate::decode::FrameCtx::new(); use TxType::*; // EXT_TX_SET_DCTONLY: `tx_size_sqr_up > TX_32X32`. set_inter_tx_mode(true, false, true, fctx); assert_eq!(reduce_inherited_chroma_tx_type(Idtx, 64, 64, fctx), DctDct); // EXT_TX_SET_DCT_IDTX at exactly TX_32X32 -- the residue's case. assert_eq!(reduce_inherited_chroma_tx_type(Idtx, 32, 32, fctx), Idtx); assert_eq!(reduce_inherited_chroma_tx_type(AdstAdst, 32, 32, fctx), DctDct); // EXT_TX_SET_DTT9_IDTX_1DDCT at `tx_size_sqr == TX_16X16`: the four // 1D ADST/FLIPADST types (TX_TYPES 12..15) drop out, the rest stay. assert_eq!(reduce_inherited_chroma_tx_type(HDct, 16, 16, fctx), HDct); assert_eq!(reduce_inherited_chroma_tx_type(FlipAdstAdst, 16, 16, fctx), FlipAdstAdst); assert_eq!(reduce_inherited_chroma_tx_type(HAdst, 16, 16, fctx), DctDct); // EXT_TX_SET_ALL16 below that (`tx_size_sqr < TX_16X16`, so a 16x8 // chroma unit too). assert_eq!(reduce_inherited_chroma_tx_type(HAdst, 16, 8, fctx), HAdst); assert_eq!(reduce_inherited_chroma_tx_type(VFlipAdst, 8, 8, fctx), VFlipAdst); // `reduced_tx_set` collapses every inter set to DCT_IDTX. set_inter_tx_mode(true, true, true, fctx); assert_eq!(reduce_inherited_chroma_tx_type(Idtx, 8, 8, fctx), Idtx); assert_eq!(reduce_inherited_chroma_tx_type(HAdst, 8, 8, fctx), DctDct); set_inter_tx_mode(true, false, true, fctx); } /// lane-fistrip r1 (class `enumerate-the-table-domain`): every block /// shape this decoder can hand [`filter_intra_size_class_rect`], against /// `av1_filter_intra_allowed_bsize` (`block_size_wide <= 32 && /// block_size_high <= 32`) and `default_filter_intra_cdfs` /// (entropymode.c) row by row. A class that exists must carry ITS OWN /// bsize's default probability -- a wrong row is a silently different /// symbol, not a decode error. The shapes with no class are listed here /// with their reason so the residue is pinned rather than implied. #[test] fn filter_intra_classes_carry_their_own_libaom_default_row() { // `default_filter_intra_cdfs[bsize]`, BLOCK_SIZES_ALL order, as // (width, height, default, refused_by) for the shapes <= 32 on both // axes. The first three fields are GENERATED from the oracle by // `scripts/extract-filter-intra-cdfs.py` (it reads BLOCK_SIZES_ALL's // order from enums.h and the table from entropymode.c, so no hand // transcription can drift -- lane-fistrip r1 listed the four 1:4 // shapes as 16384 out of exactly that kind of guess; their real rows // are 12770/10368/20229/18101). `refused_by` is `None` for a shape // this decoder's partition tree reaches today -- it must own a class, // and that class must carry exactly this row -- and the refusal // string that blocks the shape otherwise. Either way the row is // pinned HERE, so the round that lifts one of those refusals cannot // land a wrong CDF row for the shape it unlocks. let libaom: &[(usize, usize, u16, Option<&str>)] = &[ (4, 4, 4621, None), (4, 8, 6743, None), (8, 4, 5893, None), (8, 8, 7866, None), (8, 16, 12551, None), (16, 8, 9394, None), (16, 16, 12408, None), (16, 32, 14301, None), (32, 16, 12756, None), (32, 32, 22343, None), // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives // 4x16/16x4 (still refused by name before any leaf is coded), // a 32x32-level one 8x32/32x8. // lane-r14: the 16-level pair is coded now (`decode_rect4_16`), // owning classes 13/12. (4, 16, 12770, None), (16, 4, 10368, None), // lane-fi32x8 r1: the 32-level pair is coded (four 32x8/8x32 // strips per `PARTITION_HORZ_4`/`VERT_4`) and now owns classes // 10/11; only the 16-level pair is still refused before any leaf. (8, 32, 20229, None), (32, 8, 18101, None), ]; let mut classes_seen = std::collections::BTreeSet::new(); for &(bw, bh, default, refused_by) in libaom { match filter_intra_size_class_rect(bw, bh) { Some(class) => { assert!( refused_by.is_none(), "{bw}x{bh} has a CDF class but is listed as refused by {refused_by:?} -- \ one of the two is stale" ); assert_eq!( crate::cdf::FILTER_INTRA[class][0], default, "{bw}x{bh} (class {class}) must carry default_filter_intra_cdfs' own row" ); assert_eq!( &crate::cdf::FILTER_INTRA[class][1..], &[32768u16, 0][..], "{bw}x{bh} (class {class}) is a 2-symbol CDF: {{p, 32768, count}}" ); assert!( classes_seen.insert(class), "class {class} is claimed by two shapes -- one of them reads the other's \ probability" ); } None => { let why = refused_by.unwrap_or_else(|| { panic!( "{bw}x{bh} is inside av1_filter_intra_allowed_bsize and reachable, \ but has no CDF class -- its use_filter_intra symbol is never read" ) }); assert!(!why.is_empty(), "{bw}x{bh}'s refusal string must name the blocker"); } } } // The other direction: every row of `cdf::FILTER_INTRA` was claimed // by exactly one shape above, so no row can be left over (or shared) // once a class is added or removed. assert_eq!( classes_seen.len(), crate::cdf::FILTER_INTRA.len(), "cdf::FILTER_INTRA has {} rows but only {:?} are claimed by an allowed shape", crate::cdf::FILTER_INTRA.len(), classes_seen ); // Past the bound on either axis: no symbol at all (spec // `filter_intra_mode_info` never reads one). for (bw, bh) in [(64, 64), (64, 32), (32, 64)] { assert!( filter_intra_size_class_rect(bw, bh).is_none(), "{bw}x{bh} is past av1_filter_intra_allowed_bsize's <=32 bound" ); } } use super::*; /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR -- /// `SCAN_4X16[i]` must name the transpose of the position /// `SCAN_16X4[i]` names (class scan-weights-cross-axis: a naive copy of /// libaom's column-major `default_scan_*` installs the transpose and only /// an asymmetric check catches it). Also pins both as permutations, and /// pins the same relation for the 32x8/8x32 luma pair this arm reuses. #[test] fn the_rect4_scans_are_transposed_pairs() { for (a, b, w, h) in [ (&SCAN_16X4[..], &SCAN_4X16[..], 16usize, 4usize), (&SCAN_32X8[..], &SCAN_8X32[..], 32, 8), ] { let mut seen_a: Vec = a.to_vec(); seen_a.sort_unstable(); assert_eq!( seen_a, (0..(w * h) as u16).collect::>(), "{w}x{h} scan is not a permutation of its positions" ); for (i, (&pa, &pb)) in a.iter().zip(b.iter()).enumerate() { let (row, col) = (pa as usize / w, pa as usize % w); assert_eq!( pb as usize, col * w.min(h) + row, "scan step {i}: {w}x{h} visits (row {row}, col {col}) but its transpose \ visits position {pb}" ); } } } /// lane-coef2 (class `enumerate-table-domain`): the padded level buffers /// [`read_coeffs`]/[`read_coeffs_rect`] hand to [`neighbour`] dropped the /// `row >= side || col >= side` edge test, so the padding must cover the /// WIDEST offset any `base_ctx` class reads -- `(row + 4, col)` and /// `(row, col + 4)` -- at every transform size this decoder codes, and /// the buffer must be no larger than the fixed frames those two functions /// declare (`36 * 36` square, `768` rect). #[test] fn padded_level_buffers_cover_every_neighbour_read_at_every_transform_size() { for side in [4usize, 8, 16, 32] { let stride = side + 4; let (row, col) = (side - 1, side - 1); let widest = ((row + 4) * stride + col + 4).max(row * stride + col + 4); assert!(widest < stride * stride, "square {side}: {widest}"); assert!(stride * stride <= 36 * 36, "square {side} frame"); } for (w, h) in [ (4usize, 8usize), (8, 4), (8, 16), (16, 8), (4, 16), (16, 4), (8, 32), (32, 8), (16, 32), (32, 16), ] { let stride = w + 4; let n = stride * (h + 4); let (row, col) = (h - 1, w - 1); let widest = ((row + 4) * stride + col + 4).max(row * stride + col + 4); assert!(widest < n, "rect {w}x{h}: {widest} >= {n}"); assert!(n <= 768, "rect {w}x{h} frame {n}"); assert!(w.is_power_of_two(), "rect {w}x{h} stride mask"); } } /// lane-rectsplit r4 (class `enumerate-table-domain`): [`base_ctx`]'s /// `TX_CLASS_2D` arm must, over the WHOLE 5x5 domain of both rect shapes /// and the square one, return exactly what libaom's /// `av1_nz_map_ctx_offset[tx_size][coeff_idx]` holds -- the flat tables /// transcribed in [`cdf`], read at libaom's own COLUMN-major /// `coeff_idx = col * 32 + row`, i.e. `table[col][row]`. r1..r3 read them /// `[row][col]`, which is the transpose (the OTHER shape's rule, with 11 /// and 16 swapped): it desynced the first superblock strip whose luma /// corner held a coefficient off the first row/column. /// lane-coefread: the per-coefficient neighbour gather now reads FLAT /// offsets ([`flat_taps`]) instead of `(row + dr, col + dc)`. Same cells, /// every class, every square size, over the whole `(row, col)` domain. #[test] fn flat_taps_match_the_row_col_neighbour_reads() { for &side in &[4usize, 8, 16, 32] { let stride = side + 4; let mut grid = vec![0u8; stride * stride]; let mut x = 12345u32; for c in grid.iter_mut() { x = x.wrapping_mul(1103515245).wrapping_add(12345); *c = ((x >> 16) & 15) as u8; } for class in [TxClass::TwoD, TxClass::Horiz, TxClass::Vert] { let (bt, rt) = flat_taps(stride, class); for row in 0..side { for col in 0..side { let idx = row * stride + col; if !(class == TxClass::TwoD && row == 0 && col == 0) { let want = base_ctx(&grid, stride, row, col, class, None); let got = base_mag(&grid, idx, &bt) + match class { TxClass::TwoD => { cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize } TxClass::Horiz => nz_map_ctx_offset_1d(col.min(31)), TxClass::Vert => nz_map_ctx_offset_1d(row.min(31)), }; assert_eq!(got, want, "base side {side} at {row},{col}"); } let want = br_ctx(&grid, stride, row, col, class); let mag = br_mag(&grid, idx, &rt); let got = if row == 0 && col == 0 { mag } else { let near = match class { TxClass::TwoD => row < 2 && col < 2, TxClass::Horiz => col == 0, TxClass::Vert => row == 0, }; if near { mag + 7 } else { mag + 14 } }; assert_eq!(got, want, "br side {side} at {row},{col}"); assert_eq!( br_ctx_rect(&grid, stride, row, col, class), want, "br_rect side {side} at {row},{col}" ); } } } } } #[test] fn base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain() { let grid = [0u8; 36 * 36]; for (shape, table) in [ (Some((64usize, 32usize)), &cdf::NZ_MAP_CTX_OFFSET_64X32), (Some((32, 64)), &cdf::NZ_MAP_CTX_OFFSET_32X64), (None, &cdf::NZ_MAP_CTX_OFFSET_32), ] { for row in 0..5usize { for col in 0..5usize { // An all-zero neighbourhood makes the magnitude term 0, // so `base_ctx` returns the offset itself. let got = base_ctx(&grid, 36, row, col, TxClass::TwoD, shape); let want = if row == 0 && col == 0 { 0 } else { table[col][row] as usize }; assert_eq!(got, want, "{shape:?} at (row {row}, col {col})"); } } } } // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/ // `split_dc_key_frame_tile` are not exercised here: they are synthetic // single-purpose writers with their own skip-context rule (keyed to // superblock position, not the neighbour-tracked one every real block // uses), never reached by `encode_key_frame_with_modes` — decoding them // would need a second, throwaway context convention next to the real // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is // this decoder's one target, and the round-trip test below is against // that path with real quantised residual, not a synthetic all-DC frame. /// [`SCAN_8X4`]/[`SCAN_4X8`] (lane-rectx r2): a bijection check alone /// cannot catch a transposed pair -- a swap of two orientation tables is /// still a bijection over the same 32 positions. This pins BOTH arrays /// at once, element-for-element, against literal transcriptions of /// libaom's real `default_scan_4x8`/`default_scan_8x4` in /// `av1/common/scan.c` (`~/.cache/aom-oracle/src`, read directly for /// this test, not re-derived from the zigzag formula). The two source /// sequences are themselves different in their own right (not equal to /// each other), so this is asymmetric in the two axes: if the repo's /// `SCAN_8X4`/`SCAN_4X8` were swapped with each other, one side of this /// assert pair would fail even though each individual array would still /// pass a same-orientation bijection test. #[test] fn scan_8x4_and_4x8_are_not_transposed_against_each_other() { // libaom `default_scan_4x8` verbatim (scan.c:29-32) -- this repo // names it `SCAN_8X4` under the established w/h axis swap (see // `SCAN_8X4`'s own doc comment). const LIBAOM_DEFAULT_SCAN_4X8: [u16; 32] = [ 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14, 7, 29, 22, 15, 30, 23, 31, ]; // libaom `default_scan_8x4` verbatim (scan.c:44-47) -- this repo's // `SCAN_4X8`. const LIBAOM_DEFAULT_SCAN_8X4: [u16; 32] = [ 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28, 23, 26, 29, 27, 30, 31, ]; assert_ne!( LIBAOM_DEFAULT_SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, "the two libaom source sequences must differ, or this pin would \ pass regardless of a swap" ); assert_eq!(SCAN_8X4, LIBAOM_DEFAULT_SCAN_4X8, "SCAN_8X4 vs libaom default_scan_4x8"); assert_eq!(SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, "SCAN_4X8 vs libaom default_scan_8x4"); } /// lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= 32", /// so a DC_PRED 16x8/8x16 strip reads a `use_filter_intra` flag exactly /// like a square 16x16 does. [`filter_intra_size_class_rect`] returned /// `None` at those two sizes, so the symbol was never read and the tile /// desynced from that block on (root-caused against an instrumented /// aomdec `EC_TRACE_COEFF` ladder on a real stream: identical `mode=0`/ /// `uv_mode=9` values, our range 34808 vs the oracle's 40668 at the very /// next transform block). /// /// The two rows are ASYMMETRIC (9394 for 16x8, 12551 for 8x16), so this /// pin fails if the pair is ever transposed -- the shape the repo's /// scan tables already carry (`SCAN_8X4` == libaom `default_scan_4x8`). #[test] fn a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row() { // `default_filter_intra_cdfs` (entropymode.c), indexed by BLOCK_SIZES_ALL: // [4] = BLOCK_8X16, [5] = BLOCK_16X8, [7] = BLOCK_16X32, [8] = BLOCK_32X16. const LIBAOM_8X16: u16 = 12551; const LIBAOM_16X8: u16 = 9394; let c16x8 = filter_intra_size_class_rect(16, 8).expect("16x8 reads use_filter_intra"); let c8x16 = filter_intra_size_class_rect(8, 16).expect("8x16 reads use_filter_intra"); assert_ne!(c16x8, c8x16, "the two orientations must not share a CDF row"); assert_eq!(cdf::FILTER_INTRA[c16x8][0], LIBAOM_16X8, "16x8 filter_intra row"); assert_eq!(cdf::FILTER_INTRA[c8x16][0], LIBAOM_8X16, "8x16 filter_intra row"); // The sizes one class up keep their own distinct rows (lane-intradisp). assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(32, 16).unwrap()][0], 12756); assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(16, 32).unwrap()][0], 14301); // A size with a side over 32 is genuinely not allowed the flag. assert_eq!(filter_intra_size_class_rect(64, 32), None); } /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly /// when both references sit on the same temporal side -- the three /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN) /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`, /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set, /// not just the three enumerated syntax pairs). #[test] fn is_uni_comp_ref_matches_forward_backward_sides() { assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME)); assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME)); assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME)); assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME)); assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME)); assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME)); } /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1` /// with the real second reference (lane-av1comp round 12: previously /// always cleared to `None` by `record_inter`, so the next block's own /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it /// -- could never see a real compound neighbour). /// lane-interp3 r1: a decoder must never abort the process on /// stream-derived state. `neighbour_filter` used to feed the `[3, 3]` /// "no filter recorded" sentinel straight into /// `InterpFilterKind::from_switchable_symbol`, whose `panic!` ("...alphabet /// is exactly 3 symbols") crashed on a real aomenc dual-filter + OBMC /// stream. It now refuses by name; the real symbols still decode. #[test] fn an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking() { assert!( neighbour_filter(None, [3, 3]) .unwrap_err() .to_string() .contains("an OBMC neighbour whose switchable interp filter was never recorded"), "the [3, 3] sentinel must refuse by name, never panic" ); assert!(neighbour_filter(None, [3, 0]).is_err()); let (h, v) = neighbour_filter(None, [0, 2]).expect("real symbols decode"); assert_eq!(h, mc::InterpFilterKind::Sharp, "sym[1] is the horizontal kernel"); assert_eq!(v, mc::InterpFilterKind::Regular, "sym[0] is the vertical kernel"); let (h, v) = neighbour_filter(Some(mc::InterpFilterKind::Smooth), [3, 3]) .expect("a fixed-filter frame never reads a symbol"); assert_eq!((h, v), (mc::InterpFilterKind::Smooth, mc::InterpFilterKind::Smooth)); } /// lane-t900 r27, structural audit for "an OBMC neighbour whose switchable /// interp filter was never recorded": the `[3, 3]` sentinel is only ever /// PUBLISHED for a cell an OBMC blend cannot pick up. /// /// `Neighbours::record_inter_rect_mi` is the single writer of /// `above_filter`/`left_filter` (every other recorder routes through it), /// so the whole domain of published values is its call sites' 7th /// argument. Two publications are safe: an INTRA cell (`is_inter = false`, /// skipped by `overlappable_above`/`overlappable_left`'s own `is_inter` /// gate) and a fixed-filter frame (`resolve_interp_filter` returns the /// sentinel when `interp_fixed` is `Some`, which `neighbour_filter` /// answers before ever looking at the symbols). What this scans for is the /// third case -- an INTER cell stamped with a literal sentinel, which is /// what the refusal actually fires on. Arguments are tokenised /// positionally, never `contains()`d. #[test] fn every_inter_record_publishes_an_obmc_readable_filter() { let src = include_str!("decode.rs"); let mut calls = 0usize; for (start, _) in src.match_indices("record_inter_rect_mi(") { // Skip the definition and the wrapper's own forwarding call. let line_start = src[..start].rfind('\n').map_or(0, |i| i + 1); let head = &src[line_start..start]; // The definition, the wrapper's own forwarding call, and this // test's own mentions of the name (doc comment, scan pattern, // assert message) are not publication sites. if head.contains("fn ") || head.contains("///") || head.ends_with('"') { continue; } let mut i = start + "record_inter_rect_mi(".len(); let (mut depth, mut arg, mut args) = (0i32, String::new(), Vec::new()); let bytes = src.as_bytes(); while i < bytes.len() { let c = bytes[i] as char; match c { '(' | '[' => depth += 1, ')' | ']' if depth == 0 && c == ')' => break, ')' | ']' => depth -= 1, ',' if depth == 0 => { args.push(std::mem::take(&mut arg)); i += 1; continue; } _ => {} } arg.push(c); i += 1; } if !arg.trim().is_empty() { args.push(arg); } assert_eq!( args.len(), 8, "record_inter_rect_mi gained an argument -- re-index this audit: {args:?}" ); calls += 1; let (is_inter, filter) = (args[4].trim(), args[6].trim()); if filter.starts_with('[') { assert_eq!( filter.replace(' ', ""), "[3,3]", "a literal filter other than the sentinel is published at call {calls}" ); assert_eq!( is_inter, "false", "an INTER cell is stamped with the [3, 3] sentinel (call {calls}): an OBMC \ blend picking it up refuses by name. Publish the block's own resolved \ switchable symbols instead." ); } } assert!( calls >= 6, "the audit found only {calls} publication sites -- it is broken, not the decoder" ); } /// lane-t900 r27, negative gate for "a reference frame selected with no /// picture at this frame's own ref_frame_idx slot for it": every /// non-`LAST_FRAME` reference resolves through `ref_planes`, and an empty /// slot is refused BY NAME there rather than predicting from `LAST`. /// /// Direct-call, not a stream: with this crate's writers the case is /// unreachable end to end. A SHOWN key frame refreshes all eight slots /// (spec 5.9.2 forces `refresh_frame_flags`, `write_frame_header` does the /// same) and nothing ever clears a slot, so once a stream has a key frame /// every slot holds a picture; a stream that OPENS on an inter frame is /// stopped one guard earlier, by `decode_stream`'s own `LAST` lookup /// ("an inter frame with no key frame before it", gated by /// `an_inter_frame_opening_a_stream_is_refused_by_name`). The reachable /// premise is a HIDDEN key frame refreshing only some slots, which /// `write_frame_header` refuses to write (`show_frame` must be set) -- /// so the stream-level witness needs a hidden-frame writer, noted as the /// open half of this proof. #[test] fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() { const REFUSAL: &str = "a reference frame selected with no picture at this frame's own ref_frame_idx slot"; let pic = Picture { width: 4, height: 4, y: vec![0u16; 16], u: vec![0u16; 4], v: vec![0u16; 4], }; let mut refs: [Option<&Picture>; 8] = [None; 8]; refs[1] = Some(&pic); let refpix = RefPix::ready(refs); for ref_frame in [LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME, BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME] { let err = match ref_planes(ref_frame, &refpix) { Ok(_) => panic!("ref {ref_frame}: an empty slot resolved to a picture"), Err(e) => e.to_string(), }; assert!(err.contains(REFUSAL), "ref {ref_frame}: expected {REFUSAL:?}, got: {err}"); } // `LAST_FRAME` never consults the slots: `decode_stream` checked it. let Ok((y, _, _)) = ref_planes(LAST_FRAME, &refpix) else { panic!("LAST_FRAME resolves to the frame's own reference planes") }; assert_eq!(y.width, 4); } #[test] fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() { let fctx = &crate::decode::FrameCtx::new(); let mut n = Neighbours::new(4, 4, 16, 16, fctx); n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false); assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1"); n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1); assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME)); assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME)); assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap())); } /// A below-16px leaf must clear the palette neighbour state over its own /// cell: before lane-palette2 r8 `record_palette_y_rect`'s `w / SUB` loops /// ran zero times for any sub-16 span, so `decode_leaf_rect` / /// `decode_leaf8` left a previous block's palette size and colours in the /// above/left arrays and the NEXT block read `palette_y_mode` off the /// wrong CDF row with a stale colour cache (class /// [[cdf-row-held-constant]]). #[test] fn a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero() { let fctx = &crate::decode::FrameCtx::new(); let mut n = Neighbours::new(4, 4, 16, 16, fctx); // A real 16x16 palette block covering SUB cell (1, 1). n.record_palette_y_rect((4, 4), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]); let (ctx, cache) = n.palette_ctx_and_cache((1, 1)); assert_eq!(ctx, 2, "the palette block itself must be visible"); assert_eq!(cache, vec![7, 9]); // An 8x8 non-palette leaf in that same cell. n.record_palette_y_rect((4, 4), 8, 8, 0, [0u16; 8]); let (ctx, cache) = n.palette_ctx_and_cache((1, 1)); assert_eq!(ctx, 0, "a sub-16 non-palette leaf must clear its own cell"); assert!(cache.is_empty(), "and its stale colour cache with it"); // Same for the chroma half. n.record_palette_uv_rect((4, 4), 16, 16, 2, [1, 2, 0, 0, 0, 0, 0, 0]); assert_eq!(n.palette_uv_cache((1, 1)), vec![1, 2]); n.record_palette_uv_rect((4, 4), 8, 8, 0, [0u16; 8]); assert!(n.palette_uv_cache((1, 1)).is_empty()); } /// lane-publish2 (the mode-info publish surface narrowed): two invariants /// the byte-exact stream gate only covers indirectly -- a size-0 palette /// stamp leaves the PREVIOUS block's colours in place (spec 5.11.46 /// `get_palette_cache` reads a neighbour's colours only where its size is /// non-zero, so writing 16 bytes of zeroes was pure traffic), and the /// narrowed `(u16, u8)` mi maps keep their "never written" sentinel. #[test] fn narrowed_publish_surface_keeps_neighbour_semantics() { assert_eq!(std::mem::size_of::<(u16, u8)>(), 4, "the narrowing must actually be 4 bytes"); let fctx = &crate::decode::FrameCtx::new(); let mut n = Neighbours::new(4, 4, 16, 16, fctx); n.record_palette_y_rect((4, 4), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]); n.record_palette_y_rect((4, 4), 16, 16, 0, [0u16; 8]); assert_eq!(n.above_palette_size[4], 0, "the size is what a reader gates on"); assert_eq!( n.above_palette_colors[4], [7, 9, 0, 0, 0, 0, 0, 0], "a size-0 stamp deliberately leaves the stale colours behind" ); let (ctx, cache) = n.palette_ctx_and_cache((1, 1)); assert_eq!(ctx, 0, "and they stay invisible to every reader"); assert!(cache.is_empty()); assert_eq!(n.mode_above_mi(4, 4), None, "u16::MAX sentinel = never written"); n.record_mode_mi(3, 4, 1, 1, DC_PRED); assert_eq!(n.mode_above_mi(4, 4), Some(DC_PRED)); } /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`): /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]` /// -- a few corner and interior points, not the whole 6x6 grid. #[test] fn compound_mode_ctx_map_matches_libaom_corners() { assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0); assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1); assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1); assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4); assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5); assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7); // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are // exactly the ranges `find_mv_stack_compound` produces. assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7); } #[test] fn a_frame_with_no_mode_info_grid_is_refused() { let fctx = &crate::decode::FrameCtx::new(); assert!( decode_key_frame_tile( &[0u8; 4], 0, 32, 32, 0, 128, false, &CdefParams::default(), &LoopFilterParams::default(), false, true, false, false, fctx, ) .is_err() ); } /// Encodes and decodes one picture with `modes`, asserting the decoder's /// planes are byte-exact against the encoder's own reconstruction. fn round_trips(w: usize, h: usize, modes: &[u8], fctx: &crate::decode::FrameCtx) { use crate::encode::{Encoded, Picture as Pic}; let mut source = vec![0u16; w * h]; for row in 0..h { for col in 0..w { source[row * w + col] = ((row * 3 + col * 5) % 251) as u16; } } let picture = Pic { width: w, height: h, y: source, u: vec![128; w * h / 4], v: vec![128; w * h / 4], }; let Encoded { tile, reconstruction, mi_cols, mi_rows, base_q_idx, tx_select, loop_filter, cdef, loop_restoration, .. }: Encoded = crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx).unwrap(); let decoded = decode_key_frame_tile_lr( &tile, mi_cols, mi_rows, base_q_idx, w as u32, h as u32, false, &cdef, &loop_filter, tx_select, true, false, false, &loop_restoration, fctx, ) .unwrap(); assert_eq!(decoded.width, w, "{w}x{h}: decoded width"); assert_eq!(decoded.height, h, "{w}x{h}: decoded height"); assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch"); assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch"); assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch"); } #[test] fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() { let fctx = &crate::decode::FrameCtx::new(); for (w, h) in [(128usize, 128usize), (192, 128)] { round_trips(w, h, &[DC_PRED as u8], fctx); } } /// Every one of the thirteen key-frame intra modes, at their base angle, /// on real (non-flat) content: the mode search picks whichever wins each /// block, so this exercises the directional edge/reach plumbing this /// decoder round adds, not just `DC_PRED`. #[test] fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() { let fctx = &crate::decode::FrameCtx::new(); for (w, h) in [(128usize, 128usize), (192, 128)] { round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx); } } /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path /// this decoder round adds. #[test] fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() { let fctx = &crate::decode::FrameCtx::new(); for (w, h) in [(854usize, 480usize), (216, 96)] { round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx); } } /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since /// no whole 16x16/32x32 legally covers the true edge here -- this decoder /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split /// bit, `partition_w8` leaves). #[test] fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() { let fctx = &crate::decode::FrameCtx::new(); for (w, h) in [(40usize, 32usize), (640, 360)] { round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx); } } /// A skipped block codes no residual syntax at all (spec 5.11.34): /// straight prediction on every plane. The real key-frame writer never /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to /// `0`), so this constructs the exact symbol sequence a writer that did /// emit it would produce, by hand, and asserts the decoded reconstruction /// is pure DC prediction (mid-grey, with no neighbours) rather than /// refusing. #[test] fn a_skipped_block_decodes_to_pure_prediction() { let fctx = &crate::decode::FrameCtx::new(); use crate::msac::SymbolEncoder; let mut cdfs = Cdfs::new(q_ctx_of(40)); let mut enc = SymbolEncoder::new(); // One whole, unsplit 64x64 superblock, coded skip = true. enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]); enc.symbol(1, &mut cdfs.skip[0]); enc.symbol( DC_PRED, &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]], ); enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]); let data = enc.finish(); let decoded = decode_key_frame_tile( &data, 16, 16, 40, 64, 64, false, &CdefParams::default(), &LoopFilterParams::default(), false, true, false, false, fctx, ) .unwrap(); assert!( decoded.y.iter().all(|&s| s == 128), "a skipped DC_PRED block with no neighbours predicts flat mid-grey" ); } /// An inter tile's SB-level `part64` used to be read and thrown away /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real /// non-SPLIT value there silently desynced the whole tile instead of /// refusing. Hand-writes a single whole superblock's `part64 = HORZ` /// symbol (never produced by this crate's own encoder, which only ever /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can) /// and asserts this decoder refuses by name rather than decoding garbage. #[test] fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() { let fctx = &crate::decode::FrameCtx::new(); use crate::msac::SymbolEncoder; let mut cdfs = Cdfs::new(q_ctx_of(40)); let mut enc = SymbolEncoder::new(); enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]); let data = enc.finish(); let reference = crate::encode::Picture::grey(64, 64); let err = decode_inter_frame_tile( &data, 16, 16, 40, 64, 64, &last_only(&reference), &CdefParams::default(), &LoopFilterParams::default(), false, false, Some(mc::InterpFilterKind::Regular), false, false, false, None, false, fctx, ) .unwrap_err(); let msg = err.to_string(); // lane-inter4 r1: this fixture's SB value is PARTITION_HORZ, now // DECODED rather than refused outright; its first 64x32 strip is // non-skip, so the named refusal is the rectangular-inter-residual // one. Either string proves what the pin was written for: a non-SPLIT // superblock never silently decodes as SPLIT. // lane-r14 r2: the rectangular-residual refusal is gone (a 64x32 strip // now codes its truncated low-32 coefficient corner), so this // hand-written fixture walks further still and stops on the limit of // the FIXTURE rather than of the decoder: it names no reference // pictures. All three strings prove the one thing this pin exists for // -- a non-SPLIT superblock never silently decodes as SPLIT. assert!( msg.contains("SPLIT") || msg.contains("rectangular residual coding") || msg.contains("no picture at this frame's own ref_frame_idx slot"), "expected the named inter-SB-partition refusal, got: {msg}" ); } // ffmpeg cross-oracle: an independent decoder (not this crate's own // encoder-side reconstruction) agrees with what this module decodes, // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same // name (that module is another lane's territory this round, and the // helpers are `#[cfg(test)]`-private to it). use std::io::Write; use std::process::{Command, Stdio}; /// Whether ffmpeg is on PATH. Absence normally SKIPs, but /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every /// aomenc gate decodes its stream through ffmpeg and is meaningless /// without it -- turns it into a hard failure. Without this the require /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg /// printed SKIP and reported green (class gate-skips-on-its-own-failure). fn have_ffmpeg() -> bool { let present = Command::new("ffmpeg") .arg("-version") .stdout(Stdio::null()) .stderr(Stdio::null()) .status() .is_ok_and(|s| s.success()); assert!( present || (!crate::envflags::env_flag!("EC_AV1_REQUIRE_FFMPEG") && !crate::envflags::env_flag!("EC_AV1_REQUIRE_AOMENC")), "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" ); present } /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0 /// frame's planes, at ffmpeg's own (coded, block-padded) size. fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { let mut child = Command::new("ffmpeg") .args([ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", ]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("ffmpeg failed to start"); // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB) // fills before the last input byte is written -- which is exactly what // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does // (measured: 45 min, both processes at 0% CPU). A write error here is // swallowed on purpose: ffmpeg's own exit status and stderr, asserted // below, are the real diagnosis. let mut stdin = child.stdin.take().expect("ffmpeg stdin"); let payload = stream.to_vec(); let writer = std::thread::Builder::new() .name("ec-av1-ffmpeg-in".into()) .spawn(move || { let _ = stdin.write_all(&payload); }) .expect("spawning the ffmpeg stdin writer"); let out = child.wait_with_output().expect("ffmpeg failed to run"); writer.join().expect("ffmpeg stdin writer thread"); assert!( out.status.success(), "ffmpeg refused the stream: {}", String::from_utf8_lossy(&out.stderr) ); let (luma, chroma) = (width * height, width * height / 4); assert_eq!( out.stdout.len(), luma + 2 * chroma, "expected one 4:2:0 frame" ); Picture { width, height, y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), } } /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. fn ffmpeg_decode_sequence( stream: &[u8], width: usize, height: usize, frames: usize, ) -> Vec { let mut child = Command::new("ffmpeg") .args([ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", ]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("ffmpeg failed to start"); // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB) // fills before the last input byte is written -- which is exactly what // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does // (measured: 45 min, both processes at 0% CPU). A write error here is // swallowed on purpose: ffmpeg's own exit status and stderr, asserted // below, are the real diagnosis. let mut stdin = child.stdin.take().expect("ffmpeg stdin"); let payload = stream.to_vec(); let writer = std::thread::Builder::new() .name("ec-av1-ffmpeg-in".into()) .spawn(move || { let _ = stdin.write_all(&payload); }) .expect("spawning the ffmpeg stdin writer"); let out = child.wait_with_output().expect("ffmpeg failed to run"); writer.join().expect("ffmpeg stdin writer thread"); assert!( out.status.success(), "ffmpeg refused the stream: {}", String::from_utf8_lossy(&out.stderr) ); let (luma, chroma) = (width * height, width * height / 4); let frame_bytes = luma + 2 * chroma; assert_eq!( out.stdout.len(), frame_bytes * frames, "expected {frames} 4:2:0 frames, ffmpeg said: {}", String::from_utf8_lossy(&out.stderr) ); (0..frames) .map(|i| { let base = i * frame_bytes; Picture { width, height, y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(), u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(), v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(), } }) .collect() } /// `ffprobe`'s reported coded `width,height` for one OBU stream -- /// duplicating `crate::encode`'s own helper (per-call temp naming: the /// test binary runs callers on parallel threads, and a shared name lets /// one test's cleanup race another's still-reading ffprobe -- /// pid-keyed-temp-path class). fn ffprobe_size(stream: &[u8]) -> (u32, u32) { static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let path = std::env::temp_dir().join(format!( "ec-av1-decode-probe-{}-{}.obu", std::process::id(), PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) )); let _ = std::fs::remove_file(&path); std::fs::write(&path, stream).expect("writing the probe stream"); let out = Command::new("ffprobe") .args([ "-v", "error", "-f", "obu", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", ]) .arg(&path) .output() .expect("ffprobe failed to run"); let _ = std::fs::remove_file(&path); assert!( out.status.success(), "ffprobe refused the stream: {}", String::from_utf8_lossy(&out.stderr) ); let text = String::from_utf8_lossy(&out.stdout); let mut fields = text.trim().split(','); let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); (width, height) } /// This module's own decoder against an independent one (ffmpeg), not /// just against this crate's encoder-side reconstruction: both decoders /// read the identical tile bytes, so agreement here rules out a bug this /// crate's own writer and reader could otherwise share. #[test] fn ffmpeg_and_this_decoder_agree_on_a_key_frame() { let fctx = &crate::decode::FrameCtx::new(); if !have_ffmpeg() { eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg"); return; } use crate::encode::encode_key_frame_with_ctx; for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] { let picture = round_trip_test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let (coded_w, coded_h) = ffprobe_size(&encoded.stream); let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize); let ours = decode_key_frame_tile_lr( &encoded.tile, encoded.mi_cols, encoded.mi_rows, encoded.base_q_idx, coded_w, coded_h, false, &encoded.cdef, &encoded.loop_filter, encoded.tx_select, true, encoded.screen, encoded.allow_intrabc, &encoded.loop_restoration, fctx, ) .unwrap(); assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg"); assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg"); assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg"); } } /// The key frame the encoder writes carries `tx_mode == TxMode::Select`, /// and that header bit is load-bearing for a decode of its tile: read as a /// `TxMode::Largest` frame the very first block misses its `tx_depth` /// symbol and the whole tile desyncs. Pins the shape that broke nine gates /// when `Encoded` had no `tx_select` for them to pass along — a test that /// hardcoded the bit was decoding a different frame header than the one /// the encoder wrote (and than the one `decode_stream`/ffmpeg read off the /// wire). #[test] fn a_key_frames_tile_needs_the_headers_own_tx_select_bit() { let fctx = &crate::decode::FrameCtx::new(); use crate::encode::encode_key_frame_with_ctx; let (width, height) = (64usize, 64usize); let picture = round_trip_test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); assert!( encoded.tx_select, "the encoder's key frame no longer codes TxMode::Select -- this \ gate's premise moved, not the decoder" ); let decode = |tx_select: bool| { decode_key_frame_tile_lr( &encoded.tile, encoded.mi_cols, encoded.mi_rows, encoded.base_q_idx, width as u32, height as u32, false, &encoded.cdef, &encoded.loop_filter, tx_select, true, encoded.screen, encoded.allow_intrabc, &encoded.loop_restoration, fctx, ) }; let right = decode(true).expect("the header's own tx_mode decodes"); assert_eq!(right.y, encoded.reconstruction.y, "luma under tx_select"); assert_eq!(right.u, encoded.reconstruction.u, "U under tx_select"); assert_eq!(right.v, encoded.reconstruction.v, "V under tx_select"); // The wrong bit either refuses or reconstructs something else; what it // must never do is agree, which would mean the bit codes nothing. if let Ok(wrong) = decode(false) { assert_ne!( wrong.y, encoded.reconstruction.y, "reading a TxMode::Select tile as Largest agreed -- the \ tx_depth symbols are not being coded" ); } } fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture { let mut picture = crate::encode::Picture::grey(width, height); for row in 0..height { for col in 0..width { picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16; } } for row in 0..height / 2 { for col in 0..width / 2 { let i = row * width / 2 + col; picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16; picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16; } } picture } fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture { let mut picture = crate::encode::Picture::grey(width, height); for y in 0..height { for x in 0..width { let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; let gradient = sx * 200.0 / width as f64; picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16; } } for y in 0..height / 2 { for x in 0..width / 2 { let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; let i = y * width / 2 + x; picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; } } picture } /// A GOP (one key frame plus several inter frames, each panned so its /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip /// `(0, 0)` no-op) decodes bit-exact against the encoder's own /// reconstruction, frame by frame, chaining each decoded frame straight /// into the next as its reference -- exactly the single-slot DPB /// [`crate::encode::encode_sequence`] itself threads. fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) { use crate::encode::encode_sequence_with_ctx; let pictures: Vec<_> = (0..4) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); assert_eq!(encoded.frames.len(), 4); let key = &encoded.frames[0]; let mut reference = decode_key_frame_tile_lr( &key.tile, key.mi_cols, key.mi_rows, key.base_q_idx, width as u32, height as u32, false, &key.cdef, &key.loop_filter, key.tx_select, true, // This key frame's own `allow_screen_content_tools`: its intra // blocks carry the palette syntax under it (stale-header class). key.screen, // ... 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(); assert_eq!( reference.y, key.reconstruction.y, "{width}x{height} frame 0 luma" ); assert_eq!( reference.u, key.reconstruction.u, "{width}x{height} frame 0 U" ); assert_eq!( reference.v, key.reconstruction.v, "{width}x{height} frame 0 V" ); for (i, frame) in encoded.frames.iter().enumerate().skip(1) { let decoded = decode_inter_frame_tile_lr( &frame.tile, frame.mi_cols, frame.mi_rows, frame.base_q_idx, width as u32, height as u32, &last_golden_altref( &reference, &encoded.frames[0].reconstruction, (i >= 2).then(|| &encoded.frames[i - 2].reconstruction), ), &frame.cdef, &frame.loop_filter, false, false, Some(mc::InterpFilterKind::Regular), false, // The encoder's own `reference_select` (spec 5.9.22): these // GOP round trips decode a tile the ENCODER wrote, so the // header bit must be the one it wrote, not a hard-coded // `false` (stale-header class -- a `reference_select` stream // reads a `comp_mode` symbol this decode would skip). crate::encode::reference_select(), frame.tx_select, &frame.loop_restoration, Some(frame.start_cdfs.0.clone()), NO_SIGN_BIAS, // This frame's own `allow_screen_content_tools`, off the // `Encoded` the encoder handed back (stale-header class). frame.screen, // Same stale-header class: the bit that makes this frame's // inter blocks carry a `motion_mode` symbol. frame.switchable_motion_mode, // These GOP round trips decode a tile the encoder wrote, so // the warp bit must be the one it wrote too (lane-av1obmc2); // the encoder only sets it under `EC_AV1_WARP`. crate::envflags::env_flag!("EC_AV1_WARP"), fctx, ) .unwrap(); assert_eq!( decoded.y, frame.reconstruction.y, "{width}x{height} frame {i} luma" ); assert_eq!( decoded.u, frame.reconstruction.u, "{width}x{height} frame {i} U" ); assert_eq!( decoded.v, frame.reconstruction.v, "{width}x{height} frame {i} V" ); reference = decoded; } } #[test] fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() { let fctx = &crate::decode::FrameCtx::new(); gop_round_trips(128, 64, fctx); } /// Same claim, at a size that is not a whole number of 32x32 blocks /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf /// split path is exercised too. #[test] fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() { let fctx = &crate::decode::FrameCtx::new(); gop_round_trips(216, 96, fctx); } /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way /// this module does, frame for frame. /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the /// MV stack's *second* candidate (`near_mv`), not its first /// (`nearest_mv`) -- a hand-built symbol stream drives /// [`decode_inter_block`] directly, since this crate's own encoder never /// writes NEARMV (round 3: it never chooses the mode). #[test] fn a_nearmv_block_predicts_from_the_stacks_second_candidate() { let fctx = &crate::decode::FrameCtx::new(); use crate::msac::SymbolEncoder; use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx}; const LAST_FRAME: i8 = 1; let (mi_cols, mi_rows) = (12u32, 12u32); let side = 16usize; // one 16x16 leaf block let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); let bw4 = side / 4; let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); let (above_mv, left_mv) = ((4, 4), (8, 8)); let neighbour = |mv: (i32, i32)| MiInfo { is_inter: true, ref_frame: LAST_FRAME, ref_frame1: NO_REF1, mv1: (0, 0), mv: mv16(mv), is_new_mv: false, size: 1, size_h: 1, is_global_mv0: false, is_global_mv1: false, }; for col in mi_col..mi_col + bw4 { grid.set(mi_row - 1, col, neighbour(above_mv)); } for row in mi_row..mi_row + bw4 { grid.set(row, mi_col - 1, neighbour(left_mv)); } let stack = find_mv_stack( &grid, mi_row, mi_col, bw4, bw4, LAST_FRAME, mi_cols as usize, mi_rows as usize, ); // Sanity on the test's own setup, not the code under test: two equal- // weight candidates keep scan order (above, then left -- module doc). assert_eq!(stack.entries.len(), 2); assert_eq!(stack.nearest_mv, above_mv); assert_eq!(stack.near_mv, left_mv); let (skip_ctx, ii_ctx, sr_ctx) = ( 0usize, intra_inter_ctx(true, true, false, false), single_ref_ctx(false), ); let mut cdfs = Cdfs::new(q_ctx_of(100)); let mut enc = SymbolEncoder::new(); enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV let data = enc.finish(); let (width, height) = (64usize, 64usize); let ref_pattern: Vec = (0..width * height).map(|i| (i % 251) as u16).collect(); let chroma: Vec = ref_pattern .iter() .step_by(2) .take((width / 2) * (height / 2)) .copied() .collect(); let reference = Picture { width, height, y: ref_pattern.clone(), u: chroma.clone(), v: chroma, }; let refpix = &last_only(&reference); let ref_y = whole_plane(&reference.y, width, height); let mut y = PlaneBuf { data: std::borrow::Cow::Owned(vec![0u16; width * height]), width, height, true_width: width, true_height: height, tile_x0: 0, tile_y0: 0, tile_x1: width, tile_y1: height, }; let mut u = PlaneBuf { data: std::borrow::Cow::Owned(vec![0u16; (width / 2) * (height / 2)]), width: width / 2, height: height / 2, true_width: width / 2, true_height: height / 2, tile_x0: 0, tile_y0: 0, tile_x1: width / 2, tile_y1: height / 2, }; let mut v = PlaneBuf { data: std::borrow::Cow::Owned(vec![0u16; (width / 2) * (height / 2)]), width: width / 2, height: height / 2, true_width: width / 2, true_height: height / 2, tile_x0: 0, tile_y0: 0, tile_x1: width / 2, tile_y1: height / 2, }; let mut cdfs = Cdfs::new(q_ctx_of(100)); let mut dec = SymbolDecoder::new(&data); let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize, fctx); decode_inter_block( &mut dec, &mut cdfs, &mut neighbours, &mut grid, sub16_to_mi((r, c)), side, mi_cols, mi_rows, &mut y, &mut u, &mut v, refpix, &NO_SIGN_BIAS, &[ec_av1_syntax::WarpParams::default(); 7], 100, TxbSet::Luma16, TxbSet::Luma16Inter, TxbSet::Chroma8, TX16, TX8, &[], &[], 0, false, false, Some(mc::InterpFilterKind::Regular), false, None, false, false, false, false, 0, 0, [0; 7], false, [0; 2], false, false, false, side, side, false, width, fctx, ) .unwrap(); // lane-wave1: a direct caller of the block decoder RECORDS its writes // (the tile decoder is what replays them), so this gate replays its // own before reading the plane back. flush_recon(fctx, &mut y, &mut u, &mut v); let (px, py) = (c * SUB, r * SUB); let mut want_near = vec![0u16; side * side]; crate::mc::predict( &ref_y.data, ref_y.width, ref_y.true_width, ref_y.true_height, mv_to_q4(px, left_mv.1, true), mv_to_q4(py, left_mv.0, true), side, side, &mut want_near, fctx, ); let mut want_nearest = vec![0u16; side * side]; crate::mc::predict( &ref_y.data, ref_y.width, ref_y.true_width, ref_y.true_height, mv_to_q4(px, above_mv.1, true), mv_to_q4(py, above_mv.0, true), side, side, &mut want_nearest, fctx, ); assert_ne!( want_near, want_nearest, "test setup: the two candidate MVs must predict differently" ); let mut got = vec![0u16; side * side]; for row in 0..side { got[row * side..(row + 1) * side].copy_from_slice( &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side], ); } assert_eq!( got, want_near, "NEARMV predicted from the wrong stack entry" ); } #[test] fn ffmpeg_and_this_decoder_agree_on_a_gop() { let fctx = &crate::decode::FrameCtx::new(); if !have_ffmpeg() { eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg"); return; } use crate::encode::encode_sequence_with_ctx; let (width, height) = (128usize, 64usize); let pictures: Vec<_> = (0..3) .map(|i| panned_test_card(width, height, i * 3)) .collect(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); let (coded_w, coded_h) = ffprobe_size(&encoded.stream); let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3); let key = &encoded.frames[0]; let mut reference = decode_key_frame_tile_lr( &key.tile, key.mi_cols, key.mi_rows, key.base_q_idx, coded_w, coded_h, false, &key.cdef, &key.loop_filter, key.tx_select, true, // This key frame's own `allow_screen_content_tools`: its intra // blocks carry the palette syntax under it (stale-header class). key.screen, // ... 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(); assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg"); for (i, frame) in encoded.frames.iter().enumerate().skip(1) { let decoded = decode_inter_frame_tile_lr( &frame.tile, frame.mi_cols, frame.mi_rows, frame.base_q_idx, coded_w, coded_h, &last_golden_altref( &reference, &encoded.frames[0].reconstruction, (i >= 2).then(|| &encoded.frames[i - 2].reconstruction), ), &frame.cdef, &frame.loop_filter, false, false, Some(mc::InterpFilterKind::Regular), false, // The encoder's own `reference_select` (spec 5.9.22): these // GOP round trips decode a tile the ENCODER wrote, so the // header bit must be the one it wrote, not a hard-coded // `false` (stale-header class -- a `reference_select` stream // reads a `comp_mode` symbol this decode would skip). crate::encode::reference_select(), frame.tx_select, &frame.loop_restoration, Some(frame.start_cdfs.0.clone()), NO_SIGN_BIAS, // This frame's own `allow_screen_content_tools`, off the // `Encoded` the encoder handed back (stale-header class). frame.screen, // Same stale-header class: the bit that makes this frame's // inter blocks carry a `motion_mode` symbol. frame.switchable_motion_mode, // These GOP round trips decode a tile the encoder wrote, so // the warp bit must be the one it wrote too (lane-av1obmc2); // the encoder only sets it under `EC_AV1_WARP`. crate::envflags::env_flag!("EC_AV1_WARP"), fctx, ) .unwrap(); assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg"); assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg"); assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg"); reference = decoded; } } } #[cfg(test)] mod tx4x8_table_tests { use super::*; /// Asymmetric gate on the two new scan tables (class /// `reference-layout-not-spec`): a transposed pair of tables passes any /// "is a permutation" check, so this pins the pair AGAINST each other -- /// `SCAN_8X4[k]` must be `SCAN_4X8[k]` reflected across the diagonal, and /// both must be bijections of `0..32` in our own row-major indexing. #[test] fn the_rect_4x8_scans_are_each_other_transposed() { let mut seen_a = [false; 32]; let mut seen_b = [false; 32]; for k in 0..32usize { let a = SCAN_4X8[k] as usize; let b = SCAN_8X4[k] as usize; assert!(!seen_a[a] && !seen_b[b], "scan position {k} repeats"); seen_a[a] = true; seen_b[b] = true; let (row, col) = (a / 4, a % 4); assert_eq!(b, col * 8 + row, "SCAN_8X4[{k}] is not SCAN_4X8[{k}] transposed"); } assert!(seen_a.iter().all(|&s| s) && seen_b.iter().all(|&s| s)); } /// `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/`mcol_scan_8x4` /// (libaom `scan.c`), converted out of their column-major encoding by /// `(p % h) * w + p / h` -- the head of each, pinned so the rect /// `V_DCT`/`H_DCT` walk cannot silently transpose. #[test] fn the_rect_class1_scans_match_libaom() { assert_eq!( class_scan_table_wh(4, 8, TxClass::Vert), (0..32u16).collect::>() ); assert_eq!( &class_scan_table_wh(4, 8, TxClass::Horiz)[..8], &[0u16, 4, 8, 12, 16, 20, 24, 28] ); assert_eq!( class_scan_table_wh(8, 4, TxClass::Vert), (0..32u16).collect::>() ); assert_eq!( &class_scan_table_wh(8, 4, TxClass::Horiz)[..8], &[0u16, 8, 16, 24, 1, 9, 17, 25] ); } /// The 32-position `eob_pt` alphabet: six symbols (one more than the /// 16-position table, one fewer than the 64-position one), strictly /// increasing, terminated at 32768 with the adaptation counter after it. #[test] fn the_32_position_eob_tables_are_well_formed() { for table in [ &cdf::EOB_PT_32_LUMA_Q0, &cdf::EOB_PT_32_LUMA_Q1, &cdf::EOB_PT_32_LUMA, &cdf::EOB_PT_32_LUMA_Q3, &cdf::EOB_PT_32_LUMA_CLASS1_Q0, &cdf::EOB_PT_32_LUMA_CLASS1_Q1, &cdf::EOB_PT_32_LUMA_CLASS1, &cdf::EOB_PT_32_LUMA_CLASS1_Q3, ] { assert_eq!(table.len(), 7); assert_eq!(table[5], 32768); assert_eq!(table[6], 0); for w in table[..6].windows(2) { assert!(w[0] < w[1], "{table:?} is not increasing"); } } } /// `Reach::of_rect` must read libaom's own `has_tr_4x8`/`has_tr_8x4` /// rows, not the 32x16 pair the two existing rect strips use: the two /// shapes disagree at a position inside the superblock, which is what /// makes this an asymmetric check rather than a tautology. #[test] fn the_sub8_rect_reach_tables_are_shape_specific() { let fctx = &crate::decode::FrameCtx::new(); let a = Reach::of_rect(4, 8, 4, 8, 64, 64, fctx); let b = Reach::of_rect(8, 4, 8, 4, 64, 64, fctx); assert!( a.above_right != b.above_right || a.below_left != b.below_left, "4x8 and 8x4 reach identically at mirrored positions -- one table is unused" ); } }