//! 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, MAX_SEGMENTS, SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo, }; use ec_core::{Error, Result}; // lane-av112bit: the 12-bit warp refusal that used to stand at all three // warp decision sites (compound, 16x16+, 8x8 leaf) was an inline literal // (refusal_inventory.rs extracts refusal strings from the decode source); // it named the real gap: warp's reduce bits inherited the 12-bit // `conv_params->round_0` (warped_motion.c:295, convolve.h:81..86) and no // witness existed. // lane-av112bitw lifted it from all three sites: `warp::warp_round_0` // implements the bump (`round_0 += max(bd + FILTER_BITS - round_0 - 14, 0)`, // 5 at 12 bits), and the single-ref witness plus the rotating-mandelbrot // compound-warp witness are both byte-exact vs ffmpeg. Compound inter // itself was lifted by lane-av112bitc before that (the combines absorb the // CONV_BUF gain drop, `INTER_POST_ROUND - delta`, see `mc::combine_compound`). /// 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, /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every /// motion compensation of THIS frame runs, already resolved to a kernel. /// `mc::predict` used to hardwire `Regular`, so the encoder's search, /// trial and recon could only ever build a REGULAR prediction whatever /// the frame header said; it lives here (and is copied by /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same /// kernel the frame header wrote instead of the default. pub(crate) interp_filter: std::cell::Cell, /// lane-lossless: this frame's per-segment lossless table -- libaom's /// `xd->lossless[MAX_SEGMENTS]`, computed ONCE per frame in the header /// (spec 5.9.12 `CodedLossless`: each segment at `qindex == 0` with zero /// plane deltas, `get_qindex` applying that segment's own `SEG_LVL_ALT_Q`). /// Every block-decoder rule that reads [`decode::lossless`] resolves it /// through the BLOCK's own `segment_id`: TX_4X4 with the Walsh-Hadamard /// transform on every plane, the dropped `tx_type` symbol and the narrowed /// `is_cfl_allowed` (libaom `read_tx_size` (`decodeframe.c`), /// `read_tx_type` (`decodetxb.c`), `is_cfl_allowed` (`blockd.h`)) follow /// the SEGMENT, so a frame whose segments disagree codes lossless and /// lossy blocks side by side. pub(crate) lossless_per_seg: std::cell::Cell<[bool; MAX_SEGMENTS]>, /// lane-av1txr: this frame header's `disable_cdf_update` (spec 5.9.2). /// When set, the tile reader must not adapt any CDF it reads, or its /// tables drift away from the encoder's and the frame desyncs mid-tile /// (libaom: `allow_update_cdf = allow_update_cdf && /// !cm->features.disable_cdf_update`, `decodeframe.c:2909`). pub(crate) disable_cdf_update: std::cell::Cell, pub(crate) cdef_bits: std::cell::Cell, pub(crate) bit_depth: std::cell::Cell, /// lane-av1mono: the sequence header's `color_config.mono_chrome` (spec /// 5.5.2), i.e. `NumPlanes == 1`. libaom threads this as /// `av1_num_planes(cm)` and every chroma read site is guarded by /// `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`, /// `:1208`) or bounded by `plane < num_planes`; a monochrome frame codes /// NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` symbol and NO chroma /// coefficients on any block. Set once per frame from the sequence header /// (like [`FrameCtx::bit_depth`]), so a mono frame decoded on a thread /// that last saw a 4:2:0 one never inherits the wrong plane count. pub(crate) mono_chrome: std::cell::Cell, /// lane-av1-444: sequence subsampling_x/y. 1,1 is 4:2:0; 0,0 is 4:4:4. pub(crate) subsampling_x: std::cell::Cell, pub(crate) subsampling_y: 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, /// lane-av1-qmatrix: this frame's quantisation-matrix LEVEL per plane, /// straight from spec 5.9.12's `qm_y`/`qm_u`/`qm_v` (the parsed 4-bit /// value IS the table level -- libaom `quant_params->qmatrix_level_y/u/v`, /// decodeframe.c:1902-1917; the `aom_get_qmlevel` formula that maps /// base_q_idx onto a level is encoder-side only). 15 is libaom's flat /// sentinel (`NUM_QM_LEVELS - 1`, stored as NULL tables) and the default /// every `using_qmatrix == 0` frame keeps, so a matrix-free stream /// selects no matrix. pub(crate) qm_levels: std::cell::Cell<[u8; 3]>, 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, /// Whether the tile being decoded is an INTRA-ONLY frame's (key/intra-only /// frame). libaom runs `set_txfm_ctxs` for EVERY block of EVERY frame /// (`decodeframe.c` `parse_decode_block`), so an intra-only frame /// maintains the `TXFM_CONTEXT` bands exactly like an inter one; only this /// decoder's inter-side publishing was wired. See /// [`Neighbours::fill_lf_grid_rect`]'s band publish. pub(crate) intra_only: std::cell::Cell, /// This FRAME's own `tx_mode == TxMode::Select`, set for EVERY frame /// (intra included). [`Self::tx_select_inter`] cannot stand in for it: /// an intrabc block rides an INTRA frame, but libaom still reads its /// var-tx `txfm_partition` tree under the frame's `TxMode::Select`. pub(crate) tx_select_frame: 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 { // A DECODER context is seeded from the stream alone: every real // decode overwrites this from the parsed sequence header // (`set_sb128`, stream.rs). The encoder's own contexts start at // the size this process encodes -- see [`FrameCtx::for_encoder`]. sb128_flag: std::cell::Cell::new(false), interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular), lossless_per_seg: std::cell::Cell::new([false; MAX_SEGMENTS]), disable_cdf_update: std::cell::Cell::new(false), cdef_bits: std::cell::Cell::new(0), bit_depth: std::cell::Cell::new(8), mono_chrome: std::cell::Cell::new(false), subsampling_x: std::cell::Cell::new(1), subsampling_y: std::cell::Cell::new(1), 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, }), qm_levels: std::cell::Cell::new([crate::qm::NUM_QM_LEVELS as u8 - 1; 3]), 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), tx_select_frame: std::cell::Cell::new(false), intra_only: std::cell::Cell::new(false), reduced_tx_set_inter: std::cell::Cell::new(false), 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), } } /// A context for the ENCODER's own trial decodes: it starts at the /// superblock size this process encodes (`crate::encode::sb128_on`) so /// the mode search's `Reach` and the filter search's internal decodes /// agree with the tile writer. A decoder never reads that knob -- doing /// so coupled every decode to the encoder's process-global and raced the /// 128-superblock decode gates against the encoder witness. pub(crate) fn for_encoder() -> Self { let ctx = Self::new(); let on = crate::encode::sb128_on(); ctx.sb128_flag.set(on); ctx.reach_sb_px .set(if on { 128 } else { crate::encode::SUPERBLOCK }); ctx } } /// `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.mono_chrome.set(fctx.mono_chrome.get()); out.subsampling_x.set(fctx.subsampling_x.get()); out.subsampling_y.set(fctx.subsampling_y.get()); out.interp_filter.set(fctx.interp_filter.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()); // lane-b128m: the superblock size travels with the copy. A tile SEARCH // worker (`encode::search_tiles`) gets its context from here, so dropping // it made every worker search at 64 while the calling thread searched at // 128 -- the bytes a frame came out as then depended on the tile thread // count under `EC_AV1_SB128`. out.sb128_flag.set(fctx.sb128_flag.get()); out.reach_sb_px.set(fctx.reach_sb_px.get()); 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); } /// lane-av1mixloss: sets [`FrameCtx::lossless_per_seg`] (called once per frame /// from `stream.rs`). pub(crate) fn set_lossless_per_seg(table: [bool; MAX_SEGMENTS], fctx: &crate::decode::FrameCtx) { fctx.lossless_per_seg.with(|c| c.set(table)); } /// The BLOCK's own lossless bit: libaom's `xd->lossless[mbmi->segment_id]`. /// The table is computed once per frame (libaom `decodeframe.c:5205`: /// `qindex == 0` with every plane delta 0, `av1_get_qindex` applying the /// segment's `SEG_LVL_ALT_Q`), but the frame never carries ONE lossless rule /// -- `read_tx_size`, `read_tx_type` and `is_cfl_allowed` all index it by the /// BLOCK's own segment id, which the spec-order `segment_id` read sets before /// any mode/transform symbol of the block. A frame whose segments disagree /// codes TX_4X4/WHT blocks and normal blocks side by side. pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool { let seg_id = usize::from(fctx.cur_segment_id.with(|c| c.get())); fctx.lossless_per_seg.with(|c| c.get())[seg_id] } /// Sets [`FrameCtx::disable_cdf_update`] (called once per frame from /// `stream.rs`). pub(crate) fn set_disable_cdf_update(v: bool, fctx: &crate::decode::FrameCtx) { fctx.disable_cdf_update.with(|c| c.set(v)); } /// This frame's `disable_cdf_update`, for the tile readers -- /// [`msac::SymbolDecoder::set_cdf_update`](crate::msac::SymbolDecoder::set_cdf_update). pub(crate) fn cdf_update_disabled(fctx: &crate::decode::FrameCtx) -> bool { fctx.disable_cdf_update.with(|c| c.get()) } /// The transform side a block of `side` pixels codes: its own (capped at the /// caller's own largest) normally, 4 on a lossless BLOCK, where libaom's /// `read_tx_size` returns TX_4X4 before it looks at anything else /// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return /// TX_4X4;`). pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize { if lossless(fctx) { 4 } else { px } } /// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to /// 32x32 -- but on a LOSSLESS BLOCK only when the block's CHROMA plane block /// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller. /// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom /// picks the 13-symbol one (class `wrong-alphabet-same-value`). pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool { if lossless(fctx) { // `is_cfl_allowed`: at lossless CfL is available only when the // partition size equals the transform size -- the CHROMA plane block // must be a single TX_4X4. True for an 8x8 partition at 4:2:0 (its // plane block is 4x4) and for 4x4 partitions; FALSE for an 8x8 // partition at 4:4:4, whose plane block is 8x8 -- that partition // reads the 13-symbol uv_mode CDF, and reading the CFL alphabet // there desynced the tile from the leaf's own uv_mode symbol (class // `wrong-alphabet-same-value`). (bw >> ss_x(fctx)).max(4) == 4 && (bh >> ss_y(fctx)).max(4) == 4 } else { bw <= 32 && bh <= 32 } } 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. pub(crate) 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. pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7]; pub(crate) 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 stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a /// monochrome frame has `NumPlanes == 1`, so no block codes any chroma /// symbol or chroma coefficient and the output picture is luma only. pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool { fctx.mono_chrome.with(std::cell::Cell::get) } /// Sets [`mono`] for the current thread, called once per frame from /// [`crate::stream`]'s decode loop like [`set_bit_depth`]. pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) { fctx.mono_chrome.with(|c| c.set(mono_chrome)); } /// Sequence subsampling. Set once per frame from stream.rs, like set_mono. pub(crate) fn set_subsampling(ss_x: u8, ss_y: u8, fctx: &crate::decode::FrameCtx) { fctx.subsampling_x.set(ss_x); fctx.subsampling_y.set(ss_y); } #[inline] pub(crate) fn ss_x(fctx: &crate::decode::FrameCtx) -> usize { fctx.subsampling_x.get() as usize } #[inline] pub(crate) fn ss_y(fctx: &crate::decode::FrameCtx) -> usize { fctx.subsampling_y.get() as usize } /// libaom ROUND_POWER_OF_TWO. At ss=1 equals div_ceil(dim, 2); at ss=0 is dim. #[inline] pub(crate) fn round_ss(dim: usize, ss: usize) -> usize { (dim + ((1usize << ss) >> 1)) >> ss } /// 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), } } /// lane-av1-qmatrix: records this FRAME's quantisation-matrix levels /// ([`crate::decode::FrameCtx::qm_levels`]) from the parsed /// `quantization_params`. Called from `stream.rs` at the frame header, where /// the refusal this lane lifted used to sit. pub(crate) fn set_qm_levels(levels: [u8; 3], fctx: &crate::decode::FrameCtx) { fctx.qm_levels.with(|c| c.set(levels)); } /// This block's inverse quantisation matrix -- libaom `av1_get_iqmatrix` /// (`av1/common/quant_common.c:243`) plus `setup_segmentation_dequant`'s /// `av1_use_qmatrix` gate, evaluated per dequantisation call site the same /// way the site already evaluates its quantizer index. `None` dequantises /// flat (the only behaviour before lane-av1-qmatrix): /// - a level of 15, which is both libaom's flat sentinel and what every /// `using_qmatrix == 0` frame's levels are parked at; /// - a 1D/identity transform (`is_2d_transform` false: libaom's /// `av1_get_iqmatrix` reads the NULL slot for those); /// - a LOSSLESS block (libaom `av1_use_qmatrix`'s `!xd->lossless[seg]`: the /// segment-adjusted quantizer index clamped to 0 with all five plane /// deltas zero -- the same `block_q_idx` every other dequant site reads). fn block_iqmatrix( fctx: &crate::decode::FrameCtx, plane_idx: usize, w: usize, h: usize, tx_type: TxType, ) -> Option { let levels = fctx.qm_levels.with(|c| c.get()); let level = levels[plane_idx.min(2)]; if usize::from(level) >= crate::qm::NUM_QM_LEVELS - 1 { return None; } if !tx_type.is_2d_transform() { return None; } let d = fctx.quant_deltas.with(|c| c.get()); if block_q_idx(fctx) == 0 && d.y_dc == 0 && d.u_dc == 0 && d.u_ac == 0 && d.v_dc == 0 && d.v_ac == 0 { return None; } crate::qm::iwt_matrix(usize::from(level), plane_idx != 0, w, h) } /// `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, // The reading BLOCK's own span in 4x4 mode-info units: a block wider or // taller than one 64x64 CDEF unit is the first non-skip block of EVERY // unit it covers, so its one literal drives all of them (lane-b128r). (w_mi, h_mi): (usize, 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 { // lane-b128r: libaom's four CDEF units of a 128 superblock all read // their strength off the MB_MODE_INFO of the first non-skip block in // their own unit -- and a block that COVERS several units (the 128 // root's own 128x128 block, the only one there is) is that block for // every unit it covers, so one literal drives all four. This grid is // per 64x64 unit, so the read stamps every unit the block covers; one // that is smaller than a unit stamps exactly the cell it always did. let (rows, cols) = ( (h_mi / SB_MI as usize).max(1), (w_mi / SB_MI as usize).max(1), ); fctx.cdef_idx_grid.with(|g| { let mut g = g.borrow_mut(); for dr in 0..rows { for dc in 0..cols { let i = (sb_r + dr) * sb_cols + sb_c + dc; if sb_c + dc < sb_cols && 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) }; /// lane-golomb2: the (lowest, highest) quantizer index any block has been /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than /// zero (class `gate-blind-to-feature`): segmentation being enabled says /// nothing about the segments carrying distinct quantizers. static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) }; /// 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, ) { if crate::envflags::env_flag!("EC_HDR") { eprintln!( "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}", seg.enabled, seg.update_map, seg.temporal_update, seg.seg_id_pre_skip, seg.last_active_seg_id, seg.feature_data ); } 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) } /// The lowest and highest quantizer index any decoded block was dequantized /// with (`(i32::MAX, i32::MIN)` when nothing decoded). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn block_q_span() -> (i32, i32) { BLOCK_Q_SPAN.with(|c| c.get()) } /// 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)); BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN))); } /// `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; let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) { Some(data) => (base + data).clamp(0, 255), None => base, }; // lane-d792: which SEGMENT a block's quantizer came out of, beside the // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels // already proven equal is a segment-id defect, not a quantizer one. if crate::envflags::env_flag!("EC_DQCOEFF") { eprintln!("OUR_Q base={base} seg={seg_id} q={q}"); } hit_do!(BLOCK_Q_SPAN.with(|c| { let (lo, hi) = c.get(); c.set((lo.min(q), hi.max(q))); });); q } /// 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)); } /// `copy_segment_id` (libaom `decodemv.c:342`): the previous frame's map is /// inherited VERBATIM over this block's own mi footprint -- per-cell copies, /// not the minified id [`predicted_segment_id`] hands the block. Without a /// previous map the footprint is zeroed, exactly as the C NULL branch does. fn copy_segment_ids( mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, 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(); fctx.prev_seg_ids.with(|p| { let p = p.borrow(); for y in 0..y_mis { for x in 0..x_mis { let idx = (mi_r + y) * mi_cols + mi_c + x; m[idx] = p.get(idx).copied().unwrap_or(0); } } }); }); } /// `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)); let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active); // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..` // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff. if crate::envflags::env_flag!("EC_TRACE_SEG") { eprintln!( "EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}", dec.debug_state().0 ); } id 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 from the previous frame, and libaom's // `copy_segment_id` (decodemv.c:342) does that VERBATIM -- a memcpy of // the previous map over the block's own footprint, mixed ids intact -- // while the id the BLOCK itself carries is the min over that footprint // (`get_predicted_segment_id`). Stamping the min here flattened mixed // footprints into the saved map, and every later frame whose // `update_map == 0` copy or temporal prediction read that position // dequantized with the wrong segment's `SEG_LVL_ALT_Q` (class // `simplified-inheritance`). copy_segment_ids(mi_r, mi_c, w_mi, h_mi, fctx); let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx); fctx.cur_segment_id.with(|c| c.set(id)); SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id)); 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 } /// [`tu_reach`] for a unit whose LUMA footprint is a `tx_w` x `tx_h` rect /// (lane-av1-422b: a 4:2:2 chroma unit is square in chroma pixels, but its /// luma anchor is `(chroma_tx << ss_x, chroma_tx << ss_y)` -- at ss (1,0) /// twice as wide as it is tall). Same predicate as [`tu_reach`]; the /// square mismatch counter only means anything when the footprint actually /// is square. fn tu_reach_rect( bw: usize, bh: usize, col_off: usize, row_off: usize, tx_w: usize, tx_h: 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_w, tx_h, block); if tx_w == tx_h { let standalone = Reach::of(tx_w, 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.intra_only.with(|c| c.set(false)); fctx.tx_select_frame.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()) } // lane-av1-422: how many SQUARE chroma coefficient units the strip path read // on a 4:2:2 frame (ss 1,0) -- the half-width, unhalved-height shape whose // tables only exist because of the square rows in the chroma_tiled arm. A // 4:2:0 or 4:4:4 frame can never increment it (their rect strips' chroma is // itself rect), and a restored `/2 chroma height` diverts 4:2:2 squares onto // the rect rows, so the witness gate reads 0 there and fails. thread_local! { static CHROMA422_SQUARE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA422_SQUARE_HITS`]. // lane-av1-422b: `pub` so `examples/decode_probe.rs` can census it the way // it does every other capability counter. pub fn chroma422_square_hits() -> usize { CHROMA422_SQUARE_HITS.with(|c| c.get()) } // lane-av1-422f: how many RECT chroma coefficient units the square-block // path read on a 4:2:2 frame (ss 1,0) -- TX_4X8 / TX_8X16 / TX_16X32, the // plane block's own half-width, unhalved-height shape. A 4:2:0 or 4:4:4 // frame never takes the rect branch (their units are square // `chroma_tx == chroma_tx_h`), so a witness gate reading 0 here proves the // model reverted to squares. thread_local! { static CHROMA422_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA422_RECT_HITS`]. pub fn chroma422_rect_hits() -> usize { CHROMA422_RECT_HITS.with(|c| c.get()) } // lane-av1-422g: how many PER-LEAF TX_4X4 chroma coefficient units the // sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per even-column // leaf per plane (`is_chroma_reference`'s `!(mi_col & ss_x)`). A 4:2:0 frame // codes no sub-8 chroma at all and 4:4:4 goes through `sub8_leaf_chroma444`, // so a witness gate reading 0 here proves the per-leaf 4:2:2 arm never ran. thread_local! { static CHROMA422_SUB8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA422_SUB8_HITS`]. pub fn chroma422_sub8_hits() -> usize { CHROMA422_SUB8_HITS.with(|c| c.get()) } // lane-av1422llintra: how many 4:2:2 LOSSLESS chroma plane blocks // (`decode_leaf8`) were walked as 4x4 units rather than as the one // `av1_get_max_uv_txsize` rect that rule only reaches OUTSIDE a lossless // frame. A 4:2:0 or 4:4:4 frame never takes the arm (its own lossless walk // was already there), so a witness gate reading 0 here proves the model // reverted to the rect unit. thread_local! { static CHROMA422_LOSSLESS_4X4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA422_LOSSLESS_4X4_HITS`]. pub fn chroma422_lossless_4x4_hits() -> usize { CHROMA422_LOSSLESS_4X4_HITS.with(|c| c.get()) } // lane-av1-422sub8rect: how many PER-PIECE TX_4X4 chroma coefficient units // the INTER sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per // non-skipped odd-column piece per plane (`is_chroma_reference`'s // `mi_col & 0x01` at ss_x 1). 4:2:0 goes through the shared group unit and // 4:4:4 through [`sub8_leaf_chroma444`]'s own per-piece twin, so a witness // gate reading 0 here proves the inter 4:2:2 per-piece arm never ran. thread_local! { static CHROMA422_INTER_SUB8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA422_INTER_SUB8_HITS`]. pub fn chroma422_inter_sub8_hits() -> usize { CHROMA422_INTER_SUB8_HITS.with(|c| c.get()) } // lane-av1-422m: how many TX_4X4 chunk units the invalid-ss-size chroma arm // read (the 8x32 luma block whose 4:2:2 plane has no `ss_size_lookup` block). // A 4:2:0 or 4:4:4 frame cannot increment it, so a non-zero read proves the // chunked 4:2:2 chroma really decoded. thread_local! { static CHROMA422_CHUNK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA422_CHUNK_HITS`]. pub fn chroma422_chunk_hits() -> usize { CHROMA422_CHUNK_HITS.with(|c| c.get()) } // lane-av1-422stripanchor: how many 4-wide-strip PAIR chroma units // ([`decode_rect_split`]'s ported floored-pair anchor) decoded. A 4:2:0 or // 4:4:4 frame cannot increment it (the arm is keyed to a 2-px-wide chroma // block, which only a 1-mi-wide strip at ss (1, 0) produces), so a non-zero // read proves a stream routed a 4-wide strip through the split path. thread_local! { static CHROMA422_PAIR_WIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA422_PAIR_WIDE_HITS`]. pub fn chroma422_pair_wide_hits() -> usize { CHROMA422_PAIR_WIDE_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()) } // lane-av1readcensus: the PER-UNIT coefficient census -- one unit counted // per `read_coeffs`/`read_coeffs_rect` call, i.e. per object this decoder // actually walks, which is the unit the round-4 `av1444rect` count measured // (636 square chroma reads against the oracle's 1086). The counters are // 4:4:4-ONLY (`CENSUS_444`, set per frame beside `set_subsampling`), so a // 4:2:0 control reads `(0, 0, 0)` -- a walk-shape change at 4:2:0 is another // lane's business, and this census must not fire there. thread_local! { /// Per-plane unit counts, `[luma, u, v]`, at 4:4:4 only. static CENSUS_444_UNITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; /// Of [`CENSUS_444_UNITS`], the units that coded at least one coefficient /// (`txb_skip == 0`) -- the per-plane split is only comparable against /// the oracle's when both sides count all-zero units the same way. static CENSUS_444_CODED: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; /// Sequential unit index, so a trace line names its own position in the /// frame's walk rather than relying on line order alone. static CENSUS_UNIT_N: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The plane the units read from here on belong to. A thread-local rather /// than a `read_coeffs` parameter because the three luma call sites /// (`decode_rect_split`, `decode_block_rect64`, `read_inter_plane_rect`) /// are not this lane's to edit and would each grow an argument; the /// plane-owning readers stamp it once on entry instead. static CENSUS_PLANE: std::cell::Cell = const { std::cell::Cell::new(0) }; /// 4:4:4 (`subsampling_x == 0 && subsampling_y == 0`) for the frame being /// decoded, set per frame from [`crate::stream`]. static CENSUS_444: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Current `[luma, u, v]` 4:4:4 coefficient-unit counts. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn census_444_units() -> [usize; 3] { CENSUS_444_UNITS.with(|c| c.get()) } /// Current `[luma, u, v]` 4:4:4 counts of units that coded coefficients. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn census_444_coded() -> [usize; 3] { CENSUS_444_CODED.with(|c| c.get()) } /// lane-av1readcensus: arms the 4:4:4 census for the frame about to decode, /// called once per frame from [`crate::stream`]'s decode loop beside /// [`set_subsampling`]. At 4:2:0 (or 4:2:2) every census counter stays zero -- /// the walk-shape question this census answers is a 4:4:4 one. pub(crate) fn set_census_444(ss_x: u8, ss_y: u8) { CENSUS_444.with(|c| c.set(ss_x == 0 && ss_y == 0)); } /// lane-av1readcensus: the plane the units read from here on belong to, /// stamped by the plane-owning readers ([`read_plane`], [`read_inter_plane`], /// [`read_inter_plane_rect`]) on entry. pub(crate) fn set_census_plane(plane: usize) { CENSUS_PLANE.with(|c| c.set(plane)); } /// lane-av1readcensus: is the per-unit census trace on? Shares /// [`coeff_trace_on`]'s per-frame narrowing so one frame's walk can be /// dumped without the rest of the stream. fn census_trace_on() -> bool { if !crate::envflags::env_flag!("EC_CENSUS_UNIT") { return false; } match COEFF_TRACE_FRAME.with(|c| c.get()) { None => true, Some(w) if w >= usize::MAX - 1 => true, Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w, } } /// lane-av1readcensus: one line per coefficient unit this decoder walks, the /// twin of the oracle's `EC_COEFF` / `EC_COEFF_VAL` bracket around each /// `av1_read_coeffs_txb` call. Pair the two sides by `post_rng` (or by `n`), /// never by plane label or by walk position -- the walk order is exactly what /// the census is measuring. fn census_unit( w: usize, h: usize, tx_type: TxType, eob: usize, all_zero: bool, entry_rng: u32, dec: &SymbolDecoder, ) { let plane = CENSUS_PLANE.with(|c| c.get()).min(2); let coded = usize::from(!all_zero); CENSUS_UNIT_N.with(|c| c.set(c.get() + 1)); hit_do! { CENSUS_444_UNITS.with(|c| { if CENSUS_444.with(|on| on.get()) { let mut v = c.get(); v[plane] += 1; c.set(v); } }); CENSUS_444_CODED.with(|c| { if CENSUS_444.with(|on| on.get()) { let mut v = c.get(); v[plane] += coded; c.set(v); } }); } if !census_trace_on() { return; } let n = CENSUS_UNIT_N.with(|c| c.get()) - 1; let post_rng = dec.debug_state().0; eprintln!( "EC_CENSUS_UNIT side=ours n={n} plane={plane} w={w} h={h} tx={tx_type:?} eob={eob} \ all_zero={all_zero} entry_rng={entry_rng} post_rng={post_rng}" ); } /// How many transform units this thread has read since the last /// [`reset_census_unit_n`] (lane-av1offtile). The per-unit oracle twin is /// `EC_ECDUMP_IN`, one line per `read_coeffs_txb` call, so this count IS /// directly comparable with an oracle `EC_ECDUMP_IN` census -- which is what /// makes "we walk N units where libaom walks M" a gated claim rather than an /// inference from the desync's position. pub fn census_unit_n() -> usize { CENSUS_UNIT_N.with(|c| c.get()) } /// Reset [`census_unit_n`] to zero (lane-av1offtile). pub fn reset_census_unit_n() { CENSUS_UNIT_N.with(|c| c.set(0)); } /// lane-av1ibcfork: this decoder's half of the per-unit BIT INTERVAL -- the /// exact mirror of the oracle's `EC_ECDUMP_IN` / `EC_ECDUMP_OUT` / /// `EC_ECDUMP_END` triple (`aom-oracle2/src/av1/decoder/decodetxb.c`: one /// print in `read_coeffs_txb` before and after its `aom_read_symbol`, one in /// the single caller `av1_read_coeffs_txb` after the whole unit). /// /// Why three prints and not one `EC_CENSUS_UNIT`: a COUNT is not a key. The /// two sides can walk a different NUMBER of units and still be paired, because /// the interval is what a unit CONSUMED. Entry position alone drifts the moment /// one side consumes a different number of bits, and list index is invalid the /// moment one side misses a unit -- both were measured here and both /// mis-attribute. `post_bit` after the `txb_skip` read is the same /// `aom_reader_tell` the oracle prints there; `end_bit` is the end of the whole /// unit including the optional luma `tx_type`, the eob, the base/BR passes and /// the sign/Golomb loop, so a unit that reads the right symbols in the wrong /// ORDER is caught too. /// /// `bit` counts the bits this decoder has pulled out of its window, so it sits /// at a CONSTANT offset from the oracle's tell (the OBU header libaom counts /// before `aom_reader_init`). The offset is measured per fixture, never /// assumed: +14 on `444_intrabc_rect4_witness.obu`. #[inline] fn unit_iv_on() -> bool { crate::envflags::env_flag!("EC_UNITIV") } /// The unit's ENTRY position. Returns it so the caller can pass the same value /// to [`unit_iv_skip`] and [`unit_iv_end`] without reading the decoder again. #[inline] #[track_caller] fn unit_iv_in(plane: usize, w: usize, h: usize, ctx: usize, dec: &SymbolDecoder) -> usize { if !unit_iv_on() { return 0; } let bit = dec.debug_bitpos(); let (mi_r, mi_c) = SymbolDecoder::symr_mi(); eprintln!( "EC_UNITIV_IN side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} bit={bit} at {}", std::panic::Location::caller() ); bit } /// The position immediately after this unit's `txb_skip` read. `bit_in == /// post_bit` means the read consumed ZERO bits (a CDF row already at a /// boundary), so this is also the real-read filter: the reader logs a step /// either way, and counting raw lines overstates the symbol count ~2x (measured /// on `444_intrabc_rect4_witness.obu`: 2395 lines, 512 real reads, against the /// oracle's 513 -- not the "~1069 fewer" an earlier round reported). #[inline] fn unit_iv_skip( dec: &SymbolDecoder, bit_in: usize, plane: usize, w: usize, h: usize, ctx: usize, all_zero: bool, ) { if !unit_iv_on() { return; } let (mi_r, mi_c) = SymbolDecoder::symr_mi(); eprintln!( "EC_UNITIV_SKIP side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} az={} bit={bit_in} post_bit={}", all_zero as i32, dec.debug_bitpos() ); } /// The position after the WHOLE unit. One call per successful read, on both /// the all-zero early return and the full coefficient walk. #[inline] fn unit_iv_end(dec: &SymbolDecoder, plane: usize, w: usize, h: usize, ctx: usize) { if !unit_iv_on() { return; } let (mi_r, mi_c) = SymbolDecoder::symr_mi(); eprintln!( "EC_UNITIV_END side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} end_bit={}", dec.debug_bitpos() ); } // 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-av1444d10: chroma PREDICTION units on the 32-capped tiled chroma /// walk (`decode_block_rect`'s `uw/uh = min(chroma, 32)` units) that were /// handed a STRICT sub-slice of their block's palette buffer -- i.e. the /// units of a block the 32-cap actually TILED (`nw * nh > 1`). /// /// CORRECTED 2026-09-30 after the refutation pass `lanes/refute-av1444d10` /// read the numbers back: the previous comment claimed it counted "the /// units that are NOT the block's top-left corner", which is not what the /// code did -- the hit was unconditional, so a block's corner unit fired it /// too AND a single-unit block (whose window is a pure re-stride copy of /// the whole buffer) fired it as well. That made a hit prove only that some /// palette chroma block existed, not that the tiled arm ran. The `bigger` /// guard now makes the counter discriminate. On the pinned fixture the /// measured value is unchanged at 4 (one block with nw = 1, nh = 2 x two /// planes x two unit rows); a stream whose palette chroma blocks are all /// single-unit now leaves it at zero. /// /// FURTHER CORRECTED the same day by the palette lane's refutation /// (`lanes/av1444palw.report.md` + the arm-isolated mutation): the guard is /// about TILING, not about `nw > 1` specifically. Isolating the two window /// sites shows the RECT-unit arm alone reds the 10-bit cell, and the /// SQUARE-unit arm alone reds the 12-bit cell *and* the 10-bit one -- so /// windowing is load-bearing for every tiled block, and `nw > 1` is merely /// the case the corpus could not reach. Do not read this counter as /// evidence that only the horizontal term matters. static CHROMA_PALETTE_WINDOW_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`CHROMA_PALETTE_WINDOW_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_palette_window_hits() -> usize { CHROMA_PALETTE_WINDOW_HITS.with(|c| c.get()) } /// Zeroes [`CHROMA_PALETTE_WINDOW_HITS`] so a gate can read it as a DELTA /// (it is process-wide, like every counter here). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_chroma_palette_window_hits() { CHROMA_PALETTE_WINDOW_HITS.with(|c| c.set(0)); } 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)); } thread_local! { /// lane-av1rectreach: units of `decode_rect_split`'s `chroma_tiled` walk /// whose PER-UNIT reach ([`tu_reach_rect`], libaom's per-unit /// `has_top_right` / `has_bottom_left`) DIFFERS from the block-level /// `reach` this walk used to hand every unit -- i.e. units for which the /// two answers are not interchangeable. This is what a gate needs before /// it compares the walk byte-exactly: if the two agreed everywhere, the /// substitution could not change a single predicted sample and the /// exactness assert would be measuring a witness the fix cannot touch. /// /// What it does NOT prove is that the argument handed to the unit reader /// is the per-unit one -- the count is taken from the same expression /// either way, so deleting the substitution reds the exactness assert /// rather than this counter. That is the right way round: the assert is /// the claim, this is only the floor under it. static RECT_TILED_CHROMA_UNIT_REACH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Chroma units of the same walk whose grid is exactly 2x1 (a 4:4:4 /// 64x32 chroma plane block as two 32x32 units). static RECT_TILED_CHROMA_2X1_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Chroma units of the same walk whose grid is exactly 1x2 (4:4:4 32x64, /// or 16x64 as two 16x32s). static RECT_TILED_CHROMA_1X2_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Chroma units of the same walk in any other multi-unit grid (2x2 and up /// -- only reachable at 4:2:2, which is refused, so this stays 0 on /// every admitted stream; kept so the match above is exhaustive). static RECT_TILED_CHROMA_NXN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current values of the four `RECT_TILED_CHROMA_*` counters, in the order /// `(unit_reach_differs, 2x1, 1x2, other multi-unit)`. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect_tiled_chroma_grid_hits() -> (usize, usize, usize, usize) { ( RECT_TILED_CHROMA_UNIT_REACH_HITS.with(|c| c.get()), RECT_TILED_CHROMA_2X1_HITS.with(|c| c.get()), RECT_TILED_CHROMA_1X2_HITS.with(|c| c.get()), RECT_TILED_CHROMA_NXN_HITS.with(|c| c.get()), ) } /// Zeroes the four `RECT_TILED_CHROMA_*` counters (gate tests call this /// before their own decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_rect_tiled_chroma_grid_hits() { RECT_TILED_CHROMA_UNIT_REACH_HITS.with(|c| c.set(0)); RECT_TILED_CHROMA_2X1_HITS.with(|c| c.set(0)); RECT_TILED_CHROMA_1X2_HITS.with(|c| c.set(0)); RECT_TILED_CHROMA_NXN_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()) } // lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose // `tx_depth` split the luma transform -- the arm that predicted DC off the // block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels // witness this path, so a gate that wants it needs the counter. thread_local! { static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1chromadc: chroma units of a skipped block whose intra-BC / /// UV-palette override had to be WINDOWED to the unit's own extent -- /// i.e. `cn_cols * cn_rows > 1`, which at 4:2:0 never happens (the chroma /// plane block is one 32x32 unit) and at 4:4:4 is every block of 64 and /// above. Counts UNITS, not blocks. EXCLUSIVE to this walk: the other two /// override sites (the luma slot and `decode_intrabc_owned_rect`) have /// their own windows. static SKIP_CHROMA_OVERRIDE_WINDOW_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks). pub fn skip_split_tx_override_hits() -> usize { SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get()) } /// lane-av1chromadc: [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn skip_chroma_override_window_hits() -> usize { SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.get()) } /// Zeroes [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`] before a gate's own decode. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn reset_skip_chroma_override_window_hits() { SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.set(0)); } /// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt. pub fn reset_skip_split_tx_override_hits() { SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0)); } // lane-svtinter: palette colour-index maps whose block is cut by the frame's // bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight` // really are smaller than the block and FEWER symbols are read than the // block has cells (class map-read-past-frame-edge). thread_local! { static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps). pub fn palette_onscreen_cut_hits() -> usize { PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get()) } /// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt. pub fn reset_palette_onscreen_cut_hits() { PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0)); } /// 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 /// lane-lossless2: one transform unit's window on a block-sized palette /// prediction buffer. A unit reads its prediction at ITS OWN stride, so /// handing it the whole-block buffer makes every unit reconstruct the block's /// top-left corner (the luma split-transform paths already window; the chroma /// ones did not, which is invisible until a lossless frame codes a palette /// block as 4x4 chroma units). fn palette_window( buf: &[u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, ) -> Vec { // `stride` is the BLOCK's own chroma width, so a caller that handed over a // mismatched stride could read in-bounds GARBAGE instead of panicking -- // a silent misread, which is the one failure mode this walk must not have. // The refutation pass (`lanes/refute-av1444d10.report.md`, risk (e)) named // that as the only thing keeping the tiled walk safe, so the invariant is // closed loudly here instead of resting on an `unsupported` return // elsewhere that a future shape could remove. assert!( w <= stride && ox + w <= stride && (oy + h) * stride <= buf.len(), "palette window {w}x{h} at ({ox},{oy}) does not fit a {}-entry buffer at stride {stride}", buf.len() ); (0..h) .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied()) .collect() } /// `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, } fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc { CflSrc { px, py, bw: side, bh: side, } } fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc { CflSrc { px, py, bw, bh } } /// 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 { /// The plane this unit belongs to (0 luma, 1 U, 2 V), carried from the /// reader that OWNS the unit. `dequant_and_inverse_wht4x4`'s `EC_DQCOEFF` /// twin prints it so its ladder pairs with the oracle's: the per-unit /// census plane could not, because the callers that route a lossless 4x4 /// unit into the WHT are not all the ones that stamp the census plane /// (measured on `ll444-lossless-key.obu`: 1663 of 1663 chroma units paired /// by count, 1660 of them against an empty grid). pub(crate) plane: usize, 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, /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected /// on the parse thread by [`block_iqmatrix`] and captured here so the /// recon worker scales identically without touching frame state. pub(crate) qm: Option, pub(crate) stride: usize, /// lane-lossless: this transform unit belongs to a lossless BLOCK (its /// segment's `xd->lossless[segment_id]` bit), so the residual comes off /// the 4x4 Walsh-Hadamard /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`). pub(crate) lossless: bool, } /// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed. /// The mixed-lossless witness's proof the per-segment lossless path really /// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront /// workers run this on their own threads. static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after /// delta around one decode. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn lossless_wht_units() -> usize { LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed) } /// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS /// transform unit that was itself NOT 4x4 -- a shape libaom cannot code. /// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a /// `coded_lossless` frame before it looks at the `tx_mode` symbol, /// `read_tx_size` (`:1117`) returns `TX_4X4` before it looks at a tree, /// `get_vartx_max_txsize` (`av1/common/blockd.h:1447`) returns `TX_4X4` for /// EVERY plane of a lossless block, and of `av1/common/idct.c`'s /// `highbd_inv_txfm_add_*_c` only `highbd_inv_txfm_add_4x4_c` carries a /// `lossless` branch -- every other size falls through to the IDCT, because /// there is no non-4x4 lossless inverse transform to dispatch to. So one of /// these is a CALLER sizing a lossless unit wrongly, not a bitstream shape; /// read as a before/after delta around one decode it names the caller. Must /// read 0 on a stream whose lossless unit geometry is right. Atomic: the /// wavefront workers run the transform on their own threads. static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// [`LOSSLESS_WHT_SPLIT_UNITS`] -- total over the process, read as a /// before/after delta around one decode. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn lossless_wht_split_units() -> usize { LOSSLESS_WHT_SPLIT_UNITS.load(std::sync::atomic::Ordering::Relaxed) } 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 = if self.lossless { LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); // lane-whtshape: a non-4x4 unit here is this decoder's own // transform-unit geometry being wrong (see // [`LOSSLESS_WHT_SPLIT_UNITS`] for the libaom evidence). It used // to be stopped by a `debug_assert_eq!` that RELEASE never ran: // the 4x4 WHT returned 16 values for a `w * h` block and the // release build died one frame later in the strided copy with an // opaque `range end index 8 out of range for slice of length 0` // that never named lossless or the transform. Counted, and // reconstructed as the raster of 4x4 WHT units // ([`crate::transform::dequant_and_inverse_wht`]) instead: total, // the same in both profiles, and the 4x4 fast path is the same // single call it always was. The old // `debug_assert_eq!(self.tx_type, TxType::DctDct)` is gone with // it: the WHT takes no tx_type (libaom's `av1_iwht4x4_add` does // not either), and `av1_get_tx_type` already answers `DCT_DCT` on // every plane of a lossless block, so asserting an argument // nothing reads was a debug-only panic on a value release // ignores. if self.w != 4 || self.h != 4 { LOSSLESS_WHT_SPLIT_UNITS.fetch_add( self.w.div_ceil(4) * self.h.div_ceil(4), std::sync::atomic::Ordering::Relaxed, ); } crate::transform::dequant_and_inverse_wht( grid, self.plane, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta, ) } else { 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, self.qm, ) }; // 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; } // lane-av1-422sub8rect: `h` rows of `stride` -- a rect unit whose // height exceeds its (narrow) prediction stride needs the full // stride * h; every square caller has h == stride and is unchanged. let mut strided = vec![0i32; self.stride * self.h]; 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 [`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, /// lane-av1wavefront: the sequence's chroma subsampling. The replay-side /// readers -- the deferred chroma builds' `mv_to_q4(.., ss_x(fctx))` /// positions and `exec_intra`'s CfL AC signal -- must see the FRAME's /// pair, not [`FrameCtx::new`]'s 4:2:0 default: on a 4:4:4 stream the /// default halved every worker's chroma reference position and lost the /// chroma planes (the 444_sb128rect witness, U 17504 / V 3 at PREFILT on /// frame 1) while every 4:2:0 gate stream stayed accidentally exact. subsampling: (u8, u8), 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 (sx, sy) = st.subsampling; fctx.subsampling_x.set(sx); fctx.subsampling_y.set(sy); 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), subsampling: ( fctx.subsampling_x.with(std::cell::Cell::get), fctx.subsampling_y.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 #[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)] #[track_caller] fn push_mc_rect( plane: usize, x: usize, y: usize, stride: usize, w: usize, h: usize, prediction: Pred<'_>, residual: &[i32], fctx: &crate::decode::FrameCtx, ) { // lane-av1ibcfork: the PUSH site of an MC/inter write. The executed rung // (`EC_MCWR`, in `reconstruct_mc_rect`) can only name the dispatch, so // this is what names the block decoder that asked for the write -- the // only thing that distinguishes two writes of the same shape. It is what // localized a 4:4:4 intra-BC SKIP block committing its chroma plane block // at `(px/2, py/2)` instead of the ss origin, clobbering a neighbouring // block's reconstruction (lanes/av1ibcfork.report.md). if crate::envflags::env_flag!("EC_MCPUSH") { eprintln!( "EC_MCPUSH plane={plane} x={x} y={y} stride={stride} w={w} h={h} \ res_len={} at {}", residual.len(), std::panic::Location::caller() ); } 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, ) { // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel // write, leaving the entropy parse and the per-mi neighbour bookkeeping // alone. It makes the encoder's own streams garbage, so it is a // MEASUREMENT rung only -- what it measures is how much of the encoder's // first decode of its own tiles (`par::S_FIRST`) is reconstruction and // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that // stage and the parse plus the neighbour grids are the other 94%. That // is why handing the decoder the encoder's own reconstruction cannot // shrink the stage: only publishing the per-mi neighbour state the // filters read (and so never parsing at all) can. if crate::envflags::env_flag!("EC_AV1_NORECON") { return; } 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 = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx)); (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, }; // lane-av1cmpaudit: label the in-flight reconstruction's plane for the // `EC_PRED` rung (aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`). // Saved and restored so the rung reports THIS call's plane even under // nesting, and so both of exec_intra's return paths need no cleanup. let prev_plane = RECON_PLANE.with(|c| c.replace(plane)); let _plane_guard = PlaneGuard(prev_plane); 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, plane, 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 read `use_intrabc == 1` and took the DV path -- the /// gate's hit counter. Bumped on the READ, before the rect-strip refusal /// returns too, so it counts reads, not reconstructions (a refused block /// is never reconstructed). 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) }; } thread_local! { /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy + /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity /// counter: zero means the gate's fixture no longer reaches the route). static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize { INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get()) } /// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() { INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(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()) } thread_local! { /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no /// chroma coefficient at all, so the slot used to stay armed into the NEXT /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count /// here. A non-zero value is what makes the disarm below load-bearing. static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize { SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get()) } /// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a /// decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() { SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0)); } thread_local! { /// lane-av1-ibcskip2: a sub-8x8 4:4:4 leaf that is BOTH intrabc AND /// `skip` -- the arm whose chroma is the bare frame copy at the DV /// (libaom `av1_build_inter_predictors_sb` runs regardless of `skip`). /// Before the fix this route predicted intra-DC and every one of this /// fixture's 150 such cells differed from the oracle on both chroma /// planes. static SKIPPED_INTRABC_DV_COPY_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`SKIPPED_INTRABC_DV_COPY_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn skipped_intrabc_dv_copy_hits() -> usize { SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.get()) } /// Zeroes [`SKIPPED_INTRABC_DV_COPY_HITS`] (gate tests call this before a /// decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_skipped_intrabc_dv_copy_hits() { SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.set(0)); } /// 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) }; /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf /// sizes (not one square size across every leaf) -- the engagement /// counter proving a witness actually exercises the per-leaf reconstruct. static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf -- /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no /// symbol here desynced `warped.obu` at the very next block. static RECT_INTRABC_VARTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never /// this one). static INTRABC_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT). static INTRABC_RECT_VARTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read), /// split by the strip's orientation -- `bw > bh` is a HORZ strip, /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS` /// counts neither orientation nor the skip flag, so an arm that flipped /// to an all-skip stream (no residual reader at all) would stay green. static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0, 0]) }; /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`] /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split /// by orientation. The r5 panic (residual stride `bw * bh` underrunning /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was /// invisible to every gate because they only counted CODED strips. static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0, 0]) }; /// lane-ibc444c: rect intra-BC blocks whose chroma plane block was sized /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h) applies no /// halving of its own. At 4:2:0 this is the same arithmetic as the halving, /// so a `>= 1` witness can only come from a stream that is not 4:2:0. /// EXCLUSIVE to this arm: no other caller sizes an intrabc rect block's /// chroma plane block. static IBC_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-whtshape: LOSSLESS rect intrabc blocks whose chroma plane block /// [`decode_intrabc_rect`] walked as a `(cw/4) * (ch/4)` PLANE-MAJOR /// raster of TX_4X4 units -- the shape libaom's lossless geometry codes /// (`read_tx_size` returns `TX_4X4` for EVERY plane of a lossless block, /// `get_vartx_max_txsize` likewise, and `read_tx_mode` forced the frame's /// `ONLY_4X4`) -- instead of the single rect unit, which is what put a /// non-4x4 unit on the lossless Walsh-Hadamard path. EXCLUSIVE to this arm: /// no other caller walks a rect intrabc block's chroma, so `>= 1` cannot /// be satisfied by any older route. static INTRABC_RECT_LOSSLESS_CHROMA4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips /// ([`decode_intrabc_owned_rect`]) whose chroma plane block was sized /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h:1372) applies /// no halving of its own. At 4:2:0 the two forms are the same arithmetic, /// so a `>= 1` witness can only come from a stream that is not 4:2:0. /// EXCLUSIVE to this arm: no other caller sizes a 128-root intra-BC /// strip's chroma plane block. static IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed, /// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn intrabc_rect_coded_hits() -> [usize; 2] { INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get) } /// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks /// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn intrabc_rect_skipped_hits() -> [usize; 2] { INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get) } /// Current value of [`INTRABC_RECT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn intrabc_rect_hits() -> usize { INTRABC_RECT_HITS.with(|c| c.get()) } /// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_rect_hits() { INTRABC_RECT_HITS.with(|c| c.set(0)); INTRABC_RECT_VARTX_HITS.with(|c| c.set(0)); INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0])); INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0])); } /// lane-ibc444c: [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn ibc_rect_chroma_footprint_444_hits() -> usize { IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get()) } /// lane-ibc444c: zeroes [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_ibc_rect_chroma_footprint_444_hits() { IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0)); } /// lane-av1chromarect: [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize { IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get()) } /// lane-av1chromarect: zeroes [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_ibc_owned_rect_chroma_footprint_444_hits() { IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0)); } /// lane-whtshape: [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn intrabc_rect_lossless_chroma4_hits() -> usize { INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.get()) } /// lane-whtshape: zeroes [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_rect_lossless_chroma4_hits() { INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.set(0)); } /// Current value of [`INTRABC_RECT_VARTX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn intrabc_rect_vartx_hits() -> usize { INTRABC_RECT_VARTX_HITS.with(|c| c.get()) } thread_local! { /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to /// guard (`decode_block_128rect`). A refused block bumps /// [`INTRABC_HITS`] but never this one. static INTRABC_128RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call. /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 / /// side` model walked the 4:2:0 count on every axis, so this counter is /// the reach/arm witness for the per-axis walk. static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes. static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRABC_128RECT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn intrabc_128rect_hits() -> usize { INTRABC_128RECT_HITS.with(|c| c.get()) } /// Zeroes [`INTRABC_128RECT_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_128rect_hits() { INTRABC_128RECT_HITS.with(|c| c.set(0)); } /// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn intrabc_128rect_chroma_chunk_hits() -> usize { INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get()) } /// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn intrabc_128rect_chunk_shape() -> usize { INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get()) } /// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and /// [`INTRABC_128RECT_CHUNK_SHAPE`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() { INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0)); INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0)); } /// Current value of [`INTRABC_VARTX_HITS`]. pub fn intrabc_vartx_hits() -> usize { INTRABC_VARTX_HITS.with(|c| c.get()) } /// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`]. pub fn intrabc_vartx_mixed_leaves_hits() -> usize { INTRABC_VARTX_MIXED_LEAVES_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)); } /// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a /// decode). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() { INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0)); } /// Current value of [`RECT_INTRABC_VARTX_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn rect_intrabc_vartx_hits() -> usize { RECT_INTRABC_VARTX_HITS.with(|c| c.get()) } /// 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)>, n: &mut Neighbours, fctx: &crate::decode::FrameCtx, ) { record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx); } /// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs` /// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4` /// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr). /// /// Also stamps libaom's `is_inter_block` verdict for this block into the /// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override /// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] > /// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and /// `get_tx_size_context` reads its BLOCK size rather than its transform band. /// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which /// every block runs; this runs after it (class leaked-band otherwise). fn record_intrabc_mi_rect( mi_r: usize, mi_c: usize, n4_w: usize, n4_h: usize, dv: Option<(i32, i32)>, n: &mut Neighbours, fctx: &crate::decode::FrameCtx, ) { if dv.is_some() { for i in 0..n4_w { if let Some(cell) = n.above_inter.get_mut(mi_c + i) { *cell = true; } } for i in 0..n4_h { if let Some(cell) = n.left_inter.get_mut(mi_r + i) { *cell = true; } } // lane-av1txctxband: the per-CELL `is_inter_block` an INTRABC block // publishes (`blockd.h:372-374` counts it), at the granularity // `get_tx_size_context` reads it. The band above is one slot per // column and so survives every later block in that column. n.mark_inter_grid_rect((mi_r, mi_c), n4_w, n4_h, true); } 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_w as u8, size_h: n4_h as u8, }; for r in mi_r..mi_r + n4_h { for c in mi_c..mi_c + n4_w { 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`]. // lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped // motion firing ABOVE the vertical midpoint, and every pre-existing warp // counter is frame-global. These two are the same arms restricted to blocks // whose top mode-info row is in the frame's upper half, which is the half // this lane's evidence covers. thread_local! { static TOP_HALF_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static TOP_HALF_WARP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's /// upper half -- the block's top mode-info row is under `mi_rows / 2`. /// /// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal /// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the /// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream. /// The figure quoted for that fixture comes from a patch-run-restore build /// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which /// is the same discipline every 4:2:2 lane in this family uses. #[allow(dead_code)] pub(crate) fn top_half_compound_hits() -> usize { TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get) } /// How many inter blocks in the frame's upper half satisfy libaom's /// `is_global_mv_block` on at least one reference slot -- mode /// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion /// model > `TRANSLATION`. This is the block set whose prediction goes /// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1` /// as computed at the increment site; it is NOT merely "some slot has a /// non-TRANSLATION model", which also counts blocks that are not global-mv /// blocks. /// /// Like [`top_half_compound_hits`], no committed test reads it: with the /// 4:2:2 header refusal in force nothing in the suite decodes the stream /// these numbers describe. #[allow(dead_code)] pub(crate) fn top_half_warp_hits() -> usize { TOP_HALF_WARP_HITS.with(std::cell::Cell::get) } 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-av1distwtd: how many blocks took the DISTANCE-WEIGHTED compound // combine rather than the simple average -- `compound_idx == 0` under // `enable_jnt_comp`, whose weights come from // [`crate::compound::dist_wtd_comp_weight_assign`] instead of the constant // `(8, 8)` split. Counting the `idx == 0` arm (not merely the // `compound_idx` symbol read) is what makes this a witness of the TOOL: a // stream that carries `enable_jnt_comp = true` in its sequence header but // codes every compound block with `compound_idx == 1` leaves this at 0 and // decoded identically without the whole distance-weight path. thread_local! { static DIST_WTD_COMP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`DIST_WTD_COMP_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn dist_wtd_comp_hits() -> usize { DIST_WTD_COMP_HITS.with(|c| c.get()) } /// Resets [`DIST_WTD_COMP_HITS`] to 0. #[allow(dead_code)] // test-only pub(crate) fn reset_dist_wtd_comp_hits() { DIST_WTD_COMP_HITS.with(|c| c.set(0)); } // lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference // prediction through `crate::warp::global_warp_params` with a FOUR-parameter // (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM // (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref // global-warp arm a real aomenc stream can reach (AFFINE needs the widened // side build and its own counter, [`AFFINE_GM_HITS`]). thread_local! { static ROTZOOM_GM_WARP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`ROTZOOM_GM_WARP_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rotzoom_gm_warp_hits() -> usize { ROTZOOM_GM_WARP_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! { /// lane-av1ibc128arm: how many 64x64 mu-chunk CHROMA units the /// intra-in-inter 128x128 root read (`decode_inter_block`'s /// `side > 64` mu-chunk arm, the INTRA half of the inter pair). Every /// unit is one `read_plane` on U and one on V, so the counter is the /// gate's proof the arm ran at all -- no committed 4:4:4 fixture /// reached it before this lane. pub(crate) static INTRA_128_IN_INTER_MU_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRA_128_IN_INTER_MU_CHROMA_HITS`], for a gate's /// before/after delta. pub fn intra_128_in_inter_mu_chroma_hits() -> usize { INTRA_128_IN_INTER_MU_CHROMA_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-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid // approximation would have resolved off a DIFFERENT CDF row than the real // `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY // frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block" // tally is green on the old code too (class gate-blind-to-feature). thread_local! { static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`]. #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live pub(crate) fn txctx_deblock_divergence_hits() -> usize { TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get) } // lane-av1txctxband: how many `get_tx_size_context` reads the per-CELL // `is_inter_block` cover and the per-COLUMN `above_inter`/`left_inter` bands // DISAGREE about -- i.e. exactly the reads whose CDF row the old code chose // wrongly. Green on the old code too (a plain "some block was inter" tally // would be), so this is the non-vacuity arm of the witness gate: it is 0 on // every stream where the bands happened to be right and non-zero on the // 4:4:4 lossy `--sb-size=128` cq-62 stream whose entropy forked at read 32813 // on the 8x4 intra leaf at mi(57,52). thread_local! { static TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gate pub(crate) fn txctx_inter_cell_band_divergence_hits() -> usize { TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS.with(std::cell::Cell::get) } /// Zeroes [`TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gate pub(crate) fn reset_txctx_inter_cell_band_divergence_hits() { TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS.with(|c| c.set(0)); } // 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-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma // coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's // (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference` // (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair // exists there; the counter keeps a 4:4:4 1:4-strip gate from passing // vacuously (a 4:2:0 stream of the same content leaves it at 0). It proves // REACH only, never that the fix bites -- that is the gate's byte compare and // its mutation, not this count (skill://ec-av1-pipeline-gate-counters). thread_local! { static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn rect4_inter_own_chroma444_hits() -> usize { RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get) } /// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_rect4_inter_own_chroma444_hits() { RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0)); } // lane-av1444rect r2: how many intra-BC 1:4 strips at `ss (0,0)` took the // own-chroma arm of [`decode_rect4_16_intrabc`]'s `own444`. A 4:2:0 / 4:2:2 // stream of the same recipe leaves it at 0, which is what makes it the // 4:4:4-only route. // // WHAT THIS COUNTER IS NOT: it is NOT evidence that the fix bites, and it // never was. A route counter fires identically before and after a change that // changes nothing downstream, so a non-zero count proves REACH and nothing // more. On this lane it is also armed deliberately OUTSIDE the `own444` // expression, so that the mutation (`own444 = false`) still increments it and // the red comes from the pixel/entropy arm instead. The evidence that the ss // gate bites is the measured fork move -- first entropy fork read 11750 -> // 12465, luma first wrong sample 164416 -> 205264, 455240 -> 390380 total -- // not this count. See skill://ec-av1-pipeline-gate-counters: a counter needs // a DIFFERS-style assertion to carry a claim. thread_local! { static INTRABC_RECT4_OWN_CHROMA444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // lane-av1422luma: the ss (1,0) twin of `INTRABC_RECT4_OWN_CHROMA444_HITS` // -- how many intra-BC 1:4 strips at 4:2:2 took the own-chroma (no pair) // route. Same caveat as the 4:4:4 counter: it proves REACH and nothing else, // and 4:2:2 is refused at the sequence header, so no committed test can read // it (the count in `lanes/av1422luma.report.md` is from a bypassed probe build). thread_local! { static INTRABC_RECT4_OWN_CHROMA422_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`INTRABC_RECT4_OWN_CHROMA422_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intrabc_rect4_own_chroma422_hits() -> usize { INTRABC_RECT4_OWN_CHROMA422_HITS.with(std::cell::Cell::get) } /// Resets [`INTRABC_RECT4_OWN_CHROMA422_HITS`] before a decode. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_rect4_own_chroma422_hits() { INTRABC_RECT4_OWN_CHROMA422_HITS.with(|c| c.set(0)); } /// Current value of [`INTRABC_RECT4_OWN_CHROMA444_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn intrabc_rect4_own_chroma444_hits() -> usize { INTRABC_RECT4_OWN_CHROMA444_HITS.with(std::cell::Cell::get) } /// Resets [`INTRABC_RECT4_OWN_CHROMA444_HITS`] before a decode. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn reset_intrabc_rect4_own_chroma444_hits() { INTRABC_RECT4_OWN_CHROMA444_HITS.with(|c| c.set(0)); } // 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-av1leftref: how many chroma intra-edge filter-type reads land on a // left neighbour whose `uv_mode` at libaom's real read cell // (`base_mi[ss_y * mi_stride - 1]` = row `+ss_y`, col `-1`) DIFFERS from the // cell this decoder used to read (its own mi row). Two buckets: the raw mode // value moved, and `is_smooth_mode` -- the boolean the read actually feeds -- // flipped. The second is the one that can move pixels. thread_local! { static UV_LEFT_SS_Y_MODE_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static UV_LEFT_SS_Y_SMOOTH_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { static UV_LEFT_SS_Y_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`UV_LEFT_SS_Y_READS`]. pub fn uv_left_ss_y_reads() -> usize { UV_LEFT_SS_Y_READS.with(|c| c.get()) } /// Current value of [`UV_LEFT_SS_Y_MODE_DIFF_HITS`]. pub fn uv_left_ss_y_mode_diff_hits() -> usize { UV_LEFT_SS_Y_MODE_DIFF_HITS.with(|c| c.get()) } /// Current value of [`UV_LEFT_SS_Y_SMOOTH_DIFF_HITS`]. pub fn uv_left_ss_y_smooth_diff_hits() -> usize { UV_LEFT_SS_Y_SMOOTH_DIFF_HITS.with(|c| c.get()) } // lane-av1leftwit: decode-path chroma edge-filter-type reads at `ss_y > 0` // whose left-neighbour COLUMN holds a run of length 1 -- the cell this // decoder reads (its own mi row) and the cell libaom reads (one row down) // were written by two DIFFERENT blocks, i.e. the left neighbour is at most // 1 mi tall. That is the only geometry in which the `+ss_y` term can change // the answer at all; `UV_LEFT_SS_Y_READS` alone proves nothing about it. thread_local! { static UV_LEFT_1MI_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Current value of [`UV_LEFT_1MI_SPLIT_HITS`]. pub fn uv_left_1mi_split_hits() -> usize { UV_LEFT_1MI_SPLIT_HITS.with(|c| c.get()) } // lane-av1leftwit: the per-tile epoch `uv_owner` cells are stamped with. // Bumped in `Neighbours::start_tile`; never read by decode logic. thread_local! { static UV_OWNER_EPOCH: std::cell::Cell = const { std::cell::Cell::new(0) }; } // 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) }; } // lane-av1cfl: which `cfl_ac_ss` arm ran, one bump per CfL block. The 4:4:4 // arm is libaom `cfl_luma_subsampling_444_lbd_c` (1x1 luma per chroma sample) // and the 4:2:2 arm is `cfl_luma_subsampling_422_lbd_c`; only the last two // reach `cfl_ac_q3_at`'s 2x2 average, so these four are the reachability // evidence for that function's format-blind extent. thread_local! { static CFL_AC_444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static CFL_AC_422_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static CFL_AC_420_SQ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static CFL_AC_420_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static CFL_AC_Q3_AT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// `[4:4:4, 4:2:2, 4:2:0 square, 4:2:0 rect]` [`cfl_ac_ss`] arm hits. pub fn cfl_ac_arm_hits() -> [usize; 4] { [ CFL_AC_444_HITS.with(|c| c.get()), CFL_AC_422_HITS.with(|c| c.get()), CFL_AC_420_SQ_HITS.with(|c| c.get()), CFL_AC_420_RECT_HITS.with(|c| c.get()), ] } /// Entries into [`cfl_ac_q3_at`] itself -- the one arm whose extent is /// `bw / 2, bh / 2` and whose footprint is a 2x2 luma average. The gate /// proves it is reached ONLY at 4:2:0. pub fn cfl_ac_q3_at_hits() -> usize { CFL_AC_Q3_AT_HITS.with(|c| c.get()) } /// 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-arfchroma: chroma transform-unit publications whose block started // MID-CELL -- the condition `record_mi_chroma`'s origin alignment exists for. // A 4x4 chroma unit is `1 << ss` luma mi per axis, so a block whose mi origin // is not step-aligned (a 16x4 / 4x16 1:4 strip at 4:2:0 has an ODD mi row or // column) publishes a context cell whose origin is the step-aligned mi BELOW // or RIGHT of its own. Counted per publication, `[row_misaligned, // col_misaligned, both]`, so a gate can prove the witness really walks the // realigned path instead of passing on a stream whose chroma units all happen // to start on a cell boundary. thread_local! { static CHROMA_MIDCELL_PUB_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; } /// ChROMA publications that started mid-cell: `[row, col, both]`. See /// [`CHROMA_MIDCELL_PUB_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn chroma_midcell_pub_hits() -> [usize; 3] { CHROMA_MIDCELL_PUB_HITS.with(std::cell::Cell::get) } /// Zeroes [`CHROMA_MIDCELL_PUB_HITS`] so a gate can measure its own decode. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub fn reset_chroma_midcell_pub_hits() { CHROMA_MIDCELL_PUB_HITS.with(|c| c.set([0; 3])); } // 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-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s. static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip. static RECT4_16_INTRABC_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) }; /// lane-av1-loss64: chroma transform units the frame-edge clip skipped /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless /// block overhanging the frame does NOT code. static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`, /// decodeframe.c:1262) instead of leaking the previous occupant's. static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the /// hardcoded 4:2:0 span mis-stepped). static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma /// coefficients a lossless frame walked as per-4x4 inter units (the walk /// that replaced the single rect unit). static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units. static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1loss444kf: 4:4:4 lossless sub-8x8 RECT (8x4 / 4x8) leaf chroma /// units whose libaom-faithful block-relative reach /// ([`Reach::of_tu`] over the leaf's own bsize) differs from the /// standalone-BLOCK_4X4 lookup that used to answer for them. Zero means /// no stream reached a rect leaf where the two disagree -- a gate /// asserting the reach fix must see this nonzero, or the fixture never /// exercised the fixed path. static SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1offtile: 4x4 chroma units a lossless HORZ/VERT strip's plane- /// major walk skipped because their top-left sample falls outside the /// CHROMA plane. libaom bounds that walk per plane (`max_block_wide/high`, /// av1_common_int.h:1565); this walk used to count the block's own /// `chroma_w / 4` x `chroma_h / 4`. Zero means no stream decoded a /// lossless strip overhanging the frame edge -- a gate asserting the /// clip must see this nonzero. static RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_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 chroma transform units the frame-edge clip skipped in /// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a /// stream whose lossless blocks never overhang the frame -- a gate asserting /// the clip fired must see this nonzero. pub fn chroma_edge_tu_clip_hits() -> usize { CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get()) } /// How many skipped lossless intrabc rect strips had their luma entropy /// bands zeroed per unit (lane-av1-loss64). pub fn skip_lossless_band_reset_hits() -> usize { SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get()) } /// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at /// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the /// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix /// must see this nonzero. pub fn rect_split_lossless_chroma444_hits() -> usize { RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get()) } /// How many 4x4 chroma units a lossless HORZ/VERT strip's plane-major walk /// skipped for falling outside the chroma plane (lane-av1offtile). Zero means /// no stream decoded a lossless strip overhanging the frame edge -- a gate /// asserting the clip must see this nonzero. pub fn rect_split_lossless_chroma_offtile_hits() -> usize { RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS.with(|c| c.get()) } /// Reset [`rect_split_lossless_chroma_offtile_hits`] to zero (lane-av1offtile). pub fn reset_rect_split_lossless_chroma_offtile_hits() { RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS.with(|c| c.set(0)); } /// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as /// per-4x4 inter units (lane-av1-ibc444rect). pub fn intrabc_rect8_lossless_luma_hits() -> usize { INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get()) } /// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked /// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect). pub fn intrabc_rect8_lossless_chroma_hits() -> usize { INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get()) } /// How many 4:4:4 lossless sub-8x8 RECT leaf chroma units took the /// block-relative reach libaom's `has_bottom_left` gives, where the /// standalone-BLOCK_4X4 lookup that used to answer disagreed /// (lane-av1loss444kf). Zero on a stream with no such leaf. pub fn sub8_chroma444_lossless_tu_reach_hits() -> usize { SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.get()) } /// Gate-side reset for [`SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS`]. pub fn reset_sub8_chroma444_tu_reach_hits() { SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.set(0)); } /// Gate-side reset for the two lane-av1-ibc444rect counters above. pub fn reset_ibc444rect_hits() { INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0)); INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0)); } /// Gate-side reset for the two lane-av1-loss64 counters above. pub fn reset_loss64_hits() { CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0)); SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0)); } /// 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()) } /// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane. pub fn rect4_16_lossless_chroma_hits() -> usize { RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get()) } /// How many 16x4/4x16 strips reconstructed as intra block copy. pub fn rect4_16_intrabc_hits() -> usize { RECT4_16_INTRABC_HITS.with(|c| c.get()) } /// Zero the lane-av1-rect14 pair counters so a gate measures one stream. pub fn reset_rect4_16_pair_hits() { RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0)); RECT4_16_INTRABC_HITS.with(|c| c.set(0)); } // 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)] // reader is test-only (the 12-bit compound witness); dead in non-test builds 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); } } // Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V). // lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and // without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a // per-plane prediction cannot be read off ours -- a luma/chroma disagreement // looked identical to a same-plane disagreement. Set by `exec_intra` (the // single place a `PlaneBuf::reconstruct{,_rect}` is reached from) and read only // by the `EC_PRED` rung, so it cannot change a decode. thread_local! { static RECON_PLANE: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The plane index the `EC_PRED` rung prints as `plane=`. fn recon_plane() -> usize { RECON_PLANE.with(std::cell::Cell::get) } /// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on /// either of its two early returns. struct PlaneGuard(usize); impl Drop for PlaneGuard { fn drop(&mut self) { RECON_PLANE.with(|c| c.set(self.0)); } } 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, ...). pub(crate) 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)] pub(crate) enum TxClass { TwoD, Horiz, Vert, } impl TxClass { pub(crate) 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. pub(crate) 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), } } /// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide /// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it /// (class `table-and-reader-move-together` -- the writer picks its symbol /// through the reader's own map, so the two cannot drift). pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option { (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type)) } /// 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 { // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39 // masks the level with `0xFFFFF`, so no conformant stream carries a longer // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_ // stream_can_carry` enumerates that whole value domain. // // So this refusal never names a reader gap: it is always the SYMPTOM of an // earlier desync (class `refusal-hides-a-defect`), and every historical // instance was closed by fixing that desync -- lane-dgolomb's // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`. // Raising the cap only trades a clean refusal for silent corruption: // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact` // from a refusal into a frame-0 LUMA MISMATCH. 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}"); } crate::msac::SymbolDecoder::set_symr_cdf("eob_pt"); 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}"); } // lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`. #[track_caller] 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; // lane-av1readcensus: this unit's own entry state, so the census line // carries the pre-read rng and pairs against the oracle's `EC_COEFF` // (which prints `r->ec.rng` before the same `txb_skip` read). let census_entry_rng = dec.debug_state().0; let (census_w, census_h) = rect_shape.unwrap_or((side, side)); // lane-av1ibcfork: the per-unit BIT INTERVAL, the twin of the oracle's // `EC_ECDUMP_IN` / `_OUT` / `_END`. The census plane, not a fresh label: // it is the same source `census_unit` reads, so the interval line and the // census line can never disagree about which plane a unit is on. let iv_plane = CENSUS_PLANE.with(|c| c.get()).min(2); let iv_bit = unit_iv_in(iv_plane, census_w, census_h, skip_ctx, dec); 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}"); } if crate::envflags::env_flag!("EC_ECDUMP_IN") { let (range, value) = dec.debug_state(); let bit = dec.debug_bitpos(); eprintln!( "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})" ); } let dbg_txbskip = if coeff_trace_on() { coding.txb_skip[skip_ctx] } else { [0; 3] }; let sq_bit = if coeff_trace_on() { dec.debug_bitpos() } else { 0 }; let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; unit_iv_skip( dec, iv_bit, iv_plane, census_w, census_h, skip_ctx, all_zero, ); // lane-ibc444c: this reader logs an `all_zero` step even for a read that // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" -- // filter on it before pairing anything against the oracle. if crate::envflags::env_flag!("EC_IBCTX") { eprintln!( "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}", coding.side, std::panic::Location::caller(), ); } if coeff_trace_on() { let (rng, _) = dec.debug_state(); eprintln!( "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng} bit={sq_bit} post_bit={}", coding.side, all_zero as i32, dec.debug_bitpos() ); } 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. census_unit( census_w, census_h, TxType::DctDct, 0, true, census_entry_rng, dec, ); unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx); 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:?}"); } crate::msac::SymbolDecoder::set_symr_cdf("tx_type"); let t = dec.symbol(tx_type_cdf); crate::census::tx_type(len, t); 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 }; } census_unit( census_w, census_h, tx_type, eob, false, census_entry_rng, dec, ); unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx); 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. // lane-ibc444c: `#[track_caller]` so the EC_IBCTX rung below names the CALLER // of this reader -- the only thing that identifies a unit's route. No plane is // printed here: the plane is the ORACLE's side of the pairing, and a label // here is one more thing that can disagree with it. #[track_caller] 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, // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) -- // printed by the two `EC_COEFF_STEP` traces below, which hardcoded // `plane=0` and so mis-attributed a CHROMA read as a luma one in two // independent lane reports. plane: usize, ) -> Result<(Grid, TxType)> { let rect_trace = coeff_trace_on(); let entry_rng = dec.debug_state().0; // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census // plane itself rather than inheriting whichever reader did last. The // luma-only readers (`decode_rect_split`, `decode_block_rect64`, // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial // value -- and the other plane-owning readers stamp on entry. set_census_plane(plane); let ibctx_on = crate::envflags::env_flag!("EC_IBCTX"); let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 }; let iv_bit = unit_iv_in(plane, w, h, skip_ctx, dec); let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; unit_iv_skip(dec, iv_bit, plane, w, h, skip_ctx, all_zero); if rect_trace { eprintln!( "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}", all_zero as i32, dec.debug_state().0, dec.debug_bitpos() ); } if ibctx_on { // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder // range: the only collision-free key for pairing this unit against the // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells // a real symbol read from a 0-bit one -- the SQUARE reader logs a step // either way, which is exactly the artifact that made an earlier // round of this lane claim a false exactness. eprintln!( "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}", dec.debug_bitpos(), std::panic::Location::caller(), ); } if all_zero { census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec); unit_iv_end(dec, plane, w, h, skip_ctx); 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); crate::census::tx_type(len, t); 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={plane} 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); if !(w.is_power_of_two() && n <= 36 * 36) { panic!("rect coeff scratch w={w} h={h} n={n}"); } 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; // lane-av1oddheightfork2: the `base_eob` rung moved to the end of // the loop body (below). libaom prints its `tag=base_eob` AFTER // that coefficient's own br loop (decodetxb.c:317-338), so the rung // has to carry the POST-br level and rng to be the oracle's twin; // printed here it labelled the pre-br read and every rect unit's // ladder disagreed with aomdec by exactly its br tail. 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 && scan_idx == eob - 1 { // the oracle's `tag=base_eob`: POST-br level, POST-br rng, with the // same `get_lower_levels_ctx_eob` ctx (the same `eob_coeff_ctx`). let ctx = eob_coeff_ctx(scan_idx, w * h); let (rng, _) = dec.debug_state(); eprintln!( "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} 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 }; if rect_trace { // lane-av1oddheightfork2: the twin of the square reader's // `coeff_step_post_golomb`. The oracle's `EC_COEFF_STEP // tag=post_golomb` (decodetxb.c, after read_golomb) fires for a RECT // unit exactly as it does for a square one, but this reader had no // rung for it, so every rect unit's ladder was one step short and // the pairing had to guess whether a golomb had been read. This // rung reads no bits: it prints the state after the read it labels. let (rng, _) = dec.debug_state(); eprintln!( "EC_COEFF_STEP tag=post_golomb c={} pos={pos} level={level} rng={rng}", (packed >> 4) ); } grid[pos] = if negative { -level } else { level }; } // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose // grids differ is a reader defect, one whose grids agree is a transform // defect. if crate::envflags::env_flag!("EC_DQCOEFF") { let nz: Vec = grid .iter() .enumerate() .filter(|&(_, &v)| v != 0) .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w)) .collect(); eprintln!( "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}", nz.join(",") ); } census_unit(w, h, tx_type, eob, false, entry_rng, dec); unit_iv_end(dec, plane, w, h, skip_ctx); Ok((Grid::Own(grid), tx_type)) } /// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the /// [`read_plane`] family already has. /// /// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop /// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a /// chroma plane: no u/v coefficient symbol is coded, and consuming one moves /// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`] /// enforces that for every strip that reads its chroma through it, but the rect /// strip paths ([`decode_block_rect`], [`decode_leaf_rect`], /// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`]) /// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes /// this gate instead (class `reader-gate-not-on-every-path`). One un-gated /// chroma read desyncs at the FIRST rect leaf of the frame and every later /// symbol -- and therefore every later pixel -- is decoded from the wrong /// place, without ever tripping a refusal (the desynced values stay inside /// every coded alphabet). fn read_chroma_coeffs_rect( dec: &mut SymbolDecoder, coding: &mut TxbTables, scan: &[u16], w: usize, h: usize, skip_ctx: usize, sign_ctx: usize, default_tx_type: TxType, fctx: &crate::decode::FrameCtx, // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a // V-plane read was indistinguishable from a luma one in the log). plane: usize, ) -> Result<(Grid, TxType)> { if mono(fctx) { return Ok((Grid::Zero(w * h), TxType::DctDct)); } read_coeffs_rect( dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type, plane, ) } /// 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, /// lane-av1leftwit: which BLOCK wrote each cell of [`Self::uv_mode_grid`], /// as `(epoch << 24) | (mi_r << 12) | mi_c` of the writing block's own /// top-left mi. The `uv_mode` value alone cannot answer "are the two cells /// the `+ss_y` read compares written by the same block?", which is the /// whole question the `+ss_y` term turns on: the term is only observable /// when the left neighbour is 1 mi tall, i.e. when the cell this decoder /// used to read and the cell libaom reads hold DIFFERENT blocks. `epoch` /// is [`UV_OWNER_EPOCH`], bumped once per tile, so a cell no block wrote /// in this tile can never be mistaken for a written one. uv_owner: Vec, /// 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 `is_inter_block` of the coded block COVERING that cell -- /// lane-av1txctxband. libaom's `get_tx_size_context` /// (`av1/common/pred_common.h:361-370`) gates its "an inter neighbour /// contributes its own BLOCK size" override on `xd->above_mbmi` / /// `xd->left_mbmi`, which `set_mi_offsets` takes as `xd->mi[-mi_stride]` /// / `xd->mi[-1]`: the block whose bottom (left) edge abuts THIS block's /// top (right) edge at THIS cell. `setup_mbs` (`decodeframe.c:355-361`) /// writes that pointer into EVERY mi cell a block covers, so libaom's /// granularity is the covering block PER CELL -- not one slot per column. /// [`Self::above_inter`]/[`Self::left_inter`] are per-COLUMN bands holding /// the LAST block written in that column, which is the covering block only /// for the block immediately below it: on a 4:4:4 lossy `--sb-size=128` /// cq-62 stream the 8x4 intra leaf at mi(57,52) read `above_inter` as /// `true` (stale, from an intrabc block earlier in column 52) with /// `above_side_mi` 4, took the override, and read `tx_size_cat0[1]` where /// libaom reads row 2 -- the `EC_SYMR` fork at read 32813. /// Written by exactly the three places that already write the bands: /// [`Self::record_inter_rect_mi`], `record_intrabc_mi_rect` and /// `fill_lf_grid_rect`'s intra-only clear. inter_grid: Vec, /// 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), uv_owner: vec![0; cols * (SUB / MI) * rows * (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), inter_grid: vec![false; cols * (SUB / MI) * rows * (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))); // lane-av1leftwit: a fresh epoch stamps every `uv_owner` cell this // tile writes, so the `+ss_y` read's "different block?" probe never // compares against a cell a previous tile left behind. UV_OWNER_EPOCH.with(|c| c.set(c.get().wrapping_add(1) | (1 << 24))); 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 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. /// /// The extent is the block's own CHROMA footprint, `w_mi * MI >> ss_x` per /// axis -- `av1_setup_dst_planes`'s `get_plane_block_size(bsize, ss_x, /// ss_y)` (`common_data.c:38`, which at ss (0,0) is BLOCK_128X128 /// itself, so 128 and not 64). This used to be a hardcoded `w_mi * MI / 2`, /// correct at 4:2:0 by the `>> 1 == / 2` identity and half the truth at /// 4:4:4; lane-av1txsizeaudit r2 replaced it with the per-axis shift, the /// form its sibling `fill_lf_grid_rect` already used. The `fctx` is /// threaded in for it: `Neighbours` carries no subsampling of its own, so /// no format guard was possible inside this method until now. /// /// **MEASURED INERT, and do not go looking for a pixel regression.** The /// widening defeats the deblocker's alignment gate (`x0 & (tx - 1)`), but /// every edge it lets through then meets the SAME libaom rule applied at /// the correct place, `edge_params_body`'s spec-7.14.2 / libaom /// `set_lpf_parameters` term `!pu_edge && cur_ref != 0 && pv_ref != 0 && /// skip_at && skip_at`. Inside one skipped block both cells are that same /// block, so all four terms hold and the edge dies there too. The masking /// is TOTAL, not incidental: this method is only ever called for a block /// that is itself skipped, so no input exists on which one side of an /// internal edge is not skipped. Measured over 26 frames / 2 555 904 /// samples across five 4:4:4 `--sb-size=128` streams that fire this arm /// 30 times: `64` and `128` both decode pixel-exact against aomdec, and /// differ from each other in not one sample. The gate for this value is /// therefore a source scan, not a pixel gate -- /// `refusal_inventory::the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent`. fn suppress_internal_lf_edges( &mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, fctx: &FrameCtx, ) { let (mi_r, mi_c) = at_mi; let (uv_w, uv_h) = ( ((w_mi * MI) >> ss_x(fctx)).max(4) as u8, ((h_mi * MI) >> ss_y(fctx)).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, ) { self.fill_lf_grid_rect_inner(at_mi, w_mi, h_mi, tx_px, tx_h_px, ref_frame, true, fctx) } /// [`Self::fill_lf_grid_rect`] for a block whose transform tree ALREADY /// published its own `TXFM_CONTEXT` bands -- every body that ran /// [`read_block_tx_size_rect`] / [`read_block_tx_size`] / an inline /// var-tx tree of its own. /// /// libaom's `parse_decode_block` (`decodeframe.c:1227-1236`) is an /// EITHER/OR: the var-tx branch calls `read_tx_size_vartx`, which /// publishes through `txfm_partition_update` PER LEAF /// (`av1_common_int.h:1684-1695`) and never calls `set_txfm_ctxs`; the /// `else` branch calls `read_tx_size` + `set_txfm_ctxs` exactly once, over /// the whole block. So on the var-tx path there is NO whole-footprint /// publish to reproduce, and one written here is not merely redundant -- /// it OVERWRITES the leaves' sizes with the block's own. /// /// lane-av1oddheightfork3, measured on the pinned /// `420_oddheight_320x236.obu` (then diverging: Y 234349 / U 56957 / /// V 52981, 0/16 frames; byte-exact since this lane): the INTRABC 8x16 /// block at mi(44,58) split into two 8x8 /// leaves, whose per-leaf writes put `8` into `left_txfm[44..48]`, and /// this publish then put the BLOCK's `16` back over those same four /// cells. The next block, the INTRABC 8x16 at mi(44,60), read /// `txfm_partition_context` with `left = 16` where libaom has `8` (the /// `above` operand agreed at 8 on both sides, printed by the oracle rung /// `EC_VARTXCTX` in `scripts/instrument-aom-oracle.sh`), took ctx 12 /// against libaom's 13, decoded `is_split = 0` against libaom's `1`, and /// read no children against libaom's two -- the frame's first divergent /// read. fn fill_lf_grid_rect_after_vartx( &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, ) { self.fill_lf_grid_rect_inner(at_mi, w_mi, h_mi, tx_px, tx_h_px, ref_frame, false, fctx) } #[allow(clippy::too_many_arguments)] fn fill_lf_grid_rect_inner( &mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, tx_px: u8, tx_h_px: u8, ref_frame: i8, publish_txfm_bands: bool, 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) >> ss_x(fctx)).max(4).min(32)) as u8; let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).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}" ); } crate::census::tx(tx_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); } if publish_txfm_bands && fctx.intra_only.with(std::cell::Cell::get) { // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size, // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi), // xd)` for EVERY block, an intra-only frame's included, and // `get_tx_size_context` / `txfm_partition_context` read those two // `TXFM_CONTEXT` bands. This grid carries the same transform size // over the same footprint, so the publish is this write: the // `skip && is_inter` term is 0 for every intra-only block that is // not an intrabc one, and the bodies that can code an intrabc // block publish their own (the term is then the BLOCK size, a value // this grid cannot express -- see `decode_block`/`decode_leaf8`). // Inter frames publish at their own sites and are excluded here // because their skipped-block term needs the block size too. txfm_partition_update_rect( self, at_mi, (tx_px as usize, tx_h_px as usize), (w_mi * MI, h_mi * MI), ); // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`), // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size // instead of its transform band. Every block stamps its own cells // here; the intrabc bodies re-stamp theirs `true` afterwards // (`record_intrabc_inter_bands`). for i in 0..w_mi { if let Some(cell) = self.above_inter.get_mut(mi_c + i) { *cell = false; } } for i in 0..h_mi { if let Some(cell) = self.left_inter.get_mut(mi_r + i) { *cell = false; } } // lane-av1txctxband: the same clear at libaom's own per-CELL // granularity. The band above clears one slot per column, so a // block that covered column 52 and a later block in the SAME // column but a different row leave the band describing whichever // wrote last; the grid clears exactly the cells this block owns. self.mark_inter_grid_rect(at_mi, w_mi, h_mi, false); } // lane-av1-intrabc r4: publish this coded block's own mi footprint // into the intrabc MV grid's block-COVERAGE map -- every coded block, // not just the intrabc ones. A later intrabc block's DV predictor is // built by libaom's own row/col scans over `xd->mi[]`, which holds an // `MB_MODE_INFO` for EVERY block and steps by // `mi_size_wide/height[candidate->bsize]`; without this footprint a // non-intrabc neighbour reads as uncovered and the scan advances it // by one cell instead of by its real width. fctx.intrabc_mi_grid.with(|g| { if let Some((grid, _, _)) = g.borrow_mut().as_mut() { grid.cover_rect(mi_r, mi_c, w_mi, h_mi); } }); } /// 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); } // lane-census: an INTRA frame's blocks never reach the inter // publisher, and this one is what every coded block writes. crate::census::block_intra_frame(w_mi, h_mi, skip); 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], }, ); } } /// Publishes one coded block's `is_inter_block` over EVERY 4x4 mi cell it /// covers -- lane-av1txctxband. libaom's `setup_mbs` /// (`decodeframe.c:355-361`) writes the block's own `MB_MODE_INFO` /// pointer into all of them, so `xd->mi[-xd->mi_stride]` / /// `xd->mi[-1]` name the block COVERING the cell, not "the last block /// written in this column" ([`Self::above_inter`] / /// [`Self::left_inter`], which is a per-column band and therefore stale /// for any block below the last writer in its column). /// Separate from [`Self::fill_skip_grid_rect`] because the two publishers /// run in BOTH orders at different call sites; both write disjoint fields, /// so the order does not matter. The value read is libaom's /// `is_inter_block` (`blockd.h:372-374`): an INTRABC block counts. fn mark_inter_grid_rect( &mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, is_inter: bool, ) { for rr in 0..h_mi { let start = (at_mi.0 + rr) * self.skip_grid_cols_mi + at_mi.1; fill_span(&mut self.inter_grid, start, w_mi, is_inter); } } /// `is_inter_block` of the coded block covering the mi cell /// `(mi_r, mi_c)`, or `false` for a cell no block has written yet (a tile /// border or a not-yet-decoded cell) -- lane-av1txctxband. The caller's /// `up_available` / `left_available` guard already excludes the borders. fn inter_at(&self, mi_r: usize, mi_c: usize) -> bool { self.inter_grid .get(mi_r * self.skip_grid_cols_mi + mi_c) .copied() .unwrap_or(false) } /// The covering block's own `(block_size_wide, block_size_high)` in /// pixels at the mi cell `(mi_r, mi_c)`, from [`Self::blk_grid`]'s `dim` /// (the published mi extent) scaled by [`MI`] -- lane-av1txctxband. This /// is libaom's `block_size_wide[above_mbmi->bsize]` / /// `block_size_high[left_mbmi->bsize]`, read at the abutting CELL rather /// than from the per-column [`Self::above_side_mi`] / /// [`Self::left_side_mi`] band. fn blk_side_at(&self, mi_r: usize, mi_c: usize) -> (usize, usize) { self.blk_grid .get(mi_r * self.skip_grid_cols_mi + mi_c) .filter(|c| c.written) .map_or((0, 0), |c| (c.dim[0] as usize * MI, c.dim[1] as usize * MI)) } /// 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; crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip); // 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); } // lane-av1txctxband: the per-CELL `is_inter_block` the per-column // `above_inter` band stands in for, at libaom's own granularity. self.mark_inter_grid_rect(at_mi, w_mi, h_mi, is_inter); 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; crate::census::compound(); 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). Clamp each edge to the true // frame extent: a block at the right/bottom edge may be padded beyond // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there. let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c)); let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r)); let mut out = [(false, false, 0i32); 3]; for cell in 0..above_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..left_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); } } out } /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell /// spans TWO luma mi columns. Both cells of a column carry the covering /// unit's whole-unit dc sign (the same value libaom stores), so the /// per-luma-mi sum counts each chroma column twice -- and /// `dc_sign_ctx`'s signum flips whenever the above and left votes have /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0). /// Sampling every second above cell counts each chroma column once, /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so /// its per-mi cells already line up one-to-one. The level booleans are /// ORs over duplicated cells, so the sampling cannot change them. fn around_mi_422_chroma( &self, (mi_r, mi_c): (usize, usize), w: usize, h: usize, ) -> [(bool, bool, i32); 3] { let (w_mi, h_mi) = (w / MI, h / MI); let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c)); let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r)); let mut out = [(false, false, 0i32); 3]; for cell in (0..above_mi).step_by(2) { 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..left_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") { // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1. // The above rows are the SAMPLED (every-second) cells. for (plane, o) in out.iter().enumerate() { let vote = o.2; let ab: Vec = (0..above_mi) .step_by(2) .map(|k| { format!( "{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level ) }) .collect(); let lf: Vec = (0..left_mi) .map(|k| { format!( "{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level ) }) .collect(); eprintln!( "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(",") ); } } 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); let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c)); let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r)); // [`Self::around_mi`]'s single pass, with the two extents split. let mut out = [(false, false, 0i32); 3]; for cell in 0..above_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..left_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..above_mi) .map(|k| { format!( "{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level ) }) .collect(); let lf: Vec = (0..left_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 above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c)); let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r)); let mut top = 0u8; let mut left = 0u8; for cell in 0..above_mi { top |= self.above[mi_c + cell][0].level; } for cell in 0..left_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..above_mi) .map(|k| self.above[mi_c + k][0].level.to_string()) .collect(); let lf: Vec = (0..left_mi) .map(|k| self.left[mi_r + k][0].level.to_string()) .collect(); // lane-av1mix: the last few msac register states, so the // byte-position of the `all_zero` read can be matched against // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a // second run. let recent = crate::msac::symtrace::ecdump_recent(4) .iter() .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})")) .collect::>() .join(" "); eprintln!( "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]", ab.join(","), lf.join(","), recent ); } 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, ); } // lane-av1leftwit: stamp the writing block's own mi over its extent, // the same cells and the same clipping as `uv_mode_grid` above. let owner = UV_OWNER_EPOCH.with(|c| c.get()) | ((mi_r as u32) << 12) | mi_c as u32; for row in mi_r..=last_r { fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner); } if crate::envflags::env_flag!("EC_LEFTSSY") { eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}"); } } /// 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, fctx: &crate::decode::FrameCtx, ) -> 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`). // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps // nothing, and the hardcoded snap read a 4x4 leaf's smooth // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)). let snap_y = (1usize << ss_y(fctx)) - 1; let snap_x = (1usize << ss_x(fctx)) - 1; // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`, // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies // the two chroma-reference offsets on top of it -- see its own comment // for which axis each one moves. self.smooth_uv_neighbour_unsnapped( mi_r & !snap_y, mi_c & !snap_x, r, c, ss_x(fctx), ss_y(fctx), true, ) } /// [`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. /// `decode_path` is `true` only for the snapping form every decode call /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the /// `+ss_y` counters measure a read that actually filters a chroma edge and /// not the counter-only one. /// /// lane-av1leftwit: the mirror's justification used to be "no committed /// fixture reaches the shape on the decode path", and that was false -- /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a /// counter-only mirror at an ODD mi row is still not a decode-path read, /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no /// longer evidence about the `+ss_y` term, and nothing may cite it as such. /// The decode path's own reach is `uv_left_1mi_split_hits()`. fn smooth_uv_neighbour_unsnapped( &self, mi_r: usize, mi_c: usize, r: usize, c: usize, ss_x: usize, ss_y: usize, decode_path: bool, ) -> 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) }; // libaom's two chroma-reference mi, from `set_mi_row_col` // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)` // snap -- i.e. already libaom's `base_mi`: // // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1 // // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` -- // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the // boolean it feeds is simply not exercised differently by that stream // at its blocks. One chroma column spans two luma mi columns, so the // chroma edge reaches into the right-hand luma block, and that is where // its reference lives. // // SHIPPED (lane-av1leftref): the left read's `+ss_y` ROW term -- the // last open item lane-av1422warp carried. libaom puts the left // reference one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`) and on // its own row at 4:2:2 (`ss_y == 0`); this read its own row at every // subsampling. An earlier attempt applied the `ss_y` term to the WRONG // read (the above) and regressed the byte-exact 4:2:0 control, which // is what exposed the crossing. lane-av1leftwit CORRECTED the claim // this comment used to make: "six committed 4:2:0 fixtures reach it, // and on `reelb_ss600_key_frame.obu` the boolean flips" was never // measured. Measured over all 48 committed fixtures that decode // (`lanes/av1leftwit.report.md`), `reelb_ss600_key_frame.obu` reads // `mode_diff=0 smooth_diff=0 split1mi=0`, and exactly FIVE fixtures // put a 1-mi-tall left neighbour in front of a decode-path read at // all -- `gm_small_side_witness` (5), `reelc_sb128_inter_witness` (7), // `av112bit-{inter,compound,compound-masked}` (1 each) -- and in every // one of those reads the two blocks agree on `uv_mode`. So the SHAPE is // reachable (see `UV_LEFT_1MI_SPLIT_HITS`) and the term's VALUE // changing is what is still unwitnessed. let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x); // lane-av1leftref: libaom's LEFT read carries the `+ss_y` ROW term -- // `base_mi[ss_y * mi_stride - 1]` (`av1_common_int.h:1400-1401`) is // one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`), and on its own // row at 4:2:2 (`ss_y == 0`) and 4:4:4. The read below used its own // row at every subsampling. The term is only observable when the two // cells hold DIFFERENT blocks, i.e. the left neighbour is 1 mi tall or // shorter -- then `(row, col-1)` and `(row+1, col-1)` are two blocks // and only libaom's is the chroma reference. Three counters measure // that, and the third is the one the other two need: a read can only // differ if the two cells are written by DIFFERENT blocks, which // `UV_LEFT_1MI_SPLIT_HITS` counts off the per-cell owner stamp // (`uv_owner`, below). A DIFF bucket that reads 0 while SPLIT reads 0 // was never in contention; a DIFF bucket that reads 0 while SPLIT // reads > 0 is the term being unobservable on real material, not // unreachable. `..._MODE_DIFF_HITS` / `..._SMOOTH_DIFF_HITS` then say // whether the mode value, and the boolean this feeds // (`is_smooth_mode` -> `av1_get_intra_edge_filter_type` -> the chroma // edge filter), actually moved. let left_mi = (mi_r + ss_y, mi_c.saturating_sub(1)); let read_left = |row: usize| -> usize { match self.uv_mode_row.get(row) { _ if have_left && let Some(m) = cell(&self.uv_mode_grid, row, left_mi.1) => m, Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m), _ if have_left => self.left_uv_mode[r], _ => DC_PRED, } }; let above = match self.uv_mode_col.get(above_mi.1) { _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m, Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m), _ if have_above => self.above_uv_mode[c], _ => DC_PRED, }; let left = read_left(left_mi.0); // lane-av1leftref: the gate's reach + load-bearing counters. `READS` is // how many chroma edge-filter-type reads took this path at all, so a // gate can tell "the arm never ran" from "the arm ran and the `+ss_y` // term did not change the answer". The two DIFF buckets compare // libaom's read cell against the pre-lane own-row cell; both read 0 on // every committed fixture and every one of the ~1000 encodes swept in // `lanes/av1leftref.report.md`, which is what makes the read change a // proven no-op on today's material rather than an unmeasured guess. if decode_path && have_left && ss_y > 0 { hit!(UV_LEFT_SS_Y_READS); // The pre-lane read, kept as the counter's own-row arm: it is what // this decoder answered before the `+ss_y` term landed, and // comparing against it is what proves the term is load-bearing. let own_row = read_left(mi_r); if own_row != left { hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS); } if is_smooth_mode(own_row) != is_smooth_mode(left) { hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS); } // lane-av1leftwit: the geometry the `+ss_y` term needs. The two // cells are one left mi column apart, so they are two different // blocks exactly when the left neighbour is 1 mi tall or shorter. let col = left_mi.1; let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000; let own = (col < self.uv_grid_cols) .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied()) .flatten() .filter(|o| o & 0xff00_0000 == epoch) .unwrap_or(0); let down = self .uv_owner .get((mi_r + ss_y) * self.uv_grid_cols + col) .copied() .filter(|o| o & 0xff00_0000 == epoch) .unwrap_or(0); if own != 0 && down != 0 && own != down { hit!(UV_LEFT_1MI_SPLIT_HITS); if crate::envflags::env_flag!("EC_LEFTSSY") { eprintln!( "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \ owners=({},{})->({},{}) modes={own_row}/{left}", epoch >> 24, own >> 12 & 0xfff, own & 0xfff, down >> 12 & 0xfff, down & 0xfff, ); } } } 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, left_mi.0, left_mi.1).is_some_and(|m| { !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.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], ) { self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode); self.record_mi_rect(at_mi, w, h, grids); } /// [`Self::record_rect_mi`]'s mode and transform-size half, without the /// coefficient-context stamp. fn record_rect_mi_modes( &mut self, at_mi: (usize, usize), w: usize, h: usize, mode: usize, uv_mode: usize, ) { 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); } /// lane-av1chromarect: [`Self::record_rect_mi`] for a block whose uv /// plane block is SEVERAL transform units, each of which stamped its own /// span through [`Self::record_mi_chroma`]. Writing one whole-block state /// over them is the `override-slot-on-one-arm` class: libaom keeps the /// per-unit above/left contexts distinct, and the next block's first /// unit reads them. The luma plane has one unit here, so it is stamped /// exactly as the whole-block record stamps it. fn record_rect_mi_luma_only( &mut self, at_mi: (usize, usize), w: usize, h: usize, mode: usize, uv_mode: usize, luma_grid: &[i32], ) { self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode); fill_span(&mut self.left_side_mi, at_mi.0, h / MI, h as u8); fill_span(&mut self.above_side_mi, at_mi.1, w / MI, w as u8); self.record_mi_luma_rect(at_mi, w, h, luma_grid); } /// 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], ) { // lane-arfchroma: a 4x4 CHROMA transform unit is `4 << ss` luma px per // axis, i.e. `1 << ss` LUMA mi, so its context cell is the step-aligned // group of mi a block may only PART of. A block starting mid-cell (a // 16x4 / 4x16 1:4 strip, whose mi row/col is ODD at 4:2:0) stamped its // own origin plus the mi row/col BELOW it, so the strip above a block // handed that block a "left neighbour" libaom never had -- its chroma // cell is one row up -- and the block's chroma `txb_skip` context came // out one base high (ours 2, libaom 7+1 = 8, at 320x240 frame 2 block // mi (4,0) of the 4:2:0 lossless alt-ref witness). Align the origin // DOWN to the cell: that is where libaom's per-plane 2-D // `left/above_context_map` cell lives, indexed in the PLANE's own 4x4 // units rather than in luma mi. let (step_x, step_y) = (w_px / MI, h_px / MI); // the flags read the CALLER's origin, before the shadowing align below let (row_mid, col_mid) = (mi_r & (step_y - 1) != 0, mi_c & (step_x - 1) != 0); if row_mid || col_mid { CHROMA_MIDCELL_PUB_HITS.with(|c| { let mut v = c.get(); v[0] += usize::from(row_mid); v[1] += usize::from(col_mid); v[2] += usize::from(row_mid && col_mid); c.set(v); }); } let (mi_r, mi_c) = (mi_r & !(step_y - 1), mi_c & !(step_x - 1)); 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); if crate::envflags::env_flag!("EC_CHROMA_PUB") { eprintln!( "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}", state.level, state.dc.map_or(-1, |s| i32::from(s)) ); } 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], ) { self.record_split_luma_rect_mi_modes(at_mi, w, h, mode, uv_mode); let (mi_r, _) = at_mi; let (w_mi, h_mi) = (w / MI, h / MI); 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(at_mi.1)) { self.above[at_mi.1 + cell][plane] = state; } } } } /// [`Self::record_split_luma_rect_mi`]'s mode and transform-size half, /// without the per-plane coefficient stamp -- see /// [`Self::record_rect_mi_luma_only`] for why a multi-unit chroma block /// must not take the whole-block stamp. fn record_split_luma_rect_mi_modes( &mut self, at_mi: (usize, usize), w: usize, h: usize, mode: usize, uv_mode: usize, ) { 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); } } /// 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). pub(crate) 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). pub(crate) 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) } /// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512): /// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block /// cut by the frame's bottom or right mi edge codes its colour-index map only /// over this part and replicates it outward -- reading the full `bw x bh` grid /// consumed symbols libaom never wrote and desynced the rest of the tile /// (lane-svtinter; class map-read-past-frame-edge). fn palette_onscreen( mi_r: usize, mi_c: usize, bw: usize, bh: usize, fctx: &crate::decode::FrameCtx, ) -> (usize, usize) { // lane-palw: the ENCODER's own in-process reconstruct runs on a // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both // frame encoders publish the header's mi dims onto it themselves // (`encode.rs`, beside their `true_width`/`true_height`) so that this // clamp and `tile::write_color_index_map`'s now agree there too. let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols)) } /// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches /// it (`tile::write_palette_syntax`, armed per frame): the two sides must /// compute the same on-screen extent or the decoder reads a different number /// of symbols than the encoder wrote. pub(crate) fn palette_onscreen_dims( mi_r: usize, mi_c: usize, bw: usize, bh: usize, (mi_rows, mi_cols): (usize, usize), ) -> (usize, usize) { ( bw.min(mi_cols.saturating_sub(mi_c) * MI), bh.min(mi_rows.saturating_sub(mi_r) * MI), ) } /// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus /// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the /// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move /// together or a cut 8-wide block reads its chroma map at the wrong width. /// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4 /// intra-in-inter palette read its chroma map at the 4:2:0 extent and /// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct). pub(crate) fn palette_onscreen_uv( luma: (usize, usize), on: (usize, usize), chroma: (usize, usize), ss: (usize, usize), ) -> (usize, usize) { ( (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)), (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)), ) } /// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index /// map's wavefront decode over a `side x side` grid, read over the on-screen /// `on_side x on_side` corner (see [`palette_onscreen`]). fn decode_color_index_map( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: usize, side: usize, on: (usize, usize), uv: bool, ) -> Vec { decode_color_index_map_wh(dec, cdfs, n, side, side, on, 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, // `(onscreenWidth, onscreenHeight)` in this plane's own units. on: (usize, usize), uv: bool, ) -> Vec { let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh)); if on_bw < bw || on_bh < bh { hit!(PALETTE_ONSCREEN_CUT_HITS); } 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..(on_bw + on_bh - 1) { let j_hi = i.min(on_bw - 1); let j_lo = i.saturating_sub(on_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}"); } } } palette_replicate(&mut map, bw, bh, on); map } /// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the /// last on-screen column then the last on-screen row are replicated over the /// off-screen remainder, so the prediction still covers the whole block. The /// ENCODER runs this over its searched map too (`encode.rs`'s palette arms), /// so the pixels it prices and reconstructs are the ones the on-screen /// symbols it writes really decode to. pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) { let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh)); for row in 0..on_bh { let last = map[row * bw + on_bw - 1]; map[row * bw + on_bw..row * bw + bw].fill(last); } for row in on_bh..bh { map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw); } } /// [`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, // lane-av1-intrabc: the block vector, `Some` exactly when this block's // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns // straight out of `read_intra_frame_mode_info` then, so every later field // of the tuple is at its default (mode/uv_mode DC, no angle, no palette, // no filter intra). A caller that can reconstruct intrabc at its shape // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by // name with the same string it always did. Option<(i32, i32)>, )> { // lane-av1mono: libaom guards every chroma symbol read with // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`), // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/ // `palette_uv` even on a chroma-reference strip. Fold the plane count // into the same `has_chroma` this reader already gates on. let has_chroma = has_chroma && !mono(fctx); crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64); 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, (bw / MI, bh / MI), 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); // libaom `read_intrabc_info`: the DV read, then an immediate // return out of the mode-info read -- no `y_mode`, no `uv_mode`, // no angle deltas, no palette, no filter intra. The caller owns // the reconstruction at its own shape. let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx); return Ok(( skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None, Some(dv), )); } } 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 { crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); 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 && cfl_allowed_px(bw, bh, fctx); let uv_mode = if !has_chroma { DC_PRED } else if cfl { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); 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, palette_onscreen(mi_r, mi_c, bw, bh, fctx), 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 >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4)); let on = palette_onscreen_uv( (bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch), (ss_x(fctx), ss_y(fctx)), ); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, 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, None, )) } /// 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; } } } } /// [`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 { cfl_ac_q3_at(px, py, bw, bh, |lx, ly| { i32::from(y.data[ly * y.width + lx]) }) } /// 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, fctx: &crate::decode::FrameCtx, ) -> (usize, usize) { // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom // `read_tx_size`: the lossless early return comes before // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here. if lossless(fctx) { return (4, 4); } 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) } /// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the /// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide /// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at /// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and /// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a /// 2-px-wide area is not a transform shape. The strip pairs with its /// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause, /// the rule [`decode_rect4_16_strip`] implements one partition level up), and /// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at /// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with /// the entropy context on the floored cell. Returns /// `(pair block width, pair block height, write anchor x, entropy mi column)` /// for that pair, or `None` when the strip keeps its own plane block at its /// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never /// 2 px wide) and every 4:2:2 strip of 8 px or more. fn chroma422_pair_plane( ss_x: bool, ss_y: bool, mi_col: usize, bw: usize, bh: usize, ) -> Option<(usize, usize, usize, usize)> { if ss_x && !ss_y && (bw >> 1) == 2 { Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1)) } else { None } } /// 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 >> ss_x(fctx), py >> ss_y(fctx)); let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips' // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`, // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m // measurement). The plane is still coded -- `decode_token_recon_block` // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into // 4x8 rect units, plane-major. let chroma_422_oob = ss_x(fctx) == 1 && ss_y(fctx) == 0 && matches!( (bw, bh), (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64) ); // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's // plane is then `(4, chroma_h)` written at the FLOORED cell // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8) // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 -- // the same walk the (8, 32) class takes). The lossless raster arm keeps // the strip's own geometry: no caller of this function can present a // 4-wide strip yet (the enumeration test pins the five callers at // `8 <= min`), and the skip/tiled arms are the routes a future caller // needs. let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh); let chroma_422_pair_wide = chroma422_pair.is_some(); let (chroma_block_w, chroma_block_h, chroma_x) = chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x)); // 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, }; // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled // below; everything else still needs a single-unit table. // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and // halves only the width, so a rect luma strip codes a SQUARE chroma block // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a // rect strip's chroma is itself rect, so the square rows are unreachable // there and cannot change their results. // lane-av1-422blockhalf: the tiled arms below handle every shape this // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the // diagnostic names only the shapes that would actually refuse -- it used // to fire for every tiled square too (the parent lane's `chroma=8x8` // rows) and sent the next lane chasing handled shapes. let chroma_tiled = chroma_422_pair_wide || chroma_422_oob || matches!( (chroma_w, chroma_h), (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8) ); 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 !m.skip && chroma.is_none() && !chroma_tiled { // 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() && !chroma_tiled { 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, block_iqmatrix(fctx, 0, tx_w, tx_h, 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, 0, )?; 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, block_iqmatrix(fctx, 0, tx_w, tx_h, 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. // lane-lossless2: except on a lossless frame, where it is a raster of 4x4 // units -- each stamps its own neighbour context as it is read, and the // whole-block `record_split_luma_rect_mi` below would overwrite all of // them with the LAST unit's state (class `override-slot-on-one-arm`: the // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are // collected here and replayed after that record. let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); // The chroma_tiled arm below stamps each unit's coefficient context // immediately (so the NEXT unit reads it), then the whole-strip // `record_split_luma_rect_mi` rewrites every chroma cell with ONE // whole-strip state and the per-unit DC signs and levels are lost // (class `override-slot-on-one-arm`). The units are collected here and // replayed after that record, the way the lossless arm's // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail // already do. let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); let ac = m.alpha.map(|_| { // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's // luma -- the 8-px-wide region the floored 4-px chroma block covers // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px. if chroma_422_pair_wide { cfl_src_rect((mi_c & !1) * MI, py, 8, bh) } else { cfl_src_rect(px, py, bw, bh) } }); let reach = if chroma_422_pair_wide { // The chroma units predict off the PAIR block's edges: an odd-column // strip's pair starts 4 luma px to the strip's left, so the strip's // own answer names the wrong above/right samples (the pair16 arm's // `pair_reach`, one partition level up). Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx) } else { block_reach }; let (u_grid, v_grid) = if mono(fctx) { // lane-av1mono: a monochrome frame codes no chroma coefficients on // any block (`plane < av1_num_planes == 1`), so the whole chroma // section -- the skipped-strip pushes, the lossless raster and the // un-split `read_coeffs_rect` below -- is bypassed. let zero = Grid::Zero(chroma_w * chroma_h); (zero.clone(), zero) } else if m.skip { let zero = Grid::Zero(chroma_block_w * chroma_block_h); if chroma_422_pair_wide || chroma_422_oob { // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma // per transform unit even when the strip is skipped // (`decode_token_recon_block`'s per-TU plane walk runs before the // skip guard), so the BLOCK_INVALID plane predicts as (4, 8) // units -- one whole-plane push here would ask the intra // predictor for a 1:8 rect it never needs. // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the // same, over the pair's own `(chroma_block_w, chroma_block_h)` // grid at the floored anchor `chroma_x`. let (uw, uh) = (4usize, 8usize); for plane_idx in 1..=2 { if let Some((ub, vb)) = &m.palette_uv { let buf = if plane_idx == 1 { ub } else { vb }; set_palette_pred(buf.clone(), fctx); } for cu_row in 0..chroma_block_h / uh { for cu_col in 0..chroma_block_w / uw { push_intra_rect( plane_idx, chroma_x + cu_col * uw, cpy + cu_row * uh, uw, uh, m.uv_predict_mode, m.angle_delta_uv, reach, &ZERO_RESIDUAL[..uw * uh], m.alpha .zip(ac.clone()) .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)), None, m.smooth_neighbor_uv, fctx, ); } } } } else { 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 if lossless(fctx) { // lane-lossless: the strip's chroma plane block is coded as 4x4 // transform units too (libaom `read_tx_size` returns TX_4X4 for every // plane), PLANE-MAJOR inside the block -- U's units first, then V's // (`decode_token_recon_block`'s mu-chunk loop, measured against // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1, // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10` // offset (our `+3` row base) whenever the plane block is bigger than // the transform. let scan4 = default_scan(4); let offset = (chroma_w > 4 || chroma_h > 4).then_some(3); let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4); // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4 // chroma px scaled by the plane's own subsampling. The hardcoded 8 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi // cell), and the 8-px step made every unit past the first column/row // read its `txb_skip` context at the WRONG mi (two cells over) and // stamp a 2-cell span with one unit's state -- the polluted above-band // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps; // ours read `above[28..29]` where the oracle read `above[26]`). let span_x = 4 << ss_x(fctx); let span_y = 4 << ss_y(fctx); let mut last = [Grid::Zero(16), Grid::Zero(16)]; for plane_idx in 1..=2 { for cu_row in 0..ch_n { for cu_col in 0..cw_n { // lane-av1offtile: the CHROMA twin of the luma walk's // `max_blocks_wide/high` clip (decode.rs:12516, lane-hgkf // r1). libaom computes those bounds per PLANE // (`max_block_wide(xd, plane_bsize, plane)`, // av1_common_int.h:1565 -- `mb_to_right_edge >> // (3 + pd->subsampling_x)`, then `>> MI_SIZE_LOG2`), so a // chroma unit whose top-left sample falls outside the // CHROMA plane is never coded. This walk counted // `chroma_w / 4` x `chroma_h / 4` units off the BLOCK's // own extent instead. // // MEASURED on `mix_176x144_6.obu` (4:2:0 8-bit, // --cq-level=0 --aq-mode=1 altref; the 48x16 bottom-right // sliver, block mi=(32,32) px=(128,128) bw=64 bh=32): // the chroma plane is 88x72, so `cw_n` must be // `(88 - 64) / 4 = 6` and `ch_n` `(72 - 64) / 4 = 2` -- // the oracle's own `EC_ECDUMP_IN` for that block is // exactly 12 units per plane (bc 0..5 x br 0..1). Ours // walked 8 x 4 = 32 per plane: 20 phantom units x 2 // planes = the 40 extra `txb_skip` reads after SYMR // 25791, all at `mi=(32,32)`, all `all_zero`, all with // the bit position FROZEN at 36288 -- reads out of a // tile already exhausted, which is what turned the // desync 11 970 reads later into a hard // `REFUSED: unsupported: AV1 tile (a Golomb tail longer // than this decoder reads)`. if cpx + cu_col * 4 >= u.true_width || cpy + cu_row * 4 >= u.true_height { hit!(RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS); continue; } let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI)); // lane-av1422llintra: at ss (1, 0) one chroma column // spans TWO luma mi columns, so the plain rect walk sums // its whole-unit dc sign TWICE where libaom's // `get_txb_ctx_general` reads `txb_w_unit` chroma cells // -- one per column. `dc_sign_ctx` only sees the vote's // SIGNUM, so a doubled above vote flips the row exactly // when above and left cancel (a+l = 0 -> ctx 0 becomes // 2a+l = +a). Measured on the pinned 4:2:2 all-intra // lossless control `ll422_allintra.obu`: the V 4x4 unit // at chroma (24, 8) of the BLOCK_32X8 at mi(2,8) -- // oracle `EC_DBGCTX above0=23 left0=13` sums to dc 0 and // reads `dc_sign_cdf[0]`; ours summed the above column // twice, got vote +1, and read `dc_sign_cdf[2]`, so the // DC sign symbol came out inverted and the whole tile // desynced from there. Identical to the guard one arm up // at 12865. let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 { neighbours.around_mi_422_chroma(cu_mi, span_x, span_y) } else { neighbours.around_mi_rect(cu_mi, span_x, span_y) }; let cu_reach = tu_reach( bw, bh, cu_col * span_x, cu_row * span_y, span_x, block_reach, px, py, y.width, y.height, fctx, ); let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4); if let Some((ub, vb)) = &m.palette_uv { let pbuf = if plane_idx == 1 { ub } else { vb }; set_palette_pred( palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4), fctx, ); } let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; let grid = read_plane( dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx, cu_around[plane_idx], m.mode, m.uv_predict_mode, m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4, base_q_idx, m.alpha .zip(ac) .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)), None, offset, m.smooth_neighbor_uv, fctx, )?; if span_x == 4 && span_y == 4 { hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS); } neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid); ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y)); last[plane_idx - 1] = grid; } } } let [ug, vg] = last; (ug, vg) } else if chroma_tiled { let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) = if chroma_422_pair_wide || chroma_422_oob { // lane-av1-422blockhalf / lane-av1-422stripanchor: the // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8, // see above). For the 4-wide strip the units tile the PAIR's // plane, stepping from the floored anchor. (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8) } else { match (chroma_w, chroma_h) { (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)), (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16), (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32), // lane-av1-422: the 4:2:2 square chroma planes (height unhalved), // through the square reader like every other square chroma unit. (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)), (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)), _ => unreachable!("chroma_tiled"), } }; // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2 // frame's square chroma units count it. if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 { hit!(CHROMA422_SQUARE_HITS); } if chroma_422_pair_wide { hit!(CHROMA422_PAIR_WIDE_HITS); } let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh); // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in // the pinned Release oracle), so its txb_skip rows always carry the // bigger-plane +3 (the av1422q rule the pair16 arm measures). let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh; // `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; // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the // mode-indexed default, the same rule the unsplit arm below applies. let default_tx = if uw.max(uh) >= 32 { TxType::DctDct } else { default_intra_tx_type(m.uv_predict_mode as u8) }; let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)]; for plane_idx in 1..=2 { for cu_row in 0..nh { for cu_col in 0..nw { let luma_span_x = uw << ss_x(fctx); let luma_span_y = uh << ss_y(fctx); let cu_mi = ( mi_r + cu_row * (luma_span_y / MI), if chroma_422_pair_wide { mi_c & !1 } else { mi_c } + cu_col * (luma_span_x / MI), ); // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their // chroma context per chroma cell // ([`Neighbours::around_mi_422_chroma`], the block-8 // rule) -- the plain rect walk samples one chroma cell // twice at ss_x 1. Every pre-existing shape keeps its own // walk. // lane-av1422mi24: the plain rect walk's double-count // hits EVERY unit shape at ss (1,0), not just the (4, 8) // one -- the (8, 8) unit of a 16x8 intra-in-inter strip // read its above dc votes twice and its U dc_sign one // ctx row high (t422 frame 1). Route every ss (1,0) // unit through the every-second-above-cell sampling; // 4:2:0/4:4:4 keep the plain walk verbatim. let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) { neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y) } else { neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y) }; let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh); let cfl = m.alpha.map(|(au, av)| { let alpha = if plane_idx == 1 { au } else { av }; ( alpha, if chroma_422_pair_wide { // The unit's co-located luma is the PAIR's // 8-px-wide band at the floored mi column. cfl_src_rect( (mi_c & !1) * MI + cu_col * luma_span_x, py + cu_row * luma_span_y, luma_span_x, luma_span_y, ) } else { cfl_src_rect( px + cu_col * luma_span_x, py + cu_row * luma_span_y, luma_span_x, luma_span_y, ) }, ) }); // lane-av1-422kf: the palette colour map is consumed per // unit here like every other chroma arm (`av1_visit_palette` // feeds the whole plane block; window it to this unit). // Without this the square chroma rows decoded a uv-palette // strip's chroma as plain DC (class same-symbols-silent- // prediction: the rng stayed in sync, only the prediction // was dropped). if let Some((ub, vb)) = &m.palette_uv { let buf = if plane_idx == 1 { ub } else { vb }; set_palette_pred( palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh), fctx, ); } // libaom computes `has_top_right` PER TRANSFORM UNIT (defined // reconintra.c:196, called from `av1_build_intra_predictors` at // reconintra.c:1847 with the txb walk's own // `blk_col`/`blk_row`), never per block: the // `row_off == 0` arm asks `col_off + top_right_count_unit // < plane_bw_unit`, so the FIRST unit of a 2-wide chroma // grid reads its above-right out of the already-reconstructed // block ABOVE even when the block's own right edge is the // frame's. Passing this walk's block-level `reach` gave // every unit the same answer, and `PlaneBuf::edges` // (decode.rs:20840) truncates the above row at // `own_across` when `above_right` is false -- so a // directional unit whose angle is below 90 // (`need_right`, intra.rs:546) predicted with a 32-sample // above row where libaom used 64. // MEASURED on `fixtures/r512_rect2x1_1x2_444.obu` // (4:4:4 8-bit 256x256, one frame): frame 0 plane U 130 // samples and plane V 30 samples wrong, every one of them // in the right 6 columns of the `cu=(0,0)` unit at // `mi=(48,48)` `px=(192,192)` -- the unit whose above-right // the block reach denied. Row0 and col0 of the prediction // matched the oracle exactly and the prediction SUM did // not (172662 vs 171512 on U, 125978 vs 126008 on V), so // the residual read is bit-identical and the divergence is // prediction-side, not entropy. Gate: // `a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach`. let cu_reach = tu_reach_rect( bw, bh, (cu_col * uw) << ss_x(fctx), (cu_row * uh) << ss_y(fctx), uw << ss_x(fctx), uh << ss_y(fctx), reach, px, py, y.width, y.height, fctx, ); if cu_reach.above_right != reach.above_right || cu_reach.below_left != reach.below_left { hit!(RECT_TILED_CHROMA_UNIT_REACH_HITS); } if nw * nh > 1 { match (nw, nh) { (2, 1) => hit!(RECT_TILED_CHROMA_2X1_HITS), (1, 2) => hit!(RECT_TILED_CHROMA_1X2_HITS), _ => hit!(RECT_TILED_CHROMA_NXN_HITS), } } // 32x32 does not fit read_coeffs_rect's scratch (768). The // square reader is the path every other 32x32 chroma unit uses. let levels = if uw == uh { let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; read_plane( dec, cdfs, set, scan, plane_idx, cu_around[plane_idx], m.mode, m.uv_predict_mode, m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, uw, uw, base_q_idx, cfl, None, bigger.then_some(3), m.smooth_neighbor_uv, fctx, )? } else { let skip_ctx = usize::from(cu_around[plane_idx].0) + usize::from(cu_around[plane_idx].1) + usize::from(bigger) * 3; let mut coding = cdfs.txb(set, m.uv_predict_mode); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, scan, uw, uh, skip_ctx, dc_sign_ctx(cu_around[plane_idx].2), default_tx, plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, uw, uh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, block_iqmatrix(fctx, plane_idx, uw, uh, tx_type), ); push_intra_rect( plane_idx, cu_x, cu_y, uw, uh, m.uv_predict_mode, m.angle_delta_uv, cu_reach, &residual, cfl, None, m.smooth_neighbor_uv, fctx, ); levels }; neighbours.record_mi_chroma( cu_mi, luma_span_x, luma_span_y, plane_idx, &levels, ); tiled_chroma_units.push(( cu_mi, plane_idx, levels.clone(), luma_span_x, luma_span_y, )); last[plane_idx - 1] = levels; } } } (last[0].clone(), last[1].clone()) } 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) }; // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1` // chroma cells spread over `bw` luma mi columns -- the per-mi gather // counts every chroma column's whole-unit dc sign twice (the t422 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx // row high). Luma keeps the per-mi gather; the two chroma planes // take [`Neighbours::around_mi_422_chroma`]'s every-second // above-cell sampling, like every other 4:2:2 chroma gather. let mut around = neighbours.around_mi_rect(at_mi, bw, bh); if ss_x(fctx) == 1 && ss_y(fctx) == 0 { let c = neighbours.around_mi_422_chroma(at_mi, bw, bh); around[1] = c[1]; around[2] = c[2]; } 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, plane_idx, )?; // 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), // lane-d792: the BLOCK's quantizer index, i.e. the frame's // own index PLUS this block's segment `SEG_LVL_ALT_Q` -- // reading `current_q_idx` here dropped the segment feature // that every other dequant site applies (class // `parsed-then-discarded`). block_q_idx(fctx), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, 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], ); for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units { neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit); } for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units { neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit); } 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() { // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it // names that string exactly (placeholders included) and pins its guard // site. The enumeration below establishes the shape domain; on its own it // never said WHICH string the domain was about, so under a real function // boundary -- rather than a window that ran into the next test -- the row // read as unanchored. const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"; assert!( include_str!("decode.rs").contains(REFUSAL), "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" ); 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() { // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it // names it and pins its guard site. const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here"; assert!( crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL), "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" ); 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" ); } /// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port /// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over /// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm /// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column /// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would /// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes /// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 / /// 4:4:4 never enter either arm (the byte-identical claim, checked per cell). #[test] fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() { // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle, // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID. let ss10_invalid: &[(&str, bool)] = &[ ("4x4", false), ("4x8", true), ("8x4", false), ("8x8", false), ("8x16", true), ("16x8", false), ("16x16", false), ("16x32", true), ("32x16", false), ("32x32", false), ("32x64", true), ("64x32", false), ("64x64", false), ("64x128", true), ("128x64", false), ("128x128", false), ("4x16", true), ("16x4", false), ("8x32", true), ("32x8", false), ("16x64", true), ("64x16", false), ]; for (footprint, invalid10) in ss10_invalid { let (w, h) = footprint.split_once('x').unwrap(); let (bw, bh) = (w.parse::().unwrap(), h.parse::().unwrap()); // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is // valid because a (2, 4) plane area rounds UP to the 4x4 read // (`sub8_leaf_chroma422`'s own rule), and it never reaches // [`decode_rect_split`] at all. if (bw, bh) == (4, 4) { continue; } // 4:2:0 and 4:4:4: the port never fires, whatever the footprint. for (ss_x, ss_y) in [(false, false), (true, true)] { assert!( chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(), "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block" ); } // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the // BLOCK_INVALID column, anchored at the floored mi column. let pair = chroma422_pair_plane(true, false, 7, bw, bh); assert_eq!( pair.is_some(), *invalid10 && bw == 4, "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup" ); if let Some((block_w, block_h, x, ctx_col)) = pair { assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape"); assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor"); assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column"); // An even-column strip anchors at its own cell. let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) { Some((_, _, x, c)) => (x, c), None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"), }; assert_eq!( (x_even, col_even), (12, 6), "even column keeps its own cell" ); } } // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the // `chroma_422_oob` tiling's residents, not the pair arm's: both are // 4:2:2-only, so the two arms partition the BLOCK_INVALID column. for (bw, bh) in [ (8usize, 16), (16, 32), (32, 64), (64, 128), (8, 32), (16, 64), ] { assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none()); } } 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(()); } crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); 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`]. // // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol // (libaom `decodemv.c:933`). let has_chroma = !mono(fctx); let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx); let uv_mode = if !has_chroma { DC_PRED } else if cfl_allowed { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); 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. // lane-av1mono: libaom's actual guard is `num_planes > 1 && // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602). let use_palette_uv = has_chroma && 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, palette_onscreen(mi_r, mi_c, bw, bh, fctx), 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 >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4)); let on = palette_onscreen_uv( (bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch), (ss_x(fctx), ss_y(fctx)), ); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, 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, fctx); // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside // an inter frame codes no depth symbol either (`xd->lossless` is per // segment regardless of frame type; class sweep of the sub8 leaf's fix). let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) { // The frame's own `TXFM_CONTEXT` bands -- [`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 || lossless(fctx) { 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, fctx); // 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(()) } /// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real /// mi `(mi_r, mi_c)` (lane-av1-intrabc). /// /// libaom treats an intrabc block as INTER for everything except the mode-info /// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA` /// (`blockd.h:373`), so /// /// * `parse_decode_block` reads the transform size through the INTER var-tx /// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose /// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and /// whose leaves publish their own resolved size back; /// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT /// frame's own pre-loop-filter reconstruction, at the coded block vector /// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`); /// * `decode_token_recon_block`'s inter branch then reads one residual per /// transform unit, through the INTER coefficient sets /// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane /// inheriting the colocated luma unit's coded `tx_type`. /// /// Text order is libaom's: transform tree, prediction, luma residual, chroma /// residual, bookkeeping. A skipped block codes no residual at all -- the /// prediction is the reconstruction. #[allow(clippy::too_many_arguments)] fn decode_intrabc_rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, (mi_r, mi_c): (usize, usize), (bw, bh): (usize, usize), skip: bool, (dv_row, dv_col): (i32, i32), y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, fctx: &crate::decode::FrameCtx, ) -> Result<()> { hit!(INTRABC_RECT_HITS); // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`. let idx = usize::from(bh > bw); if skip { INTRABC_RECT_SKIPPED_HITS.with(|c| { let mut seen = c.get(); seen[idx] += 1; c.set(seen); }); } else { INTRABC_RECT_CODED_HITS.with(|c| { let mut seen = c.get(); seen[idx] += 1; c.set(seen); }); } let (px, py) = (mi_c * MI, mi_r * MI); // lane-whtshape: a LOSSLESS block's chroma plane block is // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize` // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes. // Measured on this lane's 4:4:4 lossless witness: with the halving, a // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless // walk below coded 2 units per plane where libaom codes 8. // // lane-ibc444c: UNSCOPED now. lane-whtshape split this on `lossless` and // named the LOSSY 4:4:4 footprint as another lane's open cell; this is // that cell. Measured on `444_intrabc_rect4_witness.obu`: with the // halving, an 8x16 luma block's 8x16 chroma plane block was read as ONE // 4x8 rect unit where libaom codes ONE TX_8X16, and the U `txb_skip` of // the block at mi (92, 104) read all_zero=0 here against the oracle's // all_zero=1 -- the bit position forks there. Identical arithmetic at // 4:2:0, where `ss_x = ss_y = 1`, so the pinned 4:2:0 twin of the // witness is the identity arm of this lane's gate. let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the // halved shape's own `max_txsize_rect_lookup` entry IS that size for every // shape this helper is called at, so the uv plane block is ONE unit -- // the same call `decode_token_recon_block`'s own chroma loop makes. let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); // lane-av1-intrabc r2: the square stride the proven INTER path uses // (`side`). The residual grids, the prediction windows AND // `TxParams::stride` are all laid out at it -- the block's own width // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h` // exceeds the stride). let side = bw.max(bh); let cside = cw.max(ch); // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right // or bottom frame edge reads no transform-tree 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 leaves = read_block_tx_size_rect( dec, cdfs, neighbours, (mi_r, mi_c), (bw, bh), (mi_cols, mi_rows), skip, fctx, )?; if leaves.is_some() { hit!(INTRABC_RECT_VARTX_HITS); } if ss_x(fctx) == 0 && ss_y(fctx) == 0 { hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS); } // lane-ibc444c: per-block geometry, for the chroma-tail attribution. if crate::envflags::env_flag!("EC_IBCBLOCK") { eprintln!( "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \ cw={cw} ch={ch} cside={cside} skip={skip}" ); } // The whole-block prediction: `predict_inter_block` runs once, before any // coefficient is read. `flush_recon` first -- the source is this frame's // own reconstruction, including the writes this superblock has queued. flush_recon(fctx, y, u, v); // `mc::predict_with_filter` writes a DENSE window; the residual machinery // reads it at the square stride, so re-lay it -- the same step the inter // path takes for its own square prediction buffer. let mut pred_y_dense = vec![0u16; bw * bh]; mc::predict_with_filter( &y.data, y.width, y.true_width, y.true_height, mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0), bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx, ); let mut pred_y = vec![0u16; side * side]; for row in 0..bh { pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]); } let mut pred_u_dense = vec![0u16; cw * ch]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_u_dense, fctx, ); let mut pred_u = vec![0u16; cside * cside]; for row in 0..ch { pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]); } let mut pred_v_dense = vec![0u16; cw * ch]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_v_dense, fctx, ); let mut pred_v = vec![0u16; cside * cside]; for row in 0..ch { pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]); } let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); let luma_tx_type: TxType; let (luma_grid, u_grid, v_grid); // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids, // kept so their per-4x4 slices can be re-stamped over the whole-block // record in the tail. `None` on every other arm. let mut ll_chroma: Option<(Vec, Vec)> = None; if skip { // No residual syntax at all: the prediction IS the block. // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm. push_mc_rect( 0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * side], fctx, ); push_mc_rect( 1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * cside], fctx, ); push_mc_rect( 2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * cside], fctx, ); if let Some(ls) = leaves.as_ref() { // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s // skip arm performs -- libaom `av1_reset_entropy_context` // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a // SKIPPED block zeroes its whole entropy-band footprint. This // helper serves `decode_block_rect4`'s 1:4 strips on this tree, // so a skipped lossless strip whose `leaves` resolved (every // lossless frame -- `read_block_tx_size_rect`'s lossless arm // returns the 4x4 grid before it looks at `skip`) left the // PREVIOUS occupant's luma bands standing and the NEXT block's // partition parse diverged from libaom's: the 320x242 lossless // sb128 gate read a phantom unskipped 8x32 intrabc strip at // mi(56,66) right after the skipped 8x16 one at mi(48,66). hit!(SKIP_LOSSLESS_BAND_RESET_HITS); for &(row, col, tw, th) in ls { neighbours.record_mi_luma_rect( (mi_r + row, mi_c + col), tw, th, &ZERO_RESIDUAL[..tw * th], ); } } luma_tx_type = TxType::DctDct; luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(cside * cside); v_grid = Grid::Zero(cside * cside); } else { match leaves.as_ref() { None => { // One whole-block rectangular transform unit. // lane-av1422mi24: at ss (1,0) the chroma above span is // `bw >> 1` chroma cells spread over `bw` luma mi columns -- // the per-mi gather counts every chroma column's whole-unit // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter // strip's U dc_sign read ctx 1 where the oracle's cell sum // is 0 -> ctx 0). Luma keeps the per-mi gather; the two // chroma planes take // [`Neighbours::around_mi_422_chroma`]'s every-second // above-cell sampling, like every other 4:2:2 chroma gather. let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); if ss_x(fctx) == 1 && ss_y(fctx) == 0 { let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh); around[1] = c[1]; around[2] = c[2]; } let (grid, tx_type) = read_inter_plane_rect( dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0, y, px, py, Pred::Inline(&pred_y, side), None, None, fctx, )?; luma_tx_type = tx_type; luma_grid = embed_grid_stride(&grid, bw, bh, side); let (ug, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, )?; u_grid = embed_grid_stride(&ug, cw, ch, cside); let (vg, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, )?; v_grid = embed_grid_stride(&vg, cw, ch, cside); } Some(leaves) => { // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies // the split override to LUMA only, per leaf -- the step the // proven inter var-tx path applies right after its own residual // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the // leaf's own transform edges are never filtered. for &(row, col, tw, th) in leaves.iter() { neighbours.fill_lf_grid_leaf_luma( (mi_r + row, mi_c + col), tw / MI, th / MI, tw as u8, th as u8, ); } // One residual per transform unit, in the order the tree coded // them; each unit reads its own neighbour-magnitude context off // the units already decoded before it, and every unit adds onto // its own window of the block's single prediction. let mut first_tx_type = TxType::DctDct; for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() { let tu_mi = (mi_r + row, mi_c + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); let (tu_grid, tu_tx_type) = if tw == th { let scan = default_scan(tw.min(32)); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI); read_inter_plane( dec, cdfs, inter_txbset_for(tw, reduced), scan, 0, neighbours.around_mi(tu_mi, tw)[0], 0, y, tu_px, tu_py, tw, base_q_idx, tu_pred, None, Some(tu_skip_ctx), fctx, )? } else { let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / 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], 0, y, tu_px, tu_py, tu_pred, 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); } // `av1_get_tx_type`'s chroma lookup lands on the colocated // LUMA unit, which for a split block is the top-left one. luma_tx_type = first_tx_type; // lane-av1422mi24: same 4:2:2 chroma gather rule as the // `None` arm above -- the per-mi rect gather double-counts // each chroma column's whole-unit dc sign at ss (1,0). let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); if ss_x(fctx) == 1 && ss_y(fctx) == 0 { let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh); around[1] = c[1]; around[2] = c[2]; } if lossless(fctx) { // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY // plane of a block -- `read_tx_size` returns `TX_4X4` for a // lossless block before it looks at a tree, `read_tx_mode` // already forced `ONLY_4X4` for the frame, and // `get_vartx_max_txsize` returns `TX_4X4` for every plane // -- so this block's chroma plane block is a // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR // (`decode_token_recon_block`: every U unit, then every V // unit), not the single rect unit the two // `read_inter_plane_rect` calls below read. That single // 8x4 unit is what reached the lossless WHT with the wrong // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane // replaced). Same helper, same walk, as the inter 8x8 and // 128 paths. hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS); let mut uo = vec![0i32; cside * cside]; let mut vo = vec![0i32; cside * cside]; read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, Pred::Inline(&pred_u, cside), Pred::Inline(&pred_v, cside), (mi_r, mi_c), (cpx, cpy), (0, 0), (cw, ch), (cw, ch), cside, 0, base_q_idx, &mut uo, &mut vo, fctx, )?; // The per-unit walk stamped every unit's own coefficient // context, but the whole-block `record_split_luma_rect_mi` // in the tail rewrites every chroma cell with ONE composed // state, which drops the per-unit DC signs and levels (class // `override-slot-on-one-arm` -- the same one // `decode_rect_split`'s `ll_chroma_units` replay exists // for). The grids are kept here and replayed AFTER that // record, from the same 4x4 slices, so the same states. u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside); v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside); ll_chroma = Some((uo, vo)); luma_grid = Grid::Zero(side * side); } else { let (ug, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, )?; u_grid = embed_grid_stride(&ug, cw, ch, cside); let (vg, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, )?; v_grid = embed_grid_stride(&vg, cw, ch, cside); luma_grid = Grid::Zero(side * side); } } } } let _ = luma_tx_type; // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the // next block reads a neighbour mode, its own block size in both `TXFM` // bands (already done by `read_block_tx_size_rect`), a zeroed palette // state (a stale entry would feed the next block's colour cache), and its // DV into the intrabc mi grid the next block's DV predictor reads. if leaves.is_some() { neighbours.record_split_luma_rect_mi( (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid], ); } else { neighbours.record_rect_mi( (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid], ); } // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over // the whole-block record above, so the NEXT block reads the per-unit DC // signs and levels libaom's plane-major walk left behind instead of one // composed state for the whole plane block. if let Some((uo, vo)) = ll_chroma { for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] { for ur in 0..ch / 4 { for uc in 0..cw / 4 { let mut unit = Vec::with_capacity(16); for r in 0..4 { unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]); } neighbours.record_mi_chroma( // lane-av1lm444loss-corr: the MI STEP between chroma // units is that same footprint expressed in luma mi // cells, `(4 << ss) / MI` -- which is exactly what // `decode_inter_block`'s reference `mu_chroma_units` // construction writes (decode.rs:43688, // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with // `cu = 4` on a lossless frame). The `4 >> ss_y` form // this replaces is 4:2:0-only arithmetic that happens // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi // and the footprint form is `(4 << 1) / 4` = 2 mi, the // SAME value, so 4:2:0 is unchanged by construction. // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi // (16 luma px) per 4x4 chroma unit, where a TX_4X4 // chroma unit covers `4 << 0` = 4 luma px = ONE mi. // The step therefore lands every replayed unit at 4x // its own mi row/column on a 4:4:4 lossless frame, and // the whole block's per-unit states are stamped over // cells that belong to other blocks (or to nothing). ( mi_r + ur * ((4 << ss_y(fctx)) / MI), mi_c + uc * ((4 << ss_x(fctx)) / MI), ), 4 << ss_x(fctx), 4 << ss_y(fctx), plane_idx, &Grid::Own(unit), ); } } } } neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); // lane-av1oddheightfork3: `read_block_tx_size_rect` ran above, so the // bands are the tree's own per-leaf publication (libaom's var-tx branch // never calls `set_txfm_ctxs`) -- publishing the block's own size over // them here is the defect this call site carried. neighbours.fill_lf_grid_rect_after_vartx( (mi_r, mi_c), bw / MI, bh / MI, bw.min(64) as u8, bh.min(64) as u8, 0, fctx, ); record_intrabc_mi_rect( mi_r, mi_c, bw / MI, bh / MI, Some((dv_row, dv_col)), neighbours, fctx, ); Ok(()) } /// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root /// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape /// `decode_block_128rect` refused by name before this port. libaom decodes /// such a block through the INTER machinery (an intrabc block /// `is_inter_block`): `predict_inter_block` copies the whole block from this /// frame's own reconstruction at the integer block vector once, then /// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks -- /// per chunk every plane, luma units at the block's own resolved transform /// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at /// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per /// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits /// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`, /// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in /// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here. #[allow(clippy::too_many_arguments)] fn decode_intrabc_128rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, (mi_r, mi_c): (usize, usize), (bw, bh): (usize, usize), skip: bool, (dv_row, dv_col): (i32, i32), y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, fctx: &crate::decode::FrameCtx, ) -> Result<()> { hit!(INTRABC_128RECT_HITS); if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); eprintln!( "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}" ); } let (px, py) = (mi_c * MI, mi_r * MI); // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded // `/2` origin and extent made the prediction window half as tall as // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT, // 4:4:4 is luma-sized. At ss (1,1) every value below is the old // `bw / 2, bh / 2` line-for-line. let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); // The square strides the proven INTER path lays its residual grids, // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2 // note): 128/64 here. let side = bw.max(bh); let cside = cw.max(ch); // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code // nothing (`decode_reconstruct_tx`'s max_blocks_* early return). let mi_cols = 2 * y.true_width.div_ceil(8); let mi_rows = 2 * y.true_height.div_ceil(8); // An intrabc block is is_inter_block: the tx tree is the INTER one, and // [`read_block_tx_size_rect`]'s 128-root branch already carries the // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid) // arms (lane-sb128c r7). let leaves = read_block_tx_size_rect( dec, cdfs, neighbours, (mi_r, mi_c), (bw, bh), (mi_cols, mi_rows), skip, fctx, )?; // Whole-block prediction, once, before any coefficient is read // (`predict_inter_block`); the source is this frame's own // reconstruction, including the writes this superblock has queued. flush_recon(fctx, y, u, v); let mut pred_y_dense = vec![0u16; bw * bh]; mc::predict_with_filter( &y.data, y.width, y.true_width, y.true_height, mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0), bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx, ); let mut pred_y = vec![0u16; side * side]; for row in 0..bh { pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]); } let mut pred_u_dense = vec![0u16; cw * ch]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_u_dense, fctx, ); let mut pred_u = vec![0u16; cside * cside]; for row in 0..ch { pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]); } let mut pred_v_dense = vec![0u16; cw * ch]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_v_dense, fctx, ); let mut pred_v = vec![0u16; cside * cside]; for row in 0..ch { pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]); } let (luma_grid, u_grid, v_grid); // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour // contexts per transform unit -- the replay after this fn's end-of-block // record restores them (the record itself re-stamps both planes with ONE // composed state, class `override-slot-on-one-arm`). let mut mu_chroma = false; if skip { // No residual syntax at all: the prediction IS the block. Strides are // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun). push_mc_rect( 0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * side], fctx, ); push_mc_rect( 1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * cside], fctx, ); push_mc_rect( 2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * cside], fctx, ); if let Some(ls) = leaves.as_ref() { // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4 // grid before it looks at `skip`; the skipped block still zeroes // its entropy-band footprint over every unit (libaom // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) -- // the same arm [`decode_intrabc_rect`]'s loss64 merge added. hit!(SKIP_LOSSLESS_BAND_RESET_HITS); for &(row, col, tw, th) in ls { neighbours.record_mi_luma_rect( (mi_r + row, mi_c + col), tw, th, &ZERO_RESIDUAL[..tw * th], ); } } luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(cside * cside); v_grid = Grid::Zero(cside * cside); } else { let leaves = leaves .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape"); // libaom `get_transform_size`'s split override applies to LUMA only, // per leaf -- each unit's own transform edges get filtered // ([`decode_intrabc_rect`]'s P2, the proven inter path's step). for &(row, col, tw, th) in leaves.iter() { neighbours.fill_lf_grid_leaf_luma( (mi_r + row, mi_c + col), tw / MI, th / MI, tw as u8, th as u8, ); } let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); let mut u_units: Vec = Vec::new(); let mut v_units: Vec = Vec::new(); let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new(); // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose // top-left sample is outside the frame codes nothing. let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c)); let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r)); // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]). let (order, _mu_reordered) = mu_chunk_order(&leaves, side); for (pos, &idx) in order.iter().enumerate() { let (row, col, tw, th) = leaves[idx]; debug_assert_eq!( tw, th, "a square TX_64X64 tree root only yields square leaves" ); let tu_mi = (mi_r + row, mi_c + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); if tu_px >= y.true_width || tu_py >= y.true_height { continue; } let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); let scan = default_scan(tw.min(32)); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI); let (tu_grid, tu_tx_type) = read_inter_plane( dec, cdfs, inter_txbset_for(tw, reduced), &scan, 0, neighbours.around_mi(tu_mi, tw)[0], 0, y, tu_px, tu_py, tw, base_q_idx, tu_pred, None, Some(tu_skip_ctx), fctx, )?; leaf_tx_types.push((row, col, tw, th, tu_tx_type)); neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid); // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64 // mu chunk before the next one starts: once this chunk's leaves // are done, its chroma is read immediately (the inter 128 path's // interleave). let chunk = (row / 16, col / 16); let done = pos + 1 == order.len() || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk; if done { let (cr, cc) = chunk; // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster // within the chunk, plane-major inside the chunk. let cu_tx = 32usize; // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma // plane block is 32x64 there), four at 4:4:4. The old // `chunk_chroma = cside * 64 / side` walked a // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both // axes: at 4:2:2 it read HALF the chroma units of a chunk // (one 32x32 at the chunk's top-left instead of two), left // the chunk's lower 32 chroma rows with no residual at all, // and stamped every unit's entropy context over a 16x16-mi // luma span instead of 16x8. The same defect and the same // per-axis repair as `decode_inter_block`'s // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock, // witnessed on `422_sb128_3f.obu`). let chunk_chroma_w = (64usize) >> ss_x(fctx); let chunk_chroma_h = (64usize) >> ss_y(fctx); // The unit's own footprint on the LUMA mi grid, per axis: // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0, // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and // `record_mi_chroma` stamp exactly the unit's own cells. let unit_luma_w = cu_tx << ss_x(fctx); let unit_luma_h = cu_tx << ss_y(fctx); INTRABC_128RECT_CHUNK_SHAPE.with(|c| { c.set((chunk_chroma_w << 8) | chunk_chroma_h); }); let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16)); let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16)); let units_x = chunk_w_mi / (unit_luma_w / MI); let units_y = chunk_h_mi / (unit_luma_h / MI); if lossless(fctx) { // TX_4X4 chroma units over this chunk (lane-lossless2's // walk, shared with the inter 128 path). read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, Pred::Inline(&pred_u, cside), Pred::Inline(&pred_v, cside), (mi_r, mi_c), (cpx, cpy), (cc * chunk_chroma_w, cr * chunk_chroma_h), (chunk_chroma_w, chunk_chroma_h), (cw, ch), cside, 0, base_q_idx, &mut u_units, &mut v_units, fctx, )?; // lane-av1-ibcrect: read_inter_chroma_lossless stamped // every TX_4X4 unit's own context (`record_mi_chroma` // inside the walk) -- the end-of-block record below must // not overwrite them with the composed grid (the inter // 128 path sets the same flag on this arm). mu_chroma = true; continue; } let cu_scan = default_scan(cu_tx); for plane_idx in 1..3 { let (src, buf) = if plane_idx == 1 { (Pred::Inline(&pred_u, cside), &mut *u) } else { (Pred::Inline(&pred_v, cside), &mut *v) }; for ur in 0..units_y { for uc in 0..units_x { let unit_mi = ( mi_r + cr * 16 + ur * (unit_luma_h / MI), mi_c + cc * 16 + uc * (unit_luma_w / MI), ); // Per unit, AFTER the earlier units' stamps: this // unit's coefficient context must see them. let cu_around = neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h); if crate::envflags::env_flag!("EC_ECDUMP") { for p in 1..3 { let ab: Vec = (0..unit_luma_w / MI) .map(|k| { format!( "{:?}/{}", neighbours.above[unit_mi.1 + k][p].dc, neighbours.above[unit_mi.1 + k][p].level ) }) .collect(); let lf: Vec = (0..unit_luma_h / MI) .map(|k| { format!( "{:?}/{}", neighbours.left[unit_mi.0 + k][p].dc, neighbours.left[unit_mi.0 + k][p].level ) }) .collect(); eprintln!( "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]", cu_around[p].0, cu_around[p].1, cu_around[p].2, ab.join(","), lf.join(",") ); } } let (cu_x, cu_y) = ( cpx + cc * chunk_chroma_w + uc * cu_tx, cpy + cr * chunk_chroma_h + ur * cu_tx, ); // `av1_get_tx_type` (blockd.h:1291): an inter // block's chroma unit never codes a tx_type; it // inherits the coded type of the luma leaf // covering its own quadrant (all of this chunk's // leaves are read by now). let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c); let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi); // The prediction window is the block's own square // `cside` buffer with the unit's true per-axis // position inside it. let cu_pred = src.offset( (cr * chunk_chroma_h + ur * cu_tx) * cside + cc * chunk_chroma_w + uc * cu_tx, ); let cu_grid = read_inter_plane( dec, cdfs, TxbSet::Chroma32, &cu_scan, plane_idx, cu_around[plane_idx], 0, buf, cu_x, cu_y, cu_tx, base_q_idx, cu_pred, Some(covering.unwrap_or(TxType::DctDct)), Some(3), fctx, )? .0; // Immediately, so the NEXT unit reads this one's // coefficient context. neighbours.record_mi_chroma( unit_mi, unit_luma_w, unit_luma_h, plane_idx, &cu_grid, ); if crate::envflags::env_flag!("EC_ECDUMP") { let st = crate::decode::neighbour_state(&cu_grid); eprintln!( "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})", st.dc, st.level ); } hit!(CHROMA_SPLIT_TX_HITS); INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1)); // lane-av1-ibcrect: per-unit chroma context -- the // end-of-block record's composed-grid re-stamp // must not stand (replayed below). mu_chroma = true; let dst = mu_units( if plane_idx == 1 { &mut u_units } else { &mut v_units }, cside * cside, ); for rr in 0..cu_tx { let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside + cc * chunk_chroma_w + uc * cu_tx; dst[start..start + cu_tx] .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]); } } } } } } // The block-level luma bands were recorded per leaf above; the // composed chroma grids carry every unit in place. luma_grid = Grid::Zero(side * side); u_grid = if u_units.is_empty() { Grid::Zero(cside * cside) } else { Grid::Own(std::mem::take(&mut u_units)) }; v_grid = if v_units.is_empty() { Grid::Zero(cside * cside) } else { Grid::Own(std::mem::take(&mut v_units)) }; } // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a // neighbour reads a mode, zeroed palette state, the skip grid, the // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them), // and the DV into the intrabc mi grid. if skip { neighbours.record_rect_mi( (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid[..], &u_grid[..], &v_grid[..]], ); } else { neighbours.record_split_luma_rect_mi( (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid[..], &v_grid[..]], ); } // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps // both planes with ONE `neighbour_state(composed_grid)` over the whole // span -- level = the SUM of every unit's levels and dc = the top-left // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128 // inter block: the next block read a stale `dc_sign_ctx` one row low). // Measured on this shape: the 128x64 block at mi(64,32) of the // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared // into chunk-0's cells and the block below read `txb_skip` off the sum. // Replay every coded unit's own state after the record, in mu-chunk order // so a later unit still wins over an earlier one on the shared seam cells // (the composed construction `mu_chroma_units` uses, transcribed here). if mu_chroma { let cu = if lossless(fctx) { 4usize } else { 32usize }; // The unit's own footprint on the LUMA mi grid (the chroma context // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2. let unit_luma_w = cu << ss_x(fctx); let unit_luma_h = cu << ss_y(fctx); // A 64x64 mu chunk's chroma plane block is PER-AXIS // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR); // `av1_get_max_uv_txsize` caps the unit at 32 on each axis. let chunk_chroma_w = (64usize) >> ss_x(fctx); let chunk_chroma_h = (64usize) >> ss_y(fctx); if lossless(fctx) { // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols` // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not // enumerate it, and this arm re-stamps only the 4x4 at each // chunk's top-left with a 2x2-mi span. The twin // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter) // instead raster-walks the WHOLE plane block at `cu` steps, and // that is the correct shape here too. It is left as-is on purpose: // it is a 4:2:0 defect, not a subsampling square-cut, and fixing // it would change 4:2:0 LOSSLESS output -- which this lane's // byte-identity requirement forbids doing on an unverified // reconstruction. Measured unreachability: this arm is entered // 0 times by the whole `lossless` and `intrabc` gate battery // (temporary env-gated counter in the arm). Unblock: one // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root // intrabc strip (`--lossless=1 --sb-size=128 // --min-partition-size=64 --enable-rect-partitions=1 // --enable-intrabc=1` over near-match screen content). let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1)); for cr in 0..rows { for cc in 0..cols { let unit_mi = ( mi_r + cr * (unit_luma_h / MI), mi_c + cc * (unit_luma_w / MI), ); for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] { let mut unit = Vec::with_capacity(cu * cu); for rr in 0..cu { let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w; unit.extend_from_slice(&grid[start..start + cu]); } neighbours.record_mi_chroma( unit_mi, unit_luma_w, unit_luma_h, plane_idx, &unit, ); } } } } else { // The chunk count on each axis, then EVERY unit inside each // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell // span, and its own quadrant of the composed plane grid -- the // twin's loop (decode_inter_block's `mu_chroma_units`, // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count // mu CHUNKS in `rows`/`cols` and then step the mi origin and read // the grid PER UNIT, which only agrees when a chunk holds exactly // one unit. At 4:2:0 (`chunk_chroma == cu`) it is // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds // 2 or 4, so the old body reached only the first of the stacked // units and the rest of the chunk kept the composed-grid smearing // this replay exists to undo. A unit the frame edge clipped codes // nothing and carries no composed samples beyond the clip, so it // replays as the zero state exactly like libaom's uncoded unit. let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu); let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1)); for cr in 0..rows { for cc in 0..cols { for kr in 0..ur { for kc in 0..uc { let unit_mi = ( mi_r + (cr * 64 + kr * unit_luma_h) / MI, mi_c + (cc * 64 + kc * unit_luma_w) / MI, ); let (cy, cx) = (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu); for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] { let mut unit = Vec::with_capacity(cu * cu); for rr in 0..cu { let start = (cy + rr) * cside + cx; unit.extend_from_slice(&grid[start..start + cu]); } neighbours.record_mi_chroma( unit_mi, unit_luma_w, unit_luma_h, plane_idx, &unit, ); } } } } } } } neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); // lane-av1oddheightfork3: see `decode_intrabc_rect`'s call -- the tree // published the bands, so no whole-footprint publish here. neighbours.fill_lf_grid_rect_after_vartx( (mi_r, mi_c), bw / MI, bh / MI, bw.min(64) as u8, bh.min(64) as u8, 0, fctx, ); record_intrabc_mi_rect( mi_r, mi_c, bw / MI, bh / MI, Some((dv_row, dv_col)), neighbours, fctx, ); 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, intrabc, ) = 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, )?; if let Some((dv_row, dv_col)) = intrabc { return decode_intrabc_rect( dec, cdfs, neighbours, (r * (SUB / MI), c * (SUB / MI)), (bw, bh), skip, (dv_row, dv_col), y, u, v, base_q_idx, 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, fctx); // 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. // lane-av1mixloss: the lossless-segment early return // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment // rect block codes no depth symbol here either (class sweep of the sub8 // leaf's fix). let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an // intra-only frame publishes them from every block too // ([`Neighbours::fill_lf_grid_rect`]). 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 = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); 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-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame // reads the `TXFM_CONTEXT` bands -- 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, fctx), (bw, bh), fctx, ); if depth != 0 || lossless(fctx) { 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, fctx); 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 >> ss_x(fctx), py >> ss_y(fctx)); let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); 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: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 }; // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis). let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) { (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16), (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32), (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8), (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16), // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the // set any 16x16 chroma plane reads); a 16x32 strip's chroma is // 8x32, whose entropy set is the 16x16 one and whose DCT-only // default follows the >=32 rule below -- the same pairing the // (8,32) row of [`decode_rect_split`]'s chroma table proves. At // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row // is reachable there. (16, 16) => (TxbSet::Chroma16, default_scan(16)), (8, 32) => (TxbSet::Chroma16, &SCAN_8X32), _ => { return Err(unsupported( "a rectangular chroma transform whose size has no coefficient table", )); } }; let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 { TxType::DctDct } else { default_intra_tx_type(uv_predict_mode as u8) }; // 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-depth 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. { // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the // strip's chroma is a square (side/2, side) block whose above cells // spread over `side` LUMA mi columns, so the per-mi rect gather // double-counts every chroma column's whole-unit dc sign. Measured on // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4 // transform of the 32x16 strip at mi(68,16) reads its DC sign from // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of // 45260 whose pre-state, bit position and symbol all match and only // the CDF row differs, and the first divergence in the EC_SYMR // sequence (all 45259 reads before it pair exactly). Luma keeps the // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim. let mut around = neighbours.around_rect(at, bw, bh); if ss_x(fctx) == 1 && ss_y(fctx) == 0 { let c2 = neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh); around[1] = c2[1]; around[2] = c2[2]; } 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, 0, )?; 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, block_iqmatrix(fctx, 0, bw, bh, 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 = chroma_default_tx; 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); let (u_levels, u_tx_type) = read_chroma_coeffs_rect( dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, dc_sign_ctx(around[1].2), u_default_tx, fctx, 1, )?; 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, block_iqmatrix(fctx, 1, chroma_w, chroma_h, 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 = chroma_default_tx; 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); let (v_levels, v_tx_type) = read_chroma_coeffs_rect( dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, dc_sign_ctx(around[2].2), v_default_tx, fctx, 2, )?; 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, block_iqmatrix(fctx, 2, chroma_w, chroma_h, 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`) at 4:2:0 -- an 8x8 *square* chroma /// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e: /// half-width, unhalved height), 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, intrabc, ) = 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, )?; if let Some((dv_row, dv_col)) = intrabc { decode_intrabc_rect( dec, cdfs, neighbours, leaf_mi, (bw, bh), skip, (dv_row, dv_col), y, u, v, base_q_idx, fctx, )?; return Ok(DC_PRED); } // 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, fctx); let depth = if tx_select && !lossless(fctx) { // 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. // lane-av1mixloss: libaom `read_tx_size`'s first line // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4). // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours // read `tx_size_cat1` (rng 55700->49918) where the oracle's next // read was the leaf's own txb_skip. let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx); // 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). 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={}", leaf_mi.0, leaf_mi.1, dec.debug_state().0 ); } d } else { 0 }; // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`]. publish_txfm_bands_if_in_inter( neighbours, leaf_mi, depth_to_tx_wh(bw, bh, depth, fctx), (bw, bh), fctx, ); if depth != 0 || lossless(fctx) { // 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, fctx); 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 >> ss_x(fctx), py >> ss_y(fctx)); let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); 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`). // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` + // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`). let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0; let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 { if bw == 16 { (&SCAN_16X8, &SCAN_16X8) } else { (&SCAN_8X16, &SCAN_8X16) } } else if chroma_422 { if bw == 16 { (&SCAN_16X8, default_scan(8)) } else { (&SCAN_8X16, default_scan(8)) } } else if bw == 16 { (&SCAN_16X8, &SCAN_8X4) } else { (&SCAN_8X16, &SCAN_4X8) }; let chroma_rect_set = if ss_x(fctx) == 0 { TxbSet::ChromaRect16x8 } else if chroma_422 { TxbSet::Chroma8 } else { TxbSet::ChromaRect8x4 }; // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE // (side/2, side) block, so `side` chroma 4-px cells above it spread // over `side` LUMA mi columns -- one chroma column per PAIR of luma // mi cells, and both carry the covering unit's whole-unit dc sign. // The per-mi rect gather therefore double-counts every chroma // column's sign. `around_mi_422_chroma`'s every-second above-cell // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma // gather in this file already routes through it (see the gate at this // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a // negative vote (`dc_sign_cdf[1]`), which is the first bit-position // divergence in the frame (the bit offset is a clean constant through // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim. let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh); if chroma_422 { let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh); around[1] = c[1]; around[2] = c[2]; } 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, 0, )?; 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), block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type, block_iqmatrix(fctx, 0, bw, bh, 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(chroma_rect_set, uv_predict_mode); let (u_l, u_tx_type) = read_chroma_coeffs_rect( dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, dc_sign_ctx(around[1].2), u_default_tx, fctx, 1, )?; u_levels = u_l; 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, block_iqmatrix(fctx, 1, chroma_w, chroma_h, 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(chroma_rect_set, uv_predict_mode); let (v_l, v_tx_type) = read_chroma_coeffs_rect( dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, dc_sign_ctx(around[2].2), v_default_tx, fctx, 2, )?; v_levels = v_l; 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, block_iqmatrix(fctx, 2, chroma_w, chroma_h, 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, intrabc, ) = 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, )?; if let Some((dv_row, dv_col)) = intrabc { decode_intrabc_rect( dec, cdfs, neighbours, strip_mi, (bw, bh), skip, (dv_row, dv_col), y, u, v, base_q_idx, fctx, )?; return Ok((DC_PRED, DC_PRED)); } // 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, fctx); 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 }; // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no // depth symbol here either (class sweep of the sub8 leaf's fix). let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an // intra-only frame publishes them from every block too // ([`Neighbours::fill_lf_grid_rect`]). 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 = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); 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, fctx), (bw, bh), fctx, ); if depth != 0 || lossless(fctx) { // 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, fctx); // 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 >> ss_x(fctx), py >> ss_y(fctx)); let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); // lane-av1-444: the strip's chroma shape follows the subsampling. // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` = // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set, // `TxbSet::Chroma16`). The caller set is closed -- this reader only // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0 // and 1/1 only -- so the table is exhaustive. let chroma422_rect32 = (chroma_w, chroma_h) == (4, 32) && ss_x(fctx) == 1 && ss_y(fctx) == 0; let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) { (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]), (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]), (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]), (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]), // lane-av1-422: a 4:2:2 1:4 strip halves only the width, so the // landscape leaves (32x8, 16x4 luma) code their chroma as the RECT // (16,8)/(8,4) -- the same TxbSet/scan pair the (16,8)/(8,4) rows of // [`decode_rect_split`]'s chroma table use. // lane-av1-422p: the PORTRAIT leaf occurs too -- the pinned // fixture's frame 2 carries an 8x32 strip at ss(1,0), whose (4, 32) // chroma block `ss_size_lookup[BLOCK_8X32][1][0]` marks // BLOCK_INVALID (255, enums.h). BLOCK_INVALID does not mean // "uncodable": `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` // OUT OF BOUNDS there, the byte at +255 in the pinned Release oracle // is 0x05 = TX_4X8 (the `decode_token_recon_block` copy at // 0xc0d030, objdump-measured), and `av1_get_adjusted_tx_size` has no // TX_4X8 case. libaom HAS the transform, so the shape CHUNKS (the // `chroma422_rect32` arm below) into FOUR stacked TX_4X8 units per // plane (`tx_size_high_unit[TX_4X8] = 2`: blk_row 0, 2, 4, 6) // instead of refusing; no coefficient-table row is added, because // BLOCK_4X32 is not a table libaom has. 4:2:0 and 4:4:4 never land // here (their 8x32 strips read (4, 16) and (8, 32)), so the row is // 4:2:2-only. (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8[..]), (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]), // lane-av1-422p: the units' own set/scan -- the whole-rect read // below never sees this row, the `chroma422_rect32` arm chunks // first. Anything else is still a named-lane gap. (4, 32) if ss_x(fctx) == 1 && ss_y(fctx) == 0 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]), _ => unreachable!("decode_block_rect4 chroma shape set is closed: {chroma_w}x{chroma_h}"), }; let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 }; 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 if chroma422_rect32 { // lane-av1-422p: the (4, 32) plane as FOUR TX_4X8 units per plane, // plane-major (every U unit, then every V) -- the walk the pinned // oracle's `decode_token_recon_block` makes for the BLOCK_INVALID // plane block: TX_4X8, so stepr = `tx_size_high_unit[TX_4X8]` = 2 // 4-px rows and stepc = 1, unit rows at chroma y 0, 8, 16, 24. // Luma is the same single TX_8X32 rect the general arm reads. 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, 0, )?; 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, block_iqmatrix(fctx, 0, bw, bh, 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, ); // CfL parameters are computed ONCE per block over the strip's luma // (`are_parameters_computed`) and shared by all four units, as in // every other chunk arm. let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); let mut unit_grids: Vec<((usize, usize), usize, Grid)> = Vec::new(); for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] { for unit_row in 0..4usize { let unit_mi = (mi_r + unit_row * 2, mi_c); let unit_reach = tu_reach_rect( bw, bh, 0, unit_row * 8, 8, 8, reach, px, py, y.width, y.height, fctx, ); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx); } // Each unit is read and recorded IMMEDIATELY: unit row 0's // `txb_skip_ctx` still sees the real above/left neighbour // states, a lower unit sees this block's own upper unit's // (libaom's per-unit `set_entropy_context`), and the lower // unit predicts off the upper one's reconstructed samples. let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8); let unit_grid = read_rect_chroma_unit( dec, cdfs, TxbSet::ChromaRect8x4, &SCAN_4X8, 4, 8, plane, chroma_around[plane], uv_predict_mode, angle_delta_uv, unit_reach, buf, cpx, cpy + unit_row * 8, base_q_idx, // `get_txb_ctx_general`'s chroma branch // (txb_common.h): plane_bsize is BLOCK_INVALID (255) // here, `num_pels_log2_lookup[255]` = 255 (the +255 // byte of the decodetxb copy at 0xc0de70, // objdump-measured) exceeds `BLOCK_4X8`'s 5, so the // ctx_offset is 10 -- the port's offset-7-first // `txb_skip_chroma_8` stores the offset-10 rows at // rows 3..6, hence +3. Some(3), alpha .zip(ac) .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), smooth_neighbor_uv, fctx, )?; neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid); unit_grids.push((unit_mi, plane, unit_grid)); } } // The whole-block stamp rewrites the chroma cells ONE state wide, // which would erase the unit boundary the next block reads (class // `override-slot-on-one-arm`), so it carries zero chroma grids and // the per-unit writes replay after it. Its luma cells and side // spans are this arm's own bookkeeping. let zero_chroma = vec![0i32; chroma_w * chroma_h]; neighbours.record_mi_rect( (mi_r, mi_c), bw, bh, &[&luma_levels[..], &zero_chroma[..], &zero_chroma[..]], ); for (unit_mi, plane, grid) in &unit_grids { neighbours.record_mi_chroma(*unit_mi, 8, 8, *plane, grid); } 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)); } 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, 0, )?; let mut planes = Vec::with_capacity(2); for plane in 1..3 { // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type // stands only while it is a member of this tx size's set; a // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32, // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps // to DCT_DCT there, and ADST is undefined at widths above 16. let default_tx = if chroma_w.max(chroma_h) >= 32 { TxType::DctDct } else { 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(chroma_set, uv_predict_mode); let (levels, tx_type) = read_chroma_coeffs_rect( dec, &mut coding, chroma_scan, chroma_w, chroma_h, skip_ctx, dc_sign_ctx(around[plane].2), default_tx, fctx, plane, )?; 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, block_iqmatrix(fctx, 0, bw, bh, 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, block_iqmatrix(fctx, plane, chroma_w, chroma_h, 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 chroma422_rect32 { // lane-av1-422p: `predict_and_reconstruct_intra_block` (decodeframe.c // ~1000) predicts EVERY unit regardless of `skip_txfm`, so the skip // arm walks the same four TX_4X8 units per plane -- the lower unit // predicts off the upper one's predicted samples. No coefficients // are coded; the tail's whole-block zero stamp below is the state // libaom's `set_entropy_context` leaves. for (plane, _buf) in [(1usize, &mut *u), (2usize, &mut *v)] { for unit_row in 0..4usize { let unit_reach = tu_reach_rect( bw, bh, 0, unit_row * 8, 8, 8, reach, px, py, y.width, y.height, fctx, ); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx); } push_intra_rect( plane, cpx, cpy + unit_row * 8, 4, 8, uv_predict_mode, angle_delta_uv, unit_reach, &ZERO_RESIDUAL[..4 * 8], alpha .zip(ac) .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), None, smooth_neighbor_uv, fctx, ); } } } else { 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) }; // lane-av1-444: at 4:4:4 every strip is its own chroma reference // (no mi-parity test at ss 0/0, and the strip's own chroma block is // already >= 4x4) -- there is no 4:2:0 pair to close. // lane-av1-422o: the parity rule is per axis, straight out of // `is_chroma_reference`: a HORZ 16x4 strip (1 mi tall) keeps the // `ss_y == 0 -> every strip a reference` row rule, but a VERT 4x16 // strip (1 mi wide) keeps the COLUMN clause `(mi_col & 1) || !(bw & // 1) || !ss_x`, which with bw == 1 mi reduces to `mi_col odd` for // every ss_x == 1 format -- the ODD strip closes the pair and reads // the chroma, exactly like 4:2:0. (VERT_4 partitions start on an // even mi_col, so `i % 2 == 1` is that clause.) let has_chroma = i % 2 == 1 || (horz && ss_y(fctx) == 0) || (!horz && ss_x(fctx) == 0); 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)`. /// Intrabc reconstruction for a rect strip that OWNS its chroma /// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that /// pair goes through [`decode_rect4_16_intrabc`]. /// /// This is the same control flow as the unmerged lane's `decode_intrabc_rect` /// (predict once, then one residual per transform unit on the INTER sets, /// chroma inherits luma's `tx_type`), written against the helpers that exist /// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The /// merge with lane-av1-intrabc should keep one of the two bodies; the call /// shape is the same. #[allow(clippy::too_many_arguments)] fn decode_intrabc_owned_rect( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, (mi_r, mi_c): (usize, usize), (bw, bh): (usize, usize), skip: bool, (dv_row, dv_col): (i32, i32), y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let _ = base_q_idx; let (px, py) = (mi_c * MI, mi_r * MI); // lane-av1chromarect: libaom does NOT halve a 128-root intra-BC strip's // chroma plane block. `av1_get_max_uv_txsize` (blockd.h:1372) is // `max_txsize_rect_lookup[get_plane_block_size(bsize, ss_x, ss_y)]` run // through `av1_get_adjusted_tx_size`, and `get_plane_block_size` is // `ss_size_lookup[bsize]` -- at 4:4:4 the chroma plane block is the block's // OWN footprint, so the extent below and the eight chroma MV origin pairs // that follow must be `>> ss_x` / `>> ss_y`, not `/ 2`. At 4:2:0 // (`ss_x == ss_y == 1`) the two forms are the same arithmetic. // MEASURED on the 4:4:4 LOSSY witness `fixtures/r512.obu` (6948 B, 3 // frames, 5 strips through this function): with the halving, frame 0 // diverges from the aomdec oracle in 166229 Y / 155383 U / 153498 V // samples and both later frames keep luma byte-exact while 74708 U + // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is // what makes this a chroma-sizing defect and not a block-geometry one. // Re-measured by this lane; see lanes/av1chromarect.report.md. if crate::envflags::env_flag!("EC_HALVSWEEP") { eprintln!("EC_HALV ibc_owned mi=({mi_r},{mi_c}) bw={bw} bh={bh} skip={skip}"); } let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); let side = bw.max(bh); let cside = cw.max(ch); if ss_x(fctx) == 0 && ss_y(fctx) == 0 { hit!(IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS); } let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get); fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); // `read_block_tx_size_rect` keys on this cell. A key frame forces it // false; the real bit is the caller's `tx_select`. Restored before return. fctx.tx_select_inter.with(|c| c.set(tx_select)); let restore = ReducedTxRestore { fctx, saved_reduced, saved_tx, }; flush_recon(fctx, y, u, v); let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx); let pred_u = predict_intrabc_window(u, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx); let pred_v = predict_intrabc_window(v, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx); let mi_cols = 2 * y.true_width.div_ceil(8); let mi_rows = 2 * y.true_height.div_ceil(8); let leaves = read_block_tx_size_rect( dec, cdfs, neighbours, (mi_r, mi_c), (bw, bh), (mi_cols, mi_rows), skip, fctx, )?; let mut luma_tx_type = TxType::DctDct; let luma_grid; let u_grid; let v_grid; if skip { // `reconstruct_mc_rect` indexes the residual at the square stride. // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136). push_mc_rect( 0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx, ); push_mc_rect( 1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * ch], fctx, ); push_mc_rect( 2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * ch], fctx, ); if let Some(ls) = leaves.as_ref() { // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`, // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its // whole entropy-band footprint. The non-skip arm below writes // those bands per transform unit and the tail's // `record_split_luma_rect_mi` writes chroma only, so without // this walk a skipped strip whose `leaves` resolved (every // lossless frame -- `read_block_tx_size_rect`'s lossless arm // returns the 4x4 grid before it looks at `skip`) leaked the // PREVIOUS occupant's luma bands into the next block's // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128 // stream left a stale 7 in left[48] and mi(48,68)'s first // transform unit read `txb_skip_ctx` 3 where aomdec reads 1). hit!(SKIP_LOSSLESS_BAND_RESET_HITS); for &(row, col, tw, th) in ls { neighbours.record_mi_luma_rect( (mi_r + row, mi_c + col), tw, th, &ZERO_RESIDUAL[..tw * th], ); } } luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(cside * cside); v_grid = Grid::Zero(cside * cside); } else if let Some(ls) = leaves.as_ref() { let mut leaf_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::with_capacity(ls.len()); for (idx, &(row, col, tw, th)) in ls.iter().enumerate() { let tu_mi = (mi_r + row, mi_c + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); let (g, tt) = if tw == th { read_inter_plane( dec, cdfs, inter_txbset_for(tw, reduced_tx_set), &default_scan(tw.min(32)), 0, neighbours.around_mi(tu_mi, tw)[0], 0, y, tu_px, tu_py, tw, base_q_idx, tu_pred, None, Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)), fctx, )? } else { 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], 0, y, tu_px, tu_py, tu_pred, None, Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)), fctx, )? }; leaf_types.push((row, col, tw, th, tt)); if idx == 0 { luma_tx_type = tt; } neighbours.record_mi_luma_rect(tu_mi, tw, th, &g); if tw != th { neighbours.fill_lf_grid_leaf_luma( (tu_mi.0, tu_mi.1), tw / MI, th / MI, tw as u8, th as u8, ); } } luma_grid = Grid::Zero(side * side); if cw.min(32) != cw || ch.min(32) != ch { // lane-av1chromarect: more than one chroma transform unit (the // 4:4:4 32x64/64x32 plane block). See the helper. let (ug, vg) = read_intrabc_rect_chroma_split( dec, cdfs, neighbours, (mi_r, mi_c), (cpx, cpy), (cw, ch), cside, &pred_u, &pred_v, &leaf_types, luma_tx_type, u, v, fctx, )?; u_grid = ug; v_grid = vg; } else { let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); let (ug, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, )?; let (vg, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, )?; u_grid = ug; v_grid = vg; } } else { let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); let (g, tt) = read_inter_plane_rect( dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0, y, px, py, Pred::Inline(&pred_y, side), None, None, fctx, )?; luma_tx_type = tt; luma_grid = g; if cw.min(32) != cw || ch.min(32) != ch { // lane-av1chromarect: more than one chroma transform unit (the // 4:4:4 32x64/64x32 plane block). See the helper. let (ug, vg) = read_intrabc_rect_chroma_split( dec, cdfs, neighbours, (mi_r, mi_c), (cpx, cpy), (cw, ch), cside, &pred_u, &pred_v, &[], luma_tx_type, u, v, fctx, )?; u_grid = ug; v_grid = vg; } else { let (ug, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, )?; let (vg, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, )?; u_grid = ug; v_grid = vg; } } drop(restore); // lane-av1chromarect: when the chroma plane block was walked as SEVERAL // transform units, each unit stamped its own span through // `record_mi_chroma` and the whole-block stamp below would overwrite them // with one state (class `override-slot-on-one-arm`). libaom keeps the // per-unit above/left contexts distinct; the next block's first unit // reads them. // `!skip` matters: a SKIPPED strip reads no chroma unit at all (its whole // chroma plane block is one `push_mc_rect` of `ZERO_RESIDUAL`), so no // per-unit `record_mi_chroma` ran and the whole-block chroma stamp below // is still the only one that happens. let chroma_split_units = !skip && (cw.min(32) != cw || ch.min(32) != ch); if leaves.is_some() { if chroma_split_units { neighbours.record_split_luma_rect_mi_modes((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED); } else { neighbours.record_split_luma_rect_mi( (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid], ); } } else if chroma_split_units { neighbours.record_rect_mi_luma_only((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &luma_grid); } else { neighbours.record_rect_mi( (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid], ); } neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); // lane-av1oddheightfork3: see `decode_intrabc_rect`'s call -- the tree // published the bands, so no whole-footprint publish here. neighbours.fill_lf_grid_rect_after_vartx( (mi_r, mi_c), bw / MI, bh / MI, bw.min(64) as u8, bh.min(64) as u8, 0, fctx, ); record_intrabc_mi_rect( mi_r, mi_c, bw / MI, bh / MI, Some((dv_row, dv_col)), neighbours, fctx, ); let _ = luma_tx_type; Ok(()) } /// The chroma plane block of a 128-root intra-BC HORZ/VERT strip when that /// plane block needs MORE THAN ONE transform unit -- the 4:4:4 cell, and the /// 4:2:0 cell of a strip with a 128-px axis. /// /// libaom never forms a 64-point CHROMA transform. `get_vartx_max_txsize` /// (blockd.h:1447) returns `av1_get_adjusted_tx_size(max_txsize_rect_lookup /// [plane_bsize])` and `av1_get_adjusted_tx_size` maps `TX_32X64`/`TX_64X32` /// to `TX_32X32`; `decode_token_recon_block` (decodeframe.c:994-1004) then /// steps the plane block by that size's mi units, and /// `decode_reconstruct_tx`'s `tx_size == plane_tx_size || plane` arm never /// recurses for chroma -- the same statement from the other side. So a 4:4:4 /// 32x64 chroma plane block is TWO stacked `TX_32X32` units, each with its /// own eob, its own scan and its own coefficient context, NOT one 32x64 unit /// whose coded corner happens to be 32x32: `av1_get_max_eob`'s 64-axis /// truncation is a LUMA rule, and a chroma plane block is never 64 points /// long to begin with. /// /// That is exactly the tiling [`read_inter_rect_chroma`] implements /// (`(write_chroma_w.min(32), write_chroma_h.min(32))` and the `nx * ny` /// walk); this is the same walk for a caller that keeps its own grid /// assembly and neighbour recording. The single-unit case is deliberately /// NOT routed through here, so at 4:2:0 and at every 4:4:4 shape below 64 /// the caller keeps its own one-unit read verbatim. #[allow(clippy::too_many_arguments)] fn read_intrabc_rect_chroma_split( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, (mi_r, mi_c): (usize, usize), (cpx, cpy): (usize, usize), (cw, ch): (usize, usize), cside: usize, pred_u: &[u16], pred_v: &[u16], leaf_tx_types: &[(usize, usize, usize, usize, TxType)], luma_tx_type: TxType, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, Grid)> { let (uw, uh) = (cw.min(32), ch.min(32)); let (nx, ny) = (cw / uw, ch / uh); let set = rect_inter_chroma_set(uw, uh)?; let assembled_h = ch.max(cside); let mut assembled: [Vec; 2] = [ vec![0i32; cside * assembled_h], vec![0i32; cside * assembled_h], ]; for plane_idx in 1..=2 { let (src, buf) = if plane_idx == 1 { (pred_u, &mut *u) } else { (pred_v, &mut *v) }; for cu_row in 0..ny { for cu_col in 0..nx { let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx)); let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI)); // lane-av1422llintra: the same ss (1, 0) above-column // double-count as the lossless walk at 12735 -- one chroma // column spans two luma mi columns and libaom reads one. // Identical at 4:2:0 and 4:4:4, where the plane block is // square. let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 { neighbours.around_mi_422_chroma(cu_mi, span_x, span_y) } else { neighbours.around_mi_rect(cu_mi, span_x, span_y) }; let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh); let cu_pred = Pred::Inline(src, cside).offset(cu_row * uh * cside + cu_col * uw); // libaom's `av1_get_tx_type` (blockd.h:1287) reads // `xd->tx_type_map` at the chroma unit's OWN position scaled // back to luma, so a unit sitting over a luma leaf that coded // nothing takes that leaf's stamp, not the block-level one. let rel_mi = (cu_mi.0 - mi_r, cu_mi.1 - mi_c); let inherit_tx_type = covering_leaf_tx_type(leaf_tx_types, rel_mi).or(Some(luma_tx_type)); let cu_grid = read_inter_plane_rect( dec, cdfs, set, (uw, uh), cside, plane_idx, cu_around[plane_idx], 0, buf, cu_x, cu_y, cu_pred, inherit_tx_type, // `get_txb_ctx`: plus 10 when the plane block is bigger // than the transform -- the same offset-3 convention // `read_inter_rect_chroma` passes on this arm. Some(3), fctx, )? .0; // Immediately, so the next unit of this block reads this one's // coefficient context (libaom updates the chroma above/left // contexts per unit). neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid); let dst = &mut assembled[plane_idx - 1]; for rr in 0..uh { let start = (cu_row * uh + rr) * cside + cu_col * uw; dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]); } } } } let [ug, vg] = assembled; Ok((Grid::Own(ug), Grid::Own(vg))) } fn predict_intrabc_window( plane: &PlaneBuf<'_>, px: usize, py: usize, w: usize, h: usize, dv_col: i32, dv_row: i32, luma: bool, stride: usize, fctx: &crate::decode::FrameCtx, ) -> Vec { let mut dense = vec![0u16; w * h]; mc::predict_with_filter( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }), mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }), w, h, mc::InterpFilterKind::Bilinear, &mut dense, fctx, ); let mut laid = vec![0u16; stride * stride]; for row in 0..h { laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]); } laid } struct ReducedTxRestore<'a> { fctx: &'a crate::decode::FrameCtx, saved_reduced: bool, saved_tx: bool, } impl Drop for ReducedTxRestore<'_> { fn drop(&mut self) { self.fctx .reduced_tx_set_inter .with(|c| c.set(self.saved_reduced)); self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx)); } } /// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14). /// /// A 1:4 strip is a PAIR. Both children share one chroma block, and only the /// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`: /// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma /// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and /// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s /// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this /// strip's own footprint, copied from this strip's DV. The block is /// `is_inter_block`, so the residual uses the INTER sets and chroma inherits /// the luma unit's coded `tx_type`. /// /// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this /// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that /// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it /// would code chroma on every strip. #[allow(clippy::too_many_arguments)] fn decode_rect4_16_intrabc( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, lmi: (usize, usize), horz: bool, has_chroma: bool, skip: bool, (dv_row, dv_col): (i32, i32), y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, base_q_idx: u8, tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(usize, Option, (usize, usize))> { let _ = base_q_idx; hit!(RECT4_16_INTRABC_HITS); let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) }; let (mi_w, mi_h) = (bw / MI, bh / MI); let (px, py) = (lmi.1 * MI, lmi.0 * MI); let side = bw.max(bh); // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder // publishes `reduced_tx_set` into it; set it here too so a caller that // passed the bit explicitly cannot disagree with the set we read. let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); let restored = scopeguard_reduced(fctx, saved_reduced); flush_recon(fctx, y, u, v); let mut pred_y_dense = vec![0u16; bw * bh]; mc::predict_with_filter( &y.data, y.width, y.true_width, y.true_height, mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0), bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx, ); let mut pred_y = vec![0u16; side * side]; for row in 0..bh { pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]); } // lane-av1444rect r2 (the class this lane named, second instance): the // pair geometry below is the 4:2:0 one and was applied at every `ss`. At // ss (0,0) `is_chroma_reference` (av1_common_int.h:1454) is // unconditionally true -- the strip is its own chroma reference, there is // no pair, and its chroma plane block IS the strip: 16x4 (HORZ_4) / 4x16 // (VERT_4) at the strip's own origin, with its coefficient context read // over that same extent. The old constants instead predicted and coded an // 8x4 block at `(lmi - 1) * MI / 2`, a quarter of the position. // // MEASURED on a `testsrc2` 640x480 `--tune-content=screen --enable-intrabc=1 // --enable-palette=1 --cq-level=60 --min-partition-size=4 // --max-partition-size=64 --sb-size=64 --profile=1` stream (1016 B, 17 // intrabc 16x4 strips at ss (0,0)): 455240 of 921600 samples wrong, the // entropy fork at read 11750 (`decodetxb.c:158`, the chroma `txb_skip`). // `--enable-intrabc=0` at the same settings is byte-exact, and the 4:2:0 // twin of the same recipe is byte-exact. // // 4:2:0 alone keeps every constant below verbatim: a 1:4 strip's chroma // plane block is 4:2:0's PAIR (the block above / beside it), because at // ss (1,1) the strip's 8x2 chroma lies INSIDE that neighbour's chroma. // // lane-av1422luma: at ss (1,0) that containment is gone -- 4:2:2 subsamples // x only, so the strip's chroma is 8x4 (full height) at the STRIP'S OWN // origin, and libaom's own clause agrees: `is_chroma_reference` // (av1_common_int.h:1454) ends in `|| !subsampling_y`, which answers TRUE // for every block at ss_y 0. Reading the strip's chroma at the 4:2:0 pair // origin instead puts the unit one mi row high: on `s422_416x250_10b` // (416x250 10-bit, sha256 d6aa7f45...) that is the V/U pair's `txb_skip` // read at mi (51,84) -- ctx 2 where the oracle reads 8, `all_zero` decoded // as 1 instead of 0, and the frame desyncs from there (luma included). // The origin half is `lane/av1422seed`'s unlanded hunk, reproduced here so // the arm is measurable whole; the gather and the publication extents // below are this lane's. VERT_4 stays on the pair: `ss_size_lookup // [BLOCK_4X16][1][0]` is BLOCK_INVALID at 4:2:2, so only HORZ reaches it. let own444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; let own422 = ss_x(fctx) == 1 && ss_y(fctx) == 0 && horz; if own422 && has_chroma { hit!(INTRABC_RECT4_OWN_CHROMA422_HITS); } // One predicate for "this strip IS its own chroma reference": the strip's // own mi position, its own luma extent, and per-axis subsampled sizes. let own_chroma = own444 || own422; if ss_x(fctx) == 0 && ss_y(fctx) == 0 && has_chroma { hit!(INTRABC_RECT4_OWN_CHROMA444_HITS); } let (pw, ph) = if own444 { (bw, bh) } else if horz { (16usize, 8usize) } else { (8, 16) }; let (cw, ch) = if own_chroma { (bw >> ss_x(fctx), bh >> ss_y(fctx)) } else { (pw / 2, ph / 2) }; let pair_mi = if has_chroma { if own_chroma { lmi } else if horz { (lmi.0 - 1, lmi.1) } else { (lmi.0, lmi.1 - 1) } } else { lmi }; let (cpx, cpy) = if has_chroma { if own_chroma { (px >> ss_x(fctx), py >> ss_y(fctx)) } else { (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2) } } else { (0, 0) }; let cside = cw.max(ch); let (pred_u, pred_v) = if has_chroma { let mut ud = vec![0u16; cw * ch]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), cw, ch, mc::InterpFilterKind::Bilinear, &mut ud, fctx, ); let mut us = vec![0u16; cside * cside]; for row in 0..ch { us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]); } let mut vd = vec![0u16; cw * ch]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), cw, ch, mc::InterpFilterKind::Bilinear, &mut vd, fctx, ); let mut vs = vec![0u16; cside * cside]; for row in 0..ch { vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]); } (us, vs) } else { (Vec::new(), Vec::new()) }; // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced // false for a key frame, so `read_block_tx_size_rect` would skip the // symbol; read it here against the parameter the intra path already uses. // A skipped intrabc block predicts the whole footprint once and codes // no residual (`decode_token_recon_block`'s inter branch). Lossless // still forces TX_4X4 when the block is coded. let leaves = if skip || (!lossless(fctx) && !tx_select) { None } else if lossless(fctx) { let mut leaves = Vec::new(); for row in 0..bh / MI { for col in 0..bw / MI { leaves.push((row, col, 4usize, 4usize)); } } // libaom's `else` branch (`!xd->lossless` fails the var-tx // condition): `set_txfm_ctxs(TX_4X4, ..)` over the block's own // width/height. Same reason as `read_block_tx_size_rect`'s arm -- // it is what makes this body's `fill_lf_grid_rect_after_vartx` // suppression sound. txfm_partition_update_rect(neighbours, lmi, (4, 4), (bw, bh)); Some(leaves) } else { let ctx = txfm_partition_ctx_rect( neighbours.above_txfm[lmi.1], neighbours.left_txfm[lmi.0], side, bw, bh, ); let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; 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}", lmi.0, lmi.1, u8::from(split) ); } if !split { None } else { let (sub_w, sub_h) = sub_tx_size_map(bw, bh); let mi_cols = 2 * y.true_width.div_ceil(8); let mi_rows = 2 * y.true_height.div_ceil(8); let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1)); let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0)); let mut out = 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, neighbours, lmi, side, (max_w_mi, max_h_mi), (sub_w, sub_h), 1, row, col, &mut out, ); } } Some(out) } }; let (tx_w, tx_h) = leaves .as_ref() .and_then(|ls| ls.first()) .map_or((bw, bh), |l| (l.2, l.3)); let mut luma_tx_type = TxType::DctDct; let luma_grid; let mut u_grid = Grid::Zero(cw * ch); let mut v_grid = Grid::Zero(cw * ch); let chroma_stamped_per_unit; if skip { push_mc_rect( 0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx, ); luma_grid = Grid::Zero(bw * bh); if has_chroma { push_mc_rect( 1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * ch], fctx, ); push_mc_rect( 2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * ch], fctx, ); } chroma_stamped_per_unit = false; } else if let Some(ls) = leaves.as_ref() { if lossless(fctx) { for &(row, col, _tw, _th) in ls { let tu_mi = (lmi.0 + row, lmi.1 + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); let (g, _) = read_inter_plane( dec, cdfs, if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 }, &default_scan(4), 0, neighbours.around_mi(tu_mi, 4)[0], 0, y, tu_px, tu_py, 4, base_q_idx, tu_pred, None, Some(neighbours.luma_skip_ctx(tu_mi, 1)), fctx, )?; neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g); } } else { for (idx, &(row, col, tw, th)) in ls.iter().enumerate() { let tu_mi = (lmi.0 + row, lmi.1 + col); let (tu_px, tu_py) = (px + col * MI, py + row * MI); let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); let (g, tt) = if tw == th { read_inter_plane( dec, cdfs, inter_txbset_for(tw, reduced_tx_set), &default_scan(tw.min(32)), 0, neighbours.around_mi(tu_mi, tw)[0], 0, y, tu_px, tu_py, tw, base_q_idx, tu_pred, None, Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)), fctx, )? } else { 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], 0, y, tu_px, tu_py, tu_pred, None, Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)), fctx, )? }; if idx == 0 { luma_tx_type = tt; } neighbours.record_mi_luma_rect(tu_mi, tw, th, &g); } } luma_grid = Grid::Zero(bw * bh); chroma_stamped_per_unit = has_chroma && lossless(fctx); if has_chroma && lossless(fctx) { let (mut uo, mut vo) = (Vec::new(), Vec::new()); read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, Pred::Inline(&pred_u, cside), Pred::Inline(&pred_v, cside), pair_mi, (cpx, cpy), (0, 0), (cw, ch), (cw, ch), cside, 0, base_q_idx, &mut uo, &mut vo, fctx, )?; u_grid = if uo.is_empty() { Grid::Zero(cw * ch) } else { Grid::Own(uo) }; v_grid = if vo.is_empty() { Grid::Zero(cw * ch) } else { Grid::Own(vo) }; } else if has_chroma { // lane-av1422luma: the own-chroma route reads its context over its // OWN extent; at ss (1,0) it additionally goes through the // every-second-column gather (one chroma 4-px column spans two // luma mi columns, so the per-mi gather would count each column's // whole-unit dc sign twice and OR in cells the unit does not // cover) -- the same choice the `decode_rect4_16` chroma arm // makes at `decode.rs:19577`. 4:4:4 keeps the per-mi gather: at // ss_x 0 a chroma column IS a luma mi column, so sampling would // halve its own above span. let (gmi, gw, gh) = if own_chroma { (lmi, bw, bh) } else { (pair_mi, pw, ph) }; let around = if own422 { neighbours.around_mi_422_chroma(gmi, gw, gh) } else { neighbours.around_mi_rect(gmi, gw, gh) }; let (ug, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, )?; u_grid = ug; let (vg, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, )?; v_grid = vg; } } else { let around = neighbours.around_mi_rect(lmi, bw, bh); let (g, tt) = read_inter_plane_rect( dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0, y, px, py, Pred::Inline(&pred_y, side), None, None, fctx, )?; luma_tx_type = tt; luma_grid = g; chroma_stamped_per_unit = false; if has_chroma { // lane-av1422luma: as the lossless twin above -- own extent, and // the sampled gather at 4:2:2 only. let (gmi, gw, gh) = if own_chroma { (lmi, bw, bh) } else { (pair_mi, pw, ph) }; let around = if own422 { neighbours.around_mi_422_chroma(gmi, gw, gh) } else { neighbours.around_mi_rect(gmi, gw, gh) }; let (ug, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, )?; u_grid = ug; let (vg, _) = read_inter_plane_rect( dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, )?; v_grid = vg; } } drop(restored); if leaves.is_none() { neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid); } neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED); neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip); // lane-av1oddheightfork3: this body reads its own var-tx tree inline // (`read_var_tx_size` per child), so the bands are per-leaf already; the // whole-footprint publish overwrote them with the block's own size. neighbours.fill_lf_grid_rect_after_vartx(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx); 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; } } let mut last_uv = None; if has_chroma { hit!(RECT4_16_CHROMA_HITS); // lane-av1422luma: the uv-mode publication and the left/above skip // state below are the STRIP's own at 4:2:2 / 4:4:4 -- publishing the // pair extent (one mi row off, `ph`/`pw`) is what the NEXT block's // chroma skip context then reads. let (rmi, rw, rh) = if own_chroma { (lmi, bw, bh) } else { (pair_mi, pw, ph) }; neighbours.record_uv_mode_mi(rmi.0, rmi.1, rw / MI, rh / MI, DC_PRED); if !chroma_stamped_per_unit { let u_state = neighbour_state(&u_grid); let v_state = neighbour_state(&v_grid); 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..(rh / MI) { if rmi.0 + cell < bound_h && let Some(slot) = neighbours.left.get_mut(rmi.0 + cell) { slot[1] = u_state; slot[2] = v_state; } } for cell in 0..(rw / MI) { if rmi.1 + cell < bound_w && let Some(slot) = neighbours.above.get_mut(rmi.1 + cell) { slot[1] = u_state; slot[2] = v_state; } } } last_uv = Some(DC_PRED); } if horz { hit!(RECT4_16_HORZ_HITS); } else { hit!(RECT4_16_VERT_HITS); } record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]); if leaves.is_none() { // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs` // with `skip && is_inter`, or the unsplit unit). A split tree already // published per leaf inside `read_var_tx_size`. txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh)); } record_intrabc_mi_rect( lmi.0, lmi.1, mi_w, mi_h, Some((dv_row, dv_col)), neighbours, fctx, ); Ok((DC_PRED, last_uv, (tx_w, tx_h))) } /// Restores `reduced_tx_set_inter` when the intrabc pair reader returns, /// including through `?`. struct ReducedRestore<'a> { fctx: &'a crate::decode::FrameCtx, saved: bool, } impl Drop for ReducedRestore<'_> { fn drop(&mut self) { self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved)); } } fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> { ReducedRestore { fctx, saved } } #[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 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, intrabc, ) = 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 let Some(dv) = intrabc { return decode_rect4_16_intrabc( dec, cdfs, neighbours, lmi, horz, has_chroma, skip, dv, y, u, v, base_q_idx, tx_select, reduced_tx_set, 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. // lane-av1mixloss: the lossless-segment early return // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a // lossless-segment strip codes no depth symbol here either (class // sweep of the sub8 leaf's fix). let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands // (`get_tx_size_context`, libaom `pred_common.h:342`). let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); 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, fctx); 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 || lossless(fctx) { // [`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, 0, )?; 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, block_iqmatrix(fctx, 0, tx_w, tx_h, 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, 0, )?; 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, block_iqmatrix(fctx, 0, bw, bh, 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); // lane-av1-444: at 4:4:4 there is no pair -- every strip is its // own chroma reference and codes its own 16x4 / 4x16 chroma // block. (`set_mi_offsets`'s chroma snap is the zero offset at // ss 0/0, so the neighbour reads below anchor at the strip.) let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 { (lmi, bw, bh) } else if ss_y(fctx) == 0 && horz { // lane-av1-422: chroma height is NOT subsampled, so a HORZ // 16x4 strip is its own chroma reference (`is_chroma_reference` // at ss(1,0): bh == 1 mi, so the row clause reduces to // `!ss_y`) and codes its own `ss_size_lookup[BLOCK_16X4][1][0]` // = BLOCK_8X4 chroma block -- a valid transform, no pair. // (lane-av1-422o: a VERTICAL 4x16 strip now falls through to // the pair merge below -- its own chroma block // `ss_size_lookup[BLOCK_4X16][1][0]` is BLOCK_INVALID, the // walk proved such leaves exist, and libaom codes the pair's // chroma from the closing strip; the chunk lives in the // `chroma422_pair16` arm below.) (lmi, bw, bh) } else if horz { ((lmi.0 - 1, lmi.1), 16, 8) } else { ((lmi.0, lmi.1 - 1), 8, 16) }; let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI); let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx)); let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx)); // lane-av1-422o: the 4:2:2 pair's chroma of a VERT 4x16 strip // pair: (4, 16) at ss(1,0). The bsize is still BLOCK_4X16, whose // `ss_size_lookup[..][1][0]` is BLOCK_INVALID, so libaom's // `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` -- the // out-of-bounds byte is TX_4X8 in the pinned Release oracle, and // `av1_get_adjusted_tx_size` has no TX_4X8 case to adjust it. // `decode_token_recon_block` walks unit_width = // ROUND_POWER_OF_TWO(1, 1) = 1, unit_height = 4, with stepr = // tx_size_high_unit[TX_4X8] = 2: TWO TX_4X8 units per plane // (chroma rows 0..8 and 8..16), plane-major. Even the skip arm // walks per unit: `predict_and_reconstruct_intra_block` predicts // every unit regardless of `skip_txfm`. let chroma422_pair16 = (cw, ch) == (4, 16) && ss_x(fctx) == 1; 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, fctx); // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the // frame's own `ss_x` -- the unsnapped read is the pair-merge witness // counter's mirror of the snapping form, and the shipped read offsets // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`). // // lane-av1leftwit: this mirror is NOT evidence about the left read's // `+ss_y` term, whatever a report once said. It reads the leaf's own // (odd) mi row, which no decode call site does -- every one of them // uses the snapping form, whose base row is even -- and its result // feeds `RECT4_16_UV_PAIR_FILT_HITS` only. What it measures is real // and worth keeping (the pair's chroma-reference read against the // leaf's own row: 51/24/121/0/1 hits on the five fixtures censused), // so it stays; the decode path's own reach for the `+ss_y` term is // `uv_left_1mi_split_hits()`. if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped( lmi.0, lmi.1, r, c, ss_x(fctx), ss_y(fctx), false, ) { hit!(RECT4_16_UV_PAIR_FILT_HITS); } // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading // the rect here consumed one symbol block too few and desynced // the next strip's `skip` (measured: lossless sb128 320x240, // mi(1,20) uv_mode matched, the following skip did not). let lossless_pair = lossless(fctx); let (u_levels, v_levels) = if lossless_pair { hit!(RECT4_16_LOSSLESS_CHROMA_HITS); if skip { for plane in 1..3usize { for rr in 0..ch / 4 { for cc in 0..cw / 4 { let (ox, oy) = (cc * 4, rr * 4); // The unit's origin and extent in LUMA pixels: `<< ss` // at 4:2:0 (8x8 luma for a 4x4 chroma unit), identity // at 4:4:4 -- the same form as the block-walk sibling // at decode.rs:35342. The hardcoded `ox * 2 / 8` is // only right at ss (1,1): at 4:4:4 it claims a 4x4 // chroma unit is 8x8 luma, so `of_tu`'s // `col_off + tx_w < bw` test answers against a // footprint twice the real one and every unit past // the block's midpoint wrongly reports // `above_right = false` -- a directional chroma // strip then predicts from a neighbour libaom // never reads (measured: key frame 0, 4:4:4 lossless // 16x4 strip at (104,26), U 29 + V 34 samples wrong, // entropy bit-identical over 351109 EC_SYMR reads). // lane-av1422llpred r2: this site had the OTHER half // of the same shape -- `tu_reach` takes ONE size for // both axes, so a subsampled chroma unit's height // came from `<< ss_x` instead of `<< ss_y` (a TX_4x4 // chroma unit is `4 << ss_x` luma px wide but // `4 << ss_y` tall). Identical at 4:2:0/4:4:4. let cu_reach = tu_reach_rect( pw, ph, ox << ss_x(fctx), oy << ss_y(fctx), 4 << ss_x(fctx), 4 << ss_y(fctx), pair_reach, ppx, ppy, y.width, y.height, fctx, ); if let Some((ub, vb)) = &palette_uv_bufs { let buf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx); } push_intra( plane, cpx + ox, cpy + oy, 4, uv_predict_mode, angle_delta_uv, cu_reach, &ZERO_RESIDUAL[..16], None, None, smooth_neighbor_uv, fctx, ); let cu_mi = ( pair_mi.0 + (oy << ss_y(fctx)) / MI, pair_mi.1 + (ox << ss_x(fctx)) / MI, ); neighbours.record_mi_chroma( cu_mi, 4 << ss_x(fctx), 4 << ss_y(fctx), plane, &ZERO_RESIDUAL[..16], ); } } } (Grid::Zero(cw * ch), Grid::Zero(cw * ch)) } else { let scan4 = default_scan(4); // `get_txb_ctx`: offset 10 (our tables store it at +3) // when the plane block is larger than the transform. let offset = Some(3usize); let mut uo = vec![0i32; cw * ch]; let mut vo = vec![0i32; cw * ch]; for plane in 1..3usize { for rr in 0..ch / 4 { for cc in 0..cw / 4 { let (ox, oy) = (cc * 4, rr * 4); if cpx + ox >= u.true_width || cpy + oy >= u.true_height { continue; } // The unit's stamp is its own span: aom // `av1_set_entropy_contexts` (blockd.c:29) // memsets exactly `tx_size_wide_unit` x // `tx_size_high_unit` cells at the unit's own // `(aoff, loff)` -- for TX_4X4 ONE above cell // and ONE left cell. `(oy / 2, ox / 2)` + // `(8, 8)` is the 4:2:0 subsampled form (one // chroma cell = 8 luma px = 2 mi cells); at // 4:4:4 a unit is ONE mi cell, and the 2x2 // smear let a 4-wide strip's later units // overwrite the NEXT COLUMN's above cell with // their own state -- a column aom never sees // this block write -- so the following block's // `all_zero` read the wrong `txb_skip` row // (frame-0 read #452, the llkf named gap). let cu_mi = ( pair_mi.0 + (oy << ss_y(fctx)) / MI, pair_mi.1 + (ox << ss_x(fctx)) / MI, ); // One luma-mi cell: the chroma entropy arrays // are subsampled, and our bands replicate that // one entry over the unit's two cells // (`read_intra_chroma_lossless`). let cu_around = neighbours.around_mi(cu_mi, MI); // Same ss-aware luma footprint as the skip arm // above -- `ox * 2 / 8` is the 4:2:0-only form and // mis-answers `of_tu` at 4:4:4 (see there). // lane-av1422llpred r2: and the SKIP arm's fix // missed the other half of the same shape -- one // size for both axes makes the height come from // `<< ss_x`, so only 4:2:2 can reach it. let cu_reach = tu_reach_rect( pw, ph, ox << ss_x(fctx), oy << ss_y(fctx), 4 << ss_x(fctx), 4 << ss_y(fctx), pair_reach, ppx, ppy, y.width, y.height, fctx, ); if let Some((ub, vb)) = &palette_uv_bufs { let buf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx); } let buf: &mut PlaneBuf<'static> = if plane == 1 { &mut *u } else { &mut *v }; let cu_grid = read_plane( dec, cdfs, TxbSet::Chroma4, &scan4, plane, cu_around[plane], mode, uv_predict_mode, angle_delta_uv, cu_reach, buf, cpx + ox, cpy + oy, 4, 4, base_q_idx, None, None, offset, smooth_neighbor_uv, fctx, )?; neighbours.record_mi_chroma( cu_mi, 4 << ss_x(fctx), 4 << ss_y(fctx), plane, &cu_grid, ); hit!(CHROMA_SPLIT_TX_HITS); let dst = if plane == 1 { &mut uo } else { &mut vo }; for row in 0..4 { let start = (oy + row) * cw + ox; dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]); } } } } (Grid::Own(uo), Grid::Own(vo)) } } else 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 chroma422_pair16 { // lane-av1-422o: two TX_4X8 units, each predicted on // its own edges (the lower one off the upper one's // samples); no coefficients are coded, and libaom's // `set_entropy_context` zeroed the block's own cells, // so the pair-wide zero stamp below stays correct. for unit_row in 0..2usize { let unit_reach = tu_reach_rect( pw, ph, 0, unit_row * 8, 8, 8, pair_reach, ppx, ppy, y.width, y.height, fctx, ); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx); } push_intra_rect( plane, cpx, cpy + unit_row * 8, 4, 8, uv_predict_mode, angle_delta_uv, unit_reach, &ZERO_RESIDUAL[..4 * 8], alpha .zip(ac) .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), None, smooth_neighbor_uv, fctx, ); } } else { 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 if chroma422_pair16 { // lane-av1-422o: the pair's 4x16 chroma as TWO TX_4X8 units // per plane, plane-major (every U unit, then every V). Each // unit: the `ChromaRect8x4` tables (`get_txsize_entropy_ctx` // squares TX_4X8 up to the 8x8 class), `SCAN_4X8`, and a // `txb_skip_ctx` of above+left in the OFFSET-10 rows -- the // offset comes from `num_pels_log2_lookup[plane_bsize] > // num_pels_log2_lookup[BLOCK_4X8]` with plane_bsize = // BLOCK_INVALID (255), and the byte at that table's +255 in // the pinned Release oracle is 255 (`cmpb` against the // `0xc0db70` copy decodetxb.c links), i.e. the bigger-plane // arm: +3 on the offset-7-first chroma tables. No tx_type // symbol (only y plane's is transmitted); the unit's type is // `intra_mode_to_tx_type(UV mode)` kept by the all-16 ext-tx // set -- [`read_rect_chroma_unit`]'s own default. CfL params // are computed ONCE per block (`are_parameters_computed`) // over the pair's luma, shared by both units. Each unit is // predicted and recorded immediately, so the lower unit // reads the upper one's coefficient context. let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph)); for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] { for unit_row in 0..2usize { let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1); let unit_reach = tu_reach_rect( pw, ph, 0, unit_row * 8, 8, 8, pair_reach, ppx, ppy, y.width, y.height, fctx, ); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx); } let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8); let unit_grid = read_rect_chroma_unit( dec, cdfs, TxbSet::ChromaRect8x4, &SCAN_4X8, 4, 8, plane, chroma_around[plane], uv_predict_mode, angle_delta_uv, unit_reach, buf, cpx, cpy + unit_row * 8, base_q_idx, // lane-av1-422q: the offset-10 rows -- the same // measured rule as the 4x32 arm (plane_bsize // BLOCK_INVALID for the pair's BLOCK_4X16 too; // num_pels_log2_lookup[255] = 0xff at the // 0xc0de70 copy -> +3 on the offset-7-first // chroma tables; see lanes/av1422q.report.md). Some(3), alpha .zip(ac) .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), smooth_neighbor_uv, fctx, )?; neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid); } } (Grid::Zero(cw * ch), Grid::Zero(cw * ch)) } else { // lane-av1422ctxgather: 4:2:2's chroma above votes sample // every second luma-mi cell // ([`Neighbours::around_mi_422_chroma`]: at ss_x 1 one // chroma 4-px column spans two luma mi columns, and the // plain per-mi gather counts each column's whole-unit dc // sign twice). The left extent is unsubsampled at ss_y 0, // so its per-mi cells already line up one-to-one. let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 { neighbours.around_mi_422_chroma(pair_mi, pw, ph) } else { neighbours.around_mi_rect(pair_mi, pw, ph) }; // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` = // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8. let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) { (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]), (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]), (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]), // lane-av1-444: 4:4:4's own-strip vert chroma is (4,16) // -- one TX_4X16. (lane-av1-422o: the 4:2:2 pair's // (4,16) never reaches this row; `chroma422_pair16` // intercepts it above and chunks it into TX_4X8 units.) (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]), // lane-av1-422: a 4:2:2 HORZ pair (16x8 luma) keeps the // pair's height: an 8x8 SQUARE chroma block, the same // `TxbSet::Chroma8` set any 8x8 chroma plane reads. The // 4:2:0 pair's chroma is 8x4 and 4:4:4's is 16x4, so this // row is unreachable there. It is also the witness arm: // a restored `/2 chroma height` lands on (8,4) and the // counter reads 0. (8, 8) => { hit!(CHROMA422_SQUARE_HITS); (TxbSet::Chroma8, default_scan(8)) } // lane-av1-422o: with the `chroma422_pair16` arm above, // the (2,16) own-strip shape and the 4:4:4 shapes are the // only residents; anything else is a named-lane gap. _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"), }; 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(chroma_set, uv_predict_mode); let (levels, tx_type) = read_chroma_coeffs_rect( dec, &mut coding, chroma_scan, cw, ch, skip_ctx, dc_sign_ctx(around[plane].2), default_tx, fctx, plane, )?; 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, block_iqmatrix(fctx, plane, cw, ch, 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); // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`). // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8. // lane-av1-422o: the chunked pair's cells are stamped PER UNIT in // the arm above (libaom's coefficient contexts are per // 4x4-cell); a pair-wide state would erase the unit boundary the // next block reads. if !lossless_pair && !chroma422_pair16 { // 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, intrabc, ) = 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 let Some((dv_row, dv_col)) = intrabc { return decode_intrabc_owned_rect( dec, cdfs, neighbours, (r * (SUB / MI), c * (SUB / MI)), (bw, bh), skip, (dv_row, dv_col), y, u, v, base_q_idx, tx_select, reduced_tx_set, 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, fctx); 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)); // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes // no depth symbol here either (class sweep of the sub8 leaf's fix). let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an // intra-only frame publishes them from every block too // ([`Neighbours::fill_lf_grid_rect`]). 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 = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); // 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, fctx), (bw, bh), fctx, ); if depth != 0 || lossless(fctx) { 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, fctx); 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 >> ss_x(fctx), py >> ss_y(fctx)); let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); 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, 0, )? }; 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, block_iqmatrix(fctx, 0, bw, bh, 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. At 4:2:0 the plane block is already one adjusted UV // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma // is larger than that, so it is tiled into 32-capped units. let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); let (uw, uh) = (chroma_w.min(32), chroma_h.min(32)); let (nw, nh) = (chroma_w / uw, chroma_h / uh); let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) { (32, 32) => (TxbSet::Chroma32, default_scan(32)), (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16), (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32), (32, 8) => (TxbSet::Chroma16, &SCAN_32X8), (8, 32) => (TxbSet::Chroma16, &SCAN_8X32), _ => { return Err(unsupported( "a 64-axis strip whose chroma unit has no coefficient table", )); } }; let bigger = nw * nh > 1; // lane-av1444palw: the reach census for the horizontal arm of this // walk. `EC_PALWALK=1` prints, per rect64 block, the plane-block // geometry, the unit grid it was tiled into, and whether a chroma // palette was present -- so a fixture search can tell `nw >= 2` (the // arm nothing had reached) from `nh >= 2` (the arm the corpus census // already covered), and can see WHY a candidate block did not fire. // Diagnostic only; no decode behaviour depends on it. if crate::envflags::env_flag!("EC_PALWALK") { eprintln!( "EC_PALWALK mi={r},{c} px={px} py={py} bw={bw} bh={bh} cw={chroma_w} \ ch={chroma_h} uw={uw} uh={uh} nw={nw} nh={nh} ast={allow_screen_content_tools} \ puv={} py_pal={}", palette_uv.is_some() as i32, palette_y.is_some() as i32 ); } let mut u_levels = vec![0i32; chroma_w * chroma_h]; let mut v_levels = vec![0i32; chroma_w * chroma_h]; // The tiled units below stamp their own coefficient context // immediately, then the whole-strip `record_rect` rewrite paints // every chroma cell with ONE whole-strip state and the per-unit DC // signs and levels are lost (class `override-slot-on-one-arm`, same // shape as `decode_rect_split`'s chroma_tiled clobber). Collected // here and replayed after that record, the c8 `mu_chroma_units` way. let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); for plane_idx in 1..=2 { for cu_row in 0..nh { for cu_col in 0..nw { let cu_around = if nw == 1 && nh == 1 { around } else { let lsx = uw << ss_x(fctx); let lsy = uh << ss_y(fctx); let cu_mi = (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)); // lane-av1422llintra: same ss (1, 0) above-column // double-count as 12735 -- one chroma column spans two // luma mi columns, libaom reads one. Identical number // at 4:2:0 and 4:4:4. if ss_x(fctx) == 1 && ss_y(fctx) == 0 { neighbours.around_mi_422_chroma(cu_mi, lsx, lsy) } else { neighbours.around_mi_rect(cu_mi, lsx, lsy) } }; let lsx = uw << ss_x(fctx); let lsy = uh << ss_y(fctx); let cfl = alpha.map(|(au, av)| { let a = if plane_idx == 1 { au } else { av }; ( a, cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy), ) }); let levels = if uw == uh { let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane_idx == 1 { ub } else { vb }; set_palette_pred( palette_window(pbuf, chroma_w, cu_col * uw, cu_row * uh, uw, uh), fctx, ); // Counted only when the window is a STRICT sub-slice of the // block's buffer, i.e. when the 32-cap actually tiled the // block: at nw * nh == 1 the window is a re-stride copy of // the whole buffer and windowing is load-bearing for // nothing. The `bigger` guard is what makes a hit PROOF // that the tiled arm ran, rather than proof that some // palette chroma block existed. if bigger { hit!(CHROMA_PALETTE_WINDOW_HITS); } } read_plane( dec, cdfs, chroma_set, chroma_scan, plane_idx, cu_around[plane_idx], mode, uv_predict_mode, angle_delta_uv, reach, plane, cpx + cu_col * uw, cpy + cu_row * uh, uw, uw, base_q_idx, cfl, None, bigger.then_some(3), smooth_neighbor_uv, fctx, )? } else { let skip_ctx = usize::from(cu_around[plane_idx].0) + usize::from(cu_around[plane_idx].1) + usize::from(bigger) * 3; let mut coding = cdfs.txb(chroma_set, uv_predict_mode); let (levels, tx_type) = read_chroma_coeffs_rect( dec, &mut coding, chroma_scan, uw, uh, skip_ctx, dc_sign_ctx(cu_around[plane_idx].2), TxType::DctDct, fctx, plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, uw, uh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, block_iqmatrix(fctx, plane_idx, uw, uh, tx_type), ); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane_idx == 1 { ub } else { vb }; set_palette_pred( palette_window(pbuf, chroma_w, cu_col * uw, cu_row * uh, uw, uh), fctx, ); // Counted only when the window is a STRICT sub-slice of the // block's buffer, i.e. when the 32-cap actually tiled the // block: at nw * nh == 1 the window is a re-stride copy of // the whole buffer and windowing is load-bearing for // nothing. The `bigger` guard is what makes a hit PROOF // that the tiled arm ran, rather than proof that some // palette chroma block existed. if bigger { hit!(CHROMA_PALETTE_WINDOW_HITS); } } push_intra_rect( plane_idx, cpx + cu_col * uw, cpy + cu_row * uh, uw, uh, uv_predict_mode, angle_delta_uv, reach, &residual, cfl, None, smooth_neighbor_uv, fctx, ); levels }; let dst = if plane_idx == 1 { &mut u_levels } else { &mut v_levels }; for row in 0..uh { let d = (cu_row * uh + row) * chroma_w + cu_col * uw; dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]); } if bigger { neighbours.record_mi_chroma( (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)), lsx, lsy, plane_idx, &levels, ); tiled_chroma_units.push(( (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)), plane_idx, levels.clone(), lsx, lsy, )); } } } } neighbours.record_rect( at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]], ); // The per-unit re-stamp: `record_rect` above wrote the whole strip's // chroma cells from the assembled grids' one whole-strip state, // overwriting exactly the stamps the tiled loop just made. for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units { neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit); } 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()`. crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64); 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, (side / MI, side / MI), 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 crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", u8::from(use_intrabc), dec.debug_state().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 / MI, side / MI), 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-av1mono: a monochrome block codes no chroma mode/CFL/palette // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref` // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader // gates its chroma symbols on. let has_chroma = !mono(fctx); let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx); let uv_mode = if !has_chroma { DC_PRED } else if cfl { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); 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. // // lane-av1mono: libaom's actual guard is `num_planes > 1 && // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size` // symbol even at this chroma-owning square block. let palette_uv_mode_ctx = usize::from(use_palette_y); 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)); } } // `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, palette_onscreen(mi_r, mi_c, side, side, fctx), 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 on = palette_onscreen_uv( (side, side), palette_onscreen(mi_r, mi_c, side, side, fctx), (side >> ss_x(fctx), side >> ss_y(fctx)), (ss_x(fctx), ss_y(fctx)), ); // lane-av1-422d: the chroma map's extent is the PLANE BLOCK // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the // square call's `(side >> ss_x)`-squared (4x4), which left a // 16-entry map for a 32-sample unit and panicked the reconstruct. let map = decode_color_index_map_wh( dec, cdfs, n, side >> ss_x(fctx), side >> ss_y(fctx), on, 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 { cfl_ac_q3_at(px, py, side, side, |lx, ly| { i32::from(y.data[ly * y.width + lx]) }) } /// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma /// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder /// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8` /// reconstruction through THIS function rather than a second transcription of /// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`. /// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4 /// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`). fn cfl_ac_ss( y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize, ss_x: usize, ss_y: usize, ) -> Vec { if ss_x == 0 && ss_y == 0 { hit!(CFL_AC_444_HITS); let mut ac = vec![0i32; bw * bh]; let mut sum = 0i32; for row in 0..bh { for col in 0..bw { let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3; ac[row * bw + col] = q3; sum += q3; } } let num_pel = (bw * bh) as i32; let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros(); ac.iter_mut().for_each(|v| *v -= avg); ac } else if ss_x == 1 && ss_y == 0 { // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample // averages the HORIZONTAL luma pair above it, at full chroma height // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma // is square here, and the 4:2:0 rect/square helpers below would halve // the height it must keep. hit!(CFL_AC_422_HITS); let (cw, ch) = (bw >> 1, bh); let mut ac = vec![0i32; cw * ch]; let mut sum = 0i32; for row in 0..ch { for col in 0..cw { let (lx, ly) = (px + col * 2, py + row); let q3 = (i32::from(y.data[ly * y.width + lx]) + i32::from(y.data[ly * y.width + lx + 1])) << 2; ac[row * cw + col] = 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 } else if bw == bh { hit!(CFL_AC_420_SQ_HITS); cfl_ac_q3(y, px, py, bw) } else { hit!(CFL_AC_420_RECT_HITS); cfl_ac_q3_rect(y, px, py, bw, bh) } } pub(crate) fn cfl_ac_q3_at( px: usize, py: usize, bw: usize, bh: usize, sample: impl Fn(usize, usize) -> i32, ) -> Vec { hit!(CFL_AC_Q3_AT_HITS); if crate::envflags::env_flag!("EC_HALVSWEEP") { eprintln!("EC_HALV cfl_ac_q3_at px={px} py={py} bw={bw} bh={bh}"); } 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 = (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 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 } /// `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). pub(crate) 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); } } } /// `EC_AV1_PREFILT_WIDE_DUMP=` -> `.f`, the pre-loop-filter /// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for /// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`, /// `uv_width`/`uv_height`), so the two can be diffed directly. /// /// lane-av1444edge: this used to be an inline block in the KEY-frame tile path /// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were /// measurement traps, and the second one is why the first went unnoticed: /// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide /// prefilter dump at all, so every 4:4:4 lossy divergence localized to an /// inter frame had no pre-filter rung to compare against and got attributed to /// reconstruction when the oracle could not see it. The `static` also restarted /// per monomorphisation, so every frame after the first overwrote `.f0` -- a /// per-frame bisection silently compared the LAST decoded frame. The counter /// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on /// the inter path (skipped when the filter pipeline is active, which has /// already deblocked by the time the tile tail runs -- same condition /// `capture_filter_replay` guards itself with). fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else { return; }; use std::io::Write; let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP"); let crop = |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(y)); let _ = f.write_all(&crop(u)); let _ = f.write_all(&crop(v)); } } /// 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`). // lane-av1pixprobe: env-gated one-sample write probe -- `EC_AV1_PIXPROBE=x,y` // prints one PIXWRITE line per reconstruction store landing on that sample, // naming the store site, the value it replaces and the one it leaves. Re-anchored // from `lane-av1-ibcwrite` @ 25f5c729 onto the main-shape sites (the two mc stores // now live in `reconstruct_mc_rect`). static PIXPROBE_ON: std::sync::LazyLock = std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_PIXPROBE").is_some()); static PIXPROBE: std::sync::LazyLock> = std::sync::LazyLock::new(|| { crate::envflags::var("EC_AV1_PIXPROBE").ok().and_then(|v| { let (x, y) = v.split_once(',')?; Some(( x.trim().parse::().ok()?, y.trim().parse::().ok()?, )) }) }); #[inline] fn pix_write( site: &str, bx: usize, by: usize, bside: usize, x: usize, y: usize, prev: u16, val: u16, ) { if *PIXPROBE_ON && Some((x, y)) == *PIXPROBE { eprintln!( "PIXWRITE {site} block=({bx},{by})+{bside} px=({x},{y}) prev={prev} val={val} at {}", std::panic::Location::caller() ); } } 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} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), recon_plane(), i32::from(smooth_neighbor) ); } let residual = dense_residual(residual, bw * bh); if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) { let res0: Vec = residual[..bw.min(8)].to_vec(); let pred0: Vec = prediction[..bw.min(8)].to_vec(); eprintln!( "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}" ); } 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; pix_write( "reconstruct_rect", x, y, bw, x + col, y + row, self.data[(y + row) * self.width + x + col], sample, ); self.data.to_mut()[(y + row) * self.width + x + col] = sample; } } // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one // -- a block whose prediction matches the oracle's but whose written // samples do not is either a residual defect or a later overwrite, and // only this print separates the two. if crate::envflags::env_flag!("EC_PRED") { let row0: Vec = (0..bw.min(8)) .map(|c| self.data[y * self.width + x + c]) .collect(); let col0: Vec = (0..bh.min(8)) .map(|r| self.data[(y + r) * self.width + x]) .collect(); eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}"); } } /// 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); if crate::envflags::env_flag!("EC_DEBUG_EDGES") { eprintln!( "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}", above.as_deref(), left.as_deref(), ); } 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} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), recon_plane(), i32::from(smooth_neighbor) ); } let residual = dense_residual(residual, side * side); if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) { let res0: Vec = residual[..side.min(8)].to_vec(); let pred0: Vec = prediction[..side.min(8)].to_vec(); eprintln!( "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}", cfl.is_some() ); } 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; pix_write( "reconstruct", x, y, side, x + col, y + row, self.data[(y + row) * self.width + x + col], sample, ); 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 { // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) // never reaches a chroma plane -- no u/v coefficient symbol is coded and // no chroma write is recorded. Return the all-zero grid the caller's // neighbour bookkeeping reads, without consuming a bit. if plane_idx > 0 && mono(fctx) { return Ok(Grid::Zero(side * side)); } // lane-av1readcensus: the units read from here on are this plane's. set_census_plane(plane_idx); 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 // (every chroma unit of a plane block above TX_4X4 -- lane-sb128b r3, // and lane-av1h5 measured the 4:4:4 lossless 128 root's TX_4X4 chroma // units reading the offset-10 rows too, against aomdec's `EC_DBGCTX`). 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). // lane-av1444chr: per-TU mode trace with the PLANE named. `PlaneBuf`'s own // `OUR_PRED` rung cannot carry it (reconstruction does not know its // plane), and a rung whose plane has to be guessed from the values has // already produced wrong claims twice this session -- `read_coeffs_rect` // labelling its unit `plane=0`, and a sweep reading a second-luma-unit // phantom out of that label (class `rung-mislabels-plane`). Diagnostic // only: no gate asserts decode behaviour off this line. if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "OUR_MODE plane={plane_idx} x={x} y={y} side={side} mode={predict_mode} \ ad={angle_delta} fi={filter_intra:?} reach={reach:?}" ); } 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); // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read // transform type for lossless mode(qindex==0)" -- the symbol is not coded // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every // plane of a lossless block (the residual then goes through the WHT, so // the type only picks the scan, which is the default one). if lossless(fctx) { coding.tx_type = None; } // A chroma plane's `tx_type` is *never* its own coded symbol // (`coding.tx_type` is always `None` for every `TxbSet::Chroma*`), so it is // resolved, not read. Three cases, in libaom's own order // (`av1_get_tx_type` / `av1_get_ext_tx_set_type`, `blockd.h`): // // * **intra** chroma: `intra_mode_to_tx_type(mbmi, PLANE_TYPE_UV)` -- the // plane's own predicted mode (`default_intra_tx_type`) -- then clamped by // `av1_get_ext_tx_set_type`. At 32 points and up that set is // `EXT_TX_SET_DCTONLY` (the `is_inter ? EXT_TX_SET_DCT_IDTX : // EXT_TX_SET_DCTONLY` line), which forces `DCT_DCT` no matter what the // mode-indexed table said. `TxbSet::Chroma8`/`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. // * **inter** chroma, i.e. [`INTRABC_CHROMA_TX`]: the same // `xd->tx_type_map` cell the luma unit stamped (`blk_row <<= // pd->subsampling_y`, `blk_col <<= pd->subsampling_x`), reduced by the // INTER transform set. At **32 points** that set is // `EXT_TX_SET_DCT_IDTX`, NOT `EXT_TX_SET_DCTONLY` -- so a 32-point // inter chroma unit inherits the luma's coded `IDTX`, and the identity // transform (a plain copy) is what libaom actually runs. // [`reduce_inherited_chroma_tx_type`] is that reduction verbatim. // * 64 points and up is `EXT_TX_SET_DCTONLY` for both, which the same // reduction already yields. // // The `side >= 32` -> `DCT_DCT` clamp this replaces was written for the // intra case (and read as libaom's clamp at `tx_size_sqr_up >= TX_32X32`), // but libaom's cap is `txsize_sqr_up_map[tx_size] > TX_32X32` -- 64 and up // -- so it also swallowed a 32-point INTER chroma unit's inherited `IDTX` // and ran `DCT_DCT` where libaom ran the identity transform. // Sub-32 units keep the raw inherited type exactly as before. let default_tx_type = if plane_idx == 0 { TxType::DctDct } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) { if side >= 32 { reduce_inherited_chroma_tx_type(inherited, side, side, fctx) } else { inherited } } else if side >= 32 { TxType::DctDct } else { default_intra_tx_type(predict_mode as u8) }; // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one. let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type }; 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 { plane: plane_idx, w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type, qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type), stride: 0, lossless: lossless(fctx), }; 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) } /// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a /// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane /// block's own rect shape, and the `rect` flag selects /// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop. #[allow(clippy::too_many_arguments)] fn push_intra_unit( plane: usize, x: usize, y: usize, w: usize, h: 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 w == h { push_intra( plane, x, y, w, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, fctx, ); } else { push_intra_rect( plane, x, y, w, h, mode, angle_delta, reach, residual, cfl, filter_intra, smooth_neighbor, fctx, ); } } /// ONE RECT chroma transform unit of a square block's uv plane /// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and /// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64 /// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`] /// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the /// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped /// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers /// the plane block exactly, so no `+3` bigger-plane term -- that one lives in /// the square multi-unit walks' `chroma_ctx_offset`), and the plane's /// predicted mode supplies the mode-derived default `tx_type` unless an armed /// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an /// entropy class of 32x32 and up, where the spec forces `DCT_DCT` /// ([`read_plane`]'s `side >= 32` clamp). #[allow(clippy::too_many_arguments)] fn read_rect_chroma_unit( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, set: TxbSet, scan: &[u16], w: usize, h: usize, plane_idx: usize, around: (bool, bool, i32), uv_predict_mode: usize, angle_delta_uv: i32, reach: Reach, // Unread, like [`read_plane`]'s own: the borrow proves the caller holds // the plane exclusively while the unit's coefficients are parsed. _plane: &mut PlaneBuf<'static>, x: usize, y: usize, // Signature parity with [`read_plane`]; the dequant reads its q index // off `block_q_idx(fctx)` like every other reader here. _base_q_idx: u8, // lane-av1-422p: `get_txb_ctx_general`'s chroma branch // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`, // where `ctx_offset` is 10 when the plane block is bigger than the // transform and 7 otherwise. The port stores the offset-7 rows at // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6 // (lane-av1-422b), so a unit SMALLER than its plane block passes // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole // plane block stays `None` -- 4:2:2 plane blocks never shrink to a // rect unit except in the chunk arms. chroma_skip_offset: Option, cfl: Option<(i32, CflSrc)>, smooth_neighbor_uv: bool, fctx: &crate::decode::FrameCtx, ) -> Result { if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h { hit!(CHROMA422_RECT_HITS); } // The same three cases as [`read_plane`], for the same reason: at 32 points // an INTER chroma unit's transform set is `EXT_TX_SET_DCT_IDTX` (the luma's // coded `IDTX` survives) where the intra set is `EXT_TX_SET_DCTONLY`, and // an armed [`INTRABC_CHROMA_TX`] slot means the block IS an inter block. let default_tx = if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) { if w.max(h) >= 32 { reduce_inherited_chroma_tx_type(inherited, w, h, fctx) } else { inherited } } else if w.max(h) >= 32 { TxType::DctDct } else { default_intra_tx_type(uv_predict_mode as u8) }; let mut coding = cdfs.txb(set, uv_predict_mode); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, scan, w, h, usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0), dc_sign_ctx(around.2), default_tx, plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, w, h, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, block_iqmatrix(fctx, plane_idx, w, h, tx_type), ); push_intra_rect( plane_idx, x, y, w, h, uv_predict_mode, angle_delta_uv, reach, &residual, cfl, None, smooth_neighbor_uv, fctx, ); 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); } // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size // tables/scans are replaced by the 4x4 ones and the block always takes the // multi-transform-unit path below. lane-av1mixloss: this rewrite used to // sit at the TOP of the function -- before `read_intra_mode`, which is // where the block's own `segment_id` is read -- so a mixed frame resolved // every block's geometry against the PREVIOUS block's segment (a lossless // neighbour forced 4x4 units on a lossy block; a lossy one handed the // lossless TxParams an 8x8 grid). libaom's order is the opposite one: // `decode_mbmi_block` (segment id included) runs before any tx-size rule. // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this // rewrite (which sat above `read_intra_mode`) rides along here -- same // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own // segment like the lossless arm above it. let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) { (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4)) } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 { let tx = if side >= 64 { 32 } else { side }; let (set, scan): (TxbSet, &[u16]) = match tx { 32 => (TxbSet::Chroma32, scan32), 16 => (TxbSet::Chroma16, scan16), 8 => (TxbSet::Chroma8, scan8), _ => (TxbSet::Chroma4, scan4), }; (luma_set, set, luma_tx, tx, tx, (scans.0, scan)) } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 { // lane-av1-422f: the uv plane block is the (side/2, side) rect // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` -- // the RECT that fills the plane block, NOT the square transform of // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 -> // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid). // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid // cell and key their rect reads on `chroma_tx != chroma_tx_h`. let (tx_w, tx_h) = match side { 4 => (4, 4), 8 => (4, 8), 16 => (8, 16), 32 => (16, 32), // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32. _ => (32, 32), }; let (set, scan): (TxbSet, &[u16]) = match side { 4 => (TxbSet::Chroma4, scan4), 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]), 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]), 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]), _ => (TxbSet::Chroma32, scan32), }; (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan)) } else { (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans) }; 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, fctx); 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 `get_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; // libaom `parse_decode_block`'s var-tx tree condition carries // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc // block inside a LOSSLESS segment of a mixed frame reads NO // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line // hands back TX_4X4. Invisible while every lossless frame was also // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which // is why the mixed frame is the first stream to reach it. let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx); 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); // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM. // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no // longer refused -- the luma reconstruct below walks the tree's own // leaf list per leaf (libaom `decode_token_recon_block`, whose token // loop reconstructs whatever `read_tx_size_vartx` resolved, per // transform unit), so mixed sizes reconstruct at their own stride. // The counter marks the shape so a gate can prove a witness actually // carries a mixed tree and not merely another uniform one. 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 { hit!(INTRABC_VARTX_MIXED_LEAVES_HITS); if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") { eprintln!( "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \ dv={intrabc_dv:?} leaves={leaves:?}" ); } } Some(leaves) } else { None }; let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) { (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, fctx); (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. (lossless_tx(side.min(64), fctx), 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() { inter_txbset_for(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 >> ss_x(fctx), py >> ss_y(fctx)); let chroma_side = side >> ss_x(fctx); // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4), // `side / 2` at 4:2:0. let chroma_height = side >> ss_y(fctx); // 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, 0), mv_to_q4(py, dv_row, 0), side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx, ); let mut ub = vec![0u16; chroma_side * chroma_height]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), chroma_side, chroma_height, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; chroma_side * chroma_height]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), chroma_side, chroma_height, 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. // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call // (the `else` arm below -- a palette/intrabc block never takes the per-unit // `split_tx_skip` walk), so its map must be armed here even when the // transform is split. Gating the arm on `logical_tx == side` alone left a // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen // key frame; class override-slot-on-one-arm). Neither prediction is // edge-derived, so the whole-block buffer at the block's own stride is // exactly what that single call wants. // Counted on the SHAPE, not on the arm below, so a gate can tell a stream // that reaches this block apart from one that never does (class // gate-blind-to-feature). if palette_y_buf.is_some() && skip && logical_tx < side { hit!(SKIP_SPLIT_TX_OVERRIDE_HITS); } if let Some(buf) = &palette_y_buf && (logical_tx == side || skip) { 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)); // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` -- // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide, // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64 // reads ONE unit per plane, the whole plane block). let cn_cols = (chroma_side / chroma_tx).max(1); let cn_rows = (chroma_height / chroma_tx_h).max(1); let luma_span_x = chroma_tx << ss_x(fctx); let luma_span_y = chroma_tx_h << ss_y(fctx); for cu_row in 0..cn_rows { for cu_col in 0..cn_cols { let cu_r = if cn_rows == 1 && cn_cols == 1 { reach } else { tu_reach_rect( side, side, cu_col * luma_span_x, cu_row * luma_span_y, luma_span_x, luma_span_y, reach, px, py, y.width, y.height, fctx, ) }; let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h); // lane-av1chromadc: the chroma override is a whole // `chroma_side x chroma_height` buffer and // `PlaneBuf::reconstruct` uses the buffer it takes as the // UNIT's own `chroma_tx x chroma_tx_h` prediction, so a // multi-unit plane block must hand each unit its own window of // it. Handing the whole buffer (the pre-fix shape) made every // unit predict from the top-left one: at 4:2:0 the chroma plane // block is a single 32x32 unit, so the whole buffer IS that // unit's window and the bug is invisible -- which is why every // 4:2:0 gate stayed green -- and at 4:4:4 a 64x64 block's 64x64 // plane block is a 2x2 grid whose right and bottom columns were // a copy of its top-left unit. // MEASURED on `fixtures/r512.obu` (4:4:4 8-bit 512x512, three // frames): frame 0's skipped 64x64 intra-BC block at // `mi=(112,80)` `px=(320,448)` reconstructed its `cu=(1,0)` // unit at `px=(352,448)` as a flat 241 where the oracle has // 202 -- byte-identical to its `cu=(0,0)` prediction, sum // 882176 and all -- and the coded 64x64 to its right then read // 202/175 against the oracle's 165/166. Gate: // `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit`. let chroma_window = |buf: &[u16]| -> Vec { if cn_cols == 1 && cn_rows == 1 { return buf.to_vec(); } let mut window = Vec::with_capacity(chroma_tx * chroma_tx_h); for row in 0..chroma_tx_h { let at = (cu_row * chroma_tx_h + row) * chroma_side + cu_col * chroma_tx; window.extend_from_slice(&buf[at..at + chroma_tx]); } window }; if let Some((ub, _)) = &palette_uv_bufs { if cn_cols * cn_rows > 1 { hit!(SKIP_CHROMA_OVERRIDE_WINDOW_HITS); } set_palette_pred(chroma_window(ub), fctx); } push_intra_unit( 1, cu_x, cu_y, chroma_tx, chroma_tx_h, uv_predict_mode, angle_delta_uv, cu_r, &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(chroma_window(vb), fctx); } push_intra_unit( 2, cu_x, cu_y, chroma_tx, chroma_tx_h, uv_predict_mode, angle_delta_uv, cu_r, &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h], 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)))); } // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane // is the same size as luma and `av1_get_max_uv_txsize` caps it at // TX_32X32, so a 64x64 block codes four chroma units, plane-major // (every U, then every V) — the same loop the multi-TU arm runs. // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read. // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall. // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one // unit is the plane block's own rect. let cn_cols = (chroma_side / chroma_tx).max(1); let cn_rows = (chroma_height / chroma_tx_h).max(1); let luma_span_x = chroma_tx << ss_x(fctx); let luma_span_y = chroma_tx_h << ss_y(fctx); let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 { if chroma_tx == chroma_tx_h { 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, )?; (u_grid, v_grid, Vec::new()) } else { // lane-av1-422f: the one unit is a RECT filling the plane // block -- the square-shaped [`read_plane`] cannot express // it, so both planes go through [`read_rect_chroma_unit`] // (U, then V, the same order the square arm reads). The // chroma context reads per chroma 4-px cell (see // [`Neighbours::around_mi_422_chroma`]). let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } let u_grid = read_rect_chroma_unit( dec, cdfs, chroma_set, scans.1, chroma_tx, chroma_tx_h, 1, chroma_around[1], uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, base_q_idx, None, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), smooth_neighbor_uv, fctx, )?; if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } let v_grid = read_rect_chroma_unit( dec, cdfs, chroma_set, scans.1, chroma_tx, chroma_tx_h, 2, chroma_around[2], uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, base_q_idx, None, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), smooth_neighbor_uv, fctx, )?; (u_grid, v_grid, Vec::new()) } } else { let chroma_ctx_offset = Some(3); let mut u_pass: Vec = Vec::new(); let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new(); let mut last_grids = [Grid::Zero(0), Grid::Zero(0)]; for plane_pass in 1..=2usize { let mut pass_idx = 0usize; for cu_row in 0..cn_rows { for cu_col in 0..cn_cols { let cu_mi = ( mi_r + cu_row * (luma_span_y / MI), mi_c + cu_col * (luma_span_x / MI), ); let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 { // lane-av1-422f: chroma-only loop; per-chroma-cell // above votes (see [`Neighbours::around_mi_422_chroma`]). neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y) } else { neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y) }; let cu_reach = tu_reach_rect( side, side, cu_col * luma_span_x, cu_row * luma_span_y, luma_span_x, luma_span_y, reach, px, py, y.width, y.height, fctx, ); let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane_pass == 1 { ub } else { vb }; set_palette_pred( palette_window( pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx_h, chroma_tx, chroma_tx_h, ), fctx, ); } let buf: &mut PlaneBuf<'static> = if plane_pass == 1 { &mut *u } else { &mut *v }; let cu_grid = read_plane( dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode, uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, alpha .zip(ac) .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)), None, chroma_ctx_offset, smooth_neighbor_uv, fctx, )?; hit!(CHROMA_SPLIT_TX_HITS); if ss_x(fctx) == 1 && ss_y(fctx) == 0 { hit!(CHROMA422_SQUARE_HITS); } // Immediately, so the next unit of this block reads this // one's coefficient context. `record` below stamps one // chroma state across the whole block; the replay after // it puts the per-unit state back. neighbours.record_mi_chroma( cu_mi, luma_span_x, luma_span_y, plane_pass, &cu_grid, ); if plane_pass == 1 { u_pass.push(cu_grid); } else { let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0)); units.push(( cu_mi, luma_span_x, luma_span_y, u_grid.clone(), cu_grid.clone(), )); last_grids = [u_grid, cu_grid]; } pass_idx += 1; } } } (last_grids[0].clone(), last_grids[1].clone(), units) }; fctx.intrabc_chroma_tx.with(|c| c.set(None)); neighbours.record( at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]], ); for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units { neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit); neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit); } } 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; // lane-av1-422f: unit width/height per axis, like walk 2 above -- // a 4:2:2 frame below side 64 reads ONE rect unit per plane per // chunk, the whole plane block. let cn_cols = (chroma_side / chroma_tx).max(1); let cn_rows = (chroma_height / chroma_tx_h).max(1); let luma_span_x = chroma_tx << ss_x(fctx); let luma_span_y = chroma_tx_h << ss_y(fctx); // 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_rows * cn_cols > 1 { Some(3) } else { None }; let tpc = (n_axis / nchunk).max(1); let cpc_rows = (cn_rows / nchunk).max(1); let cpc_cols = (cn_cols / nchunk).max(1); // The block's luma transform units, raster order inside each mu // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx // tree's own leaf list -- mixed sizes included, exactly what libaom's // `decode_token_recon_block` token loop reconstructs (one // `av1_read_coeffs_txb` + inverse transform per resolved unit) -- // while every other block's list is the uniform `logical_tx` grid // this loop has always walked, generated here in the same order. let mut chunk_tus: Vec> = vec![Vec::new(); nchunk * nchunk]; if let Some(leaves) = &intrabc_leaves { for &(lr, lc, tw, _th) in leaves { let (off_y, off_x) = (lr * MI, lc * MI); chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw)); } } else { for tu_row in 0..n_axis { for tu_col in 0..n_axis { chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push(( tu_row * logical_tx, tu_col * logical_tx, logical_tx, )); } } } let mut last_grids = [Grid::Zero(0), Grid::Zero(0)]; let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new(); for ch_row in 0..nchunk { for ch_col in 0..nchunk { // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx // type of the co-located luma position (`av1_get_tx_type`, // blockd.h:1278: a non-Y plane of an inter-classified block -- and // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the // luma unit covering it). Inside a mu chunk that is the chunk's // FIRST luma unit in raster order (the chunk origin is always the // first leaf's own origin). Captured right after that unit's read; // the single-TU arm below does the same for a whole-block unit. let mut first_leaf_tx: Option = None; for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] { let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI); let tu_px = px + tu_off_x; let tu_py = py + tu_off_y; // 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, tu_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_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height, fctx, ); // This transform unit's own bsize (`tu_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, tu_tx / MI); // An intrabc unit's CDF set and scan follow the unit's OWN // resolved size (`get_txsize_entropy_ctx` / // `av1_get_scan` per `av1_read_coeffs_txb` call); the // uniform grid's precomputed pair already matches because // `tu_tx == logical_tx` there. let (tu_set, tu_scan) = if intrabc_dv.is_some() { ( inter_txbset_for(tu_tx, reduced_tx_set), scan_for( if tu_tx == 64 { 32 } else { tu_tx }, scan32, scan16, scan8, scan4, ), ) } else { (luma_set, luma_scan) }; if let Some(buf) = &palette_y_buf { hit!(PALETTE_SPLIT_TX_HITS); let mut window = vec![0u16; tu_tx * tu_tx]; for row in 0..tu_tx { let src = (tu_off_y + row) * side + tu_off_x; window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]); } set_palette_pred(window, fctx); } let tu_grid = read_plane( dec, cdfs, tu_set, tu_scan, 0, tu_around, mode, mode, angle_delta_y, tu_reach, y, tu_px, tu_py, tu_tx, // The unit's own COEFFICIENT grid, half its side at // TX_64X64 (a 64-point transform codes nothing past 32); // identical to `tu_tx` at every smaller size // (lane-sb128b r1). if tu_tx == 64 { 32 } else { tu_tx }, 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, tu_tx, &tu_grid); if first_leaf_tx.is_none() { first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get)); } } // 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)); // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded // tx type (see `first_leaf_tx` above) -- the same arm the single-TU // branch sets before its own chroma reads. if intrabc_dv.is_some() { if let Some(t) = first_leaf_tx { fctx.intrabc_chroma_tx.with(|c| c.set(Some(t))); } } // 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. // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of // the chunk, then every V unit. At one unit per plane per chunk -- // every non-lossless case this decoder reaches -- that is the same // symbol order as the interleaved pair this loop used to read; a // lossless frame's 4x4 chroma units are the case where it differs // (lane-lossless2). let mut u_pass: Vec = Vec::new(); for plane_pass in 1..=2usize { let mut pass_idx = 0usize; for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows { for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols { // libaom `decode_reconstruct_tx`'s frame-edge clip // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col // >= max_blocks_wide` returns before ANY symbol is read): a // transform unit whose 4x4 origin sits outside the frame's mi // grid is not coded at all. The luma loop above carries the // same clip; its absence here read `txb_skip` (+coeffs) for // chroma units libaom never wrote -- the lossless 64x64 block // at mi(48,0) of a 320x240 frame overhangs the bottom edge by // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not // eight (lane-av1-loss64; 48 chroma units per plane in // aomdec's EC_COEFF census vs the 64 this loop read). // `max_block_wide/high` (av1_common_int.h:1565): the plane // block's pixel span (4:2:0 halves the luma span, clamped to // 4 by `set_plane_n4`) plus the negative overhang // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4 // units. let span_mi = side / MI; let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32 - mi_c as i32 - span_mi as i32; let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32 - mi_r as i32 - span_mi as i32; // `max_block_wide/high` in chroma pixels: the plane block's // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4 // block's coded units and desynced the tile) plus the // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose // chroma-px scale is `MI >> ss` per mi. let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32; let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32; let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32; let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize; // lane-av1-422f: the shared halved formula in the `else` counts // the plane span in 4-px units through the 2-px-per-mi // subsampled height, which a 4:2:2 plane does not have (ss_y // 0) -- its span is the full luma mi count, so a keyed // formula clips the same units libaom's `max_block_high` // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the // pre-ss form spelled). let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 { (span_mi as i32 + over_h_mi.min(0)).max(0) as usize } else { ((plane_px + over_h_px) >> 2).max(0) as usize }; let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4); if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h { hit!(CHROMA_EDGE_TU_CLIP_HITS); continue; } // The chroma context arrays are indexed in LUMA mi, so this // unit's anchor is its own luma quadrant (lane-av1-422b: the // quadrant spans `chroma_tx << ss_x` luma px wide by // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the // one unit's quadrant is the whole block). let cu_mi = ( mi_r + cu_row * (luma_span_y / MI), mi_c + cu_col * (luma_span_x / MI), ); let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 { // lane-av1-422f: chroma-only loop; per-chroma-cell above // votes (see [`Neighbours::around_mi_422_chroma`]). neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y) } else { neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y) }; let cu_reach = if cn_rows == 1 && cn_cols == 1 { reach } else { tu_reach_rect( side, side, cu_col * luma_span_x, cu_row * luma_span_y, luma_span_x, luma_span_y, reach, px, py, y.width, y.height, fctx, ) }; let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane_pass == 1 { ub } else { vb }; set_palette_pred( palette_window( pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx_h, chroma_tx, chroma_tx_h, ), fctx, ); } let buf: &mut PlaneBuf<'static> = if plane_pass == 1 { &mut *u } else { &mut *v }; let cu_grid = if chroma_tx == chroma_tx_h { read_plane( dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode, uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, alpha.zip(ac).map(|((au, av), ac)| { (if plane_pass == 1 { au } else { av }, ac) }), None, chroma_ctx_offset, smooth_neighbor_uv, fctx, )? } else { // lane-av1-422f: the whole plane block as one rect unit; // `chroma_ctx_offset` is `None` there (the unit covers // the plane block, so the offset-7 skip rows are right). read_rect_chroma_unit( dec, cdfs, chroma_set, scans.1, chroma_tx, chroma_tx_h, plane_pass, cu_around[plane_pass], uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y, base_q_idx, None, alpha.zip(ac).map(|((au, av), ac)| { (if plane_pass == 1 { au } else { av }, ac) }), smooth_neighbor_uv, fctx, )? }; if cn_rows * cn_cols > 1 { hit!(CHROMA_SPLIT_TX_HITS); if ss_x(fctx) == 1 && ss_y(fctx) == 0 { hit!(CHROMA422_SQUARE_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_x, luma_span_y, plane_pass, &cu_grid, ); } if plane_pass == 1 { u_pass.push(cu_grid); } else { let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0)); if cn_rows * cn_cols > 1 { units.push(( cu_mi, luma_span_x, luma_span_y, u_grid.clone(), cu_grid.clone(), )); } last_grids = [u_grid, cu_grid]; } pass_idx += 1; } } } } if intrabc_dv.is_some() { fctx.intrabc_chroma_tx.with(|c| c.set(None)); } } // 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, sw, sh, u_grid, v_grid) in &units { neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid); neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 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 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size, // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED // intrabc block publish its BLOCK size instead, intrabc being the only // "inter" block an intra-only frame codes (`blockd.h:373`). So this call // stays the authority wherever one can appear; with `allow_intrabc` unset // it writes exactly what the grid already did. 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, neighbours, 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) }; /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this /// shape non-vacuous -- a stream that never codes one reads 0. pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT /// intra block re-stamped by the end-of-block replay /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma /// walk published, so every unit replays its own state after it). A /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2` /// of them, so this reads 0 on any stream that never codes one -- the /// non-vacuity anchor for the replay's own gate. pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// ... and the number of non-skip 128-root rect BLOCKS whose replay /// height differs from the unit's own LUMA-MI height -- the signature of the /// width passed to both axes (`luma_span` where the in-loop stamp used /// `luma_span_h`). Zero on every stream this decoder admits: both /// supported chroma formats have `ss_x == ss_y` (4:2:0 and 4:4:4), and /// 4:2:2 -- the one format whose two spans differ -- is refused by name /// at the sequence header (`stream::decode_frame`), so the arm is /// defensive until that format is ported. The counter turns a future /// 4:2:2 admission (or any hardcoded span) into a named red gate instead /// of silent mi-state corruption. pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_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_LOSSLESS_HITS`], for a gate's own before/after delta. pub(crate) fn intra128_lossless_hits() -> usize { INTRA128_LOSSLESS_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), ) } /// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by /// `decode_block_128rect`'s end-of-block replay) and /// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was /// not the unit's own), for a gate's own before/after delta. pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) { ( SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get), SB128RECT_REPLAY_SPAN_MISMATCH_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. /// /// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to /// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size /// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything /// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units /// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma /// units, plane-major inside each 64x64 mu chunk exactly as /// `decode_token_recon_block` codes them. Reading the 64-point geometry there /// reconstructs into a `side`-sized plane with a 16-sample residual (the panic /// this lane closed); the geometry and the unit walks below are normalized on /// `lossless_frame`. #[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, intrabc, ) = 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 let Some((dv_row, dv_col)) = intrabc { // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip // from this frame's own reconstruction and runs the INTER residual // walk (`decode_token_recon_block`'s else arm) over it. return decode_intrabc_128rect( dec, cdfs, neighbours, (mi_r, mi_c), (bw, bh), skip, (dv_row, dv_col), y, u, v, base_q_idx, 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, fctx); // 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). // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all -- // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame // before the symbol is even considered (`decodeframe.c:141`) and // `read_tx_size` returns `TX_4X4` before it looks at anything // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed. let lossless_frame = lossless(fctx); let in_inter = fctx .intra_in_inter_mode .with(std::cell::Cell::get) .is_some(); let depth = if tx_select && !lossless_frame { // lane-inter128intra r1: `get_tx_size_context` compares the bands // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- // TX_64X64 for every 128-axis block, hence the `min(64)`. let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx); 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 = if lossless_frame { 4 } else { 64 >> depth }; if lossless_frame { hit!(INTRA128_LOSSLESS_HITS); } // A 64-point transform codes nothing past its low 32 coefficients. let coeff_tx_side = logical_tx.min(32); let luma_set = if lossless_frame { TxbSet::Luma4 } else { txbset_for(logical_tx, reduced_tx_set) }; let luma_scan = default_scan(coeff_tx_side); // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan). let chroma_tx = if lossless_frame { 4 } else { 32 }; let chroma_set = if lossless_frame { TxbSet::Chroma4 } else { TxbSet::Chroma32 }; let chroma_scan = default_scan(chroma_tx); let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); let (nch_x, nch_y) = (bw / 64, bh / 64); // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's // `decode_token_recon_block` clips each vector's walk to // `max_block_wide/high`, so a chroma unit whose top-left is off the frame // codes nothing. let mi_cols = 2 * y.true_width.div_ceil(8); let mi_rows = 2 * y.true_height.div_ceil(8); let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c)); let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r)); // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per // axis -- one 32x32 at 4:2:0, two stacked on the tall axis at 4:2:2 // (lane-av1-422bigblock: the chunk's chroma plane block is 32x64 there), // four at 4:4:4 (lane-av1-444sb's own finding on this same walk). debug_assert!( lossless_frame || (chroma_w / chroma_tx, chroma_h / chroma_tx) == ( nch_x * ((64 >> ss_x(fctx)) / chroma_tx), nch_y * ((64 >> ss_y(fctx)) / chroma_tx) ) ); 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, usize), Grid)> = Vec::new(); // The chroma context arrays are indexed in LUMA mi; every chroma unit of // every chunk shares this luma span (2 chroma pixels per luma unit). let luma_span = chroma_tx << ss_x(fctx); let luma_span_h = chroma_tx << ss_y(fctx); 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); } } // Transform units per axis inside this mu chunk's chroma span: // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis, // so it holds `(64 >> ss) / chroma_tx` units -- one 32x32 at // 4:2:0, four at 4:4:4 (lane-av1-444sb), TWO STACKED TX_32X32 on // the tall axis at 4:2:2 (lane-av1-422bigblock: the chunk's // chroma plane block is 32x64 there, so the two axes' counts // part ways -- 1 x 2); 8x8 TX_4X4 units when lossless. let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1); let cn_h = ((64 >> ss_y(fctx)) / chroma_tx).max(1); // libaom's per-chunk `unit_width/height` (plane-mi units of the // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`. let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx); let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx); let stepc = (chroma_tx / 4).max(1); // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U // unit of the chunk, then every V unit. At one unit per plane per // chunk (every non-lossless 128-axis block) that is the same // symbol order the interleaved pair used to read; a lossless // frame's 4x4 chroma units are where it becomes observable. for plane_pass in 1..=2usize { for ci_row in 0..cn_h { for ci_col in 0..cn { // The clamp strides are the CHUNK's chroma mi extent // per axis: 16 luma mi >> the axis's own ss. if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h { continue; } let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx; let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx; let cu_mi = ( mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4), mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4), ); let cu_r = tu_reach_rect( bw, bh, ch_col * 64 + ci_col * luma_span, ch_row * 64 + ci_row * luma_span_h, luma_span, luma_span_h, reach, px, py, y.width, y.height, fctx, ); if skip { push_intra( plane_pass, 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_rect(cu_mi, luma_span, luma_span_h); let buf: &mut PlaneBuf<'static> = if plane_pass == 1 { &mut *u } else { &mut *v }; let grid = read_plane( dec, cdfs, chroma_set, &chroma_scan, plane_pass, cu_around[plane_pass], mode, uv_predict_mode, angle_delta_uv, cu_r, buf, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None, Some(3), smooth_neighbor_uv, fctx, )?; last_grids[plane_pass - 1] = grid.clone(); // 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_h, plane_pass, &grid, ); units.push((plane_pass, cu_mi, grid)); } } } if !skip { hit!(CHROMA_SPLIT_TX_HITS); } } } 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]], ); // lane-av1-128rectspan: the replay must re-stamp each unit over the // SAME cells the walk above stamped it over -- `record_mi_chroma`'s // height drives `left[]` and its width `above[]`, and the walk used // the per-axis `luma_span_h`. Passing the width on both axes doubled // the `left[]` run wherever the two differ (4:2:2), reaching 8 mi // rows below the block on the last unit of a 128x64/64x128 strip and // smearing a neighbour chunk's unit over its neighbour's rows. // // DEFENSIVE at the decoder's current capability set: both admitted // chroma formats have `ss_x == ss_y` (4:2:0 ss (1,1), 4:4:4 ss // (0,0)), so the two spans are equal and this line is a no-op on // every stream `decode_stream` accepts; 4:2:2 (ss (1,0)) -- the one // format where they differ -- is refused by name at the sequence // header, so the arm is unreachable there. It stays per-axis because // the walk it replays is per-axis, and a 4:2:2 port must not have to // re-derive this. `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` names the // day that changes. if luma_span != luma_span_h { hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS); } for (plane, cu_mi, grid) in &units { neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid); hit!(SB128RECT_CHROMA_REPLAY_HITS); } } // 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 || allow_intrabc_frame(fctx) { // `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 reads those bands only when it allows intrabc // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom // stamps here too -- lane-av1-intrabc r3. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh)); } if in_inter { 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, fctx); 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). // `parse_decode_block`'s tree condition carries // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy): // a lossless segment's intrabc leaf reads no tree, TX_4X4 via // `read_tx_size`'s first line (lane-av1mixloss). let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) { 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, fctx) } else { // lane-lossless: TX_4X4 on a lossless frame, no symbol // (libaom `read_tx_size`). lossless_tx(8, fctx) }; 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 >> ss_x(fctx), py >> ss_y(fctx)); // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma, // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for. // lane-av1-422d: 4:2:2 (ss 1/0) halves only the width, so the plane block // is 4x8 -- ONE rect transform unit per plane (`av1_get_max_uv_txsize( // BLOCK_8X8)` at ss (1,0) is `max_txsize_rect_lookup[BLOCK_4X8]` == // TX_4X8): one txb_skip + one scan per plane in the // [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the // shape, read through [`leaf8_chroma422_unit`] in each arm below. The // `(csz, cset, cscan)` selection keeps serving the square arms (444's // 8x8, 420's 4x4); the rect arms branch on [`chroma_422`] instead. let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0; let (csz, cset, cscan) = if chroma_444 { (8usize, TxbSet::Chroma8, scans.0) } else { (4usize, TxbSet::Chroma4, scans.1) }; // 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, 0), mv_to_q4(py, dv_row, 0), 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx, ); // The chroma extent is THIS frame's subsampled size of the 8x8 luma // leaf (`get_plane_block_size`): 4x4 at 4:2:0, 4x8 at 4:2:2, 8x8 at // 4:4:4. The literal 4x4 this replaces hardcoded the 4:2:0 halving -- // at 4:4:4 the 16-sample override fed this leaf's own 8x8 chroma // reconstruct, which indexed `prediction[16]` of a 16-sample buffer // (len 16, index 16 at `PlaneBuf::reconstruct`), and at 4:2:2 it // covered half the leaf's 4x8 chroma plane block (lane-av1-422d's // `if chroma_422 { (4, 8) }` arm, which the ss-derived form subsumes: // `8 >> ss_x` is 4 and `8 >> ss_y` is 8 there). The same buffers // are windowed at stride 8 by `read_intra_chroma_lossless` (the TX4 // 4:4:4-lossless arm) and consumed whole by the TX8 and skip arms, // so all three heal with this one sizing. let (cw, ch) = (8 >> ss_x(fctx), 8 >> ss_y(fctx)); let mut ub = vec![0u16; cw * ch]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), cw, ch, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; cw * ch]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), cw, ch, 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, }; // lane-av1intrapred: the chroma twin of the `palette_y_buf` wrap above -- // `decode_block` does the same for its own `palette_uv_bufs` // (decode.rs's single-TU and multi-TU chroma reads). Without it, an // intrabc leaf whose var-tx tree split to TX_4X4 reached the TX4 arm's // chroma reads with the override unset: the unit predicted INTRA from // the UV mode (intrabc's is DC) instead of copying the frame at the DV, // R5 first differing pixel U(184,4), block mi (2,92). let palette_uv_bufs = match &intrabc_bufs { Some((_, ub, vb)) => Some((ub.clone(), vb.clone())), None => palette_uv_bufs, }; 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)); // Three skip-arm shapes, dispatched on THIS frame's subsampling. // lane-av1-422d: at 4:2:2 a skipped leaf still predicts its 4x8 rect // unit per plane (CfL keeps its contribution, [`decode_block`]'s own // skip-arm rule); no coefficient symbol exists, so the entropy // context never enters the rect read. // lane-av1422llintra: NOT in a LOSSLESS frame -- `av1_get_tx_size`'s // first line returns TX_4X4 on every plane there, so the 4x8 plane // block is two 4x4 units and the `else` arm's per-unit walk is the // right one. if chroma_422 && !lossless(fctx) { u_grid = leaf8_chroma422_unit( dec, cdfs, (false, false, 0), uv_predict_mode, angle_delta_uv, reach, 1, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), true, intrabc_bufs .as_ref() .map(|(_, ub, _)| ub.clone()) .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())), u, cpx, cpy, smooth_neighbor_uv, fctx, )?; v_grid = leaf8_chroma422_unit( dec, cdfs, (false, false, 0), uv_predict_mode, angle_delta_uv, reach, 2, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), true, intrabc_bufs .as_ref() .map(|(_, _, vb)| vb.clone()) .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())), v, cpx, cpy, smooth_neighbor_uv, fctx, )?; luma_grid = Grid::Zero(64); } else { // 4:4:4 AND 4:2:2 lossless: the leaf's chroma plane block is a // raster of TX_4X4 units (`av1_get_tx_size` returns TX_4X4 for // EVERY plane of a lossless block, so `av1_get_max_uv_txsize` -- // the TX_4X8 the 4:2:2 arm above reads -- is never reached), so a // skipped leaf predicts per unit -- each from its own edges -- like // the luma `SKIP_SPLIT_TX` loop above. At 4:2:2 that plane block is // 4x8 (`av1_ss_size_lookup[BLOCK_8X8][1][0]`), so it is one 4x4 // unit per chroma row pair. CfL never fires here (`is_cfl_allowed` // at lossless needs plane_bsize == BLOCK_4X4; this plane block is // 8x8 at 4:4:4 and 4x8 at 4:2:2, neither of which is BLOCK_4X4), // and intrabc/palette keep the whole-plane-block prediction they // already run. let chroma_units_ll = (chroma_444 || chroma_422) && lossless(fctx) && intrabc_bufs.is_none() && palette_uv_bufs.is_none(); let cu_shape: (usize, usize) = if chroma_422 { (4, 8) } else { (8, 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); } if chroma_units_ll { for cu_row in 0..cu_shape.1 / 4 { for cu_col in 0..cu_shape.0 / 4 { let cu_reach = tu_reach( 8, 8, cu_col * 4, cu_row * 4, 4, reach, px, py, y.width, y.height, fctx, ); push_intra( 1, cpx + cu_col * 4, cpy + cu_row * 4, 4, uv_predict_mode, angle_delta_uv, cu_reach, &ZERO_RESIDUAL[..16], None, None, smooth_neighbor_uv, fctx, ); } } } else { push_intra( 1, cpx, cpy, csz, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..csz * csz], 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); } if chroma_units_ll { for cu_row in 0..cu_shape.1 / 4 { for cu_col in 0..cu_shape.0 / 4 { let cu_reach = tu_reach( 8, 8, cu_col * 4, cu_row * 4, 4, reach, px, py, y.width, y.height, fctx, ); push_intra( 2, cpx + cu_col * 4, cpy + cu_row * 4, 4, uv_predict_mode, angle_delta_uv, cu_reach, &ZERO_RESIDUAL[..16], None, None, smooth_neighbor_uv, fctx, ); } } } else { push_intra( 2, cpx, cpy, csz, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..csz * csz], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); } luma_grid = Grid::Zero(64); u_grid = Grid::Zero(csz * csz); v_grid = Grid::Zero(csz * csz); } } else if resolved != 4 { let around = neighbours.around_mi(leaf_mi, 8); // lane-av1-422h: the 4:2:2 chroma rect unit's `get_txb_ctx_general` // reads its above votes over CHROMA 4-px cells -- at ss_x 1 one chroma // cell spans TWO luma mi columns, so the per-luma-mi sum counts each // above chroma column twice and `dc_sign_ctx`'s signum flips whenever // the doubled sum crosses zero (the same class // [`Neighbours::around_mi_422_chroma`] fixes for the rect readers; // measured at mi(2,24) plane 2: ours dc_sign row 0, oracle row 2). // The left extent is unsubsquared at ss_y 0 and stays one-to-one. let chroma_around = if chroma_422 { neighbours.around_mi_422_chroma(leaf_mi, 8, 8) } else { around }; if let Some(buf) = &palette_y_buf { set_palette_pred(buf.clone(), fctx); } luma_grid = read_plane( dec, cdfs, if intrabc_dv.is_some() { inter_txbset_for(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 chroma_422 { // lane-av1-422d: ONE 4x8 rect unit per plane (`av1_get_max_uv_txsize` // at ss (1,0) == TX_4X8), covering the plane block exactly, off the // leaf's own 8x8-span entropy context (`chroma_tiled`'s convention). u_grid = leaf8_chroma422_unit( dec, cdfs, chroma_around[1], uv_predict_mode, angle_delta_uv, reach, 1, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), false, intrabc_bufs .as_ref() .map(|(_, ub, _)| ub.clone()) .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())), u, cpx, cpy, smooth_neighbor_uv, fctx, )?; v_grid = leaf8_chroma422_unit( dec, cdfs, chroma_around[2], uv_predict_mode, angle_delta_uv, reach, 2, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), false, intrabc_bufs .as_ref() .map(|(_, _, vb)| vb.clone()) .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())), v, cpx, cpy, smooth_neighbor_uv, fctx, )?; } else { 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, cset, cscan, 1, around[1], mode, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, csz, csz, 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, cset, cscan, 2, around[2], mode, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, csz, csz, 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). let mut first_leaf_tx: Option = None; 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() { inter_txbset_for(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); // The FIRST (top-left, co-located with this group's chroma) // TU's coded tx_type is what the group's chroma inherits -- // the same capture [`decode_block`]'s multi-TU branch makes // for `first_leaf_tx` (libaom `av1_get_tx_type`, blockd.h: // an inter-classified block's `PLANE_TYPE_UV` reads // `tx_type_map`, and intrabc is inter-classified). if first_leaf_tx.is_none() { first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get)); } } } // lane-av1intrapred: an intrabc leaf whose var-tx tree split to // TX_4X4 never armed [`INTRABC_CHROMA_TX`], so its chroma reads fell // back to `default_intra_tx_type(DC_PRED)` = `DCT_DCT` and took the // 2D scan, the 2D eob row and the 2D nz contexts where libaom takes // the inherited luma type's (R5's first fork: mi (36,66), luma // (0,0) coded `H_ADST` off the 16-symbol inter set, chroma U then // decoded its `eob` from the wrong CDF row). Same arm the // `resolved != 4` branch above runs for its whole-leaf unit. if intrabc_dv.is_some() { if let Some(t) = first_leaf_tx { fctx.intrabc_chroma_tx.with(|c| c.set(Some(t))); } } let ac = alpha.map(|_| cfl_src(px, py, 8)); // lane-av1-422h: same ss_x-1 dc-vote sampling as the whole-leaf arm // above -- the doubled above sum crosses zero at mi(2,24) plane 2. let chroma_around = if chroma_422 { neighbours.around_mi_422_chroma(leaf_mi, 8, 8) } else { neighbours.around_mi(leaf_mi, 8) }; // lane-av1intrapred: the non-vacuity counter -- armed slot consulted // by this arm's chroma reads means the frame-copy + inherited-type // route ran; zero at gate time means the fixture stopped reaching it. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { hit!(INTRABC_TX4_CHROMA_COPY_HITS); } if chroma_422 && !lossless(fctx) { // lane-av1-422d: the chroma unit does NOT follow the luma var-tx // split -- `uv_txsize` is `av1_get_max_uv_txsize` of the block, // still the one 4x8 rect unit per plane at ss (1,0). u_grid = leaf8_chroma422_unit( dec, cdfs, chroma_around[1], uv_predict_mode, angle_delta_uv, reach, 1, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), false, intrabc_bufs .as_ref() .map(|(_, ub, _)| ub.clone()) .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())), u, cpx, cpy, smooth_neighbor_uv, fctx, )?; v_grid = leaf8_chroma422_unit( dec, cdfs, chroma_around[2], uv_predict_mode, angle_delta_uv, reach, 2, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), false, intrabc_bufs .as_ref() .map(|(_, _, vb)| vb.clone()) .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())), v, cpx, cpy, smooth_neighbor_uv, fctx, )?; } else if (chroma_444 || chroma_422) && lossless(fctx) { // lane-av1422llintra: a LOSSLESS 4:2:2 leaf is the 4:2:2 twin of // the 4:4:4 arm below. libaom's `av1_get_tx_size` (`blockd.h:1381`) // returns TX_4X4 for EVERY plane of a lossless block, and its // FIRST line is the lossless test -- so `av1_get_max_uv_txsize` // (the `Tx_4X8` the `chroma_422` arm above reads) is never reached // in a lossless frame. At ss (1,0) the leaf's chroma PLANE BLOCK is // 4x8 (`av1_ss_size_lookup[BLOCK_8X8][1][0]`), so it is a // `(4, 8)` region walked as two 4x4 units per plane, PLANE-MAJOR // -- the same walk `read_intra_chroma_lossless` runs for whole // blocks, at this leaf's own 4x8 plane block. // // MEASURED: the pinned 4:2:2 all-intra LOSSLESS control // `ll422_allintra.obu` (43 255 B, sha256 below) against the // instrumented `aomdec`: its block at mi(0,2) is `EC_IMODE_VAL // mi_row=0 mi_col=2 bsize=3` (BLOCK_8X8) and the oracle's // `EC_COEFF` units are `plane=1 row=0`, `plane=1 row=1`, // `plane=2 row=0`, `plane=2 row=1` -- four 4x4 units, two per // plane. This arm read ONE `TxbSet::ChromaRect8x4` 4x8 unit per // plane instead (our `EC_PRED` trace: // `x=4 y=0 plane=1 bw=4 bh=8 mode=1`, the first line that // disagrees with the oracle's `EC_PREDOUT8 // plane=1 row_off=0 txw=4 txh=4` + `row_off=1 txh=4` pair), so // the tile desynced at that block's second chroma symbol and // every later pixel decoded from the wrong place. // // CfL never rides here: `is_cfl_allowed` (`cfl.h:24`) allows it in // a lossless block only when the chroma PLANE BLOCK is // BLOCK_4X4, and a 4:2:2 8x8 leaf's is BLOCK_4X8 -- so // `read_intra_chroma_lossless`'s no-CfL `read_plane` is the // correct arm for this shape too. let (blk_w, blk_h) = if chroma_422 { (4usize, 8usize) } else { (8usize, 8usize) }; let (mut uo, mut vo) = (Vec::new(), Vec::new()); read_intra_chroma_lossless( dec, cdfs, neighbours, u, v, leaf_mi, (px, py), (cpx, cpy), 8, (blk_w, blk_h), (0, 0), (blk_w, blk_h), blk_w, reach, (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, base_q_idx, &mut uo, &mut vo, fctx, )?; u_grid = if uo.is_empty() { Grid::Zero(blk_w * blk_h) } else { Grid::Own(uo) }; v_grid = if vo.is_empty() { Grid::Zero(blk_w * blk_h) } else { Grid::Own(vo) }; hit!(CHROMA422_LOSSLESS_4X4_HITS); } else if chroma_444 && lossless(fctx) { // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster // of TX_4X4 units per plane, PLANE-MAJOR (`av1_get_tx_size`: // lossless forces TX_4X4 on EVERY plane) -- the same walk // `read_intra_chroma_lossless` runs for whole blocks. Reading one // TX_8X8 unit here panicked before: the lossless inverse is the // 4x4-only WHT (`TxParams::run`'s own `(w, h) == (4, 4)` // invariant), and the unit count desyncs the tile either way. // Per-unit `record_mi_chroma` calls stamp the neighbour bands // inside, which is why the tail's whole-leaf chroma stamp below // is skipped for this shape. let (mut uo, mut vo) = (Vec::new(), Vec::new()); read_intra_chroma_lossless( dec, cdfs, neighbours, u, v, leaf_mi, (px, py), (cpx, cpy), 8, (8, 8), (0, 0), (8, 8), 8, reach, (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, base_q_idx, &mut uo, &mut vo, fctx, )?; u_grid = if uo.is_empty() { Grid::Zero(64) } else { Grid::Own(uo) }; v_grid = if vo.is_empty() { Grid::Zero(64) } else { Grid::Own(vo) }; } else { if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } u_grid = read_plane( dec, cdfs, cset, cscan, 1, chroma_around[1], mode, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, csz, csz, 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, cset, cscan, 2, chroma_around[2], mode, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, csz, csz, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; } // The two chroma reads above are the only consulters of this leaf's // armed [`INTRABC_CHROMA_TX`]; leaving it set would make the NEXT // leaf's chroma inherit this leaf's luma type instead of its own // derivation (class armed-slot-leak-into-next-leaf, seen live: the // regular-intra leaf after an intrabc TX4 leaf took the intrabc // luma's `V_ADST` for its chroma eob row). if intrabc_dv.is_some() { fctx.intrabc_chroma_tx.with(|c| c.set(None)); } // `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); // The 4:4:4 AND 4:2:2 lossless walks above already stamped these // bands PER UNIT (their raster-order last writer per cell is exactly // libaom's per-entry last update); this whole-leaf aggregate would // clobber distinct unit states with one, so it runs only for the // shapes whose chroma really is one unit. if !((chroma_444 || chroma_422) && lossless(fctx)) { 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, neighbours, 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 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see // `decode_block`'s own copy for why this stays beside // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc // BLOCK-size term). 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, neighbours, fctx); Ok(mode) } /// lane-av1-422d: ONE 4:2:2 chroma transform unit of an 8x8 leaf /// ([`decode_leaf8`]). At ss (1,0) the plane block is 4x8 and /// `av1_get_max_uv_txsize(BLOCK_8X8)` resolves to /// `max_txsize_rect_lookup[BLOCK_4X8]` == TX_4X8, so the WHOLE plane block is /// a single rect unit -- one txb_skip + one scan per plane in the /// [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the /// shape. Mirrors [`sub8_leaf_chroma444`]'s rect arm at the leaf's halved /// position: the entropy context is the leaf's own 8x8 luma-span /// above/left state (the `chroma_tiled` arm's convention; no `+3` /// plane-block-bigger term -- the unit covers the plane block exactly), the /// CFL source is the leaf's whole 8x8 luma block, and the plane's predicted /// mode supplies the mode-derived default `tx_type` unless an armed /// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own (the caller /// arms and disarms it, exactly as it does around its square reads). #[allow(clippy::too_many_arguments)] fn leaf8_chroma422_unit( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, around: (bool, bool, i32), uv_predict_mode: usize, angle_delta_uv: i32, reach: Reach, plane_idx: usize, cfl: Option<(i32, CflSrc)>, skip: bool, // The prediction override the square arms feed through // `set_palette_pred`: an intrabc leaf's frame copy at the DV takes // priority over a palette block's colour-index map. pred_override: Option>, // Unread, like [`read_plane`]'s own: the borrow proves the caller holds // the plane exclusively while the unit's coefficients are parsed. _plane: &mut PlaneBuf<'static>, cpx: usize, cpy: usize, smooth_neighbor_uv: bool, fctx: &crate::decode::FrameCtx, ) -> Result { // The unit's prediction runs whether or not a residual follows it -- a // skipped leaf still predicts (the CfL contribution survives a skip), // and a skipped intrabc leaf still copies the frame at its DV. if let Some(buf) = pred_override { set_palette_pred(buf, fctx); } if skip { push_intra_rect( plane_idx, cpx, cpy, 4, 8, uv_predict_mode, angle_delta_uv, reach, &ZERO_RESIDUAL[..4 * 8], cfl, None, smooth_neighbor_uv, fctx, ); return Ok(Grid::Zero(4 * 8)); } let default_tx = fctx .intrabc_chroma_tx .with(std::cell::Cell::get) .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8)); let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, &SCAN_4X8, 4, 8, usize::from(around.0) + usize::from(around.1), dc_sign_ctx(around.2), default_tx, plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, 4, 8, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, block_iqmatrix(fctx, plane_idx, 4, 8, tx_type), ); push_intra_rect( plane_idx, cpx, cpy, 4, 8, uv_predict_mode, angle_delta_uv, reach, &residual, cfl, None, smooth_neighbor_uv, fctx, ); Ok(levels) } /// `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, // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4` // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf // left the second mi column at segment 0, which reads back as a // neighbour's `cdf_index`/prediction two blocks later. seg_w_mi: usize, seg_h_mi: usize, fctx: &crate::decode::FrameCtx, ) -> Result<( bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option, Option<(i32, i32)>, )> { // lane-av1mono: a monochrome leaf codes no chroma mode (libaom // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`. let has_chroma = has_chroma && !mono(fctx); let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64); if ec_istep { eprintln!( "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0 ); } // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block. macro_rules! istep { ($name:literal, $val:expr) => { if ec_istep { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}", $name, $val, dec.debug_state().0 ); } }; } // lane-seg2: same `intra_segment_id` placement as the square and rect // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id` // like any other block, over its own 1x1 mi footprint. Dropping it here // both ate a symbol (the tile desynced at the frame's first sub-8x8 // split) and left `cur_segment_id` on the previous block, so the leaf // dequantized with a neighbour's `SEG_LVL_ALT_Q`. 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 sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} 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); } maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx); istep!("cdef", 0); 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); if allow_intrabc { let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; if ec_istep { eprintln!( "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", u8::from(use_intrabc), dec.debug_state().0 ); } if use_intrabc { // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block // vector right after the flag and RETURNS -- no y/uv mode, angle // delta, palette, CfL or filter-intra syntax follows, and the // block is reconstructed by the INTER path (libaom's // `is_inter_block` counts an intrabc block), so the caller takes // the frame-copy prediction + inter residual. let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx); // lane-av1txr: the DV travels back in the RETURN value -- it is // NOT published through `FrameCtx::intrabc_dv`. That slot is the // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it, // then `take()` it in the same call), so a sub-8x8 leaf that // armed it left the vector standing for the NEXT >=8x8 block: // `warped.obu`'s (38,60) 8x8 intra block took it as its own // intrabc and read an inter var-tx `txfm_split` where libaom read // an intra `tx_depth` (class `stale-slot-handoff`). hit!(INTRABC_HITS); return Ok((skip, DC_PRED, 0, None, None, Some(dv))); } } 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]); istep!("mode", mode); 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 { // `is_cfl_allowed` (blockd.h): at lossless CfL needs the CHROMA plane // block to be a single TX_4X4 (`cfl_allowed_px`). True for this leaf // at 4:2:0 (the group's plane block is 4x4) and for a 4:4:4 // `BLOCK_4X4` split leaf, but FALSE for a 4:4:4 `BLOCK_8X4`/`BLOCK_4X8` // rect leaf, whose plane block is the rect itself -- that shape reads // the 13-symbol `uv_mode_no_cfl` CDF, and reading the CFL alphabet // there desynced the tile at the rect leaf's own uv_mode symbol (measured: // ours consumed the 14-symbol interval where the oracle read 13, first // divergence at the rect leaf mi (8,16) of `ll444.obu`; class // `wrong-alphabet-same-value`, lane-av1-llsub8). let uv_mode = if cfl_allowed_px(seg_w_mi * MI, seg_h_mi * MI, fctx) { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_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, None)) } /// 4:4:4 sub-8x8 key-frame leaf chroma (lane-av1-444). At subsampling 0/0 /// `is_chroma_reference` (av1_common_int.h:1459) is unconditional, so EVERY /// 4x4 / 4x8 / 8x4 leaf codes its own full-resolution chroma unit right /// after its own luma (`read_intra_mode_sub8` already read this leaf's own /// `uv_mode`), not the one shared 4x4 unit [`decode_leaf_split4`] / /// [`decode_leaf_rect8`]'s group tails decode at 4:2:0. Mirrors those tails /// arm for arm at leaf scale: a skipped leaf keeps its CfL contribution, an /// intrabc leaf predicts a frame copy at its DV with the luma `tx_type` /// inherited through [`INTRABC_CHROMA_TX`] (the caller arms it right after /// the luma read) -- and a SKIPPED intrabc leaf is still the DV copy, never /// an intra prediction (lane-av1-ibcskip2: libaom's /// `av1_build_inter_predictors_sb` runs for an intrabc block regardless of /// `skip`). The chroma position, reach and entropy-context span are /// the leaf's own (ss 0/0); the 4x8/8x4 unit reads the same /// `ChromaRect8x4` tables [`decode_rect_split`] proves for that shape. /// Records the leaf's own `uv_mode` map entry and chroma above/left state, /// and returns the (u, v) grids for the caller's coarse slots. #[allow(clippy::too_many_arguments)] fn sub8_leaf_chroma444( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, lmi: (usize, usize), bw: usize, bh: usize, uv_mode: usize, alpha: Option<(i32, i32)>, skip: bool, intrabc_dv: Option<(i32, i32)>, y: &PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, scan4: &[u16], base_q_idx: u8, smooth_neighbor_uv: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, Grid, usize, usize)> { let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let (w_mi, h_mi) = (bw / MI, bh / MI); neighbours.record_uv_mode_mi(lmi.0, lmi.1, w_mi, h_mi, uv_predict_mode); let (px, py) = (lmi.1 * MI, lmi.0 * MI); let square = (bw, bh) == (4, 4); // `Reach::of_rect` has no 4x4 table (`rect_reach_tables` starts at 4x8); // the square unit takes the leaf's own `Reach::of`, as its luma does. let reach = if square { Reach::of(4, px, py, y.width, y.height, fctx) } else { Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx) }; let grids = if let Some(dv) = intrabc_dv.filter(|_| skip) { // lane-av1-ibcskip2: a SKIPPED intrabc leaf still predicts the frame // copy at its DV -- libaom's `av1_build_inter_predictors_sb` runs for // an intrabc block regardless of `skip` (only the residual read is // dropped), so the reconstruction is the bare DV copy. The intra push // in the next arm is the NON-intrabc route; predicting DC there // decoded flat cells where this fixture's oracle copies frame bytes // (class skipped-intrabc-predicts-intra, // lanes/av1ibcskip2.report.md). Same armed-palette-slot route the // leaf's own luma skip arm uses (`decode_leaf_split4` / // `decode_leaf_rect8`); the caller already flushed the recon queue // before its luma DV copy, so the source samples are current. let mut ub = vec![0u16; bw * bh]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0), bw, bh, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; bw * bh]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0), bw, bh, mc::InterpFilterKind::Bilinear, &mut vb, fctx, ); hit!(SKIPPED_INTRABC_DV_COPY_HITS); let zeros = &ZERO_RESIDUAL[..bw * bh]; if square { set_palette_pred(ub, fctx); push_intra( 1, px, py, 4, DC_PRED, 0, reach, zeros, None, None, smooth_neighbor_uv, fctx, ); set_palette_pred(vb, fctx); push_intra( 2, px, py, 4, DC_PRED, 0, reach, zeros, None, None, smooth_neighbor_uv, fctx, ); } else { set_palette_pred(ub, fctx); push_intra_rect( 1, px, py, bw, bh, DC_PRED, 0, reach, zeros, None, None, smooth_neighbor_uv, fctx, ); set_palette_pred(vb, fctx); push_intra_rect( 2, px, py, bw, bh, DC_PRED, 0, reach, zeros, None, None, smooth_neighbor_uv, fctx, ); } // The same arm-without-clear route the 4:2:0 tails count: a skipped // leaf reads no coefficient, so the inherited chroma `tx_type` is // dropped unconsumed. hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4) } else if skip { let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); if square { push_intra( 1, px, py, 4, uv_predict_mode, 0, reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); push_intra( 2, px, py, 4, uv_predict_mode, 0, reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); } else { push_intra_rect( 1, px, py, bw, bh, uv_predict_mode, 0, reach, &ZERO_RESIDUAL[..bw * bh], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); push_intra_rect( 2, px, py, bw, bh, uv_predict_mode, 0, reach, &ZERO_RESIDUAL[..bw * bh], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); } // The same arm-without-clear route the 4:2:0 tails count: a skipped // leaf reads no coefficient, so an armed intrabc slot is dropped. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4) } else if let Some(dv) = intrabc_dv { // Frame copy at the DV; the residual still reads the ordinary chroma // tables with the inherited luma `tx_type` (see the 4:2:0 tails). let mut ub = vec![0u16; bw * bh]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0), bw, bh, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; bw * bh]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0), bw, bh, mc::InterpFilterKind::Bilinear, &mut vb, fctx, ); let around = neighbours.around_mi_rect(lmi, bw, bh); let pair = if square { set_palette_pred(ub, fctx); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], DC_PRED, DC_PRED, 0, reach, u, px, py, 4, TX4, base_q_idx, None, None, None, smooth_neighbor_uv, fctx, )?; set_palette_pred(vb, fctx); let vg = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], DC_PRED, DC_PRED, 0, reach, v, px, py, 4, TX4, base_q_idx, None, None, None, smooth_neighbor_uv, fctx, )?; (ug, vg, 4, 4) } else { // lane-av1-ibc444rect: the unskipped lossless chroma walk this // lane fixes (one rect unit -> per-4x4 Chroma4 units). if lossless(fctx) { hit!(INTRABC_RECT8_LOSSLESS_CHROMA_HITS); } if lossless(fctx) { // lane-av1-ibc444rect: at lossless `read_tx_size` forces // TX_4X4 on EVERY plane (`av1_get_tx_size`'s lossless // first line), so this rect leaf's chroma is (bw/4)*(bh/4) // TX_4X4 units at their own 4x4 origins -- not the single // `ChromaRect8x4` rect unit the non-lossless arm below reads // (`av1_get_max_uv_txsize(BLOCK_8X4)`'s rect, unreachable at // lossless). Same walk the leaf's own non-intrabc lossless // arm runs (lane-av1-llsub8's fix), plane-major per libaom // `decode_token_recon_block`, with the intra predictor // swapped for the CURRENT frame at the DV; CFL is never // allowed at lossless and no alpha rides an intrabc leaf. let mut out_u = Grid::Own(vec![0i32; bw * bh]); let mut out_v = Grid::Own(vec![0i32; bw * bh]); for (plane_idx, buf) in [(1usize, u), (2usize, v)] { for ur in 0..bh / 4usize { for uc in 0..bw / 4usize { let (umi_r, umi_c) = (lmi.0 + ur, lmi.1 + uc); let (upx, upy) = (px + uc * 4, py + ur * 4); let mut pb = vec![0u16; 16]; mc::predict_with_filter( &buf.data, buf.width, buf.true_width, buf.true_height, mv_to_q4(upx, dv.1, 0), mv_to_q4(upy, dv.0, 0), 4, 4, mc::InterpFilterKind::Bilinear, &mut pb, fctx, ); set_palette_pred(pb, fctx); let unit_around = neighbours.around_mi_rect((umi_r, umi_c), 4, 4); // lane-av1loss444kf: libaom asks // `has_top_right`/`has_bottom_left` with the // LEAF's bsize, this unit's `(col_off, row_off)` // and `tx_size` -- not as a standalone BLOCK_4X4 // at the unit's own position. A 4x8 leaf's FIRST // unit has its bottom-left pixels inside the // block's own second row (already reconstructed), // which `has_bottom_left`'s // `row_off + count < plane_bh_unit` early-out // answers TRUE; the 4x4 table answered false, so // `PlaneBuf::edges` replicated the last left // sample and the unit predicted from a fabricated // edge (the 4:4:4 lossless key frame's 49-sample // chroma damage at (196,200)-(204,200)). The // 4:2:2 twin of this arm was fixed the same way // (lane-av1-422kf2); this is its 4:4:4 twin. let unit_reach = Reach::of_tu(bw, bh, uc * 4, ur * 4, 4, 4, reach); if !square && unit_reach != Reach::of(4, upx, upy, y.width, y.height, fctx) { hit!(SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS); } let grid = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, plane_idx, unit_around[plane_idx], DC_PRED, DC_PRED, 0, unit_reach, buf, upx, upy, 4, TX4, base_q_idx, None, None, Some(3), smooth_neighbor_uv, fctx, )?; let cell = grid_unit_state(&grid, 4, 0, 0, 4, 4); if umi_r < neighbours.mi_rows { neighbours.left[umi_r][plane_idx] = cell; } if umi_c < neighbours.mi_cols { neighbours.above[umi_c][plane_idx] = cell; } let out = if plane_idx == 1 { &mut out_u } else { &mut out_v }; if let Grid::Own(v) = out { for r in 0..4usize { v[(ur * 4 + r) * bw + uc * 4..][..4] .copy_from_slice(&grid[r * 4..][..4]); } } } } } (out_u, out_v, 4, 4) } else { let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 }; let default_tx = fctx .intrabc_chroma_tx .with(std::cell::Cell::get) .unwrap_or(TxType::DctDct); let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh), bw, bh); for (plane_idx, buf) in [(1usize, ub), (2usize, vb)] { let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1); let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, DC_PRED); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, scan, bw, bh, skip_ctx, dc_sign_ctx(around[plane_idx].2), default_tx, plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, block_iqmatrix(fctx, plane_idx, bw, bh, tx_type), ); set_palette_pred(buf, fctx); push_intra_rect( plane_idx, px, py, bw, bh, DC_PRED, 0, reach, &residual, None, None, smooth_neighbor_uv, fctx, ); if plane_idx == 1 { out.0 = levels; } else { out.1 = levels; } } out } }; fctx.intrabc_chroma_tx.with(|c| c.set(None)); pair } else { let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); let around = neighbours.around_mi_rect(lmi, bw, bh); if square { let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], uv_mode, uv_predict_mode, 0, reach, u, px, py, 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, around[2], uv_mode, uv_predict_mode, 0, reach, v, px, py, 4, TX4, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; (ug, vg, 4, 4) } else if lossless(fctx) { // lane-av1-llsub8: `read_tx_size` answers TX_4X4 for EVERY plane of // a lossless block, so this rect leaf's chroma is (bw/4)*(bh/4) // TX_4X4 units at their own 4x4 origins -- not the single // TX_8X4/TX_4X8 rect unit the non-lossless arm below reads (that // one is `av1_get_max_uv_txsize(BLOCK_8X4)`'s rect transform, which // lossless never reaches). Measured on `ll444.obu`'s HORZ leaf at // mi (8,16): the oracle codes U units at bc 0,1 with // `get_txb_ctx`'s +10 rows (`txb_skip_cdf[0][10..12]`, // plane pels 32 > tx pels 16) where the rect-unit read consumed // `txb_skip_cdf[1][0]` -- the tile desynced at that U unit's // all_zero symbol. Walk is plane-major like libaom // `decode_token_recon_block`'s plane/row/col loop; each unit adds // 3 to the chroma context (Chroma4's `big` rows, the same fold // [`read_plane`]'s 128x128 caller uses); CFL is never allowed at // lossless, so no alpha rides along. let mut out_u = Grid::Own(vec![0i32; bw * bh]); let mut out_v = Grid::Own(vec![0i32; bw * bh]); for (plane_idx, buf) in [(1usize, u), (2usize, v)] { for ur in 0..bh / 4usize { for uc in 0..bw / 4usize { let (umi_r, umi_c) = (lmi.0 + ur, lmi.1 + uc); let (upx, upy) = (px + uc * 4, py + ur * 4); let unit_around = neighbours.around_mi_rect((umi_r, umi_c), 4, 4); // lane-av1loss444kf: the block-relative answer, not // a standalone BLOCK_4X4 lookup at the unit's own // position -- see the intrabc twin above for the // libaom citation and the measured damage. let unit_reach = Reach::of_tu(bw, bh, uc * 4, ur * 4, 4, 4, reach); if !square && unit_reach != Reach::of(4, upx, upy, y.width, y.height, fctx) { hit!(SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS); } let grid = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, plane_idx, unit_around[plane_idx], uv_mode, uv_predict_mode, 0, unit_reach, buf, upx, upy, 4, TX4, base_q_idx, None, None, Some(3), smooth_neighbor_uv, fctx, )?; let cell = grid_unit_state(&grid, 4, 0, 0, 4, 4); if umi_r < neighbours.mi_rows { neighbours.left[umi_r][plane_idx] = cell; } if umi_c < neighbours.mi_cols { neighbours.above[umi_c][plane_idx] = cell; } let out = if plane_idx == 1 { &mut out_u } else { &mut out_v }; if let Grid::Own(v) = out { for r in 0..4usize { v[(ur * 4 + r) * bw + uc * 4..][..4] .copy_from_slice(&grid[r * 4..][..4]); } } } } } (out_u, out_v, 4, 4) } else { // `av1_get_max_uv_txsize(BLOCK_4X8/8X4)` at ss 0/0 is the rect // transform itself; its `tx_type` is mode-derived with the // <32 set (`decode_rect_split`'s own rule for this shape). let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 }; let default_tx = default_intra_tx_type(uv_predict_mode as u8); let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh), bw, bh); for plane_idx in 1..=2usize { let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1); let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, scan, bw, bh, skip_ctx, dc_sign_ctx(around[plane_idx].2), default_tx, plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, block_iqmatrix(fctx, plane_idx, bw, bh, tx_type), ); let cfl = alpha .zip(ac) .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)); push_intra_rect( plane_idx, px, py, bw, bh, uv_predict_mode, 0, reach, &residual, cfl, None, smooth_neighbor_uv, fctx, ); if plane_idx == 1 { out.0 = levels; } else { out.1 = levels; } } out } }; // libaom `av1_set_entropy_contexts` stamps above/left PER TRANSFORM UNIT: // the leaf's own chroma span, not the 8x8 group's. A rect leaf's lossless // units (4x4) each carry their own state -- a 4:2:0-style whole-leaf smear // gave one unit's state to its neighbour's cells (lane-av1-llsub8). let (u_grid, v_grid, unit_w, unit_h) = grids; // One unit covers `unit_w/MI` mi columns and `unit_h/MI` mi rows (a 4x4 // unit: one cell each; the non-lossless rect unit: the whole leaf). let (uw_cells, uh_cells) = ((unit_w / MI).max(1), (unit_h / MI).max(1)); for ur in 0..h_mi / uh_cells { for uc in 0..w_mi / uw_cells { let (x0, y0) = (uc * unit_w, ur * unit_h); let us = grid_unit_state(&u_grid, bw, x0, y0, unit_w, unit_h); let vs = grid_unit_state(&v_grid, bw, x0, y0, unit_w, unit_h); for cell in 0..uh_cells { if lmi.0 + ur * uh_cells + cell < neighbours.mi_rows { neighbours.left[lmi.0 + ur * uh_cells + cell][1] = us; neighbours.left[lmi.0 + ur * uh_cells + cell][2] = vs; } } for cell in 0..uw_cells { if lmi.1 + uc * uw_cells + cell < neighbours.mi_cols { neighbours.above[lmi.1 + uc * uw_cells + cell][1] = us; neighbours.above[lmi.1 + uc * uw_cells + cell][2] = vs; } } } } Ok((u_grid, v_grid, unit_w, unit_h)) } /// [`neighbour_state`] over one `(unit_w x unit_h)` transform unit at offset /// `(x0, y0)` inside a `bw`-wide assembled chroma grid -- the per-unit stamp /// the rect arms need when a leaf carries more than one unit. fn grid_unit_state( grid: &Grid, bw: usize, x0: usize, y0: usize, unit_w: usize, unit_h: usize, ) -> Neighbour { let mut cul = 0u32; let mut dc = None; for r in 0..unit_h { for c in 0..unit_w { let v = grid[(y0 + r) * bw + x0 + c]; cul += v.unsigned_abs(); if r == 0 && c == 0 && v != 0 { dc = Some(v < 0); } } } if cul == 0 { return Neighbour::default(); } Neighbour { level: cul.min(7) as u8, dc, } } /// [`sub8_leaf_chroma444`] for 4:2:2 (lane-av1-422g): an even-mi-column 4x4 /// leaf is its plane's own chroma reference (`is_chroma_reference`'s /// `!(mi_col & ss_x)` at ss_x 1 -- every even-column leaf, not 4:2:0's single /// bottom-right one) and codes ONE TX_4X4 chroma unit per plane right after /// its luma: `ss_size_lookup[BLOCK_4X4][1][0]` is BLOCK_4X4, so the (2, 4) /// plane area rounds up to the square 4x4 read. The unit sits at the chroma /// position (`px >> ss_x`), and its 4 chroma-px width spans TWO luma mi /// columns, so the context reads go through /// [`Neighbours::around_mi_422_chroma`] and the entropy stamp covers both /// columns with the unit's whole-unit state. #[allow(clippy::too_many_arguments)] fn sub8_leaf_chroma422( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, lmi: (usize, usize), uv_mode: usize, angle_delta_uv: i32, alpha: Option<(i32, i32)>, skip: bool, intrabc_dv: Option<(i32, i32)>, y: &PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, scan4: &[u16], base_q_idx: u8, smooth_neighbor_uv: bool, // The owning luma leaf's own shape (`(4, 4)` for a split leaf, `(8, 4)` / // `(4, 8)` for a rect pair's strip): libaom's `has_top_right` / // `has_bottom_left` answer for this chroma TX_4X4 unit comes from the // LEAF's own rect table row at the leaf's mi (`bsize` is the leaf, the // unit covers it whole), never the standalone square-4x4 table the old // `Reach::of(4, ..)` lookup used -- that said 1 where `has_tr_8x4` says 0 // at mi(27,44) (the oracle's own EC_PRED prints `n_tr=0` there), so the // D45 unit read undecoded pixels to its upper right. leaf_shape: (usize, usize), fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, Grid)> { let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; // lane-av1-422kf2: libaom writes one MB_MODE_INFO per mi cell the LEAF // covers, and `chroma_left_mbmi`/`chroma_above_mbmi` read whichever of // those cells the next block's snap lands on -- an 8x4 strip's SM_V // uv_mode must therefore be visible at BOTH of its mi columns, or the // block to its right (mi (30,50): left neighbour cell (30,49)) missed the // smooth neighbour and skipped libaom's strength-1 intra edge filter // (class context-read-from-one-cell, the 4:2:2 sub-8 twin of the // lane-kf900 snap fix). neighbours.record_uv_mode_mi( lmi.0, lmi.1, (leaf_shape.0 / MI).max(1), (leaf_shape.1 / MI).max(1), uv_predict_mode, ); let (px, py) = (lmi.1 * MI, lmi.0 * MI); // lane-av1-422kf2: the unit's WRITE/PREDICTION anchor is the same floored // chroma cell as the entropy anchor below -- libaom positions the sub-8 // chroma plane block at `av1_setup_dst_planes`' mi-exact floor // (`(mi_col & !1) * MI >> ss_x`), NOT at the odd leaf's own chroma x: // the oracle's mi(18,55) TX_4X4 unit reconstructed chroma px 108..111 // (a pure V-copy of the row above at 108..111), while the leaf's own // chroma x is 110 -- anchoring there left px 108..109 unwritten (zeros) // and stepped px 112..113 with the unit's right columns. let (cpx, cpy) = (((lmi.1 & !1) * MI) >> ss_x(fctx), py >> ss_y(fctx)); // lane-av1-422h: the entropy-context anchor is the unit's FLOOR chroma // cell (`pd->above_entropy_context + (mi_col >> ss_x)`): an ODD-column // leaf's 4-px unit starts at a chroma px that is NOT cell aligned, and // both its ctx read and its ctx write live in the cell containing that // start -- one luma mi column to the LEFT of the leaf's own. Even-column // (cell-aligned) leaves keep their own column. The state write spans the // anchor's two luma mi columns, so the second (odd) leaf of a split group // overwrites exactly the cell the first one wrote, as libaom's // `av1_set_entropy_contexts` per-TU writes do. let ctx_mi = (lmi.0, lmi.1 & !1); // lane-av1-422kf2: the square unit takes the leaf's OWN reach, but at the // CHROMA plane's granularity, not the luma leaf's. libaom passes the leaf // through `scale_chroma_bsize(bsize, ss_x, ss_y)` first // (`reconintra.c:1823`, definition `:1649`) and only then calls // `has_top_right`/`has_bottom_left` with it, so a rect strip's answer // comes from `has_tr_8x4`/`has_tr_4x8` at the strip's mi, not from a // 4x4-block lookup. At 4:2:2 (`ss (1,0)`) that remap is NOT the identity: // a BLOCK_4X4 luma leaf is answered as BLOCK_8X4, TWO mi wide and one mi // tall. // // MEASURED, `probe/ll422_allintra.obu` (320x240, 4:2:2 lossless // all-intra) against the instrumented `aomdec`: the FIRST wrong chroma // prediction in decode order is unit 2818, plane U, chroma (96,32) -- // the leaf at mi(8,49). The oracle's own `EC_PRED` prints `plane=1 // row_off=0 col_off=0 txw=4 txh=4 mode=7 p_angle=203 have_top=1 // have_left=1 n_top=4 n_left=4 n_tr=-1 n_bl=4 bsize=2`, and `bsize=2` // is BLOCK_8X4 -- the remap, not the BLOCK_4X4 leaf libaom decoded. That // `n_bl=4` is the "leftmost column of superblock" arm: `blk_col_in_sb = // (mi_col & (sb_mi-1)) >> bw_in_mi_log2 = (49 & 15) >> 1 = 0` // (`reconintra.c:421`), where the one-mi-wide luma BLOCK_4X4 reads column // 1, and `blk_start_row_off + row_off + 1 < sb_height_unit` is // `8 + 0 + 1 < 16 >> 0` (`reconintra.c:429-435`). Squared on the luma // leaf, `Reach::of(4, ..)` instead read `has_bl_4x4[byte 32] bit 1` // (`84 = 0b0101_0100`, bit 1 clear) and answered FALSE, so // `PlaneBuf::edges` fed the predictor a 4-sample left column where // libaom fed 8. `build_directional_and_filter_intra_predictors` // (`reconintra.c:1150-1158`) copies `n_left_px` into `left_col[0..3]` and // only `if (n_bottomleft_px > 0)` the next `n_bottomleft_px`, so with the // denial `av1_dr_prediction_z3_c` reads its base term off a replicated // tail -- interior-only, with row0/col0 and the coefficients untouched. // 4:2:0 and 4:4:4 never reach this arm: the reader is 4:2:2-only (its // sibling `sub8_leaf_chroma444` owns those), and the remap is the // identity for a leaf of 8 or more at every subsampling. let (mi_bw, mi_bh) = crate::encode::chroma_mi_shape(leaf_shape.0, leaf_shape.1, ss_x(fctx), ss_y(fctx)); // libaom's two edge tests are TILE bounds over the TRANSFORM's plane // extent and its `have_top`/`have_left` flags are `y0 > 0` / `x0 > 0` // (`reconintra.c:1804-1806`, `:1815-1817`); the tile end is the frame end // for every leaf this reader owns, and the unit is one TX_4X4 chroma // transform wide and tall (`4 << ss` luma px per axis). let tx_w = 4 << ss_x(fctx); let tx_h = 4 << ss_y(fctx); let reach = Reach::of_tu_chroma( mi_bw, mi_bh, lmi.0, lmi.1, crate::encode::reach_sb_mi(fctx), 0, 0, tx_w, tx_h, ss_x(fctx), ss_y(fctx), py > 0 && px + (tx_w << ss_x(fctx)) < y.width, px > 0 && py + (tx_h << ss_y(fctx)) < y.height, ); let chroma_around = neighbours.around_mi_422_chroma(ctx_mi, 8, 4); // lane-av1422sub8pix: the CfL AC signal spans the UNIT's luma footprint, // anchored at the same FLOORED luma x the write/prediction anchor below // uses -- `px` (the odd leaf's own luma x) steps half the span into the // RIGHT neighbour group (t422 frame-1 leaf (1,23): the unit reconstructs // chroma px 44..47 from luma 88..95, while a `px`-anchored source // averaged luma 92..99 and every CFL unit of the group mismatched). let ac = alpha.map(|_| cfl_src_rect((lmi.1 & !1) * MI, py, 8, 4)); let grids: (Grid, Grid) = if let Some(dv) = intrabc_dv.filter(|_| skip) { // lane-av1422ctattr: a SKIPPED intrabc chroma leaf still predicts the // frame copy at its DV. libaom's `decode_token_recon_block` takes the // INTER arm for an intrabc block (`is_inter_block` counts it, // `blockd.h:373`) and `predict_inter_block_visit` runs // `dec_build_inter_predictor` REGARDLESS of `skip_txfm` -- only the // residual read is dropped. Measured on the 4:2:2 seed of // `R422_320x242.obu` / `Q_odd320x242.obu` (chroma U(116,160)): // oracle EC_DP mi_row=40 mi_col=58 bsize=2 inter=1 skip_txfm=1 is_intrabc=1 // EC_ISTEP mi_row=40 mi_col=58 name=intrabc val=1 rng=39264 // EC_DV mi_row=40 mi_col=58 dv_col=0 dv_row=-1024 rng=40116 // ours the SAME symbol and the SAME DV (parse in sync), then // OUR_PRED x=116 y=160 plane=1 mode=0 row0=[182,182,182,182] // i.e. this `if skip` arm was taken and the `else if let Some(dv)` // frame copy below never ran. 202 = (808+2)/4 is not a `dc_top`: there // is NO DC variant at all on the oracle side, because // `av1_predict_intra_block` is never called for an intrabc block. // `sub8_leaf_chroma444` already orders its arms this way // (`intrabc_dv.filter(|_| skip)` first, lane-av1ibcskip2); this arm is // that one, at 4:2:2's square 4x4 chroma unit. let mut ub = vec![0u16; 16]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_y(fctx)), 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); hit!(SKIPPED_INTRABC_DV_COPY_HITS); let zeros = &ZERO_RESIDUAL[..16]; set_palette_pred(ub, fctx); push_intra( 1, cpx, cpy, 4, DC_PRED, 0, reach, zeros, None, None, smooth_neighbor_uv, fctx, ); let mut vb = vec![0u16; 16]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_y(fctx)), 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx, ); set_palette_pred(vb, fctx); push_intra( 2, cpx, cpy, 4, DC_PRED, 0, reach, zeros, None, None, smooth_neighbor_uv, fctx, ); // The same arm-without-clear route the 4:2:0 tails and // [`sub8_leaf_chroma444`] count: a skipped leaf reads no coefficient, // so the inherited chroma `tx_type` is dropped unconsumed. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(16), Grid::Zero(16)) } else if skip { // A skipped chroma-reference leaf still predicts (the CfL contribution // survives a skip); no coefficient symbol exists. 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, 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, reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); // The same arm-without-clear route the 4:2:0 tails count: a skipped // leaf reads no coefficient, so an armed intrabc slot is dropped. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(16), Grid::Zero(16)) } else if let Some(dv) = intrabc_dv { hit!(CHROMA422_SUB8_HITS); // Frame copy at the DV; the residual still reads the ordinary chroma // tables with the inherited luma `tx_type` (see the 4:2:0 tails). let mut ub = vec![0u16; 16]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_y(fctx)), 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; 16]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_y(fctx)), 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx, ); set_palette_pred(ub, fctx); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED, 0, reach, u, cpx, cpy, 4, TX4, base_q_idx, None, None, None, smooth_neighbor_uv, fctx, )?; set_palette_pred(vb, fctx); let vg = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED, 0, reach, v, cpx, cpy, 4, TX4, base_q_idx, None, None, None, smooth_neighbor_uv, fctx, )?; fctx.intrabc_chroma_tx.with(|c| c.set(None)); (ug, vg) } else { hit!(CHROMA422_SUB8_HITS); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_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, )?; let vg = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_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, )?; (ug, vg) }; // libaom `av1_set_entropy_contexts` stamps above/left PER TRANSFORM UNIT: // the unit's own chroma span -- 1 mi row tall, TWO luma mi columns wide // (one chroma column) -- not the 8x8 group's. let (u_grid, v_grid) = grids; let u_state = neighbour_state(&u_grid); let v_state = neighbour_state(&v_grid); if lmi.0 < neighbours.mi_rows { neighbours.left[ctx_mi.0][1] = u_state; neighbours.left[ctx_mi.0][2] = v_state; } for cell in 0..2 { if ctx_mi.1 + cell < neighbours.mi_cols { neighbours.above[ctx_mi.1 + cell][1] = u_state; neighbours.above[ctx_mi.1 + cell][2] = v_state; } } Ok((u_grid, v_grid)) } /// 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, fctx); let mut leaf_modes = [0usize; 4]; let mut leaf_skips = [false; 4]; let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None; // lane-av1txr: the chroma-reference (i==3) leaf's block vector when that // leaf is an intrabc block -- its prediction/reconstruction below is a // frame copy at this DV, not an intra one. let mut last_intrabc: Option<(i32, i32)> = None; // 4:4:4 (lane-av1-444): `is_chroma_reference` (av1_common_int.h:1459) is // unconditional at subsampling 0/0, so EVERY 4x4 leaf reads its own // `uv_mode` and codes its own full-resolution 4x4 chroma unit right // after its luma -- there is no shared group unit at all. let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; // lane-av1-422g: at ss (1,0) every even-mi-column leaf is its plane's own // chroma reference (`is_chroma_reference`'s `!(mi_col & ss_x)`) and codes // one TX_4X4 chroma unit per plane; odd-column leaves read no chroma. let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0; // The last leaf's own `uv_predict_mode`, for the coarse above/left slots // the 4:2:0 tail fills from the group's single unit. let mut last_uv444 = DC_PRED; let mut last_uv422 = DC_PRED; 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 = if chroma_444 { true } else if chroma_422 { // lane-av1-422h: `is_chroma_reference`'s column clause at ss_x 1 is // `(mi_col & 1)` for a BLOCK_4X4 leaf -- the ODD-column leaf is the // chroma reference (oracle, mi(30,42) split group: uv_mode read at // mi(30,43) and mi(31,43) only). The even-column rule this // replaces came from 422f's pre-partition-trace misreading. (lmi.1 & 1) == 1 } else { i == 3 }; let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1); let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = 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, 1, 1, fctx, )?; leaf_modes[i] = mode; leaf_skips[i] = skip; neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode); // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this // `BLOCK_4X4` leaf -- EVERY block publishes its transform size into // the TXFM context bands, and an intrabc block's later `txfm_split` // context is read off them (`txfm_partition_context`). A 4x4 never // signals a tx size, so it is always TX_4X4 (`set_txfm_ctxs`'s // `skip && is_inter` branch writes the block's own 4 pixels -- the // same value). set_txfm_ctxs(neighbours, lmi, 4, 1, 1, false); 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 let Some(dv) = intrabc { // lane-av1txr: an intrabc `BLOCK_4X4` leaf -- prediction is the // CURRENT frame at the block vector (`predict_inter_block`'s // intrabc arm, spec 7.11.3.4), residual the INTER coefficient set // (libaom reads `tx_type` off `inter_ext_tx_cdf` for // `is_inter_block`, which counts intrabc). Published into // `intrabc_dv` so the group's chroma arm (below, when the // chroma-reference leaf is the intrabc one) and // [`record_intrabc_mi`] see it. flush_recon(fctx, y, u, v); let mut yb = vec![0u16; 16]; mc::predict_with_filter( &y.data, y.width, y.true_width, y.true_height, mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0), 4, 4, mc::InterpFilterKind::Bilinear, &mut yb, fctx, ); set_palette_pred(yb.clone(), fctx); if skip { push_intra( 0, px, py, 4, DC_PRED, 0, reach, &ZERO_RESIDUAL[..16], None, None, 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::Luma4Inter } else { TxbSet::Luma4InterSet1 }, scan4, 0, tu_around, DC_PRED, DC_PRED, 0, reach, y, px, py, 4, 4, base_q_idx, None, None, 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); record_intrabc_mi(lmi.0, lmi.1, 1, Some(dv), neighbours, fctx); if has_chroma { // An intrabc block is an INTER block for `av1_get_tx_type`, so // the chroma inherits the LUMA's coded transform type // (`xd->tx_type_map` at the co-located luma position) -- the // luma `read_plane` above just set [`LUMA_TX_TYPE`]. Armed for // exactly this leaf's two chroma reads. fctx.intrabc_chroma_tx .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get)))); if chroma_444 { // lane-av1-444: this leaf codes its OWN 4x4 chroma unit // right here (frame copy at the DV); no group tail. sub8_leaf_chroma444( dec, cdfs, neighbours, lmi, 4, 4, DC_PRED, None, skip, Some(dv), y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; last_uv444 = DC_PRED; } else if chroma_422 { sub8_leaf_chroma422( dec, cdfs, neighbours, lmi, DC_PRED, 0, None, skip, Some(dv), y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (4, 4), fctx, )?; last_uv422 = DC_PRED; } else { last_uv = Some((DC_PRED, 0, None)); // lane-av1txbands: the group's chroma is the CHROMA-REFERENCE // leaf's own block -- libaom codes one chroma unit under the // last sub-block only (`is_chroma_reference`), so its prediction // is that leaf's `uv_mode` (CfL alpha and all) unless THAT leaf // is the intrabc one. Arming this from a non-chroma-reference // leaf's DV made `warped.obu`'s 8x8 group at mi(40,62) copy // frame bytes at mi(41,62)'s vector where aomdec predicts // `uv_mode=UV_CFL_PRED`: luma stayed byte-exact and only chroma // moved (class chroma-keyed-at-a-non-chroma-leaf). Mirrors // [`decode_leaf_rect8`]'s own placement. last_intrabc = Some(dv); } } continue; } 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 { if chroma_444 { // lane-av1-444: the leaf's own 4x4 chroma unit, coded right // after its luma (no shared group unit at ss 0/0). let (uv_mode, _, alpha) = chroma.expect("4:4:4 reads uv_mode on every leaf"); sub8_leaf_chroma444( dec, cdfs, neighbours, lmi, 4, 4, uv_mode, alpha, skip, None, y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; } else if chroma_422 { let (uv_mode, angle_delta_uv, alpha) = chroma.expect("4:2:2 reads uv_mode on even-column leaves"); sub8_leaf_chroma422( dec, cdfs, neighbours, lmi, uv_mode, angle_delta_uv, alpha, skip, None, y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (4, 4), fctx, )?; last_uv422 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; } else { last_uv = chroma; } } } // lane-av1mono: as [`decode_leaf_rect8`] -- a monochrome frame has no // chroma to reconstruct and no uv_mode was read. let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) { (Grid::Zero(16), Grid::Zero(16)) } else if chroma_444 { // lane-av1-444: every leaf coded and reconstructed its own chroma in // the loop above ([`sub8_leaf_chroma444`] stamped the mi-exact maps // and per-leaf entropy state); only the coarse slots remain, filled // from the bottom-right leaf like the 4:2:0 tail's single unit. neighbours.above_uv_mode[c] = last_uv444; neighbours.left_uv_mode[r] = last_uv444; (Grid::Zero(16), Grid::Zero(16)) } else if chroma_422 { // lane-av1-422g: each even-column leaf coded and reconstructed its // own TX_4X4 chroma unit in the loop above (sub8_leaf_chroma422 // stamped the per-leaf entropy state); only the coarse slots remain, // filled from the group's last chroma-reference leaf (bottom-left). neighbours.above_uv_mode[c] = last_uv422; neighbours.left_uv_mode[r] = last_uv422; (Grid::Zero(16), Grid::Zero(16)) } else { let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx)); 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, ); // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma // coefficient, so it never consults the inherited luma transform type // -- but an intrabc chroma-reference leaf did arm // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient // branches below are the only ones that disarm it. Left armed, the slot // picks the NEXT block's chroma scan and inverse transform (class // arm-without-clear-on-a-skip-route). Counted so a gate can tell a // stream that reaches this route from one that never does. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(16), Grid::Zero(16)) } else if let Some(dv) = last_intrabc { // lane-av1txr: the chroma-reference leaf was an intrabc block, so the // group's one chroma unit is a frame copy at that DV too (its residual // still reads the ordinary `Chroma4` coefficient tables -- libaom // codes a chroma `tx_type` nowhere). let mut ub = vec![0u16; 16]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_y(fctx)), 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; 16]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_y(fctx)), 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx, ); let chroma_around = neighbours.around_mi(leaf_mi, 8); set_palette_pred(ub, fctx); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED, 0, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, None, None, None, smooth_neighbor_uv, fctx, )?; set_palette_pred(vb, fctx); let vg = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED, 0, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, None, None, None, smooth_neighbor_uv, fctx, )?; fctx.intrabc_chroma_tx.with(|c| c.set(None)); (ug, vg) } 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) }; (u_grid, v_grid) }; // 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; } // lane-av1-444: at 4:4:4 [`sub8_leaf_chroma444`] already stamped each // leaf's own span as it decoded; these placeholder grids carry no state. // lane-av1-422g: the 4:2:2 per-leaf units stamp the same way. if !chroma_444 && !chroma_422 { 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; } } } // lane-dkey: a sub-8x8 leaf can never use palette (`av1_allow_palette` // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its // `palette_size` is 0 in every one of these mi cells, so the NEXT block's // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette // block above a 4x4 group left its size/colours standing in the mi-granular // bands: the block below the group read `palette_y_mode` off CDF row 1 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a // palette libaom never coded, and then skipped the `use_filter_intra` // symbol that a palette block has none of -- one symbol short, tile // desynced. Publishing the group's own zeros is the clear. neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]); neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]); 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, fctx); 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; // lane-av1txr: as [`decode_leaf_split4`]'s own `last_intrabc`. let mut last_intrabc: Option<(i32, i32)> = None; // 4:4:4 (lane-av1-444): as [`decode_leaf_split4`] -- at subsampling 0/0 // EVERY 4x8/8x4 leaf reads its own `uv_mode` and codes its own // full-resolution rect chroma unit right after its luma. let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; let mut last_uv444 = DC_PRED; // lane-av1-422h: at ss (1,0) `is_chroma_reference` // (av1_common_int.h:1459) resolves per strip shape -- // `((mi_row & 1) || !(bh_mi & 1) || !ss_y) && ((mi_col & 1) || !(bw_mi & 1) || !ss_x)`: // a HORZ pair is two BLOCK_8X4 strips at the group's even column, so // BOTH strips are chroma references (`!(bw & 1)`); a VERT pair is two // BLOCK_4X8 strips, and the column clause keeps only the ODD-column // strip (i == 1, the same leaf the 4:2:0 rule reads chroma on). let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0; let mut last_uv422 = DC_PRED; 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 = if chroma_444 { true } else if chroma_422 { !vert || i == 1 } else { i == 1 }; let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1); let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = 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, bw / 4, bh / 4, fctx, )?; 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 let Some(dv) = intrabc { // lane-av1-ibc444rect: the unskipped lossless luma walk this lane // fixes (one rect unit -> per-4x4 inter units). if !skip && lossless(fctx) { hit!(INTRABC_RECT8_LOSSLESS_LUMA_HITS); } // lane-av1txr: an intrabc `BLOCK_4X8`/`BLOCK_8X4` leaf. The // prediction is a frame copy at the DV and the residual reads the // INTER `LumaRect8x4` set -- but with `TxMode::Select` the leaf // reads the INTER var-tx tree, exactly like every other intrabc // block: libaom's `block_signals_txsize` is `bsize > BLOCK_4X4` // (`blockd.h:1027`), TRUE at `BLOCK_4X8`/`BLOCK_8X4`, so // `parse_decode_block` sends an unskipped `inter_block_tx` block // (intrabc counts, `is_inter_block`) of a signalling bsize into // `read_tx_size_vartx` over `max_txsize_rect_lookup[BLOCK_4X8] == // TX_4X8`; only `BLOCK_4X4` reads no tx symbol at all. Measured on // `warped.obu` mi (37,62): reading NO symbol here left the // arithmetic decoder one symbol short and desynced the very next // block's `skip` (ours 60320 vs aomdec 48630, class // `symbol-consumption-gap`). let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); flush_recon(fctx, y, u, v); let mut luma_leaves: Vec<(usize, usize, usize, usize)> = Vec::new(); // The non-var-tx band publish, deferred to AFTER the unit loop: // libaom's `set_txfm_ctxs` runs at `parse_decode_block`'s tail, so // a unit's own `txb_skip_ctx` read must see the PRE-block bands. let mut publish = Some((bw, bh)); // lane-av1mixllfork: libaom `parse_decode_block` (decodeframe.c:1237) // gates the var-tx tree on `!xd->lossless[mbmi->segment_id]` as a // CONJUNCT of the tx_mode-select condition, not as the `else` arm -- // `read_tx_size` (`decodeframe.c:1208`) answers TX_4X4 on the same // flag. A frame whose segments disagree (per-segment mixed // lossless: `--cq-level=0` with AQ) therefore reads NO tree symbol // on its lossless blocks. Ordering the test the other way round // reads a `tx_size_cat1` symbol the oracle never reads and forks // the very next block's `txb_skip`. if tx_select && !skip && !lossless(fctx) { // `max_block_wide`/`max_block_high`: the frame's own mi grid, // so a leaf hanging over the right/bottom edge reads no split // symbol for the units outside it (as in `decode_block`). let mi_cols = 2 * y.true_width.div_ceil(8); let mi_rows = 2 * y.true_height.div_ceil(8); let max_w_mi = w_mi.min(mi_cols.saturating_sub(lmi.1)); let max_h_mi = h_mi.min(mi_rows.saturating_sub(lmi.0)); read_var_tx_size( dec, cdfs, neighbours, lmi, bw.max(bh), (max_w_mi, max_h_mi), (bw, bh), 0, 0, 0, &mut luma_leaves, ); hit!(RECT_INTRABC_VARTX_HITS); publish = None; } else if lossless(fctx) && !skip { // lane-av1-ibc444rect: `read_tx_size`'s lossless first line // (`decodeframe.c:1203`) answers TX_4X4 for EVERY plane before // any tree, and a lossless frame's `TxMode` is `ONLY_4X4` // (spec 6.8.20) so no var-tx tree is read either -- the leaf's // coefficients are (bw/4)*(bh/4) inter TX_4X4 units at their // own origins, plane-major, NOT the single rect transform the // non-lossless arm reads (that one is // `av1_get_max_uv_txsize(BLOCK_8X4)`'s rect, unreachable at // lossless). Same unit structure the non-intrabc lossless // split below walks; each unit predicts from the CURRENT // frame at the DV. Measured on the lane's `e4` fixture // (`ll444_ibc_rect.obu`): the single-rect read desynced the // tile and tripped the lossless WHT assert `(4, 8) != (4, 4)` // at `TxParams::run`. for ur in 0..bh / 4usize { for uc in 0..bw / 4usize { luma_leaves.push((ur, uc, 4, 4)); } } publish = Some((4, 4)); } else { luma_leaves.push((0, 0, bw, bh)); // The non-var-tx arm: a SKIPPED intrabc leaf (or a frame // outside `TxMode::Select`) publishes its own rect transform // (`set_txfm_ctxs`'s `skip && is_inter` branch writes the // block's own pixels -- the same size here). } // The transform type an intrabc block's CHROMA inherits is the // `tx_type_map` entry at the chroma unit's co-located luma // position (`av1_get_tx_type`, `blockd.h:1278`), i.e. the FIRST // luma unit the tree resolved. let single = luma_leaves.len() == 1; let mut chroma_tx = TxType::DctDct; let mut grid = Grid::Zero(bw * bh); for (li, &(tu_row, tu_col, tw, th)) in luma_leaves.iter().enumerate() { let tu_mi = (lmi.0 + tu_row, lmi.1 + tu_col); let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI); let tu_reach = if single { reach } else { tu_reach( bw, bh, tu_px - px, tu_py - py, tw, reach, px, py, y.width, y.height, fctx, ) }; let mut yb = vec![0u16; tw * th]; mc::predict_with_filter( &y.data, y.width, y.true_width, y.true_height, mv_to_q4(tu_px, dv.1, 0), mv_to_q4(tu_py, dv.0, 0), tw, th, mc::InterpFilterKind::Bilinear, &mut yb, fctx, ); set_palette_pred(yb, fctx); let tu_grid = if skip { let zeros = Grid::Zero(tw * th); if (tw, th) == (4, 4) { push_intra( 0, tu_px, tu_py, 4, DC_PRED, 0, tu_reach, &zeros, None, None, smooth_neighbor, fctx, ); } else { push_intra_rect( 0, tu_px, tu_py, tw, th, DC_PRED, 0, tu_reach, &zeros, None, None, smooth_neighbor, fctx, ); } zeros } else { // A unit smaller than its own block (the var-tx split) // reads its `txb_skip_ctx` off the neighbours; the // whole-leaf unit's `plane_bsize == txsize_to_bsize` fixes // it at 0. let (set, tu_scan, around, skip_ctx) = if (tw, th) == (4, 4) { ( inter_txbset_for(4, reduced_tx_set), scan4, neighbours.around_mi(tu_mi, 4)[0], neighbours.luma_skip_ctx(tu_mi, 1), ) } else { ( if reduced_tx_set { TxbSet::LumaRect8x4Inter } else { TxbSet::LumaRect8x4InterSet1 }, scan, neighbours.around_mi_rect(tu_mi, tw, th)[0], 0, ) }; let mut coding = cdfs.txb(set, DC_PRED); // lane-av1-ibc444rect: `av1_read_tx_type` returns before any // symbol for a lossless block (qindex == 0, decodemv.c:681) // on EVERY plane and size -- the lossless units this arm now // walks must not read the set's tx_type either (`read_plane` // does the same for its own call sites). Measured on the // lane's `ll444_ibc_rect.obu`: with the symbol read, the // first unit's ladder diverged right after a matched // `all_zero` (ours +4096 rng on the unused tx_type). if lossless(fctx) { coding.tx_type = None; } let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, tu_scan, tw, th, skip_ctx, dc_sign_ctx(around.2), TxType::DctDct, 0, )?; if li == 0 { chroma_tx = tx_type; fctx.luma_tx_type.with(|c| c.set(tx_type)); } // lane-av1-ibc444rect: the residual goes through [`TxParams`] // with the frame's lossless flag, exactly like // [`read_plane`]'s own dequant -- at lossless `TxParams::run` // is the Walsh-Hadamard inverse on every plane, and the // `dequant_and_inverse_typed_wh` shortcut the lossy var-tx // callers use has no lossless flag (it would run the DCT // inverse over the WHT-ordered levels). Measured on the lane // fixture: the DCT route left ±1..30 sample errors on every // walked leaf's luma. let tx = TxParams { plane: 0, w: tw, h: th, bit_depth: crate::decode::bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta: plane_q_delta(0, fctx).0, ac_delta: plane_q_delta(0, fctx).1, tx_type, qm: block_iqmatrix(fctx, 0, tw, th, tx_type), stride: 0, lossless: lossless(fctx), }; let residual = tx.run(&levels); if (tw, th) == (4, 4) { push_intra( 0, tu_px, tu_py, 4, DC_PRED, 0, tu_reach, &residual, None, None, smooth_neighbor, fctx, ); } else { push_intra_rect( 0, tu_px, tu_py, tw, th, DC_PRED, 0, tu_reach, &residual, None, None, smooth_neighbor, fctx, ); } levels }; if single { grid = tu_grid; } else { // Per-unit neighbour state, the same shape the intra rect // leaf's own split path runs (`decode_leaf8`'s depth-1 // loop): a transform unit inside a block is not a block at // that position. neighbours.record_mi_luma(tu_mi, 4, &tu_grid); } } // The deferred non-var-tx band publish (see `publish` above): the // units' `txb_skip_ctx` reads ran against the pre-block bands. if let Some((pub_w, pub_h)) = publish { txfm_partition_update_rect(neighbours, lmi, (pub_w, pub_h), (bw, bh)); } if single { 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); neighbours.fill_lf_grid_rect( lmi, w_mi, h_mi, if single { bw as u8 } else { 4 }, if single { bh as u8 } else { 4 }, 0, fctx, ); // `record_intrabc_mi` publishes a square `n4`x`n4` footprint; a // 4x8/8x4 leaf needs its true `w_mi`x`h_mi` (lane-av1txr). record_intrabc_mi_rect(lmi.0, lmi.1, w_mi, h_mi, Some(dv), neighbours, fctx); if has_chroma { // See [`decode_leaf_split4`]: an intrabc block's chroma // inherits the luma transform type. fctx.intrabc_chroma_tx.with(|c| c.set(Some(chroma_tx))); if chroma_444 { // lane-av1-444: this leaf codes its OWN rect chroma unit // right here (frame copy at the DV); no group tail. sub8_leaf_chroma444( dec, cdfs, neighbours, lmi, bw, bh, DC_PRED, None, skip, Some(dv), y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; last_uv444 = DC_PRED; } else if chroma_422 { // lane-av1-422h: same at ss (1,0) -- the strip's own square // TX_4X4 chroma unit at its halved position. sub8_leaf_chroma422( dec, cdfs, neighbours, lmi, DC_PRED, 0, None, skip, Some(dv), y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (bw, bh), fctx, )?; last_uv422 = DC_PRED; } else { last_uv = Some((DC_PRED, 0, None)); last_intrabc = Some(dv); } } continue; } 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`). // lane-av1mix: libaom `read_tx_size`'s FIRST line // (`decodeframe.c:1203`, `if (xd->lossless[...]) return TX_4X4`) // fires before the `TX_MODE_SELECT` test, so a lossless-segment leaf // codes NO depth symbol even in `TxMode::Select` -- the mixed-lossless // frame's sub8 leaves forked exactly here (ours read the symbol at // (12477,50864) bit 3011, the oracle's all_zero used it). let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect // reader already does. let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); dec.symbol(&mut cdfs.tx_size_cat0[ctx]) } else { 0 }; if depth != 0 { hit!(TX_DEPTH_HITS); hit!(RECT8_SPLIT_TX_HITS); } 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 || lossless(fctx); // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this // leaf -- the size the `tx_depth` symbol resolved (depth 1 -> TX_4X4, // else the leaf's own rect transform), published over the leaf's own // mi span. An intrabc block's `txfm_partition_context` reads these // bands, and the key-frame sub-8x8 leaves had no write at all: // `warped.obu` mi (37,62) read a stale 8 where aomdec read 4 (ctx 18 // vs 19) and the tile desynced (class `context-band-not-published`). let (ctx_tx_w, ctx_tx_h) = if split { (4, 4) } else { (bw, bh) }; txfm_partition_update_rect(neighbours, lmi, (ctx_tx_w, ctx_tx_h), (bw, bh)); 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 { if chroma_444 { // lane-av1-444: the leaf's own rect chroma unit after its // split luma (no shared group unit at ss 0/0). let (uv_mode, _, alpha) = chroma.expect("4:4:4 reads uv_mode on every leaf"); sub8_leaf_chroma444( dec, cdfs, neighbours, lmi, bw, bh, uv_mode, alpha, skip, None, y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; } else if chroma_422 { // lane-av1-422h: the strip's own square TX_4X4 chroma unit // per plane right after its split luma (one per ref strip). let (uv_mode, angle_delta_uv, alpha) = chroma.expect("4:2:2 chroma references read uv_mode"); sub8_leaf_chroma422( dec, cdfs, neighbours, lmi, uv_mode, angle_delta_uv, alpha, skip, None, y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (bw, bh), fctx, )?; last_uv422 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; } else { 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, 0, )?; 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), // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at // every other dequant site (class `parsed-then-discarded`). block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type, block_iqmatrix(fctx, 0, bw, bh, 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 { if chroma_444 { // lane-av1-444: the leaf's own rect chroma unit after its // luma (no shared group unit at ss 0/0). let (uv_mode, _, alpha) = chroma.expect("4:4:4 reads uv_mode on every leaf"); sub8_leaf_chroma444( dec, cdfs, neighbours, lmi, bw, bh, uv_mode, alpha, skip, None, y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; } else if chroma_422 { // lane-av1-422h: the strip's own square TX_4X4 chroma unit // per plane right after its luma -- libaom codes each // BLOCK_8X4 strip's chroma under the strip itself (both // strips of a HORZ pair are chroma references), not one // shared group unit. let (uv_mode, angle_delta_uv, alpha) = chroma.expect("4:2:2 chroma references read uv_mode"); sub8_leaf_chroma422( dec, cdfs, neighbours, lmi, uv_mode, angle_delta_uv, alpha, skip, None, y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (bw, bh), fctx, )?; last_uv422 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; } else { last_uv = chroma; } } } // lane-av1mono: a monochrome frame codes no chroma at all -- no // `uv_mode` was read ([`read_intra_mode_sub8`] folds the plane count in), // so there is no chroma to reconstruct and no chroma coefficient to read. let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) { (Grid::Zero(16), Grid::Zero(16)) } else if chroma_444 { // lane-av1-444: every leaf coded and reconstructed its own chroma in // the loop above; only the coarse slots remain (last leaf's mode). neighbours.above_uv_mode[c] = last_uv444; neighbours.left_uv_mode[r] = last_uv444; (Grid::Zero(16), Grid::Zero(16)) } else if chroma_422 { // lane-av1-422h: every chroma-reference strip coded and reconstructed // its own chroma unit in the loop above (and stamped its own entropy // span), so the 4:2:0 shared group unit below must not run. Only the // coarse 16x16 slots remain: libaom's `above_uv_mode`/`left_uv_mode` // end up holding the LAST chroma reference's mode (decode order). neighbours.above_uv_mode[c] = last_uv422; neighbours.left_uv_mode[r] = last_uv422; (Grid::Zero(16), Grid::Zero(16)) } else { let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx)); 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] && last_intrabc.is_none() { // 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, ); // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma // coefficient, so it never consults the inherited luma transform type // -- but an intrabc chroma-reference leaf did arm // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient // branches below are the only ones that disarm it. Left armed, the slot // picks the NEXT block's chroma scan and inverse transform (class // arm-without-clear-on-a-skip-route). Counted so a gate can tell a // stream that reaches this route from one that never does. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(16), Grid::Zero(16)) } else if let Some(dv) = last_intrabc { // A 4:2:0 `BLOCK_4X8`/`BLOCK_8X4` leaf maps to a clamped chroma // `BLOCK_4X4` (`get_plane_block_size`, blockd.h:1184; `set_plane_n4`, // av1_common_int.h:1344). The chroma reference is still the whole // 8x8 group's 4x4 plane block at `(cpx, cpy)`, so prediction uses the // group's destination origin, not the odd-mi leaf's nominal 2x4/4x2 // extent. The old route treated a skipped intrabc leaf as skipped // intra and predicted this block with DC, first differing at // mi(46,52), U(104,92), while consuming identical symbols. // `decode_reconstruct_tx` reads no chroma coefficients for a skipped // intrabc block, but an unskipped one reads the ordinary Chroma4 // tables; chroma inherits no coded tx_type of its own. let mut ub = vec![0u16; 16]; mc::predict_with_filter( &u.data, u.width, u.true_width, u.true_height, mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_y(fctx)), 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx, ); let mut vb = vec![0u16; 16]; mc::predict_with_filter( &v.data, v.width, v.true_width, v.true_height, mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_y(fctx)), 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx, ); if leaf_skips[1] { // `skip_txfm` still reconstructs an intrabc prediction, but // libaom's `decode_reconstruct_tx` reads NO chroma coefficients. // The ordinary skipped-intra arm above is therefore not valid for // an intrabc leaf: use the copied, clamped 4x4 prediction directly. push_mc_rect( 1, cpx, cpy, 4, 4, 4, Pred::Inline(&ub, 4), &ZERO_RESIDUAL[..16], fctx, ); push_mc_rect( 2, cpx, cpy, 4, 4, 4, Pred::Inline(&vb, 4), &ZERO_RESIDUAL[..16], fctx, ); hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); (Grid::Zero(16), Grid::Zero(16)) } else { let chroma_around = neighbours.around_mi(leaf_mi, 8); set_palette_pred(ub, fctx); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED, 0, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, None, None, None, smooth_neighbor_uv, fctx, )?; set_palette_pred(vb, fctx); let vg = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED, 0, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, None, None, None, smooth_neighbor_uv, fctx, )?; fctx.intrabc_chroma_tx.with(|c| c.set(None)); (ug, vg) } } 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) }; (u_grid, v_grid) }; // `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; } // lane-av1-444: at 4:4:4 [`sub8_leaf_chroma444`] already stamped each // leaf's own span as it decoded; these placeholder grids carry no state. // lane-av1-422h: same at ss (1,0) -- [`sub8_leaf_chroma422`] stamped each // chroma-reference strip's own span in decode order. if !(chroma_444 || chroma_422) { 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; } } } // lane-dkey (same clear as `decode_leaf_split4`): a sub-8x8 leaf can never use palette (`av1_allow_palette` // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its // `palette_size` is 0 in every one of these mi cells, so the NEXT block's // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette // block above a 4x4 group left its size/colours standing in the mi-granular // bands: the block below the group read `palette_y_mode` off CDF row 1 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a // palette libaom never coded, and then skipped the `use_filter_intra` // symbol that a palette block has none of -- one symbol short, tile // desynced. Publishing the group's own zeros is the clear. neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]); neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]); // `(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]; /// lane-av1422filter: libaom `av1_cdef_filter_fb` (cdef_block.c) remaps the /// luma direction before filtering CHROMA whenever `xdec != ydec` — the /// direction grid lives on the subsampled chroma grid, so a direction found /// on the 8x8 luma block means a different line there. `conv422` applies /// under 4:2:2 (`xdec` set), `conv440` under its mirror (not expressible in /// the profiles this decoder accepts, kept for fidelity). 4:2:0 and 4:4:4 /// (`xdec == ydec`) take no remap, exactly as before this lane. const CDEF_DIR_CONV422: [usize; 8] = [7, 0, 2, 4, 5, 6, 6, 6]; const CDEF_DIR_CONV440: [usize; 8] = [1, 2, 2, 2, 3, 4, 6, 0]; 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_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS, CDEF_VERY_LARGE, cdef_constrain_shift, }; 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 >> ss_y(fctx), y_hi >> ss_y(fctx), horz, fctx, ); } if lf.level[3] != 0 { deblock_plane_span( v, 2, lf, n, frame_width, frame_height, y_lo >> ss_y(fctx), y_hi >> ss_y(fctx), 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, ss: usize) -> usize { // scale | ((coord << scale) >> 2). ss=1 is (coord/2)|1; ss=0 is coord/4. if chroma { ss | ((coord << ss) >> 2) } 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 /// (tall) as this block's own `max_txsize_rect_lookup[bsize]`. /// /// lane-av1txbands: this reads the real `TXFM_CONTEXT` bands /// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`]) for EVERY frame /// now -- libaom maintains them on intra-only frames too (`parse_decode_block` /// runs `set_txfm_ctxs` for every block, and /// [`Neighbours::fill_lf_grid_rect`] publishes them there), except that an /// *inter* neighbour contributes its own BLOCK size rather than its transform /// size -- and libaom's `is_inter_block` counts an INTRABC block /// (`blockd.h:373`), which is what the `above_inter`/`left_inter` bands carry. /// The previous deblock-grid approximation coincided with this only while /// every neighbour coded one whole-block transform, which is exactly what /// `TxMode::Select` ends. /// /// The rect form (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. 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); // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is // wider or taller than 64, so a block with a 128 side resolves against 64 // (lane-sb128b r1). let (own_w, own_h) = (own_w.min(64), own_h.min(64)); 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; // lane-av1txctxband: the override's gate and its size term are read at // the ABUTTING CELL -- libaom's `xd->above_mbmi` is `xd->mi[-mi_stride]` // and `xd->left_mbmi` is `xd->mi[-1]` (`set_mi_offsets`, // av1_common_int.h:1381-1389), which `setup_mbs` fills with the pointer // of the block COVERING that cell (decodeframe.c:355-361). The old code // read the per-COLUMN `above_inter`/`left_inter` bands and the matching // `above_side_mi`/`left_side_mi` bands, i.e. the LAST block written in // that column, which names the abutting block only for the block directly // below it. Measured: on the 4:4:4 lossy `--sb-size=128` cq-62 stream the // 8x4 intra leaf at mi(57,52) saw a stale `above_inter=true` (from an // intrabc block earlier in column 52) with `above_side=4`, took the // override, and read `tx_size_cat0[1]` where libaom reads row 2. if has_above && n.inter_at(mi_r - 1, mi_c) { above = usize::from(n.blk_side_at(mi_r - 1, mi_c).0) >= own_w; } if has_left && n.inter_at(mi_r, mi_c - 1) { left = usize::from(n.blk_side_at(mi_r, mi_c - 1).1) >= own_h; } // lane-av1txctxband: the non-vacuity arm. It counts the reads whose // RESOLVED context term differs from what the old per-column bands would // have produced -- not merely reads where the two `is_inter` booleans // disagree, because on the measured witness they AGREE (`above_inter` and // the per-cell cover are both true at mi(57,52)) and it is the SIZE term // that is stale (band 4 vs the covering block's own 8), which is what put // the read on `tx_size_cat0[1]` instead of row 2. { let band_above = has_above && if n.above_inter[mi_c] { usize::from(n.above_side_mi[mi_c]) >= own_w } else { usize::from(n.above_txfm[mi_c]) >= own_w }; let band_left = has_left && if n.left_inter[mi_r] { usize::from(n.left_side_mi[mi_r]) >= own_h } else { usize::from(n.left_txfm[mi_r]) >= own_h }; if band_above != (has_above && usize::from(above) != 0) || band_left != (has_left && usize::from(left) != 0) { hit!(TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS); } } 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} \ intra_only={} above_txfm={} left_txfm={} above_inter={} left_inter={} \ above_side={} left_side={} above={above} left={left} \ | cell_inter ab={} lb={} ab_side={} lb_side={}", fctx.intra_only.with(std::cell::Cell::get), 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], // lane-av1txctxband: the per-CELL terms this read now uses, next to // the per-column bands it used to use, so a divergence names which // of the two disagreed. has_above .then(|| n.inter_at(mi_r - 1, mi_c)) .unwrap_or(false), has_left .then(|| n.inter_at(mi_r, mi_c - 1)) .unwrap_or(false), has_above .then(|| n.blk_side_at(mi_r - 1, mi_c).0) .unwrap_or(0), has_left .then(|| n.blk_side_at(mi_r, mi_c - 1).1) .unwrap_or(0), ); } 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, }; { let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w) + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h); if ctx != stale { hit!(TXCTX_DEBLOCK_DIVERGENCE_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. // lane-angledelta r1 (class [[context-read-from-one-cell]]) fixed the // `/ (SUB / MI)` on this pair; lane-av1txctxband fixes what it could not: // the bands are per COLUMN, so they name the last block written in the // column, not the block covering the abutting cell. libaom's // `xd->above_mbmi` is `xd->mi[-xd->mi_stride]` and `xd->left_mbmi` is // `xd->mi[-1]` (`set_mi_offsets`, av1_common_int.h:1381-1389), and // `setup_mbs` (decodeframe.c:355-361) writes the covering block's own // pointer into every mi cell the block covers. if has_above && n.inter_at(mi_r - 1, mi_c) { above = usize::from(n.blk_side_at(mi_r - 1, mi_c).0) >= side; } if has_left && n.inter_at(mi_r, mi_c - 1) { left = usize::from(n.blk_side_at(mi_r, mi_c - 1).1) >= side; } // lane-av1txctxband: the non-vacuity arm (see the rect form above). { let band_above = has_above && if n.above_inter[mi_c] { usize::from(n.above_side_mi[mi_c]) >= side } else { usize::from(n.above_txfm[mi_c]) >= side }; let band_left = has_left && if n.left_inter[mi_r] { usize::from(n.left_side_mi[mi_r]) >= side } else { usize::from(n.left_txfm[mi_r]) >= side }; if band_above != (has_above && usize::from(above) != 0) || band_left != (has_left && usize::from(left) != 0) { hit!(TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS); } } 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} | cell_inter ab={} lb={} ab_side={} lb_side={}", 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], has_above .then(|| n.inter_at(mi_r - 1, mi_c)) .unwrap_or(false), has_left .then(|| n.inter_at(mi_r, mi_c - 1)) .unwrap_or(false), has_above .then(|| n.blk_side_at(mi_r - 1, mi_c).0) .unwrap_or(0), has_left .then(|| n.blk_side_at(mi_r, mi_c - 1).1) .unwrap_or(0), ); } 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, fctx: &crate::decode::FrameCtx, ) -> usize { // libaom `read_tx_size`'s FIRST line (decodeframe.c:1203): // `if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;` -- before the // `tx_mode == TX_MODE_SELECT` test and before any symbol. Invisible while // every lossless frame was ALSO `CodedLossless` (its `tx_mode` is forced // `Only4x4`, so this function never ran); a MIXED frame keeps // `TxMode::Select`, so its lossless segments reach the symbol read and // must take the early return (lane-av1mixloss). if lossless(fctx) { return 4; } // `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 = tx_size_context_txfm(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). /// /// lane-av1-intrabc r3: an `allow_intrabc` KEY frame reads the same bands -- /// `read_intra_frame_mode_info` returns early for an intrabc block, so /// [`read_block_tx_size_rect`]'s var-tx tree is the intra path's one /// `txfm_partition_context` reader, and it reads whatever the block ABOVE and /// the block LEFT published. [`decode_block`] has published on such a frame /// since lane-t900 r32; the RECT strips did not, so the band still held the /// value of an older, smaller neighbour -- measured on the 256x192 testsrc2 /// cq45 var-tx arm: the coded 16x8 intrabc strip at mi(38,48) read ctx 14 /// where libaom reads 13 (`left_ctx` 4 vs the 8 the 16x8 intra strip at /// mi(38,44) should have published), desyncing the tile there. 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() && !allow_intrabc_frame(fctx) { 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:?})"); } } /// lane-av1oddheightfork3: `txfm_partition_update_rect`'s EXTENT is the /// transform NODE (`txb`), its VALUE is the resolved leaf -- the rule /// `txfm_partition_update` states as /// `bsize = txsize_to_bsize[txb_size]; bh = mi_size_high[bsize]; /// bw = mi_size_wide[bsize]; left_ctx[0..bh] = tx_size_high[tx_size]; /// above_ctx[0..bw] = tx_size_wide[tx_size]` (`av1_common_int.h:1684-1695`). /// /// The 320x236 ticket named the RECT case as the suspect ("`txsize_to_bsize` /// for a rect `txb_size` is the awkward part"). It is not: for every /// `TX_SIZE`, `mi_size_wide[txsize_to_bsize[t]] * MI == tx_size_wide[t]`, which /// is what makes `txb_w / MI` the right cell count. This test pins that /// identity from libaom's OWN `mi_size_wide`/`mi_size_high` rows (blockd.h) /// -- transcribed, not derived from the shape -- and then pins the primitive /// on a rect node, where an extent taken from the leaf instead of the node /// would write 1 cell where libaom writes 2 and 1 where libaom writes 4. #[test] fn txfm_partition_update_rect_extent_is_the_node_not_the_leaf() { // libaom `blockd.h`: (bsize, mi_size_wide, mi_size_high) for every // `txsize_to_bsize` image a `TX_SIZE` can name. const BSIZES: [(&str, usize, usize); 12] = [ ("BLOCK_4X4", 1, 1), ("BLOCK_4X8", 1, 2), ("BLOCK_8X4", 2, 1), ("BLOCK_8X8", 2, 2), ("BLOCK_8X16", 2, 4), ("BLOCK_16X8", 4, 2), ("BLOCK_16X16", 4, 4), ("BLOCK_16X32", 4, 8), ("BLOCK_32X16", 8, 4), ("BLOCK_32X32", 8, 8), ("BLOCK_4X16", 1, 4), ("BLOCK_16X4", 4, 1), ]; for (name, mi_w, mi_h) in BSIZES { // `tx_size_wide`/`tx_size_high` of the TX_SIZE that maps to this // bsize, and the same quantity as a pixel size. let (tx_w, tx_h) = (mi_w * MI, mi_h * MI); assert_eq!(tx_w / MI, mi_w, "{name}: width identity"); assert_eq!(tx_h / MI, mi_h, "{name}: height identity"); } // The primitive on a RECT node: an 8x16 node whose TX_4X4 early-return // leaf resolved (libaom `read_tx_size_vartx`'s `sub_txs == TX_4X4` arm, // which calls `txfm_partition_update(..., TX_4X4, tx_size)` with the // PARENT as the node). let fctx = &crate::decode::FrameCtx::new(); let mut n = Neighbours::new(4, 4, 32, 32, fctx); for cell in n.above_txfm.iter_mut() { *cell = 0; } for cell in n.left_txfm.iter_mut() { *cell = 0; } txfm_partition_update_rect(&mut n, (4, 4), (4, 4), (8, 16)); assert_eq!( &n.above_txfm[4..6], &[4, 4], "the node's OWN width (2 mi) carries the leaf's width" ); assert_eq!( &n.left_txfm[4..8], &[4, 4, 4, 4], "the node's OWN height (4 mi) carries the leaf's height" ); assert_eq!(n.above_txfm[6], 0, "and nothing past the node's extent"); assert_eq!(n.left_txfm[8], 0, "and nothing past the node's extent"); } /// 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() { // lane-av1refusalspan: this gate is the PROOF for both var-tx refusals, so // it names both and pins both guard sites. The walk below proves the leaf // domain; it never said which two strings that domain was about. for refusal in [ "an inter var-tx tree with a leaf transform larger than 32x32", "an inter var-tx tree with a leaf transform larger than 64x64", ] { assert!( crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), refusal), "this gate proves {refusal:?}, but that string is no longer in decode.rs" ); } // 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>)> { // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the // `read_tx_size` arm, which returns TX_4X4 before it reads anything. if lossless(fctx) { // lane-av1lm444loss: libaom CLIPS the transform-unit grid at the frame // edge -- `max_block_high`/`max_block_wide` (`av1_common_int.h:1565`, // `:1579`) fold `mb_to_bottom_edge`/`mb_to_right_edge` into // `block_size_high/wide` before `>> MI_SIZE_LOG2`, so a block that // hangs off the bottom/right codes only the units INSIDE the frame. // `decode_token_recon_block`'s mu walk then bounds every chunk with // `unit_height = ROUND_POWER_OF_TWO(AOMMIN(mu_blocks_high + row, // max_blocks_high), ss_y)`, so the out-of-frame units are never read. // // The unclipped `side / MI` grid is correct arithmetic for a block that // FITS, which is every block of a frame whose height and width are // multiples of the superblock -- so this reads identically on all of // those, and only differs on the partial edge block. Measured on the // 128x96 4:4:4 lossless pin (one 128 root per inter frame, frame 32 // mi = 24 tx rows tall): the unclipped grid read 32 rows where the // oracle read 24 -- 256 extra luma units per inter frame (1024 vs // the oracle's 768), the `EC_SYMR` ladder's first fork landing exactly // at that row-24 boundary (`plane=0` luma where the oracle had moved // to `plane=1`), and the pixel diff growing 5596 -> 33561 wrong // samples over the six frames. let side_mi = side / MI; 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)); if max_w_mi != side_mi || max_h_mi != side_mi { LOSSLESS_EDGE_CLIPPED.with(|c| c.set(c.get() + 1)); LOSSLESS_EDGE_CLIP_UNITS .with(|c| c.set(c.get() + (side_mi * side_mi - max_w_mi * max_h_mi))); } let mut leaves = Vec::with_capacity(max_w_mi * max_h_mi); for row in 0..max_h_mi { for col in 0..max_w_mi { leaves.push((row, col, 4, 4)); } } // lane-av1txctxband2: a lossless block still runs libaom's // `set_txfm_ctxs` at the tail of `parse_decode_block` // (decodeframe.c:1260). Its `read_tx_size` returned `TX_4X4` on the // FIRST line (decodeframe.c:1214) -- the early return skips the symbol // read, not the PUBLISH -- so `tx_size_wide[TX_4X4] == 4` goes over the // block's own width/height, and a SKIPPED inter block instead records // its block size (the `skip && is_inter` term). // // This early return published nothing, so on a MIXED frame every // lossless square block left the band holding whatever an earlier, // lossy block wrote. Measured on the 640x480 mixed-lossless+altref // cell (`420_mixll_altref_640x480_5f.obu`, 87 537 B): the abutting // 8x8 INTRA lossless block at mi(78,110) left `above_txfm[110]` at // the 16 a skipped 16-px inter block at mi(36,108) had written 43 mi // rows earlier, and the 8x4 intra leaf with `use_filter_intra` at // mi(80,110) then read `tx_size_cat0[2]` where libaom reads row 1 // (oracle `EC_TXCTXB` `abv=4 lft=8 above=0 left=1 ctx=1`). The tile // desynced there and the frame refused. // // The RECT twin [`read_block_tx_size_rect`] has published on this arm // since lane-av1lm444loss; only the square arm had the hole. let pub_above: u8 = if skip && is_inter { (side_mi * MI) as u8 } else { 4 }; // The gate's non-vacuity arm, on the DECISION, sampled BEFORE the // write: this publish CHANGES at least one of the above-band cells it // covers -- the cell did not already hold `pub_above`, so a later // `get_tx_size_context` / `txfm_partition_context` reader in the same // tile column reads a value the publish produced. // // CORRECTED 2026-09-30 (refutation pass `lanes/refute-av1txctxband2`): // an earlier version of this comment, and of the static's doc, claimed // the write counts only when it OVERWRITES "a size some earlier block // had left", and that a wholly-lossless all-non-skip stream leaves it // at zero. MEASURED FALSE: 420_lossless_tallinter_8x16.obu fires 48, // ALL with every covered column still at `TXFM_CTX_INIT` -- a first // write into a fresh tile column counts here too, because the test is // "the cell did not already hold this value", not "some block wrote a // different value earlier". Of the pin's 944 fires, 183 are that // first-touch case. The count is still a decision (no reader, no // intra-only frame, no unchanged column), so the gate keeps its teeth; // only the doc's stronger reading was wrong. let overwrote = !fctx.intra_only.with(std::cell::Cell::get) && (0..side_mi).any(|i| n.above_txfm.get(at_mi.1 + i) != Some(&pub_above)); set_txfm_ctxs(n, at_mi, 4, side_mi, side_mi, skip && is_inter); if overwrote { hit!(LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS); } return Ok((4, Some(leaves))); } 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, fctx) }; 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, // lane-av1-444: one 32x32 unit of a 4:4:4 64x32/32x64 chroma plane // block (`av1_get_max_uv_txsize` adjusts `TX_64X32`/`TX_32X64` to // `TX_32X32`); `get_txsize_entropy_ctx(TX_32X32)` is the 32x32 set. (32, 32) => TxbSet::Chroma32, // lane-av1-422j: square chroma units of a 4:2:2 strip -- a 16x8 // (8x16) luma strip's chroma plane block is 8x8 (16x16) square, and // the square-block routing above sends it here. The sets are the // exact `get_txsize_entropy_ctx` tables the square arms use. (16, 16) => TxbSet::Chroma16, (8, 8) => TxbSet::Chroma8, (4, 4) => TxbSet::Chroma4, _ => { // lane-av1-422l: the refusing (w, h) for the owning lane -- the // 4:2:2 frontier stops here at (4, 32), the plane residual of an // 8x32 luma block, which libaom itself marks BLOCK_INVALID // (`av1_ss_size_lookup[BLOCK_8X32][1][0]`, common_data.c:38) and // for which no TX_4X32 exists -- that chroma is coded as a // TX_8X32-chunked merge, not a 4-px unit. if crate::envflags::env_flag!("EC_AV1_TRACE_422") { eprintln!("EC_422 rect_inter_chroma_set missing (w,h)=({w},{h})"); } 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, // lane-av1-422j: square units routed through the rect reader -- a // 4:2:2 strip's square chroma plane block (8x8 under a 16x8 strip, // 16x16 under an 8x16 one). The default 2D scan is exactly what the // square reader uses for the same side. (w, h) if w == h => default_scan(w), _ => { 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() { // lane-av1refusalspan: this gate is the PROOF for THREE refusals, so it // names all three and pins all three guard sites. The census below proves // the shape domain and, on its own, named NONE of the strings that domain // was about -- under a real function boundary rather than a window that // ran into the next test, all three rows read as unanchored. for refusal in [ "a rectangular inter luma transform unit whose shape has no coefficient table set here", "a rectangular inter chroma transform unit whose shape has no coefficient table set here", "a rectangular transform unit whose shape has no coefficient scan table here", ] { assert!( include_str!("decode.rs").contains(refusal), "this gate proves {refusal:?}, but that string is no longer in decode.rs" ); } 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 lossless(fctx) { // lane-av1lm444loss: the same frame-edge clip as the square builder // above -- `max_block_high`/`max_block_wide` bound a rect block's // transform grid by the part of it inside the frame, so a 1:4 strip // hanging off the bottom codes only its in-frame rows. Identical // arithmetic for a block that fits. 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 full_w_mi = bw / MI; let full_h_mi = bh / MI; if max_w_mi != full_w_mi || max_h_mi != full_h_mi { LOSSLESS_EDGE_CLIPPED.with(|c| c.set(c.get() + 1)); LOSSLESS_EDGE_CLIP_UNITS .with(|c| c.set(c.get() + (full_w_mi * full_h_mi - max_w_mi * max_h_mi))); } let mut leaves = Vec::with_capacity(max_w_mi * max_h_mi); for row in 0..max_h_mi { for col in 0..max_w_mi { leaves.push((row, col, 4, 4)); } } // A lossless segment takes libaom's `else` branch (the var-tx // condition carries `!xd->lossless[mbmi->segment_id]`), so // `read_tx_size` returns `TX_4X4` and `set_txfm_ctxs` publishes it // over the block's own width/height. The grid's own values (4x4) are // identical either way, so this write is only what keeps the // caller's `fill_lf_grid_rect_after_vartx` suppression sound: a // mixed frame's lossy neighbour reads this block's bands. txfm_partition_update_rect(n, at_mi, (4, 4), (bw, bh)); return Ok(Some(leaves)); } 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_frame.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_frame.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); } // lane-av1oddheightfork2: `above_px` / `left_px` are the two // `TXFM_CONTEXT` inputs of `txfm_partition_ctx_rect`, i.e. the exact // operands of libaom's `*above_ctx < txw` / `*left_ctx < txh` // (av1_common_int.h:1750-1753). They are printed so a ctx disagreement // with aomdec's `EC_VARTX` rung names WHICH neighbour is wrong instead of // only the arithmetic difference. Trace-only; reads no bits. let (above_px, left_px) = (n.above_txfm[at_mi.1], n.left_txfm[at_mi.0]); let ctx = txfm_partition_ctx_rect(above_px, left_px, 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} above={above_px} left={left_px} maxblk={} tx={tx_w}x{tx_h} rng={rng}", at_mi.0, at_mi.1, u8::from(split), bw.max(bh), ); } 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)) } /// The chroma half of a whole-block rectangular INTER transform unit (both /// [`decode_inter_block`] rect readers): `av1_get_max_uv_txsize(bsize)` gives /// the strip's own rect chroma size at 4:2:0 (one unit for the whole block), /// but at 4:4:4 the chroma plane block keeps the luma block's 64-px axis, /// which `av1_get_adjusted_tx_size` caps at 32 (`TX_64X16` -> `TX_32X16`), /// so it codes TWO units plane-major (every U, then every V -- /// `decode_token_recon_block`'s inter branch loops `for plane` outside /// `for blk_row/blk_col` inside the one mu chunk). No unit codes a `tx_type` /// symbol: each inherits the block-wide luma one (`av1_get_tx_type`'s inter /// UV lookup at ss 0 reads the tx_type_map at its own mi, which a single-TU /// luma block fills uniformly). #[allow(clippy::too_many_arguments)] fn read_inter_rect_chroma( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, around: [(bool, bool, i32); 3], u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, su: Pred<'_>, sv: Pred<'_>, at_mi: (usize, usize), (cpx, cpy): (usize, usize), (write_chroma_w, write_chroma_h): (usize, usize), chroma_side: usize, mode_for_tx: usize, // lane-av1chrtx: this block's coded luma transform leaves, `(row, col, // tw, th, tx_type)` -- the same list the 4:4:4 four-unit arms resolve // through `covering_leaf_tx_type`. This sibling used to hand EVERY unit // the block-level `luma_tx_type` (the top-left leaf's type), so a rect // inter block whose chroma plane splits (`nx*ny > 1`) over MIXED var-tx // leaves read the wrong type per unit. leaf_tx_types: &[(usize, usize, usize, usize, TxType)], luma_tx_type: TxType, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, Grid, Vec<((usize, usize), usize, Grid, usize, usize)>)> { let (uw, uh) = (write_chroma_w.min(32), write_chroma_h.min(32)); // lane-av1-422m, CORRECTED lane-av1-422n: an 8x32 luma block HAS no // 4:2:2 plane residual block -- `av1_ss_size_lookup[BLOCK_8X32][1][0]` // is BLOCK_INVALID (= 255, blockd.h) -- so libaom never codes its chroma // as a (4, 32) unit, and no such coefficient set exists (no TX_4X32 // either). The plane is still coded, CHUNKED: `decode_token_recon_block` // (`decodeframe.c:1022`) steps the plane in `get_vartx_max_txsize` // units, where the `BLOCK_INVALID` plane size indexes // `max_txsize_rect_lookup` OUT OF BOUNDS and the byte read there in the // pinned Release oracle build is TX_4X8 -- the committed // "adjacent `vtx_tab[0]` = TX_4X4" reading was wrong (reviewer FAIL on // e24dc84b). `decode_reconstruct_tx`'s // `if (tx_size == plane_tx_size || plane)` never recurses for chroma, so // every unit reads at TX_4X8: FOUR stacked 4x8 units per plane over the // 4x32 chroma plane. The units KEEP a tx type: `av1_get_tx_type` // (blockd.h) has no TX_4X4 early-out -- it derives from the block's // inherited luma type reduced into the TX_4X8 ext-tx set // (`reduce_inherited_chroma_tx_type`), exactly like every other rect // unit here, so the 4:2:2 drop-the-type special case is gone. let invalid_ss_plane = ss_x(fctx) == 1 && ss_y(fctx) == 0 && (write_chroma_w, write_chroma_h) == (4, 32); let (uw, uh) = if invalid_ss_plane { (4, 8) } else { (uw, uh) }; // lane-av1chrtx: `inherit_tx_type` is resolved PER UNIT below, not once // for the block -- `av1_get_tx_type` (blockd.h:1287-1297) reads // `xd->tx_type_map` at the chroma unit's own position scaled back to // luma, so a unit sitting over a luma leaf that coded NOTHING takes that // leaf's `DCT_DCT` stamp (`decodetxb.c:199-203`), not the block-level // (top-left leaf) type. let (nx, ny) = (write_chroma_w / uw, write_chroma_h / uh); let multi = nx * ny > 1; let set = rect_inter_chroma_set(uw, uh)?; // lane-av1-422blockhalf: the assembled block grid is the PRED stride x // the plane's true height -- at 4:2:2 a square block's plane is // (side/2, side), so the old `chroma_side`-square sizing under-allocated // every row past `chroma_stride` once the caller began passing the // per-axis stride. let assembled_h = write_chroma_h.max(chroma_side); let mut assembled: [Vec; 2] = [Vec::new(), Vec::new()]; // The multi-unit stamps below are rewritten by the caller's whole-block // record (`record_rect_mi`/`record_split_luma_rect_mi` write ONE // whole-block chroma state, class `override-slot-on-one-arm`). The // block tail's square-mu derivation cannot express a non-square strip's // units, so the TRUE units travel back for the tail's `mu_chroma_units` // replay (the c8 re-stamp, at the strip's own tiling). let mut units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); if multi { hit!(CHROMA_SPLIT_TX_HITS); assembled = [ vec![0i32; chroma_side * assembled_h], vec![0i32; chroma_side * assembled_h], ]; } for plane_idx in 1..=2 { let (src, buf) = if plane_idx == 1 { (su, &mut *u) } else { (sv, &mut *v) }; for cu_row in 0..ny { for cu_col in 0..nx { let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx)); let cu_mi = ( at_mi.0 + cu_row * (span_y / MI), at_mi.1 + cu_col * (span_x / MI), ); let unit_rel_mi = (cu_mi.0 - at_mi.0, cu_mi.1 - at_mi.1); let cu_around = if multi { // lane-av1422ctxgather: at ss (1,0) the unit's above // span covers `uw` chroma px = `2*uw` luma mi columns, // so the plain per-mi gather counts every chroma // column's whole-unit dc sign twice // ([`Neighbours::around_mi_422_chroma`]; the left // extent is 1:1 at ss_y 0). 4:2:0 keeps the per-mi // gather (both extents duplicated there, measured // elsewhere). if ss_x(fctx) == 1 && ss_y(fctx) == 0 { neighbours.around_mi_422_chroma(cu_mi, span_x, span_y) } else { neighbours.around_mi_rect(cu_mi, span_x, span_y) } } else { around }; let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh); let cu_pred = src.offset(cu_row * uh * chroma_side + cu_col * uw); let inherit_tx_type = if let Some(t) = covering_leaf_tx_type(leaf_tx_types, unit_rel_mi) { hit!(CHROMA_RECT_LEAF_TX_HITS); if Some(t) != Some(luma_tx_type) { hit!(CHROMA_RECT_LEAF_TX_DIFF_HITS); } Some(t) } else { // lane-av1ichromatx: the ONE remaining site in // `decode_inter_block` that can hand a chroma unit a // BLOCK-level type on a split plane. `covering_leaf_tx_ // type` found nothing, i.e. no luma leaf covers this // unit's own MI cell -- which is exactly the shape a // block that coded a SINGLE luma transform has (its // leaf list is empty, so every lookup misses). For // that block `luma_tx_type` IS the type of the one // luma unit whose stamp covers the whole plane, so the // fallback is correct there. // // What is NOT correct is a fallback on a plane with // `leaves` NON-empty: then some luma leaf does exist, // it simply does not cover this unit's cell, and the // block-level value is a DIFFERENT leaf's type. The // assertion below is what closes that shape, so the // fallback can never again be a silent mistype: the // class is "block-level where the unit's own cell // says otherwise", and this is its last site. hit!(CHROMA_RECT_BLOCK_TX_FALLBACK); if multi { hit!(CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI); } debug_assert!( leaf_tx_types.is_empty(), "lane-av1ichromatx: a multi-unit rect chroma plane fell back to the \ block-level tx_type while {} luma leaves were coded -- the unit's own \ av1_get_tx_type cell is then some other leaf's stamp, not \ luma_tx_type", leaf_tx_types.len() ); Some(luma_tx_type) }; let cu_grid = read_inter_plane_rect( dec, cdfs, set, (uw, uh), chroma_side, plane_idx, cu_around[plane_idx], mode_for_tx, buf, cu_x, cu_y, cu_pred, inherit_tx_type, multi.then_some(3), fctx, )? .0; if invalid_ss_plane { hit!(CHROMA422_CHUNK_HITS); } if multi { // Immediately, so the next unit of this block reads this // one's coefficient context (libaom updates the chroma // above/left contexts per unit). neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid); let dst = &mut assembled[plane_idx - 1]; for rr in 0..uh { let start = (cu_row * uh + rr) * chroma_side + cu_col * uw; dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]); } units.push((cu_mi, plane_idx, cu_grid, span_x, span_y)); } else { let mut full = vec![0i32; chroma_side * assembled_h]; for rr in 0..uh { full[rr * chroma_side..][..uw].copy_from_slice(&cu_grid[rr * uw..][..uw]); } assembled[plane_idx - 1] = full; } } } } let [ug, vg] = assembled; Ok((Grid::Own(ug), Grid::Own(vg), units)) } /// [`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)> { // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma // coefficients (`plane < av1_num_planes == 1`). if plane_idx > 0 && mono(fctx) { return Ok((Grid::Zero(w * h), TxType::DctDct)); } // lane-av1readcensus: the units read from here on are this plane's. set_census_plane(plane_idx); 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 { // 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 a multi-unit caller adds 3 through // `luma_skip_ctx` (same convention as [`read_plane`]). usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0) }; let mut coding = cdfs.txb(set, tx_mode); // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read // transform type for lossless mode(qindex==0)" -- the symbol is not coded // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every // plane of a lossless block (the residual then goes through the WHT, so // the type only picks the scan, which is the default one). if lossless(fctx) { coding.tx_type = None; } // `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, }; // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one. let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type }; // 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, plane_idx, )? }; 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 { plane: plane_idx, w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type, qm: block_iqmatrix(fctx, plane_idx, w, h, tx_type), stride, lossless: lossless(fctx), }; 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) } /// [`embed_rect_grid`] that keeps the shared zero marker zero: an all-zero /// transform unit's grid IS `Grid::Zero` (whose deref is the shared /// `ZERO_RESIDUAL`), so re-laying it would read a zero-length slice. fn embed_grid_stride(grid: &Grid, w: usize, h: usize, stride: usize) -> Grid { if is_zero_grid(grid) { return Grid::Zero(stride * stride); } Grid::Own(embed_rect_grid(grid, w, h, stride)) } /// 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)> { // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom // `read_block_tx_size`'s lossless TX_4X4), tree or no tree. let split = split || lossless(fctx); 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). pub(crate) fn reduce_inherited_chroma_tx_type( t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx, ) -> TxType { reduce_inherited_chroma_tx_type_flagged( t, w, h, fctx.reduced_tx_set_inter.with(std::cell::Cell::get), ) } /// [`reduce_inherited_chroma_tx_type`] against an explicit `reduced_tx_set` /// bit (lane-intertx): the WRITER calls this with the frame's own header bit /// ([`crate::cdf_state::Cdfs::reduced_tx_set`]) to derive the type an inter /// block's chroma transform is coded with, the same derivation its reader /// makes -- it has no `FrameCtx` in reach and must not silently read one /// whose value can lag the frame being written (class `stale-context-bit`). pub(crate) fn reduce_inherited_chroma_tx_type_flagged( t: TxType, w: usize, h: usize, reduced: bool, ) -> TxType { use TxType::*; let sqr_up = w.max(h); let sqr = w.min(h); // `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 } } /// The [`TxbSet`] a resolved luma transform side reads its coefficient tables /// from 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 ([`txbset_for`]). /// /// 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::Luma8Inter`]/[`TxbSet::Luma4Inter`]). /// /// lane-av1txr: the intrabc leaf sites used to call a near-duplicate /// `txbset_for_inter` whose `4` fell through to `Luma64` -- 32x32-class tables /// (a 1024-entry grid) handed to a 4x4 dequant, which panicked at /// `transform.rs`'s `inverse_transform_2d_typed_wh` the first time an intrabc /// 4x4 TU coded a non-zero coefficient (`allintra0`/cpu-used=0). The /// duplicate is gone; every inter-table site goes through this one mapping. 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"), } } 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 { 1 << (if dir == 0 { ss_x(fctx) } else { ss_y(fctx) }) } 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, if c.chroma { ss_y(c.fctx) } else { 0 }), plane_to_mi(c.chroma, x0, if c.chroma { ss_x(c.fctx) } else { 0 }), ); 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 ss = if c.dir == 0 { ss_x(c.fctx) } else { ss_y(c.fctx) }; let plane_dim = ((dim_mi * MI) >> ss).max(4); (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0 } else { plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }, 0) == 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`. // lane-av1-444: the chroma crop follows the sequence subsampling, not a // hardcoded 4:2:0 halving -- at 4:4:4 the halved bound clipped the whole // filter to the top-left quarter of each chroma plane. let (cw, ch) = if chroma { ( frame_width.div_ceil(1 << ss_x(fctx)), frame_height.div_ceil(1 << ss_y(fctx)), ) } 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>, /// lane-av1cap2: the final replay's post-CDEF luma plane and the TRUE /// post-deblock rows loop restoration substitutes at its stripe /// borders ([`plane_snapshot`], exactly `restoration::lr_src_row`'s /// rows) -- what [`replay_restoration`] filters, instead of decoding /// the re-coded tile a second time. final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>, /// lane-av1speed3: the previous candidate's DESTINATION planes, still /// holding its post-CDEF samples, and one byte per 8x8 CDEF unit its /// filter wrote (see [`cdef_band`]). The CDEF half of the search moves /// no deblocking level, so every candidate of it used to copy the three /// post-deblock planes (~19 MB at 4K) into fresh destinations. Here the /// destinations are kept and only the units the last candidate touched /// are restored -- the same bytes, since a unit nobody wrote still holds /// the deblocked sample it was copied from. work: Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>, wrote: Vec, /// The strengths [`FilterReplay::work`] was filtered under: a plane whose /// new candidate can only write MORE units than the old one needs no /// restore at all, since every unit CDEF writes it writes from the /// post-deblock source alone. work_cdef: Option, /// 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); } // Test-only: run the capture decode `replay_final` replaced as well, and // hold its picture and its `FilterStages` against the replay's // (`encoder::tests::filter_replay_final_matches_the_capture_decode`). // Thread-local, not a global: the filter stage runs on the frame thread the // test itself drives, and a process-wide flag would put every test encoding // in parallel with this one through the extra decode too. #[cfg(test)] thread_local! { static VERIFY_FINAL: std::cell::Cell = const { std::cell::Cell::new(false) }; } #[cfg(test)] pub(crate) fn set_verify_final_replay(on: bool) { VERIFY_FINAL.set(on); } #[cfg(test)] pub(crate) fn verify_final_replay() -> bool { VERIFY_FINAL.get() } /// 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(), work: None, wrote: Vec::new(), work_cdef: None, final_luma: None, deblocked: None, }); }); } /// Restores, from the post-deblock cache, every sample the previous CDEF /// candidate may have written: for each unit row, the column span between /// its first and last written unit (a superset of the written units, which /// is what makes the copy contiguous -- and never more than the whole-plane /// copy it replaces). `unit` is this plane's CDEF unit side, 8 for luma and /// 4 for 4:2:0 chroma. fn restore_written( dst: &mut PlaneBuf<'static>, src: &PlaneBuf<'_>, wrote: &[u8], mask: u8, unit_cols: usize, unit: usize, ) { let w = dst.width; if w == 0 || unit_cols == 0 || wrote.is_empty() { return; } let rows = dst.data.len() / w; let s: &[u16] = &src.data; let d = dst.data.to_mut(); let band = |d: &mut [u16], wr: &[u8], ur0: usize| { for (i, row) in wr.chunks(unit_cols).enumerate() { let Some(c0) = row.iter().position(|&b| b & mask != 0) else { continue; }; let c1 = row .iter() .rposition(|&b| b & mask != 0) .expect("just found one"); let (x0, x1) = ((c0 * unit).min(w), ((c1 + 1) * unit).min(w)); let ur = ur0 + i; let (y0, y1) = ((ur * unit).min(rows), ((ur + 1) * unit).min(rows)); for r in y0..y1 { let off = (r - ur0 * unit) * w; d[off + x0..off + x1].copy_from_slice(&s[r * w + x0..r * w + x1]); } } }; let urows = wrote.len() / unit_cols; let threads = crate::par::filter_threads().min(urows.max(1)); if threads <= 1 { band(d, wrote, 0); return; } let per = urows.div_ceil(threads); let batch = crate::par::Batch::new("ec-av1-filter"); for (i, (dc, wr)) in d .chunks_mut(per * unit * w) .zip(wrote.chunks(per * unit_cols)) .enumerate() { let band = &band; batch.submit(move || band(dc, wr, i * per)); } } /// 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_inner(loop_filter, cdef, None, fctx).map(|(picture, _)| picture) } /// lane-av1cap: the filter stage's LAST replay -- the WINNING parameters, /// under the per-64x64 `cdef_idx` grid the re-coded tile carries. The stage /// used to reach this picture by decoding that re-coded tile a second time /// (10% of a 4K frame's encode), only because the loop-restoration search /// needs the decoder's own post-CDEF plane /// ([`FrameCtx::capture_stages`]). It is the same two kernel calls /// ([`apply_deblock`], [`apply_cdef`]) on the same captured pre-filter /// planes in the same order, so it is the same bytes -- pinned by /// `encoder::tests::filter_replay_final_matches_the_capture_decode`, which /// runs the decode as well and holds picture and stages against it. /// /// `want_stages` mirrors `capture_stages`' own `deblocked = None` arm: that /// decode's header says `RESTORE_NONE`, so the decoder took no pre-CDEF /// snapshot and handed the post-CDEF plane over for both stages. pub(crate) fn replay_final( loop_filter: &LoopFilterParams, cdef: &CdefParams, idx_grid: &[u8], want_stages: bool, fctx: &FrameCtx, ) -> Option<(Picture, Option)> { #[cfg(test)] if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) { return None; } replay_inner(loop_filter, cdef, Some((idx_grid, want_stages)), fctx) } fn replay_inner( loop_filter: &LoopFilterParams, cdef: &CdefParams, // `Some((cdef_idx grid, capture the filter stages))` for the final // replay; `None` for a scoring candidate, which always codes `bits == 0`. final_pass: Option<(&[u8], bool)>, fctx: &FrameCtx, ) -> Option<(Picture, Option)> { REPLAY.with_borrow_mut(|slot| { let r = slot.as_mut()?; let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter); // Set when the working planes ARE the deblocked planes (see below): // they go into the cache at the end, and the picture is cropped out // of them rather than taking their buffers. let mut share = false; let cpt = crate::par::timer(crate::par::S_COPY); let unit_cols = r.neighbours.mi_cols.div_ceil(2); let unit_rows = r.neighbours.mi_rows.div_ceil(2); let (mut y, mut u, mut v) = if hit { let work = r.work.take(); let wrote = std::mem::take(&mut r.wrote); // `cdef_adjust_strength` is monotone in the strength it is given, // so a candidate whose primary strength is no lower and whose // secondary is zero only if the last one's was writes every unit // the last one wrote -- and writes it from the same post-deblock // source, so the samples under it need not be put back first. // Only while both candidates carry ONE strength pair (`bits == // 0`, every scoring candidate) and read the same `cdef_idx` grid. let superset = |cur: (u8, u8), old: (u8, u8)| cur.0 >= old.0 && (cur.1 != 0 || old.1 == 0); let (skip_y, skip_uv) = match (final_pass, &r.work_cdef) { (None, Some(old)) if old.bits == 0 && cdef.bits == 0 => ( superset( (cdef.y_pri_strength[0], cdef.y_sec_strength[0]), (old.y_pri_strength[0], old.y_sec_strength[0]), ), superset( (cdef.uv_pri_strength[0], cdef.uv_sec_strength[0]), (old.uv_pri_strength[0], old.uv_sec_strength[0]), ), ), _ => (false, false), }; let (deblocked, scratch) = (&r.deblocked, &mut r.scratch); let (_, dy, du, dv) = deblocked.as_ref().expect("just matched"); match work { Some((mut wy, mut wu, mut wv)) => { if !skip_y { restore_written(&mut wy, dy, &wrote, 1, unit_cols, 8); } if !skip_uv { restore_written(&mut wu, du, &wrote, 2, unit_cols, 4); restore_written(&mut wv, dv, &wrote, 2, unit_cols, 4); } (wy, wu, wv) } None => ( 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. for plane in r.work.take().into_iter().flat_map(|(a, b, c)| [a, b, c]) { r.scratch.push(plane.data.into_owned()); } r.work_cdef = None; 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, ); // lane-av1cap2: an all-zero-strength CDEF writes no sample at // all ([`cdef_all_zero`]'s own early return), so THESE planes // are already this candidate's output -- they become the // deblock cache at the end instead of being copied into it // here, which is three ~6 MB copies less per candidate that // moves the levels (the whole deblocking half of the search: // its CDEF strengths are still (0,0)). share = cdef_all_zero(cdef); if !share { let scratch = &mut r.scratch; r.deblocked = Some(( *loop_filter, pooled(&y, scratch), pooled(&u, scratch), pooled(&v, scratch), )); } (y, u, v) }; drop(cpt); // The winner's `cdef_idx` literals live in the re-coded tile, which // nothing parses on this path -- hand the grid the encoder already // chose straight to the filter (`bits == 0` leaves the grid the last // parse sized, which is what every scoring candidate reads). if let Some((grid, _)) = final_pass.filter(|(g, _)| !g.is_empty()) { fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec()); } let ct = crate::par::timer(crate::par::S_CDEF); let mut wrote = std::mem::take(&mut r.wrote); wrote.clear(); wrote.resize(unit_cols * unit_rows, 0); r.work_cdef = Some(*cdef); let pre = r .deblocked .as_ref() .map(|(_, dy, du, dv)| (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())); apply_cdef( &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx, pre, Some(&mut wrote), ); drop(ct); if final_pass.is_some_and(|(_, want)| want) { // The loop-restoration search runs on the stages above (where // post-CDEF stands in for post-deblock, as the capture decode // had it); the FILTER this frame ends up applying reads the // real post-deblock rows, which is what the decoder does. let snapshot = if share { // Nothing filtered these planes after the deblock, so they // are the post-deblock picture themselves. Some(plane_snapshot(&y, 0)) } else { r.deblocked .as_ref() .map(|(_, dy, ..)| plane_snapshot(dy, 0)) }; let scratch = &mut r.scratch; r.final_luma = snapshot.map(|d| (pooled(&y, scratch), d)); } let stages = final_pass.and_then(|(_, want)| { want.then(|| FilterStages { deblocked: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()], cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()], stride: [y.width, u.width, v.width], }) }); // 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); r.wrote = Vec::new(); r.work_cdef = None; if share { let picture = Picture { width: r.width, height: r.height, y: y.data.to_vec(), u: u.data.to_vec(), v: v.data.to_vec(), }; r.deblocked = Some((*loop_filter, y, u, v)); return Some((picture, stages)); } return Some(( Picture { width: r.width, height: r.height, y: y.data.into_owned(), u: u.data.into_owned(), v: v.data.into_owned(), }, stages, )); } 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, round_ss(tw, ss_x(fctx)), round_ss(th, ss_y(fctx))), v: crop(&v, round_ss(tw, ss_x(fctx)), round_ss(th, ss_y(fctx))), }); }); let out = Picture { width: fw, height: fh, y: crop(&y, fw, fh), u: crop(&u, round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx))), v: crop(&v, round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx))), }; // The working planes outlive the crop: either they ARE the // deblocked planes this candidate's successors reuse, or they go // back to the pool. if share { r.wrote = Vec::new(); r.work_cdef = None; r.deblocked = Some((*loop_filter, y, u, v)); } else { // lane-av1speed3: kept whole (post-CDEF samples and all) for the // next candidate, together with the map of what CDEF wrote. r.wrote = wrote; r.work = Some((y, u, v)); } Some((out, stages)) }) } /// lane-av1cap2: the loop-restoration half of the final replay. Once the /// units are chosen the tile is coded a second time to carry them, and that /// re-coded tile used to be DECODED to reach the restored reference frame /// (5.6% of a 4K frame's encode). Loop restoration reads nothing of that /// tile but the per-unit filters the encoder just picked: it is the /// decoder's own [`crate::restoration::apply_loop_restoration_plane`] on /// the post-CDEF plane the final replay produced, with the TRUE /// post-deblock stripe-border rows -- the same call the decoder's /// `apply_loop_restoration` makes, on the same input. Only luma moves: the /// encoder never writes a chroma restoration type other than /// `RESTORE_NONE`, whose kernel hands its input straight back. /// /// Returns the cropped luma plane and refreshes the wide-margin stash's own /// luma (restoration writes strictly inside `frame_width x frame_height`, /// so the margin columns past it stand). `None` when nothing was captured /// -- the caller then decodes for real. pub(crate) fn replay_restoration( lr: &LoopRestorationParams, units: &[Option], 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 (cdefed, deblocked) = r.final_luma.as_ref()?; let (fw, fh) = (r.frame_width, r.frame_height); let mut grid = crate::restoration::RestorationGrid::with_ss( lr, fw as u32, fh as u32, fctx.subsampling_x.get(), fctx.subsampling_y.get(), ); let (horz, vert) = (grid.horz_units[0], grid.vert_units[0]); if horz == 0 || units.len() != horz * vert { return None; } for (i, filter) in units.iter().enumerate() { if let Some(info) = filter { grid.set( 0, i / horz, i % horz, crate::restoration::UnitFilter::Wiener(*info), ); } } let stride = cdefed.width; let mut out = scratch_empty(); crate::restoration::apply_loop_restoration_plane( &cdefed.data, &deblocked.data, stride, fw, fh, 0, lr.frame_restoration_type[0], lr.loop_restoration_size[0], &grid, 0, &mut out, None, fctx, ); fctx.last_frame_wide_margin.with(|m| { if let Some(p) = m.borrow_mut().as_mut() { let tw = p.width; for row in 0..p.height.min(fh) { let n = tw.min(fw); p.y[row * tw..][..n].copy_from_slice(&out[row * stride..][..n]); } } }); let mut y = Vec::with_capacity(fw * fh); for row in 0..fh { y.extend(out[row * stride..][..fw].iter().copied()); } scratch_return(out); Some(y) }) } /// 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, // lane-av1speed3: one byte per 8x8 CDEF unit of the WHOLE frame (stride // `mi_cols.div_ceil(2)`), set for every unit this band actually filters. // Bit 0 = this unit's LUMA square was filtered, bit 1 = its chroma ones. // `cdef_adjust_strength` zeroes a unit's primary strength off its own // variance, so which units a candidate writes is not a function of its // strengths alone -- the encoder's filter replay reuses one destination // plane across candidates and needs the map to restore it. mut wrote: Option<&mut [u8]>, ) { let unit_cols = skip_grid.mi_cols.div_ceil(2); 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; // lane-av1422filter: the chroma direction is the luma one // remapped through `conv422`/`conv440` under asymmetric // subsampling (see [`CDEF_DIR_CONV422`]); identical to the // raw luma direction for 4:2:0 and 4:4:4. let uv_dir = if t_uv != 0 { match (ss_x(fctx), ss_y(fctx)) { (1, 0) => CDEF_DIR_CONV422[dir], (0, 1) => CDEF_DIR_CONV440[dir], _ => dir, } } else { 0 }; let enable_primary_uv = t_uv != 0; let enable_secondary_uv = uv_sec_strength != 0; if let Some(w) = wrote.as_deref_mut() { let mark = u8::from(enable_primary || enable_secondary) | (u8::from(enable_primary_uv || enable_secondary_uv) << 1); w[(mi_r / 2) * unit_cols + mi_c / 2] = mark; } if enable_primary_uv || enable_secondary_uv { let (cox, coy) = (ox >> ss_x(fctx), oy >> ss_y(fctx)); let (csize_x, csize_y) = (8 >> ss_x(fctx), 8 >> ss_y(fctx)); 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, csize_x, csize_y, &mut win_uv, ); cdef_filter_block( &win_uv, plane, cox, coy, csize_x, csize_y, 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); // lane-av1422filter: chroma band rows follow the frame's ss_y // (4:2:2 chroma bands the luma 64-row grid, not 32). let (c_lo, c_hi) = ((j * 64) >> ss_y(fctx), ((j + 1) * 64) >> ss_y(fctx)); snap_band( su2.data.to_mut(), u, ss_y(fctx) as u32, c_lo, c_hi, cfg.cdef_on, ); snap_band( sv2.data.to_mut(), v, ss_y(fctx) as u32, c_lo, c_hi, 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, None, ); } } // 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()), // lane-av1422filter: chroma plane extents and stripe geometry follow // the frame's own subsampling -- 4:2:2 chroma is full-height with // luma-grid stripes (only 4:2:0 halves both). ( round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx)), ss_y(fctx) as u32, u.width, u.data.len(), ), ( round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx)), ss_y(fctx) as u32, 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; } if r_lo == 0 { // lane-av1lrflush: RU row 0 just entered this plane's // processed range -- the band release flushed the frame's // first restoration row through the pipeline. Process-global // (not a `thread_local!` gate counter): the witnessing gate // decodes on its own thread while this bump fires on a // filter-pool worker, and frame 0's whole-frame LR runs on // the gate's thread and must not satisfy the delta. LR_PIPELINE_ROW0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } 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); /// lane-av1lrflush: frames that CONSTRUCTED the filter pipeline, counted /// unconditionally. Read by gates through [`pipeline_taken_frames`] as a /// before/after delta -- the non-vacuity witness that a "pipelined" gate arm /// really ran `pipe_run`/`pipe_run_lr` rather than silently falling back to /// the whole-frame path. static PIPELINE_TAKEN: AtomicU64 = AtomicU64::new(0); /// Current value of [`PIPELINE_TAKEN`], for a gate's own before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn pipeline_taken_frames() -> u64 { PIPELINE_TAKEN.load(std::sync::atomic::Ordering::Relaxed) } /// lane-av1lrflush: RU-row-0 flushes the pipeline actually performed, one per /// LR-active plane whose first restoration unit row enters `pipe_run_lr`'s /// processed range. Process-global on purpose -- the filter-pool worker bumps /// it, the gate's thread reads it -- unlike the `thread_local!` gate counters, /// which a gate's own thread can satisfy from the whole-frame path alone. static LR_PIPELINE_ROW0: AtomicU64 = AtomicU64::new(0); /// Current value of [`LR_PIPELINE_ROW0`], for a gate's before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn lr_pipeline_row0_flushes() -> u64 { LR_PIPELINE_ROW0.load(std::sync::atomic::Ordering::Relaxed) } /// 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_SKIP_LR") || 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, // See [`cdef_band`]. Shared because the bands below write disjoint unit // ROWS of it, exactly as they write disjoint plane rows. wrote: Option>, ) { 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()) }; // SAFETY: this band marks only the unit rows its own mi rows cover, // disjoint from every other band's (see `Shared`). #[allow(unsafe_code)] let wr = wrote.as_ref().map(|w| unsafe { w.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, wr, ); }); } 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-av1cap: every CDEF unit reads the PRE-CDEF planes, so the filter // starts by copying all three (~19 MB at 4K). The encoder's filter // replay already holds an untouched copy of exactly those planes -- its // post-deblock cache, which is where the working planes were copied FROM // -- so it hands them straight in and the copy does not happen. `None` // (every decode) copies as before. src: Option<(&[u16], &[u16], &[u16])>, // See [`cdef_band`]: `Some` only from the encoder's filter replay, which // clears and sizes it (`mi_cols.div_ceil(2) * mi_rows.div_ceil(2)`) // before the call. mut wrote: Option<&mut [u8]>, ) { // 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 owned = src.is_none(); let (src_y, src_u, src_v) = match src { Some((a, b, c)) => ( std::borrow::Cow::Borrowed(a), std::borrow::Cow::Borrowed(b), std::borrow::Cow::Borrowed(c), ), None => ( std::borrow::Cow::Owned(scratch_from(&y.data)), std::borrow::Cow::Owned(scratch_from(&u.data)), std::borrow::Cow::Owned(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, wrote.as_deref_mut().map(crate::par::Shared::new), ); if owned { scratch_return(src_y.into_owned()); scratch_return(src_u.into_owned()); scratch_return(src_v.into_owned()); } } /// [`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, ) { // lane-svt1 debug rung, env-gated: see `apply_cdef`/`apply_deblock`'s siblings. if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_LR") { return; } 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, round_ss(frame_w, ss_x(fctx)), round_ss(frame_h, ss_y(fctx)), ss_y(fctx) as u32, 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, round_ss(frame_w, ss_x(fctx)), round_ss(frame_h, ss_y(fctx)), ss_y(fctx) as u32, 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) }; } thread_local! { /// lane-av1h5: how many blocks had their leaf walk actually PERMUTED into /// libaom's chunk-major order by [`mu_chunk_order`] -- a block above 64 /// whose sort was not a no-op. Deliberately not "took the order": a /// no-op ordering change must read 0 so a gate cannot look armed. pub(crate) static MU_CHUNK_ORDER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1h5: chunk-major chroma WALKS run for a 128-root plane block -- /// one per 64x64 mu chunk. libaom codes exactly 4 per unsplit 128x128 root /// (`decode_token_recon_block`'s chunk loop), so a stream whose 128 roots /// can be counted pins this exactly; the pre-fix redundancy read 64. pub(crate) static MU_CHUNK_WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1h5: chroma transform units those walks read. On the pinned /// 128x96 4:4:4 lossless stream, 1536 per inter frame (768 per plane), /// against the oracle's 1536. pub(crate) static MU_CHUNK_WALK_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1lm444loss: lossless blocks whose transform-unit grid was /// CLIPPED at the frame edge -- `max_block_high`/`max_block_wide` cut the /// grid short of the block's own `side / MI`, so libaom codes fewer TX_4X4 /// units than the block is wide/tall. Zero on any frame whose height and /// width are multiples of the superblock, so a gate cannot look armed by /// merely decoding. pub(crate) static LOSSLESS_EDGE_CLIPPED: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1lm444loss: the transform units that clip REMOVED -- the /// `(side / MI - clipped) * (side / MI)` overflow the pre-fix walk read /// past the frame bottom/right edge. On the 128x96 4:4:4 lossless pin this /// is 256 per inter frame (8 unclipped luma rows x 32 columns), and 0 on a /// frame that fits. pub(crate) static LOSSLESS_EDGE_CLIP_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1mixllfork: sub-8 (4x8 / 8x4) inter leaves whose var-tx tree /// was SUPPRESSED because their own segment is lossless -- libaom's /// `parse_decode_block` carries `!xd->lossless[mbmi->segment_id]` as a /// conjunct of the tree condition (`decodeframe.c:1237`), so a mixed- /// lossless frame codes no `tx_size_cat1` symbol there. Zero on any frame /// whose sub-8 leaves all sit in lossy segments, so a gate cannot look /// armed by merely decoding. /// /// CORRECTED 2026-09-30 by the refutation pass (`lanes/refute-av1mixllconj`): /// the hit was UNCONDITIONAL inside the else-if, which also serves leaves /// whose `tx_select_inter` is off -- the pass measured **33 hits on a build /// with the conjunct REMOVED**, i.e. it was counting a population the /// conjunct does not touch. It is now guarded on `tx_select_inter`, the same /// term the conjunct uses, so a hit means the suppression is the conjunct's /// doing. pub(crate) static SUB8_LOSSLESS_NO_VARTX: std::cell::Cell = const { std::cell::Cell::new(0) }; /// lane-av1txctxband2: SQUARE lossless blocks on an INTER frame whose /// `set_txfm_ctxs` publish CHANGED at least one above-band cell it covers /// (the cell did not already hold the published size), so a later /// `get_tx_size_context` / `txfm_partition_context` reader in the same /// tile column reads a value this publish produced. Zero on an intra-only /// frame (where `fill_lf_grid_rect_inner` publishes the same 4x4 value at /// the same footprint). /// /// CORRECTED 2026-09-30 (refutation pass `lanes/refute-av1txctxband2`): /// this doc previously claimed the hit meant "overwrote a size some /// earlier block left" and that a wholly-lossless all-non-skip stream /// leaves it at zero. MEASURED FALSE -- `420_lossless_tallinter_8x16.obu` /// fires **48**, all of them first touches of a column still at /// `TXFM_CTX_INIT`; `420_lossless_arf_1to4_320x240_5f.obu` fires 320, 53 of /// them first touches. Of the pin's 944, **183 are first-touch**. The /// predicate tests "the cell did not already hold this value", which is /// the decision that matters (no reader, no intra-only frame, no unchanged /// column still reads 0), but it is NOT the strictly narrower causal claim /// the old text made. pub(crate) static LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`MU_CHUNK_WALKS`], for a gate's own before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn mu_chunk_walks() -> usize { MU_CHUNK_WALKS.with(std::cell::Cell::get) } /// [`MU_CHUNK_WALK_UNITS`], for a gate's own before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn mu_chunk_walk_units() -> usize { MU_CHUNK_WALK_UNITS.with(std::cell::Cell::get) } /// [`MU_CHUNK_ORDER_HITS`], for a gate's own before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn mu_chunk_order_hits() -> usize { MU_CHUNK_ORDER_HITS.with(std::cell::Cell::get) } /// [`LOSSLESS_EDGE_CLIPPED`] -- lossless blocks whose TX grid the frame-edge /// clip shortened, for a gate's own before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn lossless_edge_clipped() -> usize { LOSSLESS_EDGE_CLIPPED.with(std::cell::Cell::get) } /// [`LOSSLESS_EDGE_CLIP_UNITS`] -- transform units the clip removed, i.e. the /// ones the unclipped pre-fix walk read past the frame edge. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn lossless_edge_clip_units() -> usize { LOSSLESS_EDGE_CLIP_UNITS.with(std::cell::Cell::get) } /// [`LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS`] -- square lossless inter blocks /// whose `set_txfm_ctxs` publish overwrote a size an earlier block of the /// same frame had left in the above band, for a gate's own before/after /// delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn lossless_sq_txfm_band_overwrite_hits() -> usize { LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS.with(std::cell::Cell::get) } /// [`SUB8_LOSSLESS_NO_VARTX`] -- sub-8 inter leaves on a lossless segment that /// read no var-tx symbol, for a gate's own before/after delta. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn sub8_lossless_no_vartx() -> usize { SUB8_LOSSLESS_NO_VARTX.with(std::cell::Cell::get) } /// [`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) } thread_local! { /// How many INTRA leaves of an inter frame's 8x8 block ran the lossless /// 4:4:4 chroma walk ([`read_intra_chroma_lossless`], lane-av1-llintra8) /// -- one bump per leaf, four units per plane inside it. A gate proving /// the arm must see this nonzero; CHROMA_SPLIT_TX_HITS alone cannot /// attribute its bumps to THIS leaf. pub(crate) static LLINTRA8_CHROMA_WALK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`LLINTRA8_CHROMA_WALK_HITS`]: lossless 4:4:4 chroma walks through an /// inter frame's 8x8 INTRA leaf. pub fn llintra8_chroma_walk_hits() -> usize { LLINTRA8_CHROMA_WALK_HITS.with(|c| c.get()) } thread_local! { /// lane-av1sub8rect444: how many of `decode_intra_sub8_leaf`'s 8x4/4x8 /// INTRA leaves ran the lossless 4:4:4 per-unit chroma walk (two TX_4X4 /// units per plane, plane-major) instead of one TX_8X4/TX_4X8 rect unit /// -- the shape whose unit count AND skip ctx the rect read got wrong. /// A gate proving the arm fired; CHROMA_SPLIT_TX_HITS cannot attribute /// its bumps to THIS leaf. pub(crate) static LLSUB8RECT444_CHROMA_WALK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`LLSUB8RECT444_CHROMA_WALK_HITS`]: lossless 4:4:4 chroma walks through a /// sub-8 8x4/4x8 INTRA leaf. pub fn llsub8rect444_chroma_walk_hits() -> usize { LLSUB8RECT444_CHROMA_WALK_HITS.with(|c| c.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, // `read_lr` is the ONE consumer that turns this superblock's // mode-info origin into ABSOLUTE frame space -- it divides by the // restoration-unit size, which is a real pixel count. The partition // decode below is self-consistent with `mi_r128` as written (it // only ever uses relative offsets from it), which is why a 128x128 // stream decoded correctly for 4:2:0 and 4:4:4 while placing its // loop-restoration units at double the offset. `sb_r`/`sb_c` index // 64px superblocks, so a 128px superblock's origin is half a // `SB_MI` per 64px step -- `(sb_r & !1) * SB_MI` is twice the true // mi row. The extent is `SB_MI`: a 128px superblock is 16 mi. (sb_r & !1) * (SB_MI / 2), (sb_c & !1) * (SB_MI / 2), SB_MI, 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)); fctx.tx_select_frame.with(|c| c.set(tx_select)); // lane-av1-rect14: an intrabc block is `is_inter_block`, so its // `tx_type` CDF is the INTER set selected by this frame's // `reduced_tx_set`. Left at the cell default, the first coded // 16x4 intrabc strip reads the wrong alphabet. fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); // Every block of an intra-only frame publishes its resolved transform into // the `TXFM_CONTEXT` bands exactly like an inter frame's does -- see // [`Neighbours::fill_lf_grid_rect`]. fctx.intra_only.with(|c| c.set(true)); 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 (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx)); let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx)); let mut u = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), width: cw, height: ch, true_width: ctw, true_height: cth, tile_x0: 0, tile_y0: 0, tile_x1: cw, tile_y1: ch, }; let mut v = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), width: cw, height: ch, true_width: ctw, true_height: cth, tile_x0: 0, tile_y0: 0, tile_x1: cw, tile_y1: ch, }; 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::with_ss( lr, superres(fctx).map_or(frame_width, |(w, _)| w), frame_height, fctx.subsampling_x.get(), fctx.subsampling_y.get(), ); // 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); // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets // it codes every symbol against the tables it started with. dec.set_cdf_update(!cdf_update_disabled(fctx)); crate::census::register_cdfs(&cdfs); 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 * 4) >> ss_x(fctx), (mi_row0 as usize * 4) >> ss_y(fctx), ((mi_col1 as usize * 4) >> ss_x(fctx)).min(u.width), ((mi_row1 as usize * 4) >> ss_y(fctx)).min(u.height), ); v.set_tile_origin( (mi_col0 as usize * 4) >> ss_x(fctx), (mi_row0 as usize * 4) >> ss_y(fctx), ((mi_col1 as usize * 4) >> ss_x(fctx)).min(v.width), ((mi_row1 as usize * 4) >> ss_y(fctx)).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, // True mode-info units: a 64px superblock is 8, and `SB_MI` is 16. // `read_lr` divides by the restoration-unit size (a real pixel count), // so it is the one consumer that needs the absolute origin in real mi. // The half-mi convention these arguments used to carry only worked // while `read_lr` also counted in half-mi -- the two cancelled. sb_r * (SB_MI / 2), sb_c * (SB_MI / 2), SB_MI / 2, 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 { if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={} rng={}", sb_r * SB_MI, sb_c * SB_MI, ctx, dec.debug_bitpos(), dec.debug_state().0 ); } let p = dec.symbol(&mut cdfs.partition_w64[ctx]); if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART_VAL mi_row={} mi_col={} bsize=12 value={}", sb_r * SB_MI, sb_c * SB_MI, p ); } 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 { if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={} rng={}", r32 * BLOCK_MI, c32 * BLOCK_MI, ctx32, dec.debug_bitpos(), dec.debug_state().0 ); } let p = dec.symbol(&mut cdfs.partition_w32[ctx32]); if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART_VAL mi_row={} mi_col={} bsize=9 value={}", r32 * BLOCK_MI, c32 * BLOCK_MI, p ); } 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 { if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={} rng={}", sr * SUB_MI as usize, sc * SUB_MI as usize, ctx16, dec.debug_bitpos(), dec.debug_state().0 ); } let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]); if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART_VAL mi_row={} mi_col={} bsize=6 value={}", sr * SUB_MI as usize, sc * SUB_MI as usize, part16 ); } if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}", sr * SUB_MI as usize, sc * SUB_MI as usize ); } 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); if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={} rng={}", leaf_mi.0, leaf_mi.1, leaf_ctx, dec.debug_bitpos(), dec.debug_state().0 ); } let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); if crate::envflags::env_flag!("EC_TRACE") { eprintln!( "EC_PART_VAL mi_row={} mi_col={} bsize=3 value={}", leaf_mi.0, leaf_mi.1, part8 ); } 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); } dump_prefilter_wide(&y, &u, &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), // lane-av1422filter: the bands are the LR stripe-boundary context // (`RESTORATION_UNIT_OFFSET >> ss_y` above/below each 64-luma-row // stripe). Chroma stripes are half-height ONLY under 4:2:0; a // 4:2:2 frame's chroma (ss_y = 0) stripes on the luma grid, so // the hardcoded `1` saved bands at rows 26/60/92/124 where LR // reads rows 54..57/118..121 -- every 4:2:2 boundary // substitution read uninitialised zeros (frame-0 V (48,0)). plane_snapshot(&u, ss_y(fctx) as u32), plane_snapshot(&v, ss_y(fctx) as u32), ) }); // 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, None, None, ); 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) = ( round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx)), round_ss(uw, ss_x(fctx)), ); 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, round_ss(true_width, ss_x(fctx)), round_ss(true_height, ss_y(fctx)), ), v: crop( &v, round_ss(true_width, ss_x(fctx)), round_ss(true_height, ss_y(fctx)), ), }) } else { None } }); Ok(( Picture { width: fw, height: fh, y: crop_owned(y, fw, fh), u: crop_owned(u, round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx))), v: crop_owned(v, round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx))), }, 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, ); } crate::census::mv(pred.0 + diff.0, pred.1 + diff.1); (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, // The block's own mi footprint (`av1_find_mv_refs` takes the real bsize, // so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4` leaf scans a 1x2/2x1 neighbourhood // -- lane-av1txr). (n4_w, n4_h): (usize, usize), fctx: &crate::decode::FrameCtx, ) -> (i32, i32) { const INTRABC_DELAY_PIXELS: i32 = 256; 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_w, n4_h, 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); let dv = read_mv( dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true, ); if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { let (rng, _) = dec.debug_state(); eprintln!( "EC_DV mi_row={mi_r} mi_col={mi_c} dv_col={} dv_row={} rng={rng}", dv.1, dv.0 ); } dv } /// 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, ss: usize) -> i32 { // orig_pos += mv * (1 << (1 - ss)). Luma always passes 0. (pos as i32) * 16 + mv_component * (1i32 << (1 - ss as i32)) } 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. #[track_caller] fn reconstruct_mc_rect( &mut self, x: usize, y: usize, plane: 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-av1ibcfork: the MC/inter write's own origin and shape. The intra // side's `EC_PRED` rung prints the PREDICTION, so a region whose // prediction is byte-identical to the oracle's and whose committed // samples are not can only be a DIFFERENT WRITE -- and this is the // only write path with no rung of its own. if crate::envflags::env_flag!("EC_MCWR") { eprintln!( "EC_MCWR x={x} y={y} side={side} w={w} h={h} empty_res={} at {}", residual.is_empty(), std::panic::Location::caller() ); } // lane-av1444altref r2: EC_CPRED, the picture-independent twin of the // oracle's rung of the same name (aomdec's // `dec_build_inter_predictor`). This is the ONE site every inter // prediction reaches on its way into a plane -- after the compound // blend and after the inter-intra blend, before the residual -- so it // measures exactly the quantity the oracle's rung measures. Pairing // is by (plane, x, y, w, h): the same chroma geometry recurs in many // pictures, so a rung line alone is ambiguous, but a geometry whose // samples differ by at most 1 is a unique match (any wrong pairing // differs by tens). // Env: EC_CPRED="x:y" (plane-absolute origin; -1 for either = any). if let Ok(spec) = crate::envflags::var("EC_CPRED") { let (fx, fy): (i64, i64) = spec .split_once(':') .and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?))) .unwrap_or((-1, -1)); let hit = (fx < 0 || fx == x as i64) && (fy < 0 || fy == y as i64); if hit { // `PREFILT_PICTURE_IDX` is bumped once per frame just AFTER // that frame's `flush_recon`, so it still reads this frame's own // decode-order index here -- the same numbering the oracle's // `aom_ec_pict_idx` and the `.fN` prefilter dumps use. let pict = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst); eprintln!( "OUR_CPRED pict={pict} plane={plane} x={x} y={y} w={w} h={h} side={side}" ); for row in 0..h { let src = &prediction[row * side..row * side + w]; let mut line = String::with_capacity(w * 4); for v in src { line.push(' '); line.push_str(&v.to_string()); } eprintln!("OUR_CPROW{row}:{line}"); } } } // 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 (col, (o, &p)) in out.iter_mut().zip(pred).enumerate() { let v = i32::from(p).clamp(0, max) as u16; pix_write("mc_copy", x, y, w, x + col, y + row, *o, v); *o = v; } } 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 (col, ((o, &p), &r)) in out.iter_mut().zip(pred).zip(res).enumerate() { let v = (i32::from(p) + r).clamp(0, max) as u16; pix_write("mc_add", x, y, w, x + col, y + row, *o, v); *o = v; } } } } /// 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)> { // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma // coefficients (`plane < av1_num_planes == 1`). if plane_idx > 0 && mono(fctx) { return Ok((Grid::Zero(side * side), TxType::DctDct)); } // lane-av1readcensus: the units read from here on are this plane's. set_census_plane(plane_idx); 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); // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read // transform type for lossless mode(qindex==0)" -- the symbol is not coded // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every // plane of a lossless block (the residual then goes through the WHT, so // the type only picks the scan, which is the default one). if lossless(fctx) { coding.tx_type = None; } let default_tx_type = match inherited_luma_tx_type { Some(t) => reduce_inherited_chroma_tx_type(t, side, side, fctx), None => TxType::DctDct, }; // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one. let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type }; 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 { plane: plane_idx, w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type, qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type), stride: 0, lossless: lossless(fctx), }; push_mc_rect_tx( plane_idx, x, y, side, side, side, prediction, tx, &grid, fctx, ); Ok((grid, tx_type)) } /// The intra twin of [`read_inter_chroma_lossless`]: an INTRA block inside a /// lossless frame codes its chroma plane as 4x4 transform units, plane-major /// inside each 64x64 mu chunk (libaom `decode_token_recon_block`'s /// `for (plane..) for (blk_row..) for (blk_col..)` with `av1_get_tx_size` /// returning TX_4X4 under `xd->lossless[..]`). CfL never rides here: /// `is_cfl_allowed` (`blockd.h`) needs a BLOCK_4X4 chroma plane block, i.e. a /// luma block of 8x8 or less, which the sub-8x8 readers own. #[allow(clippy::too_many_arguments)] fn read_intra_chroma_lossless( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, at_mi: (usize, usize), (px, py): (usize, usize), (cpx, cpy): (usize, usize), side: usize, (blk_w, blk_h): (usize, usize), (org_x, org_y): (usize, usize), (reg_w, reg_h): (usize, usize), stride: usize, reach: Reach, (frame_w, frame_h): (usize, usize), mode: usize, uv_predict_mode: usize, angle_delta_uv: i32, palette_uv_bufs: Option<(&[u16], &[u16])>, smooth_neighbor_uv: bool, base_q_idx: u8, u_out: &mut Vec, v_out: &mut Vec, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let scan4 = default_scan(4); let offset = (blk_w > 4 || blk_h > 4).then_some(3); for plane_idx in 1..3 { for rr in 0..reg_h / 4 { for cc in 0..reg_w / 4 { let (ox, oy) = (org_x + cc * 4, org_y + rr * 4); // libaom's `max_blocks_wide/high` clip: a unit whose origin is // past the frame edge is not coded at all // (`decode_token_recon_block`), same test `decode_block`'s // luma loop already runs. if cpx + ox >= u.true_width || cpy + oy >= u.true_height { continue; } // Chroma pixels per mi cell: 2 at 4:2:0, 4 at 4:4:4. At // 4:2:0 a TX_4X4 chroma unit spans two mi cells and anchors // at the even one; at 4:4:4 it IS one mi cell. let cu_mi = ( at_mi.0 + oy / (MI >> ss_y(fctx)), at_mi.1 + ox / (MI >> ss_x(fctx)), ); // libaom's chroma entropy-context arrays are SUBSAMPLED: // `get_txb_ctx` reads exactly one entry per plane for a // TX_4X4 chroma unit (`a[0]`/`l[0]`). Our bands are luma-mi // indexed and carry that one entry replicated over the unit's // two cells, so one cell is the same answer -- and the second // cell is past the band on a unit whose block hangs off the // frame edge, which libaom still codes. let cu_around = neighbours.around_mi(cu_mi, MI); // The unit's origin and extent in LUMA pixels: `<< ss` at // 4:2:0 (8x8 luma for a 4x4 chroma unit), identity at 4:4:4. let cu_reach = tu_reach_rect( side, side, ox << ss_x(fctx), oy << ss_y(fctx), 4 << ss_x(fctx), 4 << ss_y(fctx), reach, px, py, frame_w, frame_h, fctx, ); if let Some((ub, vb)) = palette_uv_bufs { let buf = if plane_idx == 1 { ub } else { vb }; set_palette_pred(palette_window(buf, stride, ox, oy, 4, 4), fctx); } let buf: &mut PlaneBuf<'static> = if plane_idx == 1 { &mut *u } else { &mut *v }; let cu_grid = read_plane( dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx, cu_around[plane_idx], mode, uv_predict_mode, angle_delta_uv, cu_reach, buf, cpx + ox, cpy + oy, 4, 4, base_q_idx, None, None, offset, smooth_neighbor_uv, fctx, )?; // The unit's own footprint on the LUMA mi grid: 8 luma px // (two cells) at 4:2:0, 4 (one cell) at 4:4:4. neighbours.record_mi_chroma( cu_mi, 4 << ss_x(fctx), 4 << ss_y(fctx), plane_idx, &cu_grid, ); hit!(CHROMA_SPLIT_TX_HITS); let dst = mu_units( if plane_idx == 1 { &mut *u_out } else { &mut *v_out }, // lane-av1422lpf site 7: `stride * blk_h`, the intra twin // of site 1. `read_intra_chroma_lossless`'s own // `(blk_w, blk_h)` parameter is the block's whole CHROMA // PLANE BLOCK, per-axis, and the walk below addresses up // to row `org_y + reg_h - 1` at `stride` -- so the // requirement is `stride * blk_h` and `stride * stride` // underruns by exactly the ratio the plane block's height // exceeds its width. Identical number at 4:2:0 // (`blk_h == stride`) and 4:4:4. stride * blk_h, ); for row in 0..4 { let start = (oy + row) * stride + ox; dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]); } } } } Ok(()) } /// lane-av1h5: the CHUNK-MAJOR token order for a block's var-tx leaf list. /// /// libaom's `decode_token_recon_block` (`av1/decoder/decodeframe.c:972`) /// iterates 64x64 "mu" chunks with the PLANE loop INSIDE the chunk loop: /// `for (row..) for (col..) { for (plane..) for (blk_row..) for (blk_col..) }`, /// `blk_row`/`blk_col` restarting at the chunk origin, on a chunk grid of /// `mi_size_wide[BLOCK_64X64]` = 16 mi per axis. /// /// The transform tree hands us a BLOCK-wide raster instead (32 leaves across /// at 128), whose chunk members are NOT contiguous: leaves 0..15 are chunk /// (0,0) row 0, but chunk (0,0) rows 1..15 are leaves 32..47, 64..79, ... /// Walking it as given closes each chunk every SIXTEEN leaves and codes its /// chroma sixteen times -- 64 chroma walks per 128 root where libaom codes 4, /// and 24576 chroma units per inter frame against the oracle's 1536. /// /// Below 64 a block IS one chunk, so the two orders coincide and the sort is /// skipped (the returned order is the identity). `changed` is `true` only /// when the sort actually permutes the list, so a no-op ordering reads zero /// on [`MU_CHUNK_ORDER_HITS`] and cannot make a gate look armed. fn mu_chunk_order(leaves: &[(usize, usize, usize, usize)], side: usize) -> (Vec, bool) { let identity: Vec = (0..leaves.len()).collect(); if side <= 64 { return (identity, false); } let nchunk = (side / 64).max(1); let mut order = identity.clone(); order.sort_by_key(|&i| ((leaves[i].0 / 16) * nchunk + (leaves[i].1 / 16), i)); let changed = order != identity; if changed { hit!(MU_CHUNK_ORDER_HITS); } (order, changed) } /// lane-lossless2: the chroma half of a lossless INTER block. libaom's /// `read_tx_size` (`av1/decoder/decodeframe.c`) returns TX_4X4 for EVERY /// plane of a lossless block, so the chroma plane block is a raster of 4x4 /// transform units instead of one whole-block transform, and /// `decode_token_recon_block` walks them PLANE-MAJOR inside each 64x64 "mu" /// chunk (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of /// the chunk, then every V unit. Reads one chunk-sized region /// (`org`/`reg`, chroma pixels relative to the block) and copies its units /// into the block-sized `u_out`/`v_out` grids. #[allow(clippy::too_many_arguments)] fn read_inter_chroma_lossless( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, su: Pred<'_>, sv: Pred<'_>, at_mi: (usize, usize), (cpx, cpy): (usize, usize), (org_x, org_y): (usize, usize), (reg_w, reg_h): (usize, usize), // the whole block's chroma plane block -- what `get_txb_ctx`'s offset is // decided on. (blk_w, blk_h): (usize, usize), // the stride the predictors and the block-sized `u_out`/`v_out` are read // at (the block's square chroma side, even for a 2:1 strip, which embeds // its narrower plane block in the same square grid). stride: usize, mode_for_tx: usize, base_q_idx: u8, u_out: &mut Vec, v_out: &mut Vec, fctx: &crate::decode::FrameCtx, ) -> Result<()> { let scan4 = default_scan(4); // `get_txb_ctx` (`av1/common/txb_common.h`): `ctx_offset` is 10 when the // plane block is bigger than the transform and 7 when it is the // transform -- our chroma tables carry the offset-10 rows at +3. let offset = (blk_w > 4 || blk_h > 4).then_some(3); // lane-av1h5: a plane block above 64 is the 128-root class, whose chroma // libaom walks one 64x64 mu chunk at a time. Counted so a gate can pin // the walk/unit totals exactly rather than as a floor on wrong output. let counted_128 = blk_w > 64 || blk_h > 64; if counted_128 { hit!(MU_CHUNK_WALKS); } for plane_idx in 1..3 { for rr in 0..reg_h / 4 { for cc in 0..reg_w / 4 { let (ox, oy) = (org_x + cc * 4, org_y + rr * 4); // libaom's `max_blocks_wide/high` clip: a unit whose origin is // past the frame edge is not coded at all // (`decode_token_recon_block`), same test `decode_block`'s // luma loop already runs. if cpx + ox >= u.true_width || cpy + oy >= u.true_height { continue; } // The chroma neighbour bands are indexed in LUMA mi: a 4-wide // chroma unit spans `4 << ss` luma pixels, i.e. `4 >> ss` -- // 2 mi cells at 4:2:0, one at 4:4:4. let cu_mi = ( at_mi.0 + oy / (4 >> ss_y(fctx)), at_mi.1 + ox / (4 >> ss_x(fctx)), ); // libaom's chroma entropy-context arrays are SUBSAMPLED: // `get_txb_ctx` reads exactly one entry per plane for a // TX_4X4 chroma unit (`a[0]`/`l[0]`). Our bands are luma-mi // indexed and carry that one entry replicated over the unit's // two cells, so one cell is the same answer -- and the second // cell is past the band on a unit whose block hangs off the // frame edge, which libaom still codes. let cu_around = neighbours.around_mi(cu_mi, MI); let (src, buf) = if plane_idx == 1 { (su, &mut *u) } else { (sv, &mut *v) }; let cu_grid = read_inter_plane( dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx, cu_around[plane_idx], mode_for_tx, buf, cpx + ox, cpy + oy, 4, base_q_idx, src.offset(oy * stride + ox), // A lossless block codes DCT_DCT on every plane // (`av1_get_tx_type`, `blockd.h`), so nothing is // inherited from the luma unit. None, offset, fctx, )? .0; // Immediately, so the NEXT unit reads this one's context. neighbours.record_mi_chroma( cu_mi, 4 << ss_x(fctx), 4 << ss_y(fctx), plane_idx, &cu_grid, ); hit!(CHROMA_SPLIT_TX_HITS); if counted_128 { hit!(MU_CHUNK_WALK_UNITS); } let dst = mu_units( if plane_idx == 1 { &mut *u_out } else { &mut *v_out }, // lane-av1422lpf site 1: `stride * blk_h`, NOT // `stride * stride`. The composed `u_out`/`v_out` grid is // the block's whole CHROMA PLANE BLOCK read at `stride`, // and libaom's plane block is PER-AXIS // (`(bw >> ss_x) x (bh >> ss_y)`, decodeframe.c's // `dec->uv_buffer` extent) -- square only when // `ss_x == ss_y`. The walk above addresses row // `org_y + reg_h - 1` at column `org_x + reg_w`, and every // call site passes a region that is a sub-rect of `blk` // with `org` inside `blk`, so the requirement is exactly // `stride * blk_h` (the last row's end // `(blk_h - 1) * stride + blk_w` fits because // `blk_w <= stride` at all nine call sites). // // Where the plane block IS square -- 4:2:0 (`side/2` both // axes) and 4:4:4 (`side` both axes) on a square block -- // `blk_h == stride` and this reduces to the old // `stride * stride` verbatim, so it cannot move a byte // there. It is not 4:2:2-only either: a 64x128 4:2:0 block // has a 32x64 chroma plane block, and `ll420_a.obu` // (`range end index 1028 out of range for slice of // length 1024`) panicked on the old expression. stride * blk_h, ); for row in 0..4 { let start = (oy + row) * stride + ox; dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]); } } } } Ok(()) } /// The 8x8 inter leaf's lossless chroma arm (lane-av1-llinter), shared by the /// single-ref and compound paths, for every plane block BIGGER than 4x4: /// libaom's `read_tx_size` (`av1/decoder/decodeframe.c:1197`, /// `if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;`) returns TX_4X4 /// for EVERY plane of a lossless block, not just luma, so the plane block is /// a raster of TX_4X4 units read by the same per-unit walk the bigger inter /// blocks run. /// /// **The plane block is PER-AXIS**, `av1_ss_size_lookup[BLOCK_8X8][ss_x][ss_y]` /// (`av1/common/blockd.h:1186`): BLOCK_8X8 at 4:4:4 (2x2 units), BLOCK_4X8 at /// 4:2:2 (1x2 units), BLOCK_4X4 at 4:2:0 (one unit, `get_txb_ctx`'s /// `plane_bsize == txsize_to_bsize[tx_size]` branch, ctx_offset 7 -- the one /// shape that keeps the single-unit read and is NOT routed here). Gating this /// arm on the 4:4:4 shape instead left 4:2:2 coding its 4x8 plane block as ONE /// TX_4X8 unit at ctx_offset 7, where libaom reads TWO TX_4X4 units at /// ctx_offset 10 (`av1/common/txb_common.h:430-433`): the first unit's /// `txb_skip` symbol then came out of the wrong CDF row, which desynchronised /// the coder for the rest of the frame. /// /// `(blk_w, blk_h)` is that per-axis plane block and `stride` the composed /// grid's row pitch (the leaf's `chroma_w`); the grids are `stride * blk_h` /// (`Grid::Zero` when every unit hung off the frame edge) and each unit's own /// coefficient context is left stamped in the neighbour bands -- the caller's /// tail must not let its whole-block `record_mi` overwrite them. #[allow(clippy::too_many_arguments)] fn leaf8_inter_chroma_lossless( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, su: Pred<'_>, sv: Pred<'_>, at_mi: (usize, usize), (cpx, cpy): (usize, usize), // The leaf's CHROMA PLANE BLOCK, per axis, and the composed grid's row // pitch -- `(8, 8)`/`8` at 4:4:4, `(4, 8)`/`4` at 4:2:2. (blk_w, blk_h): (usize, usize), stride: usize, base_q_idx: u8, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, Grid)> { let (mut uo, mut vo) = (Vec::new(), Vec::new()); read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, su, sv, at_mi, (cpx, cpy), (0, 0), (blk_w, blk_h), (blk_w, blk_h), stride, 0, base_q_idx, &mut uo, &mut vo, fctx, )?; let n = stride * blk_h; Ok(( if uo.is_empty() { Grid::Zero(n) } else { Grid::Own(uo) }, if vo.is_empty() { Grid::Zero(n) } else { Grid::Own(vo) }, )) } /// 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), { // No subsampling field on a stored reference: the // chroma format comes off its own sample count -- // 4:4:4 `w * h`, 4:2:2 `round_ss(w, 1) * h`, 4:2:0 // `round_ss(w, 1) * round_ss(h, 1)`. The helper's own // doc carries the measurement behind those three arms // and the pre-existing odd-dimension 4:2:0 gap. let (cw, ch) = ref_chroma_shape(g.u.len(), g.width, g.height); whole_plane(&g.u, cw, ch) }, { let (cw, ch) = ref_chroma_shape(g.v.len(), g.width, g.height); whole_plane(&g.v, cw, ch) }, ) }) }); 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(|| { if crate::envflags::env_flag!("EC_AV1_REFPROBE") { eprintln!( "EC_REFPROBE missing ref {ref_frame}\n{}", std::backtrace::Backtrace::force_capture() ); } // lane-hdrlossless: libaom errors on the same stream // (`decodeframe.c:5027`: `if (cm->ref_frame_map[ref] == NULL) // aom_internal_error(... AOM_CODEC_CORRUPT_FRAME, "Inter frame // requests nonexistent reference")`) -- a spec-conformant guard. 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, } } /// A reference picture's own chroma plane shape, `(width, height)`, from its /// luma size and its chroma sample count. A stored reference carries no /// subsampling field, so the format is read back off the count -- and the /// counts are the producer's own [`round_ss`] crops /// (`decode.rs:25806`), so the test must use `round_ss` too and not a bare /// halving: 4:4:4 stores `w * h`, 4:2:2 stores `round_ss(w, 1) * h` (half /// width CEIL, full height), 4:2:0 stores `round_ss(w, 1) * round_ss(h, 1)`. /// A floor test here silently misses every odd-width 4:2:2 reference and /// drops it into the 4:2:0 arm -- the same defect one dimension over. /// /// The two-way test this replaces ("luma-sized, else a quarter") folded 4:2:2 /// into the 4:2:0 shape entirely, so a 4:2:2 reference plane claimed /// `h / 2` rows -- half the samples it actually holds. Every chroma MC /// reading such a plane then had its source row clamped against /// `true_height` (spec 7.11.3.4 / libaom's /// `dec_calc_subpel_params_and_extend` clamps to the reference's valid /// area), which folded every chroma row at or past the frame's midpoint /// back onto the last valid row: on the pinned t422 fixture frame 1, the /// 8x4 inter strip at luma (88, 208) MC-predicted chroma (88, 104) from /// frame 0 with mv 0 and a pure copy, yet wrote (206, 204, 202, 200) x4 /// rows where the reference holds (202, 204, 204, 167) / /// (185, 190, 190, 165) / ... /// **Ambiguity, measured rather than argued away:** the inference reads a /// format off a length, so it is only as good as the lengths being /// distinct. Brute-forced against the producer's own `round_ss` crops over /// every `w, h` in `1..=128`, the 4:4:4 and 4:2:2 counts are distinct from /// each other and from the 4:2:0 count, and both route correctly for /// **every `w >= 2 && h >= 2`**. No stream this decoder accepts reaches a /// 1-pixel chroma plane; the pinned fixture's chroma is 128x144. /// /// **4:2:0 at odd dimensions: CLOSED by lane-av1odd440.** The arm used to be /// the old `(width / 2, height / 2)` floor, which was what the two-way test /// this replaces produced -- harmless then, since no 4:2:0 stream changed /// shape, and wrong for an odd-dimension 4:2:0 reference: the producer /// stored `round_ss(w, 1) x round_ss(h, 1)`, so the floor arm /// under-declared. Measured over the `1..=128` square, running each 4:2:0 /// count through this very function: 12160 of the 16384 pairs came back /// smaller than the plane actually holds, 12033 of those with `w >= 2` and /// 127 in the `w == 1` column, where the floor cannot even express /// `(1, round_ss(h, 1))`. It was left alone pending "a lane that can bring /// odd-dimension 4:2:0 fixtures with it" -- this is that lane: the pinned /// `420_odd65x65_key.obu` is a real 65x65 4:2:0 key frame (declared at /// `encode::encode_key_frame_at_size`, because aomenc rounds the coded size /// down to even and cannot produce one) whose chroma planes are 33x33, and /// the gate `an_odd_luma_420_key_frame_decodes_pixel_exact` decodes it /// sample-exact against `aomdec`. The arm is now the producer's own crop, /// so a 4:2:0 reference at ANY size routes back to the shape the producer /// wrote. Even sizes are untouched: `(2k + 1) / 2 == k`, so every 4:2:0 /// reference this decoder met before this lane claims exactly the same /// shape it did then. fn ref_chroma_shape(len: usize, width: usize, height: usize) -> (usize, usize) { let half_w = round_ss(width, 1); if len == width * height { (width, height) } else if len == half_w * height { (half_w, height) } else { (round_ss(width, 1), round_ss(height, 1)) } } /// 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. // lane-av1422warp r33 (reviewer P2): the snap must be UNCONDITIONAL. // libaom `obmc.h:41-46` is // `above_mi = prev_row_mi + (above_mi_col & ~1) + 1` -- the snapped // COLUMN is used as-is and the +1 is what lands it back on the // block's own left edge. Clamping the snapped INDEX to `mi_col` // (an earlier r25 attempt) moved the index itself, so this // decoded the neighbour one column RIGHT of libaom's and, after // `col += step`, never visited `mi_col + 1`. Only the REPORTED // offset can be negative -- `above_mi - mi_col == -1` -- so the // clamp belongs there, not on the index. 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.saturating_sub(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. // lane-av1422warp r33 (reviewer P2): the row mirror of the // `overlappable_above` fix. libaom's left-column walk snaps // `(left_mi_row & ~1)` and adds 1; the snap is unconditional and // only the REPORTED `row - mi_row` can be -1. The r25 clamp moved // the snapped index itself, which read the neighbour one row // BELOW libaom's and then skipped `mi_row + 1` entirely. 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.saturating_sub(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, if luma { 0 } else { ss_x(fctx) }), mv_to_q4(y, mv.0, if luma { 0 } else { ss_y(fctx) }), 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, if luma { 0 } else { ss_x(fctx) }), mv_to_q4(y, mv.0, if luma { 0 } else { ss_y(fctx) }), 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, subw: usize, subh: 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). // `(subw, subh)` are the plane's own subsampling shifts; // the four branches mirror aom_dsp/blend-a64-mask.c's // `subw`/`subh` pair handling exactly: luma (0, 0) reads // the direct sample, (1, 1) the 2x2 box average // (reconinter.c sub8x8), and 4:2:2's (1, 0) the // `AOM_BLEND_AVG` column pair. Some((mask, ms)) => match (subw, subh) { (0, 0) => u32::from(mask[i * ms + j]), (1, 1) => { 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 } (1, 0) => { let t = i * ms + 2 * j; (u32::from(mask[t]) + u32::from(mask[t + 1]) + 1) >> 1 } (_sw, _sh) => { let t = 2 * i * ms + j; (u32::from(mask[t]) + u32::from(mask[t + ms]) + 1) >> 1 } }, None => u32::from(match ii_mode { 0 => 32u8, 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, // lane-av1-llpred2: the FRAME's own subsampling pair -- the same pair the // chroma window half in [`obmc_run`] shifts by. A rect strip's ss cannot // be derived from a rect size over the square `chroma_side`: that ratio // gave a 16x8 strip at 4:2:0 ss=(1,0) (losing its above-chroma skip) and // divides by zero at 4:4:4 (`trailing_zeros(0)` = 64, a debug shift panic). ss_x: usize, ss_y: usize, chroma_stride: 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` 829) switches on the PLANE block // (`get_plane_block_size`, ss-shifted): only 4x4/8x4/4x8 skip the ABOVE // pass's chroma (`return dir == 0`), the LEFT pass still blends them. // lane-av1-llpred: the old luma-shape list `(8,8)|(16,8)|(8,16)` // hardcoded the 4:2:0 plane sizes; at 4:4:4 the plane block is the luma // block itself (never 4-wide), so every one of those blocks was silently // missing its above-pass chroma OBMC blend. // lane-av1-llpred2: ss is the FRAME's own pair (`ss_x`/`ss_y(fctx)`, the // same values [`obmc_run`]'s chroma windows shift by), never a ratio of // the rect write size over the square `chroma_side` -- that ratio gave a // 4:2:0 16x8 strip ss=(1,0) and dropped its above-chroma skip, and at // 4:4:4 divided to zero (`trailing_zeros(0)` = 64, a debug shift panic). let skip_chroma_above = obmc_skip_chroma_above(write_w, write_h, ss_x, ss_y); 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_stride, write_w, write_h, px, py, cpx, cpy, overlap_above, overlap_left, skip_chroma_above, }) } /// `av1_skip_u4x4_pred_in_obmc`'s above-pass decision (libaom /// `reconinter.c` 829): the PLANE block (`write_w >> ss_x`, `write_h >> /// ss_y`) is 4x4, 8x4 or 4x8. `ss_x`/`ss_y` are the FRAME's own pair -- the /// same values [`obmc_run`]'s chroma windows shift by -- never a ratio over /// the square `chroma_side` (lane-av1-llpred2: that ratio dropped the /// 4:2:0 16x8/8x16 skip and shifted by 64 at 4:4:4). Pure so the check /// below pins the rect-strip decision without decoding a stream. pub(crate) fn obmc_skip_chroma_above( write_w: usize, write_h: usize, ss_x: usize, ss_y: usize, ) -> bool { matches!((write_w >> ss_x, write_h >> ss_y), (4, 4) | (8, 4) | (4, 8)) } #[cfg(test)] mod obmc_skip_chroma_tests { use super::obmc_skip_chroma_above; /// lane-av1-llpred2: the above-chroma skip keys off the PLANE block /// under the frame's own ss pair. At 4:2:0 a 16x8/8x16 rect strip's /// plane block is 8x4/4x8 and MUST still skip (the old `chroma_side` /// ratio read ss=(1,0) off a 16x8 strip and made it blend); at 4:4:4 /// the plane block is the luma block, so only true 4-wide/high shapes /// skip and the shift never leaves `usize` range (the old ratio's /// `trailing_zeros(0)` = 64 panicked a debug build). #[test] fn rect_strips_skip_above_chroma_at_420_and_shift_never_overflows() { // 4:2:0 (ss 1,1): 8x8 -> 4x4, 16x8 -> 8x4, 8x16 -> 4x8 all skip. assert!(obmc_skip_chroma_above(8, 8, 1, 1)); assert!(obmc_skip_chroma_above(16, 8, 1, 1)); assert!(obmc_skip_chroma_above(8, 16, 1, 1)); // ... larger plane blocks blend, exactly libaom's own list. assert!(!obmc_skip_chroma_above(16, 16, 1, 1)); assert!(!obmc_skip_chroma_above(32, 16, 1, 1)); assert!(!obmc_skip_chroma_above(16, 32, 1, 1)); // 4:4:4 (ss 0,0): the plane block is the luma block itself. assert!(obmc_skip_chroma_above(4, 4, 0, 0)); assert!(obmc_skip_chroma_above(8, 4, 0, 0)); assert!(obmc_skip_chroma_above(4, 8, 0, 0)); assert!(!obmc_skip_chroma_above(8, 8, 0, 0)); assert!(!obmc_skip_chroma_above(16, 8, 0, 0)); assert!(!obmc_skip_chroma_above(8, 16, 0, 0)); } } /// 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, /// The chroma PREDICTION buffer's own stride -- `chroma_stride`, the PLANE /// BLOCK's per-axis width, NOT the enclosing square `chroma_side`. At /// 4:2:2 that buffer is `(side/2, side)` (lane-av1-422blockhalf), and /// striding it with `chroma_side` put row `r` at `r*side`: a 32x16 luma /// strip's left-pass chroma blend wrote row 15 at index 15*32 = 480 of a /// 256-sample `16 x 16` buffer -- the out-of-bounds panic in /// `obmc_blend_h` the pinned 4:2:2 rotzoom stream opened. Every other /// consumer of `pred_u`/`pred_v` in this block already strides with /// `chroma_stride`; at 4:2:0 and 4:4:4 the two are equal. chroma_stride: 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_stride, 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; : are chroma-plane pixels, the oracle's own dump // window) 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; // lane-av1ecmcb: the window is the CHROMA plane's own write region -- // the oracle's EC_MCB spans are plane pixels, and at 4:4:4 (ss 0/0) // the chroma block is full-size, so nothing halves. The old // `write_w / 2` was a 4:2:0-era assumption that quartered the window // (and the dumps below) at ss 0/0. let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx)); if x >= cpx && x < cpx + cw && y >= cpy && y < cpy + ch && (fr < 0 || fr == idx) { Some((x, y, idx)) } else { None } }); if let Some((_, _, idx)) = ec_mcb { let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx)); eprintln!("OUR_MCB pre f={idx} cpx={cpx} cpy={cpy} cw={cw} ch={ch}"); for r in 0..ch { let row: Vec = (0..cw).map(|c| pred_u[r * chroma_stride + 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 overlap (`build_obmc_inter_pred_above`: // `overlap >> ss_y`) -- the PLANE's own subsampling shift, 0 at // 4:4:4 (lane-av1-llpred: the old `/2` hardcoded the 4:2:0 half // and half-blended every 4:4:4 OBMC block's chroma). let (cbw, cbh, cox) = ( bw >> ss_x(fctx), overlap_above >> ss_y(fctx), ox >> ss_x(fctx), ); let cw = cbw.min((write_w >> ss_x(fctx)) - 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_stride, 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_stride, 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 >> ss_x(fctx), bh >> ss_y(fctx), oy >> ss_y(fctx), ); 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 >> ss_y(fctx)) - coy); obmc_blend_h(pred_u, chroma_stride, 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_stride, 0, coy, cbw, ch, &tmp_v); } if let Some((_, _, idx)) = ec_mcb { let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx)); for r in 0..ch { let row: Vec = (0..cw).map(|c| pred_u[r * chroma_stride + 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)) } /// The luma transform leaf a chroma unit inherits its `tx_type` from /// (libaom `av1_get_tx_type`, `blockd.h:1287-1297`): an INTER block's chroma /// unit never codes a `tx_type` symbol of its own, so the type is read out /// of `xd->tx_type_map` at the chroma unit's own position scaled back to luma /// (`blk_row << ss_y`, `blk_col << ss_x`). `leaves` is the block's coded /// transform tree in decode order, `(row, col, tw, th, tx_type)` with /// `(row, col)` in MI relative to the block and `(tw, th)` in PIXELS; /// `rel_mi` is the chroma unit's own luma-relative top-left MI cell. One /// function serves the 128x128 mu-chunk tail and the 64x64 arms alike -- the /// lookup is the same rule, so a second inline copy would be a second /// convention. /// /// A leaf that coded nothing resolves to `DctDct` here exactly as libaom's /// `decodetxb.c:199-203` stamps `DCT_DCT` into that leaf's map cell on the /// `all_zero` path: a chroma unit over a SKIPPED luma quadrant must NOT /// inherit the block-level (top-left leaf) type. fn covering_leaf_tx_type( leaves: &[(usize, usize, usize, usize, TxType)], rel_mi: (usize, usize), ) -> Option { leaves .iter() .copied() // leaf (row, col) are mi but (tw, th) are px (the rect leaf path // divides by MI too) .find(|&(lr, lc, lw, lh, _)| { lr <= rel_mi.0 && rel_mi.0 < lr + lh / MI && lc <= rel_mi.1 && rel_mi.1 < lc + lw / MI }) .map(|(_, _, _, _, t)| t) } thread_local! { /// lane-av1444chr: how many chroma units resolved their `tx_type` from the /// luma leaf covering their OWN quadrant instead of the block-level /// (`first_tx_type`) one -- the route this lane corrected. /// `CHROMA_SPLIT_TX_HITS` cannot attribute its bumps to it: every split /// chroma unit bumps that one. pub(crate) static CHROMA_QUAD_LEAF_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { /// Of those, how many resolved a type that DIFFERS from the block-level one /// -- the exact condition lane-av1444chr measured wrong: over a luma leaf /// that coded nothing the map cell is `DCT_DCT` while the top-left leaf's /// is `IDTX`. A gate proving the corrected route fired is NOT enough on /// its own (a block whose four leaves agree changes zero pixels); this is /// the number that says the route changed an answer. pub(crate) static CHROMA_QUAD_LEAF_TX_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { /// lane-av1f9singleland: the SINGLE-REFERENCE copy of /// [`CHROMA_QUAD_LEAF_TX_HITS`], and the half of its /// [`CHROMA_QUAD_LEAF_TX_DIFF_HITS`] that belongs to that arm. /// /// Why a separate pair rather than trusting the shared counters: the /// shared ones are bumped from BOTH arms of the four-unit 4:4:4 chroma /// arm, so a green witness on them says nothing about which arm produced /// the hits. `decode_inter_block` has two textually parallel copies of /// that arm -- the compound prediction arm (the `build` closure) and the /// single-reference arm -- and a refactor can delete or revert either one /// while the other keeps the shared total non-zero. Measured on the pinned /// witness `fixtures/444_quad_leaf_tx_type.obu`: 96 units resolve through /// the covering leaf, and 88 of them are the single-reference arm's, so /// the shared counter is 92% single-reference and the compound arm alone /// would be a 4-unit sample of the route it appears to witness. pub(crate) static CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { /// Of [`CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS`], how many resolved a type /// that DIFFERS from the block-level one. This is the arm's own non-vacuity /// bar: a route count alone stays green through a no-op resolve, because /// on a block whose four luma leaves all agree the per-quadrant value and /// the block-level one are the same answer. Mutating only the /// single-reference arm's `Some(cu_tx_type)` back to `Some(luma_tx_type)` /// turns the witness red with 777 bytes differing in decode-order frame 1. pub(crate) static CHROMA_QUAD_LEAF_TX_SINGLEREF_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS`]: single-reference-arm chroma units /// that took their type from the covering luma leaf. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_quad_leaf_tx_singleref_hits() -> usize { CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS.with(std::cell::Cell::get) } /// [`CHROMA_QUAD_LEAF_TX_SINGLEREF_DIFF_HITS`]: of those, the units whose /// covering leaf's type differs from the block-level one. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_quad_leaf_tx_singleref_diff_hits() -> usize { CHROMA_QUAD_LEAF_TX_SINGLEREF_DIFF_HITS.with(std::cell::Cell::get) } /// [`CHROMA_QUAD_LEAF_TX_HITS`]: chroma units that took their type from the /// covering luma leaf. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_quad_leaf_tx_hits() -> usize { CHROMA_QUAD_LEAF_TX_HITS.with(std::cell::Cell::get) } /// [`CHROMA_QUAD_LEAF_TX_DIFF_HITS`]: chroma units whose covering leaf's type /// differs from the block-level one. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_quad_leaf_tx_diff_hits() -> usize { CHROMA_QUAD_LEAF_TX_DIFF_HITS.with(std::cell::Cell::get) } thread_local! { /// lane-av1chrtx: chroma units of a RECT inter block /// ([`read_inter_rect_chroma`], the sibling of the 4:4:4 four-unit arms) /// that resolved their `tx_type` from the luma leaf covering their OWN /// quadrant instead of the block-level one. A SEPARATE counter from /// [`CHROMA_QUAD_LEAF_TX_HITS`] on purpose: that one gates a 4:2:0 control /// that must stay at exactly 0, and this route IS reachable at 4:2:0, so /// sharing the counter would destroy that control's meaning. pub(crate) static CHROMA_RECT_LEAF_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { /// Of those, how many resolved a type that DIFFERS from the block-level /// one -- the condition that changes pixels. A route counter alone fires /// on every multi-unit rect chroma read, including the blocks whose /// leaves all agree (the exact shape a no-op fix looks green on). pub(crate) static CHROMA_RECT_LEAF_TX_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`CHROMA_RECT_LEAF_TX_HITS`]: rect chroma units that took their type from /// the covering luma leaf. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_rect_leaf_tx_hits() -> usize { CHROMA_RECT_LEAF_TX_HITS.with(std::cell::Cell::get) } /// [`CHROMA_RECT_LEAF_TX_DIFF_HITS`]: of those, the units whose covering /// leaf's type differs from the block-level one. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_rect_leaf_tx_diff_hits() -> usize { CHROMA_RECT_LEAF_TX_DIFF_HITS.with(std::cell::Cell::get) } thread_local! { /// lane-av1ichromatx: [`read_inter_rect_chroma`] units that fell through /// `covering_leaf_tx_type` to the BLOCK-level `luma_tx_type`, and of those /// the ones whose chroma plane is MULTI-unit (`nx*ny > 1`) -- the only /// shape where two units of one plane can disagree, i.e. where a /// block-level value could actually mistype a unit. /// /// Why this needs its own number: `CHROMA_RECT_LEAF_TX_HITS` counts the /// units that took the covering leaf, so it says nothing about the units /// that did NOT -- and the fallback is the only remaining place in /// `decode_inter_block` where a chroma unit is handed a block-level type /// on a split plane. pub(crate) static CHROMA_RECT_BLOCK_TX_FALLBACK: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { /// Of [`CHROMA_RECT_BLOCK_TX_FALLBACK`], how many were on a multi-unit /// chroma plane -- the non-vacuity bar for the assertion at that site. pub(crate) static CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`CHROMA_RECT_BLOCK_TX_FALLBACK`]: rect chroma units handed the block-level /// type because no luma leaf covered their own MI cell. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_rect_block_tx_fallback() -> usize { CHROMA_RECT_BLOCK_TX_FALLBACK.with(std::cell::Cell::get) } /// [`CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI`]: of those, the ones whose chroma /// plane had more than one unit. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn chroma_rect_block_tx_fallback_multi() -> usize { CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI.with(std::cell::Cell::get) } 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<()> { // Round 27: the per-read trace is the only instrument that reaches the inter // path (the coefficient rungs stop well before the frame-3 divergence), // so publish the phase and the block's mi for every read it makes. crate::msac::SymbolDecoder::set_symr_phase("inter"); crate::msac::SymbolDecoder::set_symr_mi(at.0 as i64, at.1 as i64); // 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 >> ss_x(fctx), s.pair_mi.0 * MI >> ss_y(fctx), ), _ => (px >> ss_x(fctx), py >> ss_y(fctx)), }; // lane-av1-422j: the chroma prediction/residual buffers are // `chroma_side`-square and every consumer indexes them // `row * chroma_side + col` over the WRITE rect (`write_chroma_w` x // `write_chroma_h`). At ss (1,0) that rect is `side/2 x side` (an 8x16 // strip's 4x16 chroma), so a `side >> ss_x` square is shorter than // `row * chroma_side + write_chroma_w` on rows `>= side/2` -- frame 1's // skipped VERT_B strip read `prediction[64..68]` out of the 64-sample // buffer (reconstruct_mc_rect panic, decode.rs:29094). The enclosing // square of the chroma rect is the max: unchanged at 4:2:0 (side/2) and // 4:4:4 (side), so only 4:2:2 changes shape. let chroma_side = (side >> ss_x(fctx)).max(side >> ss_y(fctx)); let (write_chroma_w, write_chroma_h) = match strip_chroma { Some(s) if s.has_chroma => { // 4:2:0: the PAIR's 8x4 / 4x8. 4:4:4: the strip's own 16x4 / // 4x16 (lane-av1-444; no pair at ss 0/0). // // lane-av1422lpf site 4: the VERT arm's third shape. A // `PARTITION_VERT_4` strip is 4x16 luma and pairs on COLUMNS // while `ss_x == 1` (`is_chroma_reference` on `mi_col` parity, // av1_common_int.h:1454), so the pair is 8x16 luma -- and 4:2:2 // subsamples X ONLY (`subsampling_x = 1, subsampling_y = 0`, // spec 5.5.2's `color_config`), which leaves the pair's chroma // plane block at 8>>1 x 16>>0 = **4x16**, twice as tall as the // 4:2:0 pair's 4x8. The old `else` handed 4:2:2 the 4:2:0 shape, // halving `write_chroma_h` for the WHOLE of `decode_inter_block` // at ss (1,0) -- `chroma_stride`/`chroma_buf_h` at 40017 and so // every prediction buffer, every grid and every mu-chunk replay // below. Measured on `W_intrabc.obu` frame 1: a 4x16 vert strip // got `chroma_stride = 4`, `chroma_buf_h = 8`, a 32-sample grid, // and the lossless TX_4x4 replay's last unit row read index 64 of // it (`range end index 36 out of range for slice of length 32` // at the composed-grid read). // // The HORZ arm needs no third shape at 4:2:2 and gets none: a // HORZ_4 strip pairs on ROWS only while `ss_y == 1`, and 4:2:2 // has `ss_y == 0`, so each 16x4 strip is its own chroma reference // and its own 8x4 chroma block -- the number `(8, 4)` already // returns. At 4:2:0 (`ss_x == ss_y == 1`) the pair halves on both // axes and at 4:4:4 there is no pair at all, so both of those // arms are untouched by this line. if ss_x(fctx) == 0 && ss_y(fctx) == 0 { if s.horz { (16, 4) } else { (4, 16) } } else if s.horz { (8, 4) } else if ss_y(fctx) == 0 { (4, 16) } else { (4, 8) } } _ => (write_w >> ss_x(fctx), write_h >> ss_y(fctx)), }; // lane-av1-422blockhalf: the chroma PREDICTION buffers take the PLANE // BLOCK's own per-axis shape at 4:2:2 -- (side/2, side) -- instead of the // enclosing square `chroma_side` the pre-port model indexed, and the // masked-compound blend reads its luma mask through the plane's real // subsampling shifts (aom_dsp/blend-a64-mask.c's four branches; the // stop-note this lane owns). Every consumer below strides with // `chroma_stride`. At 4:2:0 and 4:4:4 both values reduce to the square // `chroma_side` verbatim, so only 4:2:2 changes shape. let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0; let (chroma_stride, chroma_buf_h) = if chroma_422 { (write_chroma_w, write_chroma_h) } else { (chroma_side, chroma_side) }; let (chroma_set, chroma_tx, scan_chroma) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 && strip_chroma.is_none() { let tx = if side >= 64 { 32 } else { side }; let set = match tx { 32 => TxbSet::Chroma32, 16 => TxbSet::Chroma16, 8 => TxbSet::Chroma8, _ => TxbSet::Chroma4, }; (set, tx, scan_luma) } else { (chroma_set, chroma_tx, scan_chroma) }; // 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, (write_w / MI, write_h / MI), 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); // The rect_tu arms' chroma helper returns its TRUE per-unit coefficient // context stamps (see `read_inter_rect_chroma`); they are appended to // `mu_chroma_units` below so the block tail replays them after the // whole-block record. `mu_chroma`'s own square-mu derivation cannot // express a non-square strip's units. let mut rect_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); 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, force_integer_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 // 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; // lane-av1422warp r33 (reviewer P3): the top-half census is // placed HERE, after `is_global_mv0`/`is_global_mv1`, so it // counts the same blocks libaom's `is_global_mv_block` does -- // mode GLOBAL_GLOBALMV AND block >= 8x8 AND that slot's own gm // model > TRANSLATION. An earlier placement tested the model term // alone, which counts blocks that are not global-mv blocks at // all, so its number was an upper bound dressed up as an // engagement figure. if mi_row < mi_rows as usize / 2 { if is_globalmv { TOP_HALF_COMPOUND_HITS.with(|c| c.set(c.get() + 1)); } if is_global_mv0 || is_global_mv1 { TOP_HALF_WARP_HITS.with(|c| c.set(c.get() + 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); // lane-av112bitw: the 12-bit refusal that stood here is // LIFTED with the compound-warp witness: the rotating- // mandelbrot 12-bit recipe refused exactly here pre-lift and // now decodes byte-exact vs ffmpeg through the same bumped // `warp::warp_round_0` shifts // (`a_real_compound_global_warp_12bit_stream_decodes_pixel_exact`). } // 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) { crate::msac::SymbolDecoder::set_symr_cdf("comp_group_idx"); 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], ); crate::msac::SymbolDecoder::set_symr_cdf("compound_idx"); 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 { // lane-av1distwtd: `idx == 0` is the // distance-weighted arm -- the only branch whose // weights are NOT the constant (8, 8) split. hit!(DIST_WTD_COMP_HITS); 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, 0), mv_to_q4(py, mv0.0, 0), scale0, side, side, write_w, write_h, h_filter, v_filter, &mut inter0_y, fctx, ); // 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, 0), mv_to_q4(py, mv1.0, 0), scale1, side, side, write_w, write_h, h_filter, v_filter, &mut inter1_y, fctx, ); // 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, 0, 0, &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_stride * chroma_buf_h]; mc::predict_compound_intermediate_kern( &pu0.data, pu0.width, pu0.true_width, pu0.true_height, mv_to_q4(cpx, mv0.1, ss_x(fctx)), mv_to_q4(cpy, mv0.0, ss_y(fctx)), scale0, chroma_stride, chroma_buf_h, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut inter0_u, fctx, ); // `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_stride as i32, chroma_buf_h as i32, chroma_stride as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, fctx, ); } } let mut inter1_u = vec![0i32; chroma_stride * chroma_buf_h]; mc::predict_compound_intermediate_kern( &pu1.data, pu1.width, pu1.true_width, pu1.true_height, mv_to_q4(cpx, mv1.1, ss_x(fctx)), mv_to_q4(cpy, mv1.0, ss_y(fctx)), scale1, chroma_stride, chroma_buf_h, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut inter1_u, fctx, ); // `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_stride as i32, chroma_buf_h as i32, chroma_stride as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, fctx, ); } } let mut pred_u = refill(std::mem::take(&mut out[1]), chroma_stride * chroma_buf_h); if let Some(mask_y) = mask_y { // lane-av1-422blockhalf: the blend walks this plane's own // (chroma_stride x chroma_buf_h) rect through the plane's // real subsampling shifts -- the mask read is aom_dsp/ // blend-a64-mask.c's `(1, 0)` branch at 4:2:2, the direct // luma sample at 4:2:0/4:4:4. mc::blend_masked_compound( &inter0_u, &inter1_u, mask_y, side, chroma_stride, chroma_buf_h, ss_x(fctx), ss_y(fctx), &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_stride * chroma_buf_h]; mc::predict_compound_intermediate_kern( &pv0.data, pv0.width, pv0.true_width, pv0.true_height, mv_to_q4(cpx, mv0.1, ss_x(fctx)), mv_to_q4(cpy, mv0.0, ss_y(fctx)), scale0, chroma_stride, chroma_buf_h, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut inter0_v, fctx, ); // `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_stride as i32, chroma_buf_h as i32, chroma_stride as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, fctx, ); } } let mut inter1_v = vec![0i32; chroma_stride * chroma_buf_h]; mc::predict_compound_intermediate_kern( &pv1.data, pv1.width, pv1.true_width, pv1.true_height, mv_to_q4(cpx, mv1.1, ss_x(fctx)), mv_to_q4(cpy, mv1.0, ss_y(fctx)), scale1, chroma_stride, chroma_buf_h, write_chroma_w, write_chroma_h, h_filter, v_filter, &mut inter1_v, fctx, ); // `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_stride as i32, chroma_buf_h as i32, chroma_stride as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, fctx, ); } } let mut pred_v = refill(std::mem::take(&mut out[2]), chroma_stride * chroma_buf_h); if let Some(mask_y) = mask_y { // lane-av1-422blockhalf: the blend walks this plane's own // (chroma_stride x chroma_buf_h) rect through the plane's // real subsampling shifts -- the mask read is aom_dsp/ // blend-a64-mask.c's `(1, 0)` branch at 4:2:2, the direct // luma sample at 4:2:0/4:4:4. mc::blend_masked_compound( &inter0_v, &inter1_v, mask_y, side, chroma_stride, chroma_buf_h, ss_x(fctx), ss_y(fctx), &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_stride, off: 0, }, Pred::Cur { plane: 2, stride: chroma_stride, 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_stride), Pred::Inline(&pred_v, chroma_stride), ) }; 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_stride, write_chroma_w, write_chroma_h, su, &ZERO_RESIDUAL[..chroma_stride * chroma_buf_h], fctx, ); push_mc_rect( 2, cpx, cpy, chroma_stride, write_chroma_w, write_chroma_h, sv, &ZERO_RESIDUAL[..chroma_stride * chroma_buf_h], fctx, ); luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(chroma_stride * chroma_buf_h); v_grid = Grid::Zero(chroma_stride * chroma_buf_h); } 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 { // lane-av1422mi24: at ss (1,0) the rect strip's chroma // above span is `write_w >> 1` chroma cells spread over // `write_w` luma mi columns -- the per-mi gather counts // every chroma column's whole-unit dc sign twice (the // t422 frame-1 mi(26,60) strip's U dc_sign read one row // high). Luma keeps the per-mi extents; chroma takes // [`Neighbours::around_mi_422_chroma`]'s every-second- // above-cell sampling. let mut a = neighbours.around_mi_rect(at_mi, write_w, write_h); if ss_x(fctx) == 1 && ss_y(fctx) == 0 { let c = neighbours.around_mi_422_chroma(at_mi, write_w, write_h); a[1] = c[1]; a[2] = c[2]; } a } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 { // lane-av1422mi24: at ss (1,0) a square block's chroma // plane block is (side/2, side) -- `side` chroma 4-px // above cells spread over `side` luma mi columns, one // chroma column per PAIR of luma mi cells. The plain // per-mi gather samples every second chroma column, and // its dc-vote sum lands one sign row off (t422 frame 1, // mi(24,56) U dc_sign: ours read dc_sign_cdf[0] where // the oracle read row 1). Luma keeps the per-mi gather // verbatim; only the two chroma planes take // [`Neighbours::around_mi_422_chroma`]'s every-second- // above-cell sampling (the same measured rule the strip // and chunk arms already run). let mut a = neighbours.around_mi(at, side); let c = neighbours.around_mi_422_chroma(at, write_w, write_h); a[1] = c[1]; a[2] = c[2]; a } else { neighbours.around_mi(at, side) }; let luma_tx_type; // lane-sb128c r1: a 128x128 inter block's chroma is read // INSIDE the luma leaf loop (each 64x64 mu chunk's own units: // one per chunk at 4:2:0, FOUR TX_32X32 at ss 0/0); these // collect them for the block-level neighbour write-back. let mut u_units: Vec = Vec::new(); let mut v_units: Vec = Vec::new(); // lane-av1-444-128: every luma leaf's coded tx_type, so the // chunk tail's chroma units can each inherit the type of the // leaf covering their own quadrant (`av1_get_tx_type`, // blockd.h:1291, scales the CHROMA 4x4 position back to luma). let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = 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; // lane-av1h5: libaom's `decode_token_recon_block` walks // 64x64 "mu" chunks with the PLANE loop inside, so at 128 // the token order is CHUNK-major; the transform tree hands // us a BLOCK-wide raster whose chunk members are not // contiguous. Below 128 a block IS one chunk. let (order, _mu_reordered) = mu_chunk_order(leaves, side); for (pos, &idx) in order.iter().enumerate() { let (row, col, tw, th) = leaves[idx]; 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; } // lane-av1444chr: EVERY luma leaf's coded type, at // every block size (see the single-reference twin // below) -- the chroma units resolve their own // quadrant's leaf, and a leaf that coded NOTHING is // `DctDct` exactly as libaom's `decodetxb.c:199-203` // stamps `DCT_DCT` into that leaf's map cell. leaf_tx_types.push((row, col, tw, th, 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 = pos + 1 == order.len() || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 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. The mu walk // (`decode_token_recon_block`, decodeframe.c) // then enumerates, per plane, EVERY TX_32X32 // unit of the chunk's chroma in raster order: // at ss 0/0 the chunk's chroma is 64x64 and // that is FOUR units; at 4:2:0 it is 32x32 // and the loop degenerates to the one unit // this arm has always coded. `chroma_side` // already carries the subsampling. let cu_tx = 32usize; // lane-av1-422bigblock: a 64x64 mu chunk's // chroma plane block is PER-AXIS // (64 >> ss_x) x (64 >> ss_y) -- 32x64 at // ss (1,0), i.e. TWO stacked TX_32X32 units // per plane (`av1_get_max_uv_txsize` caps the // unit at 32 on each axis). The old square-cut // model walked `chroma_side`-square chunks: // twice the units the oracle codes at 4:2:2, // prediction windows indexed at the square // `chroma_side` instead of the prediction // buffer's own `chroma_stride`, and chunk // columns at 64.. of a 64-wide chroma plane. let chunk_chroma_w = (64usize) >> ss_x(fctx); let chunk_chroma_h = (64usize) >> ss_y(fctx); let units_w = chunk_chroma_w / cu_tx; let units_h = chunk_chroma_h / cu_tx; // The unit's own footprint on the LUMA mi // grid, per axis (32 << ss) px: 64x64 (16x16 // mi) at 4:2:0, 32x32 (8x8 mi) at 4:4:4, // 64x32 (16x8 mi) at 4:2:2. `around_mi_rect` // reads and // `record_mi_chroma` stamps span exactly the // unit's own cells -- `get_txb_ctx` reads the // 8 context cells of the TX_32X32 itself, and // `av1_set_entropy_contexts` memsets the same // 8, so the unit over never sees this unit's // state and the unit below always does. let unit_luma_w = cu_tx << ss_x(fctx); let unit_luma_h = cu_tx << ss_y(fctx); let cu_scan = default_scan(cu_tx); if lossless(fctx) { // lane-lossless2: TX_4X4 units over this // chunk's chroma, not one TX_32X32 unit. read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, su, sv, at_mi, (cpx, cpy), (cc * chunk_chroma_w, cr * chunk_chroma_h), (chunk_chroma_w, chunk_chroma_h), (write_chroma_w, write_chroma_h), // lane-av1422lpf site 5: the stride // the walk indexes `su`/`sv` at is the // PREDICTION BUFFER's own // `chroma_stride` -- the same number // `su`/`sv` were built at, and the one // the composed `u_units`/`v_units` // grid is sized and written at (site // 1's `stride * blk_h`). `chroma_side` // is the ENCLOSING SQUARE // (`max(side >> ss_x, side >> ss_y)`) // and at 4:2:2 it is the LUMA side: a // 128x128 block's chroma plane block is // 64x128, so the walk addressed // `oy * 128 + ox` on a 64-wide, 8192- // sample buffer and the last unit row // ran off the end // (`offset 8192 .. 8580 of 8192`, // X_intrabc_tiled frame 1, at // `push_mc_rect_tx`). // // At 4:2:0 `chroma_stride == // chroma_side == side >> 1` and at // 4:4:4 both are `side`, so this // argument is the same number on every // shape this decoder admits except // 4:2:2. chroma_stride, mode_for_tx, base_q_idx, &mut u_units, &mut v_units, fctx, )?; mu_chroma = true; continue; } for plane_idx in 1..3 { let (src, buf) = if plane_idx == 1 { (su, &mut *u) } else { (sv, &mut *v) }; // Plane-major per chunk (libaom's plane // loop is outermost inside the mu walk); // within a plane the units walk raster. for ur in 0..units_h { for uc in 0..units_w { let unit_mi = ( at_mi.0 + cr * 16 + ur * (unit_luma_h / MI), at_mi.1 + cc * 16 + uc * (unit_luma_w / MI), ); // Per unit, AFTER the earlier // units' stamps: this unit's // coefficient context must see // them. let cu_around = neighbours.around_mi_rect( unit_mi, unit_luma_w, unit_luma_h, ); let (cu_x, cu_y) = ( cpx + cc * chunk_chroma_w + uc * cu_tx, cpy + cr * chunk_chroma_h + ur * cu_tx, ); // `av1_get_tx_type` (blockd.h: // 1291): an inter block's chroma // unit never codes a tx_type; it // inherits the coded type of the // luma leaf covering its own // quadrant (all of this chunk's // leaves are read by now). let unit_rel_mi = (unit_mi.0 - at_mi.0, unit_mi.1 - at_mi.1); let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi); // The prediction buffer is // `chroma_stride`-strided (the // plane block's own width at // 4:2:2), not the square // `chroma_side`. let cu_pred = src.offset( (cr * chunk_chroma_h + ur * cu_tx) * chroma_stride + cc * chunk_chroma_w + uc * 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(covering.unwrap_or(TxType::DctDct)), Some(3), fctx, )? .0; // Immediately, so the NEXT unit // reads this one's coefficient // context. neighbours.record_mi_chroma( unit_mi, unit_luma_w, unit_luma_h, 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 { // The ASSEMBLED grid stays at // the square `chroma_side` // stride the block tail's // `mu_chroma_units` re-stamp // indexes; the unit's true // per-axis position is what // changes. let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * chroma_side + cc * chunk_chroma_w + uc * cu_tx; dst[start..start + cu_tx].copy_from_slice( &cu_grid[rr * cu_tx..][..cu_tx], ); } } } } } } } // The block-level `luma_tx_type` stays the first // (top-left) luma unit's coded type; the PER-UNIT chroma // inheritance in the chunk tail above resolves each unit's // own covering leaf instead (`av1_get_tx_type`, // blockd.h:1291). 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_stride * chroma_buf_h) } else { Grid::Own(std::mem::take(&mut u_units)) }; v_grid = if v_units.is_empty() { Grid::Zero(chroma_stride * chroma_buf_h) } else { Grid::Own(std::mem::take(&mut v_units)) }; } else if lossless(fctx) { // lane-lossless2: TX_4X4 chroma units, plane-major // (libaom `read_tx_size` + `decode_token_recon_block`). let (mut uo, mut vo) = (Vec::new(), Vec::new()); read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, su, sv, at_mi, (cpx, cpy), (0, 0), (write_chroma_w, write_chroma_h), (write_chroma_w, write_chroma_h), chroma_stride, mode_for_tx, base_q_idx, &mut uo, &mut vo, fctx, )?; let zero = chroma_side * chroma_side; u_grid = if uo.is_empty() { Grid::Zero(zero) } else { Grid::Own(uo) }; v_grid = if vo.is_empty() { Grid::Zero(zero) } else { Grid::Own(vo) }; // Every unit stamped its own neighbour context above; the // whole-block record must not overwrite them with the // assembled grid (class `override-slot-on-one-arm`). mu_chroma = true; } else if rect_tu || (write_chroma_w, write_chroma_h) != (chroma_side, chroma_side) { // One chroma read for the whole strip at 4:2:0, two // 32-capped units at 4:4:4 -- see the helper. // lane-av1-422j: a 4:2:2 square block's chroma plane is the // (side/2 x side) rect (a 32x32 block's 16x32), never // `chroma_side`-square -- the square read below would pair // a `chroma_side`-square unit with the 4:2:0 unit scan // (one-coefficient-per-position assert in // inverse_transform_2d_typed_wh). The rect reader codes // the exact `av1_get_max_uv_txsize` unit (TX_16X32, // `rect_inter_chroma_set`'s tables). (u_grid, v_grid, rect_chroma_units) = read_inter_rect_chroma( dec, cdfs, neighbours, around, u, v, su, sv, at_mi, (cpx, cpy), (write_chroma_w, write_chroma_h), chroma_stride, mode_for_tx, &leaf_tx_types, luma_tx_type, fctx, )?; } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 && chroma_side > chroma_tx { // lane-av1-444: at ss 0/0 this block's chroma plane is // `chroma_side` square while `av1_get_max_uv_txsize` caps // the units at TX_32X32 -- each plane codes FOUR TX_32X32 // units, plane-major inside the block's one 64x64 mu chunk // (libaom `decode_token_recon_block`'s plane loop). Each // unit's `txb_skip_ctx` carries the +10 // `get_txb_ctx_general` offset (plane block larger than the // transform); our `txb_skip_chroma_32` holds those rows at // +3, so `luma_skip_ctx: Some(3)` (lane-sb128b r3's // convention, as the 128 mu path above). let cu_tx = chroma_tx; let mu_units_n = chroma_side / cu_tx; let mut u_acc: Vec = Vec::new(); let mut v_acc: Vec = Vec::new(); for plane_idx in 1..3 { let (src, buf, acc) = if plane_idx == 1 { (su, &mut *u, &mut u_acc) } else { (sv, &mut *v, &mut v_acc) }; for cr in 0..mu_units_n { for cc in 0..mu_units_n { let cu_mi = (rmi + cr * (cu_tx / MI), cmi + cc * (cu_tx / MI)); let cu_around = neighbours.around_mi(cu_mi, cu_tx); // Per-quadrant inheritance, as in the // single-reference twin: the covering luma // leaf's OWN coded type, `DctDct` where that // leaf coded nothing. let cu_rel_mi = (cr * (cu_tx / MI), cc * (cu_tx / MI)); let cu_tx_type = covering_leaf_tx_type(&leaf_tx_types, cu_rel_mi) .unwrap_or(luma_tx_type); if covering_leaf_tx_type(&leaf_tx_types, cu_rel_mi).is_some() { hit!(CHROMA_QUAD_LEAF_TX_HITS); if cu_tx_type != luma_tx_type { hit!(CHROMA_QUAD_LEAF_TX_DIFF_HITS); } } let cu_grid = read_inter_plane( dec, cdfs, chroma_set, &scan_chroma, plane_idx, cu_around[plane_idx], mode_for_tx, buf, cpx + cc * cu_tx, cpy + cr * cu_tx, cu_tx, base_q_idx, src.offset(cr * cu_tx * chroma_side + cc * cu_tx), Some(cu_tx_type), Some(3), fctx, )? .0; // Immediately, so the next unit's context sees // this one's coefficients. neighbours .record_mi_chroma(cu_mi, cu_tx, cu_tx, plane_idx, &cu_grid); hit!(CHROMA_SPLIT_TX_HITS); // lane-av1-444 c8: the unit's levels must ALSO // land in the block grid -- the block-tail mu // re-stamp slices the per-unit states back out // of it. This arm used to hand it a ZERO grid, // so the re-stamp (and `record_rect_mi`'s // whole-block write under it) painted the whole // block's chroma context cells 0 AFTER the // correct per-unit stamps above: the next block // read `txb_skip_ctx` base 0 where aom gathers // 1 (f52 mi(52,16) U all_zero, ctx 0 vs 8). let dst = mu_units(acc, 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]); } } } } mu_chroma = true; u_grid = Grid::Own(u_acc); v_grid = Grid::Own(v_acc); } 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, force_integer_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; if !not_new { crate::census::mode(0); } 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; if !not_zero { crate::census::mode(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; crate::census::mode(if nearest { 2 } else { 3 }); 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::msac::symtrace::dir().is_some() { crate::msac::symtrace::note(&format!( " MODE mi=({mi_row},{mi_col}) dbg={dbg_mode} mv={mv:?}" )); } 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); crate::msac::SymbolDecoder::set_symr_cdf("interintra"); 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 { crate::msac::SymbolDecoder::set_symr_cdf("motion_mode"); 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); } // lane-av1gwarp12: the ROTZOOM sibling -- the only // >TRANSLATION model vanilla aomenc can emit for a single-ref // global-motion block (encoder search pinned to ROTZOOM). if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Rotzoom { hit!(ROTZOOM_GM_WARP_HITS); } } // lane-av112bitw: a local `WARPED_CAUSAL` projection (set above) // or a global warp model both land here with `warp_params` set -- // the 12-bit refusal that used to stand here is LIFTED: warp.rs's // rounding is parameterised on the bumped `conv_params->round_0` // (`warp::warp_round_0`, 5 at 12 bits) and the six-frame 12-bit // warp stream decodes byte-exact vs ffmpeg // (`a_12bit_warped_motion_stream_decodes_pixel_exact`). 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, ss_x(fctx), ss_y(fctx), chroma_stride, 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_stride * chroma_buf_h); let mut pred_v = refill(std::mem::take(&mut out[2]), chroma_stride * chroma_buf_h); 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, 0), mv_to_q4(py, mv.0, 0), 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, ss_x(fctx)), mv_to_q4(cpy, mv.0, ss_y(fctx)), chroma_stride, chroma_buf_h, 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, ss_x(fctx)), mv_to_q4(cpy, mv.0, ss_y(fctx)), chroma_stride, chroma_buf_h, 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, 0), mv_to_q4(py, mv.0, 0), 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, ss_x(fctx)), mv_to_q4(cpy, mv.0, ss_y(fctx)), luma_scale, chroma_stride, chroma_buf_h, 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, ss_x(fctx)), mv_to_q4(cpy, mv.0, ss_y(fctx)), luma_scale, chroma_stride, chroma_buf_h, 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_stride as i32, chroma_buf_h as i32, chroma_stride as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, 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_stride as i32, chroma_buf_h as i32, chroma_stride as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, 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, 0, 0, ii, wedge_mask, &mut pred_y, fctx, ); interintra_blend( u, cpx, cpy, write_chroma_w, write_chroma_h, chroma_stride, ss_x(fctx), ss_y(fctx), ii, wedge_mask, &mut pred_u, fctx, ); interintra_blend( v, cpx, cpy, write_chroma_w, write_chroma_h, chroma_stride, ss_x(fctx), ss_y(fctx), 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, ss_x(fctx)), mv_to_q4(cpy, prev_mv.0, ss_y(fctx)), prev_scale, piece_w, piece_h, prev_h, prev_v, &mut piece, fctx, ); for row in 0..piece_h { dst[row * chroma_stride..row * chroma_stride + 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_stride, off: 0, }, Pred::Cur { plane: 2, stride: chroma_stride, 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_stride), Pred::Inline(&pred_v, chroma_stride), ) }; // 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_stride, write_chroma_w, write_chroma_h, su, &ZERO_RESIDUAL[..chroma_stride * chroma_buf_h], fctx, ); push_mc_rect( 2, cpx, cpy, chroma_stride, write_chroma_w, write_chroma_h, sv, &ZERO_RESIDUAL[..chroma_stride * chroma_buf_h], fctx, ); } luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(chroma_stride * chroma_buf_h); v_grid = Grid::Zero(chroma_stride * chroma_buf_h); } 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 { // lane-av1422mi24: same 4:2:2 rect-strip chroma gather // rule as the single-TU path above -- luma per-mi, // chroma every-second above cell. let mut a = neighbours.around_mi_rect(at_mi, write_w, write_h); if ss_x(fctx) == 1 && ss_y(fctx) == 0 { let c = neighbours.around_mi_422_chroma(at_mi, write_w, write_h); a[1] = c[1]; a[2] = c[2]; } a } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 { // lane-av1422mi24: same 4:2:2 square-block chroma gather // rule as the single-TU path above -- luma per-mi, chroma // every-second above cell. let mut a = neighbours.around_mi(at, side); let c = neighbours.around_mi_422_chroma(at, write_w, write_h); a[1] = c[1]; a[2] = c[2]; a } 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. // lane-av1422ctxgather: at 4:2:2 (ss 1,0) a HORZ strip is // its own chroma reference (`is_chroma_reference`'s // `!(subsampling_y)` row clause) -- pair_mi is the strip // itself and the context reads the strip's own 8x4, ONE // luma-mi row tall, with the 4:2:2 above sampling // ([`Neighbours::around_mi_422_chroma`]) -- and the same // reroute catches 4:2:2 VERT: its (8, 16) pair span's // above side covers one chroma column per two luma mi // columns, the identical double-count. // // lane-av1444rect (H1, MEASURED): the (16, 8) / (8, 16) pair // extent was reached at ss (0,0) too, where no pair exists. // At 4:4:4 `is_chroma_reference` (av1_common_int.h:1454) // reduces BOTH parity clauses to `!subsampling_y` / // `!subsampling_x`, so every block is its own chroma // reference: a HORZ_4 16x4 strip codes its OWN 16x4 chroma // and the setter above already gave it `pair_mi == at_mi`. // Its coefficient context is therefore the strip's own, // which is exactly the `around` gathered one screen above // as `around_mi_rect(at_mi, write_w, write_h)`. The pair // gather read one EXTRA luma mi row of LEFT chroma context // (`ph = 8` covers left[8] and left[9], a 4-px strip only // left[8]), so the U unit's `get_txb_ctx` saw a neighbour // libaom does not have and forked the arithmetic coder: the // 6441-byte 4:4:4 lossy cq-20 stream, frame 1, mi(8,16) // read our `txb_skip_ctx` 1 (0 above + 1 left) where the // oracle read offset-7 row 7 (ctx_base 0). let around_c = match strip_chroma { // lane-av1444rect: the arm `is_chroma_reference` makes the // ONLY correct choice at ss_x 0 -- no pair exists, the // extent is the strip's own. Counted so a 4:4:4 1:4-strip // gate can prove it exercised this route (a 4:2:0 stream // of the same content reads 0). Some(_) if ss_x(fctx) == 0 => { hit!(RECT4_INTER_OWN_CHROMA444_HITS); around } Some(s) if s.has_chroma => { let (pw, ph) = if s.horz { if ss_y(fctx) == 0 { (16, 4) } else { (16, 8) } } else { (8, 16) }; if ss_x(fctx) == 1 && ss_y(fctx) == 0 { neighbours.around_mi_422_chroma(s.pair_mi, pw, ph) } else { neighbours.around_mi_rect(s.pair_mi, pw, ph) } } _ => around, }; let luma_tx_type; // lane-sb128c r1: a 128x128 inter block's chroma is read // INSIDE the luma leaf loop (each 64x64 mu chunk's own units: // one per chunk at 4:2:0, FOUR TX_32X32 at ss 0/0); these // collect them for the block-level neighbour write-back. let mut u_units: Vec = Vec::new(); let mut v_units: Vec = Vec::new(); // lane-av1-444-128: every luma leaf's coded tx_type, so the // chunk tail's chroma units can each inherit the type of the // leaf covering their own quadrant (`av1_get_tx_type`, // blockd.h:1291, scales the CHROMA 4x4 position back to luma). let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = 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; // lane-av1h5: libaom's `decode_token_recon_block` walks the // block in 64x64 "mu" CHUNKS and codes EVERY PLANE of a // chunk before the next one starts, so at 128 the token // order is CHUNK-major. The transform tree hands us a // BLOCK-wide raster (32 mi across here), whose chunk // members are not contiguous: `leaves` 0..15 are chunk // (0,0) row 0, but chunk (0,0) rows 1..15 are leaves // 32..47, 64..79, ... Walking it as given closed the // "chunk" every 16 leaves and coded each chunk's chroma // sixteen times -- 64 chroma walks per 128 root where // libaom codes 4 (measured against aomdec's `EC_DBGCTX`: // 24576 chroma units per inter frame vs 1536). Below 128 a // block IS one chunk and the two orders coincide. let (order, _mu_reordered) = mu_chunk_order(leaves, side); for (pos, &idx) in order.iter().enumerate() { let (row, col, tw, th) = leaves[idx]; 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; } // lane-av1444chr: EVERY luma leaf's coded type, at // every block size -- the chroma units below resolve // their own quadrant's leaf, and at 64x64 that is // this very loop's leaves (`av1_get_tx_type`, // blockd.h:1287-1297, scales the CHROMA 4x4 position // back to luma). It used to be collected only for // `side > 64`, so the 64x64 four-unit arm below had // nothing to resolve from and handed all four units // the block-level (top-left leaf) type. A leaf that // coded NOTHING is `DctDct` here exactly as libaom's // `decodetxb.c:199-203` stamps `DCT_DCT` into that // leaf's map cell on the `all_zero` path. leaf_tx_types.push((row, col, tw, th, 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 = pos + 1 == order.len() || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 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. The mu walk // (`decode_token_recon_block`, decodeframe.c) // then enumerates, per plane, EVERY TX_32X32 // unit of the chunk's chroma in raster order: // at ss 0/0 the chunk's chroma is 64x64 and // that is FOUR units; at 4:2:0 it is 32x32 // and the loop degenerates to the one unit // this arm has always coded. `chroma_side` // already carries the subsampling. let cu_tx = 32usize; // lane-av1-422bigblock: a 64x64 mu chunk's // chroma plane block is PER-AXIS // (64 >> ss_x) x (64 >> ss_y) -- 32x64 at // ss (1,0), i.e. TWO stacked TX_32X32 units // per plane (`av1_get_max_uv_txsize` caps the // unit at 32 on each axis). The old square-cut // model walked `chroma_side`-square chunks: // twice the units the oracle codes at 4:2:2, // prediction windows indexed at the square // `chroma_side` instead of the prediction // buffer's own `chroma_stride`, and chunk // columns at 64.. of a 64-wide chroma plane. let chunk_chroma_w = (64usize) >> ss_x(fctx); let chunk_chroma_h = (64usize) >> ss_y(fctx); let units_w = chunk_chroma_w / cu_tx; let units_h = chunk_chroma_h / cu_tx; // The unit's own footprint on the LUMA mi // grid, per axis (32 << ss) px: 64x64 (16x16 // mi) at 4:2:0, 32x32 (8x8 mi) at 4:4:4, // 64x32 (16x8 mi) at 4:2:2. `around_mi_rect` // reads and // `record_mi_chroma` stamps span exactly the // unit's own cells -- `get_txb_ctx` reads the // 8 context cells of the TX_32X32 itself, and // `av1_set_entropy_contexts` memsets the same // 8, so the unit over never sees this unit's // state and the unit below always does. let unit_luma_w = cu_tx << ss_x(fctx); let unit_luma_h = cu_tx << ss_y(fctx); let cu_scan = default_scan(cu_tx); if lossless(fctx) { // lane-lossless2: TX_4X4 units over this // chunk's chroma, not one TX_32X32 unit. read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, su, sv, at_mi, (cpx, cpy), (cc * chunk_chroma_w, cr * chunk_chroma_h), (chunk_chroma_w, chunk_chroma_h), (write_chroma_w, write_chroma_h), // lane-av1422lpf site 5 (the compound // twin of the single-reference fix at // 41572): the prediction buffer's own // `chroma_stride`, never the enclosing // square `chroma_side`. Identical // number at 4:2:0 and 4:4:4. chroma_stride, mode_for_tx, base_q_idx, &mut u_units, &mut v_units, fctx, )?; mu_chroma = true; continue; } for plane_idx in 1..3 { let (src, buf) = if plane_idx == 1 { (su, &mut *u) } else { (sv, &mut *v) }; // Plane-major per chunk (libaom's plane // loop is outermost inside the mu walk); // within a plane the units walk raster. for ur in 0..units_h { for uc in 0..units_w { let unit_mi = ( at_mi.0 + cr * 16 + ur * (unit_luma_h / MI), at_mi.1 + cc * 16 + uc * (unit_luma_w / MI), ); // Per unit, AFTER the earlier // units' stamps: this unit's // coefficient context must see // them. let cu_around = neighbours.around_mi_rect( unit_mi, unit_luma_w, unit_luma_h, ); let (cu_x, cu_y) = ( cpx + cc * chunk_chroma_w + uc * cu_tx, cpy + cr * chunk_chroma_h + ur * cu_tx, ); // `av1_get_tx_type` (blockd.h: // 1291): an inter block's chroma // unit never codes a tx_type; it // inherits the coded type of the // luma leaf covering its own // quadrant (all of this chunk's // leaves are read by now). let unit_rel_mi = (unit_mi.0 - at_mi.0, unit_mi.1 - at_mi.1); let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi); // The prediction buffer is // `chroma_stride`-strided (the // plane block's own width at // 4:2:2), not the square // `chroma_side`. let cu_pred = src.offset( (cr * chunk_chroma_h + ur * cu_tx) * chroma_stride + cc * chunk_chroma_w + uc * 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(covering.unwrap_or(TxType::DctDct)), Some(3), fctx, )? .0; // Immediately, so the NEXT unit // reads this one's coefficient // context. neighbours.record_mi_chroma( unit_mi, unit_luma_w, unit_luma_h, 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 { // The ASSEMBLED grid stays at // the square `chroma_side` // stride the block tail's // `mu_chroma_units` re-stamp // indexes; the unit's true // per-axis position is what // changes. let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * chroma_side + cc * chunk_chroma_w + uc * cu_tx; dst[start..start + cu_tx].copy_from_slice( &cu_grid[rr * cu_tx..][..cu_tx], ); } } } } } } } // The block-level `luma_tx_type` stays the first // (top-left) luma unit's coded type; the PER-UNIT chroma // inheritance in the chunk tail above resolves each unit's // own covering leaf instead (`av1_get_tx_type`, // blockd.h:1291). 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_stride * chroma_buf_h); v_grid = Grid::Zero(chroma_stride * chroma_buf_h); } 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_stride * chroma_buf_h) } else { Grid::Own(std::mem::take(&mut u_units)) }; v_grid = if v_units.is_empty() { Grid::Zero(chroma_stride * chroma_buf_h) } else { Grid::Own(std::mem::take(&mut v_units)) }; } else if lossless(fctx) { // lane-lossless2: TX_4X4 chroma units, plane-major // (libaom `read_tx_size` + `decode_token_recon_block`). let (mut uo, mut vo) = (Vec::new(), Vec::new()); read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, su, sv, at_mi, (cpx, cpy), (0, 0), (write_chroma_w, write_chroma_h), (write_chroma_w, write_chroma_h), chroma_stride, mode_for_tx, base_q_idx, &mut uo, &mut vo, fctx, )?; let zero = chroma_side * chroma_side; u_grid = if uo.is_empty() { Grid::Zero(zero) } else { Grid::Own(uo) }; v_grid = if vo.is_empty() { Grid::Zero(zero) } else { Grid::Own(vo) }; // Every unit stamped its own neighbour context above; the // whole-block record must not overwrite them with the // assembled grid (class `override-slot-on-one-arm`). mu_chroma = true; } else if rect_tu || (write_chroma_w, write_chroma_h) != (chroma_side, chroma_side) { // One chroma read for the whole strip at 4:2:0, two // 32-capped units at 4:4:4 -- see the helper. // lane-av1-422j: same rule as the compound arm above -- a // 4:2:2 square block's chroma plane is the // (side/2 x side) rect, so the rect reader takes it // instead of pairing a `chroma_side`-square unit with the // 4:2:0 scan. (u_grid, v_grid, rect_chroma_units) = read_inter_rect_chroma( dec, cdfs, neighbours, around_c, u, v, su, sv, at_mi, (cpx, cpy), (write_chroma_w, write_chroma_h), chroma_stride, mode_for_tx, &leaf_tx_types, luma_tx_type, fctx, )?; } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 && chroma_side > chroma_tx { // lane-av1-444: at ss 0/0 this block's chroma plane is // `chroma_side` square while `av1_get_max_uv_txsize` caps // the units at TX_32X32 -- each plane codes FOUR TX_32X32 // units, plane-major inside the block's one 64x64 mu chunk // (libaom `decode_token_recon_block`'s plane loop). Each // unit's `txb_skip_ctx` carries the +10 // `get_txb_ctx_general` offset (plane block larger than the // transform); our `txb_skip_chroma_32` holds those rows at // +3, so `luma_skip_ctx: Some(3)` (lane-sb128b r3's // convention, as the 128 mu path above). let cu_tx = chroma_tx; let mu_units_n = chroma_side / cu_tx; let mut u_acc: Vec = Vec::new(); let mut v_acc: Vec = Vec::new(); for plane_idx in 1..3 { let (src, buf, acc) = if plane_idx == 1 { (su, &mut *u, &mut u_acc) } else { (sv, &mut *v, &mut v_acc) }; for cr in 0..mu_units_n { for cc in 0..mu_units_n { let cu_mi = (rmi + cr * (cu_tx / MI), cmi + cc * (cu_tx / MI)); let cu_around = neighbours.around_mi(cu_mi, cu_tx); // `av1_get_tx_type` (blockd.h:1287-1297): an // inter block's chroma unit never codes a // `tx_type`; it reads the map cell at its OWN // position scaled back to luma // (`blk_row << ss_y`, `blk_col << ss_x`), // which is the coded type of the luma leaf // covering this unit's top-left mi cell -- // `DctDct` when that leaf coded nothing // (`decodetxb.c:199-203`). The block-level // `luma_tx_type` is only the TOP-LEFT leaf's // type, so handing it to all four units // mistyped every unit sitting over a skipped // or differently-typed luma quadrant. let cu_rel_mi = (cr * (cu_tx / MI), cc * (cu_tx / MI)); let cu_tx_type = covering_leaf_tx_type(&leaf_tx_types, cu_rel_mi) .unwrap_or(luma_tx_type); if covering_leaf_tx_type(&leaf_tx_types, cu_rel_mi).is_some() { hit!(CHROMA_QUAD_LEAF_TX_HITS); hit!(CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS); // lane-av1f9singleland: this arm's own // non-vacuity number -- the shared // DIFFERS counter below cannot say which // arm changed an answer. if cu_tx_type != luma_tx_type { hit!(CHROMA_QUAD_LEAF_TX_DIFF_HITS); hit!(CHROMA_QUAD_LEAF_TX_SINGLEREF_DIFF_HITS); } } let cu_grid = read_inter_plane( dec, cdfs, chroma_set, &scan_chroma, plane_idx, cu_around[plane_idx], mode_for_tx, buf, cpx + cc * cu_tx, cpy + cr * cu_tx, cu_tx, base_q_idx, src.offset(cr * cu_tx * chroma_side + cc * cu_tx), Some(cu_tx_type), Some(3), fctx, )? .0; // Immediately, so the next unit's context sees // this one's coefficients. neighbours .record_mi_chroma(cu_mi, cu_tx, cu_tx, plane_idx, &cu_grid); hit!(CHROMA_SPLIT_TX_HITS); // lane-av1-444 c8: the unit's levels must ALSO // land in the block grid -- the block-tail mu // re-stamp slices the per-unit states back out // of it. This arm used to hand it a ZERO grid, // so the re-stamp (and `record_rect_mi`'s // whole-block write under it) painted the whole // block's chroma context cells 0 AFTER the // correct per-unit stamps above: the next block // read `txb_skip_ctx` base 0 where aom gathers // 1 (f52 mi(52,16) U all_zero, ctx 0 vs 8). let dst = mu_units(acc, 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]); } } } } mu_chroma = true; u_grid = Grid::Own(u_acc); v_grid = Grid::Own(v_acc); } 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(()); } crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); 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. // lane-av1mono: a monochrome block codes no chroma mode/CFL symbol // (libaom `decodemv.c:933`). let has_chroma = !mono(fctx); let cfl_allowed = has_chroma && cfl_allowed_px(write_w, write_h, fctx); if !cfl_allowed { hit!(NOCFL_UV_MODE_HITS); } let uv_mode = if !has_chroma { DC_PRED } else if cfl_allowed { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); 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, fctx); // `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 = has_chroma && 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, palette_onscreen(rmi, cmi, write_w, write_h, fctx), 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)` at the sequence's own // subsampling, floored at the 4-px transform -- the rect reader's // own copy; a hardcoded `/ 2` sized a 4:4:4 chroma map at 4:2:0 // and the full-size reconstruct panicked on it (lane-av1-444). let (cw, ch) = ( (write_w >> ss_x(fctx)).max(4), (write_h >> ss_y(fctx)).max(4), ); let on = palette_onscreen_uv( (write_w, write_h), palette_onscreen(rmi, cmi, write_w, write_h, fctx), (cw, ch), (ss_x(fctx), ss_y(fctx)), ); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, 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); // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]). let (order, _mu_reordered) = mu_chunk_order(leaves, side); for (pos, &idx) in order.iter().enumerate() { let (row, col, tx_px, _) = leaves[idx]; 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 = pos + 1 == order.len() || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk; if !done { continue; } let (cr, cc) = chunk; hit!(INTRA_128_IN_INTER_MU_CHROMA_HITS); // The unit's CHROMA size, its LUMA footprint, the // CHUNK's chroma extent and the unit's ORIGIN inside the // chunk are four different quantities; this arm had the // last three as one 4:2:0 literal and read ONE unit per // mu chunk at every subsampling. // // `cu_tx` is TX_32X32 at EVERY subsampling. // `av1_get_max_uv_txsize` (blockd.h:1371) is // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[ // get_plane_block_size(bsize, ss_x, ss_y)])`, and // `av1_get_adjusted_tx_size` (blockd.h:1361) takes NO // subsampling argument: it maps TX_64X64 / TX_64X32 / // TX_32X64 to TX_32X32 UNCONDITIONALLY, so even at ss (0,0) // (where `get_plane_block_size` returns BLOCK_128X128 and // the lookup entry is TX_64X64) the answer is TX_32X32. let cu_tx = 32usize; // The unit's own footprint on the LUMA grid, per axis // (`cu_tx << ss`): 64 luma px (16 mi) at 4:2:0, 32 luma px // (8 mi) at 4:4:4. This is the ss-aware form the repaired // siblings at decode.rs:17598 / 17685 use (`ox << // ss_x(fctx)`, never `ox * 2`), and it is the size // `around_mi` / `record_mi_chroma` want. let unit_luma_w = cu_tx << ss_x(fctx); let unit_luma_h = cu_tx << ss_y(fctx); // The CHUNK's own extent, per axis: a mu chunk is a // 64x64 LUMA region at every subsampling, so on the luma // grid this is a literal 64, and its CHROMA plane block is // `64 >> ss` square. At 4:2:0 that is 32x32 = the one unit // this arm always coded; at 4:4:4 it is 64x64 = FOUR // TX_32X32 units. Measured on the gate's own 4:4:4 stream // against the oracle's `EC_TRACE_COEFF`: every chroma read // of a 128x128 intra-in-inter root is `tx_size=3` // (TX_32X32), and each 64x64 mu chunk contributes FOUR per // plane at (row,col) (0,0) (0,8) (8,0) (8,8) -- never a // TX_64X64 chroma unit. let chunk_luma = 64usize; let chunk_chroma_w = chunk_luma >> ss_x(fctx); let chunk_chroma_h = chunk_luma >> ss_y(fctx); let units_w = chunk_chroma_w / cu_tx; let units_h = chunk_chroma_h / cu_tx; let cu_scan = default_scan(cu_tx); if lossless(fctx) { // lane-lossless2: TX_4x4 units over this chunk's // chroma, not TX_32X32 ones. read_intra_chroma_lossless( dec, cdfs, neighbours, u, v, at_mi, (px, py), (cpx, cpy), side, // lane-av1422lpf site 6 (the intra-in-inter twin of // site 5 at 41572): the plane block's own per-axis // shape and stride, never the enclosing square. // `palette_uv_bufs` is the decoded colour-index map // at `(write_w >> ss_x, write_h >> ss_y)` (44144), // i.e. per-axis already, and the lossless walk // windows it at this `stride` -- at 4:2:2 a // 16-wide square stride over an 8-wide map put the // third unit row at index 180 of 128 samples // (`palette_window`, decode.rs:2946; measured on // `Y_intrabc_10b.obu`). (chroma_stride, chroma_buf_h), (cc * chunk_chroma_w, cr * chunk_chroma_h), (chunk_chroma_w, chunk_chroma_h), chroma_stride, reach, (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, base_q_idx, &mut u_units, &mut v_units, fctx, )?; mu_chroma = true; continue; } // Plane-major per chunk (libaom's plane loop is outermost // inside the mu walk); within a plane the units walk raster. for plane_idx in 1..3 { let buf: &mut PlaneBuf<'static> = if plane_idx == 1 { &mut *u } else { &mut *v }; for ur in 0..units_h { for uc in 0..units_w { // The unit's own mi origin: the chunk's // (16x16 mi) plus the unit's offset inside it. let unit_mi = ( at_mi.0 + cr * 16 + ur * (unit_luma_h / MI), at_mi.1 + cc * 16 + uc * (unit_luma_w / MI), ); // The unit's own entropy-cell span, so the // NEXT unit of this chunk reads THIS one's // state and the next chunk reads the last. let cu_around = neighbours.around_mi(unit_mi, unit_luma_w); let (cu_x, cu_y) = ( cpx + cc * chunk_chroma_w + uc * cu_tx, cpy + cr * chunk_chroma_h + ur * cu_tx, ); let cu_reach = crate::decode::tu_reach( side, side, cc * chunk_luma + uc * unit_luma_w, cr * chunk_luma + ur * unit_luma_h, unit_luma_w, reach, px, py, y.width, y.height, fctx, ); 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 is larger than // the unit: `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 unit reads this // one's coefficient context. neighbours.record_mi_chroma( unit_mi, unit_luma_w, unit_luma_h, plane_idx, &cu_grid, ); hit!(CHROMA_SPLIT_TX_HITS); // lane-dpm1: the two INTER mu-chunk sites set // this and this INTRA-in-inter one did not, so // the whole-block chroma record below re-stamped // all four 32x32 units with the TOP-LEFT unit's // level and the next block read a txb_skip row // libaom never selects (class // `override-slot-on-one-arm`). mu_chroma = true; let dst = mu_units( if plane_idx == 1 { &mut u_units } else { &mut v_units }, chroma_side * chroma_side, ); // The ASSEMBLED grid stays at the square // `chroma_side` stride the block tail's // re-stamp indexes; the unit's true per-axis // position inside its chunk is what changes. for rr in 0..cu_tx { let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * chroma_side + cc * chunk_chroma_w + uc * cu_tx; dst[start..start + cu_tx] .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]); } } } } } } } // lane-av1-422k: the chroma PREDICTION shape is the plane block // (`side >> ss_x`, `side >> ss_y`) -- square at 4:2:0/4:4:4, a // (side/2, side) rect at 4:2:2. `chroma_side` (the 422j enclosing // square of that rect) is the right size for BOOKKEEPING buffers but // the wrong SHAPE to predict and reconstruct at: an intra-in-inter // block's chroma prediction indexes its CFL signal and residual // `row * chroma_w + col` over the plane block, and a 16x16 luma // block's 8x16 chroma CFL signal is 128 samples -- predicting at the // 16x16 square read `ac[128]` out of it (frame 1, px=192 py=96). let chroma_w = side >> ss_x(fctx); let chroma_h = side >> ss_y(fctx); 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_stride * chroma_buf_h) } else { Grid::Own(std::mem::take(&mut u_units)) }; v_grid = if v_units.is_empty() { Grid::Zero(chroma_stride * chroma_buf_h) } 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_unit( 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_unit( 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, ); luma_grid = Grid::Zero(side * side); u_grid = Grid::Zero(chroma_w * chroma_h); v_grid = Grid::Zero(chroma_w * chroma_h); } 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 lossless(fctx) { // lane-lossless2: the block's chroma plane is a raster of 4x4 // units, plane-major (`read_intra_chroma_lossless`). let (mut uo, mut vo) = (Vec::new(), Vec::new()); read_intra_chroma_lossless( dec, cdfs, neighbours, u, v, at_mi, (px, py), (cpx, cpy), side, // lane-av1422lpf site 6 (the whole-block twin of the mu // chunk fix at 44374): the plane block's own per-axis shape // and its own stride, never the enclosing square // `chroma_side`. At 4:2:0 and 4:4:4 all three are the same // number. (chroma_stride, chroma_buf_h), (0, 0), (chroma_stride, chroma_buf_h), chroma_stride, reach, (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, base_q_idx, &mut uo, &mut vo, fctx, )?; let zero = chroma_side * chroma_side; u_grid = if uo.is_empty() { Grid::Zero(zero) } else { Grid::Own(uo) }; v_grid = if vo.is_empty() { Grid::Zero(zero) } else { Grid::Own(vo) }; mu_chroma = true; } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 && chroma_side > chroma_tx { // lane-av1-rect128recon: at ss 0/0 the uv plane block of a // 64x64 intra block inside an inter frame is 64x64 while // `av1_get_max_uv_txsize` caps the unit at TX_32X32 -- FOUR // plane-major TX_32X32 units (libaom // `decode_token_recon_block`'s plane loop), each with its own // neighbour context and `get_txb_ctx`'s offset-10 rows (+3 on // the `txb_skip_chroma_32` table, lane-sb128b r3), each // stamped immediately so the next unit reads it. The old arm // read ONE whole-plane unit with the block-level context and // no offset: three quarters of the plane's residual was never // read, the unit's `txb_skip` came off the offset-7 row (444 // witness f2, right-half intra 64x64: U unit (0,0) ctx 0 // where aom reads 10), and the coded corner was even // dequantized at the TX_64X64 dqDenom. let mu_units_n = chroma_side / chroma_tx; let mut u_acc = vec![0i32; chroma_side * chroma_side]; let mut v_acc = vec![0i32; chroma_side * chroma_side]; for plane_idx in 1..=2 { let buf: &mut PlaneBuf<'static> = if plane_idx == 1 { &mut *u } else { &mut *v }; for cu_row in 0..mu_units_n { for cu_col in 0..mu_units_n { let cu_mi = ( at_mi.0 + cu_row * (chroma_tx / MI), at_mi.1 + cu_col * (chroma_tx / MI), ); let cu_around = neighbours.around_mi(cu_mi, chroma_tx); let cu_reach = crate::decode::tu_reach( side, side, cu_col * chroma_tx, cu_row * chroma_tx, chroma_tx, reach, px, py, y.width, y.height, fctx, ); let cu_grid = read_plane( dec, cdfs, chroma_set, scan_chroma, plane_idx, cu_around[plane_idx], mode, uv_predict_mode, angle_delta_uv, cu_reach, buf, cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx, chroma_tx, chroma_tx, base_q_idx, // CfL is capped at 32x32 (`is_cfl_allowed`), // so a block this size never carries alpha. None, None, Some(3), smooth_neighbor_uv, fctx, )?; // Immediately, so the NEXT unit reads this one's // coefficient context. neighbours .record_mi_chroma(cu_mi, chroma_tx, chroma_tx, plane_idx, &cu_grid); hit!(CHROMA_SPLIT_TX_HITS); let acc = if plane_idx == 1 { &mut u_acc } else { &mut v_acc }; for rr in 0..chroma_tx { let start = (cu_row * chroma_tx + rr) * chroma_side + cu_col * chroma_tx; acc[start..start + chroma_tx] .copy_from_slice(&cu_grid[rr * chroma_tx..][..chroma_tx]); } } } } mu_chroma = true; u_grid = Grid::Own(u_acc); v_grid = Grid::Own(v_acc); } else { // lane-av1-422k: the chroma plane block is (`chroma_w`, // `chroma_h`) -- the square read above at 4:2:0/4:4:4, one rect // TX_{side/2}X{side} unit through [`read_rect_chroma_unit`] at // 4:2:2 (the key-frame path's proven set/scan rows, and the // per-chroma-cell context read [`around_mi_422_chroma`]). let chroma_around = if chroma_w == chroma_h { around } else { neighbours.around_mi_422_chroma(at, side, side) }; if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } u_grid = if chroma_w == chroma_h { read_plane( dec, cdfs, chroma_set, scan_chroma, 1, chroma_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, )? } else if side == 64 { // lane-av1-422inter: `av1_get_max_uv_txsize(BLOCK_64X64)` at // ss (1,0) adjusts `max_txsize_rect_lookup[BLOCK_32X64]` = // TX_32X64 down to TX_32X32 (`av1_get_adjusted_tx_size`), so // the (side/2, side) = (32, 64) plane block codes TWO stacked // SQUARE TX_32X32 units per plane, plane-major -- the // key-frame path's own model (`decode_block`'s 4:2:2 // chroma_tx table, "64 and 128: TX_32X64 / TX_64X64 adjust // down to TX_32X32", proven byte-exact on this fixture's // frame 0) and the twin of this function's own side>64 // mu-chunk walk above. The whole-plane-block rect read this // arm replaced handed [`read_coeffs_rect`] a 36x68 levels // frame it never had (the frame-9 panic) and would have read // a full TX_32X64 scan libaom never codes. let cu_scan = default_scan(32); let (cu_w, cu_h) = (32usize, 32usize); let luma_span_x = cu_w << ss_x(fctx); let luma_span_y = cu_h << ss_y(fctx); let mut assembled = vec![0i32; chroma_side * chroma_side]; for cu_row in 0..chroma_h / cu_h { let cu_mi = (at_mi.0 + cu_row * (luma_span_y / MI), at_mi.1); let cu_around = neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y); let cu_reach = tu_reach_rect( side, side, 0, cu_row * luma_span_y, luma_span_x, luma_span_y, reach, px, py, y.width, y.height, fctx, ); let cu_grid = read_plane( dec, cdfs, TxbSet::Chroma32, &cu_scan, 1, cu_around[1], mode, uv_predict_mode, angle_delta_uv, cu_reach, u, cpx, cpy + cu_row * cu_h, cu_w, cu_w, base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, // The uv plane block (32x64) 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, )?; hit!(CHROMA_SPLIT_TX_HITS); hit!(CHROMA422_SQUARE_HITS); // Immediately, so the next unit of this plane reads this // one's coefficient context; the whole-block record below // re-stamps the block over these and the tail's // `mu_chroma_units` replay puts the per-unit state back // (lane-dpm1). neighbours.record_mi_chroma(cu_mi, luma_span_x, luma_span_y, 1, &cu_grid); for rr in 0..cu_h { let start = (cu_row * cu_h + rr) * chroma_side; assembled[start..start + cu_w] .copy_from_slice(&cu_grid[rr * cu_w..][..cu_w]); } } mu_chroma = true; Grid::Own(assembled) } else { let (rect_set, rect_scan): (TxbSet, &[u16]) = match side { 4 => (TxbSet::Chroma4, default_scan(4)), 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]), 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]), 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]), _ => (TxbSet::Chroma32, default_scan(32)), }; read_rect_chroma_unit( dec, cdfs, rect_set, rect_scan, chroma_w, chroma_h, 1, chroma_around[1], uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, base_q_idx, None, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), smooth_neighbor_uv, fctx, )? }; if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } v_grid = if chroma_w == chroma_h { read_plane( dec, cdfs, chroma_set, scan_chroma, 2, chroma_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, )? } else if side == 64 { // lane-av1-422inter: plane 2 of the TX_32X32-adjusted walk // above -- same two stacked square units, plane-major (every // U unit, then every V unit, libaom `decode_token_recon_block`'s // per-mu-chunk plane loop). let cu_scan = default_scan(32); let (cu_w, cu_h) = (32usize, 32usize); let luma_span_x = cu_w << ss_x(fctx); let luma_span_y = cu_h << ss_y(fctx); let mut assembled = vec![0i32; chroma_side * chroma_side]; for cu_row in 0..chroma_h / cu_h { let cu_mi = (at_mi.0 + cu_row * (luma_span_y / MI), at_mi.1); let cu_around = neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y); let cu_reach = tu_reach_rect( side, side, 0, cu_row * luma_span_y, luma_span_x, luma_span_y, reach, px, py, y.width, y.height, fctx, ); let cu_grid = read_plane( dec, cdfs, TxbSet::Chroma32, &cu_scan, 2, cu_around[2], mode, uv_predict_mode, angle_delta_uv, cu_reach, v, cpx, cpy + cu_row * cu_h, cu_w, cu_w, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, Some(3), smooth_neighbor_uv, fctx, )?; hit!(CHROMA_SPLIT_TX_HITS); hit!(CHROMA422_SQUARE_HITS); neighbours.record_mi_chroma(cu_mi, luma_span_x, luma_span_y, 2, &cu_grid); for rr in 0..cu_h { let start = (cu_row * cu_h + rr) * chroma_side; assembled[start..start + cu_w] .copy_from_slice(&cu_grid[rr * cu_w..][..cu_w]); } } mu_chroma = true; Grid::Own(assembled) } else { let (rect_set, rect_scan): (TxbSet, &[u16]) = match side { 4 => (TxbSet::Chroma4, default_scan(4)), 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]), 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]), 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]), _ => (TxbSet::Chroma32, default_scan(32)), }; read_rect_chroma_unit( dec, cdfs, rect_set, rect_scan, chroma_w, chroma_h, 2, chroma_around[2], uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, base_q_idx, None, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), 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. // lane-av1-444interband: 4:2:0 ONLY. At ss 0/0 every strip IS its own // chroma reference (`is_chroma_reference`, no mi parity test), its own // `record_rect_mi` above already stamps exactly the strip's 16x4 (4x16) // chroma span -- libaom `av1_set_entropy_contexts`, or // `av1_reset_entropy_context` for a skipped strip (decodeframe.c:1180) // -- and the pair-form 16x8 (8x16) span anchored at `pair_mi` (== the // strip's own mi at ss 0/0) smeared the strip's state over one extra // row/col of cells: a skipped strip wrote zero over `left[r+1][1..2]`, // erasing the 16x16-intra block to its left's U/V stamps, and the strip // below read its chroma `txb_skip` off the wrong CDF row (t6 frame 1, // U unit (2,8): our base 0 vs aom's base 1, `left[2][1]` 0 vs 23 -- // `INTER16_CHROMA_PAIR_HITS` fired 31x on a stream that has no pairs). let pair_chroma = strip_chroma .filter(|s| s.has_chroma) .filter(|_| ss_x(fctx) == 1 && ss_y(fctx) == 1) .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 mut mu_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = if mu_chroma { // lane-lossless2: the unit is TX_32X32 (one per 64x64 mu chunk) // normally and TX_4X4 on a lossless frame, where the whole chroma // plane block is a raster of them. let cu = if lossless(fctx) { 4usize } else { 32usize }; let mut units = Vec::new(); if lossless(fctx) { // lane-av1-llinter: a TX_4X4 chroma unit covers `4 << ss` LUMA // pixels (8, x2-per-unit, at 4:2:0; 4, x1, at 4:4:4) -- the // composed plane grid then holds a full cu-row per chroma row and // each unit's own origin sits `(cu << ss) / MI` mi cells out. // The hardcoded 4:2:0 /2-and-x2 math stamped half the plane with // double spans at 4:4:4 and corrupted the next block's // `txb_skip_ctx` (dodge2 frame 1, U unit mi (4,16) read row 11 // where the oracle reads row 10). let (rows, cols) = ( (write_h >> ss_y(fctx)).div_ceil(cu), (write_w >> ss_x(fctx)).div_ceil(cu), ); for cr in 0..rows { for cc in 0..cols { let cu_mi = ( at.0 + cr * ((cu << ss_y(fctx)) / MI), at.1 + cc * ((cu << ss_x(fctx)) / MI), ); for (plane, grid) in [(1usize, &u_grid), (2usize, &v_grid)] { let mut unit = Vec::with_capacity(cu * cu); for rr in 0..cu { // lane-av1422lpf site 2: the composed grid this // replays is the block's CHROMA PLANE BLOCK at // `chroma_stride` -- the same per-axis stride // site 1 sized `u_out`/`v_out` at and the same // `read_inter_chroma_lossless` wrote them at // (`src.offset(..)` + `(oy + row) * stride + ox`). // `chroma_side` is the ENCLOSING SQUARE // (`max(side >> ss_x, side >> ss_y)`), which is // the plane block's own width only when // `ss_x == ss_y`: at 4:2:2 it is the full luma // side, twice a strip block's plane-block width, // and the last unit row ran off the end // (`range end index 68 out of range for slice of // length 64`, W_intrabc frame 1). // // At 4:2:0 (`chroma_stride == chroma_side == // side >> 1`) and 4:4:4 (`side`) the two are the // same number and this line is unchanged. let start = (cr * cu + rr) * chroma_stride + cc * cu; unit.extend_from_slice(&grid[start..start + cu]); } units.push(( cu_mi, plane, Grid::Own(unit), cu << ss_x(fctx), cu << ss_y(fctx), )); } } } } else { // lane-av1-444 c8: a 64x64 mu chunk's chroma plane block is // (64 >> ss) square -- ONE TX_32X32 unit per chunk at 4:2:0 but // FOUR at ss 0/0 (`av1_get_max_uv_txsize` caps the unit at 32 // either way). Enumerate every unit at its own mi origin, its // own (32 << ss)-px entropy-cell span, and its own 32x32 // quadrant of the assembled plane grid; stamping one quadrant's // state over the whole chunk desynced the next block's // `txb_skip_ctx` (f52 mi(52,16) U read base 0, aom 1). let (ur, uc) = ( ((64usize) >> ss_y(fctx)) / cu, ((64usize) >> ss_x(fctx)) / cu, ); let (rows, cols) = ((write_h / 64).max(1), (write_w / 64).max(1)); for cr in 0..rows { for cc in 0..cols { for kr in 0..ur { for kc in 0..uc { let cu_mi = ( at.0 + (cr * 64 + kr * (cu << ss_y(fctx))) / MI, at.1 + (cc * 64 + kc * (cu << ss_x(fctx))) / MI, ); let cy = cr * ((64usize) >> ss_y(fctx)) + kr * cu; let cx = cc * ((64usize) >> ss_x(fctx)) + kc * cu; 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 = (cy + rr) * chroma_side + cx; unit.extend_from_slice(&grid[start..start + cu]); } units.push(( cu_mi, plane, Grid::Own(unit), cu << ss_x(fctx), cu << ss_y(fctx), )); } } } } } } units } else { Vec::new() }; // The rect_tu strips' true units (`read_inter_rect_chroma`'s return): // replayed by the same loop below, after the whole-block record. mu_chroma_units.extend(rect_chroma_units); // 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 { // lane-av1422ctxgather: at 4:2:2 (ss 1,0) a horz strip is its own // chroma reference -- no pair merge ever happened, so the write // covers the strip's own 8x4: ONE luma-mi left row (libaom's // `av1_set_contexts` for the TX_8X4 at ss_y 0 stamps // `tx_size_high_unit` = 1 cell). The 4:2:0 pair's two-row (16, 8) // span would overwrite the NEXT row's leaf-stamped level state // (measured: t422 frame 1, the strip at mi(8,4) zeroed // left[9][1] under the mi(8,2) 8x8's level 5 before the mi(9,4) // strip's own all_zero read it one ctx row low). let (pw, ph) = if s.horz { if ss_x(fctx) == 1 && ss_y(fctx) == 0 { (16usize, 4usize) } else { (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); } // lane-av1-444 c8: each unit stamps its OWN span (32 << ss px at // TX_32X32, 8 px lossless) -- a 64x64 mu chunk at ss 0/0 holds four // TX_32X32 units, so the old whole-chunk 64-px span smeared one unit's // state over its three neighbours' cells too. for (cu_mi, plane, unit, span_w, span_h) in &mu_chroma_units { neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *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, fctx); } 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 >> ss_x(fctx), gpy >> ss_y(fctx)); // 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; // This loop iteration's own sub-block luma `tx_type` (libaom `mbmi->tx_type` // after its `read_tx_type`): the per-piece 4:4:4 chroma units inherit it // (`av1_get_tx_type`, blockd.h -- inter chroma never codes its own symbol). let mut piece_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; // 4:4:4 (lane-av1-444): `is_chroma_reference` is unconditional at // subsampling 0/0, so EVERY 4x4 sub-block codes its own 4x4 chroma unit // right after its own luma (aomdec EC_COEFF on `av1-profile1-444.ivf` // frame 1: plane 0,1,2 per leaf in leaf order) -- there is no shared // group unit and no 2x2-piece group prediction. let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; // 4:2:2 (lane-av1-422sub8rect): `is_chroma_reference` for a BLOCK_4X4 // piece at ss (1, 0) is `(mi_col & 0x01) || !(bw & 0x01) || !ss_x` // == ODD mi_col (av1_common_int.h:1459) -- pieces 1 and 3 of the group // are their plane's own chroma references and each codes its own // TX_4X4 unit right after its luma, exactly the key-frame split-group // behaviour the pinned t422 fixture's frame 0 traces (groups (18,54) // and (30,42): U+V read on BOTH odd-column leaves) and frame 1's // inter group at mi(12,2) repeats (U+V TX_4X4 ctx 8 on leaf (12,3) // alone -- the bottom-right leaf was skipped, so it codes nothing). // The 4:2:0 shared group unit never exists at 4:2:2. let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0; 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; let ec_skip_post = if std::env::var_os("EC_DBG_SUB8").is_some() { Some(dec.debug_state().0) } else { None }; inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false, fctx); maybe_read_cdef_idx(dec, rmi, cmi, (2, 2), 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 std::env::var_os("EC_DBG_SUB8").is_some() { eprintln!( "EC_DBG piece mi=({rmi},{cmi}) skip={skip} skipctx={skip_ctx} skip_post={:?} is_inter={is_inter} iictx={ii_ctx} post={}", ec_skip_post, dec.debug_state().0 ); } 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 chroma-reference sub-blocks (`is_chroma_reference`: the // LAST one under 4:2:0, BOTH odd-column ones at 4:2:2, every // one at 4:4:4). decode_intra_sub8_leaf( dec, cdfs, neighbours, grid, group_mi, lmi, (B4, B4), chroma_444 || (cmi & 1 == 1 && chroma_422) || 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, force_integer_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; if !not_new { crate::census::mode(0); } 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; if !not_zero { crate::census::mode(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; crate::census::mode(if nearest { 2 } else { 3 }); 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, 0), mv_to_q4(py, mv.0, 0), 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, )?; piece_tx_type = tx_type; 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); } // lane-av1-444: `is_chroma_reference` is unconditional at ss 0/0 // (av1_common_int.h:1459 -- `!subsampling_x`/`!subsampling_y` force // both disjuncts true), so at 4:4:4 this 4x4 sub-block codes its own // 4x4 U and V units right after its luma, plane order 0,1,2 per leaf // (aomdec EC_COEFF on `av1-profile1-444.ivf` frame 1). Chroma MC is // the piece's own mv and filters at the piece's own pixel position // (ss 0: the chroma planes share luma's grid), and each unit's // tx_type is its own piece's luma type -- an inter block's chroma // plane never codes its own tx_type symbol but inherits the // colocated luma transform's coded type verbatim (`av1_get_tx_type`, // blockd.h), which decides the eob CDF's class-1 row // (`eob_multi_ctx`, decodetxb.c:214). if chroma_444 { let (pc_ref, pc_mv, pc_hf, pc_vf) = piece[i].expect("inter piece recorded above"); let build_c = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let Some((pc_ref_y, sref_u, sref_v)) = ref_planes_deferred(pc_ref, refpix) else { return; }; let pc_scale = mc::scale_factor(pc_ref_y.width, frame_width); 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 (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] { let mut buf = vec![0u16; B4 * B4]; mc::predict_maybe_scaled( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(px, pc_mv.1, ss_x(fctx)), mv_to_q4(py, pc_mv.0, ss_x(fctx)), pc_scale, B4, B4, pc_hf, pc_vf, &mut buf, fctx, ); dst.copy_from_slice(&buf); } out[1] = pred_u; out[2] = pred_v; }; let (pred_cu, pred_cv): (Vec, Vec); let (su, sv) = if recon_deferred(fctx) { push_pred(fctx, build_c); ( 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_c(y, u, v, fctx, &mut built); let [_, bu, bv] = built; (pred_cu, pred_cv) = (bu, bv); (Pred::Inline(&pred_cu, B4), Pred::Inline(&pred_cv, B4)) }; if skip { push_mc(1, px, py, B4, su, &ZERO_RESIDUAL[..B4 * B4], fctx); push_mc(2, px, py, B4, sv, &ZERO_RESIDUAL[..B4 * B4], fctx); neighbours.record_mi_chroma(lmi, B4, B4, 1, &ZERO_RESIDUAL[..B4 * B4]); neighbours.record_mi_chroma(lmi, B4, B4, 2, &ZERO_RESIDUAL[..B4 * B4]); } else { let ca = neighbours.around_mi(lmi, B4); let (ug, _) = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, ca[1], 0, u, px, py, B4, base_q_idx, su, Some(piece_tx_type), None, fctx, )?; let (vg, _) = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, ca[2], 0, v, px, py, B4, base_q_idx, sv, Some(piece_tx_type), None, fctx, )?; neighbours.record_mi_chroma(lmi, B4, B4, 1, &ug); neighbours.record_mi_chroma(lmi, B4, B4, 2, &vg); } // lane-av1-422sub8rect: the 4:2:2 per-piece arm. `is_chroma_reference` // for a BLOCK_4X4 at ss (1, 0) is the odd mi_col (`av1_common_int.h` // :1459), so THIS piece (right column of the group) is a chroma // reference and codes its own U and V TX_4X4 units right after its // luma -- measured on the pinned t422 fixture: frame 0 key-frame // groups (18,54)/(30,42) read U+V on both odd-column leaves, and // frame 1's inter group at mi(12,2) reads U+V TX_4X4 ctx 8 on leaf // (12,3) alone (its bottom-right twin was skipped). // // The unit anchors at the FLOORED chroma cell // (`av1_setup_dst_planes`' `(mi_col & !1) * MI >> ss_x`, the // lane-av1-422kf2 rule), so the 4-px-wide square covers the group's // whole chroma width, and the prediction walks // `build_inter_predictors_sub8x8` (reconinter_template.inc): the // left 2x4 half from the LEFT piece's own ref/mv/filters, the right // 2x4 half from this piece's -- unless the left piece is intra (or // off-frame), which makes `is_sub8x8_inter` false and predicts the // whole 4x4 from THIS piece's own mv. A skipped reference piece // still predicts (spec 7.11.3: `predict_inter_block_visit` runs // before the `skip_txfm` guard) but codes no coefficients. } else if chroma_422 && (cmi & 1) == 1 { let (pc_ref, pc_mv, pc_hf, pc_vf) = piece[i].expect("inter piece recorded above"); let unit_x = ((cmi & !1) * MI) >> ss_x(fctx); let unit_y = py >> ss_y(fctx); // `is_sub8x8_inter`'s left-neighbour probe (`mi[-1]`): the piece // one mi to the LEFT, when it exists and is inter. let piece_left = piece[i - 1]; let build_c = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let Some((pc_ref_y, sref_u, sref_v)) = ref_planes_deferred(pc_ref, refpix) else { return; }; let pc_scale = mc::scale_factor(pc_ref_y.width, frame_width); // The left piece's own reference planes + mv/filters, when it // is an inter piece (`is_sub8x8_inter`'s `mi[-1]` probe). let left = piece_left .as_ref() .map(|&(l_ref, l_mv, l_hf, l_vf)| (l_ref, l_mv, l_hf, l_vf)) .and_then(|(l_ref, l_mv, l_hf, l_vf)| { ref_planes_deferred(l_ref, refpix).map(|planes| { let (lp_y, _, _) = planes; let l_scale = mc::scale_factor(lp_y.width, frame_width); (l_mv, l_hf, l_vf, planes, l_scale) }) }); 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 (pi, (plane, dst)) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] .into_iter() .enumerate() { let mut buf = vec![0u16; B4 * B4]; // Right 2x4 half: this piece's own ref/mv/filters. let mut half = vec![0u16; 2 * 4]; mc::predict_maybe_scaled( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(unit_x + 2, pc_mv.1, ss_x(fctx)), mv_to_q4(unit_y, pc_mv.0, ss_y(fctx)), pc_scale, 2, 4, pc_hf, pc_vf, &mut half, fctx, ); for row in 0..4 { buf[row * B4 + 2..row * B4 + 4] .copy_from_slice(&half[row * 2..row * 2 + 2]); } // Left 2x4 half: the LEFT piece's own mv/filters // (sub8x8-inter); a mixed group (left piece intra or // off-frame) predicts it from THIS piece too, which // reduces to the whole-4x4-from-own rule. let (l_mv, l_hf, l_vf, l_planes, l_scale) = match left { Some((l_mv, l_hf, l_vf, l_planes, l_scale)) => { (l_mv, l_hf, l_vf, l_planes, l_scale) } None => (pc_mv, pc_hf, pc_vf, (pc_ref_y, sref_u, sref_v), pc_scale), }; // lane-av1422sub8pix: the left half predicts from the // LEFT piece's own plane of its reference -- U for the U // iteration, V for the V one. The old `l_ref_u` grab // fed the V plane's left half from the reference's U // plane (V cols 44..45 of the t422 frame-1 groups read // U samples; U was exact, V wasn't). let l_ref = if pi == 0 { let (_, u, _) = l_planes; u } else { let (_, _, v) = l_planes; v }; mc::predict_maybe_scaled( &l_ref.data, l_ref.width, l_ref.true_width, l_ref.true_height, mv_to_q4(unit_x, l_mv.1, ss_x(fctx)), mv_to_q4(unit_y, l_mv.0, ss_y(fctx)), l_scale, 2, 4, l_hf, l_vf, &mut half, fctx, ); for row in 0..4 { buf[row * B4..row * B4 + 2].copy_from_slice(&half[row * 2..row * 2 + 2]); } dst.copy_from_slice(&buf); } out[1] = pred_u; out[2] = pred_v; }; let (pred_cu, pred_cv): (Vec, Vec); let (su, sv) = if recon_deferred(fctx) { push_pred(fctx, build_c); ( 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_c(y, u, v, fctx, &mut built); let [_, bu, bv] = built; (pred_cu, pred_cv) = (bu, bv); (Pred::Inline(&pred_cu, B4), Pred::Inline(&pred_cv, B4)) }; // The unit's entropy context: one chroma cell wide, floored -- // [`Neighbours::around_mi_422_chroma`] at the unit's own 8x4 // luma span (the [`sub8_leaf_chroma422`] rule). let ctx_mi = (rmi, cmi & !1); let ca = neighbours.around_mi_422_chroma(ctx_mi, 8, 4); if skip { push_mc(1, unit_x, unit_y, B4, su, &ZERO_RESIDUAL[..B4 * B4], fctx); push_mc(2, unit_x, unit_y, B4, sv, &ZERO_RESIDUAL[..B4 * B4], fctx); neighbours.record_mi_chroma(ctx_mi, 8, 4, 1, &ZERO_RESIDUAL[..B4 * B4]); neighbours.record_mi_chroma(ctx_mi, 8, 4, 2, &ZERO_RESIDUAL[..B4 * B4]); } else { hit!(CHROMA422_INTER_SUB8_HITS); let (ug, _) = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, ca[1], 0, u, unit_x, unit_y, B4, base_q_idx, su, Some(piece_tx_type), None, fctx, )?; let (vg, _) = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, ca[2], 0, v, unit_x, unit_y, B4, base_q_idx, sv, Some(piece_tx_type), None, fctx, )?; neighbours.record_mi_chroma(ctx_mi, 8, 4, 1, &ug); neighbours.record_mi_chroma(ctx_mi, 8, 4, 2, &vg); } } 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-av1-444: when the chroma-reference sub-block was INTRA it coded // and reconstructed the group's one chroma unit itself. // lane-av1-444 (f19): at ss 0/0 the group unit does not exist -- every // piece coded its own U/V inside the loop above, and every piece also // wrote its own `uv_mode` neighbour state: an inter piece through // `record_inter_rect_mi`'s is_inter DC stamp (libaom leaves `uv_mode` // unset on an inter mbmi, `is_smooth` reads 0), an INTRA piece through // [`decode_intra_sub8_leaf`]'s chroma_444 arm (libaom's per-sub-block // `mbmi->uv_mode` is real there -- frame 19 of the fixture reads // uv 12/11/9/12 on the four pieces of the (42,54) group, and the next // block's `get_intra_edge_filter_type` must see that SMOOTH_H left // neighbour, not the DC_PRED this stamp used to paint over it). So the // group-level stamp runs only where the 4:2:0 group unit is real. // // 4:2:0 "real" means the group unit was painted by the INTER arm below: // when the chroma-reference sub-block was INTRA, that leaf's own tail // ([`decode_intra_sub8_leaf`]) already recorded the group cell with its // real `uv_predict_mode` -- possibly a SMOOTH mode the next block's // chroma edge filter must see. The 444 delta's unconditional // `!chroma_444` stamp ran after it and painted DC over the mi-exact // cell, so every later chroma block read `intra_edge_filter_type` 0 // where libaom (and the pre-delta tree) read 1 -- 188 chroma ops of the // gm_small_side witness flipped their smooth flag and 10-bit film // frames mismatched ffmpeg by +-1..7 (class // `override-slot-on-one-arm`, this lane's own 10-bit film gate // regression at 1ad7e0fc; port of lane-av1-cfl's 7c6dad53). if !chroma_444 && !chroma_422 && !intra_chroma { 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]); if !chroma_444 && !chroma_422 && !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. lane-av1-422sub8rect: 4:2:2 never takes // this arm -- the shared group unit does not exist at ss (1, 0); each // odd-column piece coded its own chroma inside the loop above. // `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, ss_x(fctx)), mv_to_q4(oy, mv.0, ss_x(fctx)), 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) }; 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`), /// `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 { // lane-av1mono: a monochrome leaf codes no chroma mode (libaom // `decodemv.c:933`). let has_chroma = has_chroma && !mono(fctx); 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). crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); 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` (blockd.h): away from lossless it is // `wide <= 32 && high <= 32` -- true for this shape; at lossless the // CHROMA plane block must be a single TX_4X4, so at 4:4:4 only the // 4x4 leaf keeps the 14-symbol CFL alphabet while an 8x4/4x8 leaf // reads the 13-symbol `uv_mode_no_cfl` one (the t6 frame-1 8x4 leaf // desynced at its uv_mode symbol reading the CFL alphabet, // lane-av1llintercdf). At 4:2:0 a sub-8 shape's chroma block is // always 4x4-or-smaller, so the predicate stays true and this read // is unchanged. let uv_mode = if cfl_allowed_px(bw, bh, fctx) { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; if step { eprintln!( "EC_ISTEP mi_row={} mi_col={} name=uv_mode val={uv_mode} rng={}", lmi.0, lmi.1, 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); } (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. // lane-av1mix: the lossless early return (`decodeframe.c:1203`) sits // before the `TX_MODE_SELECT` test, so a lossless-segment rect leaf codes // no depth symbol either (sweep of the class fixed at the key-frame pair // path). let depth = if tx_select && bw != bh && !lossless(fctx) { 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 || (lossless(fctx) && bw != bh); 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, 0, )?; let residual = dequant_and_inverse_typed_wh( &levels, bw, bh, crate::decode::bit_depth(fctx), // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at // every other dequant site (class `parsed-then-discarded`). block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type, block_iqmatrix(fctx, 0, bw, bh, 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); }); } // 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. // // lane-av1mono: this publish is NOT chroma work and must run BEFORE the // `!has_chroma` return below. libaom's mi grid holds // `palette_size[0] == 0` in every cell of such a group whatever the // plane count, and on a monochrome frame EVERY sub-8 leaf passes // `has_chroma == false`, so a publish placed after the return never ran // at all: the band kept an earlier palette block's size, the next block // read `palette_y_mode` off CDF row 1 where libaom reads row 0, decoded // a palette libaom never coded, and the tile desynced one block later // (measured: gray testsrc2 320x240, decode-order frame 33, mi(42,50), // ours ctx 2 where libaom gathers 1). record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]); if !has_chroma { // lane-av1-422sub8rect: 4:2:2 has no shared group unit whose tail // would stamp the mi map (`is_chroma_reference` runs per piece), so // a non-referenced piece publishes its own cell -- libaom leaves // `uv_mode` unset on it, `is_smooth` reads 0, i.e. DC_PRED. if ss_x(fctx) == 1 && ss_y(fctx) == 0 { neighbours.record_uv_mode_mi(lmi.0, lmi.1, 1, 1, DC_PRED); } return Ok(mode); } // lane-av1-422sub8rect: at 4:2:2 this (odd-column) piece is its plane's // OWN chroma reference -- the key-frame split group's per-leaf TX_4X4 // model, floored anchor and per-chroma-cell context included // ([`sub8_leaf_chroma422`], measured on the pinned t422 fixture frame 0: // groups (18,54)/(30,42) code U+V on both odd-column leaves), never a // shared group unit. Inter frames code no intrabc, so `intrabc_dv` is // `None` here. if ss_x(fctx) == 1 && ss_y(fctx) == 0 { sub8_leaf_chroma422( dec, cdfs, neighbours, lmi, uv_mode, 0, alpha, skip, None, y, u, v, scan4, base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (bw, bh), fctx, )?; 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. // // lane-av1-444: at ss 0/0 EVERY piece is its own chroma reference // (`is_chroma_reference`, av1_common_int.h:1459), so the unit anchors at // the piece's own position with the piece's own shape -- a 4x4 unit under // SPLIT, the leaf's own 8x4/4x8 unit under HORZ/VERT (`ChromaRect8x4`, // tx_type from the uv mode via `Intra_Mode_To_Tx_Type`, which decides the // eob CDF's class-1 row, decodetxb.c:214). let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; let (gpx, gpy) = (gc * MI, gr * MI); let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx)); let (unit_x, unit_y) = if chroma_444 { (px, py) } else { (cpx, cpy) }; let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx); let reach_c = if chroma_444 && bw != bh { Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx) } else if chroma_444 { Reach::of(bw, px, py, y.width, y.height, fctx) } else { group_reach }; let (band_r, band_c) = if chroma_444 { (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI)) } else { (r, c) }; let smooth_neighbor_uv = neighbours.smooth_uv_neighbour( if chroma_444 { lmi.0 } else { gr }, if chroma_444 { lmi.1 } else { gc }, band_r, band_c, fctx, ); let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; let angle_delta_uv = 0; neighbours.above_uv_mode[band_c] = uv_predict_mode; neighbours.left_uv_mode[band_r] = uv_predict_mode; if chroma_444 { neighbours.record_uv_mode_mi(lmi.0, lmi.1, w_mi, h_mi, uv_predict_mode); } else { neighbours.record_uv_mode_mi(gr, gc, 2, 2, uv_predict_mode); } let ac = alpha.map(|_| { if chroma_444 { cfl_src_rect(px, py, bw, bh) } else { cfl_src(gpx, gpy, 8) } }); let mut chroma_stamped_per_unit = false; let (u_grid, v_grid): (Grid, Grid) = if skip { if alpha.is_some() { hit!(CHROMA_SKIP_CFL_HITS); hit!(SKIP_CFL_HITS); } if chroma_444 && bw != bh { let zeros = Grid::Zero(bw * bh); push_intra_rect( 1, unit_x, unit_y, bw, bh, uv_predict_mode, angle_delta_uv, reach_c, &zeros, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); push_intra_rect( 2, unit_x, unit_y, bw, bh, uv_predict_mode, angle_delta_uv, reach_c, &zeros, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); (zeros, Grid::Zero(bw * bh)) } else { push_intra( 1, unit_x, unit_y, 4, uv_predict_mode, angle_delta_uv, reach_c, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, ); push_intra( 2, unit_x, unit_y, 4, uv_predict_mode, angle_delta_uv, reach_c, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, ); (Grid::Zero(16), Grid::Zero(16)) } } else if chroma_444 && bw != bh { if lossless(fctx) { // lane-av1sub8rect444: lossless codes TX_4X4 on EVERY plane // (`av1_get_tx_size`, blockd.h:1383), so this leaf's 8x4/4x8 // chroma plane block is a 1x2/2x1 raster of TX_4X4 units per // plane, PLANE-MAJOR -- the same per-unit walk // [`read_intra_chroma_lossless`] runs for whole blocks and this // leaf's own luma `split` runs above, not one TX_8X4/TX_4X8 // rect unit. The rect read was wrong twice over: its unit count // left the second unit's coefficients in the bitstream, and its // skip ctx fixed at above+left missed `get_txb_ctx`'s // plane-block-bigger-than-transform term (libaom ctx 10+above // +left, our tables' +3), where the oracle read ctx 11≡4. let (mut uo, mut vo) = (Vec::new(), Vec::new()); for plane_idx in 1..3 { for tu in 0..2usize { let (ox, oy) = if vert { (0, tu * 4) } else { (tu * 4, 0) }; // libaom's `max_blocks_wide/high` clip: a unit whose // origin is past the frame edge is not coded at all // (`decode_token_recon_block`). At 4:4:4 the unit's // chroma origin is the leaf's own (px, py). if px + ox >= u.true_width || py + oy >= u.true_height { continue; } // At 4:4:4 a TX_4X4 chroma unit IS one mi cell. let tu_mi = (lmi.0 + oy / MI, lmi.1 + ox / MI); let tu_around = neighbours.around_mi(tu_mi, MI); let tu_r = tu_reach(bw, bh, ox, oy, 4, reach_c, px, py, y.width, y.height, fctx); let buf: &mut PlaneBuf<'static> = if plane_idx == 1 { &mut *u } else { &mut *v }; // The plane block (8x4/4x8) is bigger than the TX_4X4 // transform, so `get_txb_ctx`'s chroma ctx_offset is 10, // not 7 -- our chroma tables carry the offset-10 rows at // +3, the same `Some(3)` [`read_intra_chroma_lossless`] // derives from `blk_w > 4 || blk_h > 4`. let tu_grid = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, plane_idx, tu_around[plane_idx], mode, uv_predict_mode, angle_delta_uv, tu_r, buf, px + ox, py + oy, 4, TX4, base_q_idx, None, None, Some(3), smooth_neighbor_uv, fctx, )?; // The unit's own coefficient context, stamped per unit // (`av1_set_contexts`); the tail's whole-leaf chroma // stamp below is skipped for this shape. neighbours.record_mi_chroma(tu_mi, 4, 4, plane_idx, &tu_grid); hit!(CHROMA_SPLIT_TX_HITS); let dst = mu_units(if plane_idx == 1 { &mut uo } else { &mut vo }, bw * bh); for row in 0..4 { let start = (oy + row) * bw + ox; dst[start..start + 4].copy_from_slice(&tu_grid[row * 4..][..4]); } } } chroma_stamped_per_unit = true; hit!(LLSUB8RECT444_CHROMA_WALK_HITS); ( if uo.is_empty() { Grid::Zero(bw * bh) } else { Grid::Own(uo) }, if vo.is_empty() { Grid::Zero(bw * bh) } else { Grid::Own(vo) }, ) } else { // The leaf's own TX_8X4/TX_4X8 chroma unit: it IS the chroma plane // block, so `get_txb_ctx` fixes the skip context at above+left. let ca = neighbours.around_mi_rect(lmi, bw, bh); let scan_c: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 }; let uv_tx = default_intra_tx_type(uv_predict_mode as u8); let mut read_chroma = |plane: usize, around: (bool, bool, i32), alpha_uv: Option<(i32, CflSrc)>| -> Result { let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, 0); let skip_ctx = usize::from(around.0) + usize::from(around.1); let (levels, tx_type) = read_coeffs_rect( dec, &mut coding, scan_c, bw, bh, skip_ctx, dc_sign_ctx(around.2), uv_tx, plane, )?; let residual = dequant_and_inverse_typed_wh( &levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), plane_q_delta(plane, fctx).0, plane_q_delta(plane, fctx).1, tx_type, block_iqmatrix(fctx, plane, bw, bh, tx_type), ); push_intra_rect( plane, unit_x, unit_y, bw, bh, uv_predict_mode, angle_delta_uv, reach_c, &residual, alpha_uv, None, smooth_neighbor_uv, fctx, ); Ok(levels) }; let ug = read_chroma(1, ca[1], alpha.zip(ac).map(|((au, _), ac)| (au, ac)))?; let vg = read_chroma(2, ca[2], alpha.zip(ac).map(|((_, av), ac)| (av, ac)))?; (ug, vg) } } else { let chroma_around = neighbours.around_mi( if chroma_444 { lmi } else { group_mi }, if chroma_444 { 4 } else { 8 }, ); let ug = read_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode, angle_delta_uv, reach_c, u, unit_x, unit_y, 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, reach_c, v, unit_x, unit_y, 4, TX4, base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, )?; (ug, vg) }; // The 4:4:4 lossless walk above already stamped these bands PER UNIT // (raster-order last writer per cell, exactly libaom's per-entry last // update); the whole-leaf aggregate would clobber the two units' distinct // states with one, so it runs only for the one-unit shapes (the same rule // [`decode_leaf8`]'s intrabc arm and the inter 8x8 leaf obey). The walk // must skip the 4:2:0 group-tail below too: it spans the GROUP's two mi // rows/cols with one composed state, which would overwrite the walk's // own stamps with the whole-leaf aggregate. if chroma_444 { if !chroma_stamped_per_unit { neighbours.record_mi_chroma(lmi, bw, bh, 1, &u_grid); neighbours.record_mi_chroma(lmi, bw, bh, 2, &v_grid); } } else { 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 >> ss_x(fctx), gpy >> ss_y(fctx)); // 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; // lane-av1-444: `is_chroma_reference` is unconditional at subsampling 0/0 // (av1_common_int.h:1459), so every 8x4/4x8 piece is its own chroma // reference and codes its own 8x4/4x8 U/V units right after its luma -- // there is no shared group unit (aomdec EC_COEFF on // `av1-profile1-444.ivf` decode-order frame 1, mi (3,8)). let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; // lane-av1-422blockhalf: at ss (1,0) the chroma reference is PER PIECE // too, keyed by `is_chroma_reference`'s own terms: an 8x4 HORZ piece is // 2 mi wide (`!(bw & 1)`), so BOTH pieces of the group are references; // a 4x8 VERT piece is 1 mi wide, so only the ODD-column piece is // (`mi_col & 1`) -- measured on the pinned t422 fixture frame 1: the // horz group at mi (8,10)/(9,10) reads U+V TX_4X4 after EACH piece's // luma (rng 37134/37852 then 63752/50952), and the vert group at // (3,10)/(3,11) reads U+V on the odd-column piece (3,11) alone. The old // `i == 1` rule coded the group's chroma on the wrong piece (and, for // horz, half of the units) and desynced frame 1 at (8,10)'s uv_mode. let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0; // 4:4:4: every piece. 4:2:2: both horz pieces, the odd-column vert piece. // 4:2:0 keeps its existing second-piece model untouched. let piece_is_chroma_ref = |i: usize| -> bool { if ss_x(fctx) == 0 && ss_y(fctx) == 0 { true } else if chroma_422 { !vert || ((gc + i) & 1) == 1 } else { i == 1 } }; // This piece's first transform's luma `tx_type` (libaom `mbmi->tx_type`): // an inter block's chroma plane never codes its own symbol but inherits // the colocated luma type (`av1_get_tx_type`, blockd.h:1291). let mut piece_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, (2, 2), 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, piece_is_chroma_ref(i), 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), piece_is_chroma_ref(i), 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 piece_is_chroma_ref(i) { 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, force_integer_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; if !not_new { crate::census::mode(0); } 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; if !not_zero { crate::census::mode(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; crate::census::mode(if nearest { 2 } else { 3 }); 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(); // lane-av1mixllfork: the same libaom ordering fix as the intrabc rect // leaf's (`parse_decode_block`, decodeframe.c:1237): the per-segment // `lossless` flag is a CONJUNCT of the var-tx condition, not its // `else` arm, so a lossless SEGMENT of a mixed-lossless inter frame // reads no `tx_size_cat1` symbol here and codes TX_4X4 per plane. if fctx.tx_select_inter.with(std::cell::Cell::get) && !skip && !lossless(fctx) { 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 if lossless(fctx) && !skip { // COUNTED ONLY WHEN THE SUPPRESSION IS THE CONJUNCT'S WORKING: the // else-if also fires for a leaf whose `tx_select_inter` is off, // where the tree would not have run either way. The refutation pass // measured 33 hits on a build with the conjunct REMOVED, which is // exactly that population -- so an unconditional hit proves only // "a lossless sub-8 leaf was walked", not "the conjunct suppressed // a tree". Guard it on the same term the conjunct uses. if fctx.tx_select_inter.with(std::cell::Cell::get) { hit!(SUB8_LOSSLESS_NO_VARTX); } // lane-lossless2: `read_block_tx_size` returns TX_4X4 before it // ever looks at `max_txsize_rect_lookup`, so an 8x4/4x8 leaf is // TWO 4x4 units, not one rect one. for row in 0..bh / MI { for col in 0..bw / MI { leaves.push((row, col, MI, MI)); } } set_txfm_ctxs(neighbours, lmi, MI, w_mi, h_mi, skip); } 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, 0), mv_to_q4(py, mv.0, 0), 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 { piece_tx_type = tu_tx_type; } 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, ); } // lane-av1-444: at ss 0/0 this piece codes its OWN 8x4/4x8 U and V // units right after its luma, plane order 0,1,2 (libaom decodes each // piece as its own block: `decode_token_recon_block`'s plane-major // loop over `av1_get_max_uv_txsize(BLOCK_8X4, 0, 0) == TX_8X4`). The // unit's prediction is the piece's own mv/filters at the piece's own // pixel position (ss 0: the chroma planes share luma's grid), and its // tx_type is this piece's first luma transform's coded type. if chroma_444 { let build_c = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let Some((_, sref_u, sref_v)) = ref_planes_deferred(ref_frame, refpix) else { return; }; let piece_scale = mc::scale_factor(ref_width, frame_width); let mut pred_u = refill(std::mem::take(&mut out[1]), SIDE * SIDE); let mut pred_v = refill(std::mem::take(&mut out[2]), SIDE * SIDE); for (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] { let mut dense = vec![0u16; bw * bh]; mc::predict_maybe_scaled( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(px, mv.1, ss_x(fctx)), mv_to_q4(py, mv.0, ss_x(fctx)), piece_scale, bw, bh, h_filter, v_filter, &mut dense, fctx, ); for row in 0..bh { dst[row * SIDE..][..bw].copy_from_slice(&dense[row * bw..][..bw]); } } out[1] = pred_u; out[2] = pred_v; }; let (pred_cu, pred_cv): (Vec, Vec); let (su, sv) = if recon_deferred(fctx) { push_pred(fctx, build_c); ( Pred::Cur { plane: 1, stride: SIDE, off: 0, }, Pred::Cur { plane: 2, stride: SIDE, off: 0, }, ) } else { let mut built: [Vec; 3] = Default::default(); build_c(y, u, v, fctx, &mut built); let [_, bu, bv] = built; (pred_cu, pred_cv) = (bu, bv); (Pred::Inline(&pred_cu, SIDE), Pred::Inline(&pred_cv, SIDE)) }; if skip { push_mc_rect( 1, px, py, SIDE, bw, bh, su, &ZERO_RESIDUAL[..SIDE * SIDE], fctx, ); push_mc_rect( 2, px, py, SIDE, bw, bh, sv, &ZERO_RESIDUAL[..SIDE * SIDE], fctx, ); neighbours.record_mi_chroma(lmi, bw, bh, 1, &ZERO_RESIDUAL[..bw * bh]); neighbours.record_mi_chroma(lmi, bw, bh, 2, &ZERO_RESIDUAL[..bw * bh]); } else if lossless(fctx) && !mono(fctx) { // lane-av1-llsub8b: lossless codes TX_4X4 on EVERY plane // (`av1_get_tx_size`, blockd.h:1383), so this 4:4:4 piece's // (8,4)/(4,8) chroma plane block is a 2x1/1x2 raster of // TX_4X4 units, not the ONE TX_8X4 rect unit the lossy arm // below reads -- that single rect is what tripped // `TxParams::run`'s WHT assert ((8,4) != (4,4), // decode.rs:2566). The walk stamps each unit's own // coefficient context, so -- unlike the lossy arm -- no // whole-block `record_mi_chroma` runs after it: the walk's // per-unit stamps ARE the block's chroma contexts (the same // rule `leaf8_inter_chroma_lossless`'s caller obeys). read_inter_chroma_lossless( dec, cdfs, neighbours, u, v, su, sv, (rmi, cmi), (px, py), (0, 0), (bw, bh), (bw, bh), SIDE, 0, base_q_idx, &mut Vec::new(), &mut Vec::new(), fctx, )?; } else { let ca = neighbours.around_mi_rect(lmi, bw, bh); let (ug, _) = read_inter_plane_rect( dec, cdfs, TxbSet::ChromaRect8x4, (bw, bh), SIDE, 1, ca[1], 0, u, px, py, su, Some(piece_tx_type), None, fctx, )?; let (vg, _) = read_inter_plane_rect( dec, cdfs, TxbSet::ChromaRect8x4, (bw, bh), SIDE, 2, ca[2], 0, v, px, py, sv, Some(piece_tx_type), None, fctx, )?; neighbours.record_mi_chroma(lmi, bw, bh, 1, &ug); neighbours.record_mi_chroma(lmi, bw, bh, 2, &vg); } // lane-av1-422blockhalf: the 4:2:2 per-piece arm. The chroma // reference piece codes its own U and V TX_4X4 units right after its // luma -- both pieces of a horz group, the odd-column piece of a // vert one (see `piece_is_chroma_ref` above; measured on the pinned // t422 fixture frame 1, horz group (8,10)/(9,10) and vert group // (3,10)/(3,11)). The unit anchors at the FLOORED chroma cell // (`av1_setup_dst_planes`' `(mi_col & !1) * MI >> ss_x`, the // lane-av1-422kf2 rule) and reads through // [`Neighbours::around_mi_422_chroma`]'s per-chroma-cell context. // A horz piece IS 4x4 chroma (8 luma wide, ss_y 0): its unit // predicts whole from its own mv/filters. A vert piece is 2 chroma // px wide, so its 4-px unit predicts in halves -- // `build_inter_predictors_sub8x8`'s rule: the left 2x4 from the // piece to the LEFT (the group's own left piece, or the decoded // neighbour when the group starts on an odd column), the right 2x4 // from this piece. A skipped reference piece still predicts (spec // 7.11.3) but codes no coefficients. } else if chroma_422 && piece_is_chroma_ref(i) { const B4: usize = 4; let (pc_ref, pc_mv, pc_hf, pc_vf) = piece[i].expect("inter piece recorded above"); let unit_x = ((lmi.1 & !1) * MI) >> ss_x(fctx); let unit_y = py; // The left 2x4 half's source: the in-group left piece when this // piece is the group's second, else the decoded neighbour one mi // to the left (an odd-column group start). Its interp filters // are not on the mi grid, so an outside neighbour borrows this // piece's own. let left_piece = if i > 0 { piece[i - 1] } else if lmi.1 > 0 { grid.get(rmi, lmi.1 - 1).filter(|mi| mi.is_inter).map(|mi| { ( mi.ref_frame, (i32::from(mi.mv.0), i32::from(mi.mv.1)), pc_hf, pc_vf, ) }) } else { None }; let build_c = move |_y: &mut PlaneBuf<'static>, _u: &mut PlaneBuf<'static>, _v: &mut PlaneBuf<'static>, fctx: &crate::decode::FrameCtx, out: &mut [Vec; 3]| { let Some((pc_ref_y, sref_u, sref_v)) = ref_planes_deferred(pc_ref, refpix) else { return; }; let pc_scale = mc::scale_factor(pc_ref_y.width, frame_width); 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 (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] { let mut buf = vec![0u16; B4 * B4]; if vert { // Right 2x4 half: this piece's own ref/mv/filters. let mut half = vec![0u16; 2 * 4]; mc::predict_maybe_scaled( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(unit_x + 2, pc_mv.1, ss_x(fctx)), mv_to_q4(unit_y, pc_mv.0, ss_y(fctx)), pc_scale, 2, 4, pc_hf, pc_vf, &mut half, fctx, ); for row in 0..4 { buf[row * B4 + 2..row * B4 + 4] .copy_from_slice(&half[row * 2..row * 2 + 2]); } // Left 2x4 half: the piece to the left (an // intra/off-frame neighbour reduces to whole-from-own, // `is_sub8x8_inter`'s rule). let (l_ref, l_mv, l_hf, l_vf) = match left_piece { Some((l_ref, l_mv, l_hf, l_vf)) => (l_ref, l_mv, l_hf, l_vf), None => (pc_ref, pc_mv, pc_hf, pc_vf), }; let Some((l_y, l_u, _)) = ref_planes_deferred(l_ref, refpix) else { continue; }; mc::predict_maybe_scaled( &l_u.data, l_u.width, l_u.true_width, l_u.true_height, mv_to_q4(unit_x, l_mv.1, ss_x(fctx)), mv_to_q4(unit_y, l_mv.0, ss_y(fctx)), mc::scale_factor(l_y.width, frame_width), 2, 4, l_hf, l_vf, &mut half, fctx, ); for row in 0..4 { buf[row * B4..row * B4 + 2] .copy_from_slice(&half[row * 2..row * 2 + 2]); } } else { mc::predict_maybe_scaled( &plane.data, plane.width, plane.true_width, plane.true_height, mv_to_q4(unit_x, pc_mv.1, ss_x(fctx)), mv_to_q4(unit_y, pc_mv.0, ss_y(fctx)), pc_scale, B4, B4, pc_hf, pc_vf, &mut buf, fctx, ); } dst.copy_from_slice(&buf); } out[1] = pred_u; out[2] = pred_v; }; let (pred_cu, pred_cv): (Vec, Vec); let (su, sv) = if recon_deferred(fctx) { push_pred(fctx, build_c); ( 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_c(y, u, v, fctx, &mut built); let [_, bu, bv] = built; (pred_cu, pred_cv) = (bu, bv); (Pred::Inline(&pred_cu, B4), Pred::Inline(&pred_cv, B4)) }; let ctx_mi = (lmi.0, lmi.1 & !1); let ca = neighbours.around_mi_422_chroma(ctx_mi, 8, 4); if skip { push_mc(1, unit_x, unit_y, B4, su, &ZERO_RESIDUAL[..B4 * B4], fctx); push_mc(2, unit_x, unit_y, B4, sv, &ZERO_RESIDUAL[..B4 * B4], fctx); neighbours.record_mi_chroma(ctx_mi, 8, 4, 1, &ZERO_RESIDUAL[..B4 * B4]); neighbours.record_mi_chroma(ctx_mi, 8, 4, 2, &ZERO_RESIDUAL[..B4 * B4]); } else { hit!(CHROMA422_INTER_SUB8_HITS); let (ug, _) = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 1, ca[1], 0, u, unit_x, unit_y, B4, base_q_idx, su, Some(piece_tx_type), None, fctx, )?; let (vg, _) = read_inter_plane( dec, cdfs, TxbSet::Chroma4, scan4, 2, ca[2], 0, v, unit_x, unit_y, B4, base_q_idx, sv, Some(piece_tx_type), None, fctx, )?; neighbours.record_mi_chroma(ctx_mi, 8, 4, 1, &ug); neighbours.record_mi_chroma(ctx_mi, 8, 4, 2, &vg); } } 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-av1-444: at ss 0/0 the group unit does not exist -- each piece // coded its own U/V inside the loop above, and each piece wrote its own // uv neighbour state (inter pieces through `record_inter_rect_mi`'s // is_inter DC stamp, intra pieces through their own per-piece record). // The group-level DC stamp below stays 4:2:0-only: at ss 0/0 it painted // over an intra piece's real `uv_mode` and the next block's // `get_intra_edge_filter_type` lost the smooth neighbour (same class as // [`decode_inter_sub8_split4`]'s tail, frame 19 of the fixture). // 4:2:0 needs the same second half as the split twin: the stamp must run // only when the group unit was painted by the INTER arm below. When the // chroma-reference sub-block was INTRA, its own // [`decode_intra_sub8_leaf`] tail recorded the group cell with the real // `uv_predict_mode`, and this DC stamp ran after it and flattened the // mi-exact cell (class `override-slot-on-one-arm`, this lane's own // 10-bit film gate regression at 1ad7e0fc; port of lane-av1-cfl's // 7c6dad53). lane-av1-422blockhalf: 4:2:2 never takes it either -- the // group unit does not exist there; every chroma-reference piece coded // (and recorded) its own unit inside the loop above. if !chroma_444 && !chroma_422 && !intra_chroma { 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]); // lane-sub8intra: when the chroma-reference sub-block was INTRA it coded // and reconstructed the group's one chroma unit itself. // lane-av1-422blockhalf: 4:2:2 never runs this tail -- the shared group // unit does not exist at ss (1,0); each chroma-reference piece coded its // own U/V TX_4X4 inside the loop above, exactly like the 4:4:4 arm. if !chroma_444 && !chroma_422 && !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, ss_x(fctx)), mv_to_q4(oy, mv.0, ss_x(fctx)), 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) }; 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), )> { // Round 27: this is the function whose mode read carries the block's real // mi (the `EC_MODE_VAL8` rung prints it). The `decode_inter_block` // entry sets the same label from ITS `at`, which is a different block -- // publishing from here is what makes the EC_SYMR mi trustworthy on the // inter path, which is what round 22 got wrong by assuming it was not. crate::msac::SymbolDecoder::set_symr_phase("inter8"); crate::msac::SymbolDecoder::set_symr_mi(leaf_mi.0 as i64, leaf_mi.1 as i64); 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 >> ss_x(fctx), py >> ss_y(fctx)); // 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; // lane-av1-444 / lane-av1-422sub8rect: this 8x8 leaf's chroma plane block // is `ss_size_lookup[BLOCK_8X8][ss_x][ss_y]` -- 4:2:0 BLOCK_4X4 (one // TX_4X4 unit), 4:4:4 BLOCK_8X8 (ONE TX_8X8 unit, `av1_get_max_uv_txsize` // at ss 0/0, measured against aomdec's EC_COEFF on `av1-profile1-444.ivf` // frame 1), and 4:2:2 BLOCK_4X8 (ONE TX_4X8 RECT unit per plane, measured // on the pinned t422 fixture: frame 1 mi(0,0) reads plane 1 tx_size 5 == // TX_4X8 at rng 55168 right after the agreed luma TX_8X8 txb_skip -- the // old `SIDE >> ss_x` square read was the first-divergence defect this // port fixes). let chroma_w: usize = SIDE >> ss_x(fctx); let chroma_h: usize = SIDE >> ss_y(fctx); let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0; let (chroma_set, chroma_scan): (TxbSet, &[u16]) = if chroma_422 { // `get_txsize_entropy_ctx(TX_4X8)`: the rect fills its plane block, // so the tables are the rect set and the SCAN_4X8 walk, exactly the // pairing the key-frame BLOCK_4X8 arm (`decode_block`'s lane-av1-422f // table) reads byte-exact. (TxbSet::ChromaRect8x4, &SCAN_4X8[..]) } else if chroma_w == 8 { (TxbSet::Chroma8, scan8) } else { (TxbSet::Chroma4, scan4) }; let chroma_tx = if chroma_w == 8 { TX8 } else { TX4 }; 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, (2, 2), 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); // lane-av1-llinter: set when a lossless 4:4:4 leaf's chroma went through // the per-unit walk (`read_inter_chroma_lossless`) -- the walk stamps each // TX_4X4 unit's own coefficient context, so the tail's whole-block // `record_mi` gets its chroma half saved/restored around, exactly like // `saved_luma_ctx` does for a `split8` luma. let mut chroma_stamped_per_unit = false; 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, force_integer_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) { crate::msac::SymbolDecoder::set_symr_cdf("comp_group_idx"); 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], ); crate::msac::SymbolDecoder::set_symr_cdf("compound_idx"); let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]); if idx == 1 { (8, 8, 1u8) } else { // lane-av1distwtd: the 8x8 leaf's own // distance-weighted arm, same counter as the // 16x16+ site above. hit!(DIST_WTD_COMP_HITS); 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, 0), mv_to_q4(py, mv0.0, 0), scale0, SIDE, SIDE, h_filter, v_filter, &mut inter0_y, fctx, ); 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, 0), mv_to_q4(py, mv1.0, 0), scale1, SIDE, SIDE, h_filter, v_filter, &mut inter1_y, fctx, ); 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, 0, 0, &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_w * chroma_h]; mc::predict_compound_intermediate( &pu0.data, pu0.width, pu0.true_width, pu0.true_height, mv_to_q4(cpx, mv0.1, ss_x(fctx)), mv_to_q4(cpy, mv0.0, ss_y(fctx)), scale0, chroma_w, chroma_h, h_filter, v_filter, &mut inter0_u, fctx, ); // lane-av1444altref r3: this leaf warped its LUMA // intermediates (`warp0_c`/`warp1_c` above) but left both // CHROMA arms translational. libaom warps per PLANE: // `build_inter_predictors_8x8_and_bigger` // (reconinter_template.inc:230) runs the whole // `av1_init_warp_params` + `av1_warp_plane` pair for every // plane of the block, chroma included, with // `pd->subsampling_x/y` and the plane's own origin/extent. // A global-motion (warp) 8x8 leaf at 4:4:4 therefore had // its chroma predicted from the block's top-left // translation instead of the affine map -- the MV is the // affine's local derivative, so the two agree at the // block's top-left corner and drift apart toward its // bottom-right, which is exactly the measured signature // (a bottom-right-biased +/-1 gradient in 8x8 chroma // cells of the 4:4:4 altref cell `ll444_c`, luma exact). // `warp_plane_allowed` mirrors `av1_init_warp_params`'s // `block_width < 8 || block_height < 8` bail, so a // subsampled plane's sub-8 chroma block stays // translational exactly as the 16x16+ arm above does. if let Some(wp) = &warp0_c { if warp_plane_allowed(chroma_w, 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_w as i32, chroma_h as i32, chroma_w as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, fctx, ); } } let mut inter1_u = vec![0i32; chroma_w * chroma_h]; mc::predict_compound_intermediate( &pu1.data, pu1.width, pu1.true_width, pu1.true_height, mv_to_q4(cpx, mv1.1, ss_x(fctx)), mv_to_q4(cpy, mv1.0, ss_y(fctx)), scale1, chroma_w, chroma_h, h_filter, v_filter, &mut inter1_u, fctx, ); if let Some(wp) = &warp1_c { if warp_plane_allowed(chroma_w, 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_w as i32, chroma_h as i32, chroma_w as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, fctx, ); } } let mut pred_u = refill(std::mem::take(&mut out[1]), chroma_w * chroma_h); if let Some(mask_y) = mask_y { mc::blend_masked_compound( &inter0_u, &inter1_u, mask_y, SIDE, chroma_w, chroma_h, ss_x(fctx), ss_y(fctx), &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_w * chroma_h]; mc::predict_compound_intermediate( &pv0.data, pv0.width, pv0.true_width, pv0.true_height, mv_to_q4(cpx, mv0.1, ss_x(fctx)), mv_to_q4(cpy, mv0.0, ss_y(fctx)), scale0, chroma_w, chroma_h, h_filter, v_filter, &mut inter0_v, fctx, ); // lane-av1444altref r3: the V arm's missing per-plane warp, // same defect and same fix as U above. if let Some(wp) = &warp0_c { if warp_plane_allowed(chroma_w, 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_w as i32, chroma_h as i32, chroma_w as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, fctx, ); } } let mut inter1_v = vec![0i32; chroma_w * chroma_h]; mc::predict_compound_intermediate( &pv1.data, pv1.width, pv1.true_width, pv1.true_height, mv_to_q4(cpx, mv1.1, ss_x(fctx)), mv_to_q4(cpy, mv1.0, ss_y(fctx)), scale1, chroma_w, chroma_h, h_filter, v_filter, &mut inter1_v, fctx, ); if let Some(wp) = &warp1_c { if warp_plane_allowed(chroma_w, 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_w as i32, chroma_h as i32, chroma_w as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, fctx, ); } } let mut pred_v = refill(std::mem::take(&mut out[2]), chroma_w * chroma_h); if let Some(mask_y) = mask_y { mc::blend_masked_compound( &inter0_v, &inter1_v, mask_y, SIDE, chroma_w, chroma_h, ss_x(fctx), ss_y(fctx), &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_w, off: 0, }, Pred::Cur { plane: 2, stride: chroma_w, 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_w), Pred::Inline(&pred_v, chroma_w), ) }; 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); // lane-av1-422sub8rect: the plane block is the (chroma_w, // chroma_h) rect at 4:2:2 -- the recorded write is // stride `chroma_w`, full `chroma_h` rows. push_mc_rect( 1, cpx, cpy, chroma_w, chroma_w, chroma_h, su, &ZERO_RESIDUAL[..chroma_w * chroma_h], fctx, ); push_mc_rect( 2, cpx, cpy, chroma_w, chroma_w, chroma_h, sv, &ZERO_RESIDUAL[..chroma_w * chroma_h], fctx, ); luma_grid = Grid::Zero(SIDE * SIDE); u_grid = Grid::Zero(chroma_w * chroma_h); v_grid = Grid::Zero(chroma_w * chroma_h); } else { let around = neighbours.around_mi(leaf_mi, 8); // lane-av1-422sub8rect: the 4:2:2 chroma unit is the // TX_4X8 rect -- its `txb_skip_ctx` reads per chroma // 4-px cell ([`Neighbours::around_mi_422_chroma`], the // key-frame BLOCK_4X8 arm's own context walk), and the // coefficients go through the inter rect reader with the // inherited luma tx type. let chroma_around = if chroma_422 { neighbours.around_mi_422_chroma(leaf_mi, 8, 8) } else { around }; 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; // Lossless 8x8 inter leaf: `av1_get_tx_size` returns // TX_4X4 for EVERY plane of a lossless block // (`decodeframe.c:1197`), so the chroma plane block is a // raster of TX_4X4 units whenever it is BIGGER than one -- // 4:4:4's 8x8 (2x2) and 4:2:2's 4x8 (1x2). Only 4:2:0's // 4x4 keeps the single-unit read, where // `plane_bsize == txsize_to_bsize[tx_size]` puts // `get_txb_ctx`'s ctx_offset at 7. if lossless(fctx) && (chroma_w > 4 || chroma_h > 4) && !mono(fctx) { let (ug, vg) = leaf8_inter_chroma_lossless( dec, cdfs, neighbours, u, v, su, sv, leaf_mi, (cpx, cpy), (chroma_w, chroma_h), chroma_w, base_q_idx, fctx, )?; u_grid = ug; v_grid = vg; chroma_stamped_per_unit = true; } else { u_grid = if chroma_422 { read_inter_plane_rect( dec, cdfs, chroma_set, (chroma_w, chroma_h), chroma_w, 1, chroma_around[1], mode_for_tx, u, cpx, cpy, su, Some(luma_tx_type), None, fctx, )? .0 } else { read_inter_plane( dec, cdfs, chroma_set, chroma_scan, 1, chroma_around[1], mode_for_tx, u, cpx, cpy, chroma_w, base_q_idx, su, Some(luma_tx_type), None, fctx, )? .0 }; v_grid = if chroma_422 { read_inter_plane_rect( dec, cdfs, chroma_set, (chroma_w, chroma_h), chroma_w, 2, chroma_around[2], mode_for_tx, v, cpx, cpy, sv, Some(luma_tx_type), None, fctx, )? .0 } else { read_inter_plane( dec, cdfs, chroma_set, chroma_scan, 2, chroma_around[2], mode_for_tx, v, cpx, cpy, chroma_w, 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). // lane-lossless3: `!skip` too. A SKIP block codes no coefficients and so // publishes nothing per transform unit, and on a LOSSLESS frame // `read_block_tx_size` hands back 4x4 leaves for a skip block as well // (libaom's `read_tx_size` returns TX_4X4 before it reads anything), so // `split8` is true over an UNTOUCHED band -- the restore then put the // previous block's levels back over the zeros `record_mi` had just // written, where libaom runs `av1_reset_entropy_context`. Class // [[override-slot-on-one-arm]]: a save/restore is only valid on the arm // that actually wrote the per-TU state. let saved_luma_ctx = (split8 && !skip).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, ); let saved_chroma_ctx = chroma_stamped_per_unit.then(|| { ( [ [neighbours.left[leaf_mi.0][1], neighbours.left[leaf_mi.0][2]], [ neighbours.left[leaf_mi.0 + 1][1], neighbours.left[leaf_mi.0 + 1][2], ], ], [ [ neighbours.above[leaf_mi.1][1], neighbours.above[leaf_mi.1][2], ], [ neighbours.above[leaf_mi.1 + 1][1], neighbours.above[leaf_mi.1 + 1][2], ], ], ) }); neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); if let Some((left, above)) = saved_chroma_ctx { // The walk's per-unit stamps are the block's real chroma // coefficient contexts (`av1_set_contexts` per TX_4X4 // unit); put them back over `record_mi`'s composed state. for (cell, uv) in left.into_iter().enumerate() { neighbours.left[leaf_mi.0 + cell][1] = uv[0]; neighbours.left[leaf_mi.0 + cell][2] = uv[1]; } for (cell, uv) in above.into_iter().enumerate() { neighbours.above[leaf_mi.1 + cell][1] = uv[0]; neighbours.above[leaf_mi.1 + cell][2] = uv[1]; } } 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, force_integer_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; if !not_new { crate::census::mode(0); } 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; if !not_zero { crate::census::mode(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; crate::census::mode(if nearest { 2 } else { 3 }); 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 { crate::msac::SymbolDecoder::set_symr_cdf("interintra"); 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 { crate::msac::SymbolDecoder::set_symr_cdf("motion_mode"); 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); } } // lane-av112bitw: same lift as the 16x16+ leaf -- a local // `WARPED_CAUSAL` projection or a global model both leave // `warp_params` set here; the 12-bit refusal that stood here is // lifted with the same witness (`warp::warp_round_0` moved the // filter's shifts; the same stream decodes byte-exact vs ffmpeg). 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, ss_x(fctx), ss_y(fctx), chroma_w, 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_w * chroma_h); let mut pred_v = refill(std::mem::take(&mut out[2]), chroma_w * chroma_h); // 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_w, dim_h), dst) in [ (sref_y, px, py, (SIDE, SIDE), &mut pred_y), (sref_u, cpx, cpy, (chroma_w, chroma_h), &mut pred_u), (sref_v, cpx, cpy, (chroma_w, chroma_h), &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, if luma { 0 } else { ss_x(fctx) }), mv_to_q4(y, mv.0, if luma { 0 } else { ss_y(fctx) }), dim_w, dim_h, 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, if luma { 0 } else { ss_x(fctx) }), mv_to_q4(y, mv.0, if luma { 0 } else { ss_y(fctx) }), luma_scale, dim_w, dim_h, 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 bail-out is on BOTH // extents (`block_height < 8 || block_width < 8`, // reconinter.c:61): an 8x8 leaf's chroma plane block is under 8 // at any subsampled format (4:2:0 4x4, 4:2:2 4x8), so it is // predicted translationally even when the luma warps; 4:4:4's // 8x8 chroma warps with the luma, and a rect chroma block 8 wide // but under 8 high (4:2:2 BLOCK_8X4) stays translational too. // lane-av1444altref r3: this arm tested only the width. if warp_plane_allowed(chroma_w, chroma_h) { 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_w as i32, chroma_h as i32, chroma_w as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, 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_w as i32, chroma_h as i32, chroma_w as i32, ss_x(fctx) as i32, ss_y(fctx) as i32, 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, 0, 0, ii, wedge_mask, &mut pred_y, fctx, ); interintra_blend( u, cpx, cpy, chroma_w, chroma_h, chroma_w, ss_x(fctx), ss_y(fctx), ii, wedge_mask, &mut pred_u, fctx, ); interintra_blend( v, cpx, cpy, chroma_w, chroma_h, chroma_w, ss_x(fctx), ss_y(fctx), 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_w, off: 0, }, Pred::Cur { plane: 2, stride: chroma_w, 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_w), Pred::Inline(&pred_v, chroma_w), ) }; 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); // lane-av1-422sub8rect: the plane block is the (chroma_w, // chroma_h) rect at 4:2:2 -- the recorded write is stride // `chroma_w`, full `chroma_h` rows. push_mc_rect( 1, cpx, cpy, chroma_w, chroma_w, chroma_h, su, &ZERO_RESIDUAL[..chroma_w * chroma_h], fctx, ); push_mc_rect( 2, cpx, cpy, chroma_w, chroma_w, chroma_h, sv, &ZERO_RESIDUAL[..chroma_w * chroma_h], fctx, ); luma_grid = Grid::Zero(SIDE * SIDE); u_grid = Grid::Zero(chroma_w * chroma_h); v_grid = Grid::Zero(chroma_w * chroma_h); } else { let around = neighbours.around_mi(leaf_mi, 8); // lane-av1-422sub8rect: the 4:2:2 chroma unit is the TX_4X8 // rect -- its `txb_skip_ctx` reads per chroma 4-px cell // ([`Neighbours::around_mi_422_chroma`], the key-frame // BLOCK_4X8 arm's own context walk), and the coefficients go // through the inter rect reader with the inherited luma tx // type. let chroma_around = if chroma_422 { neighbours.around_mi_422_chroma(leaf_mi, 8, 8) } else { around }; 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; // Lossless 8x8 inter leaf, compound twin of the single-ref arm // above -- same per-axis plane block (4:4:4 8x8, 4:2:2 4x8) and // the same "bigger than one TX_4X4" gate. if lossless(fctx) && (chroma_w > 4 || chroma_h > 4) && !mono(fctx) { let (ug, vg) = leaf8_inter_chroma_lossless( dec, cdfs, neighbours, u, v, su, sv, leaf_mi, (cpx, cpy), (chroma_w, chroma_h), chroma_w, base_q_idx, fctx, )?; u_grid = ug; v_grid = vg; chroma_stamped_per_unit = true; } else { u_grid = if chroma_422 { read_inter_plane_rect( dec, cdfs, chroma_set, (chroma_w, chroma_h), chroma_w, 1, chroma_around[1], mode_for_tx, u, cpx, cpy, su, Some(luma_tx_type), None, fctx, )? .0 } else { read_inter_plane( dec, cdfs, chroma_set, chroma_scan, 1, chroma_around[1], mode_for_tx, u, cpx, cpy, chroma_w, base_q_idx, su, Some(luma_tx_type), None, fctx, )? .0 }; v_grid = if chroma_422 { read_inter_plane_rect( dec, cdfs, chroma_set, (chroma_w, chroma_h), chroma_w, 2, chroma_around[2], mode_for_tx, v, cpx, cpy, sv, Some(luma_tx_type), None, fctx, )? .0 } else { read_inter_plane( dec, cdfs, chroma_set, chroma_scan, 2, chroma_around[2], mode_for_tx, v, cpx, cpy, chroma_w, base_q_idx, sv, Some(luma_tx_type), None, fctx, )? .0 }; } } } else { crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); 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 has_chroma = !mono(fctx); // lane-av1-llintra8: `read_intra_mode_uv` (decodemv.c:145) picks the // uv CDF row by `is_cfl_allowed` (cfl.h:23) -- at LOSSLESS that is // "the chroma plane block is BLOCK_4X4" (cfl.h:29), for this // BLOCK_8X8 leaf only at 4:2:0. The 4:4:4 lossless leaf reads the // 13-symbol `uv_mode_no_cfl` alphabet; the unconditional CFL row // consumed a different partition than aomdec at the leaf's own // uv_mode symbol (class wrong-alphabet-same-value) and desynced // every stream that reached the leaf's lossless chroma walk below. // 4:2:0 and every non-lossless partition keep the CFL row // (`cfl_allowed_px` answers true exactly as before). let uv_mode = if !has_chroma { DC_PRED } else if cfl_allowed_px(SIDE, SIDE, fctx) { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_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 has_chroma && 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, fctx); // 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 = has_chroma && 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, palette_onscreen(rmi, cmi, SIDE, SIDE, fctx), 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, ss)` at the sequence's own // subsampling: BLOCK_4X4 at 4:2:0, BLOCK_8X8 at 4:4:4, and at // 4:2:2 the BLOCK_4X8 plane block (lane-av1-422sub8rect). let on = palette_onscreen_uv( (SIDE, SIDE), palette_onscreen(rmi, cmi, SIDE, SIDE, fctx), (chroma_w, chroma_h), (ss_x(fctx), ss_y(fctx)), ); let map = decode_color_index_map_wh(dec, cdfs, n, chroma_w, chroma_h, on, 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); } // lane-av1-422sub8rect: the plane block is the (chroma_w, // chroma_h) rect at 4:2:2 -- the recorded prediction/write uses // the rect push. 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, ); luma_grid = Grid::Zero(SIDE * SIDE); u_grid = Grid::Zero(chroma_w * chroma_h); v_grid = Grid::Zero(chroma_w * chroma_h); } 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)); // lane-av1-422sub8rect: at 4:2:2 the plane block is the BLOCK_4X8 // rect and the key-frame arm's own reader applies -- one // TX_4X8 `ChromaRect8x4` unit per plane through // [`read_rect_chroma_unit`] with the per-chroma-cell context // walk ([`Neighbours::around_mi_422_chroma`], the // lane-av1-422f model this leaf's key-frame twin proves // byte-exact). 4:2:0/4:4:4 keep the square [`read_plane`] read. let (chroma_around_u, chroma_around_v) = if chroma_422 { let ca = neighbours.around_mi_422_chroma(leaf_mi, 8, 8); (ca[1], ca[2]) } else { (around[1], around[2]) }; // lane-av1-llintra8: lossless codes TX_4X4 on EVERY plane // (`av1_get_tx_size`, blockd.h:1383), so this intra leaf's chroma // plane block is a raster of TX_4X4 units per plane, plane-major // -- the same per-unit walk the >=16x16 intra-in-inter block // runs, not one TX_8X8 unit (whose WHT hits `TxParams::run`'s // `(8, 8) != (4, 4)` lossless assert). The plane block is // PER-AXIS, `av1_ss_size_lookup[BLOCK_8X8][ss_x][ss_y]`: 8x8 at // 4:4:4 (2x2 units) and 4x8 at 4:2:2 (1x2), so both walk here and // only 4:2:0's 4x4 keeps the single-unit read in the `else` // below (`plane_bsize == txsize_to_bsize[tx_size]`, ctx_offset 7). // The walk stamps each unit's own coefficient context // (`record_mi_chroma` inside it), so the tail's whole-block // `record_mi` gets its chroma half saved/restored around -- // the same rule the INTER arms' // `leaf8_inter_chroma_lossless` obeys. if lossless(fctx) && (chroma_w > 4 || chroma_h > 4) && !mono(fctx) { let (mut uo, mut vo) = (Vec::new(), Vec::new()); read_intra_chroma_lossless( dec, cdfs, neighbours, u, v, leaf_mi, (px, py), (cpx, cpy), SIDE, (chroma_w, chroma_h), (0, 0), (chroma_w, chroma_h), chroma_w, reach, (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, base_q_idx, &mut uo, &mut vo, fctx, )?; u_grid = if uo.is_empty() { Grid::Zero(chroma_w * chroma_h) } else { Grid::Own(uo) }; v_grid = if vo.is_empty() { Grid::Zero(chroma_w * chroma_h) } else { Grid::Own(vo) }; chroma_stamped_per_unit = true; hit!(LLINTRA8_CHROMA_WALK_HITS); } else { if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); } u_grid = if chroma_422 { read_rect_chroma_unit( dec, cdfs, chroma_set, chroma_scan, chroma_w, chroma_h, 1, chroma_around_u, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, base_q_idx, None, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), smooth_neighbor_uv, fctx, )? } else { read_plane( dec, cdfs, chroma_set, chroma_scan, 1, chroma_around_u, mode, uv_predict_mode, angle_delta_uv, reach, u, cpx, cpy, chroma_w, 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 = if chroma_422 { read_rect_chroma_unit( dec, cdfs, chroma_set, chroma_scan, chroma_w, chroma_h, 2, chroma_around_v, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, base_q_idx, None, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), smooth_neighbor_uv, fctx, )? } else { read_plane( dec, cdfs, chroma_set, chroma_scan, 2, chroma_around_v, mode, uv_predict_mode, angle_delta_uv, reach, v, cpx, cpy, chroma_w, chroma_tx, 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. // lane-lossless3: `!skip` too. A SKIP block codes no coefficients and so // publishes nothing per transform unit, and on a LOSSLESS frame // `read_block_tx_size` hands back 4x4 leaves for a skip block as well // (libaom's `read_tx_size` returns TX_4X4 before it reads anything), so // `split8` is true over an UNTOUCHED band -- the restore then put the // previous block's levels back over the zeros `record_mi` had just // written, where libaom runs `av1_reset_entropy_context`. Class // [[override-slot-on-one-arm]]: a save/restore is only valid on the arm // that actually wrote the per-TU state. let saved_luma_ctx = (split8 && !skip).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, ); let saved_chroma_ctx = chroma_stamped_per_unit.then(|| { ( [ [neighbours.left[leaf_mi.0][1], neighbours.left[leaf_mi.0][2]], [ neighbours.left[leaf_mi.0 + 1][1], neighbours.left[leaf_mi.0 + 1][2], ], ], [ [ neighbours.above[leaf_mi.1][1], neighbours.above[leaf_mi.1][2], ], [ neighbours.above[leaf_mi.1 + 1][1], neighbours.above[leaf_mi.1 + 1][2], ], ], ) }); neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); if let Some((left, above)) = saved_chroma_ctx { // The walk's per-unit stamps are the block's real chroma coefficient // contexts (`av1_set_contexts` per TX_4X4 unit); put them back over // `record_mi`'s one composed state. for (cell, uv) in left.into_iter().enumerate() { neighbours.left[leaf_mi.0 + cell][1] = uv[0]; neighbours.left[leaf_mi.0 + cell][2] = uv[1]; } for (cell, uv) in above.into_iter().enumerate() { neighbours.above[leaf_mi.1 + cell][1] = uv[0]; neighbours.above[leaf_mi.1 + cell][2] = uv[1]; } } // 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, // lane-intertx: this frame header's own `reduced_tx_set` (spec 5.9.2) -- // see [`decode_inter_frame_tile_lr`]'s parameter. Same stale-header // class as `tx_select` below. reduced_tx_set: 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, reduced_tx_set, tx_select, &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, // `enable_filter_intra`: as the `false`s beside it, this convenience // entry names a stream written without the sequence bit (lane-fintra). switchable_motion_mode, false, false, DeltaParams::default(), 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, // lane-intertx: this frame header's own `reduced_tx_set` (spec 5.9.2). // The wrapper used to hard-code `true` ("the tests all code the reduced // sets") -- true until the widened inter search put 1-D/DTT types on // `reduced_tx_set = 0` frames' inter luma, whose CHROMA then inherits // the type against this very bit // ([`reduce_inherited_chroma_tx_type`]): guessing `true` mis-derives // every inherited chroma type and desyncs the tile (class: test asserts // against a stale header, next instance). reduced_tx_set: 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, // lane-fintra: see [`decode_inter_frame_tiles_lr`]'s own parameter. enable_filter_intra: bool, // lane-deltaq: see [`decode_inter_frame_tiles_lr`]'s own parameter. delta: DeltaParams, 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, // lane-intertx: this frame's own bit, not the hardcoded `true` -- // see the parameter's note above. reduced_tx_set, tx_select, lr, initial_cdfs, sign_bias, allow_screen_content_tools, switchable_motion_mode, allow_warped_motion, enable_filter_intra, delta, 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, // lane-txi: this frame header's own `reduced_tx_set` bit. It used to be // hardcoded `true` at the call below -- the encoder's own trial decode of // the tile it just wrote then read every luma `tx_type` out of the // reduced alphabet whatever the header said (class: a header bit a raw // tile decode cannot guess, the same one `tx_select` carries). reduced_tx_set: 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, // lane-fintra: this sequence header's own `enable_filter_intra` bit (spec // 5.5.2). Hard-coded `false` here until this lane -- the same stale-header // class as `switchable_motion_mode`/`allow_warped_motion` above: the // encoder's own trial decode desyncs at the first intra-in-inter DC_PRED // block the moment its sequence header sets the bit. enable_filter_intra: bool, // lane-deltaq: this frame header's own `delta_q_params`/`delta_lf_params` // (spec 5.9.17/5.9.18) -- the same stale-header class as the three // parameters above. Hard-coded `DeltaParams::default()` here until this // lane, which desyncs the encoder's own trial decode at the first // superblock the moment its header sets `delta_q_present`. delta: DeltaParams, 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], reduced_tx_set, tx_select, switchable_motion_mode, allow_warped_motion, allow_screen_content_tools, delta, enable_filter_intra, 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. // lane-hdrlossless VERDICT: this is NOT a spec-conformant guard -- libaom // ACCEPTS a reference of a different size and scales BOTH axes // (`av1_setup_scale_factors_for_frame` + `av1_is_valid_scale`, // `decodeframe.c:5089-5099`; only an out-of-range scale errors). We port // only WIDTH scaling (superres), so a height mismatch is a named // capability gap. No aomenc witness reaches it: superres changes width // alone, and the only both-axes route (dynamic resize) stops earlier on // this decoder. See `lanes/av1hdr.report.md` §4.3. 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 (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx)); let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx)); let mut u = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), width: cw, height: ch, true_width: ctw, true_height: cth, tile_x0: 0, tile_y0: 0, tile_x1: cw, tile_y1: ch, }; let mut v = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), width: cw, height: ch, true_width: ctw, true_height: cth, tile_x0: 0, tile_y0: 0, tile_x1: cw, tile_y1: ch, }; 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::with_ss( lr, superres(fctx).map_or(frame_width, |(w, _)| w), frame_height, fctx.subsampling_x.get(), fctx.subsampling_y.get(), ); // 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(|| { // lane-av1lrflush: counted unconditionally (unlike `PIPE_FRAMES` // below, which is `EC_AV1_WAVE_STATS`-gated) so a gate can prove a // pipelined arm actually took the pipeline even when // `filter_threads()`'s once-per-process env read was already cached // by an earlier test in the same binary. PIPELINE_TAKEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); 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-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets // it codes every symbol against the tables it started with. dec.set_cdf_update(!cdf_update_disabled(fctx)); crate::census::register_cdfs(&cdfs); // 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 * 4) >> ss_x(fctx), (mi_row0 as usize * 4) >> ss_y(fctx), ((mi_col1 as usize * 4) >> ss_x(fctx)).min(u.width), ((mi_row1 as usize * 4) >> ss_y(fctx)).min(u.height), ); v.set_tile_origin( (mi_col0 as usize * 4) >> ss_x(fctx), (mi_row0 as usize * 4) >> ss_y(fctx), ((mi_col1 as usize * 4) >> ss_x(fctx)).min(v.width), ((mi_row1 as usize * 4) >> ss_y(fctx)).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, // True mode-info units: a 64px superblock is 8, and `SB_MI` is 16. // `read_lr` divides by the restoration-unit size (a real pixel count), // so it is the one consumer that needs the absolute origin in real mi. // The half-mi convention these arguments used to carry only worked // while `read_lr` also counted in half-mi -- the two cancelled. sb_r * (SB_MI / 2), sb_c * (SB_MI / 2), SB_MI / 2, 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 ); } // lane-av1tilerows: this rung printed the RAW 32-grid // index (`r32`, `c32`) into its `mi_row=`/`mi_col=` // fields — a factor of `BLOCK_MI` (8) off — while the // `TRACE part32_pre` line immediately above and the // `EC_AV1_TRACE` line immediately below both print // `r32 * BLOCK_MI` correctly. A rung whose coordinates // are wrong is worse than no rung: it cannot be paired // against libaom's per-level `EC_PART_VAL` dump, which // is the only way to locate a partition-walk // divergence. Behaviour-free: env-gated print only. if crate::envflags::env_flag!("EC_TRACE_PART") { eprintln!( "EC_PART mi_row={} mi_col={} bsize=9 ctx={} rng={}", r32 * BLOCK_MI, c32 * BLOCK_MI, 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; } // lane-av1-444: at 4:4:4 every strip is // its own chroma reference // (`is_chroma_reference`: no mi parity // test at ss 0/0 and the strip's 16x4 / // 4x16 chroma block is already >= 4x4), // so there is no pair: each strip codes // and predicts its own chroma from its // own motion (`prev` = None). // lane-av1-422l: a strip pairs along its // OWN subsampled axis -- horz strips pair // on rows (no pair once ss_y == 0: chroma // has no row parity, every 16x4 strip is // its own reference, exactly the intra // strip arm's `else if ss_y(fctx) == 0`); // vert strips pair on columns (ss_x == 0 // => every strip self-pairs, 4:2:2 keeps // the 4:2:0 column pairing -- a VERT_4 // 4x16 strip's `ss_size_lookup` chroma // at ss (1,0) is BLOCK_INVALID, so only // the pair shape can ever be coded). let strip_has_chroma = if horz { i % 2 == 1 || ss_y(fctx) == 0 } else { i % 2 == 1 || ss_x(fctx) == 0 }; let pair_mi = if !strip_has_chroma || (if horz { ss_y(fctx) == 0 } else { ss_x(fctx) == 0 }) { 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 && (if horz { ss_y(fctx) == 1 } else { ss_x(fctx) == 1 }) { 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 ec_dbg_pre = dec.debug_state().0; let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); if std::env::var_os("EC_DBG_SUB8").is_some() { let ec_dbg_post = dec.debug_state().0; eprintln!( "EC_DBG b8 mi=({},{}) ctx={leaf_ctx} val={part8} pre={ec_dbg_pre} post={ec_dbg_post}", leaf_mi.0, leaf_mi.1 ); } 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-av1444edge: the inter-frame path's mi-aligned pre-loop-filter // dump, the rung the key-frame path has always had (see // `dump_prefilter_wide`). Placed beside the padded `EC_AV1_PREFILT_DUMP` // above, i.e. before the filter pipeline is released, so the two agree on // the point in the sequence they sample. dump_prefilter_wide(&y, &u, &v); // 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 { // lane-av1422filter: chroma band geometry follows the frame's own // ss_y (see the keyframe path's note) -- 4:2:2 stripes full-height. lr_active.then(|| { ( plane_snapshot(&y, 0), plane_snapshot(&u, ss_y(fctx) as u32), plane_snapshot(&v, ss_y(fctx) as u32), ) }) }; // 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, None, None, ); } 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) = ( round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx)), round_ss(uw, ss_x(fctx)), ); 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, round_ss(true_width, ss_x(fctx)), round_ss(true_height, ss_y(fctx)), ), v: crop( &v, round_ss(true_width, ss_x(fctx)), round_ss(true_height, ss_y(fctx)), ), }) } else { None } }); Ok(( Picture { width: fw, height: fh, y: crop_owned(y, fw, fh), u: crop_owned(u, round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx))), v: crop_owned(v, round_ss(fw, ss_x(fctx)), round_ss(fh, ss_y(fctx))), }, result_cdfs, motion_field, )) } #[cfg(test)] mod tests { /// lane-av1chrtx: [`covering_leaf_tx_type`] resolves a chroma unit's /// `tx_type` from the luma leaf covering the unit's OWN quadrant, and /// reports "no leaf there" as `None` so the caller can fall back to the /// block-level type. Both halves are load-bearing: the 128 mu-chunk tail, /// the 4:4:4 four-unit arms and `read_inter_rect_chroma` all read the /// `None` arm as "this block coded a single luma unit". #[test] fn covering_leaf_tx_type_picks_the_leaf_under_the_unit_or_reports_none() { use TxType::*; // A 32x64 strip's five-leaf tree, in decode order: one 32x32 leaf // over mi rows 0..8, then 16x16 leaves. (row, col) are MI relative // to the block, (tw, th) are PIXELS, MI == 4. let leaves = [ (0usize, 0usize, 32usize, 32usize, Idtx), (8, 0, 16, 16, VDct), (8, 4, 16, 16, DctDct), (12, 0, 16, 16, HDct), (12, 4, 16, 16, VDct), ]; // The TOP chroma unit (its own mi cell (0,0)) sits over the 32x32 // leaf; the LOWER one (mi (8,0)) over the first 16x16 leaf. The // block-level type is the first leaf's, so only the second read // differs -- exactly the condition the gate's DIFF counter counts. assert_eq!(covering_leaf_tx_type(&leaves, (0, 0)), Some(Idtx)); assert_eq!(covering_leaf_tx_type(&leaves, (8, 0)), Some(VDct)); // Interior cells resolve the same leaf as the cell's top-left: the // lookup is a rectangle containment test, not a raster position. assert_eq!(covering_leaf_tx_type(&leaves, (11, 3)), Some(VDct)); assert_eq!(covering_leaf_tx_type(&leaves, (12, 4)), Some(VDct)); // The bottom-right corner of the last leaf, and the mi cell just // past the block's own extent, must not fall into a neighbour. assert_eq!(covering_leaf_tx_type(&leaves, (15, 7)), Some(VDct)); assert_eq!(covering_leaf_tx_type(&leaves, (16, 0)), None); assert_eq!(covering_leaf_tx_type(&leaves, (0, 8)), None); // A block with no var-tx tree (one coded luma unit) has no leaves at // all: the caller's block-level fallback is the answer, and the // resolver must say so rather than guess. assert_eq!(covering_leaf_tx_type(&[], (0, 0)), None); } /// lane-av1422warp r33: the OBMC pair-merge snap must move the READ to /// libaom's position, not the reported offset. /// /// libaom `obmc.h:44-46`: /// ```c /// if (mi_step == 1) { /// above_mi_col &= ~1; // snap the INDEX, unconditional /// above_mi = prev_row_mi + above_mi_col + 1; // read at snap + 1 /// mi_step = 2; /// } /// ``` /// and the relative offset handed to /// `av1_setup_build_prediction_by_above_pred` is /// `above_mi_col - mi_col` **after** the snap, which is `-1` at an odd /// `mi_col`. An earlier fix clamped the snapped INDEX to `mi_col` to /// stop that subtraction underflowing, which silenced the underflow and /// in exchange read the neighbour one column RIGHT of libaom's and then /// stepped past the block's own right edge. /// /// The grid here carries DISTINGUISHABLE neighbours at the pair's even /// half, its odd half, and the column to the right of the pair, so the /// test fails if the walk reads any position but the odd half. It is the /// snapped READ this pins -- and no stream in the corpus exercises it /// (a1.obu's 1338 traced OBMC neighbours are byte-identical before and /// after the fix, because its 4-wide pair never starts on an odd edge), /// so nothing else covers this branch. #[test] fn the_obmc_pair_merge_snap_reads_libaoms_neighbour_not_one_to_the_right() { const NAME: &str = "the_obmc_pair_merge_snap_reads_libaoms_neighbour_not_one_to_the_right"; // `ref_frame` 1 == LAST_FRAME, which is what `is_inter` consumers // expect; the MV makes each cell individually identifiable. let cell = |mv: (i16, i16), size: u8| MiInfo { is_inter: true, ref_frame: 1, ref_frame1: 0, mv: mv, mv1: (0, 0), is_new_mv: true, size, size_h: size, is_global_mv0: false, is_global_mv1: false, }; const EVEN: (i16, i16) = (10, 10); const ODD: (i16, i16) = (20, 20); const RIGHT: (i16, i16) = (30, 30); // --- the above walk, at an ODD `mi_col` --- let mut grid = crate::mvstack::MiGrid::new(16, 16); // The block under test sits at mi_col 5; the neighbour row is 4. // A 4-wide inter cell at the ODD half (5) is what forces // `mi_step == 1` and therefore the pair merge. grid.set(4, 4, cell(EVEN, 1)); grid.set(4, 5, cell(ODD, 1)); grid.set(4, 6, cell(RIGHT, 4)); // one column RIGHT of the pair // `bw4 == 2` so `AOMMIN(xd->width, mi_step)` is the pair's own 2 // rather than clipped to a 1-wide block's 1. let nb = overlappable_above(&grid, 5, 5, 2, 16, 4); assert!( !nb.is_empty(), "{NAME}: the above walk found no neighbour at all" ); let (off4, span4, info, src4) = nb[0]; assert_eq!( info.mv, ODD, "{NAME}: the above pair merge read the wrong neighbour -- libaom \ snaps the column and reads snap+1, which is the ODD half" ); assert_ne!( info.mv, RIGHT, "{NAME}: the clamp moved the snapped index onto mi_col, so the \ walk read one column RIGHT of libaom" ); assert_eq!(src4, 0, "{NAME}: the read column's relative offset"); assert_eq!(span4, 2, "{NAME}: the pair steps over BOTH halves"); // libaom's `above_mi_col - mi_col` is -1 here; this tuple is // `usize`, so the reported offset saturates to 0 rather than // wrapping to `usize::MAX`. The snap is what the read depends on. assert_eq!( off4, 0, "{NAME}: the reported offset must saturate, not wrap" ); // --- the left walk, at an ODD `mi_row`: the same shape --- let mut grid = crate::mvstack::MiGrid::new(16, 16); grid.set(4, 4, cell(EVEN, 1)); grid.set(5, 4, cell(ODD, 1)); grid.set(6, 4, cell(RIGHT, 4)); let nb = overlappable_left(&grid, 5, 5, 2, 16, 4); assert!( !nb.is_empty(), "{NAME}: the left walk found no neighbour at all" ); let (off4, span4, info, src4) = nb[0]; assert_eq!( info.mv, ODD, "{NAME}: the left pair merge read the wrong neighbour -- libaom \ snaps the row and reads snap+1, which is the ODD half" ); assert_ne!( info.mv, RIGHT, "{NAME}: the clamp moved the snapped row onto mi_row, so the walk \ read one row BELOW libaom" ); assert_eq!(src4, 0, "{NAME}: the read row's relative offset"); assert_eq!(span4, 2, "{NAME}: the pair steps over BOTH halves"); assert_eq!( off4, 0, "{NAME}: the reported offset must saturate, not wrap" ); } /// 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) } /// lane-av1422stripwrite: the reference chroma shape is read back off the /// stored plane's own sample count, so the counts the PRODUCER writes /// (`round_ss` crops, `decode.rs:25806`) must route back to the shape /// they came from. A floor half-width here passes every even-width case /// -- the pinned fixture's 256-wide frame included -- and silently drops /// every odd-width 4:2:2 reference into the 4:2:0 arm, which is the /// exact defect this lane fixed, one dimension over. So the table below /// is driven off `round_ss`, not off hand-written numbers, and sweeps /// odd and even widths. /// /// lane-av1odd440: the 4:2:0 arm's expectation is the PRODUCER's crop, /// `round_ss(w, 1) x round_ss(h, 1)`, not the `(w / 2, h / 2)` floor it /// used to name -- the floor under-declares every odd-dimension 4:2:0 /// reference, which is the shape the pinned `420_odd65x65_key.obu` cell /// finally makes reachable (see [`ref_chroma_shape`]). For every EVEN /// size the two spellings are the same number, so the arms that were /// already correct are unchanged by the edit. #[test] fn a_reference_chroma_sample_count_routes_back_to_its_own_format() { for w in [2usize, 3, 4, 5, 8, 9, 16, 17, 64, 65, 128, 129] { for h in [2usize, 3, 4, 5, 8, 9, 64, 65, 144, 145] { let cases = [ ("4:4:4", round_ss(w, 0) * round_ss(h, 0), (w, h)), ( "4:2:2", round_ss(w, 1) * round_ss(h, 0), (round_ss(w, 1), h), ), ( "4:2:0", round_ss(w, 1) * round_ss(h, 1), (round_ss(w, 1), round_ss(h, 1)), ), ]; for (name, len, want) in cases { assert_eq!( ref_chroma_shape(len, w, h), want, "{name} reference of {w}x{h} (chroma {len} samples) \ must route back to its own shape" ); } } } } /// lane-av1422stripwrite: the whole point of the 4:2:2 arm is that it /// claims the frame's FULL chroma height -- that is what stops every /// chroma MC sourcing a row at or past the midpoint from being clamped /// against `true_height`. Pinned on the t422 shape. #[test] fn a_422_reference_claims_the_full_chroma_height() { // 256x144 luma at ss (1, 0): chroma is 128 wide and 144 rows tall. let (cw, ch) = ref_chroma_shape(round_ss(256, 1) * 144, 256, 144); assert_eq!((cw, ch), (128, 144)); // The bug's own signature: 72 rows claimed for 144 rows held. assert!( ch > 144 / 2, "a 4:2:2 reference must not claim half its rows" ); } /// [`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"); // lane-av1refusalspan: this gate is the PROOF for the refusal below, so // it names it and pins its guard site. The sibling test // `an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking` // carries the same string 27k lines away in this file -- exactly the // reach a window that is not a function boundary used to have. const REFUSAL: &str = "an OBMC neighbour whose switchable interp filter was never recorded"; assert!( crate::refusal_inventory::pins_refusal(&src, REFUSAL), "this gate proves {REFUSAL:?}, but that string is no longer in 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() { // lane-av1refusalspan: the FULL refusal, not a prefix of it. This gate // is the proof for the row in `refusal_inventory`, whose anchor is the // whole string (it carries no `(` and no `:`), and this const is what // that anchor reads. Shortened to `...own ref_frame_idx slot` it // stopped being a pin on the guard's text. const REFUSAL: &str = "a reference frame selected with no picture at this frame's own \ ref_frame_idx slot for it"; 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, // lane-fintra: the sequence bit the encoder wrote this tile under // (stale-header class -- a hard-coded `false` here reads one symbol // short at the first DC_PRED block once the search offers filter intra). crate::encode::filter_intra_on(), &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::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) 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::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) 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::for_encoder(); // lane-b128: encodes, so the decode context takes this process's superblock size 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::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) 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]], ); crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); 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" ); } /// lane-av1txbands item 3: the sub-8x8 group whose CHROMA-REFERENCE leaf /// codes `use_intrabc` AND `skip` -- the one route that arms /// [`INTRABC_CHROMA_TX`] and then reads no chroma coefficient at all, so /// before this round the slot stayed armed into the NEXT block's chroma /// read (whose scan and inverse transform it then picked). No encoder in /// hand codes this shape -- `crate::tile::write_intra_mode` hardcodes /// `skip = 0`, and `aomenc`'s RD search never picked it on any of this /// lane's screen-content recipes (the census in /// `lanes/av1txbands.report.md`) -- so the symbol sequence is /// hand-written, exactly as [`a_skipped_block_decodes_to_pure_prediction`] /// does for a skipped block. /// /// An 8x8 frame descends the superblock cascade to one 8x8 group without /// coding any partition symbol at the outer levels (the true frame edge /// forces every split), so that group's own `partition_w8` is the first /// symbol the tile reads. #[test] fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { let fctx = &crate::decode::FrameCtx::new(); reset_skipped_intrabc_chroma_arm_hits(); use crate::msac::SymbolEncoder; let mut cdfs = Cdfs::new(q_ctx_of(40)); let mut enc = SymbolEncoder::new(); // The frame edge forces every split above this group, so its own // `partition_w8` is the FIRST symbol the tile reads. enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w8[0]); // Leaves 0..2: ordinary intra `DC_PRED`, skipped (a skipped block codes // no coefficient at all, which is what keeps this sequence short). // `get_skip_txfm_context` over the group: 0 with no skipped neighbour // yet, 1 once leaf 0 is to the left (leaf 1) or above (leaf 2), and 2 // for the bottom-right leaf, which has both. for skip_ctx in [0usize, 1, 1] { enc.symbol(1, &mut cdfs.skip[skip_ctx]); enc.symbol(0, &mut cdfs.intrabc); enc.symbol( DC_PRED, &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]], ); } // Leaf 3 IS the group's chroma reference: skipped AND intrabc. enc.symbol(1, &mut cdfs.skip[2]); enc.symbol(1, &mut cdfs.intrabc); enc.symbol(0, &mut cdfs.dv_joint); let data = enc.finish(); let _ = decode_key_frame_tile( &data, 2, 2, 40, 8, 8, false, &CdefParams::default(), &LoopFilterParams::default(), false, true, true, true, fctx, ); assert!( skipped_intrabc_chroma_arm_hits() >= 1, "the hand-written tile never reached the skipped-intrabc chroma-reference route" ); assert!( fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(), "the inherited chroma transform slot must be disarmed when its block's chroma \ route ends, or the NEXT block's chroma read picks its scan and inverse transform" ); } /// [`a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx`]'s /// twin for the OTHER sub-8x8 group shape: a `partition_w8` of VERT sends /// the 8x8 to [`decode_leaf_rect8`], whose chroma reference is its second /// (right-hand) 8x4 leaf. Same route, same disarm. #[test] fn a_skipped_intrabc_rect_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { let fctx = &crate::decode::FrameCtx::new(); reset_skipped_intrabc_chroma_arm_hits(); use crate::msac::SymbolEncoder; let mut cdfs = Cdfs::new(q_ctx_of(40)); let mut enc = SymbolEncoder::new(); enc.symbol(PARTITION_VERT, &mut cdfs.partition_w8[0]); // Left leaf: skipped intra `DC_PRED`. enc.symbol(1, &mut cdfs.skip[0]); enc.symbol(0, &mut cdfs.intrabc); enc.symbol( DC_PRED, &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]], ); // Right leaf IS the group's chroma reference: skipped AND intrabc. enc.symbol(1, &mut cdfs.skip[1]); enc.symbol(1, &mut cdfs.intrabc); enc.symbol(0, &mut cdfs.dv_joint); let data = enc.finish(); let _ = decode_key_frame_tile( &data, 2, 2, 40, 8, 8, false, &CdefParams::default(), &LoopFilterParams::default(), false, true, true, true, fctx, ); assert!( skipped_intrabc_chroma_arm_hits() >= 1, "the hand-written tile never reached the skipped-intrabc rect chroma-reference route" ); assert!( fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(), "the inherited chroma transform slot must be disarmed when its block's chroma \ route ends, or the NEXT block's chroma read picks its scan and inverse transform" ); } /// 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, // The fixture's own implied header codes the reduced sets (the // wrapper's old hardcoded value). true, 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 crate::probe::run_with_stdin; 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 out = run_with_stdin( Command::new("ffmpeg").args([ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", ]), stream, ); 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 out = run_with_stdin( Command::new("ffmpeg").args([ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", ]), stream, ); 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::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) 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, // lane-fintra: the sequence bit the encoder wrote this tile under // (stale-header class -- a hard-coded `false` here reads one symbol // short at the first DC_PRED block once the search offers filter intra). crate::encode::filter_intra_on(), &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"); } } /// lane-fintra: the encoder's own filter-intra blocks, read back by BOTH /// decoders. Two claims in one gate: the stream really exercises the tool /// (the decoder's own `use_filter_intra == 1` counter moves, class /// `gate-blind-to-feature` -- a feature that never fires is not measured), /// and every sample of the frame that carries them matches ffmpeg's /// (class `fixture-proves-symbol-not-signal`: the symbol alone would not /// prove the recursive predictor, the tx_type row or the syntax position /// between the palette colours and the colour-index maps). #[test] fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() { let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) if !crate::encode::filter_intra_on() { eprintln!("SKIP a_filter_intra_key_frame...: EC_AV1_FILTER_INTRA=0"); return; } if !have_ffmpeg() { eprintln!("SKIP a_filter_intra_key_frame...: no ffmpeg"); return; } let (width, height) = (128usize, 128usize); // Smooth, slowly curving content: what the recursive filter modes are // for, and what a plain directional prediction leaves residual on. let mut picture = crate::encode::Picture::grey(width, height); for row in 0..height { for col in 0..width { // lane-i64: the smooth field alone is now coded as four whole // 64x64 intra roots, which are too big for filter intra (the // tool stops at 32x32) -- so the fixture carries a hard step // through the middle of every superblock, which no 64x64 // prediction fits and which sends the quadrants back to the // sizes the recursive modes are offered at. let step = if (row % 64) > 40 && (col % 64) > 24 { 55.0 } else { 0.0 }; let v = 128.0 + 60.0 * ((row as f64) / 9.0).sin() * ((col as f64) / 11.0).cos() + 8.0 * ((row + col) as f64 / 3.0).sin() + step; picture.y[row * width + col] = v.clamp(0.0, 255.0) as u16; } } let encoded = crate::encode::encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let (coded_w, coded_h) = ffprobe_size(&encoded.stream); let before = filter_intra_hits(); let ours = decode_key_frame_tile_lr( &encoded.tile, encoded.mi_cols, encoded.mi_rows, encoded.base_q_idx, coded_w, coded_h, crate::encode::filter_intra_on(), &encoded.cdef, &encoded.loop_filter, encoded.tx_select, true, encoded.screen, encoded.allow_intrabc, &encoded.loop_restoration, fctx, ) .unwrap(); let fired = filter_intra_hits() - before; assert!( fired > 0, "no block took filter intra -- the gate is blind to the feature" ); eprintln!("a_filter_intra_key_frame: {fired} filter-intra blocks"); let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize); assert_eq!(ours.y, ffmpeg_decoded.y, "luma vs ffmpeg"); assert_eq!(ours.u, ffmpeg_decoded.u, "U vs ffmpeg"); assert_eq!(ours.v, ffmpeg_decoded.v, "V vs ffmpeg"); assert_eq!( ours.y, encoded.reconstruction.y, "luma vs the encoder's own reconstruction" ); } /// 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::for_encoder(); // lane-b128: encodes, so the decode context takes this process's superblock size 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, // lane-fintra: the sequence bit the encoder wrote this tile under // (stale-header class -- a hard-coded `false` here reads one symbol // short at the first DC_PRED block once the search offers filter intra). crate::encode::filter_intra_on(), &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, // lane-fintra: the sequence bit the encoder wrote this tile under // (stale-header class -- a hard-coded `false` here reads one symbol // short at the first DC_PRED block once the search offers filter intra). crate::encode::filter_intra_on(), &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(), // lane-intertx: this frame's own `reduced_tx_set` -- the // bit the chroma inheritance reduces against. The wrapper // used to guess `true`, which mis-derived every inherited // chroma type on a screen frame's widened inter blocks // (stale-header class). frame.reduced_tx_set, 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::encode::warp_on(), // lane-fintra: the sequence bit the encoder wrote this tile // under -- same stale-header class as the warp bit above. crate::encode::filter_intra_on(), frame.delta.clone(), 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::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) 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::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) 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, 0), mv_to_q4(py, left_mv.0, 0), 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, 0), mv_to_q4(py, above_mv.0, 0), 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::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below) 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, // lane-fintra: the sequence bit the encoder wrote this tile under // (stale-header class -- a hard-coded `false` here reads one symbol // short at the first DC_PRED block once the search offers filter intra). crate::encode::filter_intra_on(), &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 crate::encode::reference_select(), // lane-intertx: the frame's own `reduced_tx_set` -- see the // first GOP round trip's note. frame.reduced_tx_set, 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::encode::warp_on(), // lane-fintra: the sequence bit the encoder wrote this tile // under -- same stale-header class as the warp bit above. crate::encode::filter_intra_on(), frame.delta.clone(), 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" ); } }