edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching0 forksRust370.3 MiB8a5feaaTahinli2 months ago3162 commits
| 1 | //! Software decoder for this crate's own key-frame tile payloads (spec 5.11), |
| 2 | //! the reader half of [`crate::tile`]'s writer. |
| 3 | //! |
| 4 | //! `tile.rs` is another lane's territory this round (`lane-av1-rect` is |
| 5 | //! touching its partition search), so nothing here imports its private |
| 6 | //! helpers: the handful of `pub(crate)` items it already exposes |
| 7 | //! ([`crate::tile::block_grid`], [`crate::tile::has_half`], |
| 8 | //! [`crate::tile::INTRA_MODE_CTX`], [`crate::tile::write_golomb`]) are reused, |
| 9 | //! and everything else (the partition/coefficient context arithmetic, the |
| 10 | //! scan table) is a from-spec reimplementation kept in step with the writer by |
| 11 | //! the gate tests below rather than by sharing code with it. |
| 12 | //! |
| 13 | //! # Scope (round 1) |
| 14 | //! Key frames only, and only the shapes the encoder actually still needs to |
| 15 | //! prove itself against: every coded block is `DC_PRED` (this crate's mode |
| 16 | //! search names other intra modes, but a decoder for those needs the |
| 17 | //! directional-prediction edge-reach plumbing [`crate::intra::predict`] |
| 18 | //! already carries; wiring it up is round 2), never skipped, and every |
| 19 | //! superblock is a whole number of 64x64 units (a frame whose true edge falls |
| 20 | //! inside one, forcing the gathered-CDF partial-superblock path, is round 2 |
| 21 | //! too). Anything outside that refuses with [`Error::unsupported`] rather than |
| 22 | //! silently miscoding. |
| 23 | use crate::hits::{hit, hit_do}; |
| 24 | |
| 25 | use ec_av1_syntax::{ |
| 26 | CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, MAX_SEGMENTS, |
| 27 | SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo, |
| 28 | }; |
| 29 | use ec_core::{Error, Result}; |
| 30 | |
| 31 | // lane-av112bit: the 12-bit warp refusal that used to stand at all three |
| 32 | // warp decision sites (compound, 16x16+, 8x8 leaf) was an inline literal |
| 33 | // (refusal_inventory.rs extracts refusal strings from the decode source); |
| 34 | // it named the real gap: warp's reduce bits inherited the 12-bit |
| 35 | // `conv_params->round_0` (warped_motion.c:295, convolve.h:81..86) and no |
| 36 | // witness existed. |
| 37 | // lane-av112bitw lifted it from all three sites: `warp::warp_round_0` |
| 38 | // implements the bump (`round_0 += max(bd + FILTER_BITS - round_0 - 14, 0)`, |
| 39 | // 5 at 12 bits), and the single-ref witness plus the rotating-mandelbrot |
| 40 | // compound-warp witness are both byte-exact vs ffmpeg. Compound inter |
| 41 | // itself was lifted by lane-av112bitc before that (the combines absorb the |
| 42 | // CONV_BUF gain drop, `INTER_POST_ROUND - delta`, see `mc::combine_compound`). |
| 43 | |
| 44 | /// Per-frame decode state, one instance per decoded stream (lane-thread1). |
| 45 | /// |
| 46 | /// Every field here used to be a `thread_local!` static, which made a decode a |
| 47 | /// function of the calling THREAD's history rather than of the bitstream alone |
| 48 | /// -- and made frame-parallel decoding impossible, since a worker thread sees |
| 49 | /// empty state. The cells keep exactly the interior mutability the statics |
| 50 | /// had, so every read/write site is byte-identical; what changes is WHERE the |
| 51 | /// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down |
| 52 | /// the decode call graph. |
| 53 | /// |
| 54 | /// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to |
| 55 | /// exactly one thread's decode, and is never shared between workers. |
| 56 | /// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`] |
| 57 | /// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF |
| 58 | /// (pre-restoration) samples, at the decoder's own plane stride. |
| 59 | pub(crate) struct FilterStages { |
| 60 | /// Post-deblock, pre-CDEF planes (Y, U, V). |
| 61 | pub(crate) deblocked: [Vec<u16>; 3], |
| 62 | /// Post-CDEF, pre-restoration planes (Y, U, V). |
| 63 | pub(crate) cdefed: [Vec<u16>; 3], |
| 64 | /// Each plane's stride (and so its width in the buffers above). |
| 65 | pub(crate) stride: [usize; 3], |
| 66 | } |
| 67 | |
| 68 | /// Takes whatever the last capturing decode left (see |
| 69 | /// [`FrameCtx::capture_stages`]). |
| 70 | #[allow(dead_code)] // read from the encoder's loop restoration search |
| 71 | pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> { |
| 72 | fctx.stages.borrow_mut().take() |
| 73 | } |
| 74 | |
| 75 | pub(crate) struct FrameCtx { |
| 76 | /// lane-av1lr: when set, the frame filter chain leaves its post-deblock |
| 77 | /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop |
| 78 | /// restoration search (spec 7.17 reads both: the stripe interior from |
| 79 | /// the post-CDEF plane, its 3-row border from the post-deblock one). |
| 80 | /// Off for every decode but that search, and off it costs one bool read |
| 81 | /// per frame and not a single copy. |
| 82 | pub(crate) capture_stages: std::cell::Cell<bool>, |
| 83 | pub(crate) stages: std::cell::RefCell<Option<FilterStages>>, |
| 84 | pub(crate) sb128_flag: std::cell::Cell<bool>, |
| 85 | /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every |
| 86 | /// motion compensation of THIS frame runs, already resolved to a kernel. |
| 87 | /// `mc::predict` used to hardwire `Regular`, so the encoder's search, |
| 88 | /// trial and recon could only ever build a REGULAR prediction whatever |
| 89 | /// the frame header said; it lives here (and is copied by |
| 90 | /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same |
| 91 | /// kernel the frame header wrote instead of the default. |
| 92 | pub(crate) interp_filter: std::cell::Cell<crate::mc::InterpFilterKind>, |
| 93 | /// lane-lossless: this frame's per-segment lossless table -- libaom's |
| 94 | /// `xd->lossless[MAX_SEGMENTS]`, computed ONCE per frame in the header |
| 95 | /// (spec 5.9.12 `CodedLossless`: each segment at `qindex == 0` with zero |
| 96 | /// plane deltas, `get_qindex` applying that segment's own `SEG_LVL_ALT_Q`). |
| 97 | /// Every block-decoder rule that reads [`decode::lossless`] resolves it |
| 98 | /// through the BLOCK's own `segment_id`: TX_4X4 with the Walsh-Hadamard |
| 99 | /// transform on every plane, the dropped `tx_type` symbol and the narrowed |
| 100 | /// `is_cfl_allowed` (libaom `read_tx_size` (`decodeframe.c`), |
| 101 | /// `read_tx_type` (`decodetxb.c`), `is_cfl_allowed` (`blockd.h`)) follow |
| 102 | /// the SEGMENT, so a frame whose segments disagree codes lossless and |
| 103 | /// lossy blocks side by side. |
| 104 | pub(crate) lossless_per_seg: std::cell::Cell<[bool; MAX_SEGMENTS]>, |
| 105 | /// lane-av1txr: this frame header's `disable_cdf_update` (spec 5.9.2). |
| 106 | /// When set, the tile reader must not adapt any CDF it reads, or its |
| 107 | /// tables drift away from the encoder's and the frame desyncs mid-tile |
| 108 | /// (libaom: `allow_update_cdf = allow_update_cdf && |
| 109 | /// !cm->features.disable_cdf_update`, `decodeframe.c:2909`). |
| 110 | pub(crate) disable_cdf_update: std::cell::Cell<bool>, |
| 111 | pub(crate) cdef_bits: std::cell::Cell<u8>, |
| 112 | pub(crate) bit_depth: std::cell::Cell<u8>, |
| 113 | /// lane-av1mono: the sequence header's `color_config.mono_chrome` (spec |
| 114 | /// 5.5.2), i.e. `NumPlanes == 1`. libaom threads this as |
| 115 | /// `av1_num_planes(cm)` and every chroma read site is guarded by |
| 116 | /// `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`, |
| 117 | /// `:1208`) or bounded by `plane < num_planes`; a monochrome frame codes |
| 118 | /// NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` symbol and NO chroma |
| 119 | /// coefficients on any block. Set once per frame from the sequence header |
| 120 | /// (like [`FrameCtx::bit_depth`]), so a mono frame decoded on a thread |
| 121 | /// that last saw a 4:2:0 one never inherits the wrong plane count. |
| 122 | pub(crate) mono_chrome: std::cell::Cell<bool>, |
| 123 | /// lane-av1-444: sequence subsampling_x/y. 1,1 is 4:2:0; 0,0 is 4:4:4. |
| 124 | pub(crate) subsampling_x: std::cell::Cell<u8>, |
| 125 | pub(crate) subsampling_y: std::cell::Cell<u8>, |
| 126 | pub(crate) superres: std::cell::Cell<(u32, u32)>, |
| 127 | pub(crate) cdef_transmitted: std::cell::Cell<bool>, |
| 128 | pub(crate) cdef_sb_cols: std::cell::Cell<usize>, |
| 129 | pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>, |
| 130 | pub(crate) delta_q_present: std::cell::Cell<bool>, |
| 131 | pub(crate) delta_q_res: std::cell::Cell<i32>, |
| 132 | pub(crate) current_q_idx: std::cell::Cell<i32>, |
| 133 | pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>, |
| 134 | /// lane-av1-qmatrix: this frame's quantisation-matrix LEVEL per plane, |
| 135 | /// straight from spec 5.9.12's `qm_y`/`qm_u`/`qm_v` (the parsed 4-bit |
| 136 | /// value IS the table level -- libaom `quant_params->qmatrix_level_y/u/v`, |
| 137 | /// decodeframe.c:1902-1917; the `aom_get_qmlevel` formula that maps |
| 138 | /// base_q_idx onto a level is encoder-side only). 15 is libaom's flat |
| 139 | /// sentinel (`NUM_QM_LEVELS - 1`, stored as NULL tables) and the default |
| 140 | /// every `using_qmatrix == 0` frame keeps, so a matrix-free stream |
| 141 | /// selects no matrix. |
| 142 | pub(crate) qm_levels: std::cell::Cell<[u8; 3]>, |
| 143 | pub(crate) delta_lf_present: std::cell::Cell<bool>, |
| 144 | pub(crate) delta_lf_res: std::cell::Cell<i32>, |
| 145 | pub(crate) delta_lf_multi: std::cell::Cell<bool>, |
| 146 | pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>, |
| 147 | pub(crate) seg: std::cell::RefCell<SegmentationParams>, |
| 148 | pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>, |
| 149 | pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>, |
| 150 | pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>, |
| 151 | pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>, |
| 152 | pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>, |
| 153 | pub(crate) cur_segment_id: std::cell::Cell<u8>, |
| 154 | pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>, |
| 155 | pub(crate) tx_select_inter: std::cell::Cell<bool>, |
| 156 | /// Whether the tile being decoded is an INTRA-ONLY frame's (key/intra-only |
| 157 | /// frame). libaom runs `set_txfm_ctxs` for EVERY block of EVERY frame |
| 158 | /// (`decodeframe.c` `parse_decode_block`), so an intra-only frame |
| 159 | /// maintains the `TXFM_CONTEXT` bands exactly like an inter one; only this |
| 160 | /// decoder's inter-side publishing was wired. See |
| 161 | /// [`Neighbours::fill_lf_grid_rect`]'s band publish. |
| 162 | pub(crate) intra_only: std::cell::Cell<bool>, |
| 163 | /// This FRAME's own `tx_mode == TxMode::Select`, set for EVERY frame |
| 164 | /// (intra included). [`Self::tx_select_inter`] cannot stand in for it: |
| 165 | /// an intrabc block rides an INTRA frame, but libaom still reads its |
| 166 | /// var-tx `txfm_partition` tree under the frame's `TxMode::Select`. |
| 167 | pub(crate) tx_select_frame: std::cell::Cell<bool>, |
| 168 | pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>, |
| 169 | pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>, |
| 170 | pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>, |
| 171 | pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>, |
| 172 | pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>, |
| 173 | pub(crate) luma_tx_type: std::cell::Cell<TxType>, |
| 174 | pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>, |
| 175 | pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>, |
| 176 | pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>, |
| 177 | pub(crate) inter_last_mc: |
| 178 | std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>, |
| 179 | pub(crate) enable_edge_filter: std::cell::Cell<bool>, |
| 180 | pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>, |
| 181 | pub(crate) reach_sb_px: std::cell::Cell<usize>, |
| 182 | pub(crate) grain_bit_depth: std::cell::Cell<u32>, |
| 183 | /// lane-wave1 step (i): this superblock's recorded pixel writes, see |
| 184 | /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`]. |
| 185 | pub(crate) recon_ops: std::cell::RefCell<Vec<ReconOp>>, |
| 186 | /// The queue buffer [`flush_recon`] just drained, kept for its capacity |
| 187 | /// so a superblock's records do not regrow the vector from nothing. |
| 188 | pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>, |
| 189 | /// lane-recoparse: the coefficient grids of the recorded ops above, one |
| 190 | /// buffer instead of a `Vec` per transform unit -- a recorded unit is |
| 191 | /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse |
| 192 | /// before the op is published, read only by whoever replays that op, and |
| 193 | /// handed over WITH the ops at every drain point ([`wave_submit`], |
| 194 | /// [`flush_recon`]), so offsets are always relative to the live arena. |
| 195 | pub(crate) coeff_arena: std::cell::RefCell<Vec<i32>>, |
| 196 | /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain |
| 197 | /// path (a submitted job's arena travels to its worker instead). |
| 198 | pub(crate) coeff_spare: std::cell::RefCell<Vec<i32>>, |
| 199 | /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS |
| 200 | /// ([`PredSrc::Owned`]): same lifetime, same drain points. |
| 201 | pub(crate) pred_arena: std::cell::RefCell<Vec<u16>>, |
| 202 | pub(crate) pred_spare: std::cell::RefCell<Vec<u16>>, |
| 203 | /// lane-wave1 step (ii): the tile decoder's own planes, registered by |
| 204 | /// [`ReconInline`] while reconstruction runs INLINE (one recon thread). |
| 205 | /// `None` while the queue is in use (wavefront workers) and outside a |
| 206 | /// tile. See [`push_op`]. |
| 207 | pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>, |
| 208 | /// lane-wave1 step (ii): the superblock wavefront this tile's recorded |
| 209 | /// writes are handed to, at more than one reconstruction thread. |
| 210 | pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>, |
| 211 | /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse |
| 212 | /// thread last handed a superblock to the wavefront. |
| 213 | pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>, |
| 214 | } |
| 215 | |
| 216 | impl std::fmt::Debug for FrameCtx { |
| 217 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 218 | f.write_str("FrameCtx") |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | impl FrameCtx { |
| 223 | /// A fresh context, every field at the default its thread-local |
| 224 | /// predecessor was born with. |
| 225 | pub(crate) fn new() -> Self { |
| 226 | Self { |
| 227 | // A DECODER context is seeded from the stream alone: every real |
| 228 | // decode overwrites this from the parsed sequence header |
| 229 | // (`set_sb128`, stream.rs). The encoder's own contexts start at |
| 230 | // the size this process encodes -- see [`FrameCtx::for_encoder`]. |
| 231 | sb128_flag: std::cell::Cell::new(false), |
| 232 | interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular), |
| 233 | lossless_per_seg: std::cell::Cell::new([false; MAX_SEGMENTS]), |
| 234 | disable_cdf_update: std::cell::Cell::new(false), |
| 235 | cdef_bits: std::cell::Cell::new(0), |
| 236 | bit_depth: std::cell::Cell::new(8), |
| 237 | mono_chrome: std::cell::Cell::new(false), |
| 238 | subsampling_x: std::cell::Cell::new(1), |
| 239 | subsampling_y: std::cell::Cell::new(1), |
| 240 | superres: std::cell::Cell::new((0, 8)), |
| 241 | cdef_transmitted: std::cell::Cell::new(false), |
| 242 | cdef_sb_cols: std::cell::Cell::new(0), |
| 243 | capture_stages: std::cell::Cell::new(false), |
| 244 | stages: std::cell::RefCell::new(None), |
| 245 | cdef_idx_grid: std::cell::RefCell::new(Vec::new()), |
| 246 | delta_q_present: std::cell::Cell::new(false), |
| 247 | delta_q_res: std::cell::Cell::new(1), |
| 248 | current_q_idx: std::cell::Cell::new(0), |
| 249 | quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas { |
| 250 | y_dc: 0, |
| 251 | u_dc: 0, |
| 252 | u_ac: 0, |
| 253 | v_dc: 0, |
| 254 | v_ac: 0, |
| 255 | }), |
| 256 | qm_levels: std::cell::Cell::new([crate::qm::NUM_QM_LEVELS as u8 - 1; 3]), |
| 257 | delta_lf_present: std::cell::Cell::new(false), |
| 258 | delta_lf_res: std::cell::Cell::new(1), |
| 259 | delta_lf_multi: std::cell::Cell::new(false), |
| 260 | current_delta_lf: std::cell::Cell::new([0; 4]), |
| 261 | seg: std::cell::RefCell::new(SegmentationParams::default()), |
| 262 | seg_ids: std::cell::RefCell::new(Vec::new()), |
| 263 | prev_seg_ids: std::cell::RefCell::new(Vec::new()), |
| 264 | seg_mi_dims: std::cell::Cell::new((0, 0)), |
| 265 | above_seg_pred: std::cell::RefCell::new(Vec::new()), |
| 266 | left_seg_pred: std::cell::RefCell::new(Vec::new()), |
| 267 | cur_segment_id: std::cell::Cell::new(0), |
| 268 | seg_tile_origin: std::cell::Cell::new((0, 0)), |
| 269 | tx_select_inter: std::cell::Cell::new(false), |
| 270 | tx_select_frame: std::cell::Cell::new(false), |
| 271 | intra_only: std::cell::Cell::new(false), |
| 272 | reduced_tx_set_inter: std::cell::Cell::new(false), |
| 273 | enable_filter_intra_inter: std::cell::Cell::new(false), |
| 274 | palette_pred: std::cell::RefCell::new(None), |
| 275 | intrabc_mi_grid: std::cell::RefCell::new(None), |
| 276 | intrabc_dv: std::cell::Cell::new(None), |
| 277 | luma_tx_type: std::cell::Cell::new(TxType::DctDct), |
| 278 | intrabc_chroma_tx: std::cell::Cell::new(None), |
| 279 | intra_in_inter_mode: std::cell::Cell::new(None), |
| 280 | inter_strip_chroma: std::cell::Cell::new(None), |
| 281 | inter_last_mc: std::cell::Cell::new(None), |
| 282 | enable_edge_filter: std::cell::Cell::new(false), |
| 283 | last_frame_wide_margin: std::cell::RefCell::new(None), |
| 284 | reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK), |
| 285 | grain_bit_depth: std::cell::Cell::new(8), |
| 286 | recon_ops: std::cell::RefCell::new(Vec::new()), |
| 287 | recon_spare: std::cell::RefCell::new(Vec::new()), |
| 288 | coeff_arena: std::cell::RefCell::new(Vec::new()), |
| 289 | coeff_spare: std::cell::RefCell::new(Vec::new()), |
| 290 | pred_arena: std::cell::RefCell::new(Vec::new()), |
| 291 | pred_spare: std::cell::RefCell::new(Vec::new()), |
| 292 | recon_planes: std::cell::Cell::new(None), |
| 293 | wave: std::cell::RefCell::new(None), |
| 294 | wave_mark: std::cell::Cell::new(None), |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | /// A context for the ENCODER's own trial decodes: it starts at the |
| 299 | /// superblock size this process encodes (`crate::encode::sb128_on`) so |
| 300 | /// the mode search's `Reach` and the filter search's internal decodes |
| 301 | /// agree with the tile writer. A decoder never reads that knob -- doing |
| 302 | /// so coupled every decode to the encoder's process-global and raced the |
| 303 | /// 128-superblock decode gates against the encoder witness. |
| 304 | pub(crate) fn for_encoder() -> Self { |
| 305 | let ctx = Self::new(); |
| 306 | let on = crate::encode::sb128_on(); |
| 307 | ctx.sb128_flag.set(on); |
| 308 | ctx.reach_sb_px.set(if on { 128 } else { crate::encode::SUPERBLOCK }); |
| 309 | ctx |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)` |
| 314 | /// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent |
| 315 | /// `with` still wins for the scratch pools and gate counters that stay |
| 316 | /// thread-local. |
| 317 | pub(crate) trait WithRef { |
| 318 | fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R { |
| 319 | f(self) |
| 320 | } |
| 321 | } |
| 322 | impl<T: ?Sized> WithRef for T {} |
| 323 | |
| 324 | /// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads. |
| 325 | /// |
| 326 | /// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread), |
| 327 | /// and the post-decode filter chain reads exactly these fields: the bit depth |
| 328 | /// (every kernel's clamp and threshold shift), the segmentation table |
| 329 | /// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state |
| 330 | /// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s |
| 331 | /// default -- a field that turns out to be read after all shows up as a hash |
| 332 | /// mismatch in |
| 333 | /// `a_real_stream_filters_identically_with_one_and_four_filter_threads`. |
| 334 | pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx { |
| 335 | let out = FrameCtx::new(); |
| 336 | out.bit_depth.set(fctx.bit_depth.get()); |
| 337 | out.mono_chrome.set(fctx.mono_chrome.get()); |
| 338 | out.subsampling_x.set(fctx.subsampling_x.get()); |
| 339 | out.subsampling_y.set(fctx.subsampling_y.get()); |
| 340 | out.interp_filter.set(fctx.interp_filter.get()); |
| 341 | out.grain_bit_depth.set(fctx.grain_bit_depth.get()); |
| 342 | out.superres.set(fctx.superres.get()); |
| 343 | out.seg_mi_dims.set(fctx.seg_mi_dims.get()); |
| 344 | out.seg.replace(fctx.seg.borrow().clone()); |
| 345 | out.seg_ids.replace(fctx.seg_ids.borrow().clone()); |
| 346 | // lane-b128m: the superblock size travels with the copy. A tile SEARCH |
| 347 | // worker (`encode::search_tiles`) gets its context from here, so dropping |
| 348 | // it made every worker search at 64 while the calling thread searched at |
| 349 | // 128 -- the bytes a frame came out as then depended on the tile thread |
| 350 | // count under `EC_AV1_SB128`. |
| 351 | out.sb128_flag.set(fctx.sb128_flag.get()); |
| 352 | out.reach_sb_px.set(fctx.reach_sb_px.get()); |
| 353 | out |
| 354 | } |
| 355 | |
| 356 | use crate::cdf; |
| 357 | use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; |
| 358 | use crate::encode::{Picture, Reach}; |
| 359 | use crate::intra::predict; |
| 360 | use crate::mc; |
| 361 | use crate::msac::SymbolDecoder; |
| 362 | use crate::mvstack::{ |
| 363 | ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, |
| 364 | MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx, |
| 365 | find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx, |
| 366 | single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, |
| 367 | single_ref_p6_ctx, uni_comp_ref_p1_ctx, |
| 368 | }; |
| 369 | use crate::tile::{INTRA_MODE_CTX, block_grid, has_half}; |
| 370 | use crate::transform::{TxType, dequant_and_inverse_typed_wh}; |
| 371 | |
| 372 | const PARTITION_NONE: usize = 0; |
| 373 | const PARTITION_HORZ: usize = 1; |
| 374 | const PARTITION_VERT: usize = 2; |
| 375 | const PARTITION_SPLIT: usize = 3; |
| 376 | const PARTITION_HORZ_A: usize = 4; |
| 377 | const PARTITION_HORZ_B: usize = 5; |
| 378 | const PARTITION_VERT_A: usize = 6; |
| 379 | const PARTITION_VERT_B: usize = 7; |
| 380 | const PARTITION_HORZ_4: usize = 8; |
| 381 | const PARTITION_VERT_4: usize = 9; |
| 382 | const SB_MI: u32 = 16; |
| 383 | const BLOCK_MI: u32 = 8; |
| 384 | |
| 385 | // lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1). |
| 386 | // Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the |
| 387 | // superblock's own top-left mi?", the loop-restoration read's unit span, the |
| 388 | // partition tree's own root level) keys off it; `SB_MI` stays the 64x64 |
| 389 | // *quadrant* size a 128 superblock is decoded in, which is also what the CDEF |
| 390 | // grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64 |
| 391 | // inside a 128 superblock). |
| 392 | thread_local! { |
| 393 | /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the |
| 394 | /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream |
| 395 | /// prints gigabytes otherwise). Unset = every frame, as before. |
| 396 | static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) }; |
| 397 | static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) }; |
| 398 | } |
| 399 | |
| 400 | /// Called by [`crate::stream::decode_stream`] before each frame's tiles with |
| 401 | /// that frame's DECODE-order index. |
| 402 | pub fn set_coeff_trace_frame(idx: usize) { |
| 403 | COEFF_TRACE_FRAME.with(|c| { |
| 404 | if c.get().is_none() { |
| 405 | let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") { |
| 406 | Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX), |
| 407 | // unset: keep tracing every frame, as before this rung existed |
| 408 | Err(_) => usize::MAX - 1, |
| 409 | }; |
| 410 | c.set(Some(want)); |
| 411 | } |
| 412 | }); |
| 413 | COEFF_TRACE_CUR.with(|c| c.set(idx)); |
| 414 | if crate::envflags::env_flag!("EC_TRACE_COEFF") { |
| 415 | eprintln!("EC_COEFF_FRAME decode_idx={idx}"); |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | pub(crate) fn coeff_trace_on() -> bool { |
| 420 | if !crate::envflags::env_flag!("EC_TRACE_COEFF") { |
| 421 | return false; |
| 422 | } |
| 423 | match COEFF_TRACE_FRAME.with(|c| c.get()) { |
| 424 | // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the |
| 425 | // env var unset: trace every frame. |
| 426 | None => true, |
| 427 | Some(w) if w >= usize::MAX - 1 => true, |
| 428 | Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w, |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | |
| 433 | /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`). |
| 434 | pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) { |
| 435 | fctx.sb128_flag.with(|c| c.set(v)); |
| 436 | crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx); |
| 437 | } |
| 438 | |
| 439 | /// lane-av1mixloss: sets [`FrameCtx::lossless_per_seg`] (called once per frame |
| 440 | /// from `stream.rs`). |
| 441 | pub(crate) fn set_lossless_per_seg( |
| 442 | table: [bool; MAX_SEGMENTS], |
| 443 | fctx: &crate::decode::FrameCtx, |
| 444 | ) { |
| 445 | fctx.lossless_per_seg.with(|c| c.set(table)); |
| 446 | } |
| 447 | |
| 448 | /// The BLOCK's own lossless bit: libaom's `xd->lossless[mbmi->segment_id]`. |
| 449 | /// The table is computed once per frame (libaom `decodeframe.c:5205`: |
| 450 | /// `qindex == 0` with every plane delta 0, `av1_get_qindex` applying the |
| 451 | /// segment's `SEG_LVL_ALT_Q`), but the frame never carries ONE lossless rule |
| 452 | /// -- `read_tx_size`, `read_tx_type` and `is_cfl_allowed` all index it by the |
| 453 | /// BLOCK's own segment id, which the spec-order `segment_id` read sets before |
| 454 | /// any mode/transform symbol of the block. A frame whose segments disagree |
| 455 | /// codes TX_4X4/WHT blocks and normal blocks side by side. |
| 456 | pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool { |
| 457 | let seg_id = usize::from(fctx.cur_segment_id.with(|c| c.get())); |
| 458 | fctx.lossless_per_seg.with(|c| c.get())[seg_id] |
| 459 | } |
| 460 | |
| 461 | /// Sets [`FrameCtx::disable_cdf_update`] (called once per frame from |
| 462 | /// `stream.rs`). |
| 463 | pub(crate) fn set_disable_cdf_update(v: bool, fctx: &crate::decode::FrameCtx) { |
| 464 | fctx.disable_cdf_update.with(|c| c.set(v)); |
| 465 | } |
| 466 | |
| 467 | /// This frame's `disable_cdf_update`, for the tile readers -- |
| 468 | /// [`msac::SymbolDecoder::set_cdf_update`](crate::msac::SymbolDecoder::set_cdf_update). |
| 469 | pub(crate) fn cdf_update_disabled(fctx: &crate::decode::FrameCtx) -> bool { |
| 470 | fctx.disable_cdf_update.with(|c| c.get()) |
| 471 | } |
| 472 | |
| 473 | /// The transform side a block of `side` pixels codes: its own (capped at the |
| 474 | /// caller's own largest) normally, 4 on a lossless BLOCK, where libaom's |
| 475 | /// `read_tx_size` returns TX_4X4 before it looks at anything else |
| 476 | /// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return |
| 477 | /// TX_4X4;`). |
| 478 | pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize { |
| 479 | if lossless(fctx) { 4 } else { px } |
| 480 | } |
| 481 | |
| 482 | /// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to |
| 483 | /// 32x32 -- but on a LOSSLESS BLOCK only when the block's CHROMA plane block |
| 484 | /// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller. |
| 485 | /// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom |
| 486 | /// picks the 13-symbol one (class `wrong-alphabet-same-value`). |
| 487 | pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 488 | if lossless(fctx) { |
| 489 | bw <= 8 && bh <= 8 |
| 490 | } else { |
| 491 | bw <= 32 && bh <= 32 |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | fn sb128(fctx: &crate::decode::FrameCtx) -> bool { |
| 496 | fctx.sb128_flag.with(|c| c.get()) |
| 497 | } |
| 498 | |
| 499 | /// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128). |
| 500 | pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 { |
| 501 | if sb128(fctx) { SB_MI * 2 } else { SB_MI } |
| 502 | } |
| 503 | |
| 504 | // How many real 128-level partition symbols this decoder has read, and how |
| 505 | // many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the |
| 506 | // gate's proof a `--sb-size=128` stream exercised the 128 partition root. |
| 507 | thread_local! { |
| 508 | static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 509 | static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 510 | static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 511 | } |
| 512 | |
| 513 | /// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the |
| 514 | /// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec |
| 515 | /// 5.11.4), which this decoder used to read and throw away. |
| 516 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 517 | pub(crate) fn part128_gathered_symbols() -> usize { |
| 518 | PART128_GATHERED_SYMBOLS.with(|c| c.get()) |
| 519 | } |
| 520 | |
| 521 | /// Current value of [`PART128_SYMBOLS`]. |
| 522 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 523 | pub(crate) fn part128_symbols() -> usize { |
| 524 | PART128_SYMBOLS.with(|c| c.get()) |
| 525 | } |
| 526 | |
| 527 | /// Current value of [`PART128_SPLIT_HITS`]. |
| 528 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 529 | pub(crate) fn part128_split_hits() -> usize { |
| 530 | PART128_SPLIT_HITS.with(|c| c.get()) |
| 531 | } |
| 532 | |
| 533 | /// [`gather`] over an alphabet of any length -- the 128-level partition CDF |
| 534 | /// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec |
| 535 | /// `partition_cdf_length`), so its forced-split gather sums 5 elements where |
| 536 | /// the 64/32 levels sum 6. |
| 537 | pub(crate) fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] { |
| 538 | let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum(); |
| 539 | [32768 - split, 32768, 0] |
| 540 | } |
| 541 | |
| 542 | /// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root. |
| 543 | pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7]; |
| 544 | pub(crate) const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6]; |
| 545 | |
| 546 | // How many `use_filter_intra` symbols this decoder has read as `1`, across |
| 547 | // every call on the current thread -- the cheap counter [`filter_intra_hits`] gate |
| 548 | // tests read (before/after, not the absolute value) to prove a stream |
| 549 | // actually exercised the filter-intra predictor rather than silently |
| 550 | // skipping it. |
| 551 | thread_local! { |
| 552 | static FILTER_INTRA_HITS: std::cell::Cell<usize> = |
| 553 | const { std::cell::Cell::new(0) }; |
| 554 | } |
| 555 | |
| 556 | /// Current value of [`FILTER_INTRA_HITS`]. |
| 557 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 558 | pub(crate) fn filter_intra_hits() -> usize { |
| 559 | FILTER_INTRA_HITS.with(|c| c.get()) |
| 560 | } |
| 561 | |
| 562 | // lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged |
| 563 | // to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own |
| 564 | // `read_filter_intra_mode_info` call), which no gate exercised before this |
| 565 | // round -- every inter gate recipe passed `--enable-filter-intra=0`. |
| 566 | thread_local! { |
| 567 | static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> = |
| 568 | const { std::cell::Cell::new(0) }; |
| 569 | } |
| 570 | |
| 571 | /// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`]. |
| 572 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 573 | pub(crate) fn intra_in_inter_filter_intra_hits() -> usize { |
| 574 | INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get()) |
| 575 | } |
| 576 | |
| 577 | // lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a |
| 578 | // nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both |
| 579 | // arms refused a nonzero luma delta before this round, and no inter gate |
| 580 | // enabled `--enable-angle-delta` (aomenc's own default is 1). |
| 581 | thread_local! { |
| 582 | static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = |
| 583 | const { std::cell::Cell::new(0) }; |
| 584 | static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> = |
| 585 | const { std::cell::Cell::new(0) }; |
| 586 | } |
| 587 | |
| 588 | /// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`]. |
| 589 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 590 | pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize { |
| 591 | INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get()) |
| 592 | } |
| 593 | |
| 594 | /// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`]. |
| 595 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 596 | pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize { |
| 597 | INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get()) |
| 598 | } |
| 599 | |
| 600 | // lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside |
| 601 | // an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm |
| 602 | // read `uv_mode` and then refused everything but `DC_PRED`. Counted here and |
| 603 | // nowhere else so the gate's assert cannot be satisfied by a >=16x16 block. |
| 604 | thread_local! { |
| 605 | static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 606 | static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 607 | static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 608 | } |
| 609 | |
| 610 | thread_local! { |
| 611 | static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 612 | } |
| 613 | |
| 614 | /// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame |
| 615 | /// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm. |
| 616 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 617 | pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize { |
| 618 | INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get()) |
| 619 | } |
| 620 | |
| 621 | /// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf |
| 622 | /// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`]. |
| 623 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 624 | pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) { |
| 625 | ( |
| 626 | INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()), |
| 627 | INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()), |
| 628 | INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()), |
| 629 | ) |
| 630 | } |
| 631 | |
| 632 | // lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into |
| 633 | // [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a |
| 634 | // frame-level flag through the recursive block decode -- `0` (the default) |
| 635 | // makes every call a true no-op, matching every existing gate stream's |
| 636 | // `cdef_bits == 0` behaviour exactly. |
| 637 | // lane-realworld r8: the sequence header's `color_config.bit_depth`, set |
| 638 | // once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs` |
| 639 | // call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still |
| 640 | // blocks every non-8-bit stream from reaching a decode call, so this is `8` |
| 641 | // on every path that runs today -- threading it now (rather than the literal |
| 642 | // `8`) is stage 1 of widening past that refusal without re-deriving every |
| 643 | // clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of |
| 644 | // depth (this decoder's own internal choice, matches dav1d/libaom). |
| 645 | /// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current |
| 646 | /// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`. |
| 647 | pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 { |
| 648 | (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1 |
| 649 | } |
| 650 | /// The current stream's bit depth, for callers (e.g. dequant) that need the |
| 651 | /// raw value rather than the derived clamp bound. |
| 652 | pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 { |
| 653 | fctx.bit_depth.with(std::cell::Cell::get) |
| 654 | } |
| 655 | /// Sets [`BIT_DEPTH`] for the current thread, called once per frame from |
| 656 | /// [`crate::stream`]'s decode loop. |
| 657 | pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) { |
| 658 | fctx.bit_depth.with(|c| c.set(bit_depth)); |
| 659 | } |
| 660 | |
| 661 | /// This stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a |
| 662 | /// monochrome frame has `NumPlanes == 1`, so no block codes any chroma |
| 663 | /// symbol or chroma coefficient and the output picture is luma only. |
| 664 | pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool { |
| 665 | fctx.mono_chrome.with(std::cell::Cell::get) |
| 666 | } |
| 667 | |
| 668 | /// Sets [`mono`] for the current thread, called once per frame from |
| 669 | /// [`crate::stream`]'s decode loop like [`set_bit_depth`]. |
| 670 | pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) { |
| 671 | fctx.mono_chrome.with(|c| c.set(mono_chrome)); |
| 672 | } |
| 673 | |
| 674 | /// Sequence subsampling. Set once per frame from stream.rs, like set_mono. |
| 675 | pub(crate) fn set_subsampling(ss_x: u8, ss_y: u8, fctx: &crate::decode::FrameCtx) { |
| 676 | fctx.subsampling_x.set(ss_x); |
| 677 | fctx.subsampling_y.set(ss_y); |
| 678 | } |
| 679 | |
| 680 | #[inline] |
| 681 | pub(crate) fn ss_x(fctx: &crate::decode::FrameCtx) -> usize { |
| 682 | fctx.subsampling_x.get() as usize |
| 683 | } |
| 684 | |
| 685 | #[inline] |
| 686 | pub(crate) fn ss_y(fctx: &crate::decode::FrameCtx) -> usize { |
| 687 | fctx.subsampling_y.get() as usize |
| 688 | } |
| 689 | |
| 690 | /// libaom ROUND_POWER_OF_TWO. At ss=1 equals div_ceil(dim, 2); at ss=0 is dim. |
| 691 | #[inline] |
| 692 | pub(crate) fn round_ss(dim: usize, ss: usize) -> usize { |
| 693 | (dim + ((1usize << ss) >> 1)) >> ss |
| 694 | } |
| 695 | |
| 696 | |
| 697 | /// This frame's superres state: `(upscaled_width, superres_denom)`, or |
| 698 | /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs |
| 699 | /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid, |
| 700 | /// `read_lr`'s unit corners and the pixel filters themselves -- works in |
| 701 | /// UPSCALED coordinates while deblock and CDEF work in downscaled ones |
| 702 | /// (libaom `av1_superres_upscale` in `decodeframe.c`, and |
| 703 | /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x` |
| 704 | /// superres arms). Set once per frame from [`crate::stream`]'s decode |
| 705 | /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame |
| 706 | /// so a later frame never inherits it. |
| 707 | |
| 708 | /// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and |
| 709 | /// `denom` 8) for a frame that is not superres-scaled. |
| 710 | pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) { |
| 711 | fctx.superres.with(|c| c.set((upscaled_width, denom))); |
| 712 | } |
| 713 | |
| 714 | /// `(upscaled_width, superres_denom)` when this frame is superres-scaled |
| 715 | /// (libaom `av1_superres_scaled`), else `None`. |
| 716 | pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> { |
| 717 | let (w, d) = fctx.superres.with(std::cell::Cell::get); |
| 718 | (w > 0 && d != 8).then_some((w, d)) |
| 719 | } |
| 720 | // Whether this superblock's single CDEF unit (this decoder has no 128x128 |
| 721 | // SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal |
| 722 | // read -- reset to `false` at the top of each superblock in the two tile |
| 723 | // loops, spec `read_cdef`'s `cdef_transmitted[index]`. |
| 724 | // Number of superblock columns in the current tile's grid, so |
| 725 | // [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into |
| 726 | // [`CDEF_IDX_GRID`]. |
| 727 | // One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select |
| 728 | // which of the header's `1 << cdef.bits` strength pairs applies to that |
| 729 | // superblock's samples. |
| 730 | // How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`] |
| 731 | // has read, across every call on the current thread -- the gate's proof that a |
| 732 | // `cdef_bits > 0` stream actually reached the new reader rather than every |
| 733 | // superblock coincidentally being all-skip. |
| 734 | thread_local! { |
| 735 | static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 736 | } |
| 737 | |
| 738 | // How many times a warp was suppressed for one PLANE because that plane's own |
| 739 | // block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out, |
| 740 | // reconinter.c) -- the gate's proof that a stream really carries the shape, |
| 741 | // since the square `side`/`chroma_side` can be 8 or more while the plane's |
| 742 | // true block is 4 wide (an 8x16 luma block's 4x8 chroma). |
| 743 | thread_local! { |
| 744 | static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 745 | } |
| 746 | |
| 747 | /// Current value of [`WARP_PLANE_SUPPRESS_HITS`]. |
| 748 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 749 | pub(crate) fn warp_plane_suppress_hits() -> usize { |
| 750 | WARP_PLANE_SUPPRESS_HITS.with(|c| c.get()) |
| 751 | } |
| 752 | |
| 753 | /// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and |
| 754 | /// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN |
| 755 | /// block dimensions decide it -- never the square `side`/`chroma_side`, which |
| 756 | /// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is |
| 757 | /// bigger than the real block in one axis. |
| 758 | pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool { |
| 759 | if w >= 8 && h >= 8 { |
| 760 | return true; |
| 761 | } |
| 762 | hit!(WARP_PLANE_SUPPRESS_HITS); |
| 763 | false |
| 764 | } |
| 765 | |
| 766 | /// Current value of [`CDEF_IDX_HITS`]. |
| 767 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 768 | pub(crate) fn cdef_idx_hits() -> usize { |
| 769 | CDEF_IDX_HITS.with(|c| c.get()) |
| 770 | } |
| 771 | |
| 772 | // lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no |
| 773 | // counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the |
| 774 | // non-chroma-reference block that must LEAVE its neighbours' chroma coefficient |
| 775 | // contexts alone, and the intra-edge filter neighbour pair taken mi-exact |
| 776 | // instead of from the coarse 16x16 cell. |
| 777 | thread_local! { |
| 778 | static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 779 | static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 780 | static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 781 | } |
| 782 | |
| 783 | /// Current value of [`INTRA_IN_INTER_TXCTX_HITS`]. |
| 784 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 785 | pub(crate) fn intra_in_inter_txctx_hits() -> usize { |
| 786 | INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get()) |
| 787 | } |
| 788 | |
| 789 | /// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`]. |
| 790 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 791 | pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize { |
| 792 | NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get()) |
| 793 | } |
| 794 | |
| 795 | /// Current value of [`EDGE_FILTER_MI_FIX_HITS`]. |
| 796 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 797 | pub(crate) fn edge_filter_mi_fix_hits() -> usize { |
| 798 | EDGE_FILTER_MI_FIX_HITS.with(|c| c.get()) |
| 799 | } |
| 800 | |
| 801 | // lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its |
| 802 | // actual step (`1 << delta.q_res`, already the real multiplier, not the raw |
| 803 | // 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a |
| 804 | // true no-op, matching every existing gate stream's `delta_q_present == 0` |
| 805 | // behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above. |
| 806 | // The running quantizer index (spec `CurrentQIndex`, libaom |
| 807 | // `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the |
| 808 | // top of every tile (spec `decode_tile`), carried across superblocks within |
| 809 | // that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the |
| 810 | // dequantization call sites instead of the frame-constant `base_q_idx`. |
| 811 | // This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11, |
| 812 | // spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not |
| 813 | // per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read |
| 814 | // back at every dequantization call site keyed on which plane it is doing. |
| 815 | // How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has |
| 816 | // read, across every call on the current thread -- the gate's proof that a |
| 817 | // `delta_q_present` stream actually reached the new reader. |
| 818 | thread_local! { |
| 819 | static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 820 | } |
| 821 | |
| 822 | /// Current value of [`DELTA_Q_HITS`]. |
| 823 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 824 | pub(crate) fn delta_q_hits() -> usize { |
| 825 | DELTA_Q_HITS.with(|c| c.get()) |
| 826 | } |
| 827 | |
| 828 | /// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 = |
| 829 | /// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads |
| 830 | /// one), so it is always `0` here. |
| 831 | fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) { |
| 832 | let d = fctx.quant_deltas.with(|c| c.get()); |
| 833 | match plane_idx { |
| 834 | 0 => (d.y_dc, 0), |
| 835 | 1 => (d.u_dc, d.u_ac), |
| 836 | _ => (d.v_dc, d.v_ac), |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | /// lane-av1-qmatrix: records this FRAME's quantisation-matrix levels |
| 841 | /// ([`crate::decode::FrameCtx::qm_levels`]) from the parsed |
| 842 | /// `quantization_params`. Called from `stream.rs` at the frame header, where |
| 843 | /// the refusal this lane lifted used to sit. |
| 844 | pub(crate) fn set_qm_levels(levels: [u8; 3], fctx: &crate::decode::FrameCtx) { |
| 845 | fctx.qm_levels.with(|c| c.set(levels)); |
| 846 | } |
| 847 | |
| 848 | /// This block's inverse quantisation matrix -- libaom `av1_get_iqmatrix` |
| 849 | /// (`av1/common/quant_common.c:243`) plus `setup_segmentation_dequant`'s |
| 850 | /// `av1_use_qmatrix` gate, evaluated per dequantisation call site the same |
| 851 | /// way the site already evaluates its quantizer index. `None` dequantises |
| 852 | /// flat (the only behaviour before lane-av1-qmatrix): |
| 853 | /// - a level of 15, which is both libaom's flat sentinel and what every |
| 854 | /// `using_qmatrix == 0` frame's levels are parked at; |
| 855 | /// - a 1D/identity transform (`is_2d_transform` false: libaom's |
| 856 | /// `av1_get_iqmatrix` reads the NULL slot for those); |
| 857 | /// - a LOSSLESS block (libaom `av1_use_qmatrix`'s `!xd->lossless[seg]`: the |
| 858 | /// segment-adjusted quantizer index clamped to 0 with all five plane |
| 859 | /// deltas zero -- the same `block_q_idx` every other dequant site reads). |
| 860 | fn block_iqmatrix( |
| 861 | fctx: &crate::decode::FrameCtx, |
| 862 | plane_idx: usize, |
| 863 | w: usize, |
| 864 | h: usize, |
| 865 | tx_type: TxType, |
| 866 | ) -> Option<crate::qm::Iqm> { |
| 867 | let levels = fctx.qm_levels.with(|c| c.get()); |
| 868 | let level = levels[plane_idx.min(2)]; |
| 869 | if usize::from(level) >= crate::qm::NUM_QM_LEVELS - 1 { |
| 870 | return None; |
| 871 | } |
| 872 | if !tx_type.is_2d_transform() { |
| 873 | return None; |
| 874 | } |
| 875 | let d = fctx.quant_deltas.with(|c| c.get()); |
| 876 | if block_q_idx(fctx) == 0 |
| 877 | && d.y_dc == 0 |
| 878 | && d.u_dc == 0 |
| 879 | && d.u_ac == 0 |
| 880 | && d.v_dc == 0 |
| 881 | && d.v_ac == 0 |
| 882 | { |
| 883 | return None; |
| 884 | } |
| 885 | crate::qm::iwt_matrix(usize::from(level), plane_idx != 0, w, h) |
| 886 | } |
| 887 | |
| 888 | /// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom |
| 889 | /// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`] |
| 890 | /// at every block-decode call site (spec order `skip -> cdef -> delta_q`). |
| 891 | /// A no-op when `delta_q_present` is unset, or when this block is not at the |
| 892 | /// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in |
| 893 | /// libaom, collapsed here to a position check since a partition tree's |
| 894 | /// top-left leaf is the only block that can ever land there), or when that |
| 895 | /// leaf both *is* the whole superblock and is `skip` (the one case libaom |
| 896 | /// itself skips the read, state carrying over unchanged). |
| 897 | 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) { |
| 898 | if !fctx.delta_q_present.with(|c| c.get()) { |
| 899 | return; |
| 900 | } |
| 901 | let sb_mi = sb_mi_cur(fctx) as usize; |
| 902 | if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 { |
| 903 | return; |
| 904 | } |
| 905 | // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, |
| 906 | // computed against the sequence's own superblock size (lane-sb128b r1: |
| 907 | // it used to be hardcoded against 64 and disabled under `sb128`, which a |
| 908 | // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes |
| 909 | // wrong). |
| 910 | if is_whole_sb && skip { |
| 911 | return; |
| 912 | } |
| 913 | let mut abs = dec.symbol(&mut cdfs.delta_q) as i32; |
| 914 | const DELTA_Q_SMALL: i32 = 3; |
| 915 | if abs >= DELTA_Q_SMALL { |
| 916 | let rem_bits = dec.literal(3) + 1; |
| 917 | let thr = (1i32 << rem_bits) + 1; |
| 918 | abs = dec.literal(rem_bits) as i32 + thr; |
| 919 | } |
| 920 | let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true }; |
| 921 | let reduced = if sign_negative { -abs } else { abs }; |
| 922 | hit!(DELTA_Q_HITS); |
| 923 | let res = fctx.delta_q_res.with(|c| c.get()); |
| 924 | fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255))); |
| 925 | } |
| 926 | |
| 927 | // lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi` |
| 928 | // (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`. |
| 929 | // The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`, |
| 930 | // `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile, |
| 931 | // mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever |
| 932 | // updates index 0 and every reader treats that as the value for all 4 |
| 933 | // indices (spec `read_delta_lf_params`'s own single-cdf branch). |
| 934 | // How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has |
| 935 | // read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`]. |
| 936 | thread_local! { |
| 937 | static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 938 | } |
| 939 | |
| 940 | /// Current value of [`DELTA_LF_HITS`]. |
| 941 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 942 | pub(crate) fn delta_lf_hits() -> usize { |
| 943 | DELTA_LF_HITS.with(|c| c.get()) |
| 944 | } |
| 945 | |
| 946 | /// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom |
| 947 | /// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as |
| 948 | /// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over |
| 949 | /// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or |
| 950 | /// read once into index 0 otherwise. |
| 951 | 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) { |
| 952 | if !fctx.delta_lf_present.with(|c| c.get()) { |
| 953 | return; |
| 954 | } |
| 955 | let sb_mi = sb_mi_cur(fctx) as usize; |
| 956 | if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 { |
| 957 | return; |
| 958 | } |
| 959 | // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, |
| 960 | // computed against the sequence's own superblock size (lane-sb128b r1: |
| 961 | // it used to be hardcoded against 64 and disabled under `sb128`, which a |
| 962 | // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes |
| 963 | // wrong). |
| 964 | if is_whole_sb && skip { |
| 965 | return; |
| 966 | } |
| 967 | let multi = fctx.delta_lf_multi.with(|c| c.get()); |
| 968 | let res = fctx.delta_lf_res.with(|c| c.get()); |
| 969 | let count = if multi { 4 } else { 1 }; |
| 970 | let mut cur = fctx.current_delta_lf.with(|c| c.get()); |
| 971 | for i in 0..count { |
| 972 | let mut abs = if multi { |
| 973 | dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32 |
| 974 | } else { |
| 975 | dec.symbol(&mut cdfs.delta_lf) as i32 |
| 976 | }; |
| 977 | const DELTA_LF_SMALL: i32 = 3; |
| 978 | if abs >= DELTA_LF_SMALL { |
| 979 | let rem_bits = dec.literal(3) + 1; |
| 980 | let thr = (1i32 << rem_bits) + 1; |
| 981 | abs = dec.literal(rem_bits) as i32 + thr; |
| 982 | } |
| 983 | let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true }; |
| 984 | let reduced = if sign_negative { -abs } else { abs }; |
| 985 | cur[i] = (cur[i] + reduced * res).clamp(-63, 63); |
| 986 | hit!(DELTA_LF_HITS); |
| 987 | } |
| 988 | fctx.current_delta_lf.with(|c| c.set(cur)); |
| 989 | } |
| 990 | |
| 991 | /// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right |
| 992 | /// after `skip` is known at every block-decode call site. A no-op at |
| 993 | /// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and |
| 994 | /// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/ |
| 995 | /// `allow_intrabc`, so neither needs a separate check here. Reads once per |
| 996 | /// superblock, at the first non-skip block. |
| 997 | fn maybe_read_cdef_idx( |
| 998 | dec: &mut SymbolDecoder, |
| 999 | mi_r: usize, |
| 1000 | mi_c: usize, |
| 1001 | // The reading BLOCK's own span in 4x4 mode-info units: a block wider or |
| 1002 | // taller than one 64x64 CDEF unit is the first non-skip block of EVERY |
| 1003 | // unit it covers, so its one literal drives all of them (lane-b128r). |
| 1004 | (w_mi, h_mi): (usize, usize), |
| 1005 | skip: bool, |
| 1006 | fctx: &crate::decode::FrameCtx, |
| 1007 | ) { |
| 1008 | let bits = fctx.cdef_bits.with(|c| c.get()); |
| 1009 | if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) { |
| 1010 | return; |
| 1011 | } |
| 1012 | let idx = dec.literal(u32::from(bits)) as u8; |
| 1013 | fctx.cdef_transmitted.with(|c| c.set(true)); |
| 1014 | hit!(CDEF_IDX_HITS); |
| 1015 | let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize); |
| 1016 | let sb_cols = fctx.cdef_sb_cols.with(|c| c.get()); |
| 1017 | if sb_cols > 0 { |
| 1018 | // lane-b128r: libaom's four CDEF units of a 128 superblock all read |
| 1019 | // their strength off the MB_MODE_INFO of the first non-skip block in |
| 1020 | // their own unit -- and a block that COVERS several units (the 128 |
| 1021 | // root's own 128x128 block, the only one there is) is that block for |
| 1022 | // every unit it covers, so one literal drives all four. This grid is |
| 1023 | // per 64x64 unit, so the read stamps every unit the block covers; one |
| 1024 | // that is smaller than a unit stamps exactly the cell it always did. |
| 1025 | let (rows, cols) = ( |
| 1026 | (h_mi / SB_MI as usize).max(1), |
| 1027 | (w_mi / SB_MI as usize).max(1), |
| 1028 | ); |
| 1029 | fctx.cdef_idx_grid.with(|g| { |
| 1030 | let mut g = g.borrow_mut(); |
| 1031 | for dr in 0..rows { |
| 1032 | for dc in 0..cols { |
| 1033 | let i = (sb_r + dr) * sb_cols + sb_c + dc; |
| 1034 | if sb_c + dc < sb_cols && i < g.len() { |
| 1035 | g[i] = idx; |
| 1036 | } |
| 1037 | } |
| 1038 | } |
| 1039 | }); |
| 1040 | } |
| 1041 | } |
| 1042 | |
| 1043 | // --------------------------------------------------------------------------- |
| 1044 | // lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`; |
| 1045 | // this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus |
| 1046 | // the two consumers a real stream exercises: the per-segment quantizer index |
| 1047 | // (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level |
| 1048 | // (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/ |
| 1049 | // `read_intra_segment_id`/`read_inter_segment_id` and |
| 1050 | // `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL |
| 1051 | // PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which |
| 1052 | // is what the oracle every gate here compares against actually does. |
| 1053 | thread_local! { |
| 1054 | /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries |
| 1055 | /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride). |
| 1056 | /// `PrevSegmentIds`: the primary reference frame's saved map, empty when |
| 1057 | /// this frame has no primary reference (spec `load_previous_segment_ids`). |
| 1058 | /// `(mi_rows, mi_cols)` for both maps above. |
| 1059 | /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi |
| 1060 | /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which |
| 1061 | /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead. |
| 1062 | /// The block currently being decoded -- read back by [`block_q_idx`]. |
| 1063 | /// The tile's own top-left mi position, for `AvailU`/`AvailL`. |
| 1064 | /// How many real `segment_id` symbols were read, and the set of segment |
| 1065 | /// ids any block ended up with -- the gate's proof the feature fired. |
| 1066 | static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1067 | static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) }; |
| 1068 | /// lane-golomb2: the (lowest, highest) quantizer index any block has been |
| 1069 | /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to |
| 1070 | /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than |
| 1071 | /// zero (class `gate-blind-to-feature`): segmentation being enabled says |
| 1072 | /// nothing about the segments carrying distinct quantizers. |
| 1073 | static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) }; |
| 1074 | /// How many `seg_id_predicted` symbols were read (temporal update). |
| 1075 | static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1076 | } |
| 1077 | |
| 1078 | /// Installs this frame's segmentation parameters and allocates its map, with |
| 1079 | /// `prev` the primary reference frame's saved map (spec |
| 1080 | /// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty |
| 1081 | /// slot). Called once per frame, whether or not segmentation is enabled. |
| 1082 | pub(crate) fn set_segmentation( |
| 1083 | seg: SegmentationParams, |
| 1084 | mi_rows: usize, |
| 1085 | mi_cols: usize, |
| 1086 | prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx, |
| 1087 | ) { |
| 1088 | if crate::envflags::env_flag!("EC_HDR") { |
| 1089 | eprintln!( |
| 1090 | "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}", |
| 1091 | seg.enabled, seg.update_map, seg.temporal_update, seg.seg_id_pre_skip, seg.last_active_seg_id, seg.feature_data |
| 1092 | ); |
| 1093 | } |
| 1094 | fctx.seg.with(|s| *s.borrow_mut() = seg); |
| 1095 | fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols))); |
| 1096 | fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]); |
| 1097 | fctx.prev_seg_ids.with(|m| { |
| 1098 | let mut m = m.borrow_mut(); |
| 1099 | m.clear(); |
| 1100 | if let Some(p) = prev { |
| 1101 | if p.len() == mi_rows * mi_cols { |
| 1102 | m.extend_from_slice(p); |
| 1103 | } |
| 1104 | } |
| 1105 | }); |
| 1106 | fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]); |
| 1107 | fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]); |
| 1108 | fctx.cur_segment_id.with(|c| c.set(0)); |
| 1109 | } |
| 1110 | |
| 1111 | /// This frame's decoded segment map, to be stored into whichever reference |
| 1112 | /// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`). |
| 1113 | pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> { |
| 1114 | fctx.seg_ids.with(|m| m.borrow().clone()) |
| 1115 | } |
| 1116 | |
| 1117 | /// How many `segment_id` symbols have been read (never reset per frame). |
| 1118 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1119 | pub(crate) fn segment_id_hits() -> usize { |
| 1120 | SEG_ID_HITS.with(|c| c.get()) |
| 1121 | } |
| 1122 | |
| 1123 | /// How many distinct segment ids any decoded block has carried. |
| 1124 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1125 | pub(crate) fn segment_ids_seen() -> usize { |
| 1126 | SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize) |
| 1127 | } |
| 1128 | |
| 1129 | /// The lowest and highest quantizer index any decoded block was dequantized |
| 1130 | /// with (`(i32::MAX, i32::MIN)` when nothing decoded). |
| 1131 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1132 | pub(crate) fn block_q_span() -> (i32, i32) { |
| 1133 | BLOCK_Q_SPAN.with(|c| c.get()) |
| 1134 | } |
| 1135 | |
| 1136 | /// How many `seg_id_predicted` symbols have been read (temporal update). |
| 1137 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1138 | pub(crate) fn segment_pred_hits() -> usize { |
| 1139 | SEG_PRED_HITS.with(|c| c.get()) |
| 1140 | } |
| 1141 | |
| 1142 | /// Resets the segmentation hit counters (gate setup). |
| 1143 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1144 | pub(crate) fn reset_segment_hits() { |
| 1145 | SEG_ID_HITS.with(|c| c.set(0)); |
| 1146 | SEG_IDS_SEEN.with(|c| c.set(0)); |
| 1147 | SEG_PRED_HITS.with(|c| c.set(0)); |
| 1148 | BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN))); |
| 1149 | } |
| 1150 | |
| 1151 | /// `seg_feature_active_idx(segment_id, feature)` for the frame currently |
| 1152 | /// being decoded, with its `FeatureData` value. |
| 1153 | fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> { |
| 1154 | fctx.seg.with(|s| { |
| 1155 | let s = s.borrow(); |
| 1156 | s.feature_active(segment_id, feature) |
| 1157 | .then(|| i32::from(s.feature_data[segment_id][feature])) |
| 1158 | }) |
| 1159 | } |
| 1160 | |
| 1161 | /// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom |
| 1162 | /// `av1_get_qindex`) for the block currently being decoded: the running |
| 1163 | /// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data. |
| 1164 | /// Every dequant call site reads the block's quantizer through here. |
| 1165 | fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 { |
| 1166 | let base = fctx.current_q_idx.with(|c| c.get()); |
| 1167 | let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize; |
| 1168 | let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) { |
| 1169 | Some(data) => (base + data).clamp(0, 255), |
| 1170 | None => base, |
| 1171 | }; |
| 1172 | // lane-d792: which SEGMENT a block's quantizer came out of, beside the |
| 1173 | // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels |
| 1174 | // already proven equal is a segment-id defect, not a quantizer one. |
| 1175 | if crate::envflags::env_flag!("EC_DQCOEFF") { |
| 1176 | eprintln!("OUR_Q base={base} seg={seg_id} q={q}"); |
| 1177 | } |
| 1178 | hit_do!(BLOCK_Q_SPAN.with(|c| { |
| 1179 | let (lo, hi) = c.get(); |
| 1180 | c.set((lo.min(q), hi.max(q))); |
| 1181 | });); |
| 1182 | q |
| 1183 | } |
| 1184 | |
| 1185 | /// The segment id recorded for one mi cell of the current frame's map. |
| 1186 | fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 { |
| 1187 | let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); |
| 1188 | if mi_r >= mi_rows || mi_c >= mi_cols { |
| 1189 | return 0; |
| 1190 | } |
| 1191 | fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c]) |
| 1192 | } |
| 1193 | |
| 1194 | /// `set_segment_id`: stamps `id` over every mi cell this block covers. |
| 1195 | fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) { |
| 1196 | let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); |
| 1197 | let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r))); |
| 1198 | fctx.seg_ids.with(|m| { |
| 1199 | let mut m = m.borrow_mut(); |
| 1200 | for y in 0..y_mis { |
| 1201 | for x in 0..x_mis { |
| 1202 | m[(mi_r + y) * mi_cols + mi_c + x] = id; |
| 1203 | } |
| 1204 | } |
| 1205 | }); |
| 1206 | fctx.cur_segment_id.with(|c| c.set(id)); |
| 1207 | SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id)); |
| 1208 | } |
| 1209 | |
| 1210 | /// `copy_segment_id` (libaom `decodemv.c:342`): the previous frame's map is |
| 1211 | /// inherited VERBATIM over this block's own mi footprint -- per-cell copies, |
| 1212 | /// not the minified id [`predicted_segment_id`] hands the block. Without a |
| 1213 | /// previous map the footprint is zeroed, exactly as the C NULL branch does. |
| 1214 | fn copy_segment_ids(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) { |
| 1215 | let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); |
| 1216 | let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r))); |
| 1217 | fctx.seg_ids.with(|m| { |
| 1218 | let mut m = m.borrow_mut(); |
| 1219 | fctx.prev_seg_ids.with(|p| { |
| 1220 | let p = p.borrow(); |
| 1221 | for y in 0..y_mis { |
| 1222 | for x in 0..x_mis { |
| 1223 | let idx = (mi_r + y) * mi_cols + mi_c + x; |
| 1224 | m[idx] = p.get(idx).copied().unwrap_or(0); |
| 1225 | } |
| 1226 | } |
| 1227 | }); |
| 1228 | }); |
| 1229 | } |
| 1230 | |
| 1231 | /// `get_predicted_segment_id` (libaom `dec_get_segment_id` over |
| 1232 | /// `last_frame_seg_map`): the minimum previous-frame segment id over the |
| 1233 | /// block's own mi footprint. `0` when there is no previous map. |
| 1234 | fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 { |
| 1235 | let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); |
| 1236 | fctx.prev_seg_ids.with(|m| { |
| 1237 | let m = m.borrow(); |
| 1238 | if m.is_empty() { |
| 1239 | return 0; |
| 1240 | } |
| 1241 | let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r))); |
| 1242 | let mut id = u8::MAX; |
| 1243 | for y in 0..y_mis { |
| 1244 | for x in 0..x_mis { |
| 1245 | id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]); |
| 1246 | } |
| 1247 | } |
| 1248 | if id == u8::MAX { 0 } else { id } |
| 1249 | }) |
| 1250 | } |
| 1251 | |
| 1252 | /// `av1_neg_deinterleave` (libaom `decodemv.c:258`). |
| 1253 | fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 { |
| 1254 | if reference == 0 { |
| 1255 | return diff; |
| 1256 | } |
| 1257 | if reference >= max - 1 { |
| 1258 | return max - diff - 1; |
| 1259 | } |
| 1260 | let half = if 2 * reference < max { |
| 1261 | diff <= 2 * reference |
| 1262 | } else { |
| 1263 | diff <= 2 * (max - reference - 1) |
| 1264 | }; |
| 1265 | if half { |
| 1266 | return if diff & 1 != 0 { |
| 1267 | reference + ((diff + 1) >> 1) |
| 1268 | } else { |
| 1269 | reference - (diff >> 1) |
| 1270 | }; |
| 1271 | } |
| 1272 | if 2 * reference < max { diff } else { max - (diff + 1) } |
| 1273 | } |
| 1274 | |
| 1275 | /// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current |
| 1276 | /// frame's already-decoded above/left/above-left neighbours. |
| 1277 | fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) { |
| 1278 | let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get()); |
| 1279 | let (avail_u, avail_l) = (mi_r > row0, mi_c > col0); |
| 1280 | let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx))); |
| 1281 | let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx))); |
| 1282 | let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx))); |
| 1283 | let ctx = match prev_ul { |
| 1284 | None => 0, |
| 1285 | Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2, |
| 1286 | Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1, |
| 1287 | Some(_) => 0, |
| 1288 | }; |
| 1289 | let pred = match (prev_u, prev_l) { |
| 1290 | (None, l) => l.unwrap_or(0), |
| 1291 | (Some(u), None) => u, |
| 1292 | (Some(u), Some(l)) => { |
| 1293 | if prev_ul == Some(u) { |
| 1294 | u |
| 1295 | } else { |
| 1296 | l |
| 1297 | } |
| 1298 | } |
| 1299 | }; |
| 1300 | (pred, ctx) |
| 1301 | } |
| 1302 | |
| 1303 | /// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id |
| 1304 | /// when `skip`, otherwise one `segment_id` symbol de-interleaved against |
| 1305 | /// that prediction. Does NOT write the map -- callers do. |
| 1306 | fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 { |
| 1307 | let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx); |
| 1308 | if skip { |
| 1309 | return pred as u8; |
| 1310 | } |
| 1311 | let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32; |
| 1312 | hit!(SEG_ID_HITS); |
| 1313 | let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id)); |
| 1314 | let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active); |
| 1315 | // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..` |
| 1316 | // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff. |
| 1317 | if crate::envflags::env_flag!("EC_TRACE_SEG") { |
| 1318 | eprintln!("EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}", dec.debug_state().0); |
| 1319 | } |
| 1320 | id as u8 |
| 1321 | } |
| 1322 | |
| 1323 | /// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block |
| 1324 | /// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the |
| 1325 | /// caller decides which by passing `pre_skip`). |
| 1326 | fn intra_segment_id( |
| 1327 | dec: &mut SymbolDecoder, |
| 1328 | cdfs: &mut Cdfs, |
| 1329 | mi_r: usize, |
| 1330 | mi_c: usize, |
| 1331 | w_mi: usize, |
| 1332 | h_mi: usize, |
| 1333 | skip: bool, fctx: &crate::decode::FrameCtx, |
| 1334 | ) { |
| 1335 | if !fctx.seg.with(|s| s.borrow().enabled) { |
| 1336 | return; |
| 1337 | } |
| 1338 | let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx); |
| 1339 | write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx); |
| 1340 | } |
| 1341 | |
| 1342 | /// Whether this frame's intra blocks read their `segment_id` before `skip` |
| 1343 | /// (`SegIdPreSkip`); `false` also when segmentation is off. |
| 1344 | fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool { |
| 1345 | fctx.seg.with(|s| { |
| 1346 | let s = s.borrow(); |
| 1347 | s.enabled && s.seg_id_pre_skip |
| 1348 | }) |
| 1349 | } |
| 1350 | |
| 1351 | /// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`). |
| 1352 | /// Called at both spec positions of an inter frame's block: `pre_skip = true` |
| 1353 | /// before `skip_mode`/`skip`, and `pre_skip = false` after them. |
| 1354 | fn inter_segment_id( |
| 1355 | dec: &mut SymbolDecoder, |
| 1356 | cdfs: &mut Cdfs, |
| 1357 | mi_r: usize, |
| 1358 | mi_c: usize, |
| 1359 | w_mi: usize, |
| 1360 | h_mi: usize, |
| 1361 | skip: bool, |
| 1362 | pre_skip: bool, fctx: &crate::decode::FrameCtx, |
| 1363 | ) { |
| 1364 | let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| { |
| 1365 | let s = s.borrow(); |
| 1366 | (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip) |
| 1367 | }); |
| 1368 | if !enabled { |
| 1369 | return; |
| 1370 | } |
| 1371 | if !update_map { |
| 1372 | // The map is inherited from the previous frame, and libaom's |
| 1373 | // `copy_segment_id` (decodemv.c:342) does that VERBATIM -- a memcpy of |
| 1374 | // the previous map over the block's own footprint, mixed ids intact -- |
| 1375 | // while the id the BLOCK itself carries is the min over that footprint |
| 1376 | // (`get_predicted_segment_id`). Stamping the min here flattened mixed |
| 1377 | // footprints into the saved map, and every later frame whose |
| 1378 | // `update_map == 0` copy or temporal prediction read that position |
| 1379 | // dequantized with the wrong segment's `SEG_LVL_ALT_Q` (class |
| 1380 | // `simplified-inheritance`). |
| 1381 | copy_segment_ids(mi_r, mi_c, w_mi, h_mi, fctx); |
| 1382 | let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx); |
| 1383 | fctx.cur_segment_id.with(|c| c.set(id)); |
| 1384 | SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id)); |
| 1385 | return; |
| 1386 | } |
| 1387 | if pre_skip && !pre_skip_frame { |
| 1388 | return; |
| 1389 | } |
| 1390 | if !pre_skip && skip { |
| 1391 | // libaom: a skipped block never codes `seg_id_predicted`, and its |
| 1392 | // segment id is the spatial prediction. |
| 1393 | stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx); |
| 1394 | let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx); |
| 1395 | write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx); |
| 1396 | return; |
| 1397 | } |
| 1398 | let id = if temporal_update { |
| 1399 | let ctx = seg_pred_ctx(mi_r, mi_c, fctx); |
| 1400 | let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0; |
| 1401 | hit!(SEG_PRED_HITS); |
| 1402 | stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx); |
| 1403 | if predicted { |
| 1404 | predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx) |
| 1405 | } else { |
| 1406 | read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx) |
| 1407 | } |
| 1408 | } else { |
| 1409 | read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx) |
| 1410 | }; |
| 1411 | write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx); |
| 1412 | } |
| 1413 | |
| 1414 | /// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags. |
| 1415 | fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize { |
| 1416 | // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and |
| 1417 | // so contribute 0) outside the tile -- the availability check here is |
| 1418 | // what keeps a previous tile's stamps out of this tile's context. |
| 1419 | let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get()); |
| 1420 | let above = if mi_r > row0 { |
| 1421 | fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0)) |
| 1422 | } else { |
| 1423 | 0 |
| 1424 | }; |
| 1425 | let left = if mi_c > col0 { |
| 1426 | fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0)) |
| 1427 | } else { |
| 1428 | 0 |
| 1429 | }; |
| 1430 | usize::from(above + left) |
| 1431 | } |
| 1432 | |
| 1433 | /// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update. |
| 1434 | fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) { |
| 1435 | fctx.above_seg_pred.with(|m| { |
| 1436 | let mut m = m.borrow_mut(); |
| 1437 | for i in 0..w_mi { |
| 1438 | if let Some(cell) = m.get_mut(mi_c + i) { |
| 1439 | *cell = value; |
| 1440 | } |
| 1441 | } |
| 1442 | }); |
| 1443 | fctx.left_seg_pred.with(|m| { |
| 1444 | let mut m = m.borrow_mut(); |
| 1445 | for i in 0..h_mi { |
| 1446 | if let Some(cell) = m.get_mut(mi_r + i) { |
| 1447 | *cell = value; |
| 1448 | } |
| 1449 | } |
| 1450 | }); |
| 1451 | } |
| 1452 | |
| 1453 | // How many key-frame luma blocks resolved `smooth_neighbor` (spec |
| 1454 | // `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after |
| 1455 | // counter, proving a stream actually put a directional block next to a |
| 1456 | // smooth-predicted neighbour rather than every block reading the (previously |
| 1457 | // hardcoded `false`) edge-filter strength bucket unchanged. |
| 1458 | thread_local! { |
| 1459 | static SMOOTH_LUMA_HITS: std::cell::Cell<usize> = |
| 1460 | const { std::cell::Cell::new(0) }; |
| 1461 | } |
| 1462 | |
| 1463 | /// Current value of [`SMOOTH_LUMA_HITS`]. |
| 1464 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1465 | pub(crate) fn smooth_luma_hits() -> usize { |
| 1466 | SMOOTH_LUMA_HITS.with(|c| c.get()) |
| 1467 | } |
| 1468 | |
| 1469 | thread_local! { |
| 1470 | /// lane-band46 r1: how many split-transform units answered their intra |
| 1471 | /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the |
| 1472 | /// palette2 r12 fix) than the standalone-block lookup this decoder used to |
| 1473 | /// apply to them (class reach-is-per-transform-unit). Every hit is a |
| 1474 | /// transform unit whose above-right / below-left reference samples would |
| 1475 | /// be wrong without that fix. |
| 1476 | static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> = |
| 1477 | const { std::cell::Cell::new(0) }; |
| 1478 | } |
| 1479 | |
| 1480 | /// Current value of [`SPLIT_TU_REACH_FIX_HITS`]. |
| 1481 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1482 | pub(crate) fn split_tu_reach_fix_hits() -> usize { |
| 1483 | SPLIT_TU_REACH_FIX_HITS.with(|c| c.get()) |
| 1484 | } |
| 1485 | |
| 1486 | /// [`Reach::of_tu`] for one transform unit, counting how often that per-unit |
| 1487 | /// answer differs from the standalone-block answer the call sites used before |
| 1488 | /// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really |
| 1489 | /// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent |
| 1490 | /// block's top-left `(px, py)`. |
| 1491 | #[allow(clippy::too_many_arguments)] |
| 1492 | fn tu_reach( |
| 1493 | bw: usize, |
| 1494 | bh: usize, |
| 1495 | col_off: usize, |
| 1496 | row_off: usize, |
| 1497 | tx: usize, |
| 1498 | block: Reach, |
| 1499 | px: usize, |
| 1500 | py: usize, |
| 1501 | width: usize, |
| 1502 | height: usize, fctx: &crate::decode::FrameCtx, |
| 1503 | ) -> Reach { |
| 1504 | let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block); |
| 1505 | let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx); |
| 1506 | if fixed != standalone { |
| 1507 | hit!(SPLIT_TU_REACH_FIX_HITS); |
| 1508 | } |
| 1509 | fixed |
| 1510 | } |
| 1511 | |
| 1512 | // How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12), |
| 1513 | // across every call on the current thread -- lane-chroma r3's own before/after |
| 1514 | // counter, proving a stream actually exercised chroma's smooth/paeth |
| 1515 | // predictor (the previously-refused round-2 gap) rather than every block |
| 1516 | // landing on DC/CFL/directional. |
| 1517 | thread_local! { |
| 1518 | static SMOOTH_UV_HITS: std::cell::Cell<usize> = |
| 1519 | const { std::cell::Cell::new(0) }; |
| 1520 | } |
| 1521 | |
| 1522 | /// Current value of [`SMOOTH_UV_HITS`]. |
| 1523 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1524 | pub(crate) fn smooth_uv_hits() -> usize { |
| 1525 | SMOOTH_UV_HITS.with(|c| c.get()) |
| 1526 | } |
| 1527 | |
| 1528 | // How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a |
| 1529 | // full superblock walk over, across every call on the current thread -- |
| 1530 | // lane-tiles r2's own gate-blind-to-feature guard: a gate over a |
| 1531 | // multi-tile stream must prove more than one tile actually fired, not just |
| 1532 | // that the stream carried tile_info.cols > 1. |
| 1533 | thread_local! { |
| 1534 | static TILE_HITS: std::cell::Cell<usize> = |
| 1535 | const { std::cell::Cell::new(0) }; |
| 1536 | } |
| 1537 | /// Current value of [`TILE_HITS`]. |
| 1538 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1539 | pub(crate) fn tile_hits() -> usize { |
| 1540 | TILE_HITS.with(|c| c.get()) |
| 1541 | } |
| 1542 | |
| 1543 | // How many 4-pixel deblocking edge groups [`edge_params`] has actually |
| 1544 | // selected for filtering, across every call on the current thread -- the same |
| 1545 | // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream |
| 1546 | // exercised `apply_deblock` rather than every edge landing on level 0. |
| 1547 | thread_local! { |
| 1548 | static DEBLOCK_HITS: std::cell::Cell<usize> = |
| 1549 | const { std::cell::Cell::new(0) }; |
| 1550 | } |
| 1551 | /// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`, |
| 1552 | /// mirroring stream.rs's `pictures_decoded` so the two dumps index |
| 1553 | /// identically against aomdec's own `ec_frame_idx` in decodeframe.c. |
| 1554 | static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize = |
| 1555 | std::sync::atomic::AtomicUsize::new(0); |
| 1556 | |
| 1557 | /// Current value of [`DEBLOCK_HITS`]. |
| 1558 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1559 | pub(crate) fn deblock_hits() -> usize { |
| 1560 | DEBLOCK_HITS.with(|c| c.get()) |
| 1561 | } |
| 1562 | |
| 1563 | // lane-defon r1: how many COMPOUND_REFERENCE blocks read a |
| 1564 | // `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side, |
| 1565 | // spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a |
| 1566 | // stream built with `--enable-onesided-comp=1` really exercised the |
| 1567 | // `uni_comp_ref` alphabet rather than only bidirectional pairs. |
| 1568 | thread_local! { |
| 1569 | static UNI_COMP_HITS: std::cell::Cell<usize> = |
| 1570 | const { std::cell::Cell::new(0) }; |
| 1571 | } |
| 1572 | |
| 1573 | /// Current value of [`UNI_COMP_HITS`]. |
| 1574 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1575 | pub(crate) fn uni_comp_hits() -> usize { |
| 1576 | UNI_COMP_HITS.with(|c| c.get()) |
| 1577 | } |
| 1578 | |
| 1579 | // lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask |
| 1580 | // (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the |
| 1581 | // gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted |
| 1582 | // blend and not only the wedge arm. |
| 1583 | thread_local! { |
| 1584 | static DIFFWTD_HITS: std::cell::Cell<usize> = |
| 1585 | const { std::cell::Cell::new(0) }; |
| 1586 | } |
| 1587 | |
| 1588 | /// Current value of [`DIFFWTD_HITS`]. |
| 1589 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1590 | pub(crate) fn diffwtd_hits() -> usize { |
| 1591 | DIFFWTD_HITS.with(|c| c.get()) |
| 1592 | } |
| 1593 | |
| 1594 | // lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm -- |
| 1595 | // a block size where `av1_is_wedge_used` is false (64x64 is the only such size |
| 1596 | // this decoder's square inter path reaches), so no `compound_type` symbol is |
| 1597 | // coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the |
| 1598 | // coded-symbol DIFFWTD blocks at 8x8/16x16/32x32. |
| 1599 | thread_local! { |
| 1600 | static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> = |
| 1601 | const { std::cell::Cell::new(0) }; |
| 1602 | } |
| 1603 | |
| 1604 | /// Current value of [`DIFFWTD_INFERRED_HITS`]. |
| 1605 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1606 | pub(crate) fn diffwtd_inferred_hits() -> usize { |
| 1607 | DIFFWTD_INFERRED_HITS.with(|c| c.get()) |
| 1608 | } |
| 1609 | |
| 1610 | // lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded |
| 1611 | // with `show_frame == 0`, output later by a `show_existing_frame` header |
| 1612 | // (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from |
| 1613 | // `stream::decode_stream`, which is where the frame header is consumed; the |
| 1614 | // gate's proof that the on-value really reached the bitstream rather than |
| 1615 | // being dropped by the rate control. |
| 1616 | thread_local! { |
| 1617 | static FWD_KF_HITS: std::cell::Cell<usize> = |
| 1618 | const { std::cell::Cell::new(0) }; |
| 1619 | } |
| 1620 | |
| 1621 | /// Current value of [`FWD_KF_HITS`]. |
| 1622 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1623 | pub(crate) fn fwd_kf_hits() -> usize { |
| 1624 | FWD_KF_HITS.with(|c| c.get()) |
| 1625 | } |
| 1626 | |
| 1627 | /// Records one decoded forward keyframe (see [`FWD_KF_HITS`]). |
| 1628 | pub(crate) fn note_fwd_kf() { |
| 1629 | hit!(FWD_KF_HITS); |
| 1630 | } |
| 1631 | |
| 1632 | // How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than |
| 1633 | // the block's own side, across every call on the current thread -- the same |
| 1634 | // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream |
| 1635 | // actually exercised a *split* transform under `TxMode::Select` rather than |
| 1636 | // every block coincidentally resolving `depth=0` (indistinguishable from |
| 1637 | // `TxMode::Largest` pixel-wise). |
| 1638 | thread_local! { |
| 1639 | static TX_DEPTH_HITS: std::cell::Cell<usize> = |
| 1640 | const { std::cell::Cell::new(0) }; |
| 1641 | } |
| 1642 | |
| 1643 | // How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma |
| 1644 | // transform smaller than their own side (`tx_depth != 0`) while coding a |
| 1645 | // chroma prediction other than `DC_PRED` -- the pair the square path's chroma |
| 1646 | // only exercises with aomenc's tx-size search left ON (its default), which |
| 1647 | // every older recipe in this file pins off. Counted at the block, so a stream |
| 1648 | // where RD happened to give every split-transform block a DC chroma mode |
| 1649 | // reads as zero rather than silently passing for free. |
| 1650 | thread_local! { |
| 1651 | static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> = |
| 1652 | const { std::cell::Cell::new(0) }; |
| 1653 | } |
| 1654 | |
| 1655 | /// Current value of [`SQ_CHROMA_TX_HITS`]. |
| 1656 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1657 | pub(crate) fn sq_chroma_tx_hits() -> usize { |
| 1658 | SQ_CHROMA_TX_HITS.with(|c| c.get()) |
| 1659 | } |
| 1660 | |
| 1661 | /// Current value of [`TX_DEPTH_HITS`]. |
| 1662 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1663 | pub(crate) fn tx_depth_hits() -> usize { |
| 1664 | TX_DEPTH_HITS.with(|c| c.get()) |
| 1665 | } |
| 1666 | |
| 1667 | // lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree |
| 1668 | // read, and how many of those actually took the split, on the current thread |
| 1669 | // -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a |
| 1670 | // stream exercised spec 5.11.17's `read_var_tx_size` rather than every block |
| 1671 | // coincidentally coding one whole-block transform. |
| 1672 | thread_local! { |
| 1673 | static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1674 | static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1675 | // lane-inter4 r2: rectangular INTER residual coding -- how many rect |
| 1676 | // strips coded one whole-block rect transform unit, and how many split |
| 1677 | // their rect max transform into square sub-transforms. |
| 1678 | static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1679 | static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1680 | // lane-r14 r2: luma transform units of an inter strip with a 64-px axis |
| 1681 | // (64x32/32x64/64x16/16x64), whose coefficients are coded as the |
| 1682 | // truncated low-32 corner. |
| 1683 | static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1684 | // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4 |
| 1685 | // inter strip, `[32x8, 8x32]`. |
| 1686 | static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; |
| 1687 | // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32]. |
| 1688 | static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; |
| 1689 | // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8] |
| 1690 | // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip. |
| 1691 | static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; |
| 1692 | // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter |
| 1693 | // frame -- 16x8 and 8x16 inter leaves. |
| 1694 | static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1695 | static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1696 | // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits, |
| 1697 | // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] -- |
| 1698 | // `decode_inter_block` already carries forty parameters and both are |
| 1699 | // frame-constant. |
| 1700 | // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit, |
| 1701 | // frame-constant like the two above and stashed the same way -- an intra |
| 1702 | // block inside an inter frame reads `use_filter_intra` under it. |
| 1703 | } |
| 1704 | |
| 1705 | /// Current value of [`TXFM_SPLIT_READS`]. |
| 1706 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1707 | pub(crate) fn txfm_split_reads() -> usize { |
| 1708 | TXFM_SPLIT_READS.with(|c| c.get()) |
| 1709 | } |
| 1710 | |
| 1711 | /// Current value of [`TXFM_SPLIT_HITS`]. |
| 1712 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1713 | pub(crate) fn txfm_split_hits() -> usize { |
| 1714 | TXFM_SPLIT_HITS.with(|c| c.get()) |
| 1715 | } |
| 1716 | |
| 1717 | /// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3). |
| 1718 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1719 | pub(crate) fn inter_leaf16_horz_hits() -> usize { |
| 1720 | INTER_LEAF16_HORZ_HITS.with(|c| c.get()) |
| 1721 | } |
| 1722 | |
| 1723 | /// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3). |
| 1724 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1725 | pub(crate) fn inter_leaf16_vert_hits() -> usize { |
| 1726 | INTER_LEAF16_VERT_HITS.with(|c| c.get()) |
| 1727 | } |
| 1728 | |
| 1729 | /// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2). |
| 1730 | pub(crate) fn rect_inter_tu_hits() -> usize { |
| 1731 | RECT_INTER_TU_HITS.with(|c| c.get()) |
| 1732 | } |
| 1733 | |
| 1734 | /// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2). |
| 1735 | pub(crate) fn rect_inter_txsplit_hits() -> usize { |
| 1736 | RECT_INTER_TXSPLIT_HITS.with(|c| c.get()) |
| 1737 | } |
| 1738 | |
| 1739 | /// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2). |
| 1740 | pub(crate) fn rect64_inter_tu_hits() -> usize { |
| 1741 | RECT64_INTER_TU_HITS.with(|c| c.get()) |
| 1742 | } |
| 1743 | |
| 1744 | /// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]` |
| 1745 | /// whole-block luma units of a 32x32-level 1:4 inter strip. |
| 1746 | pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] { |
| 1747 | RECT32X8_INTER_TU_HITS.with(|c| c.get()) |
| 1748 | } |
| 1749 | |
| 1750 | /// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many |
| 1751 | /// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`. |
| 1752 | pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] { |
| 1753 | VARTX_RECT_LEAF_HITS.with(|c| c.get()) |
| 1754 | } |
| 1755 | |
| 1756 | /// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8 |
| 1757 | /// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`. |
| 1758 | pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] { |
| 1759 | VARTX_RECT_LEAF4_HITS.with(|c| c.get()) |
| 1760 | } |
| 1761 | |
| 1762 | /// Records one rectangular var-tx leaf. |
| 1763 | fn vartx_rect_leaf_hit(tw: usize, th: usize) { |
| 1764 | if crate::envflags::env_flag!("EC_VARTXLEAF") { |
| 1765 | eprintln!("EC_VARTXLEAF tw={tw} th={th}"); |
| 1766 | } |
| 1767 | let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS }; |
| 1768 | cell.with(|c| { |
| 1769 | let mut h = c.get(); |
| 1770 | h[usize::from(th > tw)] += 1; |
| 1771 | c.set(h); |
| 1772 | }); |
| 1773 | } |
| 1774 | |
| 1775 | /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/ |
| 1776 | /// [`ENABLE_FILTER_INTRA_INTER`]. |
| 1777 | pub(crate) fn set_inter_tx_mode( |
| 1778 | tx_select: bool, |
| 1779 | reduced_tx_set: bool, |
| 1780 | enable_filter_intra: bool, fctx: &crate::decode::FrameCtx, |
| 1781 | ) { |
| 1782 | fctx.tx_select_inter.with(|c| c.set(tx_select)); |
| 1783 | fctx.intra_only.with(|c| c.set(false)); |
| 1784 | fctx.tx_select_frame.with(|c| c.set(tx_select)); |
| 1785 | fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); |
| 1786 | fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra)); |
| 1787 | } |
| 1788 | |
| 1789 | // How many `partition_w16` reads (a 16x16 block's own partition symbol, key |
| 1790 | // intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a |
| 1791 | // plain default-settings aomenc run over lavfi mandelbrot hits this arm on |
| 1792 | // frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not |
| 1793 | // the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real |
| 1794 | // `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`, |
| 1795 | // chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8 |
| 1796 | // path above). |
| 1797 | thread_local! { |
| 1798 | static VERT_B_INTRA_HITS: std::cell::Cell<usize> = |
| 1799 | const { std::cell::Cell::new(0) }; |
| 1800 | } |
| 1801 | |
| 1802 | /// Current value of [`VERT_B_INTRA_HITS`]. |
| 1803 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1804 | pub(crate) fn vert_b_intra_hits() -> usize { |
| 1805 | VERT_B_INTRA_HITS.with(|c| c.get()) |
| 1806 | } |
| 1807 | |
| 1808 | // lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in |
| 1809 | // `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two |
| 1810 | // 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`, |
| 1811 | // the non-skip coefficient path lane-rectx proved); the gate hard-asserts |
| 1812 | // every arm separately so a run where aomenc's RD only picked one cannot |
| 1813 | // pass as proof of four. |
| 1814 | thread_local! { |
| 1815 | static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; |
| 1816 | } |
| 1817 | |
| 1818 | // [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16). |
| 1819 | thread_local! { |
| 1820 | /// 4x4 transform units decoded inside an 8x8 square of a |
| 1821 | /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before |
| 1822 | /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove |
| 1823 | /// a real `--enable-tx-size-search=1` stream reaches it. |
| 1824 | static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 1825 | } |
| 1826 | |
| 1827 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1828 | pub(crate) fn vert_ab_tx4_hits() -> usize { |
| 1829 | VERT_AB_TX4_HITS.with(std::cell::Cell::get) |
| 1830 | } |
| 1831 | |
| 1832 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1833 | pub(crate) fn ab16_hits_by_arm() -> [usize; 4] { |
| 1834 | AB16_HITS.with(std::cell::Cell::get) |
| 1835 | } |
| 1836 | |
| 1837 | fn bump_ab16(arm: usize) { |
| 1838 | hit_do! { |
| 1839 | AB16_HITS.with(|c| { |
| 1840 | let mut v = c.get(); |
| 1841 | v[arm] += 1; |
| 1842 | c.set(v); |
| 1843 | }); |
| 1844 | } |
| 1845 | } |
| 1846 | |
| 1847 | // How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/ |
| 1848 | // `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above |
| 1849 | // showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7), |
| 1850 | // not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's |
| 1851 | // very first non-NONE/SPLIT symbol" claim was about decode ORDER within one |
| 1852 | // superblock's z-order recursion, not raster mi position). |
| 1853 | thread_local! { |
| 1854 | static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> = |
| 1855 | const { std::cell::Cell::new(0) }; |
| 1856 | } |
| 1857 | |
| 1858 | /// Current value of [`HORZ_VERT_INTRA_HITS`]. |
| 1859 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1860 | pub(crate) fn horz_vert_intra_hits() -> usize { |
| 1861 | HORZ_VERT_INTRA_HITS.with(|c| c.get()) |
| 1862 | } |
| 1863 | |
| 1864 | // How many blocks were decoded as a frame-edge rect strip -- the single |
| 1865 | // coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge |
| 1866 | // (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose |
| 1867 | // height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter |
| 1868 | // paths share the counter. |
| 1869 | thread_local! { |
| 1870 | static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> = |
| 1871 | const { std::cell::Cell::new(0) }; |
| 1872 | } |
| 1873 | |
| 1874 | /// Current value of [`EDGE_RECT_STRIP_HITS`]. |
| 1875 | #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live |
| 1876 | pub(crate) fn edge_rect_strip_hits() -> usize { |
| 1877 | EDGE_RECT_STRIP_HITS.with(|c| c.get()) |
| 1878 | } |
| 1879 | |
| 1880 | // lane-interedge r1: frame-edge half strips on the INTER path, per partition |
| 1881 | // level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The |
| 1882 | // index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and |
| 1883 | // `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films |
| 1884 | // are height mod 16 == 8, so every inter frame crosses these nodes. |
| 1885 | thread_local! { |
| 1886 | static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> = |
| 1887 | const { std::cell::Cell::new([0; 6]) }; |
| 1888 | } |
| 1889 | |
| 1890 | /// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`]. |
| 1891 | pub(crate) fn bump_inter_edge_strip(idx: usize) { |
| 1892 | hit_do! { |
| 1893 | INTER_EDGE_STRIP_HITS.with(|c| { |
| 1894 | let mut v = c.get(); |
| 1895 | v[idx] += 1; |
| 1896 | c.set(v); |
| 1897 | }); |
| 1898 | } |
| 1899 | } |
| 1900 | |
| 1901 | // lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT |
| 1902 | // forced split -- libaom `decode_partition` (decodeframe.c): |
| 1903 | // `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one |
| 1904 | // straddle case that reads NO symbol at all. Indexed by level: |
| 1905 | // 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it. |
| 1906 | thread_local! { |
| 1907 | static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> = |
| 1908 | const { std::cell::Cell::new([0; 4]) }; |
| 1909 | } |
| 1910 | |
| 1911 | fn bump_edge_both_cut(level: usize) { |
| 1912 | hit_do! { |
| 1913 | EDGE_BOTH_CUT_HITS.with(|c| { |
| 1914 | let mut v = c.get(); |
| 1915 | v[level] += 1; |
| 1916 | c.set(v); |
| 1917 | }); |
| 1918 | } |
| 1919 | } |
| 1920 | |
| 1921 | /// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`). |
| 1922 | pub fn inter_edge_strip_hits() -> [usize; 6] { |
| 1923 | INTER_EDGE_STRIP_HITS.with(|c| c.get()) |
| 1924 | } |
| 1925 | |
| 1926 | /// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits |
| 1927 | /// into the next one (class `counter-from-refused-stream`). |
| 1928 | pub fn reset_inter_edge_strip_hits() { |
| 1929 | INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6])); |
| 1930 | } |
| 1931 | |
| 1932 | /// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels). |
| 1933 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1934 | pub(crate) fn edge_both_cut_hits() -> [usize; 4] { |
| 1935 | EDGE_BOTH_CUT_HITS.with(|c| c.get()) |
| 1936 | } |
| 1937 | |
| 1938 | /// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta. |
| 1939 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1940 | pub(crate) fn reset_edge_both_cut_hits() { |
| 1941 | EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4])); |
| 1942 | } |
| 1943 | |
| 1944 | // How many HORZ/VERT intra strips resolved a SPLIT luma transform |
| 1945 | // (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) -- |
| 1946 | // the case every rect path here refused by name before, and the first |
| 1947 | // refusal the user's ReelB extract (600s in) stops at. |
| 1948 | thread_local! { |
| 1949 | static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> = |
| 1950 | const { std::cell::Cell::new(0) }; |
| 1951 | } |
| 1952 | |
| 1953 | /// Current value of [`RECT_SPLIT_TX_HITS`]. |
| 1954 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1955 | pub(crate) fn rect_split_tx_hits() -> usize { |
| 1956 | RECT_SPLIT_TX_HITS.with(|c| c.get()) |
| 1957 | } |
| 1958 | |
| 1959 | // The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one |
| 1960 | // side 64) AND split past the first depth, i.e. tiled more than one unit in |
| 1961 | // each axis -- the only shape with a transform unit that has neighbours on |
| 1962 | // two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one |
| 1963 | // no gate fired before lane-rectsplit r2 (the shared counter above also |
| 1964 | // counts 32x32-level and depth-1 strips, so it cannot prove this case). |
| 1965 | thread_local! { |
| 1966 | static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> = |
| 1967 | const { std::cell::Cell::new(0) }; |
| 1968 | } |
| 1969 | |
| 1970 | /// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`]. |
| 1971 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1972 | pub(crate) fn rect_split_sb_interior_tu_hits() -> usize { |
| 1973 | RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get()) |
| 1974 | } |
| 1975 | |
| 1976 | // Per-shape hit counts for the rect chroma transforms lane-rectchroma r1 |
| 1977 | // wired into [`decode_rect_split`] -- the shapes a split-transform strip's |
| 1978 | // chroma half takes that had no coefficient tables before (index order: |
| 1979 | // 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only |
| 1980 | // proves the pair it happens to hit cannot catch a transposed scan/context |
| 1981 | // table (class scan-weights-cross-axis). |
| 1982 | thread_local! { |
| 1983 | static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> = |
| 1984 | const { std::cell::Cell::new([0; 4]) }; |
| 1985 | } |
| 1986 | |
| 1987 | /// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8). |
| 1988 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1989 | pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] { |
| 1990 | RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get()) |
| 1991 | } |
| 1992 | |
| 1993 | // How many HORZ/VERT intra strips actually predicted with filter intra |
| 1994 | // (lane-rectsplit r1) -- the case `decode_block_rect` refused by name |
| 1995 | // ("this decoder predicts square-only") until `predict_filter_intra` took |
| 1996 | // `bw`x`bh`. |
| 1997 | thread_local! { |
| 1998 | static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> = |
| 1999 | const { std::cell::Cell::new(0) }; |
| 2000 | } |
| 2001 | |
| 2002 | /// Current value of [`FILTER_INTRA_RECT_HITS`]. |
| 2003 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2004 | pub(crate) fn filter_intra_rect_hits() -> usize { |
| 2005 | FILTER_INTRA_RECT_HITS.with(|c| c.get()) |
| 2006 | } |
| 2007 | |
| 2008 | // As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips |
| 2009 | // (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol |
| 2010 | // was never read at all before that round, so a gate needs to prove the flag |
| 2011 | // fired at THAT shape and not at a 16x8 one somewhere else in the frame. |
| 2012 | // Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA` |
| 2013 | // carry different probabilities (18101 vs 20229), so a transposed pair is |
| 2014 | // only caught by a gate that sees the flag fire on BOTH shapes (class |
| 2015 | // scan-weights-cross-axis). |
| 2016 | thread_local! { |
| 2017 | static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> = |
| 2018 | const { std::cell::Cell::new(0) }; |
| 2019 | static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> = |
| 2020 | const { std::cell::Cell::new(0) }; |
| 2021 | } |
| 2022 | |
| 2023 | /// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips). |
| 2024 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2025 | pub(crate) fn filter_intra_rect4_horz_hits() -> usize { |
| 2026 | FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get()) |
| 2027 | } |
| 2028 | |
| 2029 | /// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips). |
| 2030 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2031 | pub(crate) fn filter_intra_rect4_vert_hits() -> usize { |
| 2032 | FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get()) |
| 2033 | } |
| 2034 | |
| 2035 | // How many rectangular transform units actually coded coefficients through |
| 2036 | // [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate |
| 2037 | // exercised the rect coefficient reader at all rather than passing on |
| 2038 | // all-skip blocks. |
| 2039 | thread_local! { |
| 2040 | static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2041 | static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2042 | } |
| 2043 | |
| 2044 | /// Current value of [`RECT_COEFF_TU_HITS`]. |
| 2045 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2046 | pub(crate) fn rect_coeff_tu_hits() -> usize { |
| 2047 | RECT_COEFF_TU_HITS.with(|c| c.get()) |
| 2048 | } |
| 2049 | |
| 2050 | /// Rectangular transform units whose resolved `tx_type` is a 1D class |
| 2051 | /// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can |
| 2052 | /// pin that the 1D-class-on-a-RECT-transform path fired rather than settling |
| 2053 | /// for the square reader's own 1D types. |
| 2054 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2055 | pub(crate) fn rect_class1_hits() -> usize { |
| 2056 | RECT_CLASS1_HITS.with(|c| c.get()) |
| 2057 | } |
| 2058 | |
| 2059 | // As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16 |
| 2060 | // (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the |
| 2061 | // shapes whose `use_filter_intra` symbol had no CDF class before this round. |
| 2062 | // A gate asserting the wider counter would be satisfied by a 32x16 strip and |
| 2063 | // prove nothing about the new shapes. |
| 2064 | thread_local! { |
| 2065 | static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> = |
| 2066 | const { std::cell::Cell::new(0) }; |
| 2067 | } |
| 2068 | |
| 2069 | /// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`]. |
| 2070 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2071 | pub(crate) fn filter_intra_rect_sub16_hits() -> usize { |
| 2072 | FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get()) |
| 2073 | } |
| 2074 | |
| 2075 | // As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down: |
| 2076 | // 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16 |
| 2077 | // counter would be satisfied by a 16x8 strip and prove nothing here. |
| 2078 | thread_local! { |
| 2079 | static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> = |
| 2080 | const { std::cell::Cell::new(0) }; |
| 2081 | } |
| 2082 | |
| 2083 | /// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`]. |
| 2084 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2085 | pub(crate) fn filter_intra_rect_sub8_hits() -> usize { |
| 2086 | FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get()) |
| 2087 | } |
| 2088 | |
| 2089 | // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D` |
| 2090 | // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every |
| 2091 | // call on the current thread -- the same before/after counter pattern as |
| 2092 | // [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split |
| 2093 | // `eob_pt`/1D-neighbour context path rather than every block coincidentally |
| 2094 | // landing on `DCT_DCT`. |
| 2095 | thread_local! { |
| 2096 | static TX_CLASS1_HITS: std::cell::Cell<usize> = |
| 2097 | const { std::cell::Cell::new(0) }; |
| 2098 | } |
| 2099 | |
| 2100 | // How many `uv_mode` reads resolved to a directional chroma mode (neither |
| 2101 | // `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same |
| 2102 | // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream |
| 2103 | // actually exercised chroma's own directional predictor. |
| 2104 | thread_local! { |
| 2105 | static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> = |
| 2106 | const { std::cell::Cell::new(0) }; |
| 2107 | } |
| 2108 | |
| 2109 | /// Current value of [`DIRECTIONAL_UV_HITS`]. |
| 2110 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2111 | pub(crate) fn directional_uv_hits() -> usize { |
| 2112 | DIRECTIONAL_UV_HITS.with(|c| c.get()) |
| 2113 | } |
| 2114 | |
| 2115 | // How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as |
| 2116 | // something other than [`ANGLE_DELTA_ZERO`], across every call in the |
| 2117 | // process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`], |
| 2118 | // proving a stream actually exercised a nonzero angle delta. |
| 2119 | thread_local! { |
| 2120 | static ANGLE_DELTA_HITS: std::cell::Cell<usize> = |
| 2121 | const { std::cell::Cell::new(0) }; |
| 2122 | } |
| 2123 | |
| 2124 | // How many [`read_single_ref`] reads resolved to a reference other than |
| 2125 | // `LAST_FRAME`, across every call on the current thread -- the same before/after |
| 2126 | // counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually |
| 2127 | // exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's |
| 2128 | // only other supported one so far) rather than every block coincidentally |
| 2129 | // resolving `LAST_FRAME`. |
| 2130 | thread_local! { |
| 2131 | static NON_LAST_REF_HITS: std::cell::Cell<usize> = |
| 2132 | const { std::cell::Cell::new(0) }; |
| 2133 | } |
| 2134 | |
| 2135 | /// Current value of [`NON_LAST_REF_HITS`]. |
| 2136 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2137 | pub(crate) fn non_last_ref_hits() -> usize { |
| 2138 | NON_LAST_REF_HITS.with(|c| c.get()) |
| 2139 | } |
| 2140 | |
| 2141 | // Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter |
| 2142 | // per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one |
| 2143 | // specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`) |
| 2144 | // can prove THAT reference fired rather than any non-`LAST_FRAME` one -- |
| 2145 | // `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a |
| 2146 | // `GOLDEN_FRAME` draw it did not ask for. |
| 2147 | thread_local! { |
| 2148 | static LAST2_HITS: std::cell::Cell<usize> = |
| 2149 | const { std::cell::Cell::new(0) }; |
| 2150 | } |
| 2151 | thread_local! { |
| 2152 | static LAST3_HITS: std::cell::Cell<usize> = |
| 2153 | const { std::cell::Cell::new(0) }; |
| 2154 | } |
| 2155 | thread_local! { |
| 2156 | static GOLDEN_HITS: std::cell::Cell<usize> = |
| 2157 | const { std::cell::Cell::new(0) }; |
| 2158 | } |
| 2159 | thread_local! { |
| 2160 | static BWDREF_HITS: std::cell::Cell<usize> = |
| 2161 | const { std::cell::Cell::new(0) }; |
| 2162 | } |
| 2163 | thread_local! { |
| 2164 | static ALTREF2_HITS: std::cell::Cell<usize> = |
| 2165 | const { std::cell::Cell::new(0) }; |
| 2166 | } |
| 2167 | thread_local! { |
| 2168 | static ALTREF_HITS: std::cell::Cell<usize> = |
| 2169 | const { std::cell::Cell::new(0) }; |
| 2170 | } |
| 2171 | |
| 2172 | // How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp) |
| 2173 | // -- proves a `reference_select` stream actually reached a block that picked |
| 2174 | // compound, not just that the header bit was set. Every such block is |
| 2175 | // refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]), |
| 2176 | // so this only ever counts attempted reads, never a completed decode. |
| 2177 | thread_local! { |
| 2178 | static COMP_MODE_HITS: std::cell::Cell<usize> = |
| 2179 | const { std::cell::Cell::new(0) }; |
| 2180 | } |
| 2181 | |
| 2182 | /// Current value of [`COMP_MODE_HITS`]. |
| 2183 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2184 | pub(crate) fn comp_mode_hits() -> usize { |
| 2185 | COMP_MODE_HITS.with(|c| c.get()) |
| 2186 | } |
| 2187 | |
| 2188 | // How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y |
| 2189 | // use for, across every call on the current thread -- the same before/after |
| 2190 | // counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually |
| 2191 | // exercised palette reconstruction rather than only reading and refusing the |
| 2192 | // `palette_y_mode` symbol. |
| 2193 | thread_local! { |
| 2194 | static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2195 | } |
| 2196 | |
| 2197 | /// Current value of [`PALETTE_HITS`]. |
| 2198 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2199 | pub(crate) fn palette_hits() -> usize { |
| 2200 | PALETTE_HITS.with(|c| c.get()) |
| 2201 | } |
| 2202 | |
| 2203 | // lane-tiles r12: of those, how many sat at their own TILE's left column -- |
| 2204 | // exactly the blocks whose palette cache/ctx must NOT see the previous tile's |
| 2205 | // colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile |
| 2206 | // palette gate that never hits one proves nothing about the tile guard. |
| 2207 | thread_local! { |
| 2208 | static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2209 | } |
| 2210 | |
| 2211 | /// Current value of [`PALETTE_TILE_LEFT_HITS`]. |
| 2212 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2213 | pub(crate) fn palette_tile_left_hits() -> usize { |
| 2214 | PALETTE_TILE_LEFT_HITS.with(|c| c.get()) |
| 2215 | } |
| 2216 | |
| 2217 | // lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma |
| 2218 | // palette use -- proves a stream actually reconstructed UV palette pixels, |
| 2219 | // not just read and refused the `palette_uv_mode` symbol. |
| 2220 | thread_local! { |
| 2221 | static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2222 | } |
| 2223 | |
| 2224 | /// Current value of [`PALETTE_UV_HITS`]. |
| 2225 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2226 | pub(crate) fn palette_uv_hits() -> usize { |
| 2227 | PALETTE_UV_HITS.with(|c| c.get()) |
| 2228 | } |
| 2229 | |
| 2230 | // lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`]) |
| 2231 | // decoded a real palette-Y use -- proves the rect strip's own palette syntax |
| 2232 | // (not just the square path's) actually fired. |
| 2233 | thread_local! { |
| 2234 | static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2235 | } |
| 2236 | |
| 2237 | /// Current value of [`PALETTE_RECT_HITS`]. |
| 2238 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2239 | pub(crate) fn palette_rect_hits() -> usize { |
| 2240 | PALETTE_RECT_HITS.with(|c| c.get()) |
| 2241 | } |
| 2242 | |
| 2243 | // lane-palette2 r6: how many HORZ/VERT rect intra strips ran the |
| 2244 | // [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] -- |
| 2245 | // i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in |
| 2246 | // range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per |
| 2247 | // RD, almost always refused-on-use because the block doesn't end up USING a |
| 2248 | // palette -- see r5's report). This is the site the removed refusal |
| 2249 | // ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it |
| 2250 | // fired here whether or not the block picked a palette, so this is the |
| 2251 | // counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost |
| 2252 | // never observes. |
| 2253 | thread_local! { |
| 2254 | static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2255 | } |
| 2256 | |
| 2257 | /// Current value of [`RECT_SCREEN_CONTENT_HITS`]. |
| 2258 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2259 | pub(crate) fn rect_screen_content_hits() -> usize { |
| 2260 | RECT_SCREEN_CONTENT_HITS.with(|c| c.get()) |
| 2261 | } |
| 2262 | |
| 2263 | // lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a |
| 2264 | // split luma transform (`logical_tx != side`) -- proves the per-TU index-map |
| 2265 | // windowing actually ran, not just that the whole-block path stayed exact. |
| 2266 | // Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16); |
| 2267 | // first actually incremented in r7, when the refusal it guarded was lifted. |
| 2268 | thread_local! { |
| 2269 | static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2270 | } |
| 2271 | |
| 2272 | thread_local! { |
| 2273 | /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the |
| 2274 | /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves |
| 2275 | /// (16x8/8x16), the two shapes the lifted refusals named. |
| 2276 | static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2277 | } |
| 2278 | |
| 2279 | /// Current value of [`RECT4_PALETTE_HITS`]. |
| 2280 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2281 | pub(crate) fn rect4_palette_hits() -> usize { |
| 2282 | RECT4_PALETTE_HITS.with(|c| c.get()) |
| 2283 | } |
| 2284 | |
| 2285 | /// Current value of [`PALETTE_SPLIT_TX_HITS`]. |
| 2286 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2287 | pub(crate) fn palette_split_tx_hits() -> usize { |
| 2288 | PALETTE_SPLIT_TX_HITS.with(|c| c.get()) |
| 2289 | } |
| 2290 | |
| 2291 | thread_local! { |
| 2292 | /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a |
| 2293 | /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen` |
| 2294 | /// stream stopped on, since aomenc palettes square blocks at 8 bit and |
| 2295 | /// `--min-partition-size=8` puts them on this leaf path. |
| 2296 | static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2297 | } |
| 2298 | |
| 2299 | /// Current value of [`PALETTE_LEAF8_HITS`]. |
| 2300 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2301 | pub(crate) fn palette_leaf8_hits() -> usize { |
| 2302 | PALETTE_LEAF8_HITS.with(|c| c.get()) |
| 2303 | } |
| 2304 | |
| 2305 | /// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting). |
| 2306 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2307 | pub(crate) fn reset_palette_leaf8_hits() { |
| 2308 | PALETTE_LEAF8_HITS.with(|c| c.set(0)); |
| 2309 | } |
| 2310 | |
| 2311 | thread_local! { |
| 2312 | /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level) |
| 2313 | /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette |
| 2314 | /// block that also carries a real, corner-cropped luma transform. |
| 2315 | static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2316 | } |
| 2317 | |
| 2318 | /// Current value of [`PALETTE_SB_STRIP_HITS`]. |
| 2319 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2320 | pub(crate) fn palette_sb_strip_hits() -> usize { |
| 2321 | PALETTE_SB_STRIP_HITS.with(|c| c.get()) |
| 2322 | } |
| 2323 | |
| 2324 | /// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting). |
| 2325 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2326 | pub(crate) fn reset_palette_sb_strip_hits() { |
| 2327 | PALETTE_SB_STRIP_HITS.with(|c| c.set(0)); |
| 2328 | } |
| 2329 | |
| 2330 | // lane-t900 r22: palette blocks reconstructed inside an INTER frame (the |
| 2331 | // intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted |
| 2332 | // apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame |
| 2333 | // capability rather than the key frame's, which every screen stream also |
| 2334 | // carries. |
| 2335 | thread_local! { |
| 2336 | static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2337 | static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2338 | } |
| 2339 | |
| 2340 | // lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8 |
| 2341 | // LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the |
| 2342 | // shared counter too, so only this one proves a gate really reached the leaf |
| 2343 | // where the refusal used to sit. |
| 2344 | thread_local! { |
| 2345 | static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> = |
| 2346 | const { std::cell::Cell::new((0, 0)) }; |
| 2347 | } |
| 2348 | |
| 2349 | /// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`. |
| 2350 | pub(crate) fn inter8_palette_hits() -> (usize, usize) { |
| 2351 | INTER8_PALETTE_HITS.with(std::cell::Cell::get) |
| 2352 | } |
| 2353 | |
| 2354 | /// Current values of the two intra-in-inter palette counters, `(y, uv)`. |
| 2355 | pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) { |
| 2356 | ( |
| 2357 | INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()), |
| 2358 | INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()), |
| 2359 | ) |
| 2360 | } |
| 2361 | |
| 2362 | // lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform |
| 2363 | // and which are therefore predicted one transform unit at a time (a skipped |
| 2364 | // block codes no coefficients, so nothing else in the stream witnesses this |
| 2365 | // path -- only the pixels do). |
| 2366 | thread_local! { |
| 2367 | static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2368 | } |
| 2369 | |
| 2370 | /// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units). |
| 2371 | pub fn skip_split_tx_hits() -> usize { |
| 2372 | SKIP_SPLIT_TX_HITS.with(|c| c.get()) |
| 2373 | } |
| 2374 | |
| 2375 | // lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose |
| 2376 | // `tx_depth` split the luma transform -- the arm that predicted DC off the |
| 2377 | // block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels |
| 2378 | // witness this path, so a gate that wants it needs the counter. |
| 2379 | thread_local! { |
| 2380 | static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2381 | } |
| 2382 | |
| 2383 | /// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks). |
| 2384 | pub fn skip_split_tx_override_hits() -> usize { |
| 2385 | SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get()) |
| 2386 | } |
| 2387 | |
| 2388 | /// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt. |
| 2389 | pub fn reset_skip_split_tx_override_hits() { |
| 2390 | SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0)); |
| 2391 | } |
| 2392 | |
| 2393 | // lane-svtinter: palette colour-index maps whose block is cut by the frame's |
| 2394 | // bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight` |
| 2395 | // really are smaller than the block and FEWER symbols are read than the |
| 2396 | // block has cells (class map-read-past-frame-edge). |
| 2397 | thread_local! { |
| 2398 | static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 2399 | } |
| 2400 | |
| 2401 | /// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps). |
| 2402 | pub fn palette_onscreen_cut_hits() -> usize { |
| 2403 | PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get()) |
| 2404 | } |
| 2405 | |
| 2406 | /// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt. |
| 2407 | pub fn reset_palette_onscreen_cut_hits() { |
| 2408 | PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0)); |
| 2409 | } |
| 2410 | |
| 2411 | /// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt. |
| 2412 | pub fn reset_skip_split_tx_hits() { |
| 2413 | SKIP_SPLIT_TX_HITS.with(|c| c.set(0)); |
| 2414 | } |
| 2415 | |
| 2416 | // lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth` |
| 2417 | // symbol split their luma transform, bucketed by block side (8, 16, 32, 64) -- |
| 2418 | // the gate's proof that the lifted path actually ran, per size. |
| 2419 | thread_local! { |
| 2420 | static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> = |
| 2421 | const { std::cell::Cell::new([0; 4]) }; |
| 2422 | } |
| 2423 | |
| 2424 | /// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64. |
| 2425 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2426 | pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] { |
| 2427 | INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get) |
| 2428 | } |
| 2429 | |
| 2430 | /// A just-decoded palette-Y block's own predicted pixels |
| 2431 | /// (`side*side`, row-major, `colors[map[i]]`), consumed by |
| 2432 | /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the |
| 2433 | /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a |
| 2434 | /// per-block override through `read_plane`'s two dozen call sites is the |
| 2435 | /// alternative this avoids). Always empty again once that call consumes |
| 2436 | /// it (`.take()`), so a non-palette block's own `reconstruct` call never |
| 2437 | /// sees stale state. |
| 2438 | |
| 2439 | |
| 2440 | /// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct` |
| 2441 | /// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a |
| 2442 | /// site whose reconstruct never runs would be picked up by the NEXT block's |
| 2443 | /// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so |
| 2444 | /// lane-lossless2: one transform unit's window on a block-sized palette |
| 2445 | /// prediction buffer. A unit reads its prediction at ITS OWN stride, so |
| 2446 | /// handing it the whole-block buffer makes every unit reconstruct the block's |
| 2447 | /// top-left corner (the luma split-transform paths already window; the chroma |
| 2448 | /// ones did not, which is invisible until a lossless frame codes a palette |
| 2449 | /// block as 4x4 chroma units). |
| 2450 | fn palette_window(buf: &[u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize) -> Vec<u16> { |
| 2451 | (0..h) |
| 2452 | .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied()) |
| 2453 | .collect() |
| 2454 | } |
| 2455 | |
| 2456 | /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site. |
| 2457 | #[track_caller] |
| 2458 | fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) { |
| 2459 | if crate::envflags::env_flag!("EC_DEBUG_PAL") { |
| 2460 | let stale = fctx.palette_pred.with(|c| c.borrow().is_some()); |
| 2461 | eprintln!( |
| 2462 | "PALSET len={} stale={stale} at {}", |
| 2463 | buf.len(), |
| 2464 | std::panic::Location::caller() |
| 2465 | ); |
| 2466 | } |
| 2467 | fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf)); |
| 2468 | } |
| 2469 | |
| 2470 | #[track_caller] |
| 2471 | fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> { |
| 2472 | let got = fctx.palette_pred.with(|c| c.borrow_mut().take()); |
| 2473 | if crate::envflags::env_flag!("EC_DEBUG_PAL") { |
| 2474 | eprintln!( |
| 2475 | "PALTAKE len={:?} at {}", |
| 2476 | got.as_ref().map(Vec::len), |
| 2477 | std::panic::Location::caller() |
| 2478 | ); |
| 2479 | } |
| 2480 | got |
| 2481 | } |
| 2482 | |
| 2483 | /// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over |
| 2484 | /// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the |
| 2485 | /// pixels, because at parse time this block's own luma is still queued. |
| 2486 | #[derive(Clone, Copy, Debug)] |
| 2487 | pub(crate) struct CflSrc { |
| 2488 | px: usize, |
| 2489 | py: usize, |
| 2490 | bw: usize, |
| 2491 | bh: usize, |
| 2492 | } |
| 2493 | |
| 2494 | fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc { |
| 2495 | CflSrc { px, py, bw: side, bh: side } |
| 2496 | } |
| 2497 | |
| 2498 | fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc { |
| 2499 | CflSrc { px, py, bw, bh } |
| 2500 | } |
| 2501 | |
| 2502 | /// lane-wave1 step (i): the pixel-writing half of block decoding, recorded |
| 2503 | /// instead of executed. Each variant is the resolved argument tuple of the |
| 2504 | /// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push |
| 2505 | /// order performs exactly the same writes in exactly the same order -- |
| 2506 | /// entropy parsing no longer touches the frame's own planes (except the two |
| 2507 | /// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run |
| 2508 | /// the replay on a superblock-row wavefront worker. |
| 2509 | /// The dequantization + inverse transform of one transform unit, kept as its |
| 2510 | /// INPUTS so that a recorded write carries the work instead of its result |
| 2511 | /// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the |
| 2512 | /// recon worker, not on the parsing thread. `stride == 0` means the dense |
| 2513 | /// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid |
| 2514 | /// `reconstruct_mc_rect` reads both of its buffers at. |
| 2515 | #[derive(Clone, Copy)] |
| 2516 | pub(crate) struct TxParams { |
| 2517 | pub(crate) w: usize, |
| 2518 | pub(crate) h: usize, |
| 2519 | pub(crate) bit_depth: u8, |
| 2520 | pub(crate) q_idx: i32, |
| 2521 | pub(crate) dc_delta: i32, |
| 2522 | pub(crate) ac_delta: i32, |
| 2523 | pub(crate) tx_type: TxType, |
| 2524 | /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected |
| 2525 | /// on the parse thread by [`block_iqmatrix`] and captured here so the |
| 2526 | /// recon worker scales identically without touching frame state. |
| 2527 | pub(crate) qm: Option<crate::qm::Iqm>, |
| 2528 | pub(crate) stride: usize, |
| 2529 | /// lane-lossless: this transform unit belongs to a lossless BLOCK (its |
| 2530 | /// segment's `xd->lossless[segment_id]` bit), so the residual comes off |
| 2531 | /// the 4x4 Walsh-Hadamard |
| 2532 | /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the |
| 2533 | /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`). |
| 2534 | pub(crate) lossless: bool, |
| 2535 | } |
| 2536 | |
| 2537 | /// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed. |
| 2538 | /// The mixed-lossless witness's proof the per-segment lossless path really |
| 2539 | /// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront |
| 2540 | /// workers run this on their own threads. |
| 2541 | static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = |
| 2542 | std::sync::atomic::AtomicUsize::new(0); |
| 2543 | |
| 2544 | /// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after |
| 2545 | /// delta around one decode. |
| 2546 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2547 | pub(crate) fn lossless_wht_units() -> usize { |
| 2548 | LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed) |
| 2549 | } |
| 2550 | |
| 2551 | impl TxParams { |
| 2552 | /// The one copy of the produce-the-residual code: the inline path calls it |
| 2553 | /// on the parse thread, the wavefront worker calls it on its own, so both |
| 2554 | /// are the same function on the same inputs and byte-identical. |
| 2555 | fn run(self, grid: &[i32]) -> Vec<i32> { |
| 2556 | let residual = if self.lossless { |
| 2557 | LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2558 | debug_assert_eq!((self.w, self.h), (4, 4)); |
| 2559 | debug_assert_eq!(self.tx_type, TxType::DctDct); |
| 2560 | crate::transform::dequant_and_inverse_wht4x4( |
| 2561 | grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta, |
| 2562 | ) |
| 2563 | } else { |
| 2564 | dequant_and_inverse_typed_wh( |
| 2565 | grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta, |
| 2566 | self.tx_type, |
| 2567 | self.qm, |
| 2568 | ) |
| 2569 | }; |
| 2570 | // An all-zero grid transforms to the empty marker, and a strided copy |
| 2571 | // of zeros is still zeros: the marker passes straight through. |
| 2572 | if residual.is_empty() { |
| 2573 | return residual; |
| 2574 | } |
| 2575 | if self.stride == 0 { |
| 2576 | return residual; |
| 2577 | } |
| 2578 | let mut strided = vec![0i32; self.stride * self.stride]; |
| 2579 | for row in 0..self.h { |
| 2580 | strided[row * self.stride..][..self.w] |
| 2581 | .copy_from_slice(&residual[row * self.w..][..self.w]); |
| 2582 | } |
| 2583 | strided |
| 2584 | } |
| 2585 | } |
| 2586 | |
| 2587 | /// A recorded write's residual: already transformed, or the coefficients and |
| 2588 | /// [`TxParams`] the worker transforms itself. |
| 2589 | pub(crate) enum Residual { |
| 2590 | /// An already-transformed residual in the arena, `(offset, len)`; a zero |
| 2591 | /// `len` is the all-zero marker [`dense_residual`] expands. |
| 2592 | Done(u32, u32), |
| 2593 | /// The coefficients live in the pushing tile's arena |
| 2594 | /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset, |
| 2595 | /// len)` in it. |
| 2596 | Coeffs(TxParams, u32, u32), |
| 2597 | } |
| 2598 | |
| 2599 | impl Residual { |
| 2600 | /// The record for a transform unit whose coefficient grid is all zero: |
| 2601 | /// the empty marker, so neither the grid nor the residual is cloned and |
| 2602 | /// the worker never runs the transform (60% of the 4K segment's units). |
| 2603 | fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self { |
| 2604 | if is_zero_grid(grid) { |
| 2605 | return Self::Done(0, 0); |
| 2606 | } |
| 2607 | Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32) |
| 2608 | } |
| 2609 | |
| 2610 | /// A residual the parse thread already transformed, kept in the arena |
| 2611 | /// instead of its own `Vec`. |
| 2612 | fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self { |
| 2613 | // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself, |
| 2614 | // which is exactly the all-zero marker -- one pointer compare instead |
| 2615 | // of copying up to 64 KB of zeros into the arena per block. |
| 2616 | if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) { |
| 2617 | return Self::Done(0, 0); |
| 2618 | } |
| 2619 | Self::Done(push_coeffs(residual, fctx), residual.len() as u32) |
| 2620 | } |
| 2621 | |
| 2622 | /// The residual to reconstruct with; `scratch` is where a transform run |
| 2623 | /// on this thread lands, so the caller owns that buffer. |
| 2624 | fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] { |
| 2625 | match self { |
| 2626 | Self::Done(off, len) => &arena[off as usize..][..len as usize], |
| 2627 | Self::Coeffs(p, off, len) => { |
| 2628 | *scratch = p.run(&arena[off as usize..][..len as usize]); |
| 2629 | scratch |
| 2630 | } |
| 2631 | } |
| 2632 | } |
| 2633 | } |
| 2634 | |
| 2635 | /// Appends to the tile's coefficient arena, returning the offset the record |
| 2636 | /// carries; see [`crate::decode::FrameCtx::coeff_arena`]. |
| 2637 | fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 { |
| 2638 | fctx.coeff_arena.with(|a| { |
| 2639 | let mut a = a.borrow_mut(); |
| 2640 | let off = a.len(); |
| 2641 | a.extend_from_slice(v); |
| 2642 | off as u32 |
| 2643 | }) |
| 2644 | } |
| 2645 | |
| 2646 | /// [`push_coeffs`] for a recorded prediction. |
| 2647 | fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 { |
| 2648 | fctx.pred_arena.with(|a| { |
| 2649 | let mut a = a.borrow_mut(); |
| 2650 | let off = a.len(); |
| 2651 | a.extend_from_slice(v); |
| 2652 | off as u32 |
| 2653 | }) |
| 2654 | } |
| 2655 | |
| 2656 | /// An all-zero residual, for the transform units that code no coefficient: |
| 2657 | /// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY, |
| 2658 | /// and the reconstruction loops below read this instead of a per-unit |
| 2659 | /// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry |
| 2660 | /// (a 128-wide inter block's prediction stride). |
| 2661 | pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128]; |
| 2662 | |
| 2663 | /// lane-blockscratch: one plane's coefficient levels as the block-tail |
| 2664 | /// neighbour writes want them. A plane that coded nothing (a skipped block, a |
| 2665 | /// strip with no chroma, luma under a var-tx split whose units already wrote |
| 2666 | /// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and |
| 2667 | /// zeroing up to 64 KB of its own per block. |
| 2668 | #[derive(Clone)] |
| 2669 | enum Grid { |
| 2670 | Zero(usize), |
| 2671 | Own(Vec<i32>), |
| 2672 | } |
| 2673 | |
| 2674 | /// lane-blockscratch: the mu-chunk chroma collector, allocated by the first |
| 2675 | /// unit that writes into it. Only a block wider or taller than 64 px codes its |
| 2676 | /// chroma per 64x64 chunk; every smaller block used to allocate and zero both |
| 2677 | /// collectors per block and then drop them untouched. |
| 2678 | fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> { |
| 2679 | if v.is_empty() { |
| 2680 | *v = vec![0i32; n]; |
| 2681 | } |
| 2682 | v |
| 2683 | } |
| 2684 | |
| 2685 | impl std::ops::Deref for Grid { |
| 2686 | type Target = [i32]; |
| 2687 | fn deref(&self) -> &[i32] { |
| 2688 | match self { |
| 2689 | Grid::Zero(n) => &ZERO_RESIDUAL[..*n], |
| 2690 | Grid::Own(v) => v, |
| 2691 | } |
| 2692 | } |
| 2693 | } |
| 2694 | |
| 2695 | /// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the |
| 2696 | /// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of |
| 2697 | /// transform units that code no coefficient without the scan (lane-coefgrid). |
| 2698 | pub(crate) fn is_zero_grid(grid: &[i32]) -> bool { |
| 2699 | std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0) |
| 2700 | } |
| 2701 | |
| 2702 | /// `residual`, or `n` zeros when it is the empty all-zero marker. |
| 2703 | fn dense_residual(residual: &[i32], n: usize) -> &[i32] { |
| 2704 | if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual } |
| 2705 | } |
| 2706 | |
| 2707 | /// Where a recorded motion-compensated write reads its prediction from. |
| 2708 | /// |
| 2709 | /// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is |
| 2710 | /// the parse thread's single biggest reconstruction cost, so at |
| 2711 | /// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block |
| 2712 | /// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker |
| 2713 | /// runs it into its own three-plane slot, and every transform unit of that |
| 2714 | /// block then reads its window out of that slot ([`Pred::Cur`]). |
| 2715 | #[derive(Clone, Copy)] |
| 2716 | pub(crate) enum Pred<'a> { |
| 2717 | /// A prediction the parse thread already built, at its own stride |
| 2718 | /// (`stride == 0` means "the reader's own `stride` argument"). |
| 2719 | Inline(&'a [u16], usize), |
| 2720 | /// The current block's deferred prediction: plane, its stride, and this |
| 2721 | /// unit's offset into it. |
| 2722 | Cur { plane: usize, stride: usize, off: usize }, |
| 2723 | } |
| 2724 | |
| 2725 | impl<'a> Pred<'a> { |
| 2726 | /// The same prediction read at an explicit stride. |
| 2727 | fn view(self, stride: usize) -> Self { |
| 2728 | match self { |
| 2729 | Self::Inline(b, _) => Self::Inline(b, stride), |
| 2730 | Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off }, |
| 2731 | } |
| 2732 | } |
| 2733 | /// The materialised buffer and the stride to read it at (`stride` is the |
| 2734 | /// reader's own when this prediction was built dense); `None` for a |
| 2735 | /// deferred prediction, which only a recorded op can carry. |
| 2736 | fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> { |
| 2737 | match self { |
| 2738 | Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })), |
| 2739 | Self::Cur { .. } => None, |
| 2740 | } |
| 2741 | } |
| 2742 | /// This prediction's window starting `n` samples in. |
| 2743 | fn offset(self, n: usize) -> Self { |
| 2744 | match self { |
| 2745 | Self::Inline(b, s) => Self::Inline(&b[n..], s), |
| 2746 | Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n }, |
| 2747 | } |
| 2748 | } |
| 2749 | } |
| 2750 | |
| 2751 | /// [`Pred`], resolved into what a recorded op carries. |
| 2752 | pub(crate) enum PredSrc { |
| 2753 | /// A prediction window in the tile's prediction arena, `(offset, len)`. |
| 2754 | Owned(u32, u32), |
| 2755 | /// A window of the block prediction: its plane, its offset, and the |
| 2756 | /// stride it is read at -- which is the block's, not necessarily the |
| 2757 | /// op's (a transform unit's residual stays dense, so the worker takes |
| 2758 | /// its window out of the block prediction itself). |
| 2759 | Cur { plane: usize, off: usize, src: usize }, |
| 2760 | } |
| 2761 | |
| 2762 | /// One block's whole-block prediction build, deferred to a recon worker. |
| 2763 | /// |
| 2764 | /// The closure borrows the tile's reference pictures and its own frame-level |
| 2765 | /// tables; [`WaveGuard`] joins every worker before the tile decoder returns, |
| 2766 | /// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once |
| 2767 | /// here for the closure's `'static`/`Send` laundering in [`push_pred`]. |
| 2768 | pub(crate) struct PredBuild( |
| 2769 | Box< |
| 2770 | dyn FnOnce( |
| 2771 | &mut PlaneBuf<'static>, |
| 2772 | &mut PlaneBuf<'static>, |
| 2773 | &mut PlaneBuf<'static>, |
| 2774 | &crate::decode::FrameCtx, |
| 2775 | // lane-blockmem: the previous block's three prediction buffers, |
| 2776 | // refilled in place -- the build used to return three fresh |
| 2777 | // `Vec`s per block and drop these. |
| 2778 | &mut [Vec<u16>; 3], |
| 2779 | ), |
| 2780 | >, |
| 2781 | ); |
| 2782 | |
| 2783 | // SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference |
| 2784 | // pictures and frame tables, and the closure runs on exactly one worker. |
| 2785 | #[allow(unsafe_code)] |
| 2786 | unsafe impl Send for PredBuild {} |
| 2787 | |
| 2788 | /// `true` when this tile's writes are recorded for the wavefront instead of |
| 2789 | /// performed at the push site, i.e. when a prediction may be deferred. |
| 2790 | fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool { |
| 2791 | fctx.recon_planes.with(std::cell::Cell::get).is_none() |
| 2792 | } |
| 2793 | |
| 2794 | /// The previous block's prediction buffer, cleared and zero-filled to `n` |
| 2795 | /// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced, |
| 2796 | /// without the per-block allocation and free. |
| 2797 | fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> { |
| 2798 | // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`) |
| 2799 | // than resized element by element -- which is every block on the inline |
| 2800 | // path, where there is no previous buffer to reuse. |
| 2801 | if v.capacity() < n { |
| 2802 | return vec![0u16; n]; |
| 2803 | } |
| 2804 | v.clear(); |
| 2805 | v.resize(n, 0); |
| 2806 | v |
| 2807 | } |
| 2808 | |
| 2809 | /// Records one block's prediction build for the worker that reconstructs it. |
| 2810 | #[allow(unsafe_code)] |
| 2811 | fn push_pred<'a>( |
| 2812 | fctx: &crate::decode::FrameCtx, |
| 2813 | f: impl FnOnce( |
| 2814 | &mut PlaneBuf<'static>, |
| 2815 | &mut PlaneBuf<'static>, |
| 2816 | &mut PlaneBuf<'static>, |
| 2817 | &crate::decode::FrameCtx, |
| 2818 | &mut [Vec<u16>; 3], |
| 2819 | ) + 'a, |
| 2820 | ) { |
| 2821 | type Dyn<'x> = dyn FnOnce( |
| 2822 | &mut PlaneBuf<'static>, |
| 2823 | &mut PlaneBuf<'static>, |
| 2824 | &mut PlaneBuf<'static>, |
| 2825 | &crate::decode::FrameCtx, |
| 2826 | &mut [Vec<u16>; 3], |
| 2827 | ) + 'x; |
| 2828 | let boxed: Box<Dyn<'a>> = Box::new(f); |
| 2829 | // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`] |
| 2830 | // before the borrows the closure holds go out of scope. |
| 2831 | let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) }; |
| 2832 | push_op(fctx, ReconOp::Pred(PredBuild(boxed))); |
| 2833 | } |
| 2834 | |
| 2835 | /// One superblock's recorded writes plus the two arenas they index -- the |
| 2836 | /// unit a wavefront worker takes off the queue (lane-recoparse). |
| 2837 | pub(crate) struct ReconJob { |
| 2838 | ops: Vec<ReconOp>, |
| 2839 | coeffs: Vec<i32>, |
| 2840 | preds: Vec<u16>, |
| 2841 | } |
| 2842 | |
| 2843 | pub(crate) enum ReconOp { |
| 2844 | /// lane-wave4: build this block's prediction into the worker's slot. |
| 2845 | Pred(PredBuild), |
| 2846 | Intra { |
| 2847 | plane: usize, |
| 2848 | x: usize, |
| 2849 | y: usize, |
| 2850 | bw: usize, |
| 2851 | bh: usize, |
| 2852 | /// `true` when the parse site called `reconstruct_rect` (whose |
| 2853 | /// `edges_rect` differs from `edges` even at `bw == bh`). |
| 2854 | rect: bool, |
| 2855 | mode: usize, |
| 2856 | angle_delta: i32, |
| 2857 | reach: Reach, |
| 2858 | residual: Residual, |
| 2859 | cfl: Option<(i32, CflSrc)>, |
| 2860 | filter_intra: Option<usize>, |
| 2861 | smooth_neighbor: bool, |
| 2862 | /// The palette/intrabc prediction override, taken off |
| 2863 | /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read |
| 2864 | /// from that slot by the replay. |
| 2865 | pred: Option<Vec<u16>>, |
| 2866 | }, |
| 2867 | Mc { |
| 2868 | plane: usize, |
| 2869 | x: usize, |
| 2870 | y: usize, |
| 2871 | stride: usize, |
| 2872 | w: usize, |
| 2873 | h: usize, |
| 2874 | prediction: PredSrc, |
| 2875 | residual: Residual, |
| 2876 | }, |
| 2877 | } |
| 2878 | |
| 2879 | /// The three planes of the tile currently being decoded, as raw pointers. |
| 2880 | /// |
| 2881 | /// corner-cut: at one reconstruction thread a recorded write must cost |
| 2882 | /// nothing -- deferring it to the end of the superblock is +1.2% |
| 2883 | /// instructions and +4.5% wall on 4K, because the residual is written at |
| 2884 | /// parse and read back cache-cold at replay. So the recorded op is performed |
| 2885 | /// at the push site instead, through the pointers the tile decoder registers |
| 2886 | /// once ([`ReconInline`]), which is the same thread, the same order and the |
| 2887 | /// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse |
| 2888 | /// stack still holds aliases them, exactly the [`crate::par::Shared`] |
| 2889 | /// trade-off (Miri's stacked borrows would flag both). The upgrade path is |
| 2890 | /// threading the three planes down every `read_plane`/`read_inter_plane` |
| 2891 | /// call site (~40) so the push site owns the borrow it writes through. |
| 2892 | #[derive(Clone, Copy)] |
| 2893 | pub(crate) struct ReconPlanes( |
| 2894 | *mut PlaneBuf<'static>, |
| 2895 | *mut PlaneBuf<'static>, |
| 2896 | *mut PlaneBuf<'static>, |
| 2897 | ); |
| 2898 | |
| 2899 | // SAFETY: a `FrameCtx` sent to another thread (a frame worker, or |
| 2900 | // [`filter_ctx_copy`]) is always one whose guard is not installed, so the |
| 2901 | // value travelling is `None`; the pointers never leave the tile decoder's |
| 2902 | // own thread. |
| 2903 | #[allow(unsafe_code)] |
| 2904 | unsafe impl Send for ReconPlanes {} |
| 2905 | // SAFETY: the wavefront's workers share one `ReconPlanes` and write provably |
| 2906 | // disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`] |
| 2907 | // contract, one superblock per band instead of one row band. |
| 2908 | #[allow(unsafe_code)] |
| 2909 | unsafe impl Sync for ReconPlanes {} |
| 2910 | |
| 2911 | /// Registers the tile's planes for inline reconstruction and unregisters them |
| 2912 | /// on every exit from the tile decoder, including the `?` ones -- a stale |
| 2913 | /// pointer here would outlive the planes, since [`FrameCtx`] outlives the |
| 2914 | /// tile. |
| 2915 | pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx); |
| 2916 | |
| 2917 | #[allow(unsafe_code)] |
| 2918 | impl<'a> ReconInline<'a> { |
| 2919 | /// Installs the guard for this tile when reconstruction is inline |
| 2920 | /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write |
| 2921 | /// to the queue instead, for the wavefront workers to replay. |
| 2922 | fn install( |
| 2923 | fctx: &'a crate::decode::FrameCtx, |
| 2924 | y: &mut PlaneBuf<'static>, |
| 2925 | u: &mut PlaneBuf<'static>, |
| 2926 | v: &mut PlaneBuf<'static>, |
| 2927 | ) -> Option<Self> { |
| 2928 | if crate::par::recon_threads() != 1 { |
| 2929 | return None; |
| 2930 | } |
| 2931 | // SAFETY: the planes are locals of the tile decoder and outlive the |
| 2932 | // guard, which is dropped on every exit from it (including `?`); see |
| 2933 | // [`ReconPlanes`] for the aliasing trade-off. |
| 2934 | let planes = ReconPlanes( |
| 2935 | std::ptr::from_mut(y), |
| 2936 | std::ptr::from_mut(u), |
| 2937 | std::ptr::from_mut(v), |
| 2938 | ); |
| 2939 | fctx.recon_planes.with(|c| c.set(Some(planes))); |
| 2940 | Some(Self(fctx)) |
| 2941 | } |
| 2942 | } |
| 2943 | |
| 2944 | impl Drop for ReconInline<'_> { |
| 2945 | fn drop(&mut self) { |
| 2946 | self.0.recon_planes.with(|c| c.set(None)); |
| 2947 | } |
| 2948 | } |
| 2949 | |
| 2950 | #[allow(unsafe_code)] |
| 2951 | fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) { |
| 2952 | if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) { |
| 2953 | // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one |
| 2954 | // the parse site would have performed itself before lane-wave1. |
| 2955 | // The inline path never records coefficients (the transform runs at |
| 2956 | // the push site), so the arena is not read here. |
| 2957 | unsafe { |
| 2958 | exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx) |
| 2959 | }; |
| 2960 | return; |
| 2961 | } |
| 2962 | fctx.recon_ops.with(|c| c.borrow_mut().push(op)); |
| 2963 | } |
| 2964 | |
| 2965 | /// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded |
| 2966 | /// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`. |
| 2967 | /// |
| 2968 | /// The parser keeps parsing and never touches the planes; each superblock's |
| 2969 | /// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own |
| 2970 | /// `(row, column)` inside the tile (128x128 superblocks are one job for all |
| 2971 | /// four of their 64x64 visits, since a 128 block writes across quadrants). |
| 2972 | /// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and |
| 2973 | /// `(r, c - 1)` are complete -- the classic wavefront rule, which covers |
| 2974 | /// every pixel an intra predictor can read (its edges reach one block right |
| 2975 | /// along the row above and one block down the column to the left, both |
| 2976 | /// inside those two neighbours) and every CfL AC read (this block's own |
| 2977 | /// luma, written by this same job). Jobs are handed out in raster order, so |
| 2978 | /// the oldest outstanding one always has its dependencies met: no deadlock. |
| 2979 | /// |
| 2980 | /// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are |
| 2981 | /// `thread_local!` and miss every worker, which is why the default is 1. |
| 2982 | pub(crate) struct WaveState { |
| 2983 | q: std::sync::Mutex<WaveQueue>, |
| 2984 | cv: std::sync::Condvar, |
| 2985 | planes: ReconPlanes, |
| 2986 | /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is |
| 2987 | /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op). |
| 2988 | bit_depth: u8, |
| 2989 | enable_edge_filter: bool, |
| 2990 | last_col: usize, |
| 2991 | } |
| 2992 | |
| 2993 | struct WaveQueue { |
| 2994 | /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a |
| 2995 | /// row's front job can ever be runnable -- a job waits on its own left |
| 2996 | /// neighbour -- so a worker takes the lowest row whose front job's |
| 2997 | /// dependencies are met. Popping the raster-oldest job instead (what |
| 2998 | /// this replaced) put every worker on the SAME row, where the wavefront |
| 2999 | /// rule serialises them, which is why 4 workers ran the tile at 1.2x. |
| 3000 | rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>, |
| 3001 | /// Jobs sitting in `rows`, so a worker knows the queue is empty without |
| 3002 | /// walking it. |
| 3003 | queued: usize, |
| 3004 | /// Per superblock row, the last column reconstructed (-1 = none yet). |
| 3005 | done: Vec<isize>, |
| 3006 | /// Per superblock row, the last column PARSED (submitted, whether or not |
| 3007 | /// it recorded any write) and the last column actually pushed as a job |
| 3008 | /// (-1 = none). A row is fully reconstructed once it has been parsed to |
| 3009 | /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt |
| 3010 | /// reads that to release the row's filters (see [`wave_rows_complete`]). |
| 3011 | last_sub: Vec<isize>, |
| 3012 | last_push: Vec<isize>, |
| 3013 | /// Jobs popped but not finished -- what [`wave_barrier`] waits out. |
| 3014 | active: usize, |
| 3015 | closed: bool, |
| 3016 | /// lane-sballoc: the three per-superblock buffers a finished job hands |
| 3017 | /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no |
| 3018 | /// first-touch page faults) instead of the `Vec::with_capacity` it used |
| 3019 | /// to make per superblock -- 3 allocations and 3 frees per superblock, |
| 3020 | /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives |
| 3021 | /// inside the queue's own mutex, which both sides already take. |
| 3022 | free: Vec<JobBufs>, |
| 3023 | free_cap: usize, |
| 3024 | } |
| 3025 | |
| 3026 | /// One recycled set of [`ReconJob`] buffers (lane-sballoc). |
| 3027 | type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>); |
| 3028 | |
| 3029 | impl WaveQueue { |
| 3030 | /// The lowest-row queued job whose wavefront dependencies are satisfied, |
| 3031 | /// or `None` (with the blocking condition counted when instrumented). |
| 3032 | fn take_runnable( |
| 3033 | &mut self, |
| 3034 | last_col: usize, |
| 3035 | stats: bool, |
| 3036 | ) -> Option<(usize, usize, ReconJob)> { |
| 3037 | let mut blocked: Option<bool> = None; |
| 3038 | for r in 0..self.rows.len() { |
| 3039 | let Some(front) = self.rows[r].front() else { |
| 3040 | continue; |
| 3041 | }; |
| 3042 | let c = front.0; |
| 3043 | let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize; |
| 3044 | let left = c == 0 || self.done[r] >= c as isize - 1; |
| 3045 | if above && left { |
| 3046 | let (c, job) = self.rows[r].pop_front().expect("front checked above"); |
| 3047 | self.queued -= 1; |
| 3048 | return Some((r, c, job)); |
| 3049 | } |
| 3050 | if blocked.is_none() { |
| 3051 | blocked = Some(above); |
| 3052 | } |
| 3053 | } |
| 3054 | if stats { |
| 3055 | match blocked { |
| 3056 | Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed), |
| 3057 | Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed), |
| 3058 | None => 0, |
| 3059 | }; |
| 3060 | } |
| 3061 | None |
| 3062 | } |
| 3063 | } |
| 3064 | |
| 3065 | /// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon |
| 3066 | /// worker's time goes (busy replaying, waiting for a dependency, idle on an |
| 3067 | /// empty queue), how far ahead the parse thread is, and how often the two |
| 3068 | /// parse-time pixel reads barrier the wavefront. Cumulative for the process, |
| 3069 | /// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the |
| 3070 | /// whole run. |
| 3071 | const WS_SLOTS: usize = 16; |
| 3072 | use std::sync::atomic::AtomicU64; |
| 3073 | use std::sync::atomic::Ordering::Relaxed; |
| 3074 | static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS]; |
| 3075 | static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS]; |
| 3076 | static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS]; |
| 3077 | static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS]; |
| 3078 | static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0); |
| 3079 | static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0); |
| 3080 | /// Parse-thread time between two submits, i.e. everything parse still does |
| 3081 | /// itself (symbol decode plus the predictions not deferred). |
| 3082 | static WS_PARSE: AtomicU64 = AtomicU64::new(0); |
| 3083 | /// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`] |
| 3084 | /// (the intrabc/interintra reads) and at the tile's end. |
| 3085 | static WS_BARRIER: AtomicU64 = AtomicU64::new(0); |
| 3086 | static WS_BARRIERS: AtomicU64 = AtomicU64::new(0); |
| 3087 | static WS_DRAIN: AtomicU64 = AtomicU64::new(0); |
| 3088 | static WS_TILES: AtomicU64 = AtomicU64::new(0); |
| 3089 | |
| 3090 | fn wave_stats() -> bool { |
| 3091 | static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); |
| 3092 | match ON.load(Relaxed) { |
| 3093 | 0 => { |
| 3094 | let on = crate::envflags::var("EC_AV1_WAVE_STATS") |
| 3095 | .map(|v| v.trim() == "1") |
| 3096 | .unwrap_or(false); |
| 3097 | ON.store(1 + u8::from(on), Relaxed); |
| 3098 | on |
| 3099 | } |
| 3100 | n => n == 2, |
| 3101 | } |
| 3102 | } |
| 3103 | |
| 3104 | fn wave_stats_dump() { |
| 3105 | let ms = |n: u64| n as f64 / 1e6; |
| 3106 | let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed)); |
| 3107 | for i in 0..WS_SLOTS { |
| 3108 | let jobs = WS_JOBS[i].load(Relaxed); |
| 3109 | if jobs == 0 { |
| 3110 | continue; |
| 3111 | } |
| 3112 | s += &format!( |
| 3113 | " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us", |
| 3114 | WS_OPS[i].load(Relaxed) as f64 / jobs as f64, |
| 3115 | ms(WS_BUSY[i].load(Relaxed)), |
| 3116 | ms(WS_WAIT[i].load(Relaxed)), |
| 3117 | WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3, |
| 3118 | ); |
| 3119 | } |
| 3120 | s += &format!( |
| 3121 | " | pipe={}/{}", |
| 3122 | PIPE_FRAMES.load(Relaxed), |
| 3123 | PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed), |
| 3124 | ); |
| 3125 | s += &format!( |
| 3126 | " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}", |
| 3127 | ms(WS_PARSE.load(Relaxed)), |
| 3128 | ms(WS_BARRIER.load(Relaxed)), |
| 3129 | WS_BARRIERS.load(Relaxed), |
| 3130 | ms(WS_DRAIN.load(Relaxed)), |
| 3131 | WS_BLOCK_ABOVE.load(Relaxed), |
| 3132 | WS_BLOCK_LEFT.load(Relaxed), |
| 3133 | ); |
| 3134 | eprintln!("{s}"); |
| 3135 | } |
| 3136 | |
| 3137 | #[allow(unsafe_code)] |
| 3138 | fn wave_worker(st: &WaveState, idx: usize) { |
| 3139 | let fctx = FrameCtx::new(); |
| 3140 | fctx.bit_depth.set(st.bit_depth); |
| 3141 | fctx.enable_edge_filter.set(st.enable_edge_filter); |
| 3142 | let stats = wave_stats(); |
| 3143 | let slot = idx.min(WS_SLOTS - 1); |
| 3144 | loop { |
| 3145 | let t0 = std::time::Instant::now(); |
| 3146 | let mut q = st.q.lock().unwrap(); |
| 3147 | let (r, c, job) = loop { |
| 3148 | if let Some(job) = q.take_runnable(st.last_col, stats) { |
| 3149 | break job; |
| 3150 | } |
| 3151 | if q.closed && q.queued == 0 { |
| 3152 | return; |
| 3153 | } |
| 3154 | q = st.cv.wait(q).unwrap(); |
| 3155 | }; |
| 3156 | q.active += 1; |
| 3157 | drop(q); |
| 3158 | if stats { |
| 3159 | WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed); |
| 3160 | WS_JOBS[slot].fetch_add(1, Relaxed); |
| 3161 | WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed); |
| 3162 | } |
| 3163 | let t1 = std::time::Instant::now(); |
| 3164 | let ReconPlanes(y, u, v) = st.planes; |
| 3165 | // SAFETY: this job writes only superblock (r, c)'s own pixels, and |
| 3166 | // every superblock that could have written or be reading them is |
| 3167 | // complete by the wavefront rule above. |
| 3168 | let mut cur: [Vec<u16>; 3] = Default::default(); |
| 3169 | let ReconJob { mut ops, mut coeffs, mut preds } = job; |
| 3170 | unsafe { |
| 3171 | for op in ops.drain(..) { |
| 3172 | exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx); |
| 3173 | } |
| 3174 | } |
| 3175 | if stats { |
| 3176 | WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed); |
| 3177 | } |
| 3178 | coeffs.clear(); |
| 3179 | preds.clear(); |
| 3180 | let mut q = st.q.lock().unwrap(); |
| 3181 | // lane-sballoc: hand the three buffers back for the next submit. |
| 3182 | if q.free.len() < q.free_cap { |
| 3183 | q.free.push((ops, coeffs, preds)); |
| 3184 | } |
| 3185 | q.done[r] = c as isize; |
| 3186 | q.active -= 1; |
| 3187 | st.cv.notify_all(); |
| 3188 | } |
| 3189 | } |
| 3190 | |
| 3191 | /// Installs the wavefront for one tile and joins its workers on every exit |
| 3192 | /// from the tile decoder, including the `?` ones -- the jobs hold raw |
| 3193 | /// pointers into the tile's planes, so no worker may outlive them. |
| 3194 | /// (lane-pool1: the workers come from this thread's persistent pool, so a |
| 3195 | /// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads |
| 3196 | /// with fresh scratch.) |
| 3197 | pub(crate) struct WaveGuard<'a>( |
| 3198 | &'a crate::decode::FrameCtx, |
| 3199 | Option<crate::par::Batch<'static>>, |
| 3200 | ); |
| 3201 | |
| 3202 | #[allow(unsafe_code)] |
| 3203 | impl<'a> WaveGuard<'a> { |
| 3204 | fn install( |
| 3205 | fctx: &'a crate::decode::FrameCtx, |
| 3206 | y: &mut PlaneBuf<'static>, |
| 3207 | u: &mut PlaneBuf<'static>, |
| 3208 | v: &mut PlaneBuf<'static>, |
| 3209 | rows: usize, |
| 3210 | cols: usize, |
| 3211 | ) -> Option<Self> { |
| 3212 | let threads = crate::par::recon_threads(); |
| 3213 | if threads == 1 || rows == 0 || cols == 0 { |
| 3214 | return None; |
| 3215 | } |
| 3216 | let st = std::sync::Arc::new(WaveState { |
| 3217 | q: std::sync::Mutex::new(WaveQueue { |
| 3218 | rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(), |
| 3219 | queued: 0, |
| 3220 | done: vec![-1; rows], |
| 3221 | last_sub: vec![-1; rows], |
| 3222 | last_push: vec![-1; rows], |
| 3223 | active: 0, |
| 3224 | closed: false, |
| 3225 | free: Vec::new(), |
| 3226 | free_cap: threads + 2, |
| 3227 | }), |
| 3228 | cv: std::sync::Condvar::new(), |
| 3229 | // SAFETY: the planes are locals of the tile decoder and outlive |
| 3230 | // this guard, which joins every worker in `drop`. |
| 3231 | planes: ReconPlanes( |
| 3232 | std::ptr::from_mut(y), |
| 3233 | std::ptr::from_mut(u), |
| 3234 | std::ptr::from_mut(v), |
| 3235 | ), |
| 3236 | bit_depth: fctx.bit_depth.with(std::cell::Cell::get), |
| 3237 | enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get), |
| 3238 | last_col: cols - 1, |
| 3239 | }); |
| 3240 | let batch = crate::par::Batch::new("ec-av1-recon"); |
| 3241 | for idx in 0..threads { |
| 3242 | let st = std::sync::Arc::clone(&st); |
| 3243 | batch.submit(move || wave_worker(&st, idx)); |
| 3244 | } |
| 3245 | fctx.wave.with(|w| *w.borrow_mut() = Some(st)); |
| 3246 | fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now()))); |
| 3247 | Some(Self(fctx, Some(batch))) |
| 3248 | } |
| 3249 | } |
| 3250 | |
| 3251 | impl Drop for WaveGuard<'_> { |
| 3252 | fn drop(&mut self) { |
| 3253 | let st = self.0.wave.with(|w| w.borrow_mut().take()); |
| 3254 | if let Some(st) = st { |
| 3255 | st.q.lock().unwrap().closed = true; |
| 3256 | st.cv.notify_all(); |
| 3257 | } |
| 3258 | let t0 = std::time::Instant::now(); |
| 3259 | // Dropping the batch waits every worker out, as the joins did. |
| 3260 | drop(self.1.take()); |
| 3261 | if wave_stats() { |
| 3262 | WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed); |
| 3263 | WS_TILES.fetch_add(1, Relaxed); |
| 3264 | wave_stats_dump(); |
| 3265 | } |
| 3266 | } |
| 3267 | } |
| 3268 | |
| 3269 | /// An empty buffer for the next superblock: the recycled one when it is at |
| 3270 | /// least as big as the superblock just parsed, else a fresh sized one |
| 3271 | /// (lane-sballoc; `v` is always empty). |
| 3272 | fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> { |
| 3273 | if v.capacity() < cap { |
| 3274 | v.reserve_exact(cap - v.len()); |
| 3275 | } |
| 3276 | v |
| 3277 | } |
| 3278 | |
| 3279 | /// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false` |
| 3280 | /// when there is no wavefront (one reconstruction thread), in which case the |
| 3281 | /// caller replays them itself. |
| 3282 | fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool { |
| 3283 | let st = fctx.wave.with(|w| w.borrow().clone()); |
| 3284 | let Some(st) = st else { return false }; |
| 3285 | // lane-blockmem: the op list is replaced sized for the next superblock, |
| 3286 | // exactly as the two arenas below are -- taking it left a zero-capacity |
| 3287 | // `Vec` that regrew (and memmoved every recorded op) from nothing on |
| 3288 | // every superblock. |
| 3289 | // lane-sballoc: the replacement comes from the finished jobs' free list |
| 3290 | // when there is one (warm capacity, already faulted in); only the first |
| 3291 | // superblocks of a tile allocate. |
| 3292 | let mut q = st.q.lock().unwrap(); |
| 3293 | let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default(); |
| 3294 | let ops = fctx.recon_ops.with(|c| { |
| 3295 | let mut c = c.borrow_mut(); |
| 3296 | let cap = c.len(); |
| 3297 | std::mem::replace(&mut *c, reuse(sops, cap)) |
| 3298 | }); |
| 3299 | // The job owns its coefficients: the arena is replaced by an empty one |
| 3300 | // sized for the next superblock, so parse never regrows from nothing and |
| 3301 | // the worker frees this buffer once, instead of once per unit. |
| 3302 | let coeffs = fctx.coeff_arena.with(|c| { |
| 3303 | let mut c = c.borrow_mut(); |
| 3304 | let cap = c.len(); |
| 3305 | std::mem::replace(&mut *c, reuse(scoeffs, cap)) |
| 3306 | }); |
| 3307 | let preds = fctx.pred_arena.with(|c| { |
| 3308 | let mut c = c.borrow_mut(); |
| 3309 | let cap = c.len(); |
| 3310 | std::mem::replace(&mut *c, reuse(spreds, cap)) |
| 3311 | }); |
| 3312 | { |
| 3313 | if (c as isize) > q.last_sub[r] { |
| 3314 | q.last_sub[r] = c as isize; |
| 3315 | } |
| 3316 | if !ops.is_empty() { |
| 3317 | q.rows[r].push_back((c, ReconJob { ops, coeffs, preds })); |
| 3318 | q.queued += 1; |
| 3319 | q.last_push[r] = c as isize; |
| 3320 | } |
| 3321 | drop(q); |
| 3322 | st.cv.notify_all(); |
| 3323 | } |
| 3324 | if wave_stats() { |
| 3325 | let now = std::time::Instant::now(); |
| 3326 | if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) { |
| 3327 | WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed); |
| 3328 | } |
| 3329 | } |
| 3330 | true |
| 3331 | } |
| 3332 | |
| 3333 | /// Waits until every submitted job is reconstructed, so the parser may read |
| 3334 | /// the planes itself (the intrabc source fetch and the interintra intra |
| 3335 | /// predictor -- see [`flush_recon`]). |
| 3336 | fn wave_barrier(fctx: &crate::decode::FrameCtx) { |
| 3337 | let st = fctx.wave.with(|w| w.borrow().clone()); |
| 3338 | let Some(st) = st else { return }; |
| 3339 | let stats = wave_stats(); |
| 3340 | let t0 = std::time::Instant::now(); |
| 3341 | let mut q = st.q.lock().unwrap(); |
| 3342 | while q.queued > 0 || q.active > 0 { |
| 3343 | q = st.cv.wait(q).unwrap(); |
| 3344 | } |
| 3345 | drop(q); |
| 3346 | if stats { |
| 3347 | WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed); |
| 3348 | WS_BARRIERS.fetch_add(1, Relaxed); |
| 3349 | } |
| 3350 | } |
| 3351 | |
| 3352 | /// Performs an intra write at its push site when the tile registered its |
| 3353 | /// planes for inline reconstruction ([`ReconPlanes`]); `false` when the |
| 3354 | /// caller must record it for the wavefront workers instead. |
| 3355 | #[allow(unsafe_code)] |
| 3356 | #[allow(clippy::too_many_arguments)] |
| 3357 | fn inline_intra( |
| 3358 | plane: usize, |
| 3359 | x: usize, |
| 3360 | oy: usize, |
| 3361 | bw: usize, |
| 3362 | bh: usize, |
| 3363 | rect: bool, |
| 3364 | mode: usize, |
| 3365 | angle_delta: i32, |
| 3366 | reach: Reach, |
| 3367 | residual: &[i32], |
| 3368 | cfl: Option<(i32, CflSrc)>, |
| 3369 | filter_intra: Option<usize>, |
| 3370 | smooth_neighbor: bool, |
| 3371 | fctx: &crate::decode::FrameCtx, |
| 3372 | ) -> bool { |
| 3373 | let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else { |
| 3374 | return false; |
| 3375 | }; |
| 3376 | let pred = take_palette_pred(fctx); |
| 3377 | // SAFETY: see [`ReconPlanes`]. |
| 3378 | unsafe { |
| 3379 | exec_intra( |
| 3380 | &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach, |
| 3381 | residual, cfl, filter_intra, smooth_neighbor, pred, fctx, |
| 3382 | ); |
| 3383 | } |
| 3384 | true |
| 3385 | } |
| 3386 | |
| 3387 | /// [`inline_intra`] for a motion-compensated write. |
| 3388 | #[allow(unsafe_code)] |
| 3389 | #[allow(clippy::too_many_arguments)] |
| 3390 | fn inline_mc( |
| 3391 | plane: usize, |
| 3392 | x: usize, |
| 3393 | oy: usize, |
| 3394 | stride: usize, |
| 3395 | w: usize, |
| 3396 | h: usize, |
| 3397 | prediction: &[u16], |
| 3398 | residual: &[i32], |
| 3399 | fctx: &crate::decode::FrameCtx, |
| 3400 | ) -> bool { |
| 3401 | let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else { |
| 3402 | return false; |
| 3403 | }; |
| 3404 | // SAFETY: see [`ReconPlanes`]. |
| 3405 | unsafe { |
| 3406 | exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx); |
| 3407 | } |
| 3408 | true |
| 3409 | } |
| 3410 | |
| 3411 | /// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)). |
| 3412 | #[allow(clippy::too_many_arguments)] |
| 3413 | fn push_intra( |
| 3414 | plane: usize, |
| 3415 | x: usize, |
| 3416 | y: usize, |
| 3417 | side: usize, |
| 3418 | mode: usize, |
| 3419 | angle_delta: i32, |
| 3420 | reach: Reach, |
| 3421 | residual: &[i32], |
| 3422 | cfl: Option<(i32, CflSrc)>, |
| 3423 | filter_intra: Option<usize>, |
| 3424 | smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, |
| 3425 | ) { |
| 3426 | if inline_intra( |
| 3427 | plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra, |
| 3428 | smooth_neighbor, fctx, |
| 3429 | ) { |
| 3430 | return; |
| 3431 | } |
| 3432 | let pred = take_palette_pred(fctx); |
| 3433 | push_op(fctx, ReconOp::Intra { |
| 3434 | plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach, |
| 3435 | residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred, |
| 3436 | }); |
| 3437 | } |
| 3438 | |
| 3439 | /// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)). |
| 3440 | #[allow(clippy::too_many_arguments)] |
| 3441 | fn push_intra_rect( |
| 3442 | plane: usize, |
| 3443 | x: usize, |
| 3444 | y: usize, |
| 3445 | bw: usize, |
| 3446 | bh: usize, |
| 3447 | mode: usize, |
| 3448 | angle_delta: i32, |
| 3449 | reach: Reach, |
| 3450 | residual: &[i32], |
| 3451 | cfl: Option<(i32, CflSrc)>, |
| 3452 | filter_intra: Option<usize>, |
| 3453 | smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, |
| 3454 | ) { |
| 3455 | if inline_intra( |
| 3456 | plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra, |
| 3457 | smooth_neighbor, fctx, |
| 3458 | ) { |
| 3459 | return; |
| 3460 | } |
| 3461 | let pred = take_palette_pred(fctx); |
| 3462 | push_op(fctx, ReconOp::Intra { |
| 3463 | plane, x, y, bw, bh, rect: true, mode, angle_delta, reach, |
| 3464 | residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred, |
| 3465 | }); |
| 3466 | } |
| 3467 | |
| 3468 | /// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded. |
| 3469 | fn push_mc( |
| 3470 | plane: usize, |
| 3471 | x: usize, |
| 3472 | y: usize, |
| 3473 | side: usize, |
| 3474 | prediction: Pred<'_>, |
| 3475 | residual: &[i32], fctx: &crate::decode::FrameCtx, |
| 3476 | ) { |
| 3477 | push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx); |
| 3478 | } |
| 3479 | |
| 3480 | /// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)). |
| 3481 | #[allow(clippy::too_many_arguments)] |
| 3482 | fn push_mc_rect( |
| 3483 | plane: usize, |
| 3484 | x: usize, |
| 3485 | y: usize, |
| 3486 | stride: usize, |
| 3487 | w: usize, |
| 3488 | h: usize, |
| 3489 | prediction: Pred<'_>, |
| 3490 | residual: &[i32], fctx: &crate::decode::FrameCtx, |
| 3491 | ) { |
| 3492 | let (src, stride) = match prediction.inline(stride) { |
| 3493 | Some(v) => v, |
| 3494 | None => { |
| 3495 | let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() }; |
| 3496 | push_op(fctx, ReconOp::Mc { |
| 3497 | plane, x, y, stride: ss, w, h, |
| 3498 | prediction: PredSrc::Cur { plane: sp, off, src: ss }, |
| 3499 | residual: Residual::done(residual, fctx), |
| 3500 | }); |
| 3501 | return; |
| 3502 | } |
| 3503 | }; |
| 3504 | if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) { |
| 3505 | return; |
| 3506 | } |
| 3507 | push_op(fctx, ReconOp::Mc { |
| 3508 | plane, x, y, stride, w, h, |
| 3509 | // The whole window `reconstruct_mc_rect` reads at `stride`, not |
| 3510 | // `w * h`: the record keeps exactly what `src.to_vec()` carried. |
| 3511 | prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32), |
| 3512 | residual: Residual::done(residual, fctx), |
| 3513 | }); |
| 3514 | } |
| 3515 | |
| 3516 | /// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction |
| 3517 | /// thread the transform runs here, exactly as before; on the wavefront it |
| 3518 | /// travels with the op and runs on the worker (lane-wave3). |
| 3519 | #[allow(clippy::too_many_arguments)] |
| 3520 | fn push_intra_tx( |
| 3521 | plane: usize, |
| 3522 | x: usize, |
| 3523 | y: usize, |
| 3524 | bw: usize, |
| 3525 | bh: usize, |
| 3526 | rect: bool, |
| 3527 | mode: usize, |
| 3528 | angle_delta: i32, |
| 3529 | reach: Reach, |
| 3530 | tx: TxParams, |
| 3531 | grid: &[i32], |
| 3532 | cfl: Option<(i32, CflSrc)>, |
| 3533 | filter_intra: Option<usize>, |
| 3534 | smooth_neighbor: bool, |
| 3535 | fctx: &crate::decode::FrameCtx, |
| 3536 | ) { |
| 3537 | if fctx.recon_planes.with(std::cell::Cell::get).is_some() { |
| 3538 | inline_intra( |
| 3539 | plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra, |
| 3540 | smooth_neighbor, fctx, |
| 3541 | ); |
| 3542 | return; |
| 3543 | } |
| 3544 | let pred = take_palette_pred(fctx); |
| 3545 | push_op(fctx, ReconOp::Intra { |
| 3546 | plane, x, y, bw, bh, rect, mode, angle_delta, reach, |
| 3547 | residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred, |
| 3548 | }); |
| 3549 | } |
| 3550 | |
| 3551 | /// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`]. |
| 3552 | #[allow(clippy::too_many_arguments)] |
| 3553 | fn push_mc_rect_tx( |
| 3554 | plane: usize, |
| 3555 | x: usize, |
| 3556 | y: usize, |
| 3557 | stride: usize, |
| 3558 | w: usize, |
| 3559 | h: usize, |
| 3560 | prediction: Pred<'_>, |
| 3561 | tx: TxParams, |
| 3562 | grid: &[i32], |
| 3563 | fctx: &crate::decode::FrameCtx, |
| 3564 | ) { |
| 3565 | // lane-wave4: a deferred prediction is not there to be windowed -- the |
| 3566 | // op carries its offset into the block's prediction instead, and the |
| 3567 | // residual is laid out at that same stride (`reconstruct_mc_rect` reads |
| 3568 | // both buffers at one stride). |
| 3569 | let (prediction, stride) = match prediction.inline(stride) { |
| 3570 | Some(v) => v, |
| 3571 | None => { |
| 3572 | let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() }; |
| 3573 | let mut tx = tx; |
| 3574 | tx.stride = 0; |
| 3575 | push_op(fctx, ReconOp::Mc { |
| 3576 | plane, x, y, stride: w, w, h, |
| 3577 | prediction: PredSrc::Cur { plane: sp, off, src: ss }, |
| 3578 | residual: Residual::coeffs(tx, grid, fctx), |
| 3579 | }); |
| 3580 | return; |
| 3581 | } |
| 3582 | }; |
| 3583 | if fctx.recon_planes.with(std::cell::Cell::get).is_some() { |
| 3584 | // `reconstruct_mc_rect` reads the prediction and the residual at ONE |
| 3585 | // stride, so a prediction handed over at the block's stride (a var-tx |
| 3586 | // unit's window, lane-wave4) has to be densified for a dense residual |
| 3587 | // -- which is exactly what the recorded path below does. |
| 3588 | let residual = tx.run(grid); |
| 3589 | let res_stride = if tx.stride == 0 { w } else { tx.stride }; |
| 3590 | let window; |
| 3591 | let prediction = if stride == res_stride { |
| 3592 | prediction |
| 3593 | } else { |
| 3594 | debug_assert_eq!(res_stride, w); |
| 3595 | let mut win = Vec::with_capacity(w * h); |
| 3596 | for row in 0..h { |
| 3597 | win.extend_from_slice(&prediction[row * stride..][..w]); |
| 3598 | } |
| 3599 | window = win; |
| 3600 | &window[..] |
| 3601 | }; |
| 3602 | inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx); |
| 3603 | return; |
| 3604 | } |
| 3605 | // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the |
| 3606 | // two buffers at `stride`, so the record carries that window densely |
| 3607 | // rather than the whole block's prediction: a 4x4 unit of a 64x64 block |
| 3608 | // copied 64*64 samples on the PARSING thread before. The residual is then |
| 3609 | // produced dense too (`TxParams::stride = 0`), which is the same numbers |
| 3610 | // in the same places at stride `w`. |
| 3611 | let off = fctx.pred_arena.with(|a| { |
| 3612 | let mut a = a.borrow_mut(); |
| 3613 | let off = a.len(); |
| 3614 | for row in 0..h { |
| 3615 | a.extend_from_slice(&prediction[row * stride..][..w]); |
| 3616 | } |
| 3617 | off as u32 |
| 3618 | }); |
| 3619 | let mut tx = tx; |
| 3620 | tx.stride = 0; |
| 3621 | push_op(fctx, ReconOp::Mc { |
| 3622 | plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32), |
| 3623 | residual: Residual::coeffs(tx, grid, fctx), |
| 3624 | }); |
| 3625 | } |
| 3626 | |
| 3627 | /// Replays every recorded [`ReconOp`] into the frame's planes, in push order, |
| 3628 | /// and empties the queue (lane-wave1 step (i)). |
| 3629 | /// |
| 3630 | /// Called at the top of each superblock visit and at the end of each tile, so |
| 3631 | /// a whole superblock's parsing runs with no plane access at all; the two |
| 3632 | /// parse-time pixel READS that survive -- the intrabc source fetch and the |
| 3633 | /// interintra intra predictor -- flush ahead of themselves instead, which |
| 3634 | /// keeps them byte-exact and names exactly what step (ii) still has to move. |
| 3635 | fn flush_recon( |
| 3636 | fctx: &crate::decode::FrameCtx, |
| 3637 | y: &mut PlaneBuf<'static>, |
| 3638 | u: &mut PlaneBuf<'static>, |
| 3639 | v: &mut PlaneBuf<'static>, |
| 3640 | ) { |
| 3641 | // lane-wave1 step (ii): a parse-time pixel READ needs every worker's |
| 3642 | // writes in place, not just this superblock's queue. |
| 3643 | wave_barrier(fctx); |
| 3644 | let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut())); |
| 3645 | fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops)); |
| 3646 | let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut())); |
| 3647 | fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs)); |
| 3648 | let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut())); |
| 3649 | fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds)); |
| 3650 | let mut cur: [Vec<u16>; 3] = Default::default(); |
| 3651 | for op in ops.drain(..) { |
| 3652 | exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx); |
| 3653 | } |
| 3654 | coeffs.clear(); |
| 3655 | preds.clear(); |
| 3656 | fctx.recon_spare.with(|c| *c.borrow_mut() = ops); |
| 3657 | fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs); |
| 3658 | fctx.pred_spare.with(|c| *c.borrow_mut() = preds); |
| 3659 | } |
| 3660 | |
| 3661 | /// Performs one recorded write: the body [`flush_recon`] replays, and the |
| 3662 | /// body [`push_op`] runs immediately when reconstruction is inline. |
| 3663 | fn exec_op( |
| 3664 | op: ReconOp, |
| 3665 | y: &mut PlaneBuf<'static>, |
| 3666 | u: &mut PlaneBuf<'static>, |
| 3667 | v: &mut PlaneBuf<'static>, |
| 3668 | cur: &mut [Vec<u16>; 3], |
| 3669 | coeffs: &[i32], |
| 3670 | preds: &[u16], |
| 3671 | fctx: &crate::decode::FrameCtx, |
| 3672 | ) { |
| 3673 | // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel |
| 3674 | // write, leaving the entropy parse and the per-mi neighbour bookkeeping |
| 3675 | // alone. It makes the encoder's own streams garbage, so it is a |
| 3676 | // MEASUREMENT rung only -- what it measures is how much of the encoder's |
| 3677 | // first decode of its own tiles (`par::S_FIRST`) is reconstruction and |
| 3678 | // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile |
| 3679 | // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that |
| 3680 | // stage and the parse plus the neighbour grids are the other 94%. That |
| 3681 | // is why handing the decoder the encoder's own reconstruction cannot |
| 3682 | // shrink the stage: only publishing the per-mi neighbour state the |
| 3683 | // filters read (and so never parsing at all) can. |
| 3684 | if crate::envflags::env_flag!("EC_AV1_NORECON") { |
| 3685 | return; |
| 3686 | } |
| 3687 | let mut scratch = Vec::new(); |
| 3688 | match op { |
| 3689 | ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur), |
| 3690 | ReconOp::Intra { |
| 3691 | plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl, |
| 3692 | filter_intra, smooth_neighbor, pred, |
| 3693 | } => exec_intra( |
| 3694 | y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach, |
| 3695 | residual.resolve(coeffs, &mut scratch), |
| 3696 | cfl, filter_intra, smooth_neighbor, pred, fctx, |
| 3697 | ), |
| 3698 | ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => { |
| 3699 | let residual = residual.resolve(coeffs, &mut scratch); |
| 3700 | match prediction { |
| 3701 | PredSrc::Owned(off, len) => { |
| 3702 | let p = &preds[off as usize..][..len as usize]; |
| 3703 | exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx); |
| 3704 | } |
| 3705 | PredSrc::Cur { plane: sp, off, src } => { |
| 3706 | let block = std::mem::take(&mut cur[sp]); |
| 3707 | if src == stride { |
| 3708 | exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx); |
| 3709 | } else { |
| 3710 | // A transform unit's residual is dense, so its window |
| 3711 | // of the block prediction is taken out dense too -- |
| 3712 | // the copy the parsing thread used to make, made here. |
| 3713 | let mut window = Vec::with_capacity(w * h); |
| 3714 | for row in 0..h { |
| 3715 | window.extend_from_slice(&block[off + row * src..][..w]); |
| 3716 | } |
| 3717 | exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx); |
| 3718 | } |
| 3719 | cur[sp] = block; |
| 3720 | } |
| 3721 | } |
| 3722 | } |
| 3723 | } |
| 3724 | } |
| 3725 | |
| 3726 | /// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline |
| 3727 | /// path ([`push_op`]'s registered planes) reaches it without ever building |
| 3728 | /// the record -- which is what keeps one reconstruction thread at the cost of |
| 3729 | /// the pre-lane-wave1 decoder. |
| 3730 | #[allow(clippy::too_many_arguments)] |
| 3731 | fn exec_intra( |
| 3732 | y: &mut PlaneBuf<'static>, |
| 3733 | u: &mut PlaneBuf<'static>, |
| 3734 | v: &mut PlaneBuf<'static>, |
| 3735 | plane: usize, |
| 3736 | x: usize, |
| 3737 | oy: usize, |
| 3738 | bw: usize, |
| 3739 | bh: usize, |
| 3740 | rect: bool, |
| 3741 | mode: usize, |
| 3742 | angle_delta: i32, |
| 3743 | reach: Reach, |
| 3744 | residual: &[i32], |
| 3745 | cfl: Option<(i32, CflSrc)>, |
| 3746 | filter_intra: Option<usize>, |
| 3747 | smooth_neighbor: bool, |
| 3748 | pred: Option<Vec<u16>>, |
| 3749 | fctx: &crate::decode::FrameCtx, |
| 3750 | ) { |
| 3751 | // The CfL AC signal is read HERE, off the luma that has already been |
| 3752 | // written for this block -- at parse time it would have been the previous |
| 3753 | // frame's samples. |
| 3754 | let ac = cfl.map(|(alpha, src)| { |
| 3755 | let sig = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx)); |
| 3756 | (alpha, sig) |
| 3757 | }); |
| 3758 | let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice())); |
| 3759 | let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v }; |
| 3760 | if rect { |
| 3761 | target.reconstruct_rect( |
| 3762 | x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra, |
| 3763 | smooth_neighbor, pred, fctx, |
| 3764 | ); |
| 3765 | } else { |
| 3766 | target.reconstruct( |
| 3767 | x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra, |
| 3768 | smooth_neighbor, pred, fctx, |
| 3769 | ); |
| 3770 | } |
| 3771 | } |
| 3772 | |
| 3773 | /// [`ReconOp::Mc`] performed -- see [`exec_intra`]. |
| 3774 | #[allow(clippy::too_many_arguments)] |
| 3775 | fn exec_mc( |
| 3776 | y: &mut PlaneBuf<'static>, |
| 3777 | u: &mut PlaneBuf<'static>, |
| 3778 | v: &mut PlaneBuf<'static>, |
| 3779 | plane: usize, |
| 3780 | x: usize, |
| 3781 | oy: usize, |
| 3782 | stride: usize, |
| 3783 | w: usize, |
| 3784 | h: usize, |
| 3785 | prediction: &[u16], |
| 3786 | residual: &[i32], |
| 3787 | fctx: &crate::decode::FrameCtx, |
| 3788 | ) { |
| 3789 | let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v }; |
| 3790 | target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx); |
| 3791 | } |
| 3792 | |
| 3793 | thread_local! { |
| 3794 | /// The current frame's `mi` grid, kept only while a frame header set |
| 3795 | /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary |
| 3796 | /// MV stack ([`crate::mvstack::find_mv_stack`]) built against |
| 3797 | /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise |
| 3798 | /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that |
| 3799 | /// does not allow intrabc (so nothing is paid for it). |
| 3800 | /// |
| 3801 | /// corner-cut: only [`decode_block`] (the square path) records into it, |
| 3802 | /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off |
| 3803 | /// an incomplete grid. Ceiling: the DV *value* (never the parse) would |
| 3804 | /// be wrong there; upgrade = record from the rect/leaf paths too. |
| 3805 | /// The block vector [`read_intra_mode`] just decoded, handed to |
| 3806 | /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`], |
| 3807 | /// which the alternative -- a tenth tuple member through every caller -- |
| 3808 | /// already avoids). Always `.take()`n by the block that reads it. |
| 3809 | /// How many blocks read `use_intrabc == 1` and took the DV path -- the |
| 3810 | /// gate's hit counter. Bumped on the READ, before the rect-strip refusal |
| 3811 | /// returns too, so it counts reads, not reconstructions (a refused block |
| 3812 | /// is never reconstructed). |
| 3813 | static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 3814 | } |
| 3815 | // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so |
| 3816 | // an intrabc block's chroma reads can inherit it (see |
| 3817 | // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read |
| 3818 | // through that one arming site. |
| 3819 | // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it |
| 3820 | // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also |
| 3821 | // satisfies (`blockd.h:373`) -- and takes the *colocated luma |
| 3822 | // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never |
| 3823 | // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an |
| 3824 | // intrabc block's two chroma [`read_plane`] calls; the type decides the |
| 3825 | // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context |
| 3826 | // -- getting it wrong desyncs the chroma coefficients, it is not a |
| 3827 | // reconstruction-only detail. |
| 3828 | |
| 3829 | /// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is |
| 3830 | /// `Some` exactly then (set once per frame in `decode_frame`), so the flag |
| 3831 | /// needs no separate plumbing to reach the rect-strip mode reader. |
| 3832 | fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool { |
| 3833 | fctx.intrabc_mi_grid.with(|g| g.borrow().is_some()) |
| 3834 | } |
| 3835 | |
| 3836 | thread_local! { |
| 3837 | /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many |
| 3838 | /// times the fix below was exercised) -- the rect-strip gate's hit counter, |
| 3839 | /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc. |
| 3840 | static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 3841 | } |
| 3842 | |
| 3843 | /// Current value of [`RECT_INTRABC_READS`]. |
| 3844 | pub(crate) fn rect_intrabc_reads() -> usize { |
| 3845 | RECT_INTRABC_READS.with(|c| c.get()) |
| 3846 | } |
| 3847 | |
| 3848 | /// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode). |
| 3849 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3850 | pub(crate) fn reset_rect_intrabc_reads() { |
| 3851 | RECT_INTRABC_READS.with(|c| c.set(0)); |
| 3852 | } |
| 3853 | |
| 3854 | thread_local! { |
| 3855 | /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically |
| 3856 | /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape. |
| 3857 | static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 3858 | } |
| 3859 | |
| 3860 | /// Current value of [`LEAF8_INTRABC_HITS`]. |
| 3861 | pub(crate) fn leaf8_intrabc_hits() -> usize { |
| 3862 | LEAF8_INTRABC_HITS.with(|c| c.get()) |
| 3863 | } |
| 3864 | |
| 3865 | /// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode). |
| 3866 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3867 | pub(crate) fn reset_leaf8_intrabc_hits() { |
| 3868 | LEAF8_INTRABC_HITS.with(|c| c.set(0)); |
| 3869 | } |
| 3870 | |
| 3871 | /// Current value of [`INTRABC_HITS`]. |
| 3872 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3873 | pub(crate) fn intrabc_hits() -> usize { |
| 3874 | INTRABC_HITS.with(|c| c.get()) |
| 3875 | } |
| 3876 | |
| 3877 | thread_local! { |
| 3878 | /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is |
| 3879 | /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no |
| 3880 | /// chroma coefficient at all, so the slot used to stay armed into the NEXT |
| 3881 | /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count |
| 3882 | /// here. A non-zero value is what makes the disarm below load-bearing. |
| 3883 | static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> = |
| 3884 | const { std::cell::Cell::new(0) }; |
| 3885 | } |
| 3886 | |
| 3887 | /// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`]. |
| 3888 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe |
| 3889 | pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize { |
| 3890 | SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get()) |
| 3891 | } |
| 3892 | |
| 3893 | /// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a |
| 3894 | /// decode). |
| 3895 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3896 | pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() { |
| 3897 | SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0)); |
| 3898 | } |
| 3899 | |
| 3900 | /// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode). |
| 3901 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3902 | pub(crate) fn reset_intrabc_hits() { |
| 3903 | INTRABC_HITS.with(|c| c.set(0)); |
| 3904 | } |
| 3905 | |
| 3906 | thread_local! { |
| 3907 | /// lane-t900 r32: intrabc blocks whose transform size came off the INTER |
| 3908 | /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability |
| 3909 | /// that replaced the refusal "an intrabc block under TxMode::Select". |
| 3910 | static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 3911 | /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf -- |
| 3912 | /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves |
| 3913 | /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no |
| 3914 | /// symbol here desynced `warped.obu` at the very next block. |
| 3915 | static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 3916 | /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction |
| 3917 | /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip |
| 3918 | /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never |
| 3919 | /// this one). |
| 3920 | static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 3921 | /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT). |
| 3922 | static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 3923 | /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction |
| 3924 | /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read), |
| 3925 | /// split by the strip's orientation -- `bw > bh` is a HORZ strip, |
| 3926 | /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED |
| 3927 | /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS` |
| 3928 | /// counts neither orientation nor the skip flag, so an arm that flipped |
| 3929 | /// to an all-skip stream (no residual reader at all) would stay green. |
| 3930 | static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> = |
| 3931 | const { std::cell::Cell::new([0, 0]) }; |
| 3932 | /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`] |
| 3933 | /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split |
| 3934 | /// by orientation. The r5 panic (residual stride `bw * bh` underrunning |
| 3935 | /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was |
| 3936 | /// invisible to every gate because they only counted CODED strips. |
| 3937 | static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> = |
| 3938 | const { std::cell::Cell::new([0, 0]) }; |
| 3939 | } |
| 3940 | |
| 3941 | /// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed, |
| 3942 | /// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`]. |
| 3943 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3944 | pub fn intrabc_rect_coded_hits() -> [usize; 2] { |
| 3945 | INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get) |
| 3946 | } |
| 3947 | |
| 3948 | /// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks |
| 3949 | /// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`]. |
| 3950 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3951 | pub fn intrabc_rect_skipped_hits() -> [usize; 2] { |
| 3952 | INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get) |
| 3953 | } |
| 3954 | |
| 3955 | /// Current value of [`INTRABC_RECT_HITS`]. |
| 3956 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3957 | pub fn intrabc_rect_hits() -> usize { |
| 3958 | INTRABC_RECT_HITS.with(|c| c.get()) |
| 3959 | } |
| 3960 | |
| 3961 | /// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`]. |
| 3962 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3963 | pub(crate) fn reset_intrabc_rect_hits() { |
| 3964 | INTRABC_RECT_HITS.with(|c| c.set(0)); |
| 3965 | INTRABC_RECT_VARTX_HITS.with(|c| c.set(0)); |
| 3966 | INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0])); |
| 3967 | INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0])); |
| 3968 | } |
| 3969 | |
| 3970 | /// Current value of [`INTRABC_RECT_VARTX_HITS`]. |
| 3971 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3972 | pub fn intrabc_rect_vartx_hits() -> usize { |
| 3973 | INTRABC_RECT_VARTX_HITS.with(|c| c.get()) |
| 3974 | } |
| 3975 | |
| 3976 | thread_local! { |
| 3977 | /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip |
| 3978 | /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction |
| 3979 | /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to |
| 3980 | /// guard (`decode_block_128rect`). A refused block bumps |
| 3981 | /// [`INTRABC_HITS`] but never this one. |
| 3982 | static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 3983 | } |
| 3984 | |
| 3985 | /// Current value of [`INTRABC_128RECT_HITS`]. |
| 3986 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3987 | pub fn intrabc_128rect_hits() -> usize { |
| 3988 | INTRABC_128RECT_HITS.with(|c| c.get()) |
| 3989 | } |
| 3990 | |
| 3991 | /// Zeroes [`INTRABC_128RECT_HITS`]. |
| 3992 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3993 | pub(crate) fn reset_intrabc_128rect_hits() { |
| 3994 | INTRABC_128RECT_HITS.with(|c| c.set(0)); |
| 3995 | } |
| 3996 | |
| 3997 | /// Current value of [`INTRABC_VARTX_HITS`]. |
| 3998 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3999 | pub(crate) fn intrabc_vartx_hits() -> usize { |
| 4000 | INTRABC_VARTX_HITS.with(|c| c.get()) |
| 4001 | } |
| 4002 | |
| 4003 | /// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode). |
| 4004 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4005 | pub(crate) fn reset_intrabc_vartx_hits() { |
| 4006 | INTRABC_VARTX_HITS.with(|c| c.set(0)); |
| 4007 | } |
| 4008 | |
| 4009 | /// Current value of [`RECT_INTRABC_VARTX_HITS`]. |
| 4010 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4011 | pub fn rect_intrabc_vartx_hits() -> usize { |
| 4012 | RECT_INTRABC_VARTX_HITS.with(|c| c.get()) |
| 4013 | } |
| 4014 | |
| 4015 | /// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes |
| 4016 | /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any |
| 4017 | /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an |
| 4018 | /// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`). |
| 4019 | fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, n: &mut Neighbours, fctx: &crate::decode::FrameCtx) { |
| 4020 | record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx); |
| 4021 | } |
| 4022 | |
| 4023 | /// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs` |
| 4024 | /// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4` |
| 4025 | /// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr). |
| 4026 | /// |
| 4027 | /// Also stamps libaom's `is_inter_block` verdict for this block into the |
| 4028 | /// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override |
| 4029 | /// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] > |
| 4030 | /// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and |
| 4031 | /// `get_tx_size_context` reads its BLOCK size rather than its transform band. |
| 4032 | /// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which |
| 4033 | /// every block runs; this runs after it (class leaked-band otherwise). |
| 4034 | fn record_intrabc_mi_rect( |
| 4035 | mi_r: usize, |
| 4036 | mi_c: usize, |
| 4037 | n4_w: usize, |
| 4038 | n4_h: usize, |
| 4039 | dv: Option<(i32, i32)>, |
| 4040 | n: &mut Neighbours, |
| 4041 | fctx: &crate::decode::FrameCtx, |
| 4042 | ) { |
| 4043 | if dv.is_some() { |
| 4044 | for i in 0..n4_w { |
| 4045 | if let Some(cell) = n.above_inter.get_mut(mi_c + i) { |
| 4046 | *cell = true; |
| 4047 | } |
| 4048 | } |
| 4049 | for i in 0..n4_h { |
| 4050 | if let Some(cell) = n.left_inter.get_mut(mi_r + i) { |
| 4051 | *cell = true; |
| 4052 | } |
| 4053 | } |
| 4054 | } |
| 4055 | fctx.intrabc_mi_grid.with(|g| { |
| 4056 | let mut g = g.borrow_mut(); |
| 4057 | let Some((grid, _, _)) = g.as_mut() else { |
| 4058 | return; |
| 4059 | }; |
| 4060 | let info = crate::mvstack::MiInfo { |
| 4061 | is_inter: dv.is_some(), |
| 4062 | ref_frame: 0, |
| 4063 | ref_frame1: NO_REF1, |
| 4064 | mv: mv16(dv.unwrap_or((0, 0))), |
| 4065 | mv1: (0, 0), |
| 4066 | is_new_mv: dv.is_some(), |
| 4067 | is_global_mv0: false, |
| 4068 | is_global_mv1: false, |
| 4069 | size: n4_w as u8, |
| 4070 | size_h: n4_h as u8, |
| 4071 | }; |
| 4072 | for r in mi_r..mi_r + n4_h { |
| 4073 | for c in mi_c..mi_c + n4_w { |
| 4074 | grid.set(r, c, info); |
| 4075 | } |
| 4076 | } |
| 4077 | }); |
| 4078 | } |
| 4079 | |
| 4080 | // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) -- |
| 4081 | // proves a real `skip_mode_present` stream actually reached a block that |
| 4082 | // picked it, not just that the frame header bit was set. |
| 4083 | thread_local! { |
| 4084 | static SKIP_MODE_HITS: std::cell::Cell<usize> = |
| 4085 | const { std::cell::Cell::new(0) }; |
| 4086 | } |
| 4087 | |
| 4088 | /// Current value of [`SKIP_MODE_HITS`]. |
| 4089 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4090 | pub(crate) fn skip_mode_hits() -> usize { |
| 4091 | SKIP_MODE_HITS.with(|c| c.get()) |
| 4092 | } |
| 4093 | |
| 4094 | // lane-motionmode: how many blocks actually decoded `obmc_selected == true` |
| 4095 | // (as opposed to just reaching an eligible `read_motion_mode` symbol read) |
| 4096 | // -- the gate's own proof that a real aomenc `--enable-obmc=1` stream |
| 4097 | // reached [`obmc_blend`], not just the header bit. |
| 4098 | thread_local! { |
| 4099 | static OBMC_HITS: std::cell::Cell<usize> = |
| 4100 | const { std::cell::Cell::new(0) }; |
| 4101 | } |
| 4102 | |
| 4103 | // lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the |
| 4104 | // 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled |
| 4105 | // reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while |
| 4106 | // `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have |
| 4107 | // picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this |
| 4108 | // decoder used to read with the wrong alphabet, so a gate that asserts this |
| 4109 | // counter advanced proves the fixed path fired (class |
| 4110 | // `gate-blind-to-feature`). |
| 4111 | thread_local! { |
| 4112 | static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4113 | } |
| 4114 | |
| 4115 | /// Current value of [`FIMV_ALPHABET_HITS`]. |
| 4116 | pub fn fimv_alphabet_hits() -> usize { |
| 4117 | FIMV_ALPHABET_HITS.with(|c| c.get()) |
| 4118 | } |
| 4119 | |
| 4120 | // lane-fimv r1: how many frame headers this decoder has decoded with |
| 4121 | // `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate |
| 4122 | // prove the encoder really produced the header state under test rather than |
| 4123 | // assume it. |
| 4124 | thread_local! { |
| 4125 | static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4126 | } |
| 4127 | |
| 4128 | /// Current value of [`FIMV_FRAME_HITS`]. |
| 4129 | pub fn fimv_frame_hits() -> usize { |
| 4130 | FIMV_FRAME_HITS.with(|c| c.get()) |
| 4131 | } |
| 4132 | |
| 4133 | /// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose |
| 4134 | /// `force_integer_mv` bit is set. |
| 4135 | pub fn note_force_integer_mv_frame() { |
| 4136 | hit!(FIMV_FRAME_HITS); |
| 4137 | } |
| 4138 | |
| 4139 | /// Current value of [`OBMC_HITS`]. |
| 4140 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4141 | pub(crate) fn obmc_hits() -> usize { |
| 4142 | OBMC_HITS.with(|c| c.get()) |
| 4143 | } |
| 4144 | |
| 4145 | // lane-t900 r27: OBMC blends that actually READ a recorded switchable filter |
| 4146 | // off the neighbour band -- the positive half of the proof for "an OBMC |
| 4147 | // neighbour whose switchable interp filter was never recorded". A |
| 4148 | // fixed-filter frame returns before this point (its neighbours legitimately |
| 4149 | // carry the `[3, 3]` sentinel), so every bump is a neighbour whose own |
| 4150 | // `interp_filter` symbols were published by `record_inter_rect_mi`. |
| 4151 | thread_local! { |
| 4152 | static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4153 | } |
| 4154 | |
| 4155 | /// Current value of [`OBMC_FILTER_BAND_READS`]. |
| 4156 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4157 | pub(crate) fn obmc_filter_band_reads() -> usize { |
| 4158 | OBMC_FILTER_BAND_READS.with(|c| c.get()) |
| 4159 | } |
| 4160 | |
| 4161 | // lane-scaledref r1: per-case firing counts for the scaled-reference gate |
| 4162 | // (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED |
| 4163 | // reference would pass just as well and prove nothing, so the gate |
| 4164 | // hard-asserts each combination this round lifts actually occurred: |
| 4165 | // a compound block with a scaled tap, a warp block whose warp libaom |
| 4166 | // suppresses because the reference is scaled, an OBMC block, an interintra |
| 4167 | // block, and an 8x8 leaf. |
| 4168 | thread_local! { |
| 4169 | static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4170 | static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4171 | static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4172 | static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4173 | static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4174 | static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4175 | static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4176 | } |
| 4177 | |
| 4178 | /// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one |
| 4179 | /// scaled and one unscaled tap. |
| 4180 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4181 | pub(crate) fn mixed_scale_compound_hits() -> usize { |
| 4182 | MIXED_SCALE_COMPOUND_HITS.with(|c| c.get()) |
| 4183 | } |
| 4184 | |
| 4185 | /// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have |
| 4186 | /// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf` |
| 4187 | /// instead because their reference is scaled (libaom `motion_mode_allowed`, |
| 4188 | /// `blockd.h:1484`). |
| 4189 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4190 | pub(crate) fn scaled_warp_suppressed_hits() -> usize { |
| 4191 | SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get()) |
| 4192 | } |
| 4193 | |
| 4194 | /// Current value of [`SCALED_COMPOUND_HITS`]. |
| 4195 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4196 | pub(crate) fn scaled_compound_hits() -> usize { |
| 4197 | SCALED_COMPOUND_HITS.with(|c| c.get()) |
| 4198 | } |
| 4199 | |
| 4200 | /// Current value of [`SCALED_WARP_FALLBACK_HITS`]. |
| 4201 | pub fn scaled_warp_fallback_hits() -> usize { |
| 4202 | SCALED_WARP_FALLBACK_HITS.with(|c| c.get()) |
| 4203 | } |
| 4204 | |
| 4205 | /// Current value of [`SCALED_OBMC_HITS`]. |
| 4206 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4207 | pub(crate) fn scaled_obmc_hits() -> usize { |
| 4208 | SCALED_OBMC_HITS.with(|c| c.get()) |
| 4209 | } |
| 4210 | |
| 4211 | /// Current value of [`SCALED_INTERINTRA_HITS`]. |
| 4212 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4213 | pub(crate) fn scaled_interintra_hits() -> usize { |
| 4214 | SCALED_INTERINTRA_HITS.with(|c| c.get()) |
| 4215 | } |
| 4216 | |
| 4217 | /// Current value of [`SCALED_BLOCK8_HITS`]. |
| 4218 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4219 | pub(crate) fn scaled_block8_hits() -> usize { |
| 4220 | SCALED_BLOCK8_HITS.with(|c| c.get()) |
| 4221 | } |
| 4222 | |
| 4223 | // lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to |
| 4224 | // `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of |
| 4225 | // [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an |
| 4226 | // 8x8-leaf OBMC block apart from a 16x16+ one. |
| 4227 | thread_local! { |
| 4228 | static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4229 | } |
| 4230 | |
| 4231 | // lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter` |
| 4232 | // pair whose two directions differ (`enable_dual_filter` only -- with dual |
| 4233 | // filter off both directions take the single symbol, so this can never fire). |
| 4234 | // A gate asserting it proves the stream really carries dual-filter blocks. |
| 4235 | thread_local! { |
| 4236 | static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4237 | } |
| 4238 | |
| 4239 | // lane-interp3 r1: how many COMPOUND 8x8 leaves read their own |
| 4240 | // `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf |
| 4241 | // used to skip it entirely, losing a symbol and stamping the `[3, 3]` |
| 4242 | // no-filter sentinel that made a neighbouring OBMC block panic). |
| 4243 | thread_local! { |
| 4244 | static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4245 | } |
| 4246 | |
| 4247 | /// Current value of [`DUAL_FILTER_DIFF_HITS`]. |
| 4248 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4249 | pub(crate) fn dual_filter_diff_hits() -> usize { |
| 4250 | DUAL_FILTER_DIFF_HITS.with(|c| c.get()) |
| 4251 | } |
| 4252 | |
| 4253 | /// Current value of [`COMPOUND8_FILTER_HITS`]. |
| 4254 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4255 | pub(crate) fn compound8_filter_hits() -> usize { |
| 4256 | COMPOUND8_FILTER_HITS.with(|c| c.get()) |
| 4257 | } |
| 4258 | |
| 4259 | // lane-warp round 1: how many blocks resolved `motion_mode_allowed` to |
| 4260 | // `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under |
| 4261 | // `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL` |
| 4262 | // -- the gate's proof that a fixture really exercises the alphabet this |
| 4263 | // round changed, even though the block itself still refuses (warp |
| 4264 | // estimation/filter not ported). |
| 4265 | thread_local! { |
| 4266 | static WARP_SELECTED_HITS: std::cell::Cell<usize> = |
| 4267 | const { std::cell::Cell::new(0) }; |
| 4268 | } |
| 4269 | |
| 4270 | /// Current value of [`WARP_SELECTED_HITS`]. |
| 4271 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4272 | pub(crate) fn warp_selected_hits() -> usize { |
| 4273 | WARP_SELECTED_HITS.with(|c| c.get()) |
| 4274 | } |
| 4275 | |
| 4276 | // lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one |
| 4277 | // reference predicted through the per-ref GLOBAL warp (`av1_warp_plane` |
| 4278 | // into the compound intermediate) rather than translationally -- the |
| 4279 | // gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model |
| 4280 | // really reached [`crate::warp::warp_affine_compound`]. |
| 4281 | thread_local! { |
| 4282 | static COMPOUND_WARP_HITS: std::cell::Cell<usize> = |
| 4283 | const { std::cell::Cell::new(0) }; |
| 4284 | } |
| 4285 | |
| 4286 | /// Current value of [`COMPOUND_WARP_HITS`]. |
| 4287 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4288 | pub(crate) fn compound_warp_hits() -> usize { |
| 4289 | COMPOUND_WARP_HITS.with(|c| c.get()) |
| 4290 | } |
| 4291 | |
| 4292 | // lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound |
| 4293 | // arm ([`decode_inter_block8`]) -- that arm predicted both taps |
| 4294 | // translationally until r3, so a gate needs to tell a warped 8x8 compound |
| 4295 | // leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]). |
| 4296 | thread_local! { |
| 4297 | static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> = |
| 4298 | const { std::cell::Cell::new(0) }; |
| 4299 | } |
| 4300 | |
| 4301 | /// Current value of [`COMPOUND_WARP_HITS_8`]. |
| 4302 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4303 | pub(crate) fn compound_warp_hits_8() -> usize { |
| 4304 | COMPOUND_WARP_HITS_8.with(|c| c.get()) |
| 4305 | } |
| 4306 | |
| 4307 | // lane-gmaffine r1: how many blocks built their prediction from a |
| 4308 | // SIX-parameter (`AFFINE`) global-motion model through |
| 4309 | // `crate::warp::global_warp_params` -- the gate's proof that a stream really |
| 4310 | // carried an AFFINE `global_motion_params` AND that a block was predicted |
| 4311 | // with it, not merely that the header parsed one. |
| 4312 | thread_local! { |
| 4313 | static AFFINE_GM_HITS: std::cell::Cell<usize> = |
| 4314 | const { std::cell::Cell::new(0) }; |
| 4315 | } |
| 4316 | |
| 4317 | /// Current value of [`AFFINE_GM_HITS`]. |
| 4318 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4319 | pub(crate) fn affine_gm_hits() -> usize { |
| 4320 | AFFINE_GM_HITS.with(|c| c.get()) |
| 4321 | } |
| 4322 | |
| 4323 | // lane-t900 r9: rect blocks whose warp-sample top-right probe answers |
| 4324 | // differently at the block's WIDTH than at libaom's |
| 4325 | // `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could |
| 4326 | // pick the wrong motion_mode alphabet. |
| 4327 | thread_local! { |
| 4328 | static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4329 | } |
| 4330 | |
| 4331 | /// Current value of [`TR_REACH_LONGER_SIDE_HITS`]. |
| 4332 | pub fn tr_reach_longer_side_hits() -> usize { |
| 4333 | TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get) |
| 4334 | } |
| 4335 | |
| 4336 | // lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0 |
| 4337 | // for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block |
| 4338 | // with a 4-px side is NEVER "non-translational global" and therefore ALWAYS |
| 4339 | // reads its interp-filter symbol. Counts the blocks where that guard flips |
| 4340 | // our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model |
| 4341 | // and a 4-px side, which we used to suppress the interp read on (a pre-mode |
| 4342 | // entropy desync one symbol wide). |
| 4343 | thread_local! { |
| 4344 | static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4345 | } |
| 4346 | |
| 4347 | /// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`]. |
| 4348 | pub fn gm_nontrans_small_side_hits() -> usize { |
| 4349 | GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get) |
| 4350 | } |
| 4351 | |
| 4352 | // lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves |
| 4353 | // coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real |
| 4354 | // `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented |
| 4355 | // only once `find_projection` returned a usable model, unlike |
| 4356 | // `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates' |
| 4357 | // proof that the leaf path itself fired, not the 16x16+ one. |
| 4358 | thread_local! { |
| 4359 | static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4360 | static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4361 | } |
| 4362 | |
| 4363 | /// Current value of [`GLOBALMV_HITS_8`]. |
| 4364 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4365 | pub(crate) fn globalmv_hits_8() -> usize { |
| 4366 | GLOBALMV_HITS_8.with(|c| c.get()) |
| 4367 | } |
| 4368 | |
| 4369 | /// Current value of [`WARP_HITS_8`]. |
| 4370 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4371 | pub(crate) fn warp_hits_8() -> usize { |
| 4372 | WARP_HITS_8.with(|c| c.get()) |
| 4373 | } |
| 4374 | |
| 4375 | // How many blocks decoded `interintra == 1` with the non-wedge blended |
| 4376 | // prediction applied (lane-interintra r1) -- the gate's proof that a |
| 4377 | // stream actually exercised interintra. |
| 4378 | thread_local! { |
| 4379 | static INTERINTRA_HITS: std::cell::Cell<usize> = |
| 4380 | const { std::cell::Cell::new(0) }; |
| 4381 | } |
| 4382 | |
| 4383 | /// Current value of [`INTERINTRA_HITS`]. |
| 4384 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4385 | pub(crate) fn interintra_hits() -> usize { |
| 4386 | INTERINTRA_HITS.with(|c| c.get()) |
| 4387 | } |
| 4388 | |
| 4389 | // lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`) |
| 4390 | // -- the shape `interintra_blend` used to build a square `side x side` intra |
| 4391 | // predictor for, with `ii_size_scales`/`edges` taken at the square. Every |
| 4392 | // pre-existing interintra gate passed with that bug, so the rect arm needs |
| 4393 | // its own counter to stop being vacuous. |
| 4394 | thread_local! { |
| 4395 | static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4396 | } |
| 4397 | |
| 4398 | /// Current value of [`INTERINTRA_RECT_HITS`]. |
| 4399 | pub fn interintra_rect_hits() -> usize { |
| 4400 | INTERINTRA_RECT_HITS.with(|c| c.get()) |
| 4401 | } |
| 4402 | |
| 4403 | // How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE, |
| 4404 | // wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/ |
| 4405 | // `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a |
| 4406 | // gate fixture actually exercises this alphabet, even though the block |
| 4407 | // still refuses (the mask blend itself is unported). |
| 4408 | thread_local! { |
| 4409 | static MASKED_COMPOUND_HITS: std::cell::Cell<usize> = |
| 4410 | const { std::cell::Cell::new(0) }; |
| 4411 | } |
| 4412 | |
| 4413 | /// Current value of [`MASKED_COMPOUND_HITS`]. |
| 4414 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4415 | pub(crate) fn masked_compound_hits() -> usize { |
| 4416 | MASKED_COMPOUND_HITS.with(|c| c.get()) |
| 4417 | } |
| 4418 | |
| 4419 | // lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a |
| 4420 | // masked-compound block whose true footprint is rectangular, i.e. the case |
| 4421 | // whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the |
| 4422 | // square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that |
| 4423 | // defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it. |
| 4424 | thread_local! { |
| 4425 | static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> = |
| 4426 | const { std::cell::Cell::new(0) }; |
| 4427 | } |
| 4428 | |
| 4429 | /// Current value of [`RECT_MASKED_COMPOUND_HITS`]. |
| 4430 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4431 | pub(crate) fn rect_masked_compound_hits() -> usize { |
| 4432 | RECT_MASKED_COMPOUND_HITS.with(|c| c.get()) |
| 4433 | } |
| 4434 | |
| 4435 | // How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx == |
| 4436 | // 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture |
| 4437 | // actually exercised the wedge blend, not just the DIFFWTD half of |
| 4438 | // `MASKED_COMPOUND_HITS`. |
| 4439 | thread_local! { |
| 4440 | static WEDGE_HITS: std::cell::Cell<usize> = |
| 4441 | const { std::cell::Cell::new(0) }; |
| 4442 | } |
| 4443 | |
| 4444 | /// Current value of [`WEDGE_HITS`]. |
| 4445 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4446 | pub(crate) fn wedge_hits() -> usize { |
| 4447 | WEDGE_HITS.with(|c| c.get()) |
| 4448 | } |
| 4449 | |
| 4450 | // How many blocks decoded a real wedge-INTERINTRA block |
| 4451 | // (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof |
| 4452 | // a gate fixture exercised the wedge blend (fixed sign 0), not just the |
| 4453 | // smooth arm counted by `INTERINTRA_HITS`. |
| 4454 | thread_local! { |
| 4455 | static WII_HITS: std::cell::Cell<usize> = |
| 4456 | const { std::cell::Cell::new(0) }; |
| 4457 | } |
| 4458 | |
| 4459 | /// Current value of [`WII_HITS`]. |
| 4460 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4461 | pub(crate) fn wii_hits() -> usize { |
| 4462 | WII_HITS.with(|c| c.get()) |
| 4463 | } |
| 4464 | |
| 4465 | // lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol |
| 4466 | // NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`: |
| 4467 | // wide <= 32 && high <= 32). The witness that a gate stream really carries a |
| 4468 | // 64-axis intra block -- the shape whose 14-symbol read desynced every inter |
| 4469 | // frame carrying one. |
| 4470 | thread_local! { |
| 4471 | static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4472 | } |
| 4473 | |
| 4474 | /// Current value of [`NOCFL_UV_MODE_HITS`]. |
| 4475 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4476 | pub(crate) fn nocfl_uv_mode_hits() -> usize { |
| 4477 | NOCFL_UV_MODE_HITS.with(|c| c.get()) |
| 4478 | } |
| 4479 | |
| 4480 | /// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order -- |
| 4481 | /// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`]. |
| 4482 | pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] = |
| 4483 | [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)]; |
| 4484 | |
| 4485 | fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> { |
| 4486 | RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh)) |
| 4487 | } |
| 4488 | |
| 4489 | // lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a |
| 4490 | // RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that |
| 4491 | // the rect wedge masks lifted this round actually fired, not just the square |
| 4492 | // ones already counted by `WEDGE_HITS`/`WII_HITS`. |
| 4493 | thread_local! { |
| 4494 | static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) }; |
| 4495 | static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) }; |
| 4496 | } |
| 4497 | |
| 4498 | /// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`]. |
| 4499 | pub(crate) fn rect_wedge_hits() -> [usize; 6] { |
| 4500 | RECT_WEDGE_HITS.with(|c| c.get()) |
| 4501 | } |
| 4502 | |
| 4503 | /// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`]. |
| 4504 | pub(crate) fn rect_wii_hits() -> [usize; 6] { |
| 4505 | RECT_WII_HITS.with(|c| c.get()) |
| 4506 | } |
| 4507 | |
| 4508 | // lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC |
| 4509 | // blend -- the gate's proof that `--enable-obmc=1` reached this shape (the |
| 4510 | // r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented |
| 4511 | // aomdec, neighbour list included). |
| 4512 | thread_local! { |
| 4513 | static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4514 | } |
| 4515 | |
| 4516 | /// Current value of [`OBMC_RECT_LEAF_HITS`]. |
| 4517 | pub(crate) fn obmc_rect_leaf_hits() -> usize { |
| 4518 | OBMC_RECT_LEAF_HITS.with(|c| c.get()) |
| 4519 | } |
| 4520 | |
| 4521 | // lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of |
| 4522 | // a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used |
| 4523 | // to be read from the pair's FIRST mi, which is a different block and, when |
| 4524 | // that half is intra, carries the `[3, 3]` "no filter" sentinel (the three |
| 4525 | // 1080p 10-bit film cuts refused there). The gate's proof the shape fired. |
| 4526 | thread_local! { |
| 4527 | static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4528 | } |
| 4529 | |
| 4530 | /// Current value of [`OBMC_PAIR_FILTER_HITS`]. |
| 4531 | pub(crate) fn obmc_pair_filter_hits() -> usize { |
| 4532 | OBMC_PAIR_FILTER_HITS.with(|c| c.get()) |
| 4533 | } |
| 4534 | |
| 4535 | // lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge |
| 4536 | // -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's |
| 4537 | // own side, so a block overhanging the bottom/right still predicts the full |
| 4538 | // neighbour strip (the destination write is what clips). We used to shrink the |
| 4539 | // prediction to the visible part, which at 4 chroma rows/cols also swaps the |
| 4540 | // vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired. |
| 4541 | thread_local! { |
| 4542 | static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4543 | } |
| 4544 | |
| 4545 | /// Current value of [`OBMC_EDGE_SPAN_HITS`]. |
| 4546 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4547 | pub(crate) fn obmc_edge_span_hits() -> usize { |
| 4548 | OBMC_EDGE_SPAN_HITS.with(|c| c.get()) |
| 4549 | } |
| 4550 | |
| 4551 | /// Current value of [`OBMC_HITS_8`]. |
| 4552 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4553 | pub(crate) fn obmc_hits_8() -> usize { |
| 4554 | OBMC_HITS_8.with(|c| c.get()) |
| 4555 | } |
| 4556 | |
| 4557 | // lane-rectgate r1: how many 32x32 quadrants actually decoded a |
| 4558 | // `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's |
| 4559 | // inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/ |
| 4560 | // `VERT_B` all still fall into the generic "a partition type this encoder |
| 4561 | // never writes" refusal below) -- the gate's proof that a free-partition |
| 4562 | // aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than |
| 4563 | // coincidentally never selecting one. |
| 4564 | thread_local! { |
| 4565 | static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> = |
| 4566 | const { std::cell::Cell::new(0) }; |
| 4567 | } |
| 4568 | |
| 4569 | /// Current value of [`EXTENDED_PARTITION_HITS`]. |
| 4570 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4571 | pub(crate) fn extended_partition_hits() -> usize { |
| 4572 | EXTENDED_PARTITION_HITS.with(|c| c.get()) |
| 4573 | } |
| 4574 | |
| 4575 | // lane-partitions r1: how many 32x32 quadrants decoded a real |
| 4576 | // `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike |
| 4577 | // `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition |
| 4578 | // gate's proof this round's arms actually fired. |
| 4579 | thread_local! { |
| 4580 | static RECT_PARTITION_HITS: std::cell::Cell<usize> = |
| 4581 | const { std::cell::Cell::new(0) }; |
| 4582 | } |
| 4583 | |
| 4584 | /// Current value of [`RECT_PARTITION_HITS`]. |
| 4585 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4586 | pub(crate) fn rect_partition_hits() -> usize { |
| 4587 | RECT_PARTITION_HITS.with(|c| c.get()) |
| 4588 | } |
| 4589 | |
| 4590 | // lane-inter8 r1: how many superblocks an inter tile coded as a single |
| 4591 | // whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for |
| 4592 | // static content, previously a named refusal). |
| 4593 | thread_local! { |
| 4594 | /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile |
| 4595 | /// path decoded as one whole block (its gate's own witness). |
| 4596 | pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4597 | /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7). |
| 4598 | pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4599 | pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4600 | } |
| 4601 | |
| 4602 | /// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta. |
| 4603 | pub(crate) fn inter_sb128_horz_hits() -> usize { |
| 4604 | INTER_SB128_HORZ_HITS.with(std::cell::Cell::get) |
| 4605 | } |
| 4606 | |
| 4607 | /// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta. |
| 4608 | pub(crate) fn inter_sb128_vert_hits() -> usize { |
| 4609 | INTER_SB128_VERT_HITS.with(std::cell::Cell::get) |
| 4610 | } |
| 4611 | |
| 4612 | /// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta. |
| 4613 | pub fn inter_sb128_none_hits() -> usize { |
| 4614 | INTER_SB128_NONE_HITS.with(std::cell::Cell::get) |
| 4615 | } |
| 4616 | |
| 4617 | thread_local! { |
| 4618 | /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER |
| 4619 | /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma |
| 4620 | /// units) -- the gate's witness that the lifted refusal's case fired. |
| 4621 | pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4622 | } |
| 4623 | |
| 4624 | /// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta. |
| 4625 | pub fn intra_128_in_inter_hits() -> usize { |
| 4626 | INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get) |
| 4627 | } |
| 4628 | |
| 4629 | thread_local! { |
| 4630 | static INTER_SB_NONE_HITS: std::cell::Cell<usize> = |
| 4631 | const { std::cell::Cell::new(0) }; |
| 4632 | } |
| 4633 | |
| 4634 | /// Current value of [`INTER_SB_NONE_HITS`]. |
| 4635 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4636 | pub(crate) fn inter_sb_none_hits() -> usize { |
| 4637 | INTER_SB_NONE_HITS.with(|c| c.get()) |
| 4638 | } |
| 4639 | |
| 4640 | // lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter |
| 4641 | // blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle |
| 4642 | // path has always run that loop, so only this counter proves the newly-lifted |
| 4643 | // alphabet value fired. |
| 4644 | thread_local! { |
| 4645 | static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> = |
| 4646 | const { std::cell::Cell::new(0) }; |
| 4647 | } |
| 4648 | |
| 4649 | /// Current value of [`INTER_SUB16_SPLIT_HITS`]. |
| 4650 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4651 | pub(crate) fn inter_sub16_split_hits() -> usize { |
| 4652 | INTER_SUB16_SPLIT_HITS.with(|c| c.get()) |
| 4653 | } |
| 4654 | |
| 4655 | // lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves |
| 4656 | // while at least one reference picture was SCALED (superres) -- the counter |
| 4657 | // behind the lifted "8x8 partition leaf under a scaled reference" refusal. |
| 4658 | thread_local! { |
| 4659 | static SCALED_LEAF8_HITS: std::cell::Cell<usize> = |
| 4660 | const { std::cell::Cell::new(0) }; |
| 4661 | } |
| 4662 | |
| 4663 | /// Current value of [`SCALED_LEAF8_HITS`]. |
| 4664 | pub fn scaled_leaf8_hits() -> usize { |
| 4665 | SCALED_LEAF8_HITS.with(|c| c.get()) |
| 4666 | } |
| 4667 | |
| 4668 | // lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8 |
| 4669 | // rect pair) were predicted from a SCALED reference -- the counter behind the |
| 4670 | // lifted "sub-8x8 inter block under a scaled reference" refusal. |
| 4671 | thread_local! { |
| 4672 | static SCALED_SUB8_HITS: std::cell::Cell<usize> = |
| 4673 | const { std::cell::Cell::new(0) }; |
| 4674 | } |
| 4675 | |
| 4676 | /// Current value of [`SCALED_SUB8_HITS`]. |
| 4677 | pub fn scaled_sub8_hits() -> usize { |
| 4678 | SCALED_SUB8_HITS.with(|c| c.get()) |
| 4679 | } |
| 4680 | |
| 4681 | // lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded |
| 4682 | // real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the |
| 4683 | // rect coefficient reader itself fired, not just the strip-level partition |
| 4684 | // symbol [`RECT_PARTITION_HITS`] already counts. |
| 4685 | thread_local! { |
| 4686 | static RECT_COEFF_HITS: std::cell::Cell<usize> = |
| 4687 | const { std::cell::Cell::new(0) }; |
| 4688 | } |
| 4689 | |
| 4690 | /// Current value of [`RECT_COEFF_HITS`]. |
| 4691 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4692 | pub(crate) fn rect_coeff_hits() -> usize { |
| 4693 | RECT_COEFF_HITS.with(|c| c.get()) |
| 4694 | } |
| 4695 | |
| 4696 | // lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`]) |
| 4697 | // decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the |
| 4698 | // charter's real-aomenc gate hard-asserts. |
| 4699 | thread_local! { |
| 4700 | static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> = |
| 4701 | const { std::cell::Cell::new(0) }; |
| 4702 | } |
| 4703 | |
| 4704 | /// Current value of [`RECT_LEAF_COEFF_HITS`]. |
| 4705 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4706 | pub(crate) fn rect_leaf_coeff_hits() -> usize { |
| 4707 | RECT_LEAF_COEFF_HITS.with(|c| c.get()) |
| 4708 | } |
| 4709 | |
| 4710 | // lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the |
| 4711 | // INTER block path ([`decode_intra_rect_in_inter`]), per shape class -- |
| 4712 | // [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16. |
| 4713 | // Every one of them was the named refusal "an intra-coded HORZ/VERT strip |
| 4714 | // needs rectangular intra prediction" before this round. |
| 4715 | thread_local! { |
| 4716 | static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> = |
| 4717 | const { std::cell::Cell::new([0; 3]) }; |
| 4718 | } |
| 4719 | |
| 4720 | /// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class |
| 4721 | /// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16). |
| 4722 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4723 | pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize { |
| 4724 | INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class]) |
| 4725 | } |
| 4726 | |
| 4727 | // lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded |
| 4728 | // (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the |
| 4729 | // un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of |
| 4730 | // [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on. |
| 4731 | // Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT): |
| 4732 | // a single counter cannot tell an axis swap from a working arm |
| 4733 | // (class [[scan-weights-cross-axis]]), so the gate asserts both cells. |
| 4734 | thread_local! { |
| 4735 | static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> = |
| 4736 | const { std::cell::Cell::new([0; 2]) }; |
| 4737 | } |
| 4738 | |
| 4739 | /// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation |
| 4740 | /// (0 = 64x32, 1 = 32x64). |
| 4741 | pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize { |
| 4742 | RECT64_CORNER_TU_HITS.with(|c| c.get()[orient]) |
| 4743 | } |
| 4744 | |
| 4745 | // lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma |
| 4746 | // transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0 |
| 4747 | // is never incremented) -- the gate's proof that the lifted path ran per depth. |
| 4748 | thread_local! { |
| 4749 | static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> = |
| 4750 | const { std::cell::Cell::new([0; 3]) }; |
| 4751 | } |
| 4752 | |
| 4753 | // lane-t900 r21: rect intra strips inside an inter frame that read the |
| 4754 | // screen-content palette syntax (`allow_screen_content_tools` set and the |
| 4755 | // strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket |
| 4756 | // refusal used to guard, so this counter is what keeps its witness gate |
| 4757 | // non-vacuous. |
| 4758 | thread_local! { |
| 4759 | static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4760 | } |
| 4761 | |
| 4762 | /// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`]. |
| 4763 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4764 | pub(crate) fn intra_rect_in_inter_screen_hits() -> usize { |
| 4765 | INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get) |
| 4766 | } |
| 4767 | |
| 4768 | /// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode. |
| 4769 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4770 | pub(crate) fn reset_intra_rect_in_inter_screen_hits() { |
| 4771 | INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0)); |
| 4772 | } |
| 4773 | |
| 4774 | /// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth. |
| 4775 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4776 | pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] { |
| 4777 | INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get) |
| 4778 | } |
| 4779 | |
| 4780 | // lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid |
| 4781 | // approximation would have resolved off a DIFFERENT CDF row than the real |
| 4782 | // `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY |
| 4783 | // frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block" |
| 4784 | // tally is green on the old code too (class gate-blind-to-feature). |
| 4785 | thread_local! { |
| 4786 | static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> = |
| 4787 | const { std::cell::Cell::new(0) }; |
| 4788 | } |
| 4789 | |
| 4790 | /// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`]. |
| 4791 | #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live |
| 4792 | pub(crate) fn txctx_deblock_divergence_hits() -> usize { |
| 4793 | TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get) |
| 4794 | } |
| 4795 | |
| 4796 | // lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER |
| 4797 | // block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every |
| 4798 | // one of them was the named refusal "an intra-coded 1:4 (or other non-2:1) |
| 4799 | // rect strip on the inter block path" before this round. |
| 4800 | thread_local! { |
| 4801 | static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> = |
| 4802 | const { std::cell::Cell::new([0; 4]) }; |
| 4803 | } |
| 4804 | |
| 4805 | /// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape |
| 4806 | /// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32). |
| 4807 | pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize { |
| 4808 | INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape]) |
| 4809 | } |
| 4810 | |
| 4811 | // lane-intra14 r1: set while an INTRA block of an INTER frame is decoded |
| 4812 | // through one of the key-frame rect readers ([`decode_block_rect4`], |
| 4813 | // [`decode_block_rect64`]). `Some((size_group, skip))` tells |
| 4814 | // [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were |
| 4815 | // already read by [`decode_inter_block`] and (b) the luma mode comes off |
| 4816 | // `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`, |
| 4817 | // decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair. |
| 4818 | |
| 4819 | // lane-rectx r5: how many times a NON-strip `kf_y_mode` reader |
| 4820 | // ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an |
| 4821 | // above/left mode from the mi-exact map that DIFFERS from its coarse 16x16 |
| 4822 | // slot -- i.e. how often the r5 defect would have picked the wrong CDF row. |
| 4823 | thread_local! { |
| 4824 | static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> = |
| 4825 | const { std::cell::Cell::new(0) }; |
| 4826 | } |
| 4827 | |
| 4828 | /// Current value of [`MODE_MI_OVERRIDE_HITS`]. |
| 4829 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4830 | pub(crate) fn mode_mi_override_hits() -> usize { |
| 4831 | MODE_MI_OVERRIDE_HITS.with(|c| c.get()) |
| 4832 | } |
| 4833 | |
| 4834 | // lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a |
| 4835 | // TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a |
| 4836 | // mode from the previous tile, where libaom's `up_available`/`left_available` |
| 4837 | // make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams: |
| 4838 | // `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode` |
| 4839 | // per superblock row in `start_row`, so the luma fallback cannot leak the way |
| 4840 | // lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is |
| 4841 | // the invariant that makes the coarse fallback safe. |
| 4842 | thread_local! { |
| 4843 | static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> = |
| 4844 | const { std::cell::Cell::new(0) }; |
| 4845 | } |
| 4846 | |
| 4847 | /// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`]. |
| 4848 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4849 | pub(crate) fn mode_tile_edge_coarse_leaks() -> usize { |
| 4850 | MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get()) |
| 4851 | } |
| 4852 | |
| 4853 | // lane-cfl r1: how many times a chroma intra-edge filter-type read |
| 4854 | // (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the |
| 4855 | // mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the |
| 4856 | // r1 defect would have filtered a chroma edge with the wrong strength. |
| 4857 | thread_local! { |
| 4858 | static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> = |
| 4859 | const { std::cell::Cell::new(0) }; |
| 4860 | } |
| 4861 | |
| 4862 | /// Current value of [`UV_MODE_MI_OVERRIDE_HITS`]. |
| 4863 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4864 | pub(crate) fn uv_mode_mi_override_hits() -> usize { |
| 4865 | UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get()) |
| 4866 | } |
| 4867 | |
| 4868 | // lane-t900 r12: how many chroma edge-filter-type reads took their above/left |
| 4869 | // `uv_mode` from the mi GRID where the one-slot-per-column map would have |
| 4870 | // answered differently -- the sub-8x8 pair case where the pair's own first |
| 4871 | // half had already overwritten the column slot the chroma-ref half reads. |
| 4872 | thread_local! { |
| 4873 | static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> = |
| 4874 | const { std::cell::Cell::new(0) }; |
| 4875 | } |
| 4876 | |
| 4877 | /// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`]. |
| 4878 | pub fn uv_mode_grid_override_hits() -> usize { |
| 4879 | UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get()) |
| 4880 | } |
| 4881 | |
| 4882 | // lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the |
| 4883 | // INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode |
| 4884 | // from an earlier block in that pixel row/column while the mi-exact map -- |
| 4885 | // which an inter block only started writing this round -- correctly says the |
| 4886 | // neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is |
| 4887 | // an INTER mode, and its `uv_mode` "is not set for inter blocks"). |
| 4888 | thread_local! { |
| 4889 | static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> = |
| 4890 | const { std::cell::Cell::new(0) }; |
| 4891 | } |
| 4892 | |
| 4893 | /// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`]. |
| 4894 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4895 | pub(crate) fn inter_neighbour_not_smooth_hits() -> usize { |
| 4896 | INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get()) |
| 4897 | } |
| 4898 | |
| 4899 | // lane-mtfix r1: how many times a chroma intra-edge filter-type read was |
| 4900 | // suppressed at a TILE edge that is not a frame edge -- the above/left |
| 4901 | // `uv_mode` neighbour of a block on a tile's first mi row/column lives in |
| 4902 | // another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The |
| 4903 | // coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per |
| 4904 | // tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile |
| 4905 | // above would decide this tile's chroma edge filter strength. |
| 4906 | thread_local! { |
| 4907 | static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> = |
| 4908 | const { std::cell::Cell::new(0) }; |
| 4909 | } |
| 4910 | |
| 4911 | /// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`]. |
| 4912 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4913 | pub(crate) fn uv_tile_edge_suppressed_hits() -> usize { |
| 4914 | UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get()) |
| 4915 | } |
| 4916 | |
| 4917 | // lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs` |
| 4918 | // read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block |
| 4919 | // shapes the r1 chroma defect showed up on. |
| 4920 | thread_local! { |
| 4921 | static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4922 | static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 4923 | } |
| 4924 | |
| 4925 | /// Current value of [`CFL_BLOCK_HITS`]. |
| 4926 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4927 | pub(crate) fn cfl_block_hits() -> usize { |
| 4928 | CFL_BLOCK_HITS.with(|c| c.get()) |
| 4929 | } |
| 4930 | |
| 4931 | /// Current value of [`UV_ANGLE_DELTA_HITS`]. |
| 4932 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4933 | pub(crate) fn uv_angle_delta_hits() -> usize { |
| 4934 | UV_ANGLE_DELTA_HITS.with(|c| c.get()) |
| 4935 | } |
| 4936 | |
| 4937 | // lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT` |
| 4938 | // blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the |
| 4939 | // gate's proof this round's arms actually reached a real block, not just |
| 4940 | // that `partition_w64` read one of those two symbol values. |
| 4941 | thread_local! { |
| 4942 | static SB_RECT_HITS: std::cell::Cell<usize> = |
| 4943 | const { std::cell::Cell::new(0) }; |
| 4944 | } |
| 4945 | |
| 4946 | // Current value of [`SB_RECT_HITS`]. |
| 4947 | // lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a |
| 4948 | // 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as |
| 4949 | // SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the |
| 4950 | // non-SPLIT edge arm actually decoded (before this round the bit was read and |
| 4951 | // thrown away, so that arm was unreachable). |
| 4952 | thread_local! { |
| 4953 | static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; |
| 4954 | } |
| 4955 | |
| 4956 | /// Current value of [`EDGE_PART_HITS`]. |
| 4957 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4958 | pub(crate) fn edge_part_hits() -> [usize; 4] { |
| 4959 | EDGE_PART_HITS.with(|c| c.get()) |
| 4960 | } |
| 4961 | |
| 4962 | /// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time). |
| 4963 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4964 | pub(crate) fn reset_edge_part_hits() { |
| 4965 | EDGE_PART_HITS.with(|c| c.set([0; 4])); |
| 4966 | } |
| 4967 | |
| 4968 | fn bump_edge_part(slot: usize) { |
| 4969 | hit_do! { |
| 4970 | EDGE_PART_HITS.with(|c| { |
| 4971 | let mut h = c.get(); |
| 4972 | h[slot] += 1; |
| 4973 | c.set(h); |
| 4974 | }); |
| 4975 | } |
| 4976 | } |
| 4977 | |
| 4978 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4979 | pub(crate) fn sb_rect_hits() -> usize { |
| 4980 | SB_RECT_HITS.with(|c| c.get()) |
| 4981 | } |
| 4982 | |
| 4983 | // lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the |
| 4984 | // gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level |
| 4985 | // PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half |
| 4986 | // is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile |
| 4987 | // paths (intra and inter) feed the same counter. |
| 4988 | // |
| 4989 | // lane-golomb r3: slots 4..7 are the same four facts one level up, at the |
| 4990 | // SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as |
| 4991 | // HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with |
| 4992 | // `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a |
| 4993 | // bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band, |
| 4994 | // every SB of the last row), so the 32-level slots stay 0 on that content and |
| 4995 | // only these prove the arm fired. |
| 4996 | thread_local! { |
| 4997 | static EDGE32_HITS: std::cell::Cell<[usize; 8]> = |
| 4998 | const { std::cell::Cell::new([0; 8]) }; |
| 4999 | } |
| 5000 | |
| 5001 | /// Current value of [`EDGE32_HITS`]. |
| 5002 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5003 | pub(crate) fn edge32_hits() -> [usize; 8] { |
| 5004 | EDGE32_HITS.with(|c| c.get()) |
| 5005 | } |
| 5006 | |
| 5007 | /// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge |
| 5008 | /// reads are `if`-conditions, so the counter has to ride the expression. |
| 5009 | fn bump_edge32_bit(base: usize, bit: usize) -> usize { |
| 5010 | bump_edge32(base + bit.min(1)); |
| 5011 | bit |
| 5012 | } |
| 5013 | |
| 5014 | fn bump_edge32(slot: usize) { |
| 5015 | hit_do! { |
| 5016 | EDGE32_HITS.with(|c| { |
| 5017 | let mut h = c.get(); |
| 5018 | h[slot] += 1; |
| 5019 | c.set(h) |
| 5020 | }); |
| 5021 | } |
| 5022 | } |
| 5023 | |
| 5024 | // lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/ |
| 5025 | // `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64 |
| 5026 | // strip) fired. Real aomenc picks these at 64 even with |
| 5027 | // `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is |
| 5028 | // the counter the gate hard-asserts. |
| 5029 | thread_local! { |
| 5030 | static SB_AB_HITS: std::cell::Cell<[usize; 4]> = |
| 5031 | const { std::cell::Cell::new([0; 4]) }; |
| 5032 | } |
| 5033 | |
| 5034 | /// Current value of [`SB_AB_HITS`], summed over the four arms. |
| 5035 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5036 | pub(crate) fn sb_ab_hits() -> usize { |
| 5037 | SB_AB_HITS.with(|c| c.get().iter().sum()) |
| 5038 | } |
| 5039 | |
| 5040 | /// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, |
| 5041 | /// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a |
| 5042 | /// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as |
| 5043 | /// proof of all four. |
| 5044 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5045 | pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] { |
| 5046 | SB_AB_HITS.with(std::cell::Cell::get) |
| 5047 | } |
| 5048 | |
| 5049 | // lane-tx64x16: the two 1:4 superblock arms, counted per orientation -- |
| 5050 | // `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64 |
| 5051 | // strips). Two counters, not one, because a gate that only proved "some 1:4 |
| 5052 | // strip fired" would pass on a stream that never coded the other axis, and |
| 5053 | // every scan/context table this round added comes in a transposed pair. |
| 5054 | thread_local! { |
| 5055 | static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5056 | static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5057 | } |
| 5058 | |
| 5059 | /// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded). |
| 5060 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5061 | pub(crate) fn sb_rect4_horz_hits() -> usize { |
| 5062 | SB_RECT4_HORZ_HITS.with(|c| c.get()) |
| 5063 | } |
| 5064 | |
| 5065 | /// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded). |
| 5066 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5067 | pub(crate) fn sb_rect4_vert_hits() -> usize { |
| 5068 | SB_RECT4_VERT_HITS.with(|c| c.get()) |
| 5069 | } |
| 5070 | |
| 5071 | // lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation -- |
| 5072 | // `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32 |
| 5073 | // strips), the arms the ReelB mid-film extract stops at. |
| 5074 | thread_local! { |
| 5075 | static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5076 | static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5077 | /// lane-inter4 r1: the INTER-frame twins of the two counters above -- |
| 5078 | /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` / |
| 5079 | /// `PARTITION_VERT_4`. |
| 5080 | static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5081 | static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5082 | /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT` |
| 5083 | /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64). |
| 5084 | static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5085 | static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5086 | static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5087 | static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5088 | } |
| 5089 | |
| 5090 | // How many 32x32-level 1:4 strips actually read coefficients (non-skip): |
| 5091 | // a gate that only counted strips would pass on an all-skip stream, which |
| 5092 | // exercises none of the new scan/context tables. |
| 5093 | thread_local! { |
| 5094 | static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5095 | } |
| 5096 | |
| 5097 | // lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the |
| 5098 | // per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT |
| 5099 | // unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in |
| 5100 | // every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS` |
| 5101 | // counts the same for a 16x8/8x16 strip below 16x16. |
| 5102 | thread_local! { |
| 5103 | static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5104 | static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5105 | static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5106 | } |
| 5107 | |
| 5108 | /// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`. |
| 5109 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5110 | pub(crate) fn rect4_split_depth_hits() -> (usize, usize) { |
| 5111 | ( |
| 5112 | RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()), |
| 5113 | RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()), |
| 5114 | ) |
| 5115 | } |
| 5116 | |
| 5117 | /// Current value of `SUB16_SPLIT_HITS`. |
| 5118 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5119 | pub(crate) fn sub16_split_hits() -> usize { |
| 5120 | SUB16_SPLIT_HITS.with(|c| c.get()) |
| 5121 | } |
| 5122 | |
| 5123 | // lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose |
| 5124 | // luma transform is SPLIT and which therefore leave through that fn's early |
| 5125 | // return -- the arm that published no `TXFM_CONTEXT` band until this round. |
| 5126 | thread_local! { |
| 5127 | static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5128 | } |
| 5129 | |
| 5130 | /// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`. |
| 5131 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5132 | pub(crate) fn rect64_split_txfm_publish_hits() -> usize { |
| 5133 | RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get()) |
| 5134 | } |
| 5135 | |
| 5136 | /// Current value of `RECT4_COEFF_HITS`. |
| 5137 | pub(crate) fn rect4_coeff_hits() -> usize { |
| 5138 | RECT4_COEFF_HITS.with(|c| c.get()) |
| 5139 | } |
| 5140 | |
| 5141 | // lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN |
| 5142 | // INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, |
| 5143 | // `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is |
| 5144 | // two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate |
| 5145 | // asserts the arms it proves separately so a run whose RD only picked one |
| 5146 | // cannot pass as proof of the others. |
| 5147 | thread_local! { |
| 5148 | static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; |
| 5149 | } |
| 5150 | |
| 5151 | /// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an |
| 5152 | /// inter frame). |
| 5153 | pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] { |
| 5154 | SB_AB_INTER_HITS.with(std::cell::Cell::get) |
| 5155 | } |
| 5156 | |
| 5157 | // lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER |
| 5158 | // frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` |
| 5159 | // order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8 |
| 5160 | // inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip |
| 5161 | // (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every |
| 5162 | // arm separately so a run whose RD only picked one cannot pass as proof of |
| 5163 | // four. |
| 5164 | thread_local! { |
| 5165 | static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; |
| 5166 | } |
| 5167 | |
| 5168 | /// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an |
| 5169 | /// inter frame). |
| 5170 | pub fn ab16_inter_hits_by_arm() -> [usize; 4] { |
| 5171 | AB16_INTER_HITS.with(std::cell::Cell::get) |
| 5172 | } |
| 5173 | |
| 5174 | // lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4 |
| 5175 | // (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS` |
| 5176 | // counts the odd strips that close a 4:2:0 chroma pair |
| 5177 | // (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row), |
| 5178 | // `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from |
| 5179 | // the PREVIOUS strip's own mv/ref/filters -- libaom |
| 5180 | // `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached |
| 5181 | // through `is_sub8x8_inter` (same file, :54). |
| 5182 | thread_local! { |
| 5183 | static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5184 | static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5185 | static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5186 | static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5187 | } |
| 5188 | |
| 5189 | // lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition -- |
| 5190 | // [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the |
| 5191 | // pair's single 8x4 (4x8) chroma unit for BOTH strips. |
| 5192 | thread_local! { |
| 5193 | static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> = |
| 5194 | const { std::cell::Cell::new([0; 3]) }; |
| 5195 | } |
| 5196 | |
| 5197 | /// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded |
| 5198 | /// inside an INTER 16x16-level 1:4 partition (lane-intra16x4). |
| 5199 | pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) { |
| 5200 | let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get); |
| 5201 | (v[0], v[1], v[2]) |
| 5202 | } |
| 5203 | |
| 5204 | /// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16 |
| 5205 | /// strips, chroma pairs closed, chroma pairs built from two different |
| 5206 | /// strips' motion vectors)`. |
| 5207 | pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) { |
| 5208 | ( |
| 5209 | INTER16_HORZ4_HITS.with(std::cell::Cell::get), |
| 5210 | INTER16_VERT4_HITS.with(std::cell::Cell::get), |
| 5211 | INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get), |
| 5212 | INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get), |
| 5213 | ) |
| 5214 | } |
| 5215 | |
| 5216 | /// One 16x4 / 4x16 inter strip's chroma situation, handed to |
| 5217 | /// [`decode_inter_block`] out of band (the same one-shot thread-local idiom |
| 5218 | /// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites |
| 5219 | /// that all mean "an ordinary block, chroma of its own". |
| 5220 | #[derive(Clone, Copy)] |
| 5221 | pub(crate) struct InterStripChroma { |
| 5222 | /// `is_chroma_reference` for this strip: false on strips 0 and 2, which |
| 5223 | /// read and reconstruct NO chroma at all. |
| 5224 | has_chroma: bool, |
| 5225 | /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`. |
| 5226 | horz: bool, |
| 5227 | /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s |
| 5228 | /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`, |
| 5229 | /// i.e. the origin of the 8x4 (4x8) chroma transform. |
| 5230 | pair_mi: (usize, usize), |
| 5231 | /// The previous (even) strip's single-reference MC parameters, `None` |
| 5232 | /// when it was intra or compound -- `is_sub8x8_inter` then returns false |
| 5233 | /// and the whole chroma block is predicted from THIS strip's mv. |
| 5234 | prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>, |
| 5235 | } |
| 5236 | |
| 5237 | /// The single-reference MC parameters of the inter block that decoded |
| 5238 | /// last -- read by the next 1:4 strip to build its pair's chroma. |
| 5239 | |
| 5240 | fn bump_ab16_inter(arm: usize) { |
| 5241 | hit_do! { |
| 5242 | AB16_INTER_HITS.with(|c| { |
| 5243 | let mut v = c.get(); |
| 5244 | v[arm] += 1; |
| 5245 | c.set(v); |
| 5246 | }); |
| 5247 | } |
| 5248 | } |
| 5249 | |
| 5250 | // lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or |
| 5251 | // 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that |
| 5252 | // close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual. |
| 5253 | thread_local! { |
| 5254 | static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5255 | static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5256 | static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5257 | static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5258 | static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5259 | /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's |
| 5260 | /// base mi differs from what the strip's own (odd) mi would have said -- |
| 5261 | /// the shape that made 4 chroma samples of the ReelB `-ss 1200` |
| 5262 | /// key frame miss by 1. Zero here means a gate never exercised the fix. |
| 5263 | static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5264 | /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s. |
| 5265 | static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5266 | /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip. |
| 5267 | static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5268 | /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND |
| 5269 | /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely. |
| 5270 | static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5271 | /// lane-av1-loss64: chroma transform units the frame-edge clip skipped |
| 5272 | /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in |
| 5273 | /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless |
| 5274 | /// block overhanging the frame does NOT code. |
| 5275 | static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5276 | /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma |
| 5277 | /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`, |
| 5278 | /// decodeframe.c:1262) instead of leaking the previous occupant's. |
| 5279 | static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5280 | } |
| 5281 | |
| 5282 | /// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape |
| 5283 | /// that reconstructed as flat DC before lane-kf1200 r2). |
| 5284 | pub fn skip_cfl_hits() -> usize { |
| 5285 | SKIP_CFL_HITS.with(|c| c.get()) |
| 5286 | } |
| 5287 | |
| 5288 | /// How many chroma transform units the frame-edge clip skipped in |
| 5289 | /// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a |
| 5290 | /// stream whose lossless blocks never overhang the frame -- a gate asserting |
| 5291 | /// the clip fired must see this nonzero. |
| 5292 | pub fn chroma_edge_tu_clip_hits() -> usize { |
| 5293 | CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get()) |
| 5294 | } |
| 5295 | |
| 5296 | /// How many skipped lossless intrabc rect strips had their luma entropy |
| 5297 | /// bands zeroed per unit (lane-av1-loss64). |
| 5298 | pub fn skip_lossless_band_reset_hits() -> usize { |
| 5299 | SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get()) |
| 5300 | } |
| 5301 | |
| 5302 | /// Gate-side reset for the two lane-av1-loss64 counters above. |
| 5303 | pub fn reset_loss64_hits() { |
| 5304 | CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0)); |
| 5305 | SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0)); |
| 5306 | } |
| 5307 | |
| 5308 | /// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type` |
| 5309 | /// from the pair's base mi than the strip's own mi would have given. |
| 5310 | pub fn rect4_16_uv_pair_filt_hits() -> usize { |
| 5311 | RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get()) |
| 5312 | } |
| 5313 | |
| 5314 | /// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane. |
| 5315 | pub fn rect4_16_lossless_chroma_hits() -> usize { |
| 5316 | RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get()) |
| 5317 | } |
| 5318 | |
| 5319 | /// How many 16x4/4x16 strips reconstructed as intra block copy. |
| 5320 | pub fn rect4_16_intrabc_hits() -> usize { |
| 5321 | RECT4_16_INTRABC_HITS.with(|c| c.get()) |
| 5322 | } |
| 5323 | |
| 5324 | /// Zero the lane-av1-rect14 pair counters so a gate measures one stream. |
| 5325 | pub fn reset_rect4_16_pair_hits() { |
| 5326 | RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0)); |
| 5327 | RECT4_16_INTRABC_HITS.with(|c| c.set(0)); |
| 5328 | } |
| 5329 | |
| 5330 | // lane-reelckf r1: the two chroma defects ReelC's key frames exposed -- |
| 5331 | // CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED` |
| 5332 | // (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and |
| 5333 | // RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose |
| 5334 | // intra-edge filter type must come from the chroma-reference position). |
| 5335 | thread_local! { |
| 5336 | static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5337 | static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5338 | } |
| 5339 | |
| 5340 | /// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf. |
| 5341 | pub fn reelc_chroma_counters() -> (usize, usize) { |
| 5342 | ( |
| 5343 | CHROMA_SKIP_CFL_HITS.with(|c| c.get()), |
| 5344 | RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()), |
| 5345 | ) |
| 5346 | } |
| 5347 | |
| 5348 | /// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16 |
| 5349 | /// strips, chroma-reference strips, strips with a coded residual, strips |
| 5350 | /// whose luma transform is split)`. |
| 5351 | pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) { |
| 5352 | ( |
| 5353 | RECT4_16_HORZ_HITS.with(|c| c.get()), |
| 5354 | RECT4_16_VERT_HITS.with(|c| c.get()), |
| 5355 | RECT4_16_CHROMA_HITS.with(|c| c.get()), |
| 5356 | RECT4_16_COEFF_HITS.with(|c| c.get()), |
| 5357 | RECT4_16_SPLIT_HITS.with(|c| c.get()), |
| 5358 | ) |
| 5359 | } |
| 5360 | |
| 5361 | /// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded). |
| 5362 | pub(crate) fn rect4_32_horz_hits() -> usize { |
| 5363 | RECT4_32_HORZ_HITS.with(|c| c.get()) |
| 5364 | } |
| 5365 | |
| 5366 | /// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded). |
| 5367 | pub(crate) fn rect4_32_vert_hits() -> usize { |
| 5368 | RECT4_32_VERT_HITS.with(|c| c.get()) |
| 5369 | } |
| 5370 | |
| 5371 | /// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded). |
| 5372 | pub(crate) fn rect4_32_horz_inter_hits() -> usize { |
| 5373 | RECT4_32_HORZ_INTER_HITS.with(|c| c.get()) |
| 5374 | } |
| 5375 | |
| 5376 | /// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded). |
| 5377 | pub(crate) fn rect4_32_vert_inter_hits() -> usize { |
| 5378 | RECT4_32_VERT_INTER_HITS.with(|c| c.get()) |
| 5379 | } |
| 5380 | |
| 5381 | /// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded). |
| 5382 | pub(crate) fn inter_sb_horz_hits() -> usize { |
| 5383 | INTER_SB_HORZ_HITS.with(|c| c.get()) |
| 5384 | } |
| 5385 | |
| 5386 | /// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded). |
| 5387 | pub(crate) fn inter_sb_vert_hits() -> usize { |
| 5388 | INTER_SB_VERT_HITS.with(|c| c.get()) |
| 5389 | } |
| 5390 | |
| 5391 | /// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded). |
| 5392 | pub(crate) fn inter_sb_horz4_hits() -> usize { |
| 5393 | INTER_SB_HORZ4_HITS.with(|c| c.get()) |
| 5394 | } |
| 5395 | |
| 5396 | /// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded). |
| 5397 | pub(crate) fn inter_sb_vert4_hits() -> usize { |
| 5398 | INTER_SB_VERT4_HITS.with(|c| c.get()) |
| 5399 | } |
| 5400 | |
| 5401 | // lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane |
| 5402 | // dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the |
| 5403 | // running-vs-stale-snapshot bug this round fixed is exercised by a gate, not |
| 5404 | // just inert-compiled. Zero forever on a passing gate means that gate's |
| 5405 | // stream never carries `delta_q_present=1` through a rect64 block. |
| 5406 | thread_local! { |
| 5407 | static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> = |
| 5408 | const { std::cell::Cell::new(0) }; |
| 5409 | } |
| 5410 | |
| 5411 | /// Current value of [`RECT64_QIDX_DRIFT_HITS`]. |
| 5412 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5413 | pub(crate) fn rect64_qidx_drift_hits() -> usize { |
| 5414 | RECT64_QIDX_DRIFT_HITS.with(|c| c.get()) |
| 5415 | } |
| 5416 | |
| 5417 | // lane-partab r1: how many 32x32 quadrants decoded an AB partition |
| 5418 | // (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one |
| 5419 | // 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the |
| 5420 | // free-partition gate's proof this round's arms actually fired. |
| 5421 | thread_local! { |
| 5422 | static PARTAB_HITS: std::cell::Cell<usize> = |
| 5423 | const { std::cell::Cell::new(0) }; |
| 5424 | } |
| 5425 | |
| 5426 | /// Current value of [`PARTAB_HITS`]. |
| 5427 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5428 | pub(crate) fn partab_hits() -> usize { |
| 5429 | PARTAB_HITS.with(|c| c.get()) |
| 5430 | } |
| 5431 | |
| 5432 | // lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm, |
| 5433 | // one counter per arm rather than one shared total -- the gate hard-asserts |
| 5434 | // each of these individually nonzero so a recipe that only ever fires |
| 5435 | // HORZ_A can't silently stand in for the whole set. |
| 5436 | thread_local! { |
| 5437 | static INTRA_HORZ_A_HITS: std::cell::Cell<usize> = |
| 5438 | const { std::cell::Cell::new(0) }; |
| 5439 | static INTRA_HORZ_B_HITS: std::cell::Cell<usize> = |
| 5440 | const { std::cell::Cell::new(0) }; |
| 5441 | static INTRA_VERT_A_HITS: std::cell::Cell<usize> = |
| 5442 | const { std::cell::Cell::new(0) }; |
| 5443 | static INTRA_VERT_B_HITS: std::cell::Cell<usize> = |
| 5444 | const { std::cell::Cell::new(0) }; |
| 5445 | } |
| 5446 | |
| 5447 | /// Current value of [`INTRA_HORZ_A_HITS`]. |
| 5448 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5449 | pub(crate) fn intra_horz_a_hits() -> usize { |
| 5450 | INTRA_HORZ_A_HITS.with(|c| c.get()) |
| 5451 | } |
| 5452 | /// Current value of [`INTRA_HORZ_B_HITS`]. |
| 5453 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5454 | pub(crate) fn intra_horz_b_hits() -> usize { |
| 5455 | INTRA_HORZ_B_HITS.with(|c| c.get()) |
| 5456 | } |
| 5457 | /// Current value of [`INTRA_VERT_A_HITS`]. |
| 5458 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5459 | pub(crate) fn intra_vert_a_hits() -> usize { |
| 5460 | INTRA_VERT_A_HITS.with(|c| c.get()) |
| 5461 | } |
| 5462 | /// Current value of [`INTRA_VERT_B_HITS`]. |
| 5463 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5464 | pub(crate) fn intra_vert_b_hits() -> usize { |
| 5465 | INTRA_VERT_B_HITS.with(|c| c.get()) |
| 5466 | } |
| 5467 | |
| 5468 | // How many [`read_inter_compound_mode`] reads actually happened |
| 5469 | // (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own |
| 5470 | // `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound |
| 5471 | // mvstack build), not just that `comp_mode` fired. Still refused right |
| 5472 | // after (no MV assignment or MC wired), so this only counts attempted |
| 5473 | // reads. |
| 5474 | thread_local! { |
| 5475 | static COMPOUND_MODE_HITS: std::cell::Cell<usize> = |
| 5476 | const { std::cell::Cell::new(0) }; |
| 5477 | } |
| 5478 | |
| 5479 | /// Current value of [`COMPOUND_MODE_HITS`]. |
| 5480 | #[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds |
| 5481 | pub(crate) fn compound_mode_hits() -> usize { |
| 5482 | COMPOUND_MODE_HITS.with(|c| c.get()) |
| 5483 | } |
| 5484 | |
| 5485 | /// How many query blocks folded in at least one temporal MV candidate |
| 5486 | /// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the |
| 5487 | /// temporal-MV gate's own firing counter (lane-av1tmvp). |
| 5488 | /// |
| 5489 | /// # HANDOFF (lane-av1tmvp): not yet wired to a live stream |
| 5490 | /// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in |
| 5491 | /// this file (`decode_inter_block`) still passes `tpl: None` -- this |
| 5492 | /// counter compiles and the projection math it counts is unit-tested |
| 5493 | /// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`] |
| 5494 | /// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls |
| 5495 | /// [`crate::motion_field::setup_motion_field`] yet, so this will read `0` |
| 5496 | /// against any real stream today. See the module doc on |
| 5497 | /// `crate::motion_field` and this crate's ledger for the remaining wiring. |
| 5498 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5499 | pub(crate) fn tmv_hits() -> usize { |
| 5500 | crate::mvstack::tmv_hits() |
| 5501 | } |
| 5502 | |
| 5503 | /// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions |
| 5504 | /// produced on this thread, the 10-bit inter gate's firing proof. |
| 5505 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5506 | pub(crate) fn inter_pred_hits() -> usize { |
| 5507 | crate::mc::inter_pred_hits() |
| 5508 | } |
| 5509 | |
| 5510 | /// Everything [`decode_inter_block`] needs to fold temporal MV candidates |
| 5511 | /// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]: |
| 5512 | /// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s |
| 5513 | /// output, built by the caller when `header.use_ref_frame_mvs` is set) plus |
| 5514 | /// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`] |
| 5515 | /// needs to turn a query block's own resolved `ref_frame` into |
| 5516 | /// `TplArgs::cur_offset_0` (spec 7.9.3). |
| 5517 | pub(crate) struct TplFrameArgs<'a> { |
| 5518 | pub field: &'a crate::motion_field::TplField, |
| 5519 | pub order_hint_bits: u32, |
| 5520 | pub order_hint: u32, |
| 5521 | /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in |
| 5522 | /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this |
| 5523 | /// frame's own `ref_frame_idx` names for each single reference. |
| 5524 | pub ref_order_hints: [u32; 7], |
| 5525 | } |
| 5526 | |
| 5527 | /// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`, |
| 5528 | /// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully |
| 5529 | /// decoded `grid`: every 4x4 unit an inter block covers reads the same |
| 5530 | /// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it |
| 5531 | /// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is |
| 5532 | /// exact — every block this crate ever codes is at least 8x8, so no 8x8 |
| 5533 | /// cell straddles two different blocks' values. |
| 5534 | #[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages |
| 5535 | pub(crate) fn build_motion_field( |
| 5536 | grid: &MiGrid, |
| 5537 | mi_cols: usize, |
| 5538 | mi_rows: usize, |
| 5539 | order_hint: u32, |
| 5540 | order_hint_bits: u32, |
| 5541 | ref_order_hints: [u32; 7], |
| 5542 | fctx: &FrameCtx, |
| 5543 | ) -> crate::motion_field::MotionField { |
| 5544 | let mut field = |
| 5545 | crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false); |
| 5546 | // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference |
| 5547 | // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other |
| 5548 | // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block |
| 5549 | // referencing one stores only its OTHER side's mv. With |
| 5550 | // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and |
| 5551 | // nothing is skipped. |
| 5552 | // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends |
| 5553 | // only on the reference frame, so it is 7 table lookups per frame instead |
| 5554 | // of two per inter unit. |
| 5555 | let other_side: [bool; 8] = std::array::from_fn(|rf| { |
| 5556 | let i = rf.wrapping_sub(LAST_FRAME as usize); |
| 5557 | order_hint_bits != 0 |
| 5558 | && i < 7 |
| 5559 | && (crate::motion_field::get_relative_dist(order_hint_bits, ref_order_hints[i], order_hint) > 0 |
| 5560 | || ref_order_hints[i] == order_hint) |
| 5561 | }); |
| 5562 | // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is |
| 5563 | // capped at 12 bits per component; a longer one is not stored at all. |
| 5564 | const REFMVS_LIMIT: i32 = (1 << 12) - 1; |
| 5565 | let (cols, rows, cells) = field.cells_mut(); |
| 5566 | // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands |
| 5567 | // never touch each other (an 8x8 cell lives in one cell row, and mi row |
| 5568 | // `row` writes cell row `row / 2`). |
| 5569 | let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| { |
| 5570 | for row in (r0 * 2)..(r1 * 2).min(mi_rows) { |
| 5571 | let out = &mut out[(row / 2 - r0) * cols..][..cols]; |
| 5572 | for col in 0..mi_cols { |
| 5573 | let Some(info) = grid.get_frame(row, col) else { |
| 5574 | continue; |
| 5575 | }; |
| 5576 | // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and |
| 5577 | // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`), |
| 5578 | // so an intra block -- or an inter block whose every slot is on the |
| 5579 | // other side / over the limit -- wipes what an earlier block wrote |
| 5580 | // into the same 8x8 cell (only reachable from sub-8x8 leaves, which |
| 5581 | // share a cell). |
| 5582 | if !info.is_inter { |
| 5583 | out[col / 2] = None; |
| 5584 | continue; |
| 5585 | } |
| 5586 | // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST |
| 5587 | // qualifying one wins -- a compound block stores its second |
| 5588 | // reference's mv, never its first (unless the second is on the |
| 5589 | // other side or over the limit). Storing slot 0 unconditionally |
| 5590 | // put the wrong (mv, ref_frame_offset) pair in every compound |
| 5591 | // block's cell, which a later frame's temporal candidate then |
| 5592 | // projected with the wrong reference distance. |
| 5593 | let mut saved: Option<crate::motion_field::SavedMv> = None; |
| 5594 | for (rf, mv) in [ |
| 5595 | (info.ref_frame, Some(mv32(info.mv))), |
| 5596 | (info.ref_frame1.max(0), Some(mv32(info.mv1))), |
| 5597 | ] { |
| 5598 | let (Some(mv), true) = (mv, rf > 0) else { |
| 5599 | continue; |
| 5600 | }; |
| 5601 | if other_side[rf as usize] { |
| 5602 | continue; |
| 5603 | } |
| 5604 | if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT { |
| 5605 | continue; |
| 5606 | } |
| 5607 | saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf }); |
| 5608 | } |
| 5609 | out[col / 2] = saved; |
| 5610 | } |
| 5611 | } |
| 5612 | }; |
| 5613 | // lane-mf: the whole-frame pass split over the filter pool in cell-row |
| 5614 | // bands (same `Shared` corner-cut as the filter stages -- disjointness is |
| 5615 | // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate). |
| 5616 | let bands = crate::par::bands(rows, crate::par::filter_threads()); |
| 5617 | if bands.len() <= 1 { |
| 5618 | fill(0, rows, cells); |
| 5619 | } else { |
| 5620 | let shared = crate::par::Shared::new(cells); |
| 5621 | crate::par::run_bands(&bands, fctx, |r0, r1, _| { |
| 5622 | // SAFETY: cell rows `r0..r1` are this band's alone. |
| 5623 | let cells = unsafe { shared.get() }; |
| 5624 | fill(r0, r1, &mut cells[r0 * cols..r1 * cols]); |
| 5625 | }); |
| 5626 | } |
| 5627 | if crate::envflags::env_flag!("EC_TRACE_TPL") { |
| 5628 | eprintln!("EC_TPL_SAVED oh={order_hint}"); |
| 5629 | for (r, row) in field.occupancy().iter().enumerate() { |
| 5630 | eprintln!("EC_TPL_SAVED r{r} {row}"); |
| 5631 | } |
| 5632 | } |
| 5633 | field |
| 5634 | } |
| 5635 | |
| 5636 | /// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`; |
| 5637 | /// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here). |
| 5638 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5639 | pub(crate) fn ref_hits(ref_frame: i8) -> usize { |
| 5640 | let c = match ref_frame { |
| 5641 | LAST2_FRAME => &LAST2_HITS, |
| 5642 | LAST3_FRAME => &LAST3_HITS, |
| 5643 | GOLDEN_FRAME => &GOLDEN_HITS, |
| 5644 | BWDREF_FRAME => &BWDREF_HITS, |
| 5645 | ALTREF2_FRAME => &ALTREF2_HITS, |
| 5646 | ALTREF_FRAME => &ALTREF_HITS, |
| 5647 | other => panic!("ref_hits: no per-reference counter for ref_frame {other}"), |
| 5648 | }; |
| 5649 | c.with(|v| v.get()) |
| 5650 | } |
| 5651 | |
| 5652 | /// The sequence header's `enable_intra_edge_filter`, set once per |
| 5653 | /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s |
| 5654 | /// own read of it, kept off the call stack (see that function's own doc |
| 5655 | /// comment for why) rather than threaded through every `read_plane`/ |
| 5656 | /// `decode_block`/`decode_leaf8` call between here and there. |
| 5657 | |
| 5658 | /// Set [`ENABLE_EDGE_FILTER`] for this thread. |
| 5659 | /// |
| 5660 | /// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile` |
| 5661 | /// never did -- so an inter frame's intra blocks read whatever value the last |
| 5662 | /// key frame decoded ON THIS THREAD left behind. Inside one stream that is |
| 5663 | /// harmless (its own key frame sets it first), but a caller that decodes an |
| 5664 | /// inter frame directly, or a test harness running several streams on one |
| 5665 | /// thread, inherits a foreign sequence's bit: decode stops being a pure |
| 5666 | /// function of the bitstream. `decode_stream` now calls this once per stream |
| 5667 | /// from the sequence header, which covers every frame including inter ones. |
| 5668 | pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) { |
| 5669 | fctx.enable_edge_filter.with(|f| f.set(value)); |
| 5670 | } |
| 5671 | |
| 5672 | /// Current value of [`ANGLE_DELTA_HITS`]. |
| 5673 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5674 | pub(crate) fn angle_delta_hits() -> usize { |
| 5675 | ANGLE_DELTA_HITS.with(|c| c.get()) |
| 5676 | } |
| 5677 | |
| 5678 | /// Current value of [`TX_CLASS1_HITS`]. |
| 5679 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5680 | pub(crate) fn tx_class1_hits() -> usize { |
| 5681 | TX_CLASS1_HITS.with(|c| c.get()) |
| 5682 | } |
| 5683 | |
| 5684 | // How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent |
| 5685 | // `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion |
| 5686 | // bottom) this thread's decode actually reconstructed -- the same |
| 5687 | // before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream |
| 5688 | // genuinely exercised the sub-8x8 leaf path rather than every attempt |
| 5689 | // coincidentally landing on `PARTITION_NONE`. |
| 5690 | thread_local! { |
| 5691 | static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5692 | /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter |
| 5693 | /// sub-blocks (lane-intersub8). |
| 5694 | static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5695 | /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8 |
| 5696 | /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4), |
| 5697 | /// `[1] = VERT` (two BLOCK_4X8). |
| 5698 | static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; |
| 5699 | /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8 |
| 5700 | /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were |
| 5701 | /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]` |
| 5702 | /// MIXED groups whose chroma reference is INTER while its sibling is |
| 5703 | /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4` |
| 5704 | /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 -- |
| 5705 | /// the second lifted refusal's own witness; `[0]`/`[1]` count those too, |
| 5706 | /// so only this cell separates the split arm from the HORZ/VERT one). |
| 5707 | static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) }; |
| 5708 | } |
| 5709 | |
| 5710 | /// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference, |
| 5711 | /// mixed groups, split 4x4 leaves)`. |
| 5712 | pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) { |
| 5713 | SUB8_INTRA_RECT_HITS.with(|c| { |
| 5714 | let h = c.get(); |
| 5715 | (h[0], h[1], h[2], h[3], h[4]) |
| 5716 | }) |
| 5717 | } |
| 5718 | |
| 5719 | /// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`. |
| 5720 | pub fn sub8_inter_rect_hits() -> (usize, usize) { |
| 5721 | SUB8_INTER_RECT_HITS.with(|c| { |
| 5722 | let h = c.get(); |
| 5723 | (h[0], h[1]) |
| 5724 | }) |
| 5725 | } |
| 5726 | |
| 5727 | // lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all |
| 5728 | // four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38` |
| 5729 | // `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how |
| 5730 | // many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all. |
| 5731 | // (b) was 0 for every stream before this round -- the leaf path never touched |
| 5732 | // the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got |
| 5733 | // filtered where libaom skips it. A gate asserts both are non-zero. |
| 5734 | thread_local! { |
| 5735 | static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5736 | static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5737 | // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent |
| 5738 | // crosses the cropped frame edge -- the only units for which "clamp at |
| 5739 | // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE" |
| 5740 | // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are |
| 5741 | // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame |
| 5742 | // whose width or height is not a multiple of 8 is the only shape that |
| 5743 | // produces one; the straddling-band gate arms assert it grew. |
| 5744 | static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5745 | // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band |
| 5746 | // (see `Neighbours::skip_written`). |
| 5747 | static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5748 | // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8, |
| 5749 | // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip |
| 5750 | // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip -- |
| 5751 | // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an |
| 5752 | // 8-tall strip pair where only one half is skip must still be FILTERED. |
| 5753 | static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5754 | static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5755 | } |
| 5756 | |
| 5757 | /// Current value of `RECT_SKIP_BAND_HITS`. |
| 5758 | pub fn rect_skip_band_hits() -> usize { |
| 5759 | RECT_SKIP_BAND_HITS.with(|c| c.get()) |
| 5760 | } |
| 5761 | |
| 5762 | /// Current value of `CDEF_MIXED_SKIP_UNITS`. |
| 5763 | pub fn cdef_mixed_skip_units() -> usize { |
| 5764 | CDEF_MIXED_SKIP_UNITS.with(|c| c.get()) |
| 5765 | } |
| 5766 | |
| 5767 | /// Current value of `CDEF_SKIPPED_UNITS`. |
| 5768 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5769 | pub(crate) fn cdef_skipped_units() -> usize { |
| 5770 | CDEF_SKIPPED_UNITS.with(|c| c.get()) |
| 5771 | } |
| 5772 | |
| 5773 | /// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded |
| 5774 | /// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1). |
| 5775 | pub fn cdef_unwritten_skip_units() -> usize { |
| 5776 | CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get()) |
| 5777 | } |
| 5778 | |
| 5779 | /// Current value of `INTER8_SKIP_BAND_HITS`. |
| 5780 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5781 | pub(crate) fn inter8_skip_band_hits() -> usize { |
| 5782 | INTER8_SKIP_BAND_HITS.with(|c| c.get()) |
| 5783 | } |
| 5784 | |
| 5785 | /// Current value of `CDEF_STRADDLE_UNITS`. |
| 5786 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5787 | pub(crate) fn cdef_straddle_units() -> usize { |
| 5788 | CDEF_STRADDLE_UNITS.with(|c| c.get()) |
| 5789 | } |
| 5790 | |
| 5791 | /// Current value of [`SUB8_SPLIT_HITS`]. |
| 5792 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5793 | pub(crate) fn sub8_split_hits() -> usize { |
| 5794 | SUB8_SPLIT_HITS.with(|c| c.get()) |
| 5795 | } |
| 5796 | |
| 5797 | /// Current value of [`SUB8_INTER_SPLIT_HITS`]. |
| 5798 | pub fn sub8_inter_split_hits() -> usize { |
| 5799 | SUB8_INTER_SPLIT_HITS.with(|c| c.get()) |
| 5800 | } |
| 5801 | |
| 5802 | // lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a |
| 5803 | // `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that |
| 5804 | // tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`, |
| 5805 | // which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the |
| 5806 | // first sub-block's type is never the one). Reading it off sub-block 0 |
| 5807 | // inverted one 4x4 chroma unit on the wrong basis with the entropy stream |
| 5808 | // perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only |
| 5809 | // see this rule through this counter. |
| 5810 | thread_local! { |
| 5811 | static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5812 | } |
| 5813 | |
| 5814 | /// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`. |
| 5815 | pub fn sub8_chroma_tx_from_ref_hits() -> usize { |
| 5816 | SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get()) |
| 5817 | } |
| 5818 | |
| 5819 | fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) { |
| 5820 | if coeffs && first_sub != chroma_ref { |
| 5821 | hit!(SUB8_CHROMA_TX_FROM_REF_HITS); |
| 5822 | } |
| 5823 | } |
| 5824 | |
| 5825 | // How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ` |
| 5826 | // of an 8x8 block) this thread's decode reconstructed with REAL coefficients |
| 5827 | // -- a skipped leaf exercises the prediction and the mi bookkeeping but never |
| 5828 | // the rect transform, the 32-position `eob_pt` or the rect scan, so the gate |
| 5829 | // asserts on these two rather than a plain leaf count. |
| 5830 | thread_local! { |
| 5831 | static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5832 | static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5833 | /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's |
| 5834 | /// two 4x4 transform units, predicted one after the other. A separate |
| 5835 | /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so |
| 5836 | /// the gate can prove THIS path fired. |
| 5837 | static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5838 | /// 16x8/8x16 intra strips whose prediction actually read past the block's |
| 5839 | /// own width (above-right) or height (below-left) -- the samples |
| 5840 | /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/ |
| 5841 | /// `has_bl_*` table row can corrupt (lane-tx4x8 r3). |
| 5842 | static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5843 | /// Every 16x8/8x16 intra strip predicted, reaching or not -- the |
| 5844 | /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of. |
| 5845 | static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 5846 | } |
| 5847 | |
| 5848 | /// Current value of [`RECT8_SPLIT_TX_HITS`]. |
| 5849 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5850 | pub(crate) fn rect8_split_tx_hits() -> usize { |
| 5851 | RECT8_SPLIT_TX_HITS.with(|c| c.get()) |
| 5852 | } |
| 5853 | |
| 5854 | /// Current value of [`RECT_STRIP_PRED_HITS`]. |
| 5855 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5856 | pub(crate) fn rect_strip_pred_hits() -> usize { |
| 5857 | RECT_STRIP_PRED_HITS.with(|c| c.get()) |
| 5858 | } |
| 5859 | |
| 5860 | /// Current value of [`RECT_STRIP_REACH_HITS`]. |
| 5861 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5862 | pub(crate) fn rect_strip_reach_hits() -> usize { |
| 5863 | RECT_STRIP_REACH_HITS.with(|c| c.get()) |
| 5864 | } |
| 5865 | |
| 5866 | /// Current value of [`TX4X8_CODED_HITS`]. |
| 5867 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5868 | pub(crate) fn tx4x8_coded_hits() -> usize { |
| 5869 | TX4X8_CODED_HITS.with(|c| c.get()) |
| 5870 | } |
| 5871 | |
| 5872 | /// Current value of [`TX8X4_CODED_HITS`]. |
| 5873 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5874 | pub(crate) fn tx8x4_coded_hits() -> usize { |
| 5875 | TX8X4_CODED_HITS.with(|c| c.get()) |
| 5876 | } |
| 5877 | |
| 5878 | // How many CHROMA coefficient blocks read their `eob_pt` from the class-1 |
| 5879 | // (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread. |
| 5880 | // Chroma never codes a `tx_type` symbol -- it inherits the colocated luma |
| 5881 | // type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on |
| 5882 | // an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired |
| 5883 | // (`eob_pt_{16,64,128,256}_chroma_class1`). |
| 5884 | thread_local! { |
| 5885 | static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> = |
| 5886 | const { std::cell::Cell::new(0) }; |
| 5887 | } |
| 5888 | |
| 5889 | /// Current value of [`CHROMA_EOB_CLASS1_HITS`]. |
| 5890 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5891 | pub(crate) fn chroma_eob_class1_hits() -> usize { |
| 5892 | CHROMA_EOB_CLASS1_HITS.with(|c| c.get()) |
| 5893 | } |
| 5894 | |
| 5895 | /// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited |
| 5896 | /// `tx_type` put this block's `eob_pt` on the class-1 row. |
| 5897 | fn note_chroma_class1(plane_idx: usize, tx_type: TxType) { |
| 5898 | if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD { |
| 5899 | hit!(CHROMA_EOB_CLASS1_HITS); |
| 5900 | } |
| 5901 | } |
| 5902 | |
| 5903 | const SUB_MI: u32 = 4; |
| 5904 | const MI: usize = 4; |
| 5905 | const SB: usize = 64; |
| 5906 | /// The `above_side`/`left_side` value a cell with no decoded neighbour holds |
| 5907 | /// (tile start, superblock-row start). |
| 5908 | /// |
| 5909 | /// [`Neighbours::partition_ctx_mi`] reads it as libaom's |
| 5910 | /// `av1_get_partition_plane_context` reads its own zero-initialised |
| 5911 | /// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at |
| 5912 | /// least as wide as this block". lane-sb128 r1: the old sentinel was `SB` |
| 5913 | /// (64), which reads identically at every level up to 64x64 but sets the bit |
| 5914 | /// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition |
| 5915 | /// symbol was read off CDF row 3 where libaom uses row 0 (aomdec |
| 5916 | /// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`). |
| 5917 | const NO_NEIGHBOUR_SIDE: usize = 128; |
| 5918 | const BLOCK: usize = 32; |
| 5919 | const SUB: usize = 16; |
| 5920 | const TX32: usize = 32; |
| 5921 | const TX16: usize = 16; |
| 5922 | const TX8: usize = 8; |
| 5923 | const TX4: usize = 4; |
| 5924 | const DC_PRED: usize = 0; |
| 5925 | /// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that |
| 5926 | /// carries an angle delta — [`crate::tile`]'s own private copy of the same |
| 5927 | /// constant. |
| 5928 | const V_PRED: usize = 1; |
| 5929 | const H_PRED: usize = 2; |
| 5930 | /// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec |
| 5931 | /// `Fimode_To_Intradir`, libaom `blockd.h`). |
| 5932 | const D157_PRED: usize = 6; |
| 5933 | /// The last directional mode, `D67_PRED`. |
| 5934 | const D67_PRED: usize = 8; |
| 5935 | /// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs |
| 5936 | /// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never |
| 5937 | /// codes anything else, so this decoder never reads anything else either. |
| 5938 | const ANGLE_DELTA_ZERO: usize = 3; |
| 5939 | const NUM_BASE_LEVELS: i32 = 2; |
| 5940 | const COEFF_BASE_RANGE: i32 = 12; |
| 5941 | const BR_STEP: i32 = 3; |
| 5942 | const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE; |
| 5943 | |
| 5944 | /// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types |
| 5945 | /// whose probability mass a superblock or block half outside the frame |
| 5946 | /// gathers into its one remaining flag — [`crate::tile`]'s own private copy, |
| 5947 | /// duplicated here (that module is another lane's territory this round) and |
| 5948 | /// kept in step with it by the byte-exact round-trip tests below rather than |
| 5949 | /// by sharing code. |
| 5950 | const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9]; |
| 5951 | const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8]; |
| 5952 | |
| 5953 | fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) { |
| 5954 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 5955 | eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}"); |
| 5956 | } |
| 5957 | } |
| 5958 | |
| 5959 | fn element_prob(cdf: &[u16], element: usize) -> u16 { |
| 5960 | cdf[element] - if element > 0 { cdf[element - 1] } else { 0 } |
| 5961 | } |
| 5962 | |
| 5963 | /// The two-symbol CDF a partial superblock/block's forced-split flag is read |
| 5964 | /// with: the mass of `elements` becomes the probability of the one partition |
| 5965 | /// the frame edge still allows, mirroring [`crate::tile`]'s own `gather` |
| 5966 | /// (the encoder's non-adapting counterpart to this read). |
| 5967 | fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] { |
| 5968 | let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum(); |
| 5969 | [32768 - split, 32768, 0] |
| 5970 | } |
| 5971 | |
| 5972 | fn unsupported(what: impl Into<String>) -> Error { |
| 5973 | Error::unsupported("AV1 tile", what.into()) |
| 5974 | } |
| 5975 | |
| 5976 | /// The coefficient q-context a frame's `base_q_idx` picks its default CDFs |
| 5977 | /// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the |
| 5978 | /// same rule. |
| 5979 | pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize { |
| 5980 | match base_q_idx { |
| 5981 | 0..=20 => 0, |
| 5982 | 21..=60 => 1, |
| 5983 | 61..=120 => 2, |
| 5984 | _ => 3, |
| 5985 | } |
| 5986 | } |
| 5987 | |
| 5988 | /// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk |
| 5989 | /// [`crate::tile`]'s writer generates its scan tables with. |
| 5990 | fn default_scan(side: usize) -> &'static [u16] { |
| 5991 | // One table per transform side (4/8/16/32), built once: this used to be a |
| 5992 | // fresh heap allocation plus the whole anti-diagonal walk on every |
| 5993 | // transform block read. |
| 5994 | static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| { |
| 5995 | [ |
| 5996 | default_scan_gen(4), |
| 5997 | default_scan_gen(8), |
| 5998 | default_scan_gen(16), |
| 5999 | default_scan_gen(32), |
| 6000 | ] |
| 6001 | }); |
| 6002 | assert!( |
| 6003 | matches!(side, 4 | 8 | 16 | 32), |
| 6004 | "no default scan for a {side}-point transform" |
| 6005 | ); |
| 6006 | &SCANS[side.trailing_zeros() as usize - 2] |
| 6007 | } |
| 6008 | |
| 6009 | fn default_scan_gen(side: usize) -> Vec<u16> { |
| 6010 | let mut scan = Vec::with_capacity(side * side); |
| 6011 | for d in 0..(2 * side - 1) { |
| 6012 | let lo = d.saturating_sub(side - 1); |
| 6013 | let hi = d.min(side - 1); |
| 6014 | let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16); |
| 6015 | if d % 2 == 0 { |
| 6016 | scan.extend(diagonal.rev()); |
| 6017 | } else { |
| 6018 | scan.extend(diagonal); |
| 6019 | } |
| 6020 | } |
| 6021 | scan |
| 6022 | } |
| 6023 | |
| 6024 | /// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two |
| 6025 | /// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients |
| 6026 | /// in, instead of the default zigzag. libaom's own tables are keyed by a |
| 6027 | /// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its |
| 6028 | /// physically column-major level buffer, but they decompose to the exact |
| 6029 | /// same (row, col) walk as a flat row-major traversal of *our* row-major |
| 6030 | /// `grid`/`levels` (`pos = row * side + col`) once you read them that way: |
| 6031 | /// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely |
| 6032 | /// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk |
| 6033 | /// transposed (column 0 down every row, then column 1, ...). |
| 6034 | pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> { |
| 6035 | class_scan_table_wh(side, side, class) |
| 6036 | } |
| 6037 | |
| 6038 | /// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against |
| 6039 | /// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/ |
| 6040 | /// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding |
| 6041 | /// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was |
| 6042 | /// transcribed with -- `mrow` is the plain row-major raster in our indexing |
| 6043 | /// and `mcol` its transpose, at rect sizes exactly as at square ones. |
| 6044 | fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> { |
| 6045 | match class { |
| 6046 | TxClass::Vert => (0..(w * h) as u16).collect(), |
| 6047 | TxClass::Horiz => (0..w) |
| 6048 | .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16)) |
| 6049 | .collect(), |
| 6050 | TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"), |
| 6051 | } |
| 6052 | } |
| 6053 | |
| 6054 | fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize { |
| 6055 | match scan_idx { |
| 6056 | 0 => 0, |
| 6057 | i if i <= area / 8 => 1, |
| 6058 | i if i <= area / 4 => 2, |
| 6059 | _ => 3, |
| 6060 | } |
| 6061 | } |
| 6062 | |
| 6063 | /// One cell of [`read_coeffs`]'s level buffer. |
| 6064 | /// |
| 6065 | /// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`, |
| 6066 | /// `txb_common.h`) -- four zero columns to the right of `side` and four zero |
| 6067 | /// rows below it, at a fixed `stride = side + 4` -- so the four-away reads |
| 6068 | /// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real |
| 6069 | /// zero cells instead of needing the `row >= side || col >= side` edge test |
| 6070 | /// this used to run five times per coefficient. Nothing writes a padding |
| 6071 | /// cell, so the values are the same zeros the test returned. |
| 6072 | #[inline] |
| 6073 | fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 { |
| 6074 | grid[row * stride + col] as i32 |
| 6075 | } |
| 6076 | |
| 6077 | /// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom |
| 6078 | /// `txb_common.h`): everything but the two lone-axis-identity types this |
| 6079 | /// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`. |
| 6080 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 6081 | pub(crate) enum TxClass { |
| 6082 | TwoD, |
| 6083 | Horiz, |
| 6084 | Vert, |
| 6085 | } |
| 6086 | |
| 6087 | impl TxClass { |
| 6088 | pub(crate) fn of(tx_type: TxType) -> Self { |
| 6089 | match tx_type { |
| 6090 | // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`) |
| 6091 | // key on axis alone -- FLIPADST is still ADST for this purpose. |
| 6092 | TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert, |
| 6093 | TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz, |
| 6094 | _ => Self::TwoD, |
| 6095 | } |
| 6096 | } |
| 6097 | } |
| 6098 | |
| 6099 | /// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry |
| 6100 | /// table (indexed by the position along the transform's *coded* axis -- |
| 6101 | /// `col` for horiz, `row` for vert) that places their contexts past the 2D |
| 6102 | /// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total |
| 6103 | /// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36. |
| 6104 | pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize { |
| 6105 | match i { |
| 6106 | 0 => 26, |
| 6107 | 1 => 31, |
| 6108 | _ => 36, |
| 6109 | } |
| 6110 | } |
| 6111 | |
| 6112 | fn base_ctx( |
| 6113 | grid: &[u8], |
| 6114 | stride: usize, |
| 6115 | row: usize, |
| 6116 | col: usize, |
| 6117 | class: TxClass, |
| 6118 | rect_shape: Option<(usize, usize)>, |
| 6119 | ) -> usize { |
| 6120 | // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC |
| 6121 | // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`, |
| 6122 | // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC |
| 6123 | // position through the full 1D neighbour sum and offset table. Skipping |
| 6124 | // that for every class desynced the last (DC) coefficient of a |
| 6125 | // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as |
| 6126 | // 0, which then read one extra `BR` symbol at the max and forced a |
| 6127 | // spurious third Golomb call). |
| 6128 | if class == TxClass::TwoD && row == 0 && col == 0 { |
| 6129 | return 0; |
| 6130 | } |
| 6131 | let offsets: [(usize, usize); 5] = match class { |
| 6132 | TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)], |
| 6133 | TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)], |
| 6134 | TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)], |
| 6135 | }; |
| 6136 | let mag: i32 = offsets |
| 6137 | .iter() |
| 6138 | .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3)) |
| 6139 | .sum(); |
| 6140 | let ctx = ((mag + 1) >> 1).min(4) as usize; |
| 6141 | match class { |
| 6142 | // libaom's CDF *set* for a truncated 64-wide/tall corner resolves |
| 6143 | // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this |
| 6144 | // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats` |
| 6145 | // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted |
| 6146 | // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT |
| 6147 | // strip, which own a genuinely different table from the square one |
| 6148 | // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the |
| 6149 | // square table vs the real ctx 13 the rect table gives). |
| 6150 | TxClass::TwoD => { |
| 6151 | // lane-rectsplit r4: apply libaom's GENERATING RULE |
| 6152 | // (`txb_common.h:199-209`) directly instead of indexing the |
| 6153 | // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a |
| 6154 | // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major |
| 6155 | // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the |
| 6156 | // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`), |
| 6157 | // so 32 consecutive entries are one COLUMN: the [`cdf`] |
| 6158 | // transcriptions are `[col][row]` and this read had them as |
| 6159 | // `[row][col]` -- the transpose, i.e. the other shape's rule with |
| 6160 | // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated |
| 6161 | // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain` |
| 6162 | // pins the rule against the tables over their whole 5x5 domain. |
| 6163 | if let Some((w, h)) = rect_shape { |
| 6164 | if crate::envflags::env_flag!("EC_NZOFF_DUMP") { |
| 6165 | eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}"); |
| 6166 | } |
| 6167 | if w < h && row < 2 { |
| 6168 | return ctx + 11; |
| 6169 | } |
| 6170 | if w > h && col < 2 { |
| 6171 | return ctx + 16; |
| 6172 | } |
| 6173 | } |
| 6174 | ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize |
| 6175 | } |
| 6176 | TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)), |
| 6177 | TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)), |
| 6178 | } |
| 6179 | } |
| 6180 | |
| 6181 | /// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT |
| 6182 | /// offsets into the padded level frame (lane-coefread): the tap pattern is a |
| 6183 | /// function of the tx class alone, which is fixed for a whole transform unit, |
| 6184 | /// so resolving it once per unit takes the class match and the `(dr, dc)` |
| 6185 | /// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same |
| 6186 | /// taps as [`base_ctx`]/[`br_ctx`] read, stated once; |
| 6187 | /// `flat_taps_match_the_row_col_neighbour_reads` pins them against the |
| 6188 | /// original `(dr, dc)` form. |
| 6189 | fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) { |
| 6190 | match class { |
| 6191 | TxClass::TwoD => ( |
| 6192 | [stride, 1, stride + 1, 2 * stride, 2], |
| 6193 | [stride, 1, stride + 1], |
| 6194 | ), |
| 6195 | TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]), |
| 6196 | TxClass::Vert => ( |
| 6197 | [stride, 1, 2 * stride, 3 * stride, 4 * stride], |
| 6198 | [stride, 1, 2 * stride], |
| 6199 | ), |
| 6200 | } |
| 6201 | } |
| 6202 | |
| 6203 | /// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped |
| 6204 | /// neighbours) + 1) >> 1`, clamped to 4. |
| 6205 | #[inline(always)] |
| 6206 | fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize { |
| 6207 | let mut mag = 0u32; |
| 6208 | for &t in taps { |
| 6209 | mag += u32::from(grid[idx + t]).min(3); |
| 6210 | } |
| 6211 | (((mag + 1) >> 1) as usize).min(4) |
| 6212 | } |
| 6213 | |
| 6214 | /// [`br_ctx`]'s neighbour sum, off flat taps. |
| 6215 | #[inline(always)] |
| 6216 | fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize { |
| 6217 | let mut mag = 0u32; |
| 6218 | for &t in taps { |
| 6219 | mag += u32::from(grid[idx + t]); |
| 6220 | } |
| 6221 | (((mag + 1) >> 1) as usize).min(6) |
| 6222 | } |
| 6223 | |
| 6224 | /// lane-coefread: superseded on the decode path by [`br_mag`] plus the |
| 6225 | /// origin-offset tail the two coefficient readers state inline; kept as the |
| 6226 | /// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the |
| 6227 | /// flat one against. |
| 6228 | #[cfg(test)] |
| 6229 | fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize { |
| 6230 | let extra = match class { |
| 6231 | TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1), |
| 6232 | TxClass::Horiz => neighbour(grid, stride, row, col + 2), |
| 6233 | TxClass::Vert => neighbour(grid, stride, row + 2, col), |
| 6234 | }; |
| 6235 | let mag = neighbour(grid, stride, row + 1, col) |
| 6236 | + neighbour(grid, stride, row, col + 1) |
| 6237 | + extra; |
| 6238 | let mag = (((mag + 1) >> 1).min(6)) as usize; |
| 6239 | if row == 0 && col == 0 { |
| 6240 | return mag; |
| 6241 | } |
| 6242 | let near_origin = match class { |
| 6243 | TxClass::TwoD => row < 2 && col < 2, |
| 6244 | TxClass::Horiz => col == 0, |
| 6245 | TxClass::Vert => row == 0, |
| 6246 | }; |
| 6247 | if near_origin { mag + 7 } else { mag + 14 } |
| 6248 | } |
| 6249 | |
| 6250 | /// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`): |
| 6251 | /// transposed from libaom's column-major buffer into this decoder's row-major |
| 6252 | /// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512` |
| 6253 | /// against the real table). Not the square zigzag formula generalized to |
| 6254 | /// unequal `w`/`h` -- checked and that does NOT reproduce this table. |
| 6255 | const SCAN_32X16: [u16; 512] = [ |
| 6256 | 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, |
| 6257 | 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, |
| 6258 | 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, |
| 6259 | 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, |
| 6260 | 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, |
| 6261 | 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, |
| 6262 | 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, |
| 6263 | 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, |
| 6264 | 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, |
| 6265 | 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, |
| 6266 | 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, |
| 6267 | 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, |
| 6268 | 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, |
| 6269 | 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, |
| 6270 | 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, |
| 6271 | 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, |
| 6272 | 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, |
| 6273 | 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, |
| 6274 | 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, |
| 6275 | 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, |
| 6276 | 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, |
| 6277 | 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, |
| 6278 | 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, |
| 6279 | 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, |
| 6280 | 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, |
| 6281 | 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, |
| 6282 | 509, 478, 447, 510, 479, 511, |
| 6283 | ]; |
| 6284 | |
| 6285 | /// `Default_Scan_16x32`, this decoder's own row-major transcription (see |
| 6286 | /// [`SCAN_32X16`]'s doc comment). |
| 6287 | const SCAN_16X32: [u16; 512] = [ |
| 6288 | 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, |
| 6289 | 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54, |
| 6290 | 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71, |
| 6291 | 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192, |
| 6292 | 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104, |
| 6293 | 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, |
| 6294 | 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256, |
| 6295 | 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108, |
| 6296 | 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169, |
| 6297 | 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230, |
| 6298 | 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291, |
| 6299 | 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352, |
| 6300 | 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189, |
| 6301 | 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250, |
| 6302 | 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311, |
| 6303 | 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372, |
| 6304 | 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433, |
| 6305 | 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270, |
| 6306 | 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331, |
| 6307 | 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392, |
| 6308 | 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468, |
| 6309 | 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380, |
| 6310 | 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501, |
| 6311 | 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503, |
| 6312 | 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476, |
| 6313 | 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511, |
| 6314 | ]; |
| 6315 | |
| 6316 | /// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major |
| 6317 | /// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which |
| 6318 | /// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from |
| 6319 | /// the same source). |
| 6320 | const SCAN_4X8: [u16; 32] = [ |
| 6321 | 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, |
| 6322 | 23, 26, 29, 27, 30, 31, |
| 6323 | ]; |
| 6324 | |
| 6325 | /// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`]. |
| 6326 | const SCAN_8X4: [u16; 32] = [ |
| 6327 | 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, |
| 6328 | 29, 22, 15, 30, 23, 31, |
| 6329 | ]; |
| 6330 | |
| 6331 | /// `Default_Scan_16x8`, this decoder's own row-major transcription (see |
| 6332 | /// [`SCAN_32X16`]'s doc comment). |
| 6333 | const SCAN_16X8: [u16; 128] = [ |
| 6334 | 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, |
| 6335 | 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54, |
| 6336 | 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87, |
| 6337 | 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120, |
| 6338 | 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108, |
| 6339 | 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127, |
| 6340 | ]; |
| 6341 | |
| 6342 | /// `Default_Scan_8x16`, this decoder's own row-major transcription (see |
| 6343 | /// [`SCAN_32X16`]'s doc comment). |
| 6344 | const SCAN_8X16: [u16; 128] = [ |
| 6345 | 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, |
| 6346 | 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58, |
| 6347 | 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82, |
| 6348 | 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99, |
| 6349 | 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116, |
| 6350 | 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127, |
| 6351 | ]; |
| 6352 | |
| 6353 | /// `Default_Scan_32x8`, this decoder's own row-major transcription (see |
| 6354 | /// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16 |
| 6355 | /// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its |
| 6356 | /// scans column-major (`p = col * height + row`), so a naive copy of |
| 6357 | /// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order |
| 6358 | /// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes |
| 6359 | /// are byte-identical to this decoder's [`SCAN_8X16`]. |
| 6360 | const SCAN_32X8: [u16; 256] = [ |
| 6361 | 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130, |
| 6362 | 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195, |
| 6363 | 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42, |
| 6364 | 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169, |
| 6365 | 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16, |
| 6366 | 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143, |
| 6367 | 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239, |
| 6368 | 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117, |
| 6369 | 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213, |
| 6370 | 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91, |
| 6371 | 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187, |
| 6372 | 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253, |
| 6373 | 222, 191, 254, 223, 255, |
| 6374 | ]; |
| 6375 | /// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a |
| 6376 | /// 16x64 `PARTITION_VERT_4` strip). |
| 6377 | const SCAN_8X32: [u16; 256] = [ |
| 6378 | 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, |
| 6379 | 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58, |
| 6380 | 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82, |
| 6381 | 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99, |
| 6382 | 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95, |
| 6383 | 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132, |
| 6384 | 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169, |
| 6385 | 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158, |
| 6386 | 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195, |
| 6387 | 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232, |
| 6388 | 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221, |
| 6389 | 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252, |
| 6390 | 239, 246, 253, 247, 254, 255, |
| 6391 | ]; |
| 6392 | /// `Default_Scan_16x4`, this decoder's own row-major transcription of |
| 6393 | /// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA |
| 6394 | /// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level |
| 6395 | /// (lane-tx64x16 r3). The transcription rule (`row * w + col` with |
| 6396 | /// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing |
| 6397 | /// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two |
| 6398 | /// were emitted -- a naive copy installs the transpose (class |
| 6399 | /// reference-layout-not-spec). |
| 6400 | const SCAN_16X4: [u16; 64] = [ |
| 6401 | 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, |
| 6402 | 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13, |
| 6403 | 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63, |
| 6404 | ]; |
| 6405 | /// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an |
| 6406 | /// 8x32 `PARTITION_VERT_4` strip). |
| 6407 | const SCAN_4X16: [u16; 64] = [ |
| 6408 | 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, |
| 6409 | 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52, |
| 6410 | 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63, |
| 6411 | ]; |
| 6412 | |
| 6413 | /// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding |
| 6414 | /// (`stride = w + 4`, four spare rows), so the edge test is the zeros the |
| 6415 | /// padding already holds. |
| 6416 | #[inline] |
| 6417 | fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 { |
| 6418 | grid[row * stride + col] as i32 |
| 6419 | } |
| 6420 | |
| 6421 | /// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): |
| 6422 | /// the rect generalization is libaom's own comment in |
| 6423 | /// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact |
| 6424 | /// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for |
| 6425 | /// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs |
| 6426 | /// [`decode_block_rect`] codes (see that function's own doc comment). |
| 6427 | fn base_ctx_rect( |
| 6428 | grid: &[u8], |
| 6429 | stride: usize, |
| 6430 | w: usize, |
| 6431 | h: usize, |
| 6432 | row: usize, |
| 6433 | col: usize, |
| 6434 | class: TxClass, |
| 6435 | ) -> usize { |
| 6436 | // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only |
| 6437 | // the 2D class short-circuits the DC position. |
| 6438 | if class == TxClass::TwoD && row == 0 && col == 0 { |
| 6439 | return 0; |
| 6440 | } |
| 6441 | let offsets: [(usize, usize); 5] = match class { |
| 6442 | TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)], |
| 6443 | TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)], |
| 6444 | TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)], |
| 6445 | }; |
| 6446 | let mag: i32 = offsets |
| 6447 | .iter() |
| 6448 | .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3)) |
| 6449 | .sum(); |
| 6450 | let ctx = ((mag + 1) >> 1).min(4) as usize; |
| 6451 | match class { |
| 6452 | TxClass::TwoD => { |
| 6453 | if w < h && row < 2 { |
| 6454 | return ctx + 11; |
| 6455 | } |
| 6456 | if w > h && col < 2 { |
| 6457 | return ctx + 16; |
| 6458 | } |
| 6459 | ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize |
| 6460 | } |
| 6461 | // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s |
| 6462 | // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the |
| 6463 | // position along one axis only). |
| 6464 | TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)), |
| 6465 | TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)), |
| 6466 | } |
| 6467 | } |
| 6468 | |
| 6469 | /// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the |
| 6470 | /// neighbour-offset math itself is shape-independent, only the boundary |
| 6471 | /// clamp needs the real bound in each axis. |
| 6472 | /// lane-coefread: superseded by [`br_mag`] on the rect decode path too -- |
| 6473 | /// its body was character-for-character [`br_ctx`]'s, which |
| 6474 | /// `flat_taps_match_the_row_col_neighbour_reads` now asserts. |
| 6475 | #[cfg(test)] |
| 6476 | fn br_ctx_rect( |
| 6477 | grid: &[u8], |
| 6478 | stride: usize, |
| 6479 | row: usize, |
| 6480 | col: usize, |
| 6481 | class: TxClass, |
| 6482 | ) -> usize { |
| 6483 | let extra = match class { |
| 6484 | TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1), |
| 6485 | TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2), |
| 6486 | TxClass::Vert => neighbour_rect(grid, stride, row + 2, col), |
| 6487 | }; |
| 6488 | let mag = neighbour_rect(grid, stride, row + 1, col) |
| 6489 | + neighbour_rect(grid, stride, row, col + 1) |
| 6490 | + extra; |
| 6491 | let mag = (((mag + 1) >> 1).min(6)) as usize; |
| 6492 | if row == 0 && col == 0 { |
| 6493 | return mag; |
| 6494 | } |
| 6495 | let near_origin = match class { |
| 6496 | TxClass::TwoD => row < 2 && col < 2, |
| 6497 | TxClass::Horiz => col == 0, |
| 6498 | TxClass::Vert => row == 0, |
| 6499 | }; |
| 6500 | if near_origin { mag + 7 } else { mag + 14 } |
| 6501 | } |
| 6502 | |
| 6503 | fn dc_vote(dc: Option<bool>) -> i32 { |
| 6504 | match dc { |
| 6505 | None => 0, |
| 6506 | Some(true) => -1, |
| 6507 | Some(false) => 1, |
| 6508 | } |
| 6509 | } |
| 6510 | |
| 6511 | fn dc_sign_ctx(vote: i32) -> usize { |
| 6512 | match vote.signum() { |
| 6513 | 0 => 0, |
| 6514 | -1 => 1, |
| 6515 | _ => 2, |
| 6516 | } |
| 6517 | } |
| 6518 | |
| 6519 | /// The `tx_type` a CDF symbol names, given the width of the row it was read |
| 6520 | /// from. |
| 6521 | /// |
| 6522 | /// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` / |
| 6523 | /// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13 |
| 6524 | /// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything |
| 6525 | /// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two |
| 6526 | /// members are a prefix of the five. |
| 6527 | /// |
| 6528 | /// One function rather than a `match` at each reader, so |
| 6529 | /// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair |
| 6530 | /// tests the mapping the readers actually use. |
| 6531 | pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> { |
| 6532 | match cdf_len { |
| 6533 | 17 => TxType::from_symbol_all16(t), |
| 6534 | 13 => TxType::from_symbol_set2_12(t), |
| 6535 | 8 => TxType::from_symbol_set1(t), |
| 6536 | _ => TxType::from_symbol(t), |
| 6537 | } |
| 6538 | } |
| 6539 | |
| 6540 | /// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide |
| 6541 | /// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it |
| 6542 | /// (class `table-and-reader-move-together` -- the writer picks its symbol |
| 6543 | /// through the reader's own map, so the two cannot drift). |
| 6544 | pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> { |
| 6545 | (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type)) |
| 6546 | } |
| 6547 | |
| 6548 | /// The remainder of a level the base and base-range syntax could not reach |
| 6549 | /// (spec 5.11.40): its bit length in unary, then that many of its own bits, |
| 6550 | /// most significant first — the exact inverse of [`crate::tile::write_golomb`]. |
| 6551 | pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> { |
| 6552 | // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2 |
| 6553 | // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same |
| 6554 | // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid |
| 6555 | // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39 |
| 6556 | // masks the level with `0xFFFFF`, so no conformant stream carries a longer |
| 6557 | // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_ |
| 6558 | // stream_can_carry` enumerates that whole value domain. |
| 6559 | // |
| 6560 | // So this refusal never names a reader gap: it is always the SYMPTOM of an |
| 6561 | // earlier desync (class `refusal-hides-a-defect`), and every historical |
| 6562 | // instance was closed by fixing that desync -- lane-dgolomb's |
| 6563 | // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`. |
| 6564 | // Raising the cap only trades a clean refusal for silent corruption: |
| 6565 | // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and |
| 6566 | // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact` |
| 6567 | // from a refusal into a frame-0 LUMA MISMATCH. |
| 6568 | let mut length = 1u32; |
| 6569 | while dec.literal(1) == 0 { |
| 6570 | length += 1; |
| 6571 | if length > 20 { |
| 6572 | return Err(unsupported("a Golomb tail longer than this decoder reads")); |
| 6573 | } |
| 6574 | } |
| 6575 | let mut x = 1u32; |
| 6576 | for _ in 1..length { |
| 6577 | x = (x << 1) | dec.literal(1); |
| 6578 | } |
| 6579 | Ok(x - 1) |
| 6580 | } |
| 6581 | |
| 6582 | /// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of |
| 6583 | /// [`crate::tile`]'s `write_eob`. |
| 6584 | fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize { |
| 6585 | const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513]; |
| 6586 | const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; |
| 6587 | |
| 6588 | let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); |
| 6589 | // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan |
| 6590 | // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt |
| 6591 | // a wholly separate CDF from every other tx_type (`decodetxb.c`'s |
| 6592 | // `eob_multi_ctx`). Missing that split desynced the very first |
| 6593 | // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught |
| 6594 | // against a real aomdec trace). |
| 6595 | let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) { |
| 6596 | (TxClass::TwoD, _) | (_, None) => coding.eob_pt, |
| 6597 | (_, Some(class1)) => class1, |
| 6598 | }; |
| 6599 | if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { |
| 6600 | let (range, value) = dec.debug_state(); |
| 6601 | eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}"); |
| 6602 | } |
| 6603 | let group = dec.symbol(eob_pt) + 1; |
| 6604 | if trace { |
| 6605 | eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0); |
| 6606 | } |
| 6607 | let bits = OFFSET_BITS[group]; |
| 6608 | let mut offset = 0u32; |
| 6609 | if bits > 0 { |
| 6610 | let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32; |
| 6611 | if trace { |
| 6612 | eprintln!("TRACE eob_extra ctx={} value={top}", group - 3); |
| 6613 | } |
| 6614 | offset = top << (bits - 1); |
| 6615 | if bits > 1 { |
| 6616 | offset |= dec.literal(bits - 1); |
| 6617 | } |
| 6618 | } |
| 6619 | GROUP_START[group] + offset as usize |
| 6620 | } |
| 6621 | |
| 6622 | /// One transform block's levels, the inverse of [`crate::tile`]'s |
| 6623 | /// `write_coeffs`, returned as a `side * side` grid in raster order, along |
| 6624 | /// with the transform type that grid was coded under (`DCT_DCT` when the |
| 6625 | /// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and |
| 6626 | /// 64-point transforms, which never code anything else). |
| 6627 | /// |
| 6628 | /// # Errors |
| 6629 | /// Returns an error if the `tx_type` symbol decodes to a value outside its |
| 6630 | /// CDF's own set (a corrupt or unsupported bitstream) — every value the |
| 6631 | /// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can |
| 6632 | /// produce dispatches to a real inverse transform. |
| 6633 | /// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its |
| 6634 | /// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None` |
| 6635 | /// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so |
| 6636 | /// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from |
| 6637 | /// the plane's own predicted mode instead. Every entry this table can |
| 6638 | /// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two |
| 6639 | /// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this |
| 6640 | /// table ever names), so unlike the CDF-coded luma path there is no |
| 6641 | /// ext-tx-set membership check to fall back from here. |
| 6642 | pub(crate) fn default_intra_tx_type(mode: u8) -> TxType { |
| 6643 | use crate::intra::{ |
| 6644 | D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED, |
| 6645 | PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED, |
| 6646 | }; |
| 6647 | match mode { |
| 6648 | DC_PRED | D45_PRED => TxType::DctDct, |
| 6649 | V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct, |
| 6650 | H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst, |
| 6651 | D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst, |
| 6652 | other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"), |
| 6653 | } |
| 6654 | } |
| 6655 | |
| 6656 | /// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED` |
| 6657 | /// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own |
| 6658 | /// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth. |
| 6659 | fn is_smooth_mode(mode: usize) -> bool { |
| 6660 | (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode) |
| 6661 | } |
| 6662 | |
| 6663 | /// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each. |
| 6664 | /// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so |
| 6665 | /// nine of them inside the base/sign loops pinned nine sets of values in the |
| 6666 | /// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill |
| 6667 | /// traffic). Out of line, the loop keeps its values in registers and the |
| 6668 | /// trace output is character-for-character what it was. |
| 6669 | #[cold] |
| 6670 | #[inline(never)] |
| 6671 | fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) { |
| 6672 | eprintln!("TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"); |
| 6673 | } |
| 6674 | |
| 6675 | #[cold] |
| 6676 | #[inline(never)] |
| 6677 | fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) { |
| 6678 | eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"); |
| 6679 | } |
| 6680 | |
| 6681 | #[cold] |
| 6682 | #[inline(never)] |
| 6683 | fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) { |
| 6684 | eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"); |
| 6685 | } |
| 6686 | |
| 6687 | #[cold] |
| 6688 | #[inline(never)] |
| 6689 | fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) { |
| 6690 | let (rng, _) = dec.debug_state(); |
| 6691 | eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"); |
| 6692 | } |
| 6693 | |
| 6694 | #[cold] |
| 6695 | #[inline(never)] |
| 6696 | fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) { |
| 6697 | let (rng, _) = dec.debug_state(); |
| 6698 | eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}"); |
| 6699 | } |
| 6700 | |
| 6701 | #[cold] |
| 6702 | #[inline(never)] |
| 6703 | fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) { |
| 6704 | let (rng, _) = dec.debug_state(); |
| 6705 | eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32); |
| 6706 | } |
| 6707 | |
| 6708 | #[cold] |
| 6709 | #[inline(never)] |
| 6710 | fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) { |
| 6711 | let (rng, _) = dec.debug_state(); |
| 6712 | eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}"); |
| 6713 | } |
| 6714 | |
| 6715 | #[cold] |
| 6716 | #[inline(never)] |
| 6717 | fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) { |
| 6718 | let (rng, _) = dec.debug_state(); |
| 6719 | eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}"); |
| 6720 | } |
| 6721 | |
| 6722 | fn read_coeffs( |
| 6723 | dec: &mut SymbolDecoder, |
| 6724 | coding: &mut TxbTables, |
| 6725 | scan: &[u16], |
| 6726 | skip_ctx: usize, |
| 6727 | sign_ctx: usize, |
| 6728 | // The chroma default (spec `Intra_Mode_To_Tx_Type`, see |
| 6729 | // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes |
| 6730 | // nothing at all; `DctDct` for every luma call and every chroma call at |
| 6731 | // a size the spec forces to `DCT_DCT` regardless of mode (32-point and |
| 6732 | // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in. |
| 6733 | default_tx_type: TxType, |
| 6734 | // `Some((w, h))` with `w != h` when this read is a superblock-level |
| 6735 | // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square |
| 6736 | // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table |
| 6737 | // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8 |
| 6738 | // root cause, see [`base_ctx`]). `None` everywhere else -- every other |
| 6739 | // caller's block genuinely is `side` x `side`. |
| 6740 | rect_shape: Option<(usize, usize)>, |
| 6741 | ) -> Result<(Grid, TxType)> { |
| 6742 | let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); |
| 6743 | let side = coding.side; |
| 6744 | if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { |
| 6745 | let (range, value) = dec.debug_state(); |
| 6746 | eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}"); |
| 6747 | } |
| 6748 | if crate::envflags::env_flag!("EC_ECDUMP_IN") { |
| 6749 | let (range, value) = dec.debug_state(); |
| 6750 | let bit = dec.debug_bitpos(); |
| 6751 | eprintln!( |
| 6752 | "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})" |
| 6753 | ); |
| 6754 | } |
| 6755 | let dbg_txbskip = if coeff_trace_on() { |
| 6756 | coding.txb_skip[skip_ctx] |
| 6757 | } else { |
| 6758 | [0; 3] |
| 6759 | }; |
| 6760 | let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; |
| 6761 | if coeff_trace_on() { |
| 6762 | let (rng, _) = dec.debug_state(); |
| 6763 | eprintln!( |
| 6764 | "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}", |
| 6765 | coding.side, |
| 6766 | all_zero as i32 |
| 6767 | ); |
| 6768 | } |
| 6769 | if crate::envflags::env_flag!("EC_AV1_TELL") { |
| 6770 | eprintln!( |
| 6771 | "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}", |
| 6772 | all_zero as u8, dec.debug_bitpos(), dec.debug_state().0 |
| 6773 | ); |
| 6774 | } |
| 6775 | if trace { |
| 6776 | eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32); |
| 6777 | } |
| 6778 | if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { |
| 6779 | let (range, value) = dec.debug_state(); |
| 6780 | eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}"); |
| 6781 | } |
| 6782 | if all_zero { |
| 6783 | // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the |
| 6784 | // shared zero grid instead of allocating and zeroing its own. |
| 6785 | return Ok((Grid::Zero(side * side), TxType::DctDct)); |
| 6786 | } |
| 6787 | let mut grid = vec![0i32; side * side]; |
| 6788 | let mut tx_type = default_tx_type; |
| 6789 | if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { |
| 6790 | // The CDF row's own width names its set (lane-cdffwd2: extended |
| 6791 | // past the original two-way intra split once wider `reduced_tx_set |
| 6792 | // == 0` inter sets joined the table): 17 slots (16 symbols) is |
| 6793 | // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`, |
| 6794 | // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5 |
| 6795 | // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets |
| 6796 | // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two |
| 6797 | // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five). |
| 6798 | let len = tx_type_cdf.len(); |
| 6799 | if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 { |
| 6800 | eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}"); |
| 6801 | } |
| 6802 | let t = dec.symbol(tx_type_cdf); |
| 6803 | crate::census::tx_type(len, t); |
| 6804 | if coeff_trace_on() { |
| 6805 | let (rng, _) = dec.debug_state(); |
| 6806 | eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}"); |
| 6807 | } |
| 6808 | if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { |
| 6809 | let (range, value) = dec.debug_state(); |
| 6810 | eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}"); |
| 6811 | } |
| 6812 | if trace { |
| 6813 | eprintln!("TRACE tx_type value={t} len={len}"); |
| 6814 | } |
| 6815 | tx_type = tx_type_from_symbol(len, t) |
| 6816 | .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; |
| 6817 | } |
| 6818 | |
| 6819 | let class = TxClass::of(tx_type); |
| 6820 | if class != TxClass::TwoD { |
| 6821 | hit!(TX_CLASS1_HITS); |
| 6822 | hit!(RECT_CLASS1_HITS); |
| 6823 | } |
| 6824 | let eob = read_eob(dec, coding, class); |
| 6825 | if trace { |
| 6826 | eprintln!("TRACE eob value={eob}"); |
| 6827 | } |
| 6828 | let ec_trace_coeff = coeff_trace_on(); |
| 6829 | if ec_trace_coeff { |
| 6830 | let (rng, _) = dec.debug_state(); |
| 6831 | let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" }; |
| 6832 | eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}"); |
| 6833 | } |
| 6834 | let class_scan; |
| 6835 | let scan: &[u16] = if class == TxClass::TwoD { |
| 6836 | scan |
| 6837 | } else { |
| 6838 | class_scan = class_scan_table(side, class); |
| 6839 | &class_scan |
| 6840 | }; |
| 6841 | // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per- |
| 6842 | // coefficient `pos / side`, `pos % side` was a hardware divide where a |
| 6843 | // shift and a mask say the same thing, and the level buffer fits a fixed |
| 6844 | // 32x32 frame of stack instead of a heap allocation per transform block. |
| 6845 | debug_assert!(side.is_power_of_two() && side <= 32); |
| 6846 | let sh = side.trailing_zeros(); |
| 6847 | let col_mask = side - 1; |
| 6848 | // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]): |
| 6849 | // `stride = side + 4` columns and four spare rows, so the widest read |
| 6850 | // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with |
| 6851 | // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at |
| 6852 | // most `36 * 36`. Only `col < side`, `row < side` cells are ever written. |
| 6853 | let stride = side + 4; |
| 6854 | let mut levels_buf = [0u8; 36 * 36]; |
| 6855 | let levels = &mut levels_buf[..stride * stride]; |
| 6856 | // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the |
| 6857 | // `pos >> sh` / `& mask` decomposition and load the level back out of the |
| 6858 | // padded frame just to skip the zeros. The base pass already knows both, |
| 6859 | // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient |
| 6860 | // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign |
| 6861 | // pass walks that list in reverse (the base pass runs in reverse scan |
| 6862 | // order, so reversing it is forward scan order: the same coefficients, in |
| 6863 | // the same order, with the same `c` the trace prints). |
| 6864 | let mut nz_buf = [0u16; 1024]; |
| 6865 | let mut nz_n = 0usize; |
| 6866 | let (base_taps, br_taps) = flat_taps(stride, class); |
| 6867 | for scan_idx in (0..eob).rev() { |
| 6868 | let pos = scan[scan_idx] as usize; |
| 6869 | let (row, col) = (pos >> sh, pos & col_mask); |
| 6870 | let idx = row * stride + col; |
| 6871 | let level = if scan_idx == eob - 1 { |
| 6872 | let ctx = eob_coeff_ctx(scan_idx, side * side); |
| 6873 | let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; |
| 6874 | if trace { |
| 6875 | trace_base_eob(scan_idx, pos, row, col, ctx, v); |
| 6876 | } |
| 6877 | v |
| 6878 | } else { |
| 6879 | let ctx = if class == TxClass::TwoD && rect_shape.is_none() { |
| 6880 | if row == 0 && col == 0 { |
| 6881 | 0 |
| 6882 | } else { |
| 6883 | base_mag(levels, idx, &base_taps) |
| 6884 | + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize |
| 6885 | } |
| 6886 | } else { |
| 6887 | base_ctx(levels, stride, row, col, class, rect_shape) |
| 6888 | }; |
| 6889 | let v = dec.symbol(&mut coding.base[ctx]) as i32; |
| 6890 | if ec_trace_coeff { |
| 6891 | // `pos` in libaom's column-major `coeff_idx` convention, so |
| 6892 | // the ladder lines up with instrumented `aomdec`. |
| 6893 | coeff_step_base(dec, scan_idx, col * side + row, ctx, v); |
| 6894 | } |
| 6895 | if trace { |
| 6896 | trace_base(scan_idx, pos, row, col, ctx, v); |
| 6897 | } |
| 6898 | v |
| 6899 | }; |
| 6900 | let level = if level > NUM_BASE_LEVELS { |
| 6901 | let ctx = { |
| 6902 | let mag = br_mag(levels, idx, &br_taps); |
| 6903 | if row == 0 && col == 0 { |
| 6904 | mag |
| 6905 | } else { |
| 6906 | let near_origin = match class { |
| 6907 | TxClass::TwoD => row < 2 && col < 2, |
| 6908 | TxClass::Horiz => col == 0, |
| 6909 | TxClass::Vert => row == 0, |
| 6910 | }; |
| 6911 | if near_origin { mag + 7 } else { mag + 14 } |
| 6912 | } |
| 6913 | }; |
| 6914 | let mut level = level; |
| 6915 | let mut sent = 0; |
| 6916 | loop { |
| 6917 | let k = dec.symbol(&mut coding.br[ctx]) as i32; |
| 6918 | if ec_trace_coeff { |
| 6919 | // lane-leaf8tx r3: the `br` rung was missing from THIS |
| 6920 | // path's trace, so the cross-decoder range ladder was |
| 6921 | // blind to every base-range symbol and mis-reported the |
| 6922 | // first divergence (class [[gate-blind-to-feature]]). |
| 6923 | coeff_step_br(dec, scan_idx, col * side + row, ctx, k); |
| 6924 | } |
| 6925 | if trace { |
| 6926 | trace_br(scan_idx, pos, row, col, ctx, k); |
| 6927 | } |
| 6928 | level += k; |
| 6929 | sent += BR_STEP; |
| 6930 | if k < BR_STEP || sent >= COEFF_BASE_RANGE { |
| 6931 | break; |
| 6932 | } |
| 6933 | } |
| 6934 | level |
| 6935 | } else { |
| 6936 | level |
| 6937 | }; |
| 6938 | if ec_trace_coeff && scan_idx == eob - 1 { |
| 6939 | coeff_step_base_eob_level(dec, level); |
| 6940 | } |
| 6941 | // Every coded level here is a magnitude in `0..=15` (base <= 3 plus |
| 6942 | // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is |
| 6943 | // added in the sign pass below, straight into `grid`), so the context |
| 6944 | // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a |
| 6945 | // byte gather (lane-coefbuf). |
| 6946 | debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame"); |
| 6947 | levels[idx] = level as u8; |
| 6948 | if level != 0 { |
| 6949 | nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16; |
| 6950 | nz_n += 1; |
| 6951 | } |
| 6952 | } |
| 6953 | if ec_trace_coeff { |
| 6954 | let (rng, _) = dec.debug_state(); |
| 6955 | eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}"); |
| 6956 | } |
| 6957 | |
| 6958 | for &packed in nz_buf[..nz_n].iter().rev() { |
| 6959 | let c = (packed >> 4) as usize; |
| 6960 | let pos = scan[c] as usize; |
| 6961 | let level = (packed & 15) as i32; |
| 6962 | let negative = if pos == 0 { |
| 6963 | let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1; |
| 6964 | if trace { |
| 6965 | eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32); |
| 6966 | } |
| 6967 | v |
| 6968 | } else { |
| 6969 | dec.literal(1) == 1 |
| 6970 | }; |
| 6971 | if ec_trace_coeff { |
| 6972 | coeff_step_sign(dec, c, negative); |
| 6973 | } |
| 6974 | let level = if level > MAX_BR_LEVEL { |
| 6975 | let g = read_golomb(dec)?; |
| 6976 | if trace { |
| 6977 | eprintln!("TRACE golomb pos={pos} value={g}"); |
| 6978 | } |
| 6979 | level + g as i32 |
| 6980 | } else { |
| 6981 | level |
| 6982 | }; |
| 6983 | if ec_trace_coeff { |
| 6984 | coeff_step_post_golomb(dec, c, level); |
| 6985 | } |
| 6986 | grid[pos] = if negative { -level } else { level }; |
| 6987 | } |
| 6988 | Ok((Grid::Own(grid), tx_type)) |
| 6989 | } |
| 6990 | |
| 6991 | /// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the |
| 6992 | /// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to |
| 6993 | /// `TxClass::TwoD` -- the only class any rect size pair this decoder codes |
| 6994 | /// can ever produce, since every `tx_type` this decoder's rect sets can read |
| 6995 | /// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name |
| 6996 | /// rather than guess-decode if a non-2D class ever shows up here, since |
| 6997 | /// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect |
| 6998 | /// form for those. |
| 6999 | |
| 7000 | fn read_coeffs_rect( |
| 7001 | dec: &mut SymbolDecoder, |
| 7002 | coding: &mut TxbTables, |
| 7003 | scan: &[u16], |
| 7004 | w: usize, |
| 7005 | h: usize, |
| 7006 | skip_ctx: usize, |
| 7007 | sign_ctx: usize, |
| 7008 | default_tx_type: TxType, |
| 7009 | ) -> Result<(Grid, TxType)> { |
| 7010 | let rect_trace = coeff_trace_on(); |
| 7011 | let entry_rng = dec.debug_state().0; |
| 7012 | let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; |
| 7013 | if rect_trace { |
| 7014 | eprintln!( |
| 7015 | "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}", |
| 7016 | all_zero as i32, |
| 7017 | dec.debug_state().0 |
| 7018 | ); |
| 7019 | } |
| 7020 | if all_zero { |
| 7021 | return Ok((Grid::Zero(w * h), TxType::DctDct)); |
| 7022 | } |
| 7023 | let mut grid = vec![0i32; w * h]; |
| 7024 | hit!(RECT_COEFF_TU_HITS); |
| 7025 | // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is |
| 7026 | // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including |
| 7027 | // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and |
| 7028 | // context offsets -- both of which now have rect forms |
| 7029 | // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`). |
| 7030 | // The rect sets that carry no symbol at all still pass `None` here. |
| 7031 | let mut tx_type = default_tx_type; |
| 7032 | if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { |
| 7033 | let len = tx_type_cdf.len(); |
| 7034 | let t = dec.symbol(tx_type_cdf); |
| 7035 | crate::census::tx_type(len, t); |
| 7036 | tx_type = tx_type_from_symbol(len, t) |
| 7037 | .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; |
| 7038 | if rect_trace { |
| 7039 | eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0); |
| 7040 | } |
| 7041 | } |
| 7042 | let class = TxClass::of(tx_type); |
| 7043 | if class != TxClass::TwoD { |
| 7044 | hit!(TX_CLASS1_HITS); |
| 7045 | } |
| 7046 | let eob = read_eob(dec, coding, class); |
| 7047 | if rect_trace { |
| 7048 | eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0); |
| 7049 | } |
| 7050 | let class_scan; |
| 7051 | let scan: &[u16] = if class == TxClass::TwoD { |
| 7052 | scan |
| 7053 | } else { |
| 7054 | class_scan = class_scan_table_wh(w, h, class); |
| 7055 | &class_scan |
| 7056 | }; |
| 7057 | // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a |
| 7058 | // stack frame sized to the unit -- same reasoning as [`read_coeffs`]: |
| 7059 | // `neighbour_rect` returns 0 outside `(w, h)` and every write is |
| 7060 | // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1 |
| 7061 | // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a |
| 7062 | // mask rather than a hardware divide. |
| 7063 | let stride = w + 4; |
| 7064 | let n = stride * (h + 4); |
| 7065 | if !(w.is_power_of_two() && n <= 36 * 36) { |
| 7066 | panic!("rect coeff scratch w={w} h={h} n={n}"); |
| 7067 | } |
| 7068 | let (mut b96, mut b256, mut b768); |
| 7069 | // Byte levels, same `0..=15` bound [`read_coeffs`] states. |
| 7070 | let levels: &mut [u8] = if n <= 96 { |
| 7071 | b96 = [0u8; 96]; |
| 7072 | &mut b96[..n] |
| 7073 | } else if n <= 256 { |
| 7074 | b256 = [0u8; 256]; |
| 7075 | &mut b256[..n] |
| 7076 | } else { |
| 7077 | b768 = [0u8; 768]; |
| 7078 | &mut b768[..n] |
| 7079 | }; |
| 7080 | let wsh = w.trailing_zeros(); |
| 7081 | let wmask = w - 1; |
| 7082 | // lane-coefread: the non-zero list [`read_coeffs`] documents. |
| 7083 | let mut nz_buf = [0u16; 1024]; |
| 7084 | let mut nz_n = 0usize; |
| 7085 | let (base_taps, br_taps) = flat_taps(stride, class); |
| 7086 | let (wlt, wgt) = (w < h, w > h); |
| 7087 | for scan_idx in (0..eob).rev() { |
| 7088 | let pos = scan[scan_idx] as usize; |
| 7089 | let (row, col) = (pos >> wsh, pos & wmask); |
| 7090 | let idx = row * stride + col; |
| 7091 | // libaom's column-major `coeff_idx`, for ladder comparison. |
| 7092 | let _apos = col * h + row; |
| 7093 | let level = if scan_idx == eob - 1 { |
| 7094 | let ctx = eob_coeff_ctx(scan_idx, w * h); |
| 7095 | let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; |
| 7096 | if rect_trace { |
| 7097 | eprintln!( |
| 7098 | "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}", |
| 7099 | dec.debug_state().0 |
| 7100 | ); |
| 7101 | } |
| 7102 | v |
| 7103 | } else { |
| 7104 | let ctx = if class == TxClass::TwoD { |
| 7105 | if row == 0 && col == 0 { |
| 7106 | 0 |
| 7107 | } else { |
| 7108 | let m = base_mag(levels, idx, &base_taps); |
| 7109 | if wlt && row < 2 { |
| 7110 | m + 11 |
| 7111 | } else if wgt && col < 2 { |
| 7112 | m + 16 |
| 7113 | } else { |
| 7114 | m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize |
| 7115 | } |
| 7116 | } |
| 7117 | } else { |
| 7118 | base_ctx_rect(levels, stride, w, h, row, col, class) |
| 7119 | }; |
| 7120 | let v = dec.symbol(&mut coding.base[ctx]) as i32; |
| 7121 | if rect_trace { |
| 7122 | eprintln!( |
| 7123 | "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}", |
| 7124 | dec.debug_state().0 |
| 7125 | ); |
| 7126 | } |
| 7127 | v |
| 7128 | }; |
| 7129 | let level = if level > NUM_BASE_LEVELS { |
| 7130 | let ctx = { |
| 7131 | let mag = br_mag(levels, idx, &br_taps); |
| 7132 | if row == 0 && col == 0 { |
| 7133 | mag |
| 7134 | } else { |
| 7135 | let near_origin = match class { |
| 7136 | TxClass::TwoD => row < 2 && col < 2, |
| 7137 | TxClass::Horiz => col == 0, |
| 7138 | TxClass::Vert => row == 0, |
| 7139 | }; |
| 7140 | if near_origin { mag + 7 } else { mag + 14 } |
| 7141 | } |
| 7142 | }; |
| 7143 | let mut level = level; |
| 7144 | let mut sent = 0; |
| 7145 | loop { |
| 7146 | let k = dec.symbol(&mut coding.br[ctx]) as i32; |
| 7147 | if rect_trace { |
| 7148 | eprintln!( |
| 7149 | "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}", |
| 7150 | dec.debug_state().0 |
| 7151 | ); |
| 7152 | } |
| 7153 | level += k; |
| 7154 | sent += BR_STEP; |
| 7155 | if k < BR_STEP || sent >= COEFF_BASE_RANGE { |
| 7156 | break; |
| 7157 | } |
| 7158 | } |
| 7159 | level |
| 7160 | } else { |
| 7161 | level |
| 7162 | }; |
| 7163 | debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame"); |
| 7164 | levels[idx] = level as u8; |
| 7165 | if level != 0 { |
| 7166 | nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16; |
| 7167 | nz_n += 1; |
| 7168 | } |
| 7169 | if rect_trace { |
| 7170 | let (rng, _) = dec.debug_state(); |
| 7171 | eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}"); |
| 7172 | } |
| 7173 | } |
| 7174 | if rect_trace { |
| 7175 | let (rng, _) = dec.debug_state(); |
| 7176 | eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}"); |
| 7177 | } |
| 7178 | for &packed in nz_buf[..nz_n].iter().rev() { |
| 7179 | let pos = scan[(packed >> 4) as usize] as usize; |
| 7180 | let level = (packed & 15) as i32; |
| 7181 | let negative = if pos == 0 { |
| 7182 | dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1 |
| 7183 | } else { |
| 7184 | dec.literal(1) == 1 |
| 7185 | }; |
| 7186 | if rect_trace { |
| 7187 | let (rng, _) = dec.debug_state(); |
| 7188 | eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative)); |
| 7189 | } |
| 7190 | let level = if level > MAX_BR_LEVEL { |
| 7191 | let g = read_golomb(dec)?; |
| 7192 | level + g as i32 |
| 7193 | } else { |
| 7194 | level |
| 7195 | }; |
| 7196 | grid[pos] = if negative { -level } else { level }; |
| 7197 | } |
| 7198 | // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the |
| 7199 | // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose |
| 7200 | // grids differ is a reader defect, one whose grids agree is a transform |
| 7201 | // defect. |
| 7202 | if crate::envflags::env_flag!("EC_DQCOEFF") { |
| 7203 | let nz: Vec<String> = grid |
| 7204 | .iter() |
| 7205 | .enumerate() |
| 7206 | .filter(|&(_, &v)| v != 0) |
| 7207 | .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w)) |
| 7208 | .collect(); |
| 7209 | eprintln!("OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}", nz.join(",")); |
| 7210 | } |
| 7211 | Ok((Grid::Own(grid), tx_type)) |
| 7212 | } |
| 7213 | |
| 7214 | /// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the |
| 7215 | /// [`read_plane`] family already has. |
| 7216 | /// |
| 7217 | /// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop |
| 7218 | /// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a |
| 7219 | /// chroma plane: no u/v coefficient symbol is coded, and consuming one moves |
| 7220 | /// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`] |
| 7221 | /// enforces that for every strip that reads its chroma through it, but the rect |
| 7222 | /// strip paths ([`decode_block_rect`], [`decode_leaf_rect`], |
| 7223 | /// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`]) |
| 7224 | /// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes |
| 7225 | /// this gate instead (class `reader-gate-not-on-every-path`). One un-gated |
| 7226 | /// chroma read desyncs at the FIRST rect leaf of the frame and every later |
| 7227 | /// symbol -- and therefore every later pixel -- is decoded from the wrong |
| 7228 | /// place, without ever tripping a refusal (the desynced values stay inside |
| 7229 | /// every coded alphabet). |
| 7230 | fn read_chroma_coeffs_rect( |
| 7231 | dec: &mut SymbolDecoder, |
| 7232 | coding: &mut TxbTables, |
| 7233 | scan: &[u16], |
| 7234 | w: usize, |
| 7235 | h: usize, |
| 7236 | skip_ctx: usize, |
| 7237 | sign_ctx: usize, |
| 7238 | default_tx_type: TxType, |
| 7239 | fctx: &crate::decode::FrameCtx, |
| 7240 | ) -> Result<(Grid, TxType)> { |
| 7241 | if mono(fctx) { |
| 7242 | return Ok((Grid::Zero(w * h), TxType::DctDct)); |
| 7243 | } |
| 7244 | read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type) |
| 7245 | } |
| 7246 | |
| 7247 | /// What one coded block leaves behind for the blocks that read it as a |
| 7248 | /// neighbour: whether it coded anything at all, and the sign of its DC — |
| 7249 | /// [`crate::tile`]'s own private `Neighbour`. |
| 7250 | #[derive(Clone, Copy, Default)] |
| 7251 | struct Neighbour { |
| 7252 | /// The transform unit's cumulative coefficient level (spec `cul_level`, |
| 7253 | /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's |
| 7254 | /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not" |
| 7255 | /// boolean (`level != 0`) is enough for every context this decoder read |
| 7256 | /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller |
| 7257 | /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`) |
| 7258 | /// needs the actual magnitude tier of its above/left neighbours, not |
| 7259 | /// just whether they coded anything. |
| 7260 | level: u8, |
| 7261 | dc: Option<bool>, |
| 7262 | } |
| 7263 | |
| 7264 | /// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the |
| 7265 | /// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the |
| 7266 | /// grid is dropped, never a panic. One `memset` per grid row instead of a |
| 7267 | /// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers |
| 7268 | /// is contiguous, so this writes exactly the cells the cell loop did, |
| 7269 | /// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the |
| 7270 | /// next row. |
| 7271 | #[inline] |
| 7272 | fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) { |
| 7273 | let end = (start + n).min(dst.len()); |
| 7274 | if start < end { |
| 7275 | dst[start..end].fill(v); |
| 7276 | } |
| 7277 | } |
| 7278 | |
| 7279 | fn neighbour_state(grid: &[i32]) -> Neighbour { |
| 7280 | // lane-coefgrid: the shared zero grid sums to zero by construction; this |
| 7281 | // sum has no early exit, so the 60% of units that code nothing used to |
| 7282 | // walk their whole grid here. |
| 7283 | if is_zero_grid(grid) { |
| 7284 | return Neighbour::default(); |
| 7285 | } |
| 7286 | let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum(); |
| 7287 | Neighbour { |
| 7288 | level: cul.min(7) as u8, |
| 7289 | dc: (grid[0] != 0).then_some(grid[0] < 0), |
| 7290 | } |
| 7291 | } |
| 7292 | |
| 7293 | /// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0, |
| 7294 | /// transform unit smaller than the block it sits in): `top`/`left` are the |
| 7295 | /// above/left neighbours' magnitude tiers, each already clamped to 4. |
| 7296 | pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [ |
| 7297 | [1, 2, 2, 2, 3], |
| 7298 | [2, 4, 4, 4, 5], |
| 7299 | [2, 4, 4, 4, 5], |
| 7300 | [2, 4, 4, 4, 5], |
| 7301 | [3, 5, 5, 5, 6], |
| 7302 | ]; |
| 7303 | |
| 7304 | /// The `skip` flag, its written-instrument bit, and the covering coded |
| 7305 | /// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the |
| 7306 | /// four maps are written together by `Neighbours::fill_skip_grid_rect` and by |
| 7307 | /// nothing else, so a block's row is one fill instead of four, and the |
| 7308 | /// deblocker's `pu_edge` reads origin and dims off one cache line. |
| 7309 | #[derive(Clone, Copy)] |
| 7310 | struct BlkCell { |
| 7311 | skip: bool, |
| 7312 | written: bool, |
| 7313 | org: [u16; 2], |
| 7314 | dim: [u8; 2], |
| 7315 | } |
| 7316 | |
| 7317 | /// The neighbour state a block's contexts are read from — a duplicate of |
| 7318 | /// [`crate::tile`]'s own private `Neighbours` (that module is another lane's |
| 7319 | /// territory this round), kept at the same two granularities the real writer |
| 7320 | /// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16 |
| 7321 | /// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s |
| 7322 | /// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient |
| 7323 | /// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a |
| 7324 | /// chroma transform straddling the true, odd-sized frame edge see its |
| 7325 | /// neighbour's state clamped at its own subsampled edge rather than luma's. |
| 7326 | #[derive(Clone)] |
| 7327 | struct Neighbours { |
| 7328 | above: Vec<[Neighbour; 3]>, |
| 7329 | left: Vec<[Neighbour; 3]>, |
| 7330 | above_mode: Vec<usize>, |
| 7331 | left_mode: Vec<usize>, |
| 7332 | /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma |
| 7333 | /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec |
| 7334 | /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the |
| 7335 | /// luma one -- the same block can (and often does) code a different |
| 7336 | /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`; |
| 7337 | /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real |
| 7338 | /// within-block neighbour finer than this grid) is luma-only -- a known, |
| 7339 | /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs` |
| 7340 | /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this). |
| 7341 | above_uv_mode: Vec<usize>, |
| 7342 | left_uv_mode: Vec<usize>, |
| 7343 | above_side: Vec<usize>, |
| 7344 | left_side: Vec<usize>, |
| 7345 | /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4) |
| 7346 | /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s |
| 7347 | /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16 |
| 7348 | /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse |
| 7349 | /// array cannot tell the second leaf's partition symbol that the first |
| 7350 | /// one was coded at 8x8. |
| 7351 | /// lane-publish2: `u8` (a block side is at most 128 px, and so is |
| 7352 | /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi. |
| 7353 | above_side_mi: Vec<u8>, |
| 7354 | left_side_mi: Vec<u8>, |
| 7355 | /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column |
| 7356 | /// / row, with the mi position it was written at |
| 7357 | /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on |
| 7358 | /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an |
| 7359 | /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode |
| 7360 | /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8 |
| 7361 | /// leaf whose neighbour is another split group needs that group's leaf 3 |
| 7362 | /// (bottom-right), not the leaf the coarse slot happens to hold. Written |
| 7363 | /// and read only by [`decode_leaf_split4`]; the position guard makes it |
| 7364 | /// fall back to the coarse slot whenever the real neighbour was a block |
| 7365 | /// of 8x8 or larger (whose one mode is correct for every row it spans). |
| 7366 | /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to |
| 7367 | /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes |
| 7368 | /// per mi per side of publish traffic was pure width. `u16::MAX` is the |
| 7369 | /// "never written" sentinel (an mi index cannot reach it: AV1's largest |
| 7370 | /// frame is 65536 px = 16384 mi). |
| 7371 | sub8_mode_col: Vec<(u16, u8)>, |
| 7372 | sub8_mode_row: Vec<(u16, u8)>, |
| 7373 | /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5): |
| 7374 | /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode` |
| 7375 | /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse |
| 7376 | /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves -- |
| 7377 | /// the leaf above writes the same row slot the block to the left owns. |
| 7378 | uv_mode_col: Vec<(u16, u8)>, |
| 7379 | uv_mode_row: Vec<(u16, u8)>, |
| 7380 | /// Every mi cell's own `uv_mode`, the mi grid libaom's |
| 7381 | /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`, |
| 7382 | /// blockd.h). lane-t900 r12: the one-slot-per-column |
| 7383 | /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written |
| 7384 | /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half |
| 7385 | /// overwrote the row the pair's chroma-ref half then wanted to read -- |
| 7386 | /// the mi-exact match failed and the coarse [`SUB`] band answered instead. |
| 7387 | /// `u8::MAX` = no block has written this cell yet (fall back to the maps). |
| 7388 | uv_mode_grid: Vec<u8>, |
| 7389 | /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like |
| 7390 | /// every other band here). |
| 7391 | uv_grid_cols: usize, |
| 7392 | /// Whether the block above/left of this column/row was coded `skip` -- |
| 7393 | /// an inter frame's own `skip` context (spec `SkipContext`), which the |
| 7394 | /// key-frame writer never tracks (its skip context is always zero); a |
| 7395 | /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/ |
| 7396 | /// `left_skip`. |
| 7397 | above_skip: Vec<bool>, |
| 7398 | left_skip: Vec<bool>, |
| 7399 | /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at |
| 7400 | /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in |
| 7401 | /// pixels last written over each unit by `set_txfm_ctxs`/ |
| 7402 | /// `txfm_partition_update`, which is what an inter block's `txfm_split` |
| 7403 | /// symbol reads its context from (lane-txselect, spec 5.11.17). |
| 7404 | /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left` |
| 7405 | /// array is exactly libaom's per-superblock-row reset, since each mi row |
| 7406 | /// is only ever visited inside one superblock row. |
| 7407 | above_txfm: Vec<u8>, |
| 7408 | left_txfm: Vec<u8>, |
| 7409 | /// Whether the block above/left of this column/row coded `skip_mode` |
| 7410 | /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup, |
| 7411 | /// lane-av1comp round 14. |
| 7412 | above_skip_mode: Vec<bool>, |
| 7413 | left_skip_mode: Vec<bool>, |
| 7414 | /// Whether the block above/left was coded inter -- the `is_inter` |
| 7415 | /// context (spec `av1_get_intra_inter_context`), a duplicate of |
| 7416 | /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`. |
| 7417 | above_inter: Vec<bool>, |
| 7418 | left_inter: Vec<bool>, |
| 7419 | /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME` |
| 7420 | /// alphabet) the block above/left of this column/row coded, or `-1` for |
| 7421 | /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context |
| 7422 | /// functions (`mvstack::ref_ctx` family) need the real reference, not |
| 7423 | /// just "was it inter" (lane-av1refs: every inter block used to be |
| 7424 | /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was |
| 7425 | /// enough). |
| 7426 | above_ref: Vec<i8>, |
| 7427 | left_ref: Vec<i8>, |
| 7428 | /// The block above/left's *second* reference frame when it was coded |
| 7429 | /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra -- |
| 7430 | /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx` |
| 7431 | /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s |
| 7432 | /// `i8`, once a compound `read_ref_frames` lands. |
| 7433 | /// lane-publish2 audit: the "always `None` today" note this doc used to |
| 7434 | /// carry is long stale -- compound blocks do occur, and |
| 7435 | /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference |
| 7436 | /// over their span right after [`Self::record_inter_rect_mi`]'s reset. |
| 7437 | /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every |
| 7438 | /// [`crate::mvstack::NeighbourRef`] construction (class |
| 7439 | /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong). |
| 7440 | above_ref1: Vec<Option<i8>>, |
| 7441 | left_ref1: Vec<Option<i8>>, |
| 7442 | /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context` |
| 7443 | /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`): |
| 7444 | /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or |
| 7445 | /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a |
| 7446 | /// single-ref one, or `0` for intra/unavailable -- lane-av1comp. |
| 7447 | above_comp_group_idx: Vec<u8>, |
| 7448 | left_comp_group_idx: Vec<u8>, |
| 7449 | above_compound_idx: Vec<u8>, |
| 7450 | left_compound_idx: Vec<u8>, |
| 7451 | /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or |
| 7452 | /// `3` = "no info": an intra neighbour or the frame's own border) of the |
| 7453 | /// block above/left of this column/row -- spec |
| 7454 | /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup. |
| 7455 | above_filter: Vec<[u8; 2]>, |
| 7456 | left_filter: Vec<[u8; 2]>, |
| 7457 | mi_cols: usize, |
| 7458 | mi_rows: usize, |
| 7459 | /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame, |
| 7460 | /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec |
| 7461 | /// 7.15) never filters an 8x8 luma block whose covering coded block read |
| 7462 | /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the |
| 7463 | /// grain [`Self::record_mi`] already writes at), read back at 8x8 |
| 7464 | /// granularity by [`apply_cdef`] since `skip` is constant across every |
| 7465 | /// mi cell one coded block covers. |
| 7466 | /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell. |
| 7467 | /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE |
| 7468 | /// the `skip` bit at this mi cell during this frame. A fresh |
| 7469 | /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode |
| 7470 | /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes |
| 7471 | /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip` |
| 7472 | /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and |
| 7473 | /// unobservable from the pixels alone. Counted by |
| 7474 | /// [`cdef_unwritten_skip_units`]. |
| 7475 | /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block |
| 7476 | /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`, |
| 7477 | /// which re-enables the loop filter at a prediction boundary between two |
| 7478 | /// skipped inter blocks (lane-mergefix r4). Written by |
| 7479 | /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin. |
| 7480 | /// Per-4x4-mi `(width, height)` in mi units of the coded block covering |
| 7481 | /// that cell -- the other half of `pu_edge`: libaom tests the edge |
| 7482 | /// coordinate against the block's size in the FILTERED plane's own |
| 7483 | /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b). |
| 7484 | blk_grid: Vec<BlkCell>, |
| 7485 | skip_grid_cols_mi: usize, |
| 7486 | /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder |
| 7487 | /// never splits a coded block's transform below its own size (round 2: |
| 7488 | /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its |
| 7489 | /// transform size, spec 7.14's `get_transform_size`/`get_filter_level` |
| 7490 | /// edge-length lookup (`apply_deblock`). |
| 7491 | tx_grid: Vec<u8>, |
| 7492 | /// The transform HEIGHT companion to [`Self::tx_grid`]'s width -- |
| 7493 | /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal |
| 7494 | /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT). |
| 7495 | tx_h_grid: Vec<u8>, |
| 7496 | /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4. |
| 7497 | /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the |
| 7498 | /// largest transform covering the subsampled BLOCK, capped at 32x32. It |
| 7499 | /// does NOT follow luma's `tx_depth` split, so deriving it as |
| 7500 | /// `tx_grid / 2` invented chroma transform edges the deblocker then |
| 7501 | /// filtered (32x16 frames, U plane, seeds 42/47). Written from the |
| 7502 | /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place |
| 7503 | /// every caller routes through. |
| 7504 | uv_tx_grid: Vec<u8>, |
| 7505 | uv_tx_h_grid: Vec<u8>, |
| 7506 | /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` = |
| 7507 | /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` -- |
| 7508 | /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2) |
| 7509 | /// -- the loop filter's ref/mode delta lookup (spec 7.14.4 |
| 7510 | /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs: |
| 7511 | /// widened from a bare `is_inter` bool, which collapsed every non-`LAST` |
| 7512 | /// reference onto `LAST_FRAME`'s own delta). |
| 7513 | ref_grid: Vec<i8>, |
| 7514 | /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's |
| 7515 | /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`, |
| 7516 | /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s |
| 7517 | /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot |
| 7518 | /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots |
| 7519 | /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs |
| 7520 | /// to know which mode produced the value. |
| 7521 | delta_lf_grid: Vec<[i8; 4]>, |
| 7522 | /// The block above/left's own palette-Y size (0 = not a palette block) |
| 7523 | /// and its base colours -- `av1_get_palette_mode_ctx`/ |
| 7524 | /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette |
| 7525 | /// r2. UV has no equivalent yet (stage 2, unreconstructed). |
| 7526 | above_palette_size: Vec<u8>, |
| 7527 | left_palette_size: Vec<u8>, |
| 7528 | above_palette_colors: Vec<[u16; 8]>, |
| 7529 | left_palette_colors: Vec<[u16; 8]>, |
| 7530 | /// As the four fields above, for the neighbour's own chroma (U-channel |
| 7531 | /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`]) |
| 7532 | /// palette size/colours (lane-palette2 r1). |
| 7533 | above_palette_uv_size: Vec<u8>, |
| 7534 | left_palette_uv_size: Vec<u8>, |
| 7535 | above_palette_uv_colors: Vec<[u16; 8]>, |
| 7536 | left_palette_uv_colors: Vec<[u16; 8]>, |
| 7537 | /// This tile's own top-left corner, in 4x4 mode-info units (spec |
| 7538 | /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a |
| 7539 | /// neighbour" check compares against this instead of literal `0`, since a |
| 7540 | /// block at the tile's own top/left edge has no usable neighbour even |
| 7541 | /// though a decoded block sits there in the picture (spec `decode_tile`'s |
| 7542 | /// per-tile `clear_above_context`/`left_available`/`up_available`). |
| 7543 | /// `0` for a single-tile frame, matching every existing caller exactly. |
| 7544 | tile_row0_mi: usize, |
| 7545 | tile_col0_mi: usize, |
| 7546 | } |
| 7547 | |
| 7548 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 7549 | impl Neighbours { |
| 7550 | /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's |
| 7551 | /// true (unpadded) size in 4x4 mode-info units. |
| 7552 | fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self { |
| 7553 | // lane-sb128c r7: a 128x64 block at the bottom frame edge records its |
| 7554 | // neighbour state over the whole 64-row extent, past the frame's last |
| 7555 | // mi row (mi_rows 198, block rows 192..208). libaom's own context |
| 7556 | // buffers are superblock-aligned for exactly that reason |
| 7557 | // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the |
| 7558 | // side arrays to a superblock multiple and leave those cells unread -- |
| 7559 | // every availability check uses the true `mi_rows`/`mi_cols` below. |
| 7560 | let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI); |
| 7561 | let (cols, rows) = ( |
| 7562 | cols.next_multiple_of(sb_sub), |
| 7563 | rows.next_multiple_of(sb_sub), |
| 7564 | ); |
| 7565 | Self { |
| 7566 | above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)], |
| 7567 | left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)], |
| 7568 | above_mode: vec![DC_PRED; cols], |
| 7569 | left_mode: vec![DC_PRED; rows], |
| 7570 | above_uv_mode: vec![DC_PRED; cols], |
| 7571 | left_uv_mode: vec![DC_PRED; rows], |
| 7572 | above_side: vec![NO_NEIGHBOUR_SIDE; cols], |
| 7573 | left_side: vec![NO_NEIGHBOUR_SIDE; rows], |
| 7574 | above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)], |
| 7575 | left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)], |
| 7576 | sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)], |
| 7577 | sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)], |
| 7578 | uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)], |
| 7579 | uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)], |
| 7580 | uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)], |
| 7581 | uv_grid_cols: cols * (SUB / MI), |
| 7582 | above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], |
| 7583 | left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], |
| 7584 | // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an |
| 7585 | // 8x8 inter leaf's left neighbour is the OTHER leaf row of the |
| 7586 | // 16x16 block beside it, which a SUB-grid slot cannot name |
| 7587 | // (class context-read-from-one-cell). |
| 7588 | above_skip: vec![false; cols * (SUB / MI)], |
| 7589 | left_skip: vec![false; rows * (SUB / MI)], |
| 7590 | above_skip_mode: vec![false; cols * (SUB / MI)], |
| 7591 | left_skip_mode: vec![false; rows * (SUB / MI)], |
| 7592 | above_inter: vec![false; cols * (SUB / MI)], |
| 7593 | left_inter: vec![false; rows * (SUB / MI)], |
| 7594 | above_ref: vec![-1; cols * (SUB / MI)], |
| 7595 | left_ref: vec![-1; rows * (SUB / MI)], |
| 7596 | above_ref1: vec![None; cols * (SUB / MI)], |
| 7597 | left_ref1: vec![None; rows * (SUB / MI)], |
| 7598 | above_comp_group_idx: vec![0; cols * (SUB / MI)], |
| 7599 | left_comp_group_idx: vec![0; rows * (SUB / MI)], |
| 7600 | above_compound_idx: vec![0; cols * (SUB / MI)], |
| 7601 | left_compound_idx: vec![0; rows * (SUB / MI)], |
| 7602 | above_filter: vec![[3u8; 2]; cols * (SUB / MI)], |
| 7603 | left_filter: vec![[3u8; 2]; rows * (SUB / MI)], |
| 7604 | mi_cols, |
| 7605 | mi_rows, |
| 7606 | blk_grid: vec![ |
| 7607 | BlkCell { skip: false, written: false, org: [0; 2], dim: [1; 2] }; |
| 7608 | cols * (SUB / MI) * rows * (SUB / MI) |
| 7609 | ], |
| 7610 | skip_grid_cols_mi: cols * (SUB / MI), |
| 7611 | tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], |
| 7612 | tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], |
| 7613 | uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], |
| 7614 | uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], |
| 7615 | ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)], |
| 7616 | delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)], |
| 7617 | above_palette_size: vec![0; cols * (SUB / MI)], |
| 7618 | left_palette_size: vec![0; rows * (SUB / MI)], |
| 7619 | above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)], |
| 7620 | left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)], |
| 7621 | above_palette_uv_size: vec![0; cols * (SUB / MI)], |
| 7622 | left_palette_uv_size: vec![0; rows * (SUB / MI)], |
| 7623 | above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)], |
| 7624 | left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)], |
| 7625 | tile_row0_mi: 0, |
| 7626 | tile_col0_mi: 0, |
| 7627 | } |
| 7628 | } |
| 7629 | |
| 7630 | /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this |
| 7631 | /// tile's own column span (`col1_mi` exclusive), plus recording |
| 7632 | /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every |
| 7633 | /// availability check below. Left context resets every superblock row |
| 7634 | /// regardless of tile ([`Self::start_row`], already called once per SB |
| 7635 | /// row by every caller) so it needs no tile-specific reset here. |
| 7636 | fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) { |
| 7637 | // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction |
| 7638 | // are tile-relative, same as every other neighbour lookup here. |
| 7639 | fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi))); |
| 7640 | self.tile_row0_mi = row0_mi; |
| 7641 | self.tile_col0_mi = col0_mi; |
| 7642 | let end = col1_mi.min(self.above.len()); |
| 7643 | for i in col0_mi.min(end)..end { |
| 7644 | self.above[i] = Default::default(); |
| 7645 | self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8; |
| 7646 | } |
| 7647 | let (sc0, sc1) = ( |
| 7648 | col0_mi / (SUB / MI), |
| 7649 | (col1_mi / (SUB / MI)).min(self.above_mode.len()), |
| 7650 | ); |
| 7651 | for i in sc0.min(sc1)..sc1 { |
| 7652 | self.above_mode[i] = DC_PRED; |
| 7653 | self.above_side[i] = NO_NEIGHBOUR_SIDE; |
| 7654 | } |
| 7655 | // lane-inter8 r2: the inter bands are mi-granular, so they reset over |
| 7656 | // the tile's own mi column span directly. |
| 7657 | let mend = col1_mi.min(self.above_skip.len()); |
| 7658 | for i in col0_mi.min(mend)..mend { |
| 7659 | self.above_skip[i] = false; |
| 7660 | self.above_skip_mode[i] = false; |
| 7661 | self.above_inter[i] = false; |
| 7662 | self.above_ref[i] = -1; |
| 7663 | self.above_ref1[i] = None; |
| 7664 | self.above_comp_group_idx[i] = 0; |
| 7665 | self.above_compound_idx[i] = 0; |
| 7666 | self.above_filter[i] = [3u8; 2]; |
| 7667 | } |
| 7668 | // lane-sub8 r6: the mi-granular column maps are per tile too -- a |
| 7669 | // stale `(row, mode)` from the tile to the LEFT names an mi row this |
| 7670 | // tile's first block would read as its own above neighbour. |
| 7671 | let mcol_end = col1_mi.min(self.sub8_mode_col.len()); |
| 7672 | for i in col0_mi.min(mcol_end)..mcol_end { |
| 7673 | self.sub8_mode_col[i] = (u16::MAX, 0); |
| 7674 | self.uv_mode_col[i] = (u16::MAX, 0); |
| 7675 | } |
| 7676 | // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row |
| 7677 | // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`, |
| 7678 | // not zero) -- without it a second tile column reads the first one's |
| 7679 | // resolved transform sizes as its own above context. |
| 7680 | let tend = col1_mi.min(self.above_txfm.len()); |
| 7681 | for i in col0_mi.min(tend)..tend { |
| 7682 | self.above_txfm[i] = TXFM_CTX_INIT; |
| 7683 | } |
| 7684 | } |
| 7685 | |
| 7686 | /// Writes a just-decoded block's own palette-Y size/colours (`size == 0` |
| 7687 | /// for a non-palette block, clearing any stale neighbour state) into every |
| 7688 | /// [`SUB`]-grid cell it covers on both the above and left edges -- |
| 7689 | /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's |
| 7690 | /// call sites are all square blocks). |
| 7691 | fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) { |
| 7692 | self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors); |
| 7693 | } |
| 7694 | |
| 7695 | /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`) |
| 7696 | /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs |
| 7697 | /// [`Self::record`]): a true rect strip's above/left neighbour spans |
| 7698 | /// differ. |
| 7699 | fn record_palette_y_rect( |
| 7700 | &mut self, |
| 7701 | mi: (usize, usize), |
| 7702 | w: usize, |
| 7703 | h: usize, |
| 7704 | size: usize, |
| 7705 | colors: [u16; 8], |
| 7706 | ) { |
| 7707 | let (r, c) = mi; |
| 7708 | if crate::envflags::env_flag!("EC_PALPUB") { |
| 7709 | eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}"); |
| 7710 | } |
| 7711 | // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size` |
| 7712 | // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi |
| 7713 | // cell immediately left of the block, not its 16px [`SUB`] cell. The |
| 7714 | // old SUB grid let a 16x8 strip pair share one slot, so the second |
| 7715 | // strip of mi(0,8) read the FIRST strip's palette size and the colour |
| 7716 | // cache came out one entry short (class [[context-read-from-one-cell]]). |
| 7717 | for cell in 0..(w / MI).max(1) { |
| 7718 | if let Some(e) = self.above_palette_size.get_mut(c + cell) { |
| 7719 | *e = size as u8; |
| 7720 | // lane-publish2: spec 5.11.46 `get_palette_cache` reads a |
| 7721 | // neighbour's colours only where its palette size > 0, so a |
| 7722 | // non-palette block need not stamp 16 bytes of zeroes here. |
| 7723 | if size > 0 { |
| 7724 | self.above_palette_colors[c + cell] = colors; |
| 7725 | } |
| 7726 | } |
| 7727 | } |
| 7728 | for cell in 0..(h / MI).max(1) { |
| 7729 | if let Some(e) = self.left_palette_size.get_mut(r + cell) { |
| 7730 | *e = size as u8; |
| 7731 | if size > 0 { |
| 7732 | self.left_palette_colors[r + cell] = colors; |
| 7733 | } |
| 7734 | } |
| 7735 | } |
| 7736 | } |
| 7737 | |
| 7738 | /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left |
| 7739 | /// neighbours that are themselves a palette-Y block, plus |
| 7740 | /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour |
| 7741 | /// cache (pred_common.c:73). |
| 7742 | /// |
| 7743 | /// The SB-top-row exclusion of the above neighbour (`row % 64` in |
| 7744 | /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to |
| 7745 | /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain |
| 7746 | /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to |
| 7747 | /// the ctx too made every superblock in the frame's second SB row read |
| 7748 | /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real |
| 7749 | /// palette block decoded as "no palette" and the tile desynced from |
| 7750 | /// there (class [[cdf-row-held-constant]]). |
| 7751 | fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) { |
| 7752 | self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI))) |
| 7753 | } |
| 7754 | |
| 7755 | /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a |
| 7756 | /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache` |
| 7757 | /// drops the above neighbour on a 64-px superblock boundary |
| 7758 | /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the |
| 7759 | /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the |
| 7760 | /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of |
| 7761 | /// every strip in an SB's top cell row, which libaom does not do. |
| 7762 | fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) { |
| 7763 | let (r, c) = mi; |
| 7764 | let above_ok = r % 16 != 0; |
| 7765 | // `xd->above_mbmi` exists for every row but the tile's own first. |
| 7766 | let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0; |
| 7767 | let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 { |
| 7768 | (usize::from(self.above_palette_size[c]), self.above_palette_colors[c]) |
| 7769 | } else { |
| 7770 | (0, [0u16; 8]) |
| 7771 | }; |
| 7772 | // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which |
| 7773 | // is NULL whenever the block sits at its TILE's own left column |
| 7774 | // (`left_available`), not the frame's -- without this guard a second |
| 7775 | // tile column reads the previous tile's palette colours into its cache |
| 7776 | // and its `palette_y_mode` ctx. |
| 7777 | let left_ok = c > self.tile_col0_mi; |
| 7778 | let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 { |
| 7779 | (usize::from(self.left_palette_size[r]), self.left_palette_colors[r]) |
| 7780 | } else { |
| 7781 | (0, [0u16; 8]) |
| 7782 | }; |
| 7783 | let ctx = usize::from(above_is_palette) + usize::from(left_n > 0); |
| 7784 | let mut cache = Vec::with_capacity(16); |
| 7785 | let push_dedup = |cache: &mut Vec<u16>, v: u16| { |
| 7786 | if cache.last() != Some(&v) { |
| 7787 | cache.push(v); |
| 7788 | } |
| 7789 | }; |
| 7790 | let (mut ai, mut li) = (0usize, 0usize); |
| 7791 | while ai < above_n && li < left_n { |
| 7792 | let (va, vl) = (above_colors[ai], left_colors[li]); |
| 7793 | if vl < va { |
| 7794 | push_dedup(&mut cache, vl); |
| 7795 | li += 1; |
| 7796 | } else { |
| 7797 | push_dedup(&mut cache, va); |
| 7798 | ai += 1; |
| 7799 | if vl == va { |
| 7800 | li += 1; |
| 7801 | } |
| 7802 | } |
| 7803 | } |
| 7804 | while ai < above_n { |
| 7805 | push_dedup(&mut cache, above_colors[ai]); |
| 7806 | ai += 1; |
| 7807 | } |
| 7808 | while li < left_n { |
| 7809 | push_dedup(&mut cache, left_colors[li]); |
| 7810 | li += 1; |
| 7811 | } |
| 7812 | (ctx, cache) |
| 7813 | } |
| 7814 | |
| 7815 | /// As [`Self::record_palette_y`], for a just-decoded block's own chroma |
| 7816 | /// (U-channel) palette size/colours -- `size == 0` clears stale state the |
| 7817 | /// same way (lane-palette2 r1). |
| 7818 | fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) { |
| 7819 | self.record_palette_uv_rect( |
| 7820 | (at.0 * (SUB / MI), at.1 * (SUB / MI)), |
| 7821 | side, |
| 7822 | side, |
| 7823 | size, |
| 7824 | colors, |
| 7825 | ); |
| 7826 | } |
| 7827 | |
| 7828 | /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`) |
| 7829 | /// extents, in LUMA pixels (lane-palette2 r4, same convention as |
| 7830 | /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at |
| 7831 | /// luma resolution regardless of which plane the recorded state is for). |
| 7832 | fn record_palette_uv_rect( |
| 7833 | &mut self, |
| 7834 | mi: (usize, usize), |
| 7835 | w: usize, |
| 7836 | h: usize, |
| 7837 | size: usize, |
| 7838 | colors: [u16; 8], |
| 7839 | ) { |
| 7840 | let (r, c) = mi; |
| 7841 | // mi granularity, see [`Self::record_palette_y_rect`]. |
| 7842 | for cell in 0..(w / MI).max(1) { |
| 7843 | if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) { |
| 7844 | *e = size as u8; |
| 7845 | if size > 0 { |
| 7846 | self.above_palette_uv_colors[c + cell] = colors; |
| 7847 | } |
| 7848 | } |
| 7849 | } |
| 7850 | for cell in 0..(h / MI).max(1) { |
| 7851 | if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) { |
| 7852 | *e = size as u8; |
| 7853 | if size > 0 { |
| 7854 | self.left_palette_uv_colors[r + cell] = colors; |
| 7855 | } |
| 7856 | } |
| 7857 | } |
| 7858 | } |
| 7859 | |
| 7860 | /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel |
| 7861 | /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs |
| 7862 | /// no neighbour lookup at all (it is this block's own just-decided Y |
| 7863 | /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`), |
| 7864 | /// so only the cache is wanted here. |
| 7865 | fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> { |
| 7866 | self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI))) |
| 7867 | } |
| 7868 | |
| 7869 | /// [`Self::palette_uv_cache`] with the block's real mi row -- see |
| 7870 | /// [`Self::palette_ctx_and_cache_mi`]. |
| 7871 | fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> { |
| 7872 | let (r, c) = mi; |
| 7873 | let above_ok = r % 16 != 0; |
| 7874 | let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 { |
| 7875 | (usize::from(self.above_palette_uv_size[c]), self.above_palette_uv_colors[c]) |
| 7876 | } else { |
| 7877 | (0, [0u16; 8]) |
| 7878 | }; |
| 7879 | // Same tile-relative left availability as the luma cache above. |
| 7880 | let left_ok = c > self.tile_col0_mi; |
| 7881 | let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 { |
| 7882 | (usize::from(self.left_palette_uv_size[r]), self.left_palette_uv_colors[r]) |
| 7883 | } else { |
| 7884 | (0, [0u16; 8]) |
| 7885 | }; |
| 7886 | let mut cache = Vec::with_capacity(16); |
| 7887 | let push_dedup = |cache: &mut Vec<u16>, v: u16| { |
| 7888 | if cache.last() != Some(&v) { |
| 7889 | cache.push(v); |
| 7890 | } |
| 7891 | }; |
| 7892 | let (mut ai, mut li) = (0usize, 0usize); |
| 7893 | while ai < above_n && li < left_n { |
| 7894 | let (va, vl) = (above_colors[ai], left_colors[li]); |
| 7895 | if vl < va { |
| 7896 | push_dedup(&mut cache, vl); |
| 7897 | li += 1; |
| 7898 | } else { |
| 7899 | push_dedup(&mut cache, va); |
| 7900 | ai += 1; |
| 7901 | if vl == va { |
| 7902 | li += 1; |
| 7903 | } |
| 7904 | } |
| 7905 | } |
| 7906 | while ai < above_n { |
| 7907 | push_dedup(&mut cache, above_colors[ai]); |
| 7908 | ai += 1; |
| 7909 | } |
| 7910 | while li < left_n { |
| 7911 | push_dedup(&mut cache, left_colors[li]); |
| 7912 | li += 1; |
| 7913 | } |
| 7914 | cache |
| 7915 | } |
| 7916 | |
| 7917 | /// Marks every 4x4 mi cell a just-decoded coded block covers with its own |
| 7918 | /// transform width (in pixels) and `is_inter` flag -- the loop filter's |
| 7919 | /// per-edge lookup (`apply_deblock`), filled at the same call sites and |
| 7920 | /// units as [`Self::fill_skip_grid`]. |
| 7921 | fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) { |
| 7922 | self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx); |
| 7923 | } |
| 7924 | |
| 7925 | /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions |
| 7926 | /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi` |
| 7927 | /// != `h_mi`); `tx_px` still names a single scalar (this decoder's |
| 7928 | /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a |
| 7929 | /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked |
| 7930 | /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent). |
| 7931 | /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a |
| 7932 | /// transform-unit edge but NOT a prediction-unit edge is not filtered when |
| 7933 | /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this |
| 7934 | /// block's published transform extent to its own size is exactly that |
| 7935 | /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape |
| 7936 | /// that needs it is the 128 root, whose chroma extent (64) is the one |
| 7937 | /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is |
| 7938 | /// never suppressed (libaom's `is_inter_block` term), so this is called |
| 7939 | /// only from the skipped-inter branch. |
| 7940 | fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) { |
| 7941 | let (mi_r, mi_c) = at_mi; |
| 7942 | let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8); |
| 7943 | for rr in 0..h_mi { |
| 7944 | let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; |
| 7945 | fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w); |
| 7946 | fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h); |
| 7947 | } |
| 7948 | } |
| 7949 | |
| 7950 | fn fill_lf_grid_rect( |
| 7951 | &mut self, |
| 7952 | at_mi: (usize, usize), |
| 7953 | w_mi: usize, |
| 7954 | h_mi: usize, |
| 7955 | tx_px: u8, |
| 7956 | tx_h_px: u8, |
| 7957 | ref_frame: i8, fctx: &crate::decode::FrameCtx, |
| 7958 | ) { |
| 7959 | let (mi_r, mi_c) = at_mi; |
| 7960 | // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is |
| 7961 | // half its luma one (min 4 px, the smallest transform), capped at |
| 7962 | // TX_32X32 -- independent of this block's luma `tx_depth`. |
| 7963 | let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8; |
| 7964 | let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8; |
| 7965 | if crate::envflags::env_flag!("EC_TXGRID_TRACE") { |
| 7966 | 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}"); |
| 7967 | } |
| 7968 | crate::census::tx(tx_px, tx_h_px); |
| 7969 | let cur = fctx.current_delta_lf.with(|c| c.get()); |
| 7970 | let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) { |
| 7971 | std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8) |
| 7972 | } else { |
| 7973 | [cur[0].clamp(-63, 63) as i8; 4] |
| 7974 | }; |
| 7975 | for rr in 0..h_mi { |
| 7976 | let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; |
| 7977 | fill_span(&mut self.tx_grid, start, w_mi, tx_px); |
| 7978 | fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px); |
| 7979 | fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w); |
| 7980 | fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h); |
| 7981 | fill_span(&mut self.ref_grid, start, w_mi, ref_frame); |
| 7982 | fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot); |
| 7983 | } |
| 7984 | if fctx.intra_only.with(std::cell::Cell::get) { |
| 7985 | // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size, |
| 7986 | // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi), |
| 7987 | // xd)` for EVERY block, an intra-only frame's included, and |
| 7988 | // `get_tx_size_context` / `txfm_partition_context` read those two |
| 7989 | // `TXFM_CONTEXT` bands. This grid carries the same transform size |
| 7990 | // over the same footprint, so the publish is this write: the |
| 7991 | // `skip && is_inter` term is 0 for every intra-only block that is |
| 7992 | // not an intrabc one, and the bodies that can code an intrabc |
| 7993 | // block publish their own (the term is then the BLOCK size, a value |
| 7994 | // this grid cannot express -- see `decode_block`/`decode_leaf8`). |
| 7995 | // Inter frames publish at their own sites and are excluded here |
| 7996 | // because their skipped-block term needs the block size too. |
| 7997 | txfm_partition_update_rect( |
| 7998 | self, |
| 7999 | at_mi, |
| 8000 | (tx_px as usize, tx_h_px as usize), |
| 8001 | (w_mi * MI, h_mi * MI), |
| 8002 | ); |
| 8003 | // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`), |
| 8004 | // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size |
| 8005 | // instead of its transform band. Every block stamps its own cells |
| 8006 | // here; the intrabc bodies re-stamp theirs `true` afterwards |
| 8007 | // (`record_intrabc_inter_bands`). |
| 8008 | for i in 0..w_mi { |
| 8009 | if let Some(cell) = self.above_inter.get_mut(mi_c + i) { |
| 8010 | *cell = false; |
| 8011 | } |
| 8012 | } |
| 8013 | for i in 0..h_mi { |
| 8014 | if let Some(cell) = self.left_inter.get_mut(mi_r + i) { |
| 8015 | *cell = false; |
| 8016 | } |
| 8017 | } |
| 8018 | } |
| 8019 | // lane-av1-intrabc r4: publish this coded block's own mi footprint |
| 8020 | // into the intrabc MV grid's block-COVERAGE map -- every coded block, |
| 8021 | // not just the intrabc ones. A later intrabc block's DV predictor is |
| 8022 | // built by libaom's own row/col scans over `xd->mi[]`, which holds an |
| 8023 | // `MB_MODE_INFO` for EVERY block and steps by |
| 8024 | // `mi_size_wide/height[candidate->bsize]`; without this footprint a |
| 8025 | // non-intrabc neighbour reads as uncovered and the scan advances it |
| 8026 | // by one cell instead of by its real width. |
| 8027 | fctx.intrabc_mi_grid.with(|g| { |
| 8028 | if let Some((grid, _, _)) = g.borrow_mut().as_mut() { |
| 8029 | grid.cover_rect(mi_r, mi_c, w_mi, h_mi); |
| 8030 | } |
| 8031 | }); |
| 8032 | } |
| 8033 | |
| 8034 | /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span. |
| 8035 | /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split |
| 8036 | /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps |
| 8037 | /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform. |
| 8038 | /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv |
| 8039 | /// dims from the LEAF span and so invented chroma transform edges the |
| 8040 | /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid` |
| 8041 | /// are already correct from the block's own fill over the same span. |
| 8042 | fn fill_lf_grid_leaf_luma( |
| 8043 | &mut self, |
| 8044 | at_mi: (usize, usize), |
| 8045 | w_mi: usize, |
| 8046 | h_mi: usize, |
| 8047 | tx_px: u8, |
| 8048 | tx_h_px: u8, |
| 8049 | ) { |
| 8050 | let (mi_r, mi_c) = at_mi; |
| 8051 | if crate::envflags::env_flag!("EC_TXGRID_TRACE") { |
| 8052 | 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}"); |
| 8053 | } |
| 8054 | for rr in 0..h_mi { |
| 8055 | let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; |
| 8056 | fill_span(&mut self.tx_grid, start, w_mi, tx_px); |
| 8057 | fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px); |
| 8058 | } |
| 8059 | } |
| 8060 | |
| 8061 | /// Marks every 4x4 mi cell a just-decoded coded block covers with its |
| 8062 | /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and |
| 8063 | /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s |
| 8064 | /// own units, not [`Self::record`]'s [`SUB`]-grid ones). |
| 8065 | fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) { |
| 8066 | self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip); |
| 8067 | } |
| 8068 | |
| 8069 | /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1). |
| 8070 | fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) { |
| 8071 | let (mi_r, mi_c) = at_mi; |
| 8072 | if skip && w_mi != h_mi { |
| 8073 | hit!(RECT_SKIP_BAND_HITS); |
| 8074 | } |
| 8075 | // lane-census: an INTRA frame's blocks never reach the inter |
| 8076 | // publisher, and this one is what every coded block writes. |
| 8077 | crate::census::block_intra_frame(w_mi, h_mi, skip); |
| 8078 | for rr in 0..h_mi { |
| 8079 | let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; |
| 8080 | fill_span( |
| 8081 | &mut self.blk_grid, |
| 8082 | start, |
| 8083 | w_mi, |
| 8084 | BlkCell { |
| 8085 | skip, |
| 8086 | written: true, |
| 8087 | org: [mi_r as u16, mi_c as u16], |
| 8088 | dim: [w_mi as u8, h_mi as u8], |
| 8089 | }, |
| 8090 | ); |
| 8091 | } |
| 8092 | } |
| 8093 | |
| 8094 | /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi |
| 8095 | /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test. |
| 8096 | /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4 |
| 8097 | /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can |
| 8098 | /// straddle the region with a mix of skip/non-skip blocks). |
| 8099 | /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike |
| 8100 | /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop |
| 8101 | /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a |
| 8102 | /// filtered edge's two sides are each exactly one coded block wide. |
| 8103 | fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool { |
| 8104 | self.blk_grid |
| 8105 | .get(mi_r * self.skip_grid_cols_mi + mi_c) |
| 8106 | .is_some_and(|c| c.skip) |
| 8107 | } |
| 8108 | |
| 8109 | /// The `skip_txfm` context of a block whose top-left mi cell is |
| 8110 | /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context` |
| 8111 | /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`, |
| 8112 | /// with an absent neighbour contributing 0. The mi grid is per tile, so |
| 8113 | /// row/column 0 is a tile edge and has no neighbour on that axis. |
| 8114 | fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize { |
| 8115 | usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c)) |
| 8116 | + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1)) |
| 8117 | } |
| 8118 | |
| 8119 | fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool { |
| 8120 | (0..2).all(|rr| { |
| 8121 | (0..2).all(|cc| { |
| 8122 | self.blk_grid |
| 8123 | .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc)) |
| 8124 | .is_some_and(|c| c.skip) |
| 8125 | }) |
| 8126 | }) |
| 8127 | } |
| 8128 | |
| 8129 | fn start_row(&mut self) { |
| 8130 | self.left.iter_mut().for_each(|l| *l = Default::default()); |
| 8131 | self.left_mode.iter_mut().for_each(|m| *m = DC_PRED); |
| 8132 | self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED); |
| 8133 | self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE); |
| 8134 | self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8); |
| 8135 | self.left_skip.iter_mut().for_each(|s| *s = false); |
| 8136 | self.left_skip_mode.iter_mut().for_each(|s| *s = false); |
| 8137 | self.left_inter.iter_mut().for_each(|i| *i = false); |
| 8138 | self.left_ref.iter_mut().for_each(|r| *r = -1); |
| 8139 | self.left_ref1.iter_mut().for_each(|r| *r = None); |
| 8140 | self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0); |
| 8141 | self.left_compound_idx.iter_mut().for_each(|r| *r = 0); |
| 8142 | self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]); |
| 8143 | // lane-sub8 r6: mi-granular row maps reset with the rest of the left |
| 8144 | // context (a tile/SB-row boundary has no left neighbour). |
| 8145 | self.sub8_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0)); |
| 8146 | self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0)); |
| 8147 | // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands |
| 8148 | // are per-mi maps like every other one here, so they reset with the |
| 8149 | // row too -- the left guard above is what actually stops a cross-tile |
| 8150 | // read, this keeps a stale colour out of the arrays at all. |
| 8151 | self.left_palette_size.iter_mut().for_each(|s| *s = 0); |
| 8152 | self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]); |
| 8153 | self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0); |
| 8154 | self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]); |
| 8155 | // lane-mergefix r2: `av1_zero_left_context` memsets |
| 8156 | // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at |
| 8157 | // every superblock row of every tile -- the var-tx left context does |
| 8158 | // NOT carry over a tile boundary (its `txfm_partition` ctx read the |
| 8159 | // previous tile column's last block otherwise). |
| 8160 | self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); |
| 8161 | } |
| 8162 | |
| 8163 | /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next |
| 8164 | /// block that reads it as a neighbour -- [`crate::tile`]'s |
| 8165 | /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec |
| 8166 | /// `get_ref_filter_type`'s "not this ref frame" case reads the same as |
| 8167 | /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the |
| 8168 | /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs |
| 8169 | /// the real value, not just `is_inter`). |
| 8170 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 8171 | fn record_inter( |
| 8172 | &mut self, |
| 8173 | at: (usize, usize), |
| 8174 | side: usize, |
| 8175 | skip: bool, |
| 8176 | is_inter: bool, |
| 8177 | ref_frame: i8, |
| 8178 | filter: [u8; 2], |
| 8179 | skip_mode: bool, |
| 8180 | ) { |
| 8181 | self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode); |
| 8182 | } |
| 8183 | |
| 8184 | /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid |
| 8185 | /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions |
| 8186 | /// r1: a true rectangular strip's above-context span (its own width) and |
| 8187 | /// left-context span (its own height) differ, unlike every caller before |
| 8188 | /// this round (class neighbour-votes-all-its-fields). |
| 8189 | #[allow(clippy::too_many_arguments)] |
| 8190 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 8191 | fn record_inter_rect( |
| 8192 | &mut self, |
| 8193 | at: (usize, usize), |
| 8194 | w_sub: usize, |
| 8195 | h_sub: usize, |
| 8196 | skip: bool, |
| 8197 | is_inter: bool, |
| 8198 | ref_frame: i8, |
| 8199 | filter: [u8; 2], |
| 8200 | skip_mode: bool, |
| 8201 | ) { |
| 8202 | let (r, c) = at; |
| 8203 | self.record_inter_rect_mi( |
| 8204 | (r * (SUB / MI), c * (SUB / MI)), |
| 8205 | w_sub / MI, |
| 8206 | h_sub / MI, |
| 8207 | skip, |
| 8208 | is_inter, |
| 8209 | ref_frame, |
| 8210 | filter, |
| 8211 | skip_mode, |
| 8212 | ); |
| 8213 | } |
| 8214 | |
| 8215 | /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an |
| 8216 | /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the |
| 8217 | /// side bands are written (and read) per mi. Every [`SUB`]-unit caller |
| 8218 | /// routes through the wrapper above. |
| 8219 | #[allow(clippy::too_many_arguments)] |
| 8220 | fn record_inter_rect_mi( |
| 8221 | &mut self, |
| 8222 | at_mi: (usize, usize), |
| 8223 | w_mi: usize, |
| 8224 | h_mi: usize, |
| 8225 | skip: bool, |
| 8226 | is_inter: bool, |
| 8227 | ref_frame: i8, |
| 8228 | filter: [u8; 2], |
| 8229 | skip_mode: bool, |
| 8230 | ) { |
| 8231 | let (r, c) = at_mi; |
| 8232 | crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip); |
| 8233 | // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY |
| 8234 | // writes for a whole block class): an INTER block left the luma mode |
| 8235 | // map untouched, so a later intra block's `get_intra_edge_filter_type` |
| 8236 | // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the |
| 8237 | // coarse SUB-row band, which still held a SMOOTH mode from an earlier |
| 8238 | // block in that pixel row -- the directional edge filter then ran at |
| 8239 | // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour, |
| 8240 | // which for an inter block is an INTER mode (>= NEARESTMV) and is |
| 8241 | // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups |
| 8242 | // already stamped it). |
| 8243 | // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for |
| 8244 | // an inter neighbour ("uv_mode is not set for inter blocks"), so the |
| 8245 | // uv map must read DC_PRED over an inter block's cells too. |
| 8246 | if is_inter { |
| 8247 | self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED); |
| 8248 | self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED); |
| 8249 | } |
| 8250 | let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME; |
| 8251 | self.above_skip[c..c + w_mi].fill(skip); |
| 8252 | self.above_skip_mode[c..c + w_mi].fill(skip_mode); |
| 8253 | self.above_inter[c..c + w_mi].fill(is_inter); |
| 8254 | self.above_ref[c..c + w_mi].fill(ref_frame); |
| 8255 | // The single-ref default: `record_compound_ctx_rect_mi` overwrites |
| 8256 | // this with the block's real second reference for a compound block, |
| 8257 | // called right after this one (lane-publish2 audit). |
| 8258 | self.above_ref1[c..c + w_mi].fill(None); |
| 8259 | // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s |
| 8260 | // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads |
| 8261 | // as `3`/`1` even though this block has no second reference. |
| 8262 | // `record_compound_ctx` overwrites this with the real bit for an |
| 8263 | // actual compound block's cells, called right after this one. |
| 8264 | self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 }); |
| 8265 | self.above_compound_idx[c..c + w_mi].fill(u8::from(altref)); |
| 8266 | self.above_filter[c..c + w_mi].fill(filter); |
| 8267 | self.left_skip[r..r + h_mi].fill(skip); |
| 8268 | self.left_skip_mode[r..r + h_mi].fill(skip_mode); |
| 8269 | self.left_inter[r..r + h_mi].fill(is_inter); |
| 8270 | self.left_ref[r..r + h_mi].fill(ref_frame); |
| 8271 | self.left_ref1[r..r + h_mi].fill(None); |
| 8272 | self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 }); |
| 8273 | self.left_compound_idx[r..r + h_mi].fill(u8::from(altref)); |
| 8274 | self.left_filter[r..r + h_mi].fill(filter); |
| 8275 | } |
| 8276 | |
| 8277 | /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with |
| 8278 | /// a real compound block's own `comp_group_idx`/`compound_idx` bits |
| 8279 | /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/ |
| 8280 | /// `get_comp_index_context`) -- called right after `record_inter` for |
| 8281 | /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also |
| 8282 | /// stamps `above_ref1`/`left_ref1` with the block's real second |
| 8283 | /// reference, which `record_inter` always clears to `None` (lane-av1comp: |
| 8284 | /// this is the one caller that actually knows it) -- so the next block's |
| 8285 | /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound |
| 8286 | /// neighbour instead of `record_inter`'s single-ref default. |
| 8287 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 8288 | fn record_compound_ctx( |
| 8289 | &mut self, |
| 8290 | at: (usize, usize), |
| 8291 | side: usize, |
| 8292 | ref1: i8, |
| 8293 | comp_group_idx: u8, |
| 8294 | compound_idx: u8, |
| 8295 | ) { |
| 8296 | self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx); |
| 8297 | } |
| 8298 | |
| 8299 | /// [`Self::record_compound_ctx`] with independent above/left extents, |
| 8300 | /// mirroring [`Self::record_inter_rect`] (lane-partitions r1). |
| 8301 | #[allow(clippy::too_many_arguments)] |
| 8302 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 8303 | fn record_compound_ctx_rect( |
| 8304 | &mut self, |
| 8305 | at: (usize, usize), |
| 8306 | w_sub: usize, |
| 8307 | h_sub: usize, |
| 8308 | ref1: i8, |
| 8309 | comp_group_idx: u8, |
| 8310 | compound_idx: u8, |
| 8311 | ) { |
| 8312 | let (r, c) = at; |
| 8313 | self.record_compound_ctx_rect_mi( |
| 8314 | (r * (SUB / MI), c * (SUB / MI)), |
| 8315 | w_sub / MI, |
| 8316 | h_sub / MI, |
| 8317 | ref1, |
| 8318 | comp_group_idx, |
| 8319 | compound_idx, |
| 8320 | ); |
| 8321 | } |
| 8322 | |
| 8323 | /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see |
| 8324 | /// [`Self::record_inter_rect_mi`]). |
| 8325 | fn record_compound_ctx_rect_mi( |
| 8326 | &mut self, |
| 8327 | at_mi: (usize, usize), |
| 8328 | w_mi: usize, |
| 8329 | h_mi: usize, |
| 8330 | ref1: i8, |
| 8331 | comp_group_idx: u8, |
| 8332 | compound_idx: u8, |
| 8333 | ) { |
| 8334 | let (r, c) = at_mi; |
| 8335 | crate::census::compound(); |
| 8336 | for cell in 0..w_mi { |
| 8337 | self.above_ref1[c + cell] = Some(ref1); |
| 8338 | self.above_comp_group_idx[c + cell] = comp_group_idx; |
| 8339 | self.above_compound_idx[c + cell] = compound_idx; |
| 8340 | } |
| 8341 | for cell in 0..h_mi { |
| 8342 | self.left_ref1[r + cell] = Some(ref1); |
| 8343 | self.left_comp_group_idx[r + cell] = comp_group_idx; |
| 8344 | self.left_compound_idx[r + cell] = compound_idx; |
| 8345 | } |
| 8346 | } |
| 8347 | |
| 8348 | /// The context of a block's partition symbol: delegates to the mi-precise |
| 8349 | /// reader (same pattern as `around`/`around_mi`) -- `above_side`/ |
| 8350 | /// `left_side` are only ever advanced in whole-[`SUB`] steps by |
| 8351 | /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which |
| 8352 | /// only touches the finer mi arrays -- leaves them stale for the *next* |
| 8353 | /// sibling's own partition symbol. |
| 8354 | fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize { |
| 8355 | let (r, c) = at; |
| 8356 | self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side) |
| 8357 | } |
| 8358 | |
| 8359 | /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a |
| 8360 | /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi` |
| 8361 | /// arrays so the second leaf sees the first leaf's own 8x8 side rather |
| 8362 | /// than the enclosing 16x16 slot's stale, shared state. |
| 8363 | fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize { |
| 8364 | 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side) |
| 8365 | + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side) |
| 8366 | } |
| 8367 | |
| 8368 | /// The gathered coded/DC-sign state of the blocks above and to the left |
| 8369 | /// of a block `side` samples across, per plane. |
| 8370 | fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] { |
| 8371 | self.around_mi((r * (SUB / MI), c * (SUB / MI)), side) |
| 8372 | } |
| 8373 | |
| 8374 | /// [`Self::around`] taking the block's position directly in 4x4 mode-info |
| 8375 | /// units, for the same reason [`Self::record_mi`] does. |
| 8376 | fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] { |
| 8377 | let side_mi = side / MI; |
| 8378 | // One pass over the cells accumulating all three planes, not one pass |
| 8379 | // per plane: the three planes of a cell live in the same |
| 8380 | // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same |
| 8381 | // cache lines three times (lane-publish). Clamp each edge to the true |
| 8382 | // frame extent: a block at the right/bottom edge may be padded beyond |
| 8383 | // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there. |
| 8384 | let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c)); |
| 8385 | let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r)); |
| 8386 | let mut out = [(false, false, 0i32); 3]; |
| 8387 | for cell in 0..above_mi { |
| 8388 | let above = &self.above[mi_c + cell]; |
| 8389 | for (plane, o) in out.iter_mut().enumerate() { |
| 8390 | o.0 |= above[plane].level != 0; |
| 8391 | o.2 += dc_vote(above[plane].dc); |
| 8392 | } |
| 8393 | } |
| 8394 | for cell in 0..left_mi { |
| 8395 | let left = &self.left[mi_r + cell]; |
| 8396 | for (plane, o) in out.iter_mut().enumerate() { |
| 8397 | o.1 |= left[plane].level != 0; |
| 8398 | o.2 += dc_vote(left[plane].dc); |
| 8399 | } |
| 8400 | } |
| 8401 | out |
| 8402 | } |
| 8403 | |
| 8404 | /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in |
| 8405 | /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric |
| 8406 | /// extent pattern for a true rectangular strip's own coefficient context. |
| 8407 | fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] { |
| 8408 | self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h) |
| 8409 | } |
| 8410 | |
| 8411 | /// [`Self::around_rect`] taking the block's position directly in 4x4 |
| 8412 | /// mode-info units, mirroring [`Self::around_mi`]. |
| 8413 | fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] { |
| 8414 | let (w_mi, h_mi) = (w / MI, h / MI); |
| 8415 | let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c)); |
| 8416 | let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r)); |
| 8417 | // [`Self::around_mi`]'s single pass, with the two extents split. |
| 8418 | let mut out = [(false, false, 0i32); 3]; |
| 8419 | for cell in 0..above_mi { |
| 8420 | let above = &self.above[mi_c + cell]; |
| 8421 | for (plane, o) in out.iter_mut().enumerate() { |
| 8422 | o.0 |= above[plane].level != 0; |
| 8423 | o.2 += dc_vote(above[plane].dc); |
| 8424 | } |
| 8425 | } |
| 8426 | for cell in 0..left_mi { |
| 8427 | let left = &self.left[mi_r + cell]; |
| 8428 | for (plane, o) in out.iter_mut().enumerate() { |
| 8429 | o.1 |= left[plane].level != 0; |
| 8430 | o.2 += dc_vote(left[plane].dc); |
| 8431 | } |
| 8432 | } |
| 8433 | if crate::envflags::env_flag!("EC_DCDUMP") { |
| 8434 | for (plane, o) in out.iter().enumerate() { |
| 8435 | let vote = o.2; |
| 8436 | let ab: Vec<String> = (0..above_mi) |
| 8437 | .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level)) |
| 8438 | .collect(); |
| 8439 | let lf: Vec<String> = (0..left_mi) |
| 8440 | .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level)) |
| 8441 | .collect(); |
| 8442 | eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(",")); |
| 8443 | } |
| 8444 | } |
| 8445 | out |
| 8446 | } |
| 8447 | |
| 8448 | /// The luma `txb_skip_ctx` of a transform unit smaller than its own block |
| 8449 | /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the |
| 8450 | /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own |
| 8451 | /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike |
| 8452 | /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real |
| 8453 | /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx` |
| 8454 | /// is always 0, spec's `plane_bsize == tx_size` branch). |
| 8455 | fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize { |
| 8456 | self.luma_skip_ctx_rect(at_mi, side_mi, side_mi) |
| 8457 | } |
| 8458 | |
| 8459 | /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi |
| 8460 | /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above |
| 8461 | /// context over `tx_size_wide` and the left one over `tx_size_high`. |
| 8462 | fn luma_skip_ctx_rect( |
| 8463 | &self, |
| 8464 | (mi_r, mi_c): (usize, usize), |
| 8465 | w_mi: usize, |
| 8466 | h_mi: usize, |
| 8467 | ) -> usize { |
| 8468 | let side_mi = w_mi; |
| 8469 | let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c)); |
| 8470 | let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r)); |
| 8471 | let mut top = 0u8; |
| 8472 | let mut left = 0u8; |
| 8473 | for cell in 0..above_mi { |
| 8474 | top |= self.above[mi_c + cell][0].level; |
| 8475 | } |
| 8476 | for cell in 0..left_mi { |
| 8477 | left |= self.left[mi_r + cell][0].level; |
| 8478 | } |
| 8479 | let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)]; |
| 8480 | if crate::envflags::env_flag!("EC_ECDUMP") { |
| 8481 | let ab: Vec<String> = |
| 8482 | (0..above_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect(); |
| 8483 | let lf: Vec<String> = |
| 8484 | (0..left_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect(); |
| 8485 | // lane-av1mix: the last few msac register states, so the |
| 8486 | // byte-position of the `all_zero` read can be matched against |
| 8487 | // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a |
| 8488 | // second run. |
| 8489 | let recent = crate::msac::symtrace::ecdump_recent(4) |
| 8490 | .iter() |
| 8491 | .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})")) |
| 8492 | .collect::<Vec<_>>() |
| 8493 | .join(" "); |
| 8494 | eprintln!( |
| 8495 | "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]", |
| 8496 | ab.join(","), lf.join(","), recent |
| 8497 | ); |
| 8498 | } |
| 8499 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 8500 | eprintln!( |
| 8501 | "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}", |
| 8502 | self.left.iter().map(|e| e[0].level).collect::<Vec<_>>() |
| 8503 | ); |
| 8504 | } |
| 8505 | ctx |
| 8506 | } |
| 8507 | |
| 8508 | /// Writes one coded block into every cell it covers, on both grids: the |
| 8509 | /// mode/side arrays up to `side`'s own width, and the coefficient-context |
| 8510 | /// arrays up to the true frame edge — the units past it are left at their |
| 8511 | /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own |
| 8512 | /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to |
| 8513 | /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`, |
| 8514 | /// not from this block's own side). |
| 8515 | fn record( |
| 8516 | &mut self, |
| 8517 | at: (usize, usize), |
| 8518 | side: usize, |
| 8519 | mode: usize, |
| 8520 | uv_mode: usize, |
| 8521 | grids: &[&[i32]; 3], |
| 8522 | ) { |
| 8523 | self.record_rect(at, side, side, mode, uv_mode, grids); |
| 8524 | } |
| 8525 | |
| 8526 | /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in |
| 8527 | /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by |
| 8528 | /// [`Self::partition_ctx`]) are the neighbour's own width/height per the |
| 8529 | /// spec's per-edge partition-context rule, so a true rectangular block |
| 8530 | /// naturally wants two different values here rather than one. |
| 8531 | /// Writes this block's luma `mode` into the mi-granular |
| 8532 | /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi |
| 8533 | /// position a *later* neighbour would read it from: the block's LAST mi |
| 8534 | /// row for every column it spans (what the block below reads via |
| 8535 | /// `mi(row-1, col)`) and its LAST mi column for every row (what the |
| 8536 | /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves |
| 8537 | /// read these back, and only when the recorded position is exactly their |
| 8538 | /// own neighbour -- see [`Self::sub8_mode_col`]'s doc. |
| 8539 | fn record_mode_mi( |
| 8540 | &mut self, |
| 8541 | mi_r: usize, |
| 8542 | mi_c: usize, |
| 8543 | mi_w: usize, |
| 8544 | mi_h: usize, |
| 8545 | mode: usize, |
| 8546 | ) { |
| 8547 | let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16); |
| 8548 | let mode = mode as u8; |
| 8549 | for cell in 0..mi_w { |
| 8550 | if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) { |
| 8551 | *slot = (last_r, mode); |
| 8552 | } |
| 8553 | } |
| 8554 | for cell in 0..mi_h { |
| 8555 | if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) { |
| 8556 | *slot = (last_c, mode); |
| 8557 | } |
| 8558 | } |
| 8559 | } |
| 8560 | |
| 8561 | /// The mi-exact above/left neighbour luma mode for a block whose top-left |
| 8562 | /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact |
| 8563 | /// mi position (then the coarse [`SUB`]-grid slot is right by |
| 8564 | /// construction). See [`Self::record_mode_mi`]. |
| 8565 | fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> { |
| 8566 | match self.sub8_mode_col.get(mi_c) { |
| 8567 | Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => Some(usize::from(m)), |
| 8568 | _ => None, |
| 8569 | } |
| 8570 | } |
| 8571 | |
| 8572 | fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> { |
| 8573 | match self.sub8_mode_row.get(mi_r) { |
| 8574 | Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => Some(usize::from(m)), |
| 8575 | _ => None, |
| 8576 | } |
| 8577 | } |
| 8578 | |
| 8579 | /// [`Self::record_mode_mi`] for the block's `uv_mode`, into |
| 8580 | /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`]. |
| 8581 | fn record_uv_mode_mi( |
| 8582 | &mut self, |
| 8583 | mi_r: usize, |
| 8584 | mi_c: usize, |
| 8585 | mi_w: usize, |
| 8586 | mi_h: usize, |
| 8587 | uv_mode: usize, |
| 8588 | ) { |
| 8589 | let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1); |
| 8590 | fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r as u16, uv_mode as u8)); |
| 8591 | fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c as u16, uv_mode as u8)); |
| 8592 | // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block |
| 8593 | // covers, so the chroma neighbour read below is a plain grid read. |
| 8594 | let stride = self.uv_grid_cols; |
| 8595 | let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c); |
| 8596 | for row in mi_r..=last_r { |
| 8597 | fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8); |
| 8598 | } |
| 8599 | } |
| 8600 | |
| 8601 | /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)` |
| 8602 | /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for |
| 8603 | /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no |
| 8604 | /// block has recorded the exact neighbouring mi. |
| 8605 | fn smooth_uv_neighbour( |
| 8606 | &self, |
| 8607 | mi_r: usize, |
| 8608 | mi_c: usize, |
| 8609 | r: usize, |
| 8610 | c: usize, |
| 8611 | fctx: &crate::decode::FrameCtx, |
| 8612 | ) -> bool { |
| 8613 | // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA |
| 8614 | // REFERENCE block, not off the mi that carries the chroma syntax. |
| 8615 | // `set_mi_row_col` (`blockd.h`) takes |
| 8616 | // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and |
| 8617 | // only then `chroma_above_mbmi = base_mi[-stride]` / |
| 8618 | // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at |
| 8619 | // the ODD mi, so without the snap we looked one mi row/column too far |
| 8620 | // down/right -- the mi-exact slot never matched and the coarse |
| 8621 | // fallback answered instead. Measured on a 4K 10-bit key frame, chroma |
| 8622 | // 8x4 at (688, 100) = mi (51, 344): libaom's |
| 8623 | // `get_intra_edge_filter_type` is 1 (the chroma block above it is |
| 8624 | // `UV_SMOOTH_PRED`), ours was 0, which flips |
| 8625 | // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`: |
| 8626 | // false for type 1, TRUE for type 0) and upsampled an edge libaom |
| 8627 | // leaves alone -- +1 on rows 2/3 of that block and every chroma block |
| 8628 | // predicting from it (class `context-read-from-one-cell`). |
| 8629 | // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded |
| 8630 | // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps |
| 8631 | // nothing, and the hardcoded snap read a 4x4 leaf's smooth |
| 8632 | // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf |
| 8633 | // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)). |
| 8634 | let snap_y = (1usize << ss_y(fctx)) - 1; |
| 8635 | let snap_x = (1usize << ss_x(fctx)) - 1; |
| 8636 | self.smooth_uv_neighbour_unsnapped(mi_r & !snap_y, mi_c & !snap_x, r, c) |
| 8637 | } |
| 8638 | |
| 8639 | /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e. |
| 8640 | /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness |
| 8641 | /// counter wants this: it measures how often the snap CHANGES the answer, |
| 8642 | /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every |
| 8643 | /// decode path uses the snapping form. |
| 8644 | fn smooth_uv_neighbour_unsnapped( |
| 8645 | &self, |
| 8646 | mi_r: usize, |
| 8647 | mi_c: usize, |
| 8648 | r: usize, |
| 8649 | c: usize, |
| 8650 | ) -> bool { |
| 8651 | // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the |
| 8652 | // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid |
| 8653 | // array that `start_tile` does not clear, so a block on a tile's first |
| 8654 | // mi row used to read the uv_mode of the block above it in the tile |
| 8655 | // ABOVE and filter its chroma edge at that neighbour's strength |
| 8656 | // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block |
| 8657 | // at chroma (120, 32), the top-right tile's first block). |
| 8658 | let have_above = mi_r > self.tile_row0_mi; |
| 8659 | let have_left = mi_c > self.tile_col0_mi; |
| 8660 | if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED |
| 8661 | || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED |
| 8662 | { |
| 8663 | hit!(UV_TILE_EDGE_SUPPRESSED_HITS); |
| 8664 | } |
| 8665 | // The mi grid is libaom's own read; the two maps below stay as the |
| 8666 | // fallback for cells no block has written (see [`Self::uv_mode_grid`]). |
| 8667 | let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> { |
| 8668 | (col < self.uv_grid_cols) |
| 8669 | .then(|| grid.get(row * self.uv_grid_cols + col).copied()) |
| 8670 | .flatten() |
| 8671 | .filter(|&m| m != u8::MAX) |
| 8672 | .map(usize::from) |
| 8673 | }; |
| 8674 | let above = match self.uv_mode_col.get(mi_c) { |
| 8675 | _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m, |
| 8676 | Some(&(row, m)) if have_above && usize::from(row) == mi_r - 1 => usize::from(m), |
| 8677 | _ if have_above => self.above_uv_mode[c], |
| 8678 | _ => DC_PRED, |
| 8679 | }; |
| 8680 | let left = match self.uv_mode_row.get(mi_r) { |
| 8681 | _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m, |
| 8682 | Some(&(col, m)) if have_left && usize::from(col) == mi_c - 1 => usize::from(m), |
| 8683 | _ if have_left => self.left_uv_mode[r], |
| 8684 | _ => DC_PRED, |
| 8685 | }; |
| 8686 | if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| { |
| 8687 | !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m) |
| 8688 | }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| { |
| 8689 | !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m) |
| 8690 | }) { |
| 8691 | hit!(UV_MODE_GRID_OVERRIDE_HITS); |
| 8692 | } |
| 8693 | // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs |
| 8694 | // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would |
| 8695 | // have been filtered at the wrong strength by the coarse map alone. |
| 8696 | if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] { |
| 8697 | hit!(UV_MODE_MI_OVERRIDE_HITS); |
| 8698 | } |
| 8699 | if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above)) |
| 8700 | || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left)) |
| 8701 | { |
| 8702 | hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS); |
| 8703 | } |
| 8704 | is_smooth_mode(above) || is_smooth_mode(left) |
| 8705 | } |
| 8706 | |
| 8707 | /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a |
| 8708 | /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse |
| 8709 | /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a |
| 8710 | /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them |
| 8711 | /// holding an OLDER, larger block's mode -- it only ever recorded into the |
| 8712 | /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the |
| 8713 | /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip |
| 8714 | /// whose left neighbour was a 16x8 leaf still read the stale row and picked |
| 8715 | /// a different CDF for the same mode value). |
| 8716 | /// lane-rectsplitx r2: availability-correct above/left luma modes for a |
| 8717 | /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi` |
| 8718 | /// only when `up_available` and `left_mbmi` only when `left_available`; |
| 8719 | /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they |
| 8720 | /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16 |
| 8721 | /// `left_mode` cell, so the second strip at tile column 0 read the FIRST |
| 8722 | /// strip's mode as its "left neighbour" (measured on the band fixture at |
| 8723 | /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row). |
| 8724 | fn modes_above_left_mi( |
| 8725 | &self, |
| 8726 | mi_r: usize, |
| 8727 | mi_c: usize, |
| 8728 | fallback: (usize, usize), |
| 8729 | ) -> (usize, usize) { |
| 8730 | let above = if mi_r > self.tile_row0_mi { |
| 8731 | self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0) |
| 8732 | } else { |
| 8733 | DC_PRED |
| 8734 | }; |
| 8735 | let left = if mi_c > self.tile_col0_mi { |
| 8736 | self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1) |
| 8737 | } else { |
| 8738 | DC_PRED |
| 8739 | }; |
| 8740 | (above, left) |
| 8741 | } |
| 8742 | |
| 8743 | /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability |
| 8744 | /// correct. The mi-exact lookups already refuse to cross a tile edge, but |
| 8745 | /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset |
| 8746 | /// per superblock row and never per tile, so the first block column of |
| 8747 | /// tile 2..N read the previous tile's mode as its left neighbour, and the |
| 8748 | /// above band survives across a tile ROW boundary the same way lane-mtfix's |
| 8749 | /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when |
| 8750 | /// `up_available`/`left_available` and uses DC_PRED otherwise |
| 8751 | /// ([`Self::modes_above_left_mi`]). |
| 8752 | fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) { |
| 8753 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); |
| 8754 | let (above, left) = |
| 8755 | self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r])); |
| 8756 | if above != self.above_mode[c] || left != self.left_mode[r] { |
| 8757 | hit!(MODE_MI_OVERRIDE_HITS); |
| 8758 | } |
| 8759 | if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above)) |
| 8760 | || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left)) |
| 8761 | { |
| 8762 | hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS); |
| 8763 | } |
| 8764 | // A neighbour the coarse band offered where the tile edge makes it |
| 8765 | // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`). |
| 8766 | if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED) |
| 8767 | || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED) |
| 8768 | { |
| 8769 | hit!(MODE_TILE_EDGE_COARSE_LEAKS); |
| 8770 | } |
| 8771 | (above, left) |
| 8772 | } |
| 8773 | |
| 8774 | fn record_rect( |
| 8775 | &mut self, |
| 8776 | at: (usize, usize), |
| 8777 | w: usize, |
| 8778 | h: usize, |
| 8779 | mode: usize, |
| 8780 | uv_mode: usize, |
| 8781 | grids: &[&[i32]; 3], |
| 8782 | ) { |
| 8783 | self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids); |
| 8784 | } |
| 8785 | |
| 8786 | /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a |
| 8787 | /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the |
| 8788 | /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed |
| 8789 | /// by the enclosing cell (a sub-16 extent writes none of them, exactly as |
| 8790 | /// the [`SUB`]-unit path does). |
| 8791 | fn record_rect_mi( |
| 8792 | &mut self, |
| 8793 | at_mi: (usize, usize), |
| 8794 | w: usize, |
| 8795 | h: usize, |
| 8796 | mode: usize, |
| 8797 | uv_mode: usize, |
| 8798 | grids: &[&[i32]; 3], |
| 8799 | ) { |
| 8800 | let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI)); |
| 8801 | // lane-inter4 r2: a strip whose own footprint runs past the frame's |
| 8802 | // last 16-px column/row stamps only the cells that exist (libaom's |
| 8803 | // arrays are padded past the frame and those cells are never read). |
| 8804 | for cell in 0..w / SUB { |
| 8805 | if c + cell >= self.above_mode.len() { |
| 8806 | break; |
| 8807 | } |
| 8808 | self.above_mode[c + cell] = mode; |
| 8809 | self.above_uv_mode[c + cell] = uv_mode; |
| 8810 | self.above_side[c + cell] = w; |
| 8811 | } |
| 8812 | for cell in 0..h / SUB { |
| 8813 | if r + cell >= self.left_mode.len() { |
| 8814 | break; |
| 8815 | } |
| 8816 | self.left_mode[r + cell] = mode; |
| 8817 | self.left_uv_mode[r + cell] = uv_mode; |
| 8818 | self.left_side[r + cell] = h; |
| 8819 | } |
| 8820 | self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode); |
| 8821 | self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode); |
| 8822 | self.record_mi_rect(at_mi, w, h, grids); |
| 8823 | } |
| 8824 | |
| 8825 | /// The coefficient-context half of [`Self::record`], taking the block's |
| 8826 | /// position directly in 4x4 mode-info units rather than [`SUB`]-grid |
| 8827 | /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at |
| 8828 | /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name. |
| 8829 | fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) { |
| 8830 | self.record_mi_rect(at_mi, side, side, grids); |
| 8831 | } |
| 8832 | |
| 8833 | /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents, |
| 8834 | /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]). |
| 8835 | fn record_mi_rect( |
| 8836 | &mut self, |
| 8837 | at_mi: (usize, usize), |
| 8838 | w: usize, |
| 8839 | h: usize, |
| 8840 | grids: &[&[i32]; 3], |
| 8841 | ) { |
| 8842 | let (mi_r, mi_c) = at_mi; |
| 8843 | let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane])); |
| 8844 | let (w_mi, h_mi) = (w / MI, h / MI); |
| 8845 | if crate::envflags::env_flag!("EC_ECPUB") { |
| 8846 | eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level); |
| 8847 | } |
| 8848 | fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8); |
| 8849 | fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8); |
| 8850 | // A chroma 4x4 unit straddling the true luma edge is still whole in |
| 8851 | // chroma's own halved grid, so libaom rounds the luma bound up to the |
| 8852 | // plane's own 4x4 unit before clamping a subsampled plane |
| 8853 | // (`av1_write_intra_coeffs_mb`, encodetxb.c). |
| 8854 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 8855 | let bound_h = [ |
| 8856 | self.mi_rows, |
| 8857 | round_up_even(self.mi_rows), |
| 8858 | round_up_even(self.mi_rows), |
| 8859 | ]; |
| 8860 | let bound_w = [ |
| 8861 | self.mi_cols, |
| 8862 | round_up_even(self.mi_cols), |
| 8863 | round_up_even(self.mi_cols), |
| 8864 | ]; |
| 8865 | // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows |
| 8866 | // past the padded side arrays (mi_rows 198, block rows 192..208); |
| 8867 | // libaom's own arrays are superblock-sized, so those cells simply |
| 8868 | // have no reader -- [`fill_span`] drops them, as the `break` did. |
| 8869 | // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane |
| 8870 | // predicate is three contiguous runs: all planes, chroma only, none |
| 8871 | // (lane-mi). |
| 8872 | let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r)); |
| 8873 | let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r)); |
| 8874 | let uv_only = [Neighbour::default(), states[1], states[2]]; |
| 8875 | fill_span(&mut self.left, mi_r, luma_h, states); |
| 8876 | fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only); |
| 8877 | fill_span( |
| 8878 | &mut self.left, |
| 8879 | mi_r + chroma_h, |
| 8880 | h_mi - chroma_h, |
| 8881 | [Neighbour::default(); 3], |
| 8882 | ); |
| 8883 | let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c)); |
| 8884 | let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c)); |
| 8885 | let uv_only_w = [Neighbour::default(), states[1], states[2]]; |
| 8886 | fill_span(&mut self.above, mi_c, luma_w, states); |
| 8887 | fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w); |
| 8888 | fill_span( |
| 8889 | &mut self.above, |
| 8890 | mi_c + chroma_w, |
| 8891 | w_mi - chroma_w, |
| 8892 | [Neighbour::default(); 3], |
| 8893 | ); |
| 8894 | } |
| 8895 | |
| 8896 | /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit |
| 8897 | /// inside a coded block whose luma transform is smaller than its own |
| 8898 | /// side (`TxMode::Select`): the real per-transform-unit coefficient |
| 8899 | /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the |
| 8900 | /// coarse per-block `tx_grid`/`fill_lf_grid` state |
| 8901 | /// [`Self::record_split_luma`] still writes once for the whole block. |
| 8902 | /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone -- |
| 8903 | /// the caller's own [`Self::record_split_luma`] call sets those once, |
| 8904 | /// at the block's own true side, not this TU's. |
| 8905 | fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) { |
| 8906 | self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid); |
| 8907 | } |
| 8908 | |
| 8909 | /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose |
| 8910 | /// uv plane block is several units (lane-sb128b r2: a 128x128 block's |
| 8911 | /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`). |
| 8912 | /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma |
| 8913 | /// coefficient-context arrays are indexed by luma mi, the convention |
| 8914 | /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge |
| 8915 | /// clamp included. |
| 8916 | fn record_mi_chroma( |
| 8917 | &mut self, |
| 8918 | (mi_r, mi_c): (usize, usize), |
| 8919 | w_px: usize, |
| 8920 | h_px: usize, |
| 8921 | plane: usize, |
| 8922 | grid: &[i32], |
| 8923 | ) { |
| 8924 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 8925 | let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); |
| 8926 | let state = neighbour_state(grid); |
| 8927 | for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) { |
| 8928 | self.left[mi_r + cell][plane] = state; |
| 8929 | } |
| 8930 | for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) { |
| 8931 | self.above[mi_c + cell][plane] = state; |
| 8932 | } |
| 8933 | } |
| 8934 | |
| 8935 | /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx |
| 8936 | /// r1): the above context spans the unit's width, the left context its |
| 8937 | /// height, which for a square unit is the same loop it always was. |
| 8938 | fn record_mi_luma_rect( |
| 8939 | &mut self, |
| 8940 | (mi_r, mi_c): (usize, usize), |
| 8941 | w_px: usize, |
| 8942 | h_px: usize, |
| 8943 | grid: &[i32], |
| 8944 | ) { |
| 8945 | let state = neighbour_state(grid); |
| 8946 | if crate::envflags::env_flag!("EC_ECPUB") { |
| 8947 | eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level); |
| 8948 | } |
| 8949 | for cell in 0..h_px / MI { |
| 8950 | if mi_r + cell < self.mi_rows { |
| 8951 | self.left[mi_r + cell][0] = state; |
| 8952 | } |
| 8953 | } |
| 8954 | for cell in 0..w_px / MI { |
| 8955 | if mi_c + cell < self.mi_cols { |
| 8956 | self.above[mi_c + cell][0] = state; |
| 8957 | } |
| 8958 | } |
| 8959 | } |
| 8960 | |
| 8961 | /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a |
| 8962 | /// block whose luma was decoded as several transform units through |
| 8963 | /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single |
| 8964 | /// whole-block luma write -- everything [`Self::record`] does except |
| 8965 | /// plane 0, which is already correct per-TU by the time this runs. |
| 8966 | fn record_split_luma( |
| 8967 | &mut self, |
| 8968 | at: (usize, usize), |
| 8969 | side: usize, |
| 8970 | mode: usize, |
| 8971 | uv_mode: usize, |
| 8972 | chroma_grids: [&[i32]; 2], |
| 8973 | ) { |
| 8974 | self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids); |
| 8975 | } |
| 8976 | |
| 8977 | /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`) |
| 8978 | /// extents in pixels (lane-rectsplit r1), the same relationship |
| 8979 | /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose |
| 8980 | /// luma transform split into several square units needs exactly this |
| 8981 | /// bookkeeping, at its own true rectangular extents. |
| 8982 | fn record_split_luma_rect( |
| 8983 | &mut self, |
| 8984 | at: (usize, usize), |
| 8985 | w: usize, |
| 8986 | h: usize, |
| 8987 | mode: usize, |
| 8988 | uv_mode: usize, |
| 8989 | chroma_grids: [&[i32]; 2], |
| 8990 | ) { |
| 8991 | let (r, c) = at; |
| 8992 | self.record_split_luma_rect_mi( |
| 8993 | (r * (SUB / MI), c * (SUB / MI)), |
| 8994 | w, |
| 8995 | h, |
| 8996 | mode, |
| 8997 | uv_mode, |
| 8998 | chroma_grids, |
| 8999 | ); |
| 9000 | } |
| 9001 | |
| 9002 | /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx |
| 9003 | /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse |
| 9004 | /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for |
| 9005 | /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the |
| 9006 | /// convention [`decode_block_rect4`] already established for 1:4 strips. |
| 9007 | fn record_split_luma_rect_mi( |
| 9008 | &mut self, |
| 9009 | at_mi: (usize, usize), |
| 9010 | w: usize, |
| 9011 | h: usize, |
| 9012 | mode: usize, |
| 9013 | uv_mode: usize, |
| 9014 | chroma_grids: [&[i32]; 2], |
| 9015 | ) { |
| 9016 | let (mi_r, mi_c) = at_mi; |
| 9017 | let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); |
| 9018 | for cell in 0..w.div_ceil(SUB) { |
| 9019 | if c + cell >= self.above_mode.len() { |
| 9020 | break; |
| 9021 | } |
| 9022 | self.above_mode[c + cell] = mode; |
| 9023 | self.above_uv_mode[c + cell] = uv_mode; |
| 9024 | self.above_side[c + cell] = w; |
| 9025 | } |
| 9026 | for cell in 0..h.div_ceil(SUB) { |
| 9027 | if r + cell >= self.left_mode.len() { |
| 9028 | break; |
| 9029 | } |
| 9030 | self.left_mode[r + cell] = mode; |
| 9031 | self.left_uv_mode[r + cell] = uv_mode; |
| 9032 | self.left_side[r + cell] = h; |
| 9033 | } |
| 9034 | |
| 9035 | let (w_mi, h_mi) = (w / MI, h / MI); |
| 9036 | self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode); |
| 9037 | self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode); |
| 9038 | fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8); |
| 9039 | fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8); |
| 9040 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 9041 | let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); |
| 9042 | for (plane_idx, grid) in chroma_grids.into_iter().enumerate() { |
| 9043 | let plane = plane_idx + 1; |
| 9044 | let state = neighbour_state(grid); |
| 9045 | for cell in 0..h_mi { |
| 9046 | if cell < h_mi.min(bound_h.saturating_sub(mi_r)) { |
| 9047 | self.left[mi_r + cell][plane] = state; |
| 9048 | } |
| 9049 | } |
| 9050 | for cell in 0..w_mi { |
| 9051 | if cell < w_mi.min(bound_w.saturating_sub(mi_c)) { |
| 9052 | self.above[mi_c + cell][plane] = state; |
| 9053 | } |
| 9054 | } |
| 9055 | } |
| 9056 | } |
| 9057 | } |
| 9058 | |
| 9059 | /// Reads one coded block's skip flag, luma mode, angle delta (if the mode |
| 9060 | /// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode` |
| 9061 | /// exactly — including its skip context, which the real key-frame writer |
| 9062 | /// always writes at a fixed context of zero (it never tracks a neighbour-based |
| 9063 | /// one for intra blocks; that is the inter-frame writer's rule instead). |
| 9064 | /// Refuses a nonzero angle delta: this decoder reconstructs the thirteen |
| 9065 | /// luma modes at their base angle only. Chroma is DC-only or, where CFL is |
| 9066 | /// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the |
| 9067 | /// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for |
| 9068 | /// plain DC chroma. |
| 9069 | /// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which |
| 9070 | /// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's |
| 9071 | /// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode |
| 9072 | /// instead (the defect commit 1a89ed9 fixed at the square sites). |
| 9073 | pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize { |
| 9074 | const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED]; |
| 9075 | filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi]) |
| 9076 | } |
| 9077 | |
| 9078 | /// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`, |
| 9079 | /// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32 |
| 9080 | /// bound (spec `filter_intra_mode_info` never reads a symbol there). |
| 9081 | pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> { |
| 9082 | match side { |
| 9083 | 4 => Some(0), |
| 9084 | 8 => Some(1), |
| 9085 | 16 => Some(2), |
| 9086 | 32 => Some(3), |
| 9087 | _ => None, |
| 9088 | } |
| 9089 | } |
| 9090 | |
| 9091 | /// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip |
| 9092 | /// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize |
| 9093 | /// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their |
| 9094 | /// own distinct `cdf::FILTER_INTRA` rows, classes 4/5. |
| 9095 | fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> { |
| 9096 | match (bw, bh) { |
| 9097 | (32, 16) => Some(4), |
| 9098 | (16, 32) => Some(5), |
| 9099 | // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= |
| 9100 | // 32", so a 16x8/8x16 strip reads the flag too -- returning `None` |
| 9101 | // here dropped that symbol on every DC_PRED strip of that size and |
| 9102 | // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder: |
| 9103 | // identical mode/uv_mode values, range 34808 vs the oracle's 40668). |
| 9104 | (16, 8) => Some(6), |
| 9105 | (8, 16) => Some(7), |
| 9106 | // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <= |
| 9107 | // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of |
| 9108 | // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0. |
| 9109 | (4, 8) => Some(8), |
| 9110 | (8, 4) => Some(9), |
| 9111 | // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair |
| 9112 | // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no |
| 9113 | // `use_filter_intra` symbol on those strips although aomenc writes |
| 9114 | // one for every DC_PRED block of that shape with |
| 9115 | // `--enable-filter-intra=1` (its default), silently desyncing the |
| 9116 | // tile (class symbol-consumption-gap). |
| 9117 | (32, 8) => Some(10), |
| 9118 | (8, 32) => Some(11), |
| 9119 | // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16 |
| 9120 | // strips), rows 17/16 of `default_filter_intra_cdfs`. |
| 9121 | (16, 4) => Some(12), |
| 9122 | (4, 16) => Some(13), |
| 9123 | _ if bw == bh => filter_intra_size_class(bw), |
| 9124 | _ => None, |
| 9125 | } |
| 9126 | } |
| 9127 | |
| 9128 | /// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <= |
| 9129 | /// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus |
| 9130 | /// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize] |
| 9131 | /// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past |
| 9132 | /// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise. |
| 9133 | pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> { |
| 9134 | palette_bsize_ctx_wh(side, side) |
| 9135 | } |
| 9136 | |
| 9137 | /// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip |
| 9138 | /// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's |
| 9139 | /// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes |
| 9140 | /// for ANY bsize, not just the square ones a hand-picked table happened to |
| 9141 | /// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned |
| 9142 | /// row breaks the moment its indexing field moves off the diagonal, and a |
| 9143 | /// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1 |
| 9144 | /// block dimension is a power of two, so `bw*bh` always is too and |
| 9145 | /// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own |
| 9146 | /// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`). |
| 9147 | fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> { |
| 9148 | // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the |
| 9149 | // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and |
| 9150 | // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx` |
| 9151 | // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as |
| 9152 | // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped |
| 9153 | // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame. |
| 9154 | if bw > 64 || bh > 64 || bw * bh < 64 { |
| 9155 | return None; |
| 9156 | } |
| 9157 | Some(((bw * bh) as u32).trailing_zeros() as usize - 6) |
| 9158 | } |
| 9159 | |
| 9160 | /// A just-decoded palette-Y block's own size, base colours (only the first |
| 9161 | /// `size` entries are real), and per-pixel colour-index map (`side*side`, |
| 9162 | /// row-major, each entry `< size`). |
| 9163 | struct PaletteY { |
| 9164 | size: usize, |
| 9165 | colors: [u16; 8], |
| 9166 | map: Vec<u8>, |
| 9167 | } |
| 9168 | |
| 9169 | /// As [`PaletteY`], for a just-decoded chroma palette block: one shared |
| 9170 | /// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is |
| 9171 | /// shared between U and V, both co-located after 4:2:0 subsampling) plus |
| 9172 | /// each plane's own base colours. |
| 9173 | struct PaletteUv { |
| 9174 | size: usize, |
| 9175 | u_colors: [u16; 8], |
| 9176 | v_colors: [u16; 8], |
| 9177 | map: Vec<u8>, |
| 9178 | } |
| 9179 | |
| 9180 | /// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by |
| 9181 | /// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s |
| 9182 | /// `get_unsigned_bits`, which is the same formula): smallest `n` with |
| 9183 | /// `2^n >= x`, `0` for `x <= 1`. |
| 9184 | pub(crate) fn ceil_log2(x: u32) -> u32 { |
| 9185 | if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() } |
| 9186 | } |
| 9187 | |
| 9188 | /// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as |
| 9189 | /// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`. |
| 9190 | fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize { |
| 9191 | let l = ceil_log2(n as u32); |
| 9192 | let m = (1usize << l) - n; |
| 9193 | let v = dec.literal(l - 1) as usize; |
| 9194 | if v < m { |
| 9195 | v |
| 9196 | } else { |
| 9197 | (v << 1) - m + dec.literal(1) as usize |
| 9198 | } |
| 9199 | } |
| 9200 | |
| 9201 | /// `merge_colors` (decodemv.c:462): interleaves the ascending `cached` |
| 9202 | /// colours (already-known, from the above/left neighbours) with the |
| 9203 | /// ascending `transmitted` ones (delta-coded off the wire) back into one |
| 9204 | /// ascending list of `cached.len() + transmitted.len()` colours -- a tied |
| 9205 | /// value picks the cached copy first, matching the C `<=`. |
| 9206 | fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> { |
| 9207 | let mut out = Vec::with_capacity(transmitted.len() + cached.len()); |
| 9208 | let (mut ci, mut ti) = (0, 0); |
| 9209 | while ci < cached.len() && ti < transmitted.len() { |
| 9210 | if cached[ci] <= transmitted[ti] { |
| 9211 | out.push(cached[ci]); |
| 9212 | ci += 1; |
| 9213 | } else { |
| 9214 | out.push(transmitted[ti]); |
| 9215 | ti += 1; |
| 9216 | } |
| 9217 | } |
| 9218 | out.extend_from_slice(&cached[ci..]); |
| 9219 | out.extend_from_slice(&transmitted[ti..]); |
| 9220 | out |
| 9221 | } |
| 9222 | |
| 9223 | /// `read_palette_colors_y` (decodemv.c:478), at the sequence's real |
| 9224 | /// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour, |
| 9225 | /// each delta's width, the `range` bound and the clamp) is sized by |
| 9226 | /// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every |
| 9227 | /// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges |
| 9228 | /// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of |
| 9229 | /// the msac range, so a cross-decoder range ladder stays bit-identical |
| 9230 | /// through the whole miscount -- only the decoded VALUE differs (class |
| 9231 | /// `compare-range-not-tell`'s blind spot). (this |
| 9232 | /// decoder is 8-bit only): accepts up to `n` colours straight from `cache` |
| 9233 | /// (one flag bit each, in cache order), then delta-codes the remainder |
| 9234 | /// (first value raw, each following delta `>= 1` off a shrinking bit width), |
| 9235 | /// and merges the two ascending lists back together. |
| 9236 | fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] { |
| 9237 | let mut cached = Vec::with_capacity(n); |
| 9238 | for &c in cache { |
| 9239 | if cached.len() >= n { |
| 9240 | break; |
| 9241 | } |
| 9242 | if dec.literal(1) == 1 { |
| 9243 | cached.push(c); |
| 9244 | } |
| 9245 | } |
| 9246 | let bd = u32::from(bit_depth(fctx)); |
| 9247 | let max_val = (1i32 << bd) - 1; |
| 9248 | let mut colors = [0u16; 8]; |
| 9249 | let n_cached = cached.len(); |
| 9250 | if n_cached < n { |
| 9251 | let mut transmitted = Vec::with_capacity(n - n_cached); |
| 9252 | let first = dec.literal(bd) as u16; |
| 9253 | transmitted.push(first); |
| 9254 | if n_cached + 1 < n { |
| 9255 | let min_bits = bd - 3; |
| 9256 | let mut bits = min_bits + dec.literal(2); |
| 9257 | let mut range = (1i32 << bd) - i32::from(first) - 1; |
| 9258 | for _ in (n_cached + 1)..n { |
| 9259 | let delta = dec.literal(bits) as i32 + 1; |
| 9260 | let prev = *transmitted.last().unwrap(); |
| 9261 | let val = (i32::from(prev) + delta).clamp(0, max_val) as u16; |
| 9262 | range -= i32::from(val) - i32::from(prev); |
| 9263 | bits = bits.min(ceil_log2(range.max(0) as u32)); |
| 9264 | transmitted.push(val); |
| 9265 | } |
| 9266 | } |
| 9267 | let merged = merge_colors(&transmitted, &cached); |
| 9268 | colors[..n].copy_from_slice(&merged); |
| 9269 | } else { |
| 9270 | colors[..n].copy_from_slice(&cached[..n]); |
| 9271 | } |
| 9272 | colors |
| 9273 | } |
| 9274 | |
| 9275 | /// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real |
| 9276 | /// `bit_depth` (see [`read_palette_colors_y`]): U reads |
| 9277 | /// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only |
| 9278 | /// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta` |
| 9279 | /// unbiased by `+1` -- both differences from Y's own reader, matching the C |
| 9280 | /// side by side). V never uses a cache: a leading bit picks either `n` raw |
| 9281 | /// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256 |
| 9282 | /// rather than clamp. |
| 9283 | fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) { |
| 9284 | let mut cached = Vec::with_capacity(n); |
| 9285 | for &c in cache { |
| 9286 | if cached.len() >= n { |
| 9287 | break; |
| 9288 | } |
| 9289 | if dec.literal(1) == 1 { |
| 9290 | cached.push(c); |
| 9291 | } |
| 9292 | } |
| 9293 | let bd = u32::from(bit_depth(fctx)); |
| 9294 | let max_val = 1i32 << bd; |
| 9295 | let mut u_colors = [0u16; 8]; |
| 9296 | let n_cached = cached.len(); |
| 9297 | if n_cached < n { |
| 9298 | let mut transmitted = Vec::with_capacity(n - n_cached); |
| 9299 | let first = dec.literal(bd) as u16; |
| 9300 | transmitted.push(first); |
| 9301 | if n_cached + 1 < n { |
| 9302 | let min_bits = bd - 3; |
| 9303 | let mut bits = min_bits + dec.literal(2); |
| 9304 | let mut range = max_val - i32::from(first); |
| 9305 | for _ in (n_cached + 1)..n { |
| 9306 | let delta = dec.literal(bits) as i32; |
| 9307 | let prev = *transmitted.last().unwrap(); |
| 9308 | let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16; |
| 9309 | range -= i32::from(val) - i32::from(prev); |
| 9310 | bits = bits.min(ceil_log2(range.max(0) as u32)); |
| 9311 | transmitted.push(val); |
| 9312 | } |
| 9313 | } |
| 9314 | let merged = merge_colors(&transmitted, &cached); |
| 9315 | u_colors[..n].copy_from_slice(&merged); |
| 9316 | } else { |
| 9317 | u_colors[..n].copy_from_slice(&cached[..n]); |
| 9318 | } |
| 9319 | let mut v_colors = [0u16; 8]; |
| 9320 | if dec.literal(1) == 1 { |
| 9321 | let min_bits_v = bd - 4; |
| 9322 | let bits = min_bits_v + dec.literal(2); |
| 9323 | v_colors[0] = dec.literal(bd) as u16; |
| 9324 | for i in 1..n { |
| 9325 | let mut delta = dec.literal(bits) as i32; |
| 9326 | if delta != 0 && dec.literal(1) == 1 { |
| 9327 | delta = -delta; |
| 9328 | } |
| 9329 | let mut val = i32::from(v_colors[i - 1]) + delta; |
| 9330 | if val < 0 { |
| 9331 | val += max_val; |
| 9332 | } |
| 9333 | if val >= max_val { |
| 9334 | val -= max_val; |
| 9335 | } |
| 9336 | v_colors[i] = val as u16; |
| 9337 | } |
| 9338 | } else { |
| 9339 | for i in 0..n { |
| 9340 | v_colors[i] = dec.literal(bd) as u16; |
| 9341 | } |
| 9342 | } |
| 9343 | (u_colors, v_colors) |
| 9344 | } |
| 9345 | |
| 9346 | /// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a |
| 9347 | /// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real |
| 9348 | /// `0..=4` context, `-1` for hashes no real neighbour configuration produces. |
| 9349 | const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1]; |
| 9350 | |
| 9351 | /// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index |
| 9352 | /// map's own per-pixel context and colour-order permutation, from the |
| 9353 | /// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3 |
| 9354 | /// selection sort). `map`'s stride is `side` (this decoder never crops a |
| 9355 | /// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s |
| 9356 | /// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the |
| 9357 | /// actual colour index to store. |
| 9358 | pub(crate) fn palette_color_index_context( |
| 9359 | map: &[u8], |
| 9360 | side: usize, |
| 9361 | row: usize, |
| 9362 | col: usize, |
| 9363 | n: usize, |
| 9364 | ) -> (usize, [u8; 8]) { |
| 9365 | let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None }; |
| 9366 | let up_left = if col >= 1 && row >= 1 { |
| 9367 | Some(map[(row - 1) * side + col - 1]) |
| 9368 | } else { |
| 9369 | None |
| 9370 | }; |
| 9371 | let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None }; |
| 9372 | let mut scores = [0i32; 8]; |
| 9373 | for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] { |
| 9374 | if let Some(v) = neighbour { |
| 9375 | scores[v as usize] += weight; |
| 9376 | } |
| 9377 | } |
| 9378 | let mut color_order = [0u8; 8]; |
| 9379 | for i in 0..8 { |
| 9380 | color_order[i] = i as u8; |
| 9381 | } |
| 9382 | for i in 0..3 { |
| 9383 | let mut max = scores[i]; |
| 9384 | let mut max_idx = i; |
| 9385 | for j in (i + 1)..n { |
| 9386 | if scores[j] > max { |
| 9387 | max = scores[j]; |
| 9388 | max_idx = j; |
| 9389 | } |
| 9390 | } |
| 9391 | if max_idx != i { |
| 9392 | let max_score = scores[max_idx]; |
| 9393 | let max_color = color_order[max_idx]; |
| 9394 | for k in (i + 1..=max_idx).rev() { |
| 9395 | scores[k] = scores[k - 1]; |
| 9396 | color_order[k] = color_order[k - 1]; |
| 9397 | } |
| 9398 | scores[i] = max_score; |
| 9399 | color_order[i] = max_color; |
| 9400 | } |
| 9401 | } |
| 9402 | let hash = scores[0] + scores[1] * 2 + scores[2] * 2; |
| 9403 | let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize]; |
| 9404 | (ctx as usize, color_order) |
| 9405 | } |
| 9406 | |
| 9407 | /// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512): |
| 9408 | /// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block |
| 9409 | /// cut by the frame's bottom or right mi edge codes its colour-index map only |
| 9410 | /// over this part and replicates it outward -- reading the full `bw x bh` grid |
| 9411 | /// consumed symbols libaom never wrote and desynced the rest of the tile |
| 9412 | /// (lane-svtinter; class map-read-past-frame-edge). |
| 9413 | fn palette_onscreen( |
| 9414 | mi_r: usize, |
| 9415 | mi_c: usize, |
| 9416 | bw: usize, |
| 9417 | bh: usize, |
| 9418 | fctx: &crate::decode::FrameCtx, |
| 9419 | ) -> (usize, usize) { |
| 9420 | // lane-palw: the ENCODER's own in-process reconstruct runs on a |
| 9421 | // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both |
| 9422 | // frame encoders publish the header's mi dims onto it themselves |
| 9423 | // (`encode.rs`, beside their `true_width`/`true_height`) so that this |
| 9424 | // clamp and `tile::write_color_index_map`'s now agree there too. |
| 9425 | let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); |
| 9426 | palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols)) |
| 9427 | } |
| 9428 | |
| 9429 | /// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches |
| 9430 | /// it (`tile::write_palette_syntax`, armed per frame): the two sides must |
| 9431 | /// compute the same on-screen extent or the decoder reads a different number |
| 9432 | /// of symbols than the encoder wrote. |
| 9433 | pub(crate) fn palette_onscreen_dims( |
| 9434 | mi_r: usize, |
| 9435 | mi_c: usize, |
| 9436 | bw: usize, |
| 9437 | bh: usize, |
| 9438 | (mi_rows, mi_cols): (usize, usize), |
| 9439 | ) -> (usize, usize) { |
| 9440 | ( |
| 9441 | bw.min(mi_cols.saturating_sub(mi_c) * MI), |
| 9442 | bh.min(mi_rows.saturating_sub(mi_r) * MI), |
| 9443 | ) |
| 9444 | } |
| 9445 | |
| 9446 | /// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus |
| 9447 | /// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the |
| 9448 | /// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move |
| 9449 | /// together or a cut 8-wide block reads its chroma map at the wrong width. |
| 9450 | /// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4 |
| 9451 | /// intra-in-inter palette read its chroma map at the 4:2:0 extent and |
| 9452 | /// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct). |
| 9453 | pub(crate) fn palette_onscreen_uv( |
| 9454 | luma: (usize, usize), |
| 9455 | on: (usize, usize), |
| 9456 | chroma: (usize, usize), |
| 9457 | ss: (usize, usize), |
| 9458 | ) -> (usize, usize) { |
| 9459 | ( |
| 9460 | (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)), |
| 9461 | (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)), |
| 9462 | ) |
| 9463 | } |
| 9464 | |
| 9465 | /// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index |
| 9466 | /// map's wavefront decode over a `side x side` grid, read over the on-screen |
| 9467 | /// `on_side x on_side` corner (see [`palette_onscreen`]). |
| 9468 | fn decode_color_index_map( |
| 9469 | dec: &mut SymbolDecoder, |
| 9470 | cdfs: &mut Cdfs, |
| 9471 | n: usize, |
| 9472 | side: usize, |
| 9473 | on: (usize, usize), |
| 9474 | uv: bool, |
| 9475 | ) -> Vec<u8> { |
| 9476 | decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv) |
| 9477 | } |
| 9478 | |
| 9479 | /// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip |
| 9480 | /// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal |
| 9481 | /// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh` |
| 9482 | /// independently rather than one shared `side` -- the square call above is |
| 9483 | /// just `bw == bh`. |
| 9484 | fn decode_color_index_map_wh( |
| 9485 | dec: &mut SymbolDecoder, |
| 9486 | cdfs: &mut Cdfs, |
| 9487 | n: usize, |
| 9488 | bw: usize, |
| 9489 | bh: usize, |
| 9490 | // `(onscreenWidth, onscreenHeight)` in this plane's own units. |
| 9491 | on: (usize, usize), |
| 9492 | uv: bool, |
| 9493 | ) -> Vec<u8> { |
| 9494 | let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); |
| 9495 | let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh)); |
| 9496 | if on_bw < bw || on_bh < bh { |
| 9497 | hit!(PALETTE_ONSCREEN_CUT_HITS); |
| 9498 | } |
| 9499 | let mut map = vec![0u8; bw * bh]; |
| 9500 | if trace { |
| 9501 | let (rng, _) = dec.debug_state(); |
| 9502 | eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}"); |
| 9503 | } |
| 9504 | map[0] = read_uniform(dec, n) as u8; |
| 9505 | if trace { |
| 9506 | let (rng, _) = dec.debug_state(); |
| 9507 | eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]); |
| 9508 | } |
| 9509 | for i in 1..(on_bw + on_bh - 1) { |
| 9510 | let j_hi = i.min(on_bw - 1); |
| 9511 | let j_lo = i.saturating_sub(on_bh - 1); |
| 9512 | for j in (j_lo..=j_hi).rev() { |
| 9513 | let row = i - j; |
| 9514 | let col = j; |
| 9515 | let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n); |
| 9516 | if trace { |
| 9517 | let (rng, _) = dec.debug_state(); |
| 9518 | let row_cdf = if uv { |
| 9519 | &cdfs.palette_uv_color_index[n - 2][ctx] |
| 9520 | } else { |
| 9521 | &cdfs.palette_y_color_index[n - 2][ctx] |
| 9522 | }; |
| 9523 | eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]); |
| 9524 | } |
| 9525 | let symbol = if uv { |
| 9526 | dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n]) |
| 9527 | } else { |
| 9528 | dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n]) |
| 9529 | }; |
| 9530 | map[row * bw + col] = color_order[symbol]; |
| 9531 | if trace { |
| 9532 | let (rng, _) = dec.debug_state(); |
| 9533 | eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}"); |
| 9534 | } |
| 9535 | } |
| 9536 | } |
| 9537 | palette_replicate(&mut map, bw, bh, on); |
| 9538 | map |
| 9539 | } |
| 9540 | |
| 9541 | /// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the |
| 9542 | /// last on-screen column then the last on-screen row are replicated over the |
| 9543 | /// off-screen remainder, so the prediction still covers the whole block. The |
| 9544 | /// ENCODER runs this over its searched map too (`encode.rs`'s palette arms), |
| 9545 | /// so the pixels it prices and reconstructs are the ones the on-screen |
| 9546 | /// symbols it writes really decode to. |
| 9547 | pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) { |
| 9548 | let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh)); |
| 9549 | for row in 0..on_bh { |
| 9550 | let last = map[row * bw + on_bw - 1]; |
| 9551 | map[row * bw + on_bw..row * bw + bw].fill(last); |
| 9552 | } |
| 9553 | for row in on_bh..bh { |
| 9554 | map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw); |
| 9555 | } |
| 9556 | } |
| 9557 | |
| 9558 | /// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1, |
| 9559 | /// palette wired lane-palette2 r4): identical except the `use_filter_intra` |
| 9560 | /// size class comes from [`filter_intra_size_class_rect`] instead of the |
| 9561 | /// square-only [`filter_intra_size_class`], and the palette read (when |
| 9562 | /// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/ |
| 9563 | /// [`decode_color_index_map_wh`] instead of their square-only counterparts -- |
| 9564 | /// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`, |
| 9565 | /// `cfl_alphas`) is indexed by mode or neighbour state, never by block size. |
| 9566 | #[allow(clippy::too_many_arguments)] |
| 9567 | fn read_intra_mode_rect( |
| 9568 | dec: &mut SymbolDecoder, |
| 9569 | cdfs: &mut Cdfs, |
| 9570 | above_mode: usize, |
| 9571 | left_mode: usize, |
| 9572 | cfl: bool, |
| 9573 | // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall |
| 9574 | // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads |
| 9575 | // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's |
| 9576 | // chroma is coded once, on the closing strip). Every other caller is a |
| 9577 | // block big enough to own its chroma and passes `true`. |
| 9578 | has_chroma: bool, |
| 9579 | bw: usize, |
| 9580 | bh: usize, |
| 9581 | enable_filter_intra: bool, |
| 9582 | skip_ctx: usize, |
| 9583 | allow_screen_content_tools: bool, |
| 9584 | // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params: |
| 9585 | // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y |
| 9586 | // block here, `None` still reads (and refuses on use) the symbol at ctx 0. |
| 9587 | palette: Option<(usize, &[u16])>, |
| 9588 | palette_uv_cache: &[u16], |
| 9589 | mi_r: usize, |
| 9590 | mi_c: usize, fctx: &crate::decode::FrameCtx, |
| 9591 | ) -> Result<( |
| 9592 | bool, |
| 9593 | usize, |
| 9594 | i32, |
| 9595 | usize, |
| 9596 | i32, |
| 9597 | Option<(i32, i32)>, |
| 9598 | Option<usize>, |
| 9599 | Option<PaletteY>, |
| 9600 | Option<PaletteUv>, |
| 9601 | // lane-av1-intrabc: the block vector, `Some` exactly when this block's |
| 9602 | // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns |
| 9603 | // straight out of `read_intra_frame_mode_info` then, so every later field |
| 9604 | // of the tuple is at its default (mode/uv_mode DC, no angle, no palette, |
| 9605 | // no filter intra). A caller that can reconstruct intrabc at its shape |
| 9606 | // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by |
| 9607 | // name with the same string it always did. |
| 9608 | Option<(i32, i32)>, |
| 9609 | )> { |
| 9610 | // lane-av1mono: libaom guards every chroma symbol read with |
| 9611 | // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`), |
| 9612 | // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/ |
| 9613 | // `palette_uv` even on a chroma-reference strip. Fold the plane count |
| 9614 | // into the same `has_chroma` this reader already gates on. |
| 9615 | let has_chroma = has_chroma && !mono(fctx); |
| 9616 | let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); |
| 9617 | if ec_istep { |
| 9618 | // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line |
| 9619 | // (decodemv.c:818), printed at the same point: before the first |
| 9620 | // mode-info symbol of the block, so a cross-decoder range ladder can |
| 9621 | // be keyed on the BLOCK, not just on the symbol sequence. |
| 9622 | 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); |
| 9623 | } |
| 9624 | macro_rules! istep { |
| 9625 | ($name:literal, $val:expr) => { |
| 9626 | if ec_istep { |
| 9627 | let (rng, _) = dec.debug_state(); |
| 9628 | eprintln!( |
| 9629 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}", |
| 9630 | $name, $val |
| 9631 | ); |
| 9632 | } |
| 9633 | }; |
| 9634 | } |
| 9635 | // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is |
| 9636 | // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at |
| 9637 | // the one point every rect caller routes through, so no call site can |
| 9638 | // offer the 14-symbol CFL alphabet on a 64-axis block (class |
| 9639 | // wrong-alphabet-same-value: same value, wrong interval, silent desync). |
| 9640 | let cfl = if cfl && bw.max(bh) > 32 { |
| 9641 | hit!(NOCFL_UV_MODE_HITS); |
| 9642 | false |
| 9643 | } else { |
| 9644 | cfl |
| 9645 | }; |
| 9646 | // lane-intra14 r1: on the INTER block path everything up to and including |
| 9647 | // `is_inter` was already read by [`decode_inter_block`], so this reader |
| 9648 | // starts at the mode syntax with the `skip` that caller read. |
| 9649 | let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get); |
| 9650 | let skip = if let Some((_, skip)) = inter { |
| 9651 | skip |
| 9652 | } else { |
| 9653 | // Same `intra_segment_id` placement as the square reader above. |
| 9654 | let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4); |
| 9655 | if seg_id_pre_skip(fctx) { |
| 9656 | intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx); |
| 9657 | } |
| 9658 | let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; |
| 9659 | istep!("skip", skip as i32); |
| 9660 | if !seg_id_pre_skip(fctx) { |
| 9661 | intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx); |
| 9662 | } |
| 9663 | maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx); |
| 9664 | istep!("cdef", 0); |
| 9665 | // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never |
| 9666 | // both 64 here -- see this fn's own doc), so `is_whole_sb` is always |
| 9667 | // `false`. |
| 9668 | maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx); |
| 9669 | maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx); |
| 9670 | istep!("dq", 0); |
| 9671 | // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after |
| 9672 | // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the |
| 9673 | // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc` |
| 9674 | // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so |
| 9675 | // rect strips read it exactly like square leaves ([`read_intra_mode`], |
| 9676 | // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic |
| 9677 | // decoder at the FIRST symbol of the first rect block of every |
| 9678 | // `--tune-content=screen` key frame. Reconstruction of a real intrabc |
| 9679 | // block at this shape is out of scope, so the flag is consumed and |
| 9680 | // refused by name when it fires. |
| 9681 | if allow_intrabc_frame(fctx) { |
| 9682 | let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; |
| 9683 | hit!(RECT_INTRABC_READS); |
| 9684 | istep!("intrabc", use_intrabc as i32); |
| 9685 | if use_intrabc { |
| 9686 | hit!(INTRABC_HITS); |
| 9687 | // libaom `read_intrabc_info`: the DV read, then an immediate |
| 9688 | // return out of the mode-info read -- no `y_mode`, no `uv_mode`, |
| 9689 | // no angle deltas, no palette, no filter intra. The caller owns |
| 9690 | // the reconstruction at its own shape. |
| 9691 | let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx); |
| 9692 | return Ok(( |
| 9693 | skip, |
| 9694 | DC_PRED, |
| 9695 | 0, |
| 9696 | DC_PRED, |
| 9697 | 0, |
| 9698 | None, |
| 9699 | None, |
| 9700 | None, |
| 9701 | None, |
| 9702 | Some(dv), |
| 9703 | )); |
| 9704 | } |
| 9705 | } |
| 9706 | skip |
| 9707 | }; |
| 9708 | // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key |
| 9709 | // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode` |
| 9710 | // off `kf_y_mode_cdf[above][left]`). |
| 9711 | let mode = if let Some((size_group, _)) = inter { |
| 9712 | dec.symbol(&mut cdfs.y_mode[size_group]) |
| 9713 | } else { |
| 9714 | let above_ctx = INTRA_MODE_CTX[above_mode]; |
| 9715 | let left_ctx = INTRA_MODE_CTX[left_mode]; |
| 9716 | dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]) |
| 9717 | }; |
| 9718 | istep!("mode", mode as i32); |
| 9719 | let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { |
| 9720 | read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) |
| 9721 | } else { |
| 9722 | 0 |
| 9723 | }; |
| 9724 | istep!("angle_y", angle_delta_y); |
| 9725 | // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)` |
| 9726 | // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 && |
| 9727 | // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet |
| 9728 | // here, from the block's own size, is the single point every caller routes |
| 9729 | // through -- a caller passing `true` for a >32 strip used to pick the |
| 9730 | // 14-symbol CFL CDF, same value but a different range (class |
| 9731 | // wrong-alphabet-same-value). |
| 9732 | let cfl = cfl && cfl_allowed_px(bw, bh, fctx); |
| 9733 | let uv_mode = if !has_chroma { |
| 9734 | DC_PRED |
| 9735 | } else if cfl { |
| 9736 | dec.symbol(&mut cdfs.uv_mode_cfl[mode]) |
| 9737 | } else { |
| 9738 | dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) |
| 9739 | }; |
| 9740 | istep!("uv_mode", uv_mode as i32); |
| 9741 | let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED { |
| 9742 | Some(read_cfl_alphas(dec, cdfs)) |
| 9743 | } else { |
| 9744 | None |
| 9745 | }; |
| 9746 | if has_chroma && (9..=12).contains(&uv_mode) { |
| 9747 | hit!(SMOOTH_UV_HITS); |
| 9748 | } |
| 9749 | let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 9750 | hit!(DIRECTIONAL_UV_HITS); |
| 9751 | read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) |
| 9752 | } else { |
| 9753 | 0 |
| 9754 | }; |
| 9755 | istep!("angle_uv", angle_delta_uv); |
| 9756 | if angle_delta_uv != 0 { |
| 9757 | hit!(UV_ANGLE_DELTA_HITS); |
| 9758 | } |
| 9759 | // `read_palette_mode_info` (spec 5.11.13), rect-generalised |
| 9760 | // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`], |
| 9761 | // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only |
| 9762 | // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/ |
| 9763 | // colours only here, the colour-index maps deferred past `filter_intra` |
| 9764 | // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette` |
| 9765 | // runs from the caller, after the whole mode-info read). |
| 9766 | let mut palette_y_pending: Option<(usize, [u16; 8])> = None; |
| 9767 | let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; |
| 9768 | if allow_screen_content_tools |
| 9769 | && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) |
| 9770 | { |
| 9771 | // r6: this is the exact site the removed blanket refusal used to |
| 9772 | // guard -- reached for EVERY rect strip in a screen-content frame, |
| 9773 | // independent of whether the block ends up using a palette. |
| 9774 | hit!(RECT_SCREEN_CONTENT_HITS); |
| 9775 | let (mode_ctx, cache) = palette.unwrap_or((0, &[])); |
| 9776 | let use_palette_y = |
| 9777 | mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0; |
| 9778 | if use_palette_y { |
| 9779 | let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); |
| 9780 | let colors = read_palette_colors_y(dec, n, cache, fctx); |
| 9781 | palette_y_pending = Some((n, colors)); |
| 9782 | } |
| 9783 | let palette_uv_mode_ctx = usize::from(use_palette_y); |
| 9784 | // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard. |
| 9785 | if has_chroma |
| 9786 | && uv_mode == DC_PRED |
| 9787 | && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 |
| 9788 | { |
| 9789 | let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); |
| 9790 | let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx); |
| 9791 | palette_uv_pending = Some((n, u_colors, v_colors)); |
| 9792 | } |
| 9793 | } |
| 9794 | let mut filter_intra = None; |
| 9795 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 9796 | let (rng, _) = dec.debug_state(); |
| 9797 | eprintln!( |
| 9798 | "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \ |
| 9799 | class={:?} rng={rng}", |
| 9800 | enable_filter_intra as i32, |
| 9801 | filter_intra_size_class_rect(bw, bh) |
| 9802 | ); |
| 9803 | } |
| 9804 | // As the square path: `av1_filter_intra_allowed` excludes a palette-Y |
| 9805 | // block (reconintra.h:77), so no `use_filter_intra` symbol exists there. |
| 9806 | if mode == DC_PRED |
| 9807 | && enable_filter_intra |
| 9808 | && palette_y_pending.is_none() |
| 9809 | && let Some(class) = filter_intra_size_class_rect(bw, bh) |
| 9810 | { |
| 9811 | let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0; |
| 9812 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 9813 | eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32); |
| 9814 | } |
| 9815 | istep!("use_filter_intra", use_filter_intra as i32); |
| 9816 | if use_filter_intra { |
| 9817 | hit!(FILTER_INTRA_HITS); |
| 9818 | let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); |
| 9819 | istep!("filter_intra_mode", fi_mode as i32); |
| 9820 | filter_intra = Some(fi_mode); |
| 9821 | } |
| 9822 | } |
| 9823 | // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map), |
| 9824 | // same order as [`read_intra_mode`]'s own square path. |
| 9825 | let palette_y = palette_y_pending.map(|(n, colors)| { |
| 9826 | let map = |
| 9827 | decode_color_index_map_wh(dec, cdfs, n, bw, bh, palette_onscreen(mi_r, mi_c, bw, bh, fctx), false); |
| 9828 | hit!(PALETTE_HITS); |
| 9829 | hit!(PALETTE_RECT_HITS); |
| 9830 | PaletteY { size: n, colors, map } |
| 9831 | }); |
| 9832 | let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { |
| 9833 | // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a |
| 9834 | // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to |
| 9835 | // BLOCK_4X8, both floored at the 4-px transform. Halving the short |
| 9836 | // axis to 2 read HALF the colour-index symbols of a 1:4 strip's |
| 9837 | // chroma palette and desynced the tile from there. |
| 9838 | let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4)); |
| 9839 | let on = palette_onscreen_uv((bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch), (ss_x(fctx), ss_y(fctx))); |
| 9840 | let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true); |
| 9841 | hit!(PALETTE_UV_HITS); |
| 9842 | PaletteUv { size: n, u_colors, v_colors, map } |
| 9843 | }); |
| 9844 | Ok(( |
| 9845 | skip, |
| 9846 | mode, |
| 9847 | angle_delta_y, |
| 9848 | uv_mode, |
| 9849 | angle_delta_uv, |
| 9850 | alpha, |
| 9851 | filter_intra, |
| 9852 | palette_y, |
| 9853 | palette_uv, |
| 9854 | None, |
| 9855 | )) |
| 9856 | } |
| 9857 | |
| 9858 | /// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays, |
| 9859 | /// at the strip's REAL mi position. `av1_get_palette_cache` reads |
| 9860 | /// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the |
| 9861 | /// block, so each strip owns its own rows and columns and no aliasing rule |
| 9862 | /// is needed (lane-kf900 r6). |
| 9863 | #[allow(clippy::too_many_arguments)] |
| 9864 | fn record_strip_palette( |
| 9865 | n: &mut Neighbours, |
| 9866 | mi: (usize, usize), |
| 9867 | bw: usize, |
| 9868 | bh: usize, |
| 9869 | y_size: usize, |
| 9870 | y_colors: [u16; 8], |
| 9871 | uv_size: usize, |
| 9872 | uv_colors: [u16; 8], |
| 9873 | ) { |
| 9874 | let (r, c) = mi; |
| 9875 | // lane-t900 r23 rung: every publication of a block's palette state into |
| 9876 | // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode |
| 9877 | // path left a stale `left_palette_size` behind when |
| 9878 | // `av1_get_palette_mode_ctx` disagrees with libaom's. |
| 9879 | if crate::envflags::env_flag!("EC_PALPUB") { |
| 9880 | eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}"); |
| 9881 | } |
| 9882 | // lane-kf900 r6: the palette side bands are mi-granular now, so a strip |
| 9883 | // writes its OWN span on BOTH axes -- the old `last` split-axis rule only |
| 9884 | // existed because the 16px [`SUB`] cell held one slot for all the strips |
| 9885 | // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the |
| 9886 | // real neighbour leaf 1 reads. |
| 9887 | { |
| 9888 | for cell in 0..(bw / MI).max(1) { |
| 9889 | if let Some(e) = n.above_palette_size.get_mut(c + cell) { |
| 9890 | *e = y_size as u8; |
| 9891 | n.above_palette_uv_size[c + cell] = uv_size as u8; |
| 9892 | // lane-publish2, see [`Neighbours::record_palette_y_rect`]: |
| 9893 | // colours of a size-0 neighbour are never read. |
| 9894 | if y_size > 0 { |
| 9895 | n.above_palette_colors[c + cell] = y_colors; |
| 9896 | } |
| 9897 | if uv_size > 0 { |
| 9898 | n.above_palette_uv_colors[c + cell] = uv_colors; |
| 9899 | } |
| 9900 | } |
| 9901 | } |
| 9902 | } |
| 9903 | { |
| 9904 | for cell in 0..(bh / MI).max(1) { |
| 9905 | if n.left_palette_size.get(r + cell).is_none() { |
| 9906 | break; |
| 9907 | } |
| 9908 | n.left_palette_size[r + cell] = y_size as u8; |
| 9909 | n.left_palette_uv_size[r + cell] = uv_size as u8; |
| 9910 | if y_size > 0 { |
| 9911 | n.left_palette_colors[r + cell] = y_colors; |
| 9912 | } |
| 9913 | if uv_size > 0 { |
| 9914 | n.left_palette_uv_colors[r + cell] = uv_colors; |
| 9915 | } |
| 9916 | } |
| 9917 | } |
| 9918 | } |
| 9919 | |
| 9920 | /// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1). |
| 9921 | fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> { |
| 9922 | cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx])) |
| 9923 | } |
| 9924 | |
| 9925 | /// Everything a rect strip already read out of the stream before its luma |
| 9926 | /// transform units are decoded -- [`decode_rect_split`]'s own mode bundle |
| 9927 | /// (nine values that would otherwise be nine more parameters). |
| 9928 | struct RectStripModes { |
| 9929 | skip: bool, |
| 9930 | mode: usize, |
| 9931 | angle_delta_y: i32, |
| 9932 | uv_predict_mode: usize, |
| 9933 | angle_delta_uv: i32, |
| 9934 | alpha: Option<(i32, i32)>, |
| 9935 | filter_intra: Option<usize>, |
| 9936 | smooth_neighbor: bool, |
| 9937 | smooth_neighbor_uv: bool, |
| 9938 | /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already |
| 9939 | /// mapped through the colour table), sliced per transform unit below -- |
| 9940 | /// palette prediction reads no edge pixels, so a unit's slice of the |
| 9941 | /// whole-block map IS its prediction. Without this a palette strip whose |
| 9942 | /// transform splits predicted DC and came out flat grey while the entropy |
| 9943 | /// stream stayed in sync (the coefficients are read either way). |
| 9944 | palette_y: Option<Vec<u16>>, |
| 9945 | /// As `palette_y`, for the un-split chroma transform (U, V). |
| 9946 | palette_uv: Option<(Vec<u16>, Vec<u16>)>, |
| 9947 | } |
| 9948 | |
| 9949 | /// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth` |
| 9950 | /// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times |
| 9951 | /// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the |
| 9952 | /// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's |
| 9953 | /// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 -> |
| 9954 | /// TX_32X16`) and only the second reaches a square -- the reason |
| 9955 | /// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is |
| 9956 | /// already square) mis-tiled 1:4 strips. |
| 9957 | fn depth_to_tx_wh( |
| 9958 | bw: usize, |
| 9959 | bh: usize, |
| 9960 | depth: usize, |
| 9961 | fctx: &crate::decode::FrameCtx, |
| 9962 | ) -> (usize, usize) { |
| 9963 | // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom |
| 9964 | // `read_tx_size`: the lossless early return comes before |
| 9965 | // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here. |
| 9966 | if lossless(fctx) { |
| 9967 | return (4, 4); |
| 9968 | } |
| 9969 | let (mut w, mut h) = (bw.min(64), bh.min(64)); |
| 9970 | for _ in 0..depth { |
| 9971 | match w.cmp(&h) { |
| 9972 | std::cmp::Ordering::Greater => w /= 2, |
| 9973 | std::cmp::Ordering::Less => h /= 2, |
| 9974 | std::cmp::Ordering::Equal => { |
| 9975 | w /= 2; |
| 9976 | h /= 2; |
| 9977 | } |
| 9978 | } |
| 9979 | } |
| 9980 | (w, h) |
| 9981 | } |
| 9982 | |
| 9983 | /// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma |
| 9984 | /// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every |
| 9985 | /// rect path here refused by name until now ("per-unit rect prediction is not |
| 9986 | /// ported"). |
| 9987 | /// |
| 9988 | /// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth` |
| 9989 | /// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1 |
| 9990 | /// strip the very first step already lands on a SQUARE transform |
| 9991 | /// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and |
| 9992 | /// every further step halves a square) -- so each unit is square and reads |
| 9993 | /// through the ordinary square [`read_plane`]. What is genuinely rectangular |
| 9994 | /// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as |
| 9995 | /// [`decode_block`]'s square split loop assumes) and the chroma plane, whose |
| 9996 | /// own transform is `av1_get_max_uv_txsize` of the whole strip and is never |
| 9997 | /// split by luma's depth. |
| 9998 | /// |
| 9999 | /// Each unit predicts off whatever the earlier units of this same block |
| 10000 | /// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block` |
| 10001 | /// inside `av1_foreach_transformed_block`, raster order), which is exactly |
| 10002 | /// what predicting the whole strip in one shot got wrong. |
| 10003 | #[allow(clippy::too_many_arguments)] |
| 10004 | fn decode_rect_split( |
| 10005 | dec: &mut SymbolDecoder, |
| 10006 | cdfs: &mut Cdfs, |
| 10007 | neighbours: &mut Neighbours, |
| 10008 | at_mi: (usize, usize), |
| 10009 | bw: usize, |
| 10010 | bh: usize, |
| 10011 | // The transform unit's own width and height in pixels. Square for every |
| 10012 | // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is |
| 10013 | // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`, |
| 10014 | // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`]. |
| 10015 | tx_w: usize, |
| 10016 | tx_h: usize, |
| 10017 | m: &RectStripModes, |
| 10018 | y: &mut PlaneBuf<'static>, |
| 10019 | u: &mut PlaneBuf<'static>, |
| 10020 | v: &mut PlaneBuf<'static>, |
| 10021 | base_q_idx: u8, |
| 10022 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 10023 | ) -> Result<()> { |
| 10024 | let (mi_r, mi_c) = at_mi; |
| 10025 | let (px, py) = (mi_c * MI, mi_r * MI); |
| 10026 | let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); |
| 10027 | let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); |
| 10028 | // The chroma transform is picked before any symbol is read, so an |
| 10029 | // unsupported chroma shape refuses before this strip desyncs the tile. |
| 10030 | let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) { |
| 10031 | (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])), |
| 10032 | (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])), |
| 10033 | (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])), |
| 10034 | (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])), |
| 10035 | // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32 |
| 10036 | // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx` |
| 10037 | // squares a rect transform down to a CDF set by |
| 10038 | // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set, |
| 10039 | // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets |
| 10040 | // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`) |
| 10041 | // paths already prove for these same shapes. |
| 10042 | (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])), |
| 10043 | (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])), |
| 10044 | (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])), |
| 10045 | (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])), |
| 10046 | (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])), |
| 10047 | (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])), |
| 10048 | _ => None, |
| 10049 | }; |
| 10050 | if !m.skip { |
| 10051 | if let Some(i) = match (chroma_w, chroma_h) { |
| 10052 | (32, 8) => Some(0), |
| 10053 | (8, 32) => Some(1), |
| 10054 | (8, 4) => Some(2), |
| 10055 | (4, 8) => Some(3), |
| 10056 | _ => None, |
| 10057 | } { |
| 10058 | hit_do! { |
| 10059 | RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| { |
| 10060 | let mut hits = c.get(); |
| 10061 | hits[i] += 1; |
| 10062 | c.set(hits); |
| 10063 | }); |
| 10064 | } |
| 10065 | } |
| 10066 | if chroma.is_none() { |
| 10067 | // Diagnostic for the next caller that lands here (class |
| 10068 | // refusal-names-a-correlate: the message names the tool, not the |
| 10069 | // shape); the refusal below keeps its inventory-pinned wording. |
| 10070 | eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}"); |
| 10071 | } |
| 10072 | } |
| 10073 | // lane-rectsplit r2 (verifier finding): with both callers wired |
| 10074 | // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s |
| 10075 | // 64x32/32x64) every shape that reaches here has a table above, so this |
| 10076 | // arm is UNREACHABLE today. It stays as the shape guard for the next |
| 10077 | // caller -- a new strip size would otherwise hit the `expect` below and |
| 10078 | // panic instead of refusing by name -- and so stays in |
| 10079 | // `refusal_inventory::REFUSALS`. |
| 10080 | // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted |
| 10081 | // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled |
| 10082 | // below; everything else still needs a single-unit table. |
| 10083 | let chroma_tiled = matches!((chroma_w, chroma_h), (64, 32) | (32, 64) | (64, 16) | (16, 64)); |
| 10084 | if !m.skip && chroma.is_none() && !chroma_tiled { |
| 10085 | return Err(unsupported( |
| 10086 | "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", |
| 10087 | )); |
| 10088 | } |
| 10089 | hit!(RECT_SPLIT_TX_HITS); |
| 10090 | if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 { |
| 10091 | hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS); |
| 10092 | } |
| 10093 | // LUMA: `bw/tx` x `bh/tx` square transform units, raster order. |
| 10094 | // A square unit reads through the ordinary square [`read_plane`]; a rect |
| 10095 | // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with |
| 10096 | // the very tables the unsplit 16x8/32x16 paths use. |
| 10097 | let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) { |
| 10098 | (w, h) if w == h => None, |
| 10099 | (16, 8) | (8, 16) => Some(( |
| 10100 | if reduced_tx_set { |
| 10101 | TxbSet::LumaRect16x8 |
| 10102 | } else { |
| 10103 | TxbSet::LumaRect16x8Set1 |
| 10104 | }, |
| 10105 | if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] }, |
| 10106 | )), |
| 10107 | (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])), |
| 10108 | (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])), |
| 10109 | // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level |
| 10110 | // strip, read through the `luma_64corner` arm below instead of a rect |
| 10111 | // table -- a 64-length axis codes only its low 32 coefficients |
| 10112 | // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so |
| 10113 | // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own |
| 10114 | // depth-0 arm already reads on the key-frame path. |
| 10115 | // |
| 10116 | // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind |
| 10117 | // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the |
| 10118 | // sub-8x8 intra leaves still refused: with those lifted (r2) the |
| 10119 | // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode |
| 10120 | // all 33 frames pixel-exact against ffmpeg while this arm fires 90x |
| 10121 | // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu` |
| 10122 | // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`. |
| 10123 | // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm |
| 10124 | // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the |
| 10125 | // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact. |
| 10126 | (64, 32) | (32, 64) => None, |
| 10127 | _ => { |
| 10128 | return Err(unsupported(format!( |
| 10129 | "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \ |
| 10130 | coefficient tables for that shape here)" |
| 10131 | ))) |
| 10132 | } |
| 10133 | }; |
| 10134 | // The `None` above that is NOT the square arm. |
| 10135 | let luma_64corner = tx_w != tx_h; |
| 10136 | // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact |
| 10137 | // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole |
| 10138 | // frame exactly, two sub-16 split strips in it), but the RECT-unit arm -- |
| 10139 | // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the |
| 10140 | // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the |
| 10141 | // per-unit rect walk stay wired above/below; the round that finds that |
| 10142 | // defect deletes this refusal and nothing else. |
| 10143 | let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set); |
| 10144 | let luma_scan = default_scan(tx_w.min(tx_h)); |
| 10145 | let zero_tu = vec![0i32; tx_w * tx_h]; |
| 10146 | // The strip's OWN edge availability, the fallback for a transform unit |
| 10147 | // whose top-right/bottom-left pixels fall outside the strip. |
| 10148 | let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 10149 | for tu_row in 0..bh / tx_h { |
| 10150 | for tu_col in 0..bw / tx_w { |
| 10151 | let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI)); |
| 10152 | let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h); |
| 10153 | let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h); |
| 10154 | // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged): |
| 10155 | // libaom clips `av1_foreach_transformed_block_in_plane` to |
| 10156 | // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`, |
| 10157 | // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose |
| 10158 | // TOP-LEFT sample falls outside the frame is never coded. We read |
| 10159 | // coefficients for those phantom units and desynced the stream at |
| 10160 | // the very next symbol. |
| 10161 | if tu_px >= y.true_width || tu_py >= y.true_height { |
| 10162 | continue; |
| 10163 | } |
| 10164 | // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a |
| 10165 | // transform unit INSIDE a block, which is a different rule from |
| 10166 | // the standalone-block table [`Reach::of`] applies -- and the |
| 10167 | // reason a depth-2 superblock strip came out one sample off |
| 10168 | // before this: `Reach::of(tx, ..)` answered as if the unit were |
| 10169 | // its own block at that superblock position. |
| 10170 | // * top-right: if the unit's right neighbour is still inside the |
| 10171 | // strip the pixels are already reconstructed (`col_off + |
| 10172 | // tx_wide < plane_bw`); otherwise only the strip's own top row |
| 10173 | // of units can reach past it, through the block-level answer. |
| 10174 | // * bottom-left: a unit that is not in the strip's left column |
| 10175 | // has none (`col_off > 0` returns 0); inside the strip |
| 10176 | // (`row_off + tx_high < plane_bh`) they are the left |
| 10177 | // neighbour's, already reconstructed; the last row falls back |
| 10178 | // to the block-level answer. |
| 10179 | let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach); |
| 10180 | // The unit's own window on the block's palette prediction. |
| 10181 | if let Some(buf) = &m.palette_y { |
| 10182 | let tu_buf: Vec<u16> = (0..tx_h) |
| 10183 | .flat_map(|i| { |
| 10184 | let base = (row_off + i) * bw + col_off; |
| 10185 | buf[base..base + tx_w].iter().copied() |
| 10186 | }) |
| 10187 | .collect(); |
| 10188 | set_palette_pred(tu_buf, fctx); |
| 10189 | } |
| 10190 | if m.skip { |
| 10191 | push_intra_rect(0, |
| 10192 | tu_px, |
| 10193 | tu_py, |
| 10194 | tx_w, |
| 10195 | tx_h, |
| 10196 | m.mode, |
| 10197 | m.angle_delta_y, |
| 10198 | tu_reach, |
| 10199 | &zero_tu, |
| 10200 | None, |
| 10201 | m.filter_intra, |
| 10202 | m.smooth_neighbor, fctx, |
| 10203 | ); |
| 10204 | neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu); |
| 10205 | } else if luma_64corner && luma_rect.is_none() { |
| 10206 | // The un-split 64-level luma transform: `read_coeffs` on the |
| 10207 | // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)` |
| 10208 | // and the real rect shape passed through for |
| 10209 | // `av1_nz_map_ctx_offset` -- byte for byte |
| 10210 | // [`decode_block_rect64`]'s depth-0 read, which the key-frame |
| 10211 | // 64-level strip gate already proves. `tx_type` is not coded |
| 10212 | // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once |
| 10213 | // the square-up size is TX_64X64), and this unit covers its |
| 10214 | // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat. |
| 10215 | if crate::envflags::env_flag!("EC_RECT64TU") { |
| 10216 | eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode); |
| 10217 | } |
| 10218 | hit_do! { |
| 10219 | RECT64_CORNER_TU_HITS.with(|c| { |
| 10220 | let mut v = c.get(); |
| 10221 | v[usize::from(tx_h > tx_w)] += 1; |
| 10222 | c.set(v); |
| 10223 | }); |
| 10224 | } |
| 10225 | let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; |
| 10226 | let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra)); |
| 10227 | let (corner, tu_tx_type) = read_coeffs( |
| 10228 | dec, |
| 10229 | &mut coding, |
| 10230 | default_scan(TX32), |
| 10231 | 0, |
| 10232 | dc_sign_ctx(tu_around.2), |
| 10233 | TxType::DctDct, |
| 10234 | Some((tx_w, tx_h)), |
| 10235 | )?; |
| 10236 | let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32)); |
| 10237 | let mut tu_grid = vec![0i32; tx_w * tx_h]; |
| 10238 | for row in 0..ch { |
| 10239 | tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]); |
| 10240 | } |
| 10241 | let residual = dequant_and_inverse_typed_wh( |
| 10242 | &tu_grid, |
| 10243 | tx_w, |
| 10244 | tx_h, |
| 10245 | crate::decode::bit_depth(fctx), |
| 10246 | block_q_idx(fctx), |
| 10247 | plane_q_delta(0, fctx).0, |
| 10248 | plane_q_delta(0, fctx).1, |
| 10249 | tu_tx_type, |
| 10250 | block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type), |
| 10251 | ); |
| 10252 | push_intra_rect(0, |
| 10253 | tu_px, |
| 10254 | tu_py, |
| 10255 | tx_w, |
| 10256 | tx_h, |
| 10257 | m.mode, |
| 10258 | m.angle_delta_y, |
| 10259 | tu_reach, |
| 10260 | &residual, |
| 10261 | None, |
| 10262 | m.filter_intra, |
| 10263 | m.smooth_neighbor, fctx, |
| 10264 | ); |
| 10265 | neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); |
| 10266 | } else if let Some((rect_set, rect_scan)) = luma_rect { |
| 10267 | // The rect-unit twin of the square arm below: same contexts, |
| 10268 | // same order, through the rect coefficient reader. The |
| 10269 | // `tx_type` CDF row of a filter-intra block is |
| 10270 | // `fimode_to_intradir[filter_intra_mode]`, never the block's |
| 10271 | // own (always DC_PRED) mode -- [`read_plane`] applies that |
| 10272 | // for the square arm, so this one must too. |
| 10273 | let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; |
| 10274 | // libaom `get_txb_ctx`: a LUMA transform that covers its whole |
| 10275 | // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the |
| 10276 | // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the |
| 10277 | // neighbour-magnitude table is for a unit SMALLER than its |
| 10278 | // block. [`decode_block_rect`]'s own unsplit read passes a |
| 10279 | // literal 0 for the same reason; this arm applied the table |
| 10280 | // unconditionally and desynced every depth-0 rect strip that |
| 10281 | // reached it (lane-intrarect r2: ctx 5 where aomdec read 0). |
| 10282 | let tu_skip_ctx = if tx_w == bw && tx_h == bh { |
| 10283 | 0 |
| 10284 | } else { |
| 10285 | neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI) |
| 10286 | }; |
| 10287 | let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra)); |
| 10288 | let (tu_grid, tu_tx_type) = read_coeffs_rect( |
| 10289 | dec, |
| 10290 | &mut coding, |
| 10291 | rect_scan, |
| 10292 | tx_w, |
| 10293 | tx_h, |
| 10294 | tu_skip_ctx, |
| 10295 | dc_sign_ctx(tu_around.2), |
| 10296 | TxType::DctDct, |
| 10297 | )?; |
| 10298 | let residual = dequant_and_inverse_typed_wh( |
| 10299 | &tu_grid, |
| 10300 | tx_w, |
| 10301 | tx_h, |
| 10302 | crate::decode::bit_depth(fctx), |
| 10303 | block_q_idx(fctx), |
| 10304 | plane_q_delta(0, fctx).0, |
| 10305 | plane_q_delta(0, fctx).1, |
| 10306 | tu_tx_type, |
| 10307 | block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type), |
| 10308 | ); |
| 10309 | push_intra_rect(0, |
| 10310 | tu_px, |
| 10311 | tu_py, |
| 10312 | tx_w, |
| 10313 | tx_h, |
| 10314 | m.mode, |
| 10315 | m.angle_delta_y, |
| 10316 | tu_reach, |
| 10317 | &residual, |
| 10318 | None, |
| 10319 | m.filter_intra, |
| 10320 | m.smooth_neighbor, fctx, |
| 10321 | ); |
| 10322 | neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); |
| 10323 | } else { |
| 10324 | let tu_around = neighbours.around_mi(tu_mi, tx_w)[0]; |
| 10325 | // This unit is smaller than the block it sits in, so |
| 10326 | // `txb_skip_ctx` is the neighbour-magnitude table, not the |
| 10327 | // lone-TU 0 (spec `get_txb_ctx_general`). |
| 10328 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI); |
| 10329 | let tu_grid = read_plane( |
| 10330 | dec, |
| 10331 | cdfs, |
| 10332 | luma_set, |
| 10333 | &luma_scan, |
| 10334 | 0, |
| 10335 | tu_around, |
| 10336 | m.mode, |
| 10337 | m.mode, |
| 10338 | m.angle_delta_y, |
| 10339 | tu_reach, |
| 10340 | y, |
| 10341 | tu_px, |
| 10342 | tu_py, |
| 10343 | tx_w, |
| 10344 | tx_w, |
| 10345 | base_q_idx, |
| 10346 | None, |
| 10347 | m.filter_intra, |
| 10348 | Some(tu_skip_ctx), |
| 10349 | m.smooth_neighbor, fctx, |
| 10350 | )?; |
| 10351 | neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid); |
| 10352 | } |
| 10353 | } |
| 10354 | } |
| 10355 | // CHROMA: one un-split rect transform for the whole strip. |
| 10356 | // lane-lossless2: except on a lossless frame, where it is a raster of 4x4 |
| 10357 | // units -- each stamps its own neighbour context as it is read, and the |
| 10358 | // whole-block `record_split_luma_rect_mi` below would overwrite all of |
| 10359 | // them with the LAST unit's state (class `override-slot-on-one-arm`: the |
| 10360 | // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are |
| 10361 | // collected here and replayed after that record. |
| 10362 | let mut ll_chroma_units: Vec<((usize, usize), usize, Grid)> = Vec::new(); |
| 10363 | // The chroma_tiled arm below stamps each unit's coefficient context |
| 10364 | // immediately (so the NEXT unit reads it), then the whole-strip |
| 10365 | // `record_split_luma_rect_mi` rewrites every chroma cell with ONE |
| 10366 | // whole-strip state and the per-unit DC signs and levels are lost |
| 10367 | // (class `override-slot-on-one-arm`). The units are collected here and |
| 10368 | // replayed after that record, the way the lossless arm's |
| 10369 | // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail |
| 10370 | // already do. |
| 10371 | let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); |
| 10372 | let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 10373 | let reach = block_reach; |
| 10374 | let (u_grid, v_grid) = if mono(fctx) { |
| 10375 | // lane-av1mono: a monochrome frame codes no chroma coefficients on |
| 10376 | // any block (`plane < av1_num_planes == 1`), so the whole chroma |
| 10377 | // section -- the skipped-strip pushes, the lossless raster and the |
| 10378 | // un-split `read_coeffs_rect` below -- is bypassed. |
| 10379 | let zero = Grid::Zero(chroma_w * chroma_h); |
| 10380 | (zero.clone(), zero) |
| 10381 | } else if m.skip { |
| 10382 | let zero = Grid::Zero(chroma_w * chroma_h); |
| 10383 | if let Some((ub, _)) = &m.palette_uv { |
| 10384 | set_palette_pred(ub.clone(), fctx); |
| 10385 | } |
| 10386 | push_intra_rect(1, |
| 10387 | cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, |
| 10388 | m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx, |
| 10389 | ); |
| 10390 | if let Some((_, vb)) = &m.palette_uv { |
| 10391 | set_palette_pred(vb.clone(), fctx); |
| 10392 | } |
| 10393 | push_intra_rect(2, |
| 10394 | cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, |
| 10395 | m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx, |
| 10396 | ); |
| 10397 | (zero.clone(), zero) |
| 10398 | } else if lossless(fctx) { |
| 10399 | // lane-lossless: the strip's chroma plane block is coded as 4x4 |
| 10400 | // transform units too (libaom `read_tx_size` returns TX_4X4 for every |
| 10401 | // plane), PLANE-MAJOR inside the block -- U's units first, then V's |
| 10402 | // (`decode_token_recon_block`'s mu-chunk loop, measured against |
| 10403 | // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1, |
| 10404 | // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10` |
| 10405 | // offset (our `+3` row base) whenever the plane block is bigger than |
| 10406 | // the transform. |
| 10407 | let scan4 = default_scan(4); |
| 10408 | let offset = (chroma_w > 4 || chroma_h > 4).then_some(3); |
| 10409 | let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4); |
| 10410 | let mut last = [Grid::Zero(16), Grid::Zero(16)]; |
| 10411 | for plane_idx in 1..=2 { |
| 10412 | for cu_row in 0..ch_n { |
| 10413 | for cu_col in 0..cw_n { |
| 10414 | let luma_span = 8; |
| 10415 | let cu_mi = ( |
| 10416 | mi_r + cu_row * (luma_span / MI), |
| 10417 | mi_c + cu_col * (luma_span / MI), |
| 10418 | ); |
| 10419 | let cu_around = neighbours.around_mi(cu_mi, luma_span); |
| 10420 | let cu_reach = tu_reach( |
| 10421 | bw, bh, |
| 10422 | cu_col * luma_span, cu_row * luma_span, luma_span, |
| 10423 | block_reach, px, py, y.width, y.height, fctx, |
| 10424 | ); |
| 10425 | let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4); |
| 10426 | if let Some((ub, vb)) = &m.palette_uv { |
| 10427 | let pbuf = if plane_idx == 1 { ub } else { vb }; |
| 10428 | set_palette_pred( |
| 10429 | palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4), |
| 10430 | fctx, |
| 10431 | ); |
| 10432 | } |
| 10433 | let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; |
| 10434 | let grid = read_plane( |
| 10435 | dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx, |
| 10436 | cu_around[plane_idx], m.mode, m.uv_predict_mode, |
| 10437 | m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4, |
| 10438 | base_q_idx, |
| 10439 | m.alpha.zip(ac).map(|((au, av), ac)| { |
| 10440 | (if plane_idx == 1 { au } else { av }, ac) |
| 10441 | }), |
| 10442 | None, offset, m.smooth_neighbor_uv, fctx, |
| 10443 | )?; |
| 10444 | neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_idx, &grid); |
| 10445 | ll_chroma_units.push((cu_mi, plane_idx, grid.clone())); |
| 10446 | last[plane_idx - 1] = grid; |
| 10447 | } |
| 10448 | } |
| 10449 | } |
| 10450 | let [ug, vg] = last; |
| 10451 | (ug, vg) |
| 10452 | } else if chroma_tiled { |
| 10453 | let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) = match (chroma_w, chroma_h) { |
| 10454 | (64, 32) | (32, 64) => (32, 32, TxbSet::Chroma32, default_scan(32)), |
| 10455 | (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16), |
| 10456 | (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32), |
| 10457 | _ => unreachable!("chroma_tiled"), |
| 10458 | }; |
| 10459 | let (nw, nh) = (chroma_w / uw, chroma_h / uh); |
| 10460 | let bigger = chroma_w * chroma_h > uw * uh; |
| 10461 | let default_tx = TxType::DctDct; |
| 10462 | let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)]; |
| 10463 | for plane_idx in 1..=2 { |
| 10464 | for cu_row in 0..nh { |
| 10465 | for cu_col in 0..nw { |
| 10466 | let luma_span_x = uw << ss_x(fctx); |
| 10467 | let luma_span_y = uh << ss_y(fctx); |
| 10468 | let cu_mi = ( |
| 10469 | mi_r + cu_row * (luma_span_y / MI), |
| 10470 | mi_c + cu_col * (luma_span_x / MI), |
| 10471 | ); |
| 10472 | let cu_around = neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y); |
| 10473 | let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh); |
| 10474 | let cfl = m.alpha.map(|(au, av)| { |
| 10475 | let alpha = if plane_idx == 1 { au } else { av }; |
| 10476 | ( |
| 10477 | alpha, |
| 10478 | cfl_src_rect( |
| 10479 | px + cu_col * luma_span_x, |
| 10480 | py + cu_row * luma_span_y, |
| 10481 | luma_span_x, |
| 10482 | luma_span_y, |
| 10483 | ), |
| 10484 | ) |
| 10485 | }); |
| 10486 | // 32x32 does not fit read_coeffs_rect's scratch (768). The |
| 10487 | // square reader is the path every other 32x32 chroma unit uses. |
| 10488 | let levels = if uw == uh { |
| 10489 | let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; |
| 10490 | read_plane( |
| 10491 | dec, cdfs, set, scan, plane_idx, cu_around[plane_idx], |
| 10492 | m.mode, m.uv_predict_mode, m.angle_delta_uv, reach, |
| 10493 | plane, cu_x, cu_y, uw, uw, base_q_idx, cfl, None, |
| 10494 | bigger.then_some(3), m.smooth_neighbor_uv, fctx, |
| 10495 | )? |
| 10496 | } else { |
| 10497 | let skip_ctx = usize::from(cu_around[plane_idx].0) |
| 10498 | + usize::from(cu_around[plane_idx].1) |
| 10499 | + usize::from(bigger) * 3; |
| 10500 | let mut coding = cdfs.txb(set, m.uv_predict_mode); |
| 10501 | let (levels, tx_type) = read_coeffs_rect( |
| 10502 | dec, &mut coding, scan, uw, uh, skip_ctx, |
| 10503 | dc_sign_ctx(cu_around[plane_idx].2), default_tx, |
| 10504 | )?; |
| 10505 | let residual = dequant_and_inverse_typed_wh( |
| 10506 | &levels, uw, uh, crate::decode::bit_depth(fctx), |
| 10507 | block_q_idx(fctx), |
| 10508 | plane_q_delta(plane_idx, fctx).0, |
| 10509 | plane_q_delta(plane_idx, fctx).1, |
| 10510 | tx_type, |
| 10511 | block_iqmatrix(fctx, plane_idx, uw, uh, tx_type), |
| 10512 | ); |
| 10513 | push_intra_rect( |
| 10514 | plane_idx, cu_x, cu_y, uw, uh, |
| 10515 | m.uv_predict_mode, m.angle_delta_uv, reach, &residual, |
| 10516 | cfl, None, m.smooth_neighbor_uv, fctx, |
| 10517 | ); |
| 10518 | levels |
| 10519 | }; |
| 10520 | neighbours.record_mi_chroma(cu_mi, luma_span_x, luma_span_y, plane_idx, &levels); |
| 10521 | tiled_chroma_units.push(( |
| 10522 | cu_mi, |
| 10523 | plane_idx, |
| 10524 | levels.clone(), |
| 10525 | luma_span_x, |
| 10526 | luma_span_y, |
| 10527 | )); |
| 10528 | last[plane_idx - 1] = levels; |
| 10529 | } |
| 10530 | } |
| 10531 | } |
| 10532 | (last[0].clone(), last[1].clone()) |
| 10533 | } else { |
| 10534 | let (chroma_set, chroma_scan) = chroma.expect("refused above when None"); |
| 10535 | // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size |
| 10536 | // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra, |
| 10537 | // so only the 16x8/8x16 pair takes the mode-indexed default. |
| 10538 | let default_tx = if chroma_w.max(chroma_h) >= 32 { |
| 10539 | TxType::DctDct |
| 10540 | } else { |
| 10541 | default_intra_tx_type(m.uv_predict_mode as u8) |
| 10542 | }; |
| 10543 | let around = neighbours.around_mi_rect(at_mi, bw, bh); |
| 10544 | let mut grids: Vec<Grid> = Vec::with_capacity(2); |
| 10545 | for plane_idx in 1..=2 { |
| 10546 | let skip_ctx = |
| 10547 | usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1); |
| 10548 | let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode); |
| 10549 | let (levels, tx_type) = read_coeffs_rect( |
| 10550 | dec, |
| 10551 | &mut coding, |
| 10552 | chroma_scan, |
| 10553 | chroma_w, |
| 10554 | chroma_h, |
| 10555 | skip_ctx, |
| 10556 | dc_sign_ctx(around[plane_idx].2), |
| 10557 | default_tx, |
| 10558 | )?; |
| 10559 | // The same delta_q proof the unsplit rect64 path records |
| 10560 | // (lane-rectsplit r4: lifting the split-transform refusal moved |
| 10561 | // superblock strips onto this path, so only counting there would |
| 10562 | // leave the delta_q gate's counter silent for them). |
| 10563 | if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) { |
| 10564 | hit!(RECT64_QIDX_DRIFT_HITS); |
| 10565 | } |
| 10566 | let residual = dequant_and_inverse_typed_wh( |
| 10567 | &levels, |
| 10568 | chroma_w, |
| 10569 | chroma_h, |
| 10570 | crate::decode::bit_depth(fctx), |
| 10571 | // lane-d792: the BLOCK's quantizer index, i.e. the frame's |
| 10572 | // own index PLUS this block's segment `SEG_LVL_ALT_Q` -- |
| 10573 | // reading `current_q_idx` here dropped the segment feature |
| 10574 | // that every other dequant site applies (class |
| 10575 | // `parsed-then-discarded`). |
| 10576 | block_q_idx(fctx), |
| 10577 | plane_q_delta(plane_idx, fctx).0, |
| 10578 | plane_q_delta(plane_idx, fctx).1, |
| 10579 | tx_type, |
| 10580 | block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type), |
| 10581 | ); |
| 10582 | let cfl = m |
| 10583 | .alpha |
| 10584 | .zip(ac) |
| 10585 | .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)); |
| 10586 | let _plane = if plane_idx == 1 { &mut *u } else { &mut *v }; |
| 10587 | if let Some((ub, vb)) = &m.palette_uv { |
| 10588 | let buf = if plane_idx == 1 { ub } else { vb }; |
| 10589 | set_palette_pred(buf.clone(), fctx); |
| 10590 | } |
| 10591 | push_intra_rect(plane_idx, |
| 10592 | cpx, |
| 10593 | cpy, |
| 10594 | chroma_w, |
| 10595 | chroma_h, |
| 10596 | m.uv_predict_mode, |
| 10597 | m.angle_delta_uv, |
| 10598 | reach, |
| 10599 | &residual, |
| 10600 | cfl, |
| 10601 | None, |
| 10602 | m.smooth_neighbor_uv, fctx, |
| 10603 | ); |
| 10604 | grids.push(levels); |
| 10605 | } |
| 10606 | let mut it = grids.into_iter(); |
| 10607 | (it.next().unwrap(), it.next().unwrap()) |
| 10608 | }; |
| 10609 | neighbours.record_split_luma_rect_mi( |
| 10610 | at_mi, |
| 10611 | bw, |
| 10612 | bh, |
| 10613 | m.mode, |
| 10614 | m.uv_predict_mode, |
| 10615 | [&u_grid, &v_grid], |
| 10616 | ); |
| 10617 | for (cu_mi, plane, unit) in &ll_chroma_units { |
| 10618 | neighbours.record_mi_chroma(*cu_mi, 8, 8, *plane, unit); |
| 10619 | } |
| 10620 | for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units { |
| 10621 | neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit); |
| 10622 | } |
| 10623 | neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip); |
| 10624 | neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx); |
| 10625 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 10626 | let (rng, _) = dec.debug_state(); |
| 10627 | eprintln!( |
| 10628 | "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \ |
| 10629 | tx={tx_w}x{tx_h} rng={rng}" |
| 10630 | ); |
| 10631 | } |
| 10632 | Ok(()) |
| 10633 | } |
| 10634 | |
| 10635 | /// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect |
| 10636 | /// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name |
| 10637 | /// because it predicts squares only. Every pixel here goes through the rect |
| 10638 | /// machinery the key-frame paths already prove: [`decode_rect_split`], which |
| 10639 | /// at `depth == 0` is the unsplit strip as a single transform unit and |
| 10640 | /// beyond it the per-unit walk of [`depth_to_tx_wh`]. |
| 10641 | /// |
| 10642 | /// What is genuinely different from [`decode_block_rect`] is the mode |
| 10643 | /// syntax: on an inter frame an intra block reads `y_mode[size_group]` and |
| 10644 | /// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never |
| 10645 | /// the key frame's `kf_y_mode` above/left pair. This mirrors the square |
| 10646 | /// intra-in-inter arm's own reads at the rect footprint, including its |
| 10647 | /// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe |
| 10648 | /// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the |
| 10649 | /// square and this arm) and a nonzero luma angle delta refused by name. |
| 10650 | /// |
| 10651 | /// The strip's own neighbour records (luma per transform unit, chroma, skip |
| 10652 | /// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the |
| 10653 | /// inter-side bands and the mi map. |
| 10654 | #[allow(clippy::too_many_arguments)] |
| 10655 | /// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded |
| 10656 | /// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for |
| 10657 | /// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the |
| 10658 | /// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own |
| 10659 | /// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1 |
| 10660 | /// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 -> |
| 10661 | /// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but |
| 10662 | /// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a |
| 10663 | /// table here rather than a shift of `bw.min(bh)`. |
| 10664 | fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> { |
| 10665 | Some(match (bw.min(bh), bw.max(bh)) { |
| 10666 | (8, 16) => (1usize, 1usize), |
| 10667 | (16, 32) => (2, 2), |
| 10668 | (32, 64) => (3, 3), |
| 10669 | (8, 32) => (1, 2), |
| 10670 | (16, 64) => (2, 3), |
| 10671 | _ => return None, |
| 10672 | }) |
| 10673 | } |
| 10674 | |
| 10675 | /// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter |
| 10676 | /// block path"): the shapes that can reach that arm, enumerated against the |
| 10677 | /// MEASURED domain of the inter block path |
| 10678 | /// ([`INTER_BLOCK_SHAPES`], the census the gate |
| 10679 | /// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable` |
| 10680 | /// fills from three real streams). |
| 10681 | /// |
| 10682 | /// [`decode_intra_rect_in_inter`] is called from one site, under |
| 10683 | /// `write_w != side || write_h != side`, and only after two earlier arms have |
| 10684 | /// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16 |
| 10685 | /// strip WITH a chroma-pair record (the `strip16` branch) or refused by name, |
| 10686 | /// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is |
| 10687 | /// left is every rectangular census shape with `8 <= min` and `max <= 64` -- |
| 10688 | /// and each of those has a row, so the refusal names a shape no measured |
| 10689 | /// stream can present. |
| 10690 | #[test] |
| 10691 | fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() { |
| 10692 | let mut checked = 0; |
| 10693 | for &(side, w, h) in &INTER_BLOCK_SHAPES { |
| 10694 | if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 { |
| 10695 | continue; |
| 10696 | } |
| 10697 | assert!( |
| 10698 | intra_in_inter_size_row(w, h).is_some(), |
| 10699 | "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \ |
| 10700 | the \"no size-group/tx-category row\" refusal" |
| 10701 | ); |
| 10702 | checked += 1; |
| 10703 | } |
| 10704 | assert_eq!( |
| 10705 | checked, 10, |
| 10706 | "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \ |
| 10707 | lookup, not the 10 this claim was measured over" |
| 10708 | ); |
| 10709 | } |
| 10710 | |
| 10711 | /// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's |
| 10712 | /// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which |
| 10713 | /// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are |
| 10714 | /// matched before the square arm's `log2` shortcut). |
| 10715 | /// |
| 10716 | /// `None` is the refusal "a motion_mode symbol for a block shape with no CDF |
| 10717 | /// row here"; the enumeration below is what proves no conformant block can |
| 10718 | /// reach it. |
| 10719 | pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> { |
| 10720 | Some(match (write_w, write_h) { |
| 10721 | // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm |
| 10722 | // below maps 128 to row 4 (BLOCK_16X32). |
| 10723 | (64, 128) => 14, |
| 10724 | (128, 64) => 15, |
| 10725 | (128, 128) => 16, |
| 10726 | (w, h) if w == h => (w.trailing_zeros() - 3) as usize, |
| 10727 | (16, 32) => 4, |
| 10728 | (32, 16) => 5, |
| 10729 | (32, 64) => 6, |
| 10730 | (64, 32) => 7, |
| 10731 | (8, 32) => 8, |
| 10732 | (32, 8) => 9, |
| 10733 | (16, 64) => 10, |
| 10734 | (64, 16) => 11, |
| 10735 | // lane-inter4 r3: the 16x16-level rect inter leaves. |
| 10736 | (8, 16) => 12, |
| 10737 | (16, 8) => 13, |
| 10738 | _ => return None, |
| 10739 | }) |
| 10740 | } |
| 10741 | |
| 10742 | /// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six |
| 10743 | /// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`, |
| 10744 | /// `block_size_wide`/`block_size_high`). |
| 10745 | #[cfg(test)] |
| 10746 | const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [ |
| 10747 | (4, 4), |
| 10748 | (4, 8), |
| 10749 | (8, 4), |
| 10750 | (8, 8), |
| 10751 | (8, 16), |
| 10752 | (16, 8), |
| 10753 | (16, 16), |
| 10754 | (16, 32), |
| 10755 | (32, 16), |
| 10756 | (32, 32), |
| 10757 | (32, 64), |
| 10758 | (64, 32), |
| 10759 | (64, 64), |
| 10760 | (64, 128), |
| 10761 | (128, 64), |
| 10762 | (128, 128), |
| 10763 | (4, 16), |
| 10764 | (16, 4), |
| 10765 | (8, 32), |
| 10766 | (32, 8), |
| 10767 | (16, 64), |
| 10768 | (64, 16), |
| 10769 | ]; |
| 10770 | |
| 10771 | /// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block |
| 10772 | /// shape with no CDF row here" names a shape no conformant stream can present. |
| 10773 | /// |
| 10774 | /// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`, |
| 10775 | /// whose `write_w.min(write_h) >= 8` clause is libaom's |
| 10776 | /// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable |
| 10777 | /// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL` |
| 10778 | /// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those |
| 10779 | /// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The |
| 10780 | /// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility |
| 10781 | /// clause rejects before the lookup. |
| 10782 | #[test] |
| 10783 | fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() { |
| 10784 | let mut rows = std::collections::BTreeSet::new(); |
| 10785 | let mut excluded = 0; |
| 10786 | for (w, h) in BLOCK_SIZES_ALL_WH { |
| 10787 | if w.min(h) < 8 { |
| 10788 | excluded += 1; |
| 10789 | assert!( |
| 10790 | w == 4 || h == 4, |
| 10791 | "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects" |
| 10792 | ); |
| 10793 | continue; |
| 10794 | } |
| 10795 | let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| { |
| 10796 | panic!( |
| 10797 | "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \ |
| 10798 | symbol, but has no CDF row -- the refusal is a real gap, not a dead arm" |
| 10799 | ) |
| 10800 | }); |
| 10801 | assert!( |
| 10802 | row < 17, |
| 10803 | "{w}x{h} maps to motion_mode row {row}, outside the 17-row table" |
| 10804 | ); |
| 10805 | assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}"); |
| 10806 | } |
| 10807 | assert_eq!(excluded, 5, "the sub-8 footprint set changed"); |
| 10808 | assert_eq!( |
| 10809 | rows.len(), |
| 10810 | 17, |
| 10811 | "17 eligible footprints must fill all 17 rows of the motion_mode table" |
| 10812 | ); |
| 10813 | } |
| 10814 | |
| 10815 | fn decode_intra_rect_in_inter( |
| 10816 | dec: &mut SymbolDecoder, |
| 10817 | cdfs: &mut Cdfs, |
| 10818 | neighbours: &mut Neighbours, |
| 10819 | at: (usize, usize), |
| 10820 | bw: usize, |
| 10821 | bh: usize, |
| 10822 | skip: bool, |
| 10823 | allow_screen_content_tools: bool, |
| 10824 | // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the |
| 10825 | // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4). |
| 10826 | strip16: Option<(bool, bool)>, |
| 10827 | y: &mut PlaneBuf<'static>, |
| 10828 | u: &mut PlaneBuf<'static>, |
| 10829 | v: &mut PlaneBuf<'static>, |
| 10830 | base_q_idx: u8, fctx: &crate::decode::FrameCtx, |
| 10831 | ) -> Result<()> { |
| 10832 | // `at` is in MI units (the inter path's own unit since lane-inter4); |
| 10833 | // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands |
| 10834 | // below are still keyed by. |
| 10835 | let (mi_r, mi_c) = at; |
| 10836 | let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); |
| 10837 | // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat` |
| 10838 | // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 / |
| 10839 | // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx |
| 10840 | // finding -- the category is NOT the same for every strip size). |
| 10841 | // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so |
| 10842 | // it is refused by name rather than read from the wrong CDF row. |
| 10843 | // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup` |
| 10844 | // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its |
| 10845 | // tx-depth category is 1 -- but nothing here has to know either, because |
| 10846 | // the strip decodes through the very body the KEY FRAME path proves for |
| 10847 | // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma |
| 10848 | // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all, |
| 10849 | // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only |
| 10850 | // inter-frame difference is the mode-info read, which |
| 10851 | // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s |
| 10852 | // `y_mode[0]` plus the `skip` this caller already read. |
| 10853 | if let Some((horz, has_chroma)) = strip16 { |
| 10854 | // lane-t900 r22: the screen-content refusal here was STALE (class |
| 10855 | // stale-premise): [`decode_rect4_16_strip`] takes |
| 10856 | // `allow_screen_content_tools` and reads the whole palette syntax |
| 10857 | // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi` |
| 10858 | // pair) -- the key frame proves that body. Lifted with the 10-bit |
| 10859 | // witness `palette_screen_witness_10bit.obu`, whose inter frames carry |
| 10860 | // 16x4/4x16 intra strips inside a `--tune-content=screen` frame. |
| 10861 | debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) }); |
| 10862 | fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip)))); |
| 10863 | let res = decode_rect4_16_strip( |
| 10864 | dec, |
| 10865 | cdfs, |
| 10866 | neighbours, |
| 10867 | (mi_r, mi_c), |
| 10868 | horz, |
| 10869 | has_chroma, |
| 10870 | // The inter strips of the same partition publish their own |
| 10871 | // mi-exact mode, so the key-frame caller's coarse-cell stand-in |
| 10872 | // has nothing to add here. |
| 10873 | None, |
| 10874 | y, |
| 10875 | u, |
| 10876 | v, |
| 10877 | fctx.enable_filter_intra_inter.with(std::cell::Cell::get), |
| 10878 | allow_screen_content_tools, |
| 10879 | base_q_idx, |
| 10880 | fctx.tx_select_inter.with(std::cell::Cell::get), |
| 10881 | fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, |
| 10882 | ); |
| 10883 | fctx.intra_in_inter_mode.with(|c| c.set(None)); |
| 10884 | let (mode, uv, (tx_w, tx_h)) = res?; |
| 10885 | // lane-intra16x4, the same publication the 2:1 intra-in-inter strip |
| 10886 | // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs |
| 10887 | // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY |
| 10888 | // block of an inter frame, intra ones included, and |
| 10889 | // `txfm_partition_update` for the var-tx context. The key-frame body |
| 10890 | // writes neither (a key frame has no var-tx tree and its own readers |
| 10891 | // use the deblock grid), so the block AFTER this strip read a stale |
| 10892 | // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4 |
| 10893 | // strips at mi(23,16)/(23,20) exactly and then broke on the very next |
| 10894 | // 16x16 row. |
| 10895 | txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); |
| 10896 | for i in 0..bw / MI { |
| 10897 | if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) { |
| 10898 | *cell = tx_w as u8; |
| 10899 | } |
| 10900 | } |
| 10901 | for i in 0..bh / MI { |
| 10902 | if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) { |
| 10903 | *cell = tx_h as u8; |
| 10904 | } |
| 10905 | } |
| 10906 | // [`decode_rect4_16`]'s own post-loop publication, per strip (the |
| 10907 | // coarse 16-px cell holds one entry for the whole 16x16 and the last |
| 10908 | // block to write it wins). |
| 10909 | neighbours.above_mode[c] = mode; |
| 10910 | neighbours.left_mode[r] = mode; |
| 10911 | if let Some(uvm) = uv { |
| 10912 | neighbours.above_uv_mode[c] = uvm; |
| 10913 | neighbours.left_uv_mode[r] = uvm; |
| 10914 | } |
| 10915 | neighbours.above_side[c] = bw; |
| 10916 | neighbours.left_side[r] = bh; |
| 10917 | if crate::envflags::env_flag!("EC_INTRA16X4") { |
| 10918 | eprintln!( |
| 10919 | "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}", |
| 10920 | mi_c * MI, |
| 10921 | mi_r * MI |
| 10922 | ); |
| 10923 | } |
| 10924 | hit_do! { |
| 10925 | INTRA16X4_IN_INTER_HITS.with(|h| { |
| 10926 | let mut v = h.get(); |
| 10927 | v[usize::from(!horz)] += 1; |
| 10928 | v[2] += usize::from(has_chroma); |
| 10929 | h.set(v); |
| 10930 | }); |
| 10931 | } |
| 10932 | return Ok(()); |
| 10933 | } |
| 10934 | // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half |
| 10935 | // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61) |
| 10936 | // puts BLOCK_128X64/64X128/128X128 in group 3 and |
| 10937 | // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same |
| 10938 | // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole |
| 10939 | // block decodes through the very body the KEY FRAME path proves for this |
| 10940 | // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu |
| 10941 | // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk |
| 10942 | // `Reach` rule and the frame-edge write clip). The only inter-frame |
| 10943 | // differences live inside that body: the mode-info read |
| 10944 | // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller |
| 10945 | // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and |
| 10946 | // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and |
| 10947 | // palette (>64) do not exist at this size and are refused by name there. |
| 10948 | // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness. |
| 10949 | // `intra128_in_inter_witness2.obu` (gate |
| 10950 | // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`) |
| 10951 | // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of |
| 10952 | // all 15 frames, so the hits are counted out of exact frames (class |
| 10953 | // `counter-from-refused-stream`). What r16/r17 could not find, and what |
| 10954 | // that recipe exploits: libaom's RD essentially never PICKS a 128-root |
| 10955 | // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured |
| 10956 | // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears |
| 10957 | // where the frame EDGE forces it: a partial last superblock row has |
| 10958 | // `has_rows128 == false`, so the 128x64 top half is implied, and a |
| 10959 | // partial last column implies the 64x128 left half. Put content no |
| 10960 | // reference holds (a fresh smooth ramp) in exactly those two bands of an |
| 10961 | // inter frame and the encoder codes those forced halves INTRA. |
| 10962 | if bw.max(bh) == 128 { |
| 10963 | // lane-t900 r32: no screen-content refusal here. `av1_allow_palette` |
| 10964 | // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`, |
| 10965 | // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\ |
| 10966 | // palette_syntax`), so a 128-root half consumes no palette syntax and |
| 10967 | // a screen-content frame's half is syntactically identical to the |
| 10968 | // non-screen one this arm already decodes byte-exact. |
| 10969 | if coeff_trace_on() { |
| 10970 | // lane-t900 r16: which decode-order frame this arm fires in -- |
| 10971 | // interleaved with the `EC_COEFF_FRAME` markers, this is what |
| 10972 | // proves the hit is counted out of a frame that compares exact |
| 10973 | // (class `counter-from-refused-stream`). |
| 10974 | eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}"); |
| 10975 | } |
| 10976 | fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip)))); |
| 10977 | let res = decode_block_128rect( |
| 10978 | dec, |
| 10979 | cdfs, |
| 10980 | neighbours, |
| 10981 | (r, c), |
| 10982 | bw, |
| 10983 | bh, |
| 10984 | y, |
| 10985 | u, |
| 10986 | v, |
| 10987 | base_q_idx, |
| 10988 | fctx.enable_filter_intra_inter.with(std::cell::Cell::get), |
| 10989 | allow_screen_content_tools, |
| 10990 | fctx.tx_select_inter.with(std::cell::Cell::get), |
| 10991 | fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, |
| 10992 | ); |
| 10993 | fctx.intra_in_inter_mode.with(|c| c.set(None)); |
| 10994 | return res; |
| 10995 | } |
| 10996 | let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else { |
| 10997 | if crate::envflags::env_flag!("EC_OBMCREC") { |
| 10998 | eprintln!( |
| 10999 | "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}" |
| 11000 | ); |
| 11001 | } |
| 11002 | // lane-obmcrec r1: the message used to name a 16x4/4x16 strip |
| 11003 | // (class refusal-names-a-correlate). lane-t900 r20: the shapes that |
| 11004 | // can arrive here are enumerated against the measured block-shape |
| 11005 | // census ([`INTER_BLOCK_SHAPES`]) by |
| 11006 | // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`] |
| 11007 | // -- every one of them has a row, so this arm names a shape no stream |
| 11008 | // has been able to present. |
| 11009 | return Err(unsupported(format!( |
| 11010 | "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)" |
| 11011 | ))); |
| 11012 | }; |
| 11013 | // lane-t900 r21: this arm used to refuse EVERY rect strip of a |
| 11014 | // screen-content frame ("palette syntax is consumed for square blocks |
| 11015 | // only"). It is not: [`read_intra_mode_rect`] generalised the palette read |
| 11016 | // to rect blocks on the key-frame path, and the 1:4 arm below goes through |
| 11017 | // it, while the 2:1 reader inlined further down now codes the same syntax |
| 11018 | // itself. A real `--tune-content=screen` inter stream reached this refusal |
| 11019 | // on 8x16 / 16x8 strips (gate |
| 11020 | // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`). |
| 11021 | // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY |
| 11022 | // FRAME path already proves for this shape ([`decode_block_rect4`] at the |
| 11023 | // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4 |
| 11024 | // luma/chroma transform tables, the per-unit split walk and the strip's |
| 11025 | // own neighbour records). The ONLY difference on an inter frame is the |
| 11026 | // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to |
| 11027 | // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip` |
| 11028 | // this caller already read. `tx_cat` above is the same category those |
| 11029 | // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in |
| 11030 | // `decode_block_rect64`), asserted here so a future shape cannot drift. |
| 11031 | if bw.max(bh) == 4 * bw.min(bh) { |
| 11032 | debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 }); |
| 11033 | fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip)))); |
| 11034 | let res = if bw.max(bh) == 64 { |
| 11035 | decode_block_rect64( |
| 11036 | dec, |
| 11037 | cdfs, |
| 11038 | neighbours, |
| 11039 | (mi_r / (SUB / MI), mi_c / (SUB / MI)), |
| 11040 | bw, |
| 11041 | bh, |
| 11042 | y, |
| 11043 | u, |
| 11044 | v, |
| 11045 | fctx.enable_filter_intra_inter.with(std::cell::Cell::get), |
| 11046 | allow_screen_content_tools, |
| 11047 | base_q_idx, |
| 11048 | fctx.tx_select_inter.with(std::cell::Cell::get), |
| 11049 | fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, |
| 11050 | ) |
| 11051 | } else { |
| 11052 | decode_block_rect4( |
| 11053 | dec, |
| 11054 | cdfs, |
| 11055 | neighbours, |
| 11056 | (mi_r, mi_c), |
| 11057 | bw, |
| 11058 | bh, |
| 11059 | None, |
| 11060 | y, |
| 11061 | u, |
| 11062 | v, |
| 11063 | fctx.enable_filter_intra_inter.with(std::cell::Cell::get), |
| 11064 | allow_screen_content_tools, |
| 11065 | base_q_idx, |
| 11066 | fctx.tx_select_inter.with(std::cell::Cell::get), fctx, |
| 11067 | ) |
| 11068 | .map(|_| ()) |
| 11069 | }; |
| 11070 | fctx.intra_in_inter_mode.with(|c| c.set(None)); |
| 11071 | res?; |
| 11072 | let shape = match (bw, bh) { |
| 11073 | (64, 16) => 0, |
| 11074 | (16, 64) => 1, |
| 11075 | (32, 8) => 2, |
| 11076 | _ => 3, |
| 11077 | }; |
| 11078 | hit_do! { |
| 11079 | INTRA_RECT4_IN_INTER_HITS.with(|h| { |
| 11080 | let mut v = h.get(); |
| 11081 | v[shape] += 1; |
| 11082 | h.set(v); |
| 11083 | }); |
| 11084 | } |
| 11085 | return Ok(()); |
| 11086 | } |
| 11087 | let mode = dec.symbol(&mut cdfs.y_mode[size_group]); |
| 11088 | // lane-t900 r1: this arm read six mode symbols with no ladder rung of its |
| 11089 | // own, so a cross-decoder bisection could only see the block's first |
| 11090 | // coefficient. Same names/format as [`read_tx_size`]'s rung. |
| 11091 | let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); |
| 11092 | if step_trace { |
| 11093 | eprintln!( |
| 11094 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}", |
| 11095 | dec.debug_state().0 |
| 11096 | ); |
| 11097 | } |
| 11098 | if mode >= 13 { |
| 11099 | return Err(unsupported( |
| 11100 | "an intra mode this decoder does not code (round 2)", |
| 11101 | )); |
| 11102 | } |
| 11103 | // lane-angleinter (merged on main for the square intra-in-inter arm): |
| 11104 | // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the |
| 11105 | // directional predictor; this arm refused a nonzero one before the merge. |
| 11106 | let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { |
| 11107 | read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) |
| 11108 | } else { |
| 11109 | 0 |
| 11110 | }; |
| 11111 | if angle_delta_y != 0 { |
| 11112 | hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS); |
| 11113 | } |
| 11114 | // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the |
| 11115 | // superblock-level strip reads the no-CFL alphabet -- the same split |
| 11116 | // [`read_intra_mode_rect`] makes for [`decode_block_rect64`]. |
| 11117 | // |
| 11118 | // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol |
| 11119 | // (libaom `decodemv.c:933`). |
| 11120 | let has_chroma = !mono(fctx); |
| 11121 | let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx); |
| 11122 | let uv_mode = if !has_chroma { |
| 11123 | DC_PRED |
| 11124 | } else if cfl_allowed { |
| 11125 | dec.symbol(&mut cdfs.uv_mode_cfl[mode]) |
| 11126 | } else { |
| 11127 | dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) |
| 11128 | }; |
| 11129 | if step_trace { |
| 11130 | eprintln!( |
| 11131 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}", |
| 11132 | u8::from(cfl_allowed), |
| 11133 | dec.debug_state().0 |
| 11134 | ); |
| 11135 | } |
| 11136 | if (9..=12).contains(&uv_mode) { |
| 11137 | hit!(SMOOTH_UV_HITS); |
| 11138 | } |
| 11139 | let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED { |
| 11140 | Some(read_cfl_alphas(dec, cdfs)) |
| 11141 | } else { |
| 11142 | None |
| 11143 | }; |
| 11144 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { |
| 11145 | DC_PRED |
| 11146 | } else { |
| 11147 | uv_mode |
| 11148 | }; |
| 11149 | let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 11150 | hit!(DIRECTIONAL_UV_HITS); |
| 11151 | read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) |
| 11152 | } else { |
| 11153 | 0 |
| 11154 | }; |
| 11155 | if angle_delta_uv != 0 { |
| 11156 | hit!(UV_ANGLE_DELTA_HITS); |
| 11157 | hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS); |
| 11158 | } |
| 11159 | // `read_palette_mode_info` (spec 5.11.13), in the position |
| 11160 | // `read_intra_block_mode_info` writes it: after the chroma mode and |
| 11161 | // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter |
| 11162 | // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose |
| 11163 | // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so |
| 11164 | // skipping the syntax here desynced the tile at the strip's own symbol. |
| 11165 | // lane-t900 r22: reconstructed, not refused -- the strip's real mode |
| 11166 | // context and colour cache at its own mi position, and the two |
| 11167 | // colour-index maps decoded after `filter_intra` (`av1_visit_palette`), |
| 11168 | // exactly as [`read_intra_mode_rect`] does on the key-frame path. |
| 11169 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c)); |
| 11170 | let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c)); |
| 11171 | let mut palette_y_pending: Option<(usize, [u16; 8])> = None; |
| 11172 | let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; |
| 11173 | if allow_screen_content_tools |
| 11174 | && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) |
| 11175 | { |
| 11176 | hit!(INTRA_RECT_IN_INTER_SCREEN_HITS); |
| 11177 | let use_palette_y = |
| 11178 | mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0; |
| 11179 | if use_palette_y { |
| 11180 | let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); |
| 11181 | palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx))); |
| 11182 | } |
| 11183 | // A 2:1 strip of at least 8x8 is always a chroma reference, so |
| 11184 | // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here. |
| 11185 | // lane-av1mono: libaom's actual guard is `num_planes > 1 && |
| 11186 | // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602). |
| 11187 | let use_palette_uv = has_chroma |
| 11188 | && uv_mode == DC_PRED |
| 11189 | && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; |
| 11190 | if crate::envflags::env_flag!("EC_PALSYN") { |
| 11191 | 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); |
| 11192 | } |
| 11193 | if use_palette_uv { |
| 11194 | let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); |
| 11195 | let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx); |
| 11196 | palette_uv_pending = Some((n, u_colors, v_colors)); |
| 11197 | } |
| 11198 | } |
| 11199 | // lane-fiinter (merged on main for the square intra-in-inter arm): |
| 11200 | // `read_filter_intra_mode_info` is the tail of |
| 11201 | // `read_intra_block_mode_info`, after the palette syntax (refused whole |
| 11202 | // above for this shape), and `av1_filter_intra_allowed_bsize` admits the |
| 11203 | // 2:1 strips with both sides <= 32 -- their own CDF rows |
| 11204 | // ([`filter_intra_size_class_rect`]). |
| 11205 | let mut filter_intra = None; |
| 11206 | if mode == DC_PRED |
| 11207 | && fctx.enable_filter_intra_inter.with(std::cell::Cell::get) |
| 11208 | // `av1_filter_intra_allowed` excludes a palette-Y block. |
| 11209 | && palette_y_pending.is_none() |
| 11210 | && let Some(class) = filter_intra_size_class_rect(bw, bh) |
| 11211 | && dec.symbol(&mut cdfs.filter_intra[class]) != 0 |
| 11212 | { |
| 11213 | hit!(FILTER_INTRA_HITS); |
| 11214 | hit!(INTRA_IN_INTER_FILTER_INTRA_HITS); |
| 11215 | filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode)); |
| 11216 | } |
| 11217 | // `av1_visit_palette`: Y's colour-index map then the shared chroma one. |
| 11218 | let palette_y = palette_y_pending.map(|(n, colors)| { |
| 11219 | let map = |
| 11220 | decode_color_index_map_wh(dec, cdfs, n, bw, bh, palette_onscreen(mi_r, mi_c, bw, bh, fctx), false); |
| 11221 | hit!(PALETTE_HITS); |
| 11222 | hit!(PALETTE_RECT_HITS); |
| 11223 | hit!(INTRA_IN_INTER_PALETTE_Y_HITS); |
| 11224 | PaletteY { size: n, colors, map } |
| 11225 | }); |
| 11226 | let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { |
| 11227 | let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4)); |
| 11228 | let on = palette_onscreen_uv((bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch), (ss_x(fctx), ss_y(fctx))); |
| 11229 | let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true); |
| 11230 | hit!(PALETTE_UV_HITS); |
| 11231 | hit!(INTRA_IN_INTER_PALETTE_UV_HITS); |
| 11232 | PaletteUv { size: n, u_colors, v_colors, map } |
| 11233 | }); |
| 11234 | // The intra-edge filter type is the NEIGHBOUR's mode (libaom |
| 11235 | // `get_filt_type`), luma's off the luma neighbours and chroma's off the |
| 11236 | // chroma ones -- [`decode_block_rect`]'s own pair. |
| 11237 | // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left |
| 11238 | // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST |
| 11239 | // half. libaom's `above_mbmi`/`left_mbmi` are this block's own |
| 11240 | // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse |
| 11241 | // one exactly as [`decode_leaf8`] already does (class |
| 11242 | // context-read-from-one-cell). |
| 11243 | let coarse_pair = neighbours.modes_above_left(r, c); |
| 11244 | let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair); |
| 11245 | if (nb_above_mode, nb_left_mode) != coarse_pair { |
| 11246 | hit!(EDGE_FILTER_MI_FIX_HITS); |
| 11247 | } |
| 11248 | let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); |
| 11249 | if smooth_neighbor { |
| 11250 | hit!(SMOOTH_LUMA_HITS); |
| 11251 | } |
| 11252 | let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx); |
| 11253 | // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) |
| 11254 | // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside |
| 11255 | // an inter frame codes no depth symbol either (`xd->lossless` is per |
| 11256 | // segment regardless of frame type; class sweep of the sub8 leaf's fix). |
| 11257 | let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) { |
| 11258 | // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`]. |
| 11259 | let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx); |
| 11260 | let d = match tx_cat { |
| 11261 | 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]), |
| 11262 | 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]), |
| 11263 | _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]), |
| 11264 | }; |
| 11265 | if step_trace { |
| 11266 | eprintln!( |
| 11267 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}", |
| 11268 | dec.debug_state().0 |
| 11269 | ); |
| 11270 | } |
| 11271 | d |
| 11272 | } else { |
| 11273 | 0 |
| 11274 | }; |
| 11275 | if depth != 0 || lossless(fctx) { |
| 11276 | hit!(TX_DEPTH_HITS); |
| 11277 | // lane-intrasplit r1: a split intra strip in an inter frame walks the |
| 11278 | // key frame's own per-TU path ([`decode_rect_split`] below); what was |
| 11279 | // wrong when this refusal was written was the depth SYMBOL, not the walk. |
| 11280 | hit_do! { |
| 11281 | INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| { |
| 11282 | let mut v = h.get(); |
| 11283 | v[depth.min(2)] += 1; |
| 11284 | h.set(v); |
| 11285 | }); |
| 11286 | } |
| 11287 | } |
| 11288 | // lane-intrasplit r3: print EVERY intra strip with its depth, not only the |
| 11289 | // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and |
| 11290 | // the two are indistinguishable when the diagnostic fires on splits alone. |
| 11291 | if crate::envflags::env_flag!("EC_SPLITSTRIP") { |
| 11292 | eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}"); |
| 11293 | } |
| 11294 | let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); |
| 11295 | // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h, |
| 11296 | // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block |
| 11297 | // of an inter frame, intra ones included -- with the skip term 0 it |
| 11298 | // memsets `above_txfm_context` to `tx_size_wide` over the block's width |
| 11299 | // and `left_txfm_context` to `tx_size_high` over its height. This strip |
| 11300 | // wrote neither, so the next block's var-tx `txfm_partition` context read |
| 11301 | // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at |
| 11302 | // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at |
| 11303 | // mi(16,0) and desyncing the tile at that symbol. |
| 11304 | txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); |
| 11305 | let modes = RectStripModes { |
| 11306 | skip, |
| 11307 | mode, |
| 11308 | angle_delta_y, |
| 11309 | uv_predict_mode, |
| 11310 | angle_delta_uv, |
| 11311 | alpha, |
| 11312 | filter_intra, |
| 11313 | smooth_neighbor, |
| 11314 | smooth_neighbor_uv, |
| 11315 | palette_y: palette_y |
| 11316 | .as_ref() |
| 11317 | .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), |
| 11318 | palette_uv: palette_uv.as_ref().map(|p| { |
| 11319 | ( |
| 11320 | p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), |
| 11321 | p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), |
| 11322 | ) |
| 11323 | }), |
| 11324 | }; |
| 11325 | decode_rect_split( |
| 11326 | dec, |
| 11327 | cdfs, |
| 11328 | neighbours, |
| 11329 | (mi_r, mi_c), |
| 11330 | bw, |
| 11331 | bh, |
| 11332 | tx_w, |
| 11333 | tx_h, |
| 11334 | &modes, |
| 11335 | y, |
| 11336 | u, |
| 11337 | v, |
| 11338 | base_q_idx, |
| 11339 | fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, |
| 11340 | )?; |
| 11341 | // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of |
| 11342 | // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in |
| 11343 | // both `TXFM_CONTEXT` bands -- the above row over the block's width, the |
| 11344 | // left column over its height. This arm wrote neither before lane-intrasplit |
| 11345 | // r1, so every later block in the frame read a stale `tx_size`/`txfm_split` |
| 11346 | // context across the strip's footprint. |
| 11347 | for i in 0..bw / MI { |
| 11348 | if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) { |
| 11349 | *cell = tx_w as u8; |
| 11350 | } |
| 11351 | } |
| 11352 | for i in 0..bh / MI { |
| 11353 | if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) { |
| 11354 | *cell = tx_h as u8; |
| 11355 | } |
| 11356 | } |
| 11357 | // The strip's own palette state into the mi-granular neighbour bands, so |
| 11358 | // the next block's colour cache and `palette_y_mode` context are libaom's. |
| 11359 | record_strip_palette( |
| 11360 | neighbours, |
| 11361 | (mi_r, mi_c), |
| 11362 | bw, |
| 11363 | bh, |
| 11364 | palette_y.as_ref().map_or(0, |p| p.size), |
| 11365 | palette_y.as_ref().map_or([0u16; 8], |p| p.colors), |
| 11366 | palette_uv.as_ref().map_or(0, |p| p.size), |
| 11367 | palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors), |
| 11368 | ); |
| 11369 | let class = match bw.max(bh) { |
| 11370 | 64 => 0, |
| 11371 | 32 => 1, |
| 11372 | _ => 2, |
| 11373 | }; |
| 11374 | hit_do! { |
| 11375 | INTRA_RECT_IN_INTER_HITS.with(|h| { |
| 11376 | let mut v = h.get(); |
| 11377 | v[class] += 1; |
| 11378 | h.set(v); |
| 11379 | }); |
| 11380 | } |
| 11381 | Ok(()) |
| 11382 | } |
| 11383 | |
| 11384 | /// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real |
| 11385 | /// mi `(mi_r, mi_c)` (lane-av1-intrabc). |
| 11386 | /// |
| 11387 | /// libaom treats an intrabc block as INTER for everything except the mode-info |
| 11388 | /// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA` |
| 11389 | /// (`blockd.h:373`), so |
| 11390 | /// |
| 11391 | /// * `parse_decode_block` reads the transform size through the INTER var-tx |
| 11392 | /// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose |
| 11393 | /// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and |
| 11394 | /// whose leaves publish their own resolved size back; |
| 11395 | /// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT |
| 11396 | /// frame's own pre-loop-filter reconstruction, at the coded block vector |
| 11397 | /// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`); |
| 11398 | /// * `decode_token_recon_block`'s inter branch then reads one residual per |
| 11399 | /// transform unit, through the INTER coefficient sets |
| 11400 | /// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane |
| 11401 | /// inheriting the colocated luma unit's coded `tx_type`. |
| 11402 | /// |
| 11403 | /// Text order is libaom's: transform tree, prediction, luma residual, chroma |
| 11404 | /// residual, bookkeeping. A skipped block codes no residual at all -- the |
| 11405 | /// prediction is the reconstruction. |
| 11406 | #[allow(clippy::too_many_arguments)] |
| 11407 | fn decode_intrabc_rect( |
| 11408 | dec: &mut SymbolDecoder, |
| 11409 | cdfs: &mut Cdfs, |
| 11410 | neighbours: &mut Neighbours, |
| 11411 | (mi_r, mi_c): (usize, usize), |
| 11412 | (bw, bh): (usize, usize), |
| 11413 | skip: bool, |
| 11414 | (dv_row, dv_col): (i32, i32), |
| 11415 | y: &mut PlaneBuf<'static>, |
| 11416 | u: &mut PlaneBuf<'static>, |
| 11417 | v: &mut PlaneBuf<'static>, |
| 11418 | base_q_idx: u8, |
| 11419 | fctx: &crate::decode::FrameCtx, |
| 11420 | ) -> Result<()> { |
| 11421 | hit!(INTRABC_RECT_HITS); |
| 11422 | // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`. |
| 11423 | let idx = usize::from(bh > bw); |
| 11424 | if skip { |
| 11425 | INTRABC_RECT_SKIPPED_HITS.with(|c| { |
| 11426 | let mut seen = c.get(); |
| 11427 | seen[idx] += 1; |
| 11428 | c.set(seen); |
| 11429 | }); |
| 11430 | } else { |
| 11431 | INTRABC_RECT_CODED_HITS.with(|c| { |
| 11432 | let mut seen = c.get(); |
| 11433 | seen[idx] += 1; |
| 11434 | c.set(seen); |
| 11435 | }); |
| 11436 | } |
| 11437 | let (px, py) = (mi_c * MI, mi_r * MI); |
| 11438 | let (cpx, cpy) = (px / 2, py / 2); |
| 11439 | // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the |
| 11440 | // halved shape's own `max_txsize_rect_lookup` entry IS that size for every |
| 11441 | // shape this helper is called at, so the uv plane block is ONE unit -- |
| 11442 | // the same call `decode_token_recon_block`'s own chroma loop makes. |
| 11443 | let (cw, ch) = (bw / 2, bh / 2); |
| 11444 | // lane-av1-intrabc r2: the square stride the proven INTER path uses |
| 11445 | // (`side`). The residual grids, the prediction windows AND |
| 11446 | // `TxParams::stride` are all laid out at it -- the block's own width |
| 11447 | // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h` |
| 11448 | // exceeds the stride). |
| 11449 | let side = bw.max(bh); |
| 11450 | let cside = cw.max(ch); |
| 11451 | // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right |
| 11452 | // or bottom frame edge reads no transform-tree symbol for the units |
| 11453 | // outside it. |
| 11454 | let mi_cols = 2 * y.true_width.div_ceil(8); |
| 11455 | let mi_rows = 2 * y.true_height.div_ceil(8); |
| 11456 | let leaves = read_block_tx_size_rect( |
| 11457 | dec, |
| 11458 | cdfs, |
| 11459 | neighbours, |
| 11460 | (mi_r, mi_c), |
| 11461 | (bw, bh), |
| 11462 | (mi_cols, mi_rows), |
| 11463 | skip, fctx, |
| 11464 | )?; |
| 11465 | if leaves.is_some() { |
| 11466 | hit!(INTRABC_RECT_VARTX_HITS); |
| 11467 | } |
| 11468 | // The whole-block prediction: `predict_inter_block` runs once, before any |
| 11469 | // coefficient is read. `flush_recon` first -- the source is this frame's |
| 11470 | // own reconstruction, including the writes this superblock has queued. |
| 11471 | flush_recon(fctx, y, u, v); |
| 11472 | // `mc::predict_with_filter` writes a DENSE window; the residual machinery |
| 11473 | // reads it at the square stride, so re-lay it -- the same step the inter |
| 11474 | // path takes for its own square prediction buffer. |
| 11475 | let mut pred_y_dense = vec![0u16; bw * bh]; |
| 11476 | mc::predict_with_filter( |
| 11477 | &y.data, y.width, y.true_width, y.true_height, |
| 11478 | mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0), |
| 11479 | bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx, |
| 11480 | ); |
| 11481 | let mut pred_y = vec![0u16; side * side]; |
| 11482 | for row in 0..bh { |
| 11483 | pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]); |
| 11484 | } |
| 11485 | let mut pred_u_dense = vec![0u16; cw * ch]; |
| 11486 | mc::predict_with_filter( |
| 11487 | &u.data, u.width, u.true_width, u.true_height, |
| 11488 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), |
| 11489 | cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_u_dense, fctx, |
| 11490 | ); |
| 11491 | let mut pred_u = vec![0u16; cside * cside]; |
| 11492 | for row in 0..ch { |
| 11493 | pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]); |
| 11494 | } |
| 11495 | let mut pred_v_dense = vec![0u16; cw * ch]; |
| 11496 | mc::predict_with_filter( |
| 11497 | &v.data, v.width, v.true_width, v.true_height, |
| 11498 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), |
| 11499 | cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_v_dense, fctx, |
| 11500 | ); |
| 11501 | let mut pred_v = vec![0u16; cside * cside]; |
| 11502 | for row in 0..ch { |
| 11503 | pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]); |
| 11504 | } |
| 11505 | let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); |
| 11506 | let luma_tx_type: TxType; |
| 11507 | let (luma_grid, u_grid, v_grid); |
| 11508 | if skip { |
| 11509 | // No residual syntax at all: the prediction IS the block. |
| 11510 | // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes |
| 11511 | // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip |
| 11512 | // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm. |
| 11513 | push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * side], fctx); |
| 11514 | push_mc_rect(1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * cside], fctx); |
| 11515 | push_mc_rect(2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * cside], fctx); |
| 11516 | if let Some(ls) = leaves.as_ref() { |
| 11517 | // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s |
| 11518 | // skip arm performs -- libaom `av1_reset_entropy_context` |
| 11519 | // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a |
| 11520 | // SKIPPED block zeroes its whole entropy-band footprint. This |
| 11521 | // helper serves `decode_block_rect4`'s 1:4 strips on this tree, |
| 11522 | // so a skipped lossless strip whose `leaves` resolved (every |
| 11523 | // lossless frame -- `read_block_tx_size_rect`'s lossless arm |
| 11524 | // returns the 4x4 grid before it looks at `skip`) left the |
| 11525 | // PREVIOUS occupant's luma bands standing and the NEXT block's |
| 11526 | // partition parse diverged from libaom's: the 320x242 lossless |
| 11527 | // sb128 gate read a phantom unskipped 8x32 intrabc strip at |
| 11528 | // mi(56,66) right after the skipped 8x16 one at mi(48,66). |
| 11529 | hit!(SKIP_LOSSLESS_BAND_RESET_HITS); |
| 11530 | for &(row, col, tw, th) in ls { |
| 11531 | neighbours.record_mi_luma_rect( |
| 11532 | (mi_r + row, mi_c + col), |
| 11533 | tw, |
| 11534 | th, |
| 11535 | &ZERO_RESIDUAL[..tw * th], |
| 11536 | ); |
| 11537 | } |
| 11538 | } |
| 11539 | luma_tx_type = TxType::DctDct; |
| 11540 | luma_grid = Grid::Zero(side * side); |
| 11541 | u_grid = Grid::Zero(cside * cside); |
| 11542 | v_grid = Grid::Zero(cside * cside); |
| 11543 | } else { |
| 11544 | match leaves.as_ref() { |
| 11545 | None => { |
| 11546 | // One whole-block rectangular transform unit. |
| 11547 | let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); |
| 11548 | let (grid, tx_type) = read_inter_plane_rect( |
| 11549 | dec, |
| 11550 | cdfs, |
| 11551 | rect_inter_luma_set(bw, bh, fctx)?, |
| 11552 | (bw, bh), |
| 11553 | side, |
| 11554 | 0, |
| 11555 | around[0], |
| 11556 | 0, |
| 11557 | y, |
| 11558 | px, |
| 11559 | py, |
| 11560 | Pred::Inline(&pred_y, side), |
| 11561 | None, |
| 11562 | None, fctx, |
| 11563 | )?; |
| 11564 | luma_tx_type = tx_type; |
| 11565 | luma_grid = embed_grid_stride(&grid, bw, bh, side); |
| 11566 | let (ug, _) = read_inter_plane_rect( |
| 11567 | dec, |
| 11568 | cdfs, |
| 11569 | rect_inter_chroma_set(cw, ch)?, |
| 11570 | (cw, ch), |
| 11571 | cside, |
| 11572 | 1, |
| 11573 | around[1], |
| 11574 | 0, |
| 11575 | u, |
| 11576 | cpx, |
| 11577 | cpy, |
| 11578 | Pred::Inline(&pred_u, cside), |
| 11579 | Some(luma_tx_type), |
| 11580 | None, fctx, |
| 11581 | )?; |
| 11582 | u_grid = embed_grid_stride(&ug, cw, ch, cside); |
| 11583 | let (vg, _) = read_inter_plane_rect( |
| 11584 | dec, |
| 11585 | cdfs, |
| 11586 | rect_inter_chroma_set(cw, ch)?, |
| 11587 | (cw, ch), |
| 11588 | cside, |
| 11589 | 2, |
| 11590 | around[2], |
| 11591 | 0, |
| 11592 | v, |
| 11593 | cpx, |
| 11594 | cpy, |
| 11595 | Pred::Inline(&pred_v, cside), |
| 11596 | Some(luma_tx_type), |
| 11597 | None, fctx, |
| 11598 | )?; |
| 11599 | v_grid = embed_grid_stride(&vg, cw, ch, cside); |
| 11600 | } |
| 11601 | Some(leaves) => { |
| 11602 | // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies |
| 11603 | // the split override to LUMA only, per leaf -- the step the |
| 11604 | // proven inter var-tx path applies right after its own residual |
| 11605 | // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the |
| 11606 | // leaf's own transform edges are never filtered. |
| 11607 | for &(row, col, tw, th) in leaves.iter() { |
| 11608 | neighbours.fill_lf_grid_leaf_luma( |
| 11609 | (mi_r + row, mi_c + col), |
| 11610 | tw / MI, |
| 11611 | th / MI, |
| 11612 | tw as u8, |
| 11613 | th as u8, |
| 11614 | ); |
| 11615 | } |
| 11616 | // One residual per transform unit, in the order the tree coded |
| 11617 | // them; each unit reads its own neighbour-magnitude context off |
| 11618 | // the units already decoded before it, and every unit adds onto |
| 11619 | // its own window of the block's single prediction. |
| 11620 | let mut first_tx_type = TxType::DctDct; |
| 11621 | for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() { |
| 11622 | let tu_mi = (mi_r + row, mi_c + col); |
| 11623 | let (tu_px, tu_py) = (px + col * MI, py + row * MI); |
| 11624 | let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); |
| 11625 | let (tu_grid, tu_tx_type) = if tw == th { |
| 11626 | let scan = default_scan(tw.min(32)); |
| 11627 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI); |
| 11628 | read_inter_plane( |
| 11629 | dec, |
| 11630 | cdfs, |
| 11631 | inter_txbset_for(tw, reduced), |
| 11632 | scan, |
| 11633 | 0, |
| 11634 | neighbours.around_mi(tu_mi, tw)[0], |
| 11635 | 0, |
| 11636 | y, |
| 11637 | tu_px, |
| 11638 | tu_py, |
| 11639 | tw, |
| 11640 | base_q_idx, |
| 11641 | tu_pred, |
| 11642 | None, |
| 11643 | Some(tu_skip_ctx), fctx, |
| 11644 | )? |
| 11645 | } else { |
| 11646 | let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI); |
| 11647 | read_inter_plane_rect( |
| 11648 | dec, |
| 11649 | cdfs, |
| 11650 | rect_inter_luma_set(tw, th, fctx)?, |
| 11651 | (tw, th), |
| 11652 | side, |
| 11653 | 0, |
| 11654 | neighbours.around_mi_rect(tu_mi, tw, th)[0], |
| 11655 | 0, |
| 11656 | y, |
| 11657 | tu_px, |
| 11658 | tu_py, |
| 11659 | tu_pred, |
| 11660 | None, |
| 11661 | Some(tu_skip_ctx), fctx, |
| 11662 | )? |
| 11663 | }; |
| 11664 | if idx == 0 { |
| 11665 | first_tx_type = tu_tx_type; |
| 11666 | } |
| 11667 | neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid); |
| 11668 | } |
| 11669 | // `av1_get_tx_type`'s chroma lookup lands on the colocated |
| 11670 | // LUMA unit, which for a split block is the top-left one. |
| 11671 | luma_tx_type = first_tx_type; |
| 11672 | let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); |
| 11673 | let (ug, _) = read_inter_plane_rect( |
| 11674 | dec, |
| 11675 | cdfs, |
| 11676 | rect_inter_chroma_set(cw, ch)?, |
| 11677 | (cw, ch), |
| 11678 | cside, |
| 11679 | 1, |
| 11680 | around[1], |
| 11681 | 0, |
| 11682 | u, |
| 11683 | cpx, |
| 11684 | cpy, |
| 11685 | Pred::Inline(&pred_u, cside), |
| 11686 | Some(luma_tx_type), |
| 11687 | None, fctx, |
| 11688 | )?; |
| 11689 | u_grid = embed_grid_stride(&ug, cw, ch, cside); |
| 11690 | let (vg, _) = read_inter_plane_rect( |
| 11691 | dec, |
| 11692 | cdfs, |
| 11693 | rect_inter_chroma_set(cw, ch)?, |
| 11694 | (cw, ch), |
| 11695 | cside, |
| 11696 | 2, |
| 11697 | around[2], |
| 11698 | 0, |
| 11699 | v, |
| 11700 | cpx, |
| 11701 | cpy, |
| 11702 | Pred::Inline(&pred_v, cside), |
| 11703 | Some(luma_tx_type), |
| 11704 | None, fctx, |
| 11705 | )?; |
| 11706 | v_grid = embed_grid_stride(&vg, cw, ch, cside); |
| 11707 | luma_grid = Grid::Zero(side * side); |
| 11708 | } |
| 11709 | } |
| 11710 | } |
| 11711 | let _ = luma_tx_type; |
| 11712 | // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the |
| 11713 | // next block reads a neighbour mode, its own block size in both `TXFM` |
| 11714 | // bands (already done by `read_block_tx_size_rect`), a zeroed palette |
| 11715 | // state (a stale entry would feed the next block's colour cache), and its |
| 11716 | // DV into the intrabc mi grid the next block's DV predictor reads. |
| 11717 | if leaves.is_some() { |
| 11718 | neighbours.record_split_luma_rect_mi( |
| 11719 | (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid], |
| 11720 | ); |
| 11721 | } else { |
| 11722 | neighbours.record_rect_mi( |
| 11723 | (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid], |
| 11724 | ); |
| 11725 | } |
| 11726 | neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); |
| 11727 | neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); |
| 11728 | neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); |
| 11729 | neighbours.fill_lf_grid_rect( |
| 11730 | (mi_r, mi_c), |
| 11731 | bw / MI, |
| 11732 | bh / MI, |
| 11733 | bw.min(64) as u8, |
| 11734 | bh.min(64) as u8, |
| 11735 | 0, fctx, |
| 11736 | ); |
| 11737 | record_intrabc_mi_rect( |
| 11738 | mi_r, |
| 11739 | mi_c, |
| 11740 | bw / MI, |
| 11741 | bh / MI, |
| 11742 | Some((dv_row, dv_col)), |
| 11743 | neighbours, |
| 11744 | fctx, |
| 11745 | ); |
| 11746 | Ok(()) |
| 11747 | } |
| 11748 | |
| 11749 | /// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root |
| 11750 | /// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape |
| 11751 | /// `decode_block_128rect` refused by name before this port. libaom decodes |
| 11752 | /// such a block through the INTER machinery (an intrabc block |
| 11753 | /// `is_inter_block`): `predict_inter_block` copies the whole block from this |
| 11754 | /// frame's own reconstruction at the integer block vector once, then |
| 11755 | /// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks -- |
| 11756 | /// per chunk every plane, luma units at the block's own resolved transform |
| 11757 | /// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at |
| 11758 | /// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per |
| 11759 | /// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits |
| 11760 | /// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`, |
| 11761 | /// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in |
| 11762 | /// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here. |
| 11763 | #[allow(clippy::too_many_arguments)] |
| 11764 | fn decode_intrabc_128rect( |
| 11765 | dec: &mut SymbolDecoder, |
| 11766 | cdfs: &mut Cdfs, |
| 11767 | neighbours: &mut Neighbours, |
| 11768 | (mi_r, mi_c): (usize, usize), |
| 11769 | (bw, bh): (usize, usize), |
| 11770 | skip: bool, |
| 11771 | (dv_row, dv_col): (i32, i32), |
| 11772 | y: &mut PlaneBuf<'static>, |
| 11773 | u: &mut PlaneBuf<'static>, |
| 11774 | v: &mut PlaneBuf<'static>, |
| 11775 | base_q_idx: u8, |
| 11776 | fctx: &crate::decode::FrameCtx, |
| 11777 | ) -> Result<()> { |
| 11778 | hit!(INTRABC_128RECT_HITS); |
| 11779 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 11780 | let (rng, _) = dec.debug_state(); |
| 11781 | eprintln!( |
| 11782 | "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}" |
| 11783 | ); |
| 11784 | } |
| 11785 | let (px, py) = (mi_c * MI, mi_r * MI); |
| 11786 | let (cpx, cpy) = (px / 2, py / 2); |
| 11787 | let (cw, ch) = (bw / 2, bh / 2); |
| 11788 | // The square strides the proven INTER path lays its residual grids, |
| 11789 | // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2 |
| 11790 | // note): 128/64 here. |
| 11791 | let side = bw.max(bh); |
| 11792 | let cside = cw.max(ch); |
| 11793 | // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code |
| 11794 | // nothing (`decode_reconstruct_tx`'s max_blocks_* early return). |
| 11795 | let mi_cols = 2 * y.true_width.div_ceil(8); |
| 11796 | let mi_rows = 2 * y.true_height.div_ceil(8); |
| 11797 | // An intrabc block is is_inter_block: the tx tree is the INTER one, and |
| 11798 | // [`read_block_tx_size_rect`]'s 128-root branch already carries the |
| 11799 | // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree |
| 11800 | // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid) |
| 11801 | // arms (lane-sb128c r7). |
| 11802 | let leaves = read_block_tx_size_rect( |
| 11803 | dec, |
| 11804 | cdfs, |
| 11805 | neighbours, |
| 11806 | (mi_r, mi_c), |
| 11807 | (bw, bh), |
| 11808 | (mi_cols, mi_rows), |
| 11809 | skip, fctx, |
| 11810 | )?; |
| 11811 | // Whole-block prediction, once, before any coefficient is read |
| 11812 | // (`predict_inter_block`); the source is this frame's own |
| 11813 | // reconstruction, including the writes this superblock has queued. |
| 11814 | flush_recon(fctx, y, u, v); |
| 11815 | let mut pred_y_dense = vec![0u16; bw * bh]; |
| 11816 | mc::predict_with_filter( |
| 11817 | &y.data, y.width, y.true_width, y.true_height, |
| 11818 | mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0), |
| 11819 | bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx, |
| 11820 | ); |
| 11821 | let mut pred_y = vec![0u16; side * side]; |
| 11822 | for row in 0..bh { |
| 11823 | pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]); |
| 11824 | } |
| 11825 | let mut pred_u_dense = vec![0u16; cw * ch]; |
| 11826 | mc::predict_with_filter( |
| 11827 | &u.data, u.width, u.true_width, u.true_height, |
| 11828 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), |
| 11829 | cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_u_dense, fctx, |
| 11830 | ); |
| 11831 | let mut pred_u = vec![0u16; cside * cside]; |
| 11832 | for row in 0..ch { |
| 11833 | pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]); |
| 11834 | } |
| 11835 | let mut pred_v_dense = vec![0u16; cw * ch]; |
| 11836 | mc::predict_with_filter( |
| 11837 | &v.data, v.width, v.true_width, v.true_height, |
| 11838 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), |
| 11839 | cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_v_dense, fctx, |
| 11840 | ); |
| 11841 | let mut pred_v = vec![0u16; cside * cside]; |
| 11842 | for row in 0..ch { |
| 11843 | pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]); |
| 11844 | } |
| 11845 | let (luma_grid, u_grid, v_grid); |
| 11846 | // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour |
| 11847 | // contexts per transform unit -- the replay after this fn's end-of-block |
| 11848 | // record restores them (the record itself re-stamps both planes with ONE |
| 11849 | // composed state, class `override-slot-on-one-arm`). |
| 11850 | let mut mu_chroma = false; |
| 11851 | if skip { |
| 11852 | // No residual syntax at all: the prediction IS the block. Strides are |
| 11853 | // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes |
| 11854 | // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun). |
| 11855 | push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * side], fctx); |
| 11856 | push_mc_rect(1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * cside], fctx); |
| 11857 | push_mc_rect(2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * cside], fctx); |
| 11858 | if let Some(ls) = leaves.as_ref() { |
| 11859 | // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4 |
| 11860 | // grid before it looks at `skip`; the skipped block still zeroes |
| 11861 | // its entropy-band footprint over every unit (libaom |
| 11862 | // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) -- |
| 11863 | // the same arm [`decode_intrabc_rect`]'s loss64 merge added. |
| 11864 | hit!(SKIP_LOSSLESS_BAND_RESET_HITS); |
| 11865 | for &(row, col, tw, th) in ls { |
| 11866 | neighbours.record_mi_luma_rect( |
| 11867 | (mi_r + row, mi_c + col), |
| 11868 | tw, |
| 11869 | th, |
| 11870 | &ZERO_RESIDUAL[..tw * th], |
| 11871 | ); |
| 11872 | } |
| 11873 | } |
| 11874 | luma_grid = Grid::Zero(side * side); |
| 11875 | u_grid = Grid::Zero(cside * cside); |
| 11876 | v_grid = Grid::Zero(cside * cside); |
| 11877 | } else { |
| 11878 | let leaves = leaves.expect( |
| 11879 | "read_block_tx_size_rect returns None only for skip below 128 at this shape", |
| 11880 | ); |
| 11881 | // libaom `get_transform_size`'s split override applies to LUMA only, |
| 11882 | // per leaf -- each unit's own transform edges get filtered |
| 11883 | // ([`decode_intrabc_rect`]'s P2, the proven inter path's step). |
| 11884 | for &(row, col, tw, th) in leaves.iter() { |
| 11885 | neighbours.fill_lf_grid_leaf_luma( |
| 11886 | (mi_r + row, mi_c + col), |
| 11887 | tw / MI, |
| 11888 | th / MI, |
| 11889 | tw as u8, |
| 11890 | th as u8, |
| 11891 | ); |
| 11892 | } |
| 11893 | let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); |
| 11894 | let mut u_units: Vec<i32> = Vec::new(); |
| 11895 | let mut v_units: Vec<i32> = Vec::new(); |
| 11896 | let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new(); |
| 11897 | // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose |
| 11898 | // top-left sample is outside the frame codes nothing. |
| 11899 | let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c)); |
| 11900 | let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r)); |
| 11901 | for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() { |
| 11902 | debug_assert_eq!(tw, th, "a square TX_64X64 tree root only yields square leaves"); |
| 11903 | let tu_mi = (mi_r + row, mi_c + col); |
| 11904 | let (tu_px, tu_py) = (px + col * MI, py + row * MI); |
| 11905 | if tu_px >= y.true_width || tu_py >= y.true_height { |
| 11906 | continue; |
| 11907 | } |
| 11908 | let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); |
| 11909 | let scan = default_scan(tw.min(32)); |
| 11910 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI); |
| 11911 | let (tu_grid, tu_tx_type) = read_inter_plane( |
| 11912 | dec, |
| 11913 | cdfs, |
| 11914 | inter_txbset_for(tw, reduced), |
| 11915 | &scan, |
| 11916 | 0, |
| 11917 | neighbours.around_mi(tu_mi, tw)[0], |
| 11918 | 0, |
| 11919 | y, |
| 11920 | tu_px, |
| 11921 | tu_py, |
| 11922 | tw, |
| 11923 | base_q_idx, |
| 11924 | tu_pred, |
| 11925 | None, |
| 11926 | Some(tu_skip_ctx), fctx, |
| 11927 | )?; |
| 11928 | leaf_tx_types.push((row, col, tw, th, tu_tx_type)); |
| 11929 | neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid); |
| 11930 | // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64 |
| 11931 | // mu chunk before the next one starts: once this chunk's leaves |
| 11932 | // are done, its chroma is read immediately (the inter 128 path's |
| 11933 | // interleave). |
| 11934 | let chunk = (row / 16, col / 16); |
| 11935 | let done = idx + 1 == leaves.len() |
| 11936 | || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk; |
| 11937 | if done { |
| 11938 | let (cr, cc) = chunk; |
| 11939 | // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one |
| 11940 | // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster |
| 11941 | // within the chunk, plane-major inside the chunk. |
| 11942 | let cu_tx = 32usize; |
| 11943 | let chunk_chroma = cside * 64 / side; |
| 11944 | let unit_luma = cu_tx * (side / cside); |
| 11945 | let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16)); |
| 11946 | let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16)); |
| 11947 | let units_x = chunk_w_mi / (unit_luma / MI); |
| 11948 | let units_y = chunk_h_mi / (unit_luma / MI); |
| 11949 | if lossless(fctx) { |
| 11950 | // TX_4X4 chroma units over this chunk (lane-lossless2's |
| 11951 | // walk, shared with the inter 128 path). |
| 11952 | read_inter_chroma_lossless( |
| 11953 | dec, cdfs, neighbours, u, v, |
| 11954 | Pred::Inline(&pred_u, cside), Pred::Inline(&pred_v, cside), |
| 11955 | (mi_r, mi_c), (cpx, cpy), |
| 11956 | (cc * chunk_chroma, cr * chunk_chroma), |
| 11957 | (chunk_chroma, chunk_chroma), |
| 11958 | (cw, ch), |
| 11959 | cside, 0, base_q_idx, |
| 11960 | &mut u_units, &mut v_units, fctx, |
| 11961 | )?; |
| 11962 | // lane-av1-ibcrect: read_inter_chroma_lossless stamped |
| 11963 | // every TX_4X4 unit's own context (`record_mi_chroma` |
| 11964 | // inside the walk) -- the end-of-block record below must |
| 11965 | // not overwrite them with the composed grid (the inter |
| 11966 | // 128 path sets the same flag on this arm). |
| 11967 | mu_chroma = true; |
| 11968 | continue; |
| 11969 | } |
| 11970 | let cu_scan = default_scan(cu_tx); |
| 11971 | for plane_idx in 1..3 { |
| 11972 | let (src, buf) = if plane_idx == 1 { |
| 11973 | (Pred::Inline(&pred_u, cside), &mut *u) |
| 11974 | } else { |
| 11975 | (Pred::Inline(&pred_v, cside), &mut *v) |
| 11976 | }; |
| 11977 | for ur in 0..units_y { |
| 11978 | for uc in 0..units_x { |
| 11979 | let unit_mi = ( |
| 11980 | mi_r + cr * 16 + ur * (unit_luma / MI), |
| 11981 | mi_c + cc * 16 + uc * (unit_luma / MI), |
| 11982 | ); |
| 11983 | // Per unit, AFTER the earlier units' stamps: this |
| 11984 | // unit's coefficient context must see them. |
| 11985 | let cu_around = neighbours.around_mi(unit_mi, unit_luma); |
| 11986 | if crate::envflags::env_flag!("EC_ECDUMP") { |
| 11987 | for p in 1..3 { |
| 11988 | let ab: Vec<String> = (0..unit_luma / MI) |
| 11989 | .map(|k| { |
| 11990 | format!( |
| 11991 | "{:?}/{}", |
| 11992 | neighbours.above[unit_mi.1 + k][p].dc, |
| 11993 | neighbours.above[unit_mi.1 + k][p].level |
| 11994 | ) |
| 11995 | }) |
| 11996 | .collect(); |
| 11997 | let lf: Vec<String> = (0..unit_luma / MI) |
| 11998 | .map(|k| { |
| 11999 | format!( |
| 12000 | "{:?}/{}", |
| 12001 | neighbours.left[unit_mi.0 + k][p].dc, |
| 12002 | neighbours.left[unit_mi.0 + k][p].level |
| 12003 | ) |
| 12004 | }) |
| 12005 | .collect(); |
| 12006 | eprintln!( |
| 12007 | "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]", |
| 12008 | cu_around[p].0, cu_around[p].1, cu_around[p].2, ab.join(","), lf.join(",") |
| 12009 | ); |
| 12010 | } |
| 12011 | } |
| 12012 | let (cu_x, cu_y) = ( |
| 12013 | cpx + cc * chunk_chroma + uc * cu_tx, |
| 12014 | cpy + cr * chunk_chroma + ur * cu_tx, |
| 12015 | ); |
| 12016 | // `av1_get_tx_type` (blockd.h:1291): an inter |
| 12017 | // block's chroma unit never codes a tx_type; it |
| 12018 | // inherits the coded type of the luma leaf |
| 12019 | // covering its own quadrant (all of this chunk's |
| 12020 | // leaves are read by now). |
| 12021 | let unit_rel_mi = ( |
| 12022 | unit_mi.0 - mi_r, |
| 12023 | unit_mi.1 - mi_c, |
| 12024 | ); |
| 12025 | let covering = leaf_tx_types |
| 12026 | .iter() |
| 12027 | .copied() |
| 12028 | .find(|&(lr, lc, lw, lh, _)| { |
| 12029 | lr <= unit_rel_mi.0 |
| 12030 | && unit_rel_mi.0 < lr + lh / MI |
| 12031 | && lc <= unit_rel_mi.1 |
| 12032 | && unit_rel_mi.1 < lc + lw / MI |
| 12033 | }) |
| 12034 | .map(|(_, _, _, _, t)| t); |
| 12035 | let cu_pred = src.offset( |
| 12036 | (cr * chunk_chroma + ur * cu_tx) * cside |
| 12037 | + cc * chunk_chroma |
| 12038 | + uc * cu_tx, |
| 12039 | ); |
| 12040 | let cu_grid = read_inter_plane( |
| 12041 | dec, |
| 12042 | cdfs, |
| 12043 | TxbSet::Chroma32, |
| 12044 | &cu_scan, |
| 12045 | plane_idx, |
| 12046 | cu_around[plane_idx], |
| 12047 | 0, |
| 12048 | buf, |
| 12049 | cu_x, |
| 12050 | cu_y, |
| 12051 | cu_tx, |
| 12052 | base_q_idx, |
| 12053 | cu_pred, |
| 12054 | Some(covering.unwrap_or(TxType::DctDct)), |
| 12055 | Some(3), fctx, |
| 12056 | )? |
| 12057 | .0; |
| 12058 | // Immediately, so the NEXT unit reads this one's |
| 12059 | // coefficient context. |
| 12060 | neighbours.record_mi_chroma( |
| 12061 | unit_mi, |
| 12062 | unit_luma, |
| 12063 | unit_luma, |
| 12064 | plane_idx, |
| 12065 | &cu_grid, |
| 12066 | ); |
| 12067 | if crate::envflags::env_flag!("EC_ECDUMP") { |
| 12068 | let st = crate::decode::neighbour_state(&cu_grid); |
| 12069 | eprintln!( |
| 12070 | "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})", |
| 12071 | st.dc, st.level |
| 12072 | ); |
| 12073 | } |
| 12074 | hit!(CHROMA_SPLIT_TX_HITS); |
| 12075 | // lane-av1-ibcrect: per-unit chroma context -- the |
| 12076 | // end-of-block record's composed-grid re-stamp |
| 12077 | // must not stand (replayed below). |
| 12078 | mu_chroma = true; |
| 12079 | let dst = mu_units( |
| 12080 | if plane_idx == 1 { &mut u_units } else { &mut v_units }, |
| 12081 | cside * cside, |
| 12082 | ); |
| 12083 | for rr in 0..cu_tx { |
| 12084 | let start = (cr * chunk_chroma + ur * cu_tx + rr) |
| 12085 | * cside |
| 12086 | + cc * chunk_chroma |
| 12087 | + uc * cu_tx; |
| 12088 | dst[start..start + cu_tx] |
| 12089 | .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]); |
| 12090 | } |
| 12091 | } |
| 12092 | } |
| 12093 | } |
| 12094 | } |
| 12095 | } |
| 12096 | // The block-level luma bands were recorded per leaf above; the |
| 12097 | // composed chroma grids carry every unit in place. |
| 12098 | luma_grid = Grid::Zero(side * side); |
| 12099 | u_grid = if u_units.is_empty() { |
| 12100 | Grid::Zero(cside * cside) |
| 12101 | } else { |
| 12102 | Grid::Own(std::mem::take(&mut u_units)) |
| 12103 | }; |
| 12104 | v_grid = if v_units.is_empty() { |
| 12105 | Grid::Zero(cside * cside) |
| 12106 | } else { |
| 12107 | Grid::Own(std::mem::take(&mut v_units)) |
| 12108 | }; |
| 12109 | } |
| 12110 | // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a |
| 12111 | // neighbour reads a mode, zeroed palette state, the skip grid, the |
| 12112 | // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them), |
| 12113 | // and the DV into the intrabc mi grid. |
| 12114 | if skip { |
| 12115 | neighbours.record_rect_mi( |
| 12116 | (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, |
| 12117 | &[&luma_grid[..], &u_grid[..], &v_grid[..]], |
| 12118 | ); |
| 12119 | } else { |
| 12120 | neighbours.record_split_luma_rect_mi( |
| 12121 | (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid[..], &v_grid[..]], |
| 12122 | ); |
| 12123 | } |
| 12124 | // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER |
| 12125 | // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside |
| 12126 | // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps |
| 12127 | // both planes with ONE `neighbour_state(composed_grid)` over the whole |
| 12128 | // span -- level = the SUM of every unit's levels and dc = the top-left |
| 12129 | // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128 |
| 12130 | // inter block: the next block read a stale `dc_sign_ctx` one row low). |
| 12131 | // Measured on this shape: the 128x64 block at mi(64,32) of the |
| 12132 | // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared |
| 12133 | // into chunk-0's cells and the block below read `txb_skip` off the sum. |
| 12134 | // Replay every coded unit's own state after the record, in mu-chunk order |
| 12135 | // so a later unit still wins over an earlier one on the shared seam cells |
| 12136 | // (the composed construction `mu_chroma_units` uses, transcribed here). |
| 12137 | if mu_chroma { |
| 12138 | let cu = if lossless(fctx) { 4usize } else { 32usize }; |
| 12139 | // The unit's own footprint on the LUMA mi grid (the chroma context |
| 12140 | // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s |
| 12141 | // convention): 8 px x2 per TX_4X4 unit, 64 px per TX_32X32 one. |
| 12142 | let unit_luma = cu * 2; |
| 12143 | // Raster over the block's chroma plane, `chunk_chroma` per mu chunk |
| 12144 | // (the same extents the read loop above laid the composed grid out |
| 12145 | // at) -- a unit the frame edge clipped codes nothing and carries no |
| 12146 | // composed samples beyond the clip, so it replays as the zero state |
| 12147 | // exactly like libaom's uncoded unit. |
| 12148 | let chunk_chroma = cside * 64 / side; |
| 12149 | let (rows, cols) = ((ch / chunk_chroma).max(1), (cw / chunk_chroma).max(1)); |
| 12150 | for cr in 0..rows { |
| 12151 | for cc in 0..cols { |
| 12152 | let unit_mi = (mi_r + cr * (unit_luma / MI), mi_c + cc * (unit_luma / MI)); |
| 12153 | for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] { |
| 12154 | let mut unit = Vec::with_capacity(cu * cu); |
| 12155 | for rr in 0..cu { |
| 12156 | let start = |
| 12157 | (cr * chunk_chroma + rr) * cside + cc * chunk_chroma; |
| 12158 | unit.extend_from_slice(&grid[start..start + cu]); |
| 12159 | } |
| 12160 | neighbours.record_mi_chroma( |
| 12161 | unit_mi, unit_luma, unit_luma, plane_idx, &unit, |
| 12162 | ); |
| 12163 | } |
| 12164 | } |
| 12165 | } |
| 12166 | } |
| 12167 | neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); |
| 12168 | neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); |
| 12169 | neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); |
| 12170 | neighbours.fill_lf_grid_rect( |
| 12171 | (mi_r, mi_c), |
| 12172 | bw / MI, |
| 12173 | bh / MI, |
| 12174 | bw.min(64) as u8, |
| 12175 | bh.min(64) as u8, |
| 12176 | 0, fctx, |
| 12177 | ); |
| 12178 | record_intrabc_mi_rect( |
| 12179 | mi_r, |
| 12180 | mi_c, |
| 12181 | bw / MI, |
| 12182 | bh / MI, |
| 12183 | Some((dv_row, dv_col)), |
| 12184 | neighbours, |
| 12185 | fctx, |
| 12186 | ); |
| 12187 | Ok(()) |
| 12188 | } |
| 12189 | |
| 12190 | /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip |
| 12191 | /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's |
| 12192 | /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/ |
| 12193 | /// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way |
| 12194 | /// (so a skip strip elsewhere in the tile stays in sync), but this decoder |
| 12195 | /// has no rectangular-transform coefficient reader, and a chroma plane here |
| 12196 | /// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16) |
| 12197 | /// with no depth-based square-tiling escape the way luma's own resolved |
| 12198 | /// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) -- |
| 12199 | /// so a coded (non-skip) strip is refused by name instead of guess-decoded. |
| 12200 | #[allow(clippy::too_many_arguments)] |
| 12201 | fn decode_block_rect( |
| 12202 | dec: &mut SymbolDecoder, |
| 12203 | cdfs: &mut Cdfs, |
| 12204 | neighbours: &mut Neighbours, |
| 12205 | at: (usize, usize), |
| 12206 | bw: usize, |
| 12207 | bh: usize, |
| 12208 | y: &mut PlaneBuf<'static>, |
| 12209 | u: &mut PlaneBuf<'static>, |
| 12210 | v: &mut PlaneBuf<'static>, |
| 12211 | enable_filter_intra: bool, |
| 12212 | allow_screen_content_tools: bool, |
| 12213 | base_q_idx: u8, |
| 12214 | tx_select: bool, |
| 12215 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 12216 | ) -> Result<()> { |
| 12217 | let (r, c) = at; |
| 12218 | let (px, py) = (c * SUB, r * SUB); |
| 12219 | let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); |
| 12220 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); |
| 12221 | let palette_uv_cache = neighbours.palette_uv_cache(at); |
| 12222 | let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) = |
| 12223 | read_intra_mode_rect( |
| 12224 | dec, |
| 12225 | cdfs, |
| 12226 | nb_above_mode, |
| 12227 | nb_left_mode, |
| 12228 | true, |
| 12229 | true, |
| 12230 | bw, |
| 12231 | bh, |
| 12232 | enable_filter_intra, |
| 12233 | neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), |
| 12234 | allow_screen_content_tools, |
| 12235 | Some((palette_ctx, &palette_cache)), |
| 12236 | &palette_uv_cache, |
| 12237 | r * (SUB / MI), |
| 12238 | c * (SUB / MI), fctx, |
| 12239 | )?; |
| 12240 | |
| 12241 | if let Some((dv_row, dv_col)) = intrabc { |
| 12242 | return decode_intrabc_rect( |
| 12243 | dec, |
| 12244 | cdfs, |
| 12245 | neighbours, |
| 12246 | (r * (SUB / MI), c * (SUB / MI)), |
| 12247 | (bw, bh), |
| 12248 | skip, |
| 12249 | (dv_row, dv_col), |
| 12250 | y, |
| 12251 | u, |
| 12252 | v, |
| 12253 | base_q_idx, fctx, |
| 12254 | ); |
| 12255 | } |
| 12256 | let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); |
| 12257 | if smooth_neighbor { |
| 12258 | hit!(SMOOTH_LUMA_HITS); |
| 12259 | } |
| 12260 | // lane-chroma r3: chroma's own edge-filter-strength neighbour check |
| 12261 | // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's |
| 12262 | // `uv_mode`, not the luma one. |
| 12263 | let smooth_neighbor_uv = |
| 12264 | neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx); |
| 12265 | // lane-rectsplit r1: `predict_filter_intra` now takes the block's own |
| 12266 | // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a |
| 12267 | // rectangle just as happily), so a `use_filter_intra` strip at this level |
| 12268 | // predicts instead of refusing. The below-16x16 leaf arm |
| 12269 | // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own. |
| 12270 | if filter_intra.is_some() { |
| 12271 | hit!(FILTER_INTRA_RECT_HITS); |
| 12272 | } |
| 12273 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { |
| 12274 | DC_PRED |
| 12275 | } else { |
| 12276 | uv_mode |
| 12277 | }; |
| 12278 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); |
| 12279 | // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths |
| 12280 | // gate their `read_tx_size` on `tx_select` for exactly this reason; this |
| 12281 | // one did not, so with `--enable-tx-size-search=0` -- which several gate |
| 12282 | // recipes use -- the decoder consumed a symbol the encoder never wrote and |
| 12283 | // desynced the tile from that point on. That is why both strips of the |
| 12284 | // pinned HORZ quadrant were wrong from their very first pixel, and why our |
| 12285 | // range after the read equalled the oracle's range for the whole block. |
| 12286 | // lane-av1mixloss: the lossless-segment early return |
| 12287 | // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment |
| 12288 | // rect block codes no depth symbol here either (class sweep of the sub8 |
| 12289 | // leaf's fix). |
| 12290 | let depth = if tx_select && !lossless(fctx) { |
| 12291 | // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` |
| 12292 | // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an |
| 12293 | // intra-only frame publishes them from every block too |
| 12294 | // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit |
| 12295 | // 1920x792 128-superblock stream, |
| 12296 | // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read |
| 12297 | // `tx_size_cat2` row 1 where libaom reads row 2. |
| 12298 | let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); |
| 12299 | let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]); |
| 12300 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 12301 | eprintln!( |
| 12302 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}", |
| 12303 | dec.debug_state().0 |
| 12304 | ); |
| 12305 | } |
| 12306 | d |
| 12307 | } else { |
| 12308 | 0 |
| 12309 | }; |
| 12310 | // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame |
| 12311 | // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`]. |
| 12312 | publish_txfm_bands_if_in_inter( |
| 12313 | neighbours, |
| 12314 | (mi_r, mi_c), |
| 12315 | depth_to_tx_wh(bw, bh, depth, fctx), |
| 12316 | (bw, bh), fctx, |
| 12317 | ); |
| 12318 | if depth != 0 || lossless(fctx) { |
| 12319 | hit!(TX_DEPTH_HITS); |
| 12320 | // lane-rectsplit r1: a split transform is predicted and reconstructed |
| 12321 | // per transform unit, each unit taking its edges from the previous |
| 12322 | // unit's reconstruction inside this same strip (spec 5.11.36) -- |
| 12323 | // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`]. |
| 12324 | let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); |
| 12325 | if crate::envflags::env_flag!("EC_SBPART_DUMP64") { |
| 12326 | eprintln!( |
| 12327 | "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ |
| 12328 | depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \ |
| 12329 | angle_y={angle_delta_y}" |
| 12330 | ); |
| 12331 | } |
| 12332 | let modes = RectStripModes { |
| 12333 | skip, |
| 12334 | mode, |
| 12335 | angle_delta_y, |
| 12336 | uv_predict_mode, |
| 12337 | angle_delta_uv, |
| 12338 | alpha, |
| 12339 | filter_intra, |
| 12340 | smooth_neighbor, |
| 12341 | smooth_neighbor_uv, |
| 12342 | palette_y: palette_y |
| 12343 | .as_ref() |
| 12344 | .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), |
| 12345 | palette_uv: palette_uv.as_ref().map(|p| { |
| 12346 | ( |
| 12347 | p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), |
| 12348 | p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), |
| 12349 | ) |
| 12350 | }), |
| 12351 | }; |
| 12352 | if palette_y.is_some() || palette_uv.is_some() { |
| 12353 | hit!(PALETTE_SPLIT_TX_HITS); |
| 12354 | } |
| 12355 | decode_rect_split( |
| 12356 | dec, |
| 12357 | cdfs, |
| 12358 | neighbours, |
| 12359 | (mi_r, mi_c), |
| 12360 | bw, |
| 12361 | bh, |
| 12362 | tx_w, |
| 12363 | tx_h, |
| 12364 | &modes, |
| 12365 | y, |
| 12366 | u, |
| 12367 | v, |
| 12368 | base_q_idx, |
| 12369 | reduced_tx_set, fctx, |
| 12370 | )?; |
| 12371 | // This early return skips this fn's own tail, so the palette |
| 12372 | // neighbour state has to be stamped HERE too: without it a split-tx |
| 12373 | // strip left the above/left palette arrays holding a DEAD block's |
| 12374 | // colours, and the next block's colour cache |
| 12375 | // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the |
| 12376 | // wrong VALUE -- same bit count, so the entropy stream stayed in sync |
| 12377 | // and only those pixels were wrong (lane-palette2 r10). |
| 12378 | let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 12379 | neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors); |
| 12380 | let (puv_size, puv_colors) = |
| 12381 | palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 12382 | neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); |
| 12383 | hit!(RECT_PARTITION_HITS); |
| 12384 | return Ok(()); |
| 12385 | } |
| 12386 | let (tx_w, tx_h) = (bw, bh); |
| 12387 | let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); |
| 12388 | let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); |
| 12389 | let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 12390 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 12391 | let (rng, _) = dec.debug_state(); |
| 12392 | eprintln!( |
| 12393 | "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \ |
| 12394 | skip={} tx={depth} rng={rng}", |
| 12395 | skip as i32 |
| 12396 | ); |
| 12397 | } |
| 12398 | // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV |
| 12399 | // block's prediction is the reconstructed colour-index map, set fresh |
| 12400 | // right before each `reconstruct_rect` call below (lane-palette2 r4). |
| 12401 | if let Some(ref pyv) = palette_y { |
| 12402 | let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect(); |
| 12403 | set_palette_pred(buf, fctx); |
| 12404 | } |
| 12405 | let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| { |
| 12406 | ( |
| 12407 | puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(), |
| 12408 | puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), |
| 12409 | ) |
| 12410 | }); |
| 12411 | if skip { |
| 12412 | push_intra_rect(0, |
| 12413 | px, |
| 12414 | py, |
| 12415 | bw, |
| 12416 | bh, |
| 12417 | mode, |
| 12418 | angle_delta_y, |
| 12419 | reach, |
| 12420 | &ZERO_RESIDUAL[..bw * bh], |
| 12421 | None, |
| 12422 | filter_intra, |
| 12423 | smooth_neighbor, fctx, |
| 12424 | ); |
| 12425 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 12426 | if let Some((ub, _)) = &palette_uv_bufs { |
| 12427 | set_palette_pred(ub.clone(), fctx); |
| 12428 | } |
| 12429 | push_intra_rect(1, |
| 12430 | cpx, |
| 12431 | cpy, |
| 12432 | chroma_w, |
| 12433 | chroma_h, |
| 12434 | uv_predict_mode, |
| 12435 | angle_delta_uv, |
| 12436 | reach, |
| 12437 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 12438 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 12439 | None, |
| 12440 | smooth_neighbor_uv, fctx, |
| 12441 | ); |
| 12442 | if let Some((_, vb)) = &palette_uv_bufs { |
| 12443 | set_palette_pred(vb.clone(), fctx); |
| 12444 | } |
| 12445 | push_intra_rect(2, |
| 12446 | cpx, |
| 12447 | cpy, |
| 12448 | chroma_w, |
| 12449 | chroma_h, |
| 12450 | uv_predict_mode, |
| 12451 | angle_delta_uv, |
| 12452 | reach, |
| 12453 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 12454 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 12455 | None, |
| 12456 | smooth_neighbor_uv, fctx, |
| 12457 | ); |
| 12458 | neighbours.record_rect( |
| 12459 | at, |
| 12460 | bw, |
| 12461 | bh, |
| 12462 | mode, |
| 12463 | uv_predict_mode, |
| 12464 | &[ |
| 12465 | &ZERO_RESIDUAL[..bw * bh], |
| 12466 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 12467 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 12468 | ], |
| 12469 | ); |
| 12470 | } else { |
| 12471 | // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx` |
| 12472 | // reduces both size pairs to their square-up CDF sets |
| 12473 | // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own |
| 12474 | // doc comments); the scan order and 2D context tables are the real |
| 12475 | // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`). |
| 12476 | let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 }; |
| 12477 | // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a |
| 12478 | // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16 |
| 12479 | // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis). |
| 12480 | let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) { |
| 12481 | (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16), |
| 12482 | (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32), |
| 12483 | (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8), |
| 12484 | (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16), |
| 12485 | _ => { |
| 12486 | return Err(unsupported( |
| 12487 | "a rectangular chroma transform whose size has no coefficient table", |
| 12488 | )) |
| 12489 | } |
| 12490 | }; |
| 12491 | let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 { |
| 12492 | TxType::DctDct |
| 12493 | } else { |
| 12494 | default_intra_tx_type(uv_predict_mode as u8) |
| 12495 | }; |
| 12496 | // lane-rectwire r3: real coefficients desync a pixel-exact gate |
| 12497 | // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's |
| 12498 | // mi(8,8) HORZ quadrant come out ~100% wrong from their very first |
| 12499 | // pixel (not a subtle context-table off-by-one), while the sibling |
| 12500 | // non-rect quadrants of the same frame match. Range-ladder bisection |
| 12501 | // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started |
| 12502 | // but the intra key-frame path has no traced symbol between the |
| 12503 | // partition read and the first coefficient block (mode/skip/tx_depth |
| 12504 | // reads are all untraced in libaom's decodeframe.c intra path, unlike |
| 12505 | // the inter EC_TRACE_MODE this round added), so a same-length range |
| 12506 | // comparison wasn't reachable within budget -- see |
| 12507 | // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's |
| 12508 | // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and |
| 12509 | // dc_sign_ctx's around-index all cross-checked byte-for-byte against |
| 12510 | // libaom and match). lane-rectwire r4: range-ladder against the |
| 12511 | // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL) |
| 12512 | // narrowed the divergence past skip/y_mode/uv_mode (values AND range |
| 12513 | // both confirmed in sync -- rng=58692 on both sides right after |
| 12514 | // uv_mode, with `enable_filter_intra=0` on this frame so neither side |
| 12515 | // reads a filter_intra symbol) to the `tx_size_cat2` depth read |
| 12516 | // immediately after: ours moves rng 58692 -> 43570, which cannot be |
| 12517 | // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after* |
| 12518 | // its own tx_size read) unless oracle's tx symbol is a near-certainty |
| 12519 | // CDF that barely narrows the range -- i.e. this decoder's |
| 12520 | // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for |
| 12521 | // a 32x16/16x32 strip is the first diverging symbol, not the |
| 12522 | // coefficient-context math r3 already cleared. Not confirmed byte- |
| 12523 | // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on |
| 12524 | // `read_tx_size`'s own rng, not attempted this round -- budget), so |
| 12525 | // r5 CONFIRMED the suspect and it was simpler than the CDF row: the |
| 12526 | // tx-depth symbol exists only under TX_MODE_SELECT, and this path read |
| 12527 | // it unconditionally where both square paths gate on `tx_select`. With |
| 12528 | // --enable-tx-size-search=0 the encoder writes no such symbol, so the |
| 12529 | // decoder consumed one that was never there. |
| 12530 | { |
| 12531 | let around = neighbours.around_rect(at, bw, bh); |
| 12532 | let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra)); |
| 12533 | let (luma_levels, luma_tx_type) = read_coeffs_rect( |
| 12534 | dec, |
| 12535 | &mut luma_coding, |
| 12536 | luma_scan, |
| 12537 | bw, |
| 12538 | bh, |
| 12539 | 0, |
| 12540 | dc_sign_ctx(around[0].2), |
| 12541 | TxType::DctDct, |
| 12542 | )?; |
| 12543 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 12544 | let (rng, _) = dec.debug_state(); |
| 12545 | eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}"); |
| 12546 | } |
| 12547 | let luma_residual = dequant_and_inverse_typed_wh( |
| 12548 | &luma_levels, |
| 12549 | bw, |
| 12550 | bh, |
| 12551 | crate::decode::bit_depth(fctx), |
| 12552 | block_q_idx(fctx), |
| 12553 | plane_q_delta(0, fctx).0, |
| 12554 | plane_q_delta(0, fctx).1, |
| 12555 | luma_tx_type, |
| 12556 | block_iqmatrix(fctx, 0, bw, bh, luma_tx_type), |
| 12557 | ); |
| 12558 | push_intra_rect(0, |
| 12559 | px, |
| 12560 | py, |
| 12561 | bw, |
| 12562 | bh, |
| 12563 | mode, |
| 12564 | angle_delta_y, |
| 12565 | reach, |
| 12566 | &luma_residual, |
| 12567 | None, |
| 12568 | filter_intra, |
| 12569 | smooth_neighbor, fctx, |
| 12570 | ); |
| 12571 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 12572 | if let Some((ub, _)) = &palette_uv_bufs { |
| 12573 | set_palette_pred(ub.clone(), fctx); |
| 12574 | } |
| 12575 | let u_default_tx = chroma_default_tx; |
| 12576 | let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); |
| 12577 | let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode); |
| 12578 | let (u_levels, u_tx_type) = read_chroma_coeffs_rect( |
| 12579 | dec, |
| 12580 | &mut u_coding, |
| 12581 | chroma_scan, |
| 12582 | chroma_w, |
| 12583 | chroma_h, |
| 12584 | u_skip_ctx, |
| 12585 | dc_sign_ctx(around[1].2), |
| 12586 | u_default_tx, |
| 12587 | fctx, |
| 12588 | )?; |
| 12589 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 12590 | let (rng, _) = dec.debug_state(); |
| 12591 | eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}"); |
| 12592 | } |
| 12593 | let u_residual = dequant_and_inverse_typed_wh( |
| 12594 | &u_levels, |
| 12595 | chroma_w, |
| 12596 | chroma_h, |
| 12597 | crate::decode::bit_depth(fctx), |
| 12598 | block_q_idx(fctx), |
| 12599 | plane_q_delta(1, fctx).0, |
| 12600 | plane_q_delta(1, fctx).1, |
| 12601 | u_tx_type, |
| 12602 | block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type), |
| 12603 | ); |
| 12604 | push_intra_rect(1, |
| 12605 | cpx, |
| 12606 | cpy, |
| 12607 | chroma_w, |
| 12608 | chroma_h, |
| 12609 | uv_predict_mode, |
| 12610 | angle_delta_uv, |
| 12611 | reach, |
| 12612 | &u_residual, |
| 12613 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 12614 | None, |
| 12615 | smooth_neighbor_uv, fctx, |
| 12616 | ); |
| 12617 | if let Some((_, vb)) = &palette_uv_bufs { |
| 12618 | set_palette_pred(vb.clone(), fctx); |
| 12619 | } |
| 12620 | let v_default_tx = chroma_default_tx; |
| 12621 | let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); |
| 12622 | let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode); |
| 12623 | let (v_levels, v_tx_type) = read_chroma_coeffs_rect( |
| 12624 | dec, |
| 12625 | &mut v_coding, |
| 12626 | chroma_scan, |
| 12627 | chroma_w, |
| 12628 | chroma_h, |
| 12629 | v_skip_ctx, |
| 12630 | dc_sign_ctx(around[2].2), |
| 12631 | v_default_tx, |
| 12632 | fctx, |
| 12633 | )?; |
| 12634 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 12635 | let (rng, _) = dec.debug_state(); |
| 12636 | eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}"); |
| 12637 | } |
| 12638 | let v_residual = dequant_and_inverse_typed_wh( |
| 12639 | &v_levels, |
| 12640 | chroma_w, |
| 12641 | chroma_h, |
| 12642 | crate::decode::bit_depth(fctx), |
| 12643 | block_q_idx(fctx), |
| 12644 | plane_q_delta(2, fctx).0, |
| 12645 | plane_q_delta(2, fctx).1, |
| 12646 | v_tx_type, |
| 12647 | block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type), |
| 12648 | ); |
| 12649 | push_intra_rect(2, |
| 12650 | cpx, |
| 12651 | cpy, |
| 12652 | chroma_w, |
| 12653 | chroma_h, |
| 12654 | uv_predict_mode, |
| 12655 | angle_delta_uv, |
| 12656 | reach, |
| 12657 | &v_residual, |
| 12658 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 12659 | None, |
| 12660 | smooth_neighbor_uv, fctx, |
| 12661 | ); |
| 12662 | neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]); |
| 12663 | hit!(RECT_COEFF_HITS); |
| 12664 | } |
| 12665 | } |
| 12666 | let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 12667 | neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors); |
| 12668 | let (puv_size, puv_colors) = |
| 12669 | palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 12670 | neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); |
| 12671 | neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); |
| 12672 | neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx); |
| 12673 | hit!(RECT_PARTITION_HITS); |
| 12674 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 12675 | eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}"); |
| 12676 | } |
| 12677 | Ok(()) |
| 12678 | } |
| 12679 | |
| 12680 | /// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/ |
| 12681 | /// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but |
| 12682 | /// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid |
| 12683 | /// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`: |
| 12684 | /// the second strip of a HORZ/VERT split sits offset by half the 16x16 |
| 12685 | /// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't |
| 12686 | /// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the |
| 12687 | /// previous strip is directly above (same column, `mi_h` rows up) or |
| 12688 | /// directly left (same row, `mi_w` cols over), its mode overrides the coarse |
| 12689 | /// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode |
| 12690 | /// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour |
| 12691 | /// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at |
| 12692 | /// this strip's real position, never the coarse `record_rect` (which the |
| 12693 | /// caller uses once, after both strips, exactly like the `VERT_B` arm next |
| 12694 | /// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16` |
| 12695 | /// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8` |
| 12696 | /// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level |
| 12697 | /// under [`decode_block_rect`]'s own 32x16/16x32 strip. |
| 12698 | #[allow(clippy::too_many_arguments)] |
| 12699 | fn decode_leaf_rect( |
| 12700 | dec: &mut SymbolDecoder, |
| 12701 | cdfs: &mut Cdfs, |
| 12702 | neighbours: &mut Neighbours, |
| 12703 | outer_at: (usize, usize), |
| 12704 | leaf_mi: (usize, usize), |
| 12705 | bw: usize, |
| 12706 | bh: usize, |
| 12707 | prev_leaf: Option<((usize, usize), usize)>, |
| 12708 | y: &mut PlaneBuf<'static>, |
| 12709 | u: &mut PlaneBuf<'static>, |
| 12710 | v: &mut PlaneBuf<'static>, |
| 12711 | enable_filter_intra: bool, |
| 12712 | allow_screen_content_tools: bool, |
| 12713 | base_q_idx: u8, |
| 12714 | tx_select: bool, |
| 12715 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 12716 | ) -> Result<usize> { |
| 12717 | let _ = base_q_idx; |
| 12718 | if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { |
| 12719 | eprintln!( |
| 12720 | "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}", |
| 12721 | dec.debug_state().0 |
| 12722 | ); |
| 12723 | } |
| 12724 | let (r, c) = outer_at; |
| 12725 | let mut above_mode = neighbours.above_mode[c]; |
| 12726 | let mut left_mode = neighbours.left_mode[r]; |
| 12727 | let (mi_w, mi_h) = (bw / MI, bh / MI); |
| 12728 | if let Some(((pr, pc), pmode)) = prev_leaf { |
| 12729 | if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h { |
| 12730 | above_mode = pmode; |
| 12731 | } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w { |
| 12732 | left_mode = pmode; |
| 12733 | } |
| 12734 | } |
| 12735 | // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot |
| 12736 | // cannot hold the modes a split (or a pair of strips) leaves behind, so |
| 12737 | // when the map holds the block at exactly this strip's above/left mi it |
| 12738 | // is the neighbour libaom's `above_mi`/`left_mi` reads. |
| 12739 | // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND |
| 12740 | // availability-correct -- four 16x8 strips share one coarse 16x16 |
| 12741 | // `left_mode` cell too, so the fallback must not stand in for an absent |
| 12742 | // tile-edge neighbour. |
| 12743 | let (above_mode, left_mode) = |
| 12744 | neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode)); |
| 12745 | let smooth_neighbor = |
| 12746 | is_smooth_mode(above_mode) || is_smooth_mode(left_mode); |
| 12747 | if smooth_neighbor { |
| 12748 | hit!(SMOOTH_LUMA_HITS); |
| 12749 | } |
| 12750 | // The palette-Y mode CDF row is picked by the neighbours' palette use |
| 12751 | // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real |
| 12752 | // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use |
| 12753 | // a palette narrows the wrong interval and desyncs the tile even when the |
| 12754 | // decoded bit is the same. The cell is the 16px-SUB cell containing the |
| 12755 | // leaf (the palette neighbour arrays have no finer granularity). |
| 12756 | // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8 |
| 12757 | // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row |
| 12758 | // exclusion and the neighbour palette lookup itself are mi-granular |
| 12759 | // (see [`Neighbours::palette_ctx_and_cache_mi`]). |
| 12760 | let pal_at = leaf_mi; |
| 12761 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at); |
| 12762 | let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at); |
| 12763 | let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) = |
| 12764 | read_intra_mode_rect( |
| 12765 | dec, |
| 12766 | cdfs, |
| 12767 | above_mode, |
| 12768 | left_mode, |
| 12769 | true, |
| 12770 | true, |
| 12771 | bw, |
| 12772 | bh, |
| 12773 | enable_filter_intra, |
| 12774 | neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1), |
| 12775 | allow_screen_content_tools, |
| 12776 | Some((palette_ctx, &palette_cache)), |
| 12777 | &palette_uv_cache, |
| 12778 | leaf_mi.0, |
| 12779 | leaf_mi.1, fctx, |
| 12780 | )?; |
| 12781 | |
| 12782 | if let Some((dv_row, dv_col)) = intrabc { |
| 12783 | decode_intrabc_rect( |
| 12784 | dec, cdfs, neighbours, leaf_mi, (bw, bh), skip, (dv_row, dv_col), |
| 12785 | y, u, v, base_q_idx, fctx, |
| 12786 | )?; |
| 12787 | return Ok(DC_PRED); |
| 12788 | } |
| 12789 | // lane-kf900 r4: palette prediction on this shape, the same colour-index |
| 12790 | // map -> base colours buffer [`decode_block_rect`] hands each |
| 12791 | // `reconstruct_rect` through [`set_palette_pred`]. |
| 12792 | if palette_y.is_some() || palette_uv.is_some() { |
| 12793 | hit!(RECT4_PALETTE_HITS); |
| 12794 | } |
| 12795 | let palette_y_buf: Option<Vec<u16>> = palette_y |
| 12796 | .as_ref() |
| 12797 | .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); |
| 12798 | let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| { |
| 12799 | ( |
| 12800 | p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), |
| 12801 | p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), |
| 12802 | ) |
| 12803 | }); |
| 12804 | let (pal_y_size, pal_y_colors) = |
| 12805 | palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 12806 | let (pal_uv_size, pal_uv_colors) = |
| 12807 | palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 12808 | if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { |
| 12809 | eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}"); |
| 12810 | } |
| 12811 | if filter_intra.is_some() { |
| 12812 | // lane-fistrip r1: `predict_filter_intra` already walks its 4x2 |
| 12813 | // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an |
| 12814 | // 8x16/16x8 strip predicts through the same call `reconstruct_rect` |
| 12815 | // below already makes; this refusal was square-only prose. |
| 12816 | hit!(FILTER_INTRA_RECT_HITS); |
| 12817 | hit!(FILTER_INTRA_RECT_SUB16_HITS); |
| 12818 | } |
| 12819 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 12820 | // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge |
| 12821 | // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not |
| 12822 | // a constant `false`. |
| 12823 | let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx); |
| 12824 | let depth = if tx_select && !lossless(fctx) { |
| 12825 | // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read |
| 12826 | // every other rect reader now does -- a no-op on a key frame. |
| 12827 | // lane-av1mixloss: libaom `read_tx_size`'s first line |
| 12828 | // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return |
| 12829 | // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment |
| 12830 | // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4). |
| 12831 | // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours |
| 12832 | // read `tx_size_cat1` (rng 55700->49918) where the oracle's next |
| 12833 | // read was the leaf's own txb_skip. |
| 12834 | let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx); |
| 12835 | // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`, |
| 12836 | // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so |
| 12837 | // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol |
| 12838 | // count (3), different CDF row: a wrong-table read of a real symbol, |
| 12839 | // the class that cost lane-rectsplit r1 its 64x32 depth. |
| 12840 | // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's |
| 12841 | // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and |
| 12842 | // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this |
| 12843 | // function also decodes) sit at depth 2, so they read |
| 12844 | // `tx_size_cdf[1]` -- the same table a 16x16 square block reads -- |
| 12845 | // while `tx_size_cat2` belongs to the 32-level shapes |
| 12846 | // ([`decode_block_rect`]). Both tables carry three symbols, so the |
| 12847 | // wrong one decodes a plausible depth from the wrong probabilities: |
| 12848 | // the range diverges silently at the first such leaf and every later |
| 12849 | // symbol in the tile is read from the wrong place (class |
| 12850 | // `wrong-alphabet-same-value`, here same alphabet / wrong row). |
| 12851 | let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]); |
| 12852 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 12853 | 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); |
| 12854 | } |
| 12855 | d |
| 12856 | } else { |
| 12857 | 0 |
| 12858 | }; |
| 12859 | // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads |
| 12860 | // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`]. |
| 12861 | publish_txfm_bands_if_in_inter( |
| 12862 | neighbours, |
| 12863 | leaf_mi, |
| 12864 | depth_to_tx_wh(bw, bh, depth, fctx), |
| 12865 | (bw, bh), fctx, |
| 12866 | ); |
| 12867 | if depth != 0 || lossless(fctx) { |
| 12868 | // The same per-transform-unit walk the bigger strips take |
| 12869 | // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at |
| 12870 | // depth 2), addressed at this leaf's own mi position. |
| 12871 | hit!(TX_DEPTH_HITS); |
| 12872 | hit!(SUB16_SPLIT_HITS); |
| 12873 | let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); |
| 12874 | let modes = RectStripModes { |
| 12875 | skip, |
| 12876 | mode, |
| 12877 | angle_delta_y, |
| 12878 | uv_predict_mode, |
| 12879 | angle_delta_uv, |
| 12880 | alpha, |
| 12881 | filter_intra, |
| 12882 | smooth_neighbor, |
| 12883 | // lane-rectsplitx r3: the split arm hard-coded `false` here while |
| 12884 | // the unsplit arm below passes the real neighbour answer -- chroma |
| 12885 | // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type. |
| 12886 | smooth_neighbor_uv, |
| 12887 | palette_y: palette_y_buf.clone(), |
| 12888 | palette_uv: palette_uv_bufs.clone(), |
| 12889 | }; |
| 12890 | if palette_y.is_some() || palette_uv.is_some() { |
| 12891 | hit!(PALETTE_SPLIT_TX_HITS); |
| 12892 | } |
| 12893 | decode_rect_split( |
| 12894 | dec, |
| 12895 | cdfs, |
| 12896 | neighbours, |
| 12897 | leaf_mi, |
| 12898 | bw, |
| 12899 | bh, |
| 12900 | tx_w, |
| 12901 | tx_h, |
| 12902 | &modes, |
| 12903 | y, |
| 12904 | u, |
| 12905 | v, |
| 12906 | base_q_idx, |
| 12907 | reduced_tx_set, fctx, |
| 12908 | )?; |
| 12909 | record_strip_palette( |
| 12910 | neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, |
| 12911 | ); |
| 12912 | return Ok(mode); |
| 12913 | } |
| 12914 | let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); |
| 12915 | let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 12916 | let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); |
| 12917 | let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); |
| 12918 | let (luma_levels, u_levels, v_levels); |
| 12919 | if skip { |
| 12920 | luma_levels = Grid::Zero(bw * bh); |
| 12921 | u_levels = Grid::Zero(chroma_w * chroma_h); |
| 12922 | v_levels = Grid::Zero(chroma_w * chroma_h); |
| 12923 | if let Some(b) = &palette_y_buf { |
| 12924 | set_palette_pred(b.clone(), fctx); |
| 12925 | } |
| 12926 | push_intra_rect(0, |
| 12927 | px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra, |
| 12928 | smooth_neighbor, fctx, |
| 12929 | ); |
| 12930 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 12931 | if let Some((ub, _)) = &palette_uv_bufs { |
| 12932 | set_palette_pred(ub.clone(), fctx); |
| 12933 | } |
| 12934 | push_intra_rect(1, |
| 12935 | cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels, |
| 12936 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, |
| 12937 | ); |
| 12938 | if let Some((_, vb)) = &palette_uv_bufs { |
| 12939 | set_palette_pred(vb.clone(), fctx); |
| 12940 | } |
| 12941 | push_intra_rect(2, |
| 12942 | cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels, |
| 12943 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, |
| 12944 | ); |
| 12945 | } else { |
| 12946 | // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`, |
| 12947 | // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type` |
| 12948 | // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s |
| 12949 | // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at |
| 12950 | // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square |
| 12951 | // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`). |
| 12952 | let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 { |
| 12953 | if bw == 16 { (&SCAN_16X8, &SCAN_16X8) } else { (&SCAN_8X16, &SCAN_8X16) } |
| 12954 | } else if bw == 16 { |
| 12955 | (&SCAN_16X8, &SCAN_8X4) |
| 12956 | } else { |
| 12957 | (&SCAN_8X16, &SCAN_4X8) |
| 12958 | }; |
| 12959 | let chroma_rect_set = if ss_x(fctx) == 0 { TxbSet::ChromaRect16x8 } else { TxbSet::ChromaRect8x4 }; |
| 12960 | let around = neighbours.around_mi_rect(leaf_mi, bw, bh); |
| 12961 | let luma_set = if reduced_tx_set { |
| 12962 | TxbSet::LumaRect16x8 |
| 12963 | } else { |
| 12964 | TxbSet::LumaRect16x8Set1 |
| 12965 | }; |
| 12966 | let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra)); |
| 12967 | let (l_levels, luma_tx_type) = read_coeffs_rect( |
| 12968 | dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct, |
| 12969 | )?; |
| 12970 | if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { |
| 12971 | let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect(); |
| 12972 | eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}"); |
| 12973 | } |
| 12974 | luma_levels = l_levels; |
| 12975 | let luma_residual = dequant_and_inverse_typed_wh( |
| 12976 | &luma_levels, bw, bh, crate::decode::bit_depth(fctx), |
| 12977 | block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type, |
| 12978 | block_iqmatrix(fctx, 0, bw, bh, luma_tx_type), |
| 12979 | ); |
| 12980 | if let Some(b) = &palette_y_buf { |
| 12981 | set_palette_pred(b.clone(), fctx); |
| 12982 | } |
| 12983 | push_intra_rect(0, |
| 12984 | px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra, |
| 12985 | smooth_neighbor, fctx, |
| 12986 | ); |
| 12987 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 12988 | let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); |
| 12989 | let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); |
| 12990 | let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode); |
| 12991 | let (u_l, u_tx_type) = read_chroma_coeffs_rect( |
| 12992 | dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, |
| 12993 | dc_sign_ctx(around[1].2), u_default_tx, fctx, |
| 12994 | )?; |
| 12995 | u_levels = u_l; |
| 12996 | let u_residual = dequant_and_inverse_typed_wh( |
| 12997 | &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), |
| 12998 | block_q_idx(fctx), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type, |
| 12999 | block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type), |
| 13000 | ); |
| 13001 | if let Some((ub, _)) = &palette_uv_bufs { |
| 13002 | set_palette_pred(ub.clone(), fctx); |
| 13003 | } |
| 13004 | push_intra_rect(1, |
| 13005 | cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual, |
| 13006 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx, |
| 13007 | ); |
| 13008 | let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); |
| 13009 | let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); |
| 13010 | let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode); |
| 13011 | let (v_l, v_tx_type) = read_chroma_coeffs_rect( |
| 13012 | dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, |
| 13013 | dc_sign_ctx(around[2].2), v_default_tx, fctx, |
| 13014 | )?; |
| 13015 | v_levels = v_l; |
| 13016 | let v_residual = dequant_and_inverse_typed_wh( |
| 13017 | &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), |
| 13018 | block_q_idx(fctx), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type, |
| 13019 | block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type), |
| 13020 | ); |
| 13021 | if let Some((_, vb)) = &palette_uv_bufs { |
| 13022 | set_palette_pred(vb.clone(), fctx); |
| 13023 | } |
| 13024 | push_intra_rect(2, |
| 13025 | cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual, |
| 13026 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx, |
| 13027 | ); |
| 13028 | hit!(RECT_LEAF_COEFF_HITS); |
| 13029 | } |
| 13030 | neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]); |
| 13031 | neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip); |
| 13032 | neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx); |
| 13033 | // The leaf's own palette state (`0` clears, as this site always did |
| 13034 | // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT |
| 13035 | // AXIS only until the pair's closing leaf: the coarse cell holds one |
| 13036 | // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the |
| 13037 | // real left neighbour leaf 1 reads (lane-kf900 r4). |
| 13038 | record_strip_palette( |
| 13039 | neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, |
| 13040 | ); |
| 13041 | // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and |
| 13042 | // rows -- record the whole span, not one cell. |
| 13043 | neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode); |
| 13044 | neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode); |
| 13045 | Ok(mode) |
| 13046 | } |
| 13047 | |
| 13048 | /// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` / |
| 13049 | /// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling, |
| 13050 | /// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`] |
| 13051 | /// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an |
| 13052 | /// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous |
| 13053 | /// strip's mode so this one's mode context sees its true above/left |
| 13054 | /// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention). |
| 13055 | /// |
| 13056 | /// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context |
| 13057 | /// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with |
| 13058 | /// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the |
| 13059 | /// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with |
| 13060 | /// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale -- |
| 13061 | /// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2 |
| 13062 | /// (`inverse_transform_2d_typed_wh`'s own `rect_scale`). |
| 13063 | /// |
| 13064 | /// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of |
| 13065 | /// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1 |
| 13066 | /// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused |
| 13067 | /// unexamined. |
| 13068 | #[allow(clippy::too_many_arguments)] |
| 13069 | fn decode_block_rect4( |
| 13070 | dec: &mut SymbolDecoder, |
| 13071 | cdfs: &mut Cdfs, |
| 13072 | neighbours: &mut Neighbours, |
| 13073 | strip_mi: (usize, usize), |
| 13074 | bw: usize, |
| 13075 | bh: usize, |
| 13076 | prev_strip: Option<((usize, usize), usize)>, |
| 13077 | y: &mut PlaneBuf<'static>, |
| 13078 | u: &mut PlaneBuf<'static>, |
| 13079 | v: &mut PlaneBuf<'static>, |
| 13080 | enable_filter_intra: bool, |
| 13081 | allow_screen_content_tools: bool, |
| 13082 | base_q_idx: u8, |
| 13083 | tx_select: bool, fctx: &crate::decode::FrameCtx, |
| 13084 | ) -> Result<(usize, usize)> { |
| 13085 | let _ = base_q_idx; |
| 13086 | let (mi_r, mi_c) = strip_mi; |
| 13087 | let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); |
| 13088 | let (mi_w, mi_h) = (bw / MI, bh / MI); |
| 13089 | let mut above_mode = neighbours.above_mode[c]; |
| 13090 | let mut left_mode = neighbours.left_mode[r]; |
| 13091 | if let Some(((pr, pc), pmode)) = prev_strip { |
| 13092 | if pc == mi_c && mi_r == pr + mi_h { |
| 13093 | above_mode = pmode; |
| 13094 | } else if pr == mi_r && mi_c == pc + mi_w { |
| 13095 | left_mode = pmode; |
| 13096 | } |
| 13097 | } |
| 13098 | // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact + |
| 13099 | // availability-correct neighbour modes (see |
| 13100 | // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every |
| 13101 | // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell. |
| 13102 | let (above_mode, left_mode) = |
| 13103 | neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode)); |
| 13104 | // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache. |
| 13105 | // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every |
| 13106 | // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count, |
| 13107 | // wrong interval, so a screen-content tile desynced at the first strip |
| 13108 | // whose neighbour used a palette (class [[cdf-row-held-constant]]). |
| 13109 | let pal_at = (mi_r, mi_c); |
| 13110 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at); |
| 13111 | let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at); |
| 13112 | let ( |
| 13113 | skip, |
| 13114 | mode, |
| 13115 | angle_delta_y, |
| 13116 | uv_mode, |
| 13117 | angle_delta_uv, |
| 13118 | alpha, |
| 13119 | filter_intra, |
| 13120 | palette_y, |
| 13121 | palette_uv, |
| 13122 | intrabc, |
| 13123 | ) = read_intra_mode_rect( |
| 13124 | dec, |
| 13125 | cdfs, |
| 13126 | above_mode, |
| 13127 | left_mode, |
| 13128 | true, |
| 13129 | true, |
| 13130 | bw, |
| 13131 | bh, |
| 13132 | enable_filter_intra, |
| 13133 | neighbours.skip_txfm_ctx(mi_r, mi_c), |
| 13134 | allow_screen_content_tools, |
| 13135 | Some((palette_ctx, &palette_cache)), |
| 13136 | &palette_uv_cache, |
| 13137 | mi_r, |
| 13138 | mi_c, fctx, |
| 13139 | )?; |
| 13140 | if let Some((dv_row, dv_col)) = intrabc { |
| 13141 | decode_intrabc_rect( |
| 13142 | dec, cdfs, neighbours, strip_mi, (bw, bh), skip, (dv_row, dv_col), |
| 13143 | y, u, v, base_q_idx, fctx, |
| 13144 | )?; |
| 13145 | return Ok((DC_PRED, DC_PRED)); |
| 13146 | } |
| 13147 | // lane-kf900 r4: palette prediction on this shape, exactly as |
| 13148 | // [`decode_block_rect`] does one aspect ratio up -- the colour-index map |
| 13149 | // mapped through the base colours IS the prediction (it reads no edge |
| 13150 | // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`]. |
| 13151 | if palette_y.is_some() || palette_uv.is_some() { |
| 13152 | hit!(RECT4_PALETTE_HITS); |
| 13153 | } |
| 13154 | let palette_y_buf: Option<Vec<u16>> = palette_y |
| 13155 | .as_ref() |
| 13156 | .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); |
| 13157 | let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| { |
| 13158 | ( |
| 13159 | p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), |
| 13160 | p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), |
| 13161 | ) |
| 13162 | }); |
| 13163 | let (pal_y_size, pal_y_colors) = |
| 13164 | palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 13165 | let (pal_uv_size, pal_uv_colors) = |
| 13166 | palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 13167 | let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); |
| 13168 | if smooth_neighbor { |
| 13169 | hit!(SMOOTH_LUMA_HITS); |
| 13170 | } |
| 13171 | // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's |
| 13172 | // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so |
| 13173 | // `r * (SUB / MI)` names a different mi column and the chroma |
| 13174 | // edge-filter strength was read from the wrong neighbour (measured: |
| 13175 | // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch |
| 13176 | // with luma bit-exact). |
| 13177 | let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx); |
| 13178 | if filter_intra.is_some() { |
| 13179 | hit!(FILTER_INTRA_RECT_HITS); |
| 13180 | if bw > bh { |
| 13181 | hit!(FILTER_INTRA_RECT4_HORZ_HITS); |
| 13182 | } else { |
| 13183 | hit!(FILTER_INTRA_RECT4_VERT_HITS); |
| 13184 | } |
| 13185 | } |
| 13186 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { |
| 13187 | DC_PRED |
| 13188 | } else { |
| 13189 | uv_mode |
| 13190 | }; |
| 13191 | // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) |
| 13192 | // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no |
| 13193 | // depth symbol here either (class sweep of the sub8 leaf's fix). |
| 13194 | let depth = if tx_select && !lossless(fctx) { |
| 13195 | // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` |
| 13196 | // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an |
| 13197 | // intra-only frame publishes them from every block too |
| 13198 | // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit |
| 13199 | // 1920x792 128-superblock stream, |
| 13200 | // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read |
| 13201 | // `tx_size_cat2` row 1 where libaom reads row 2. |
| 13202 | let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); |
| 13203 | let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]); |
| 13204 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 13205 | eprintln!( |
| 13206 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}", |
| 13207 | dec.debug_state().0 |
| 13208 | ); |
| 13209 | } |
| 13210 | d |
| 13211 | } else { |
| 13212 | 0 |
| 13213 | }; |
| 13214 | // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra |
| 13215 | // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`]. |
| 13216 | publish_txfm_bands_if_in_inter( |
| 13217 | neighbours, |
| 13218 | (mi_r, mi_c), |
| 13219 | depth_to_tx_wh(bw, bh, depth, fctx), |
| 13220 | (bw, bh), fctx, |
| 13221 | ); |
| 13222 | if depth != 0 || lossless(fctx) { |
| 13223 | // lane-rectsplitx r1: the per-transform-unit walk, at this strip's |
| 13224 | // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a |
| 13225 | // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16 |
| 13226 | // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8; |
| 13227 | // both interleave in every real stream. |
| 13228 | hit!(TX_DEPTH_HITS); |
| 13229 | let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); |
| 13230 | // lane-rectsplitx r2: both depths ship together, as the r1 handoff |
| 13231 | // predicted -- depth 1 fires FIRST in every attempt that splits at |
| 13232 | // all, so a depth-2-only lift could never be gated. The r1 mismatch |
| 13233 | // was never the rect unit: it was the neighbour MODE the strip reads |
| 13234 | // (see `modes_above_left_mi`). |
| 13235 | let which = if depth == 1 { |
| 13236 | &RECT4_SPLIT_DEPTH1_HITS |
| 13237 | } else { |
| 13238 | &RECT4_SPLIT_DEPTH2_HITS |
| 13239 | }; |
| 13240 | hit_do! { which.with(|c| c.set(c.get() + 1)); } |
| 13241 | let modes = RectStripModes { |
| 13242 | skip, |
| 13243 | mode, |
| 13244 | angle_delta_y, |
| 13245 | uv_predict_mode, |
| 13246 | angle_delta_uv, |
| 13247 | alpha, |
| 13248 | filter_intra, |
| 13249 | smooth_neighbor, |
| 13250 | smooth_neighbor_uv, |
| 13251 | palette_y: palette_y_buf.clone(), |
| 13252 | palette_uv: palette_uv_bufs.clone(), |
| 13253 | }; |
| 13254 | if palette_y.is_some() || palette_uv.is_some() { |
| 13255 | hit!(PALETTE_SPLIT_TX_HITS); |
| 13256 | } |
| 13257 | decode_rect_split( |
| 13258 | dec, |
| 13259 | cdfs, |
| 13260 | neighbours, |
| 13261 | (mi_r, mi_c), |
| 13262 | bw, |
| 13263 | bh, |
| 13264 | tx_w, |
| 13265 | tx_h, |
| 13266 | &modes, |
| 13267 | y, |
| 13268 | u, |
| 13269 | v, |
| 13270 | base_q_idx, |
| 13271 | false, fctx, |
| 13272 | )?; |
| 13273 | record_strip_palette( |
| 13274 | neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, |
| 13275 | pal_uv_colors, |
| 13276 | ); |
| 13277 | if bw > bh { |
| 13278 | hit!(RECT4_32_HORZ_HITS); |
| 13279 | } else { |
| 13280 | hit!(RECT4_32_VERT_HITS); |
| 13281 | } |
| 13282 | if !skip { |
| 13283 | hit!(RECT4_COEFF_HITS); |
| 13284 | } |
| 13285 | // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, |
| 13286 | // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter |
| 13287 | // frame, so this 1:4 strip -- which is also the INTER frame's reader |
| 13288 | // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its |
| 13289 | // transform size in both TXFM_CONTEXT bands. Without it the next block |
| 13290 | // reads the row's stale value. |
| 13291 | txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); |
| 13292 | return Ok((mode, uv_predict_mode)); |
| 13293 | } |
| 13294 | // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip |
| 13295 | // that is 8 px tall, so each strip stamps every cell it touches and the |
| 13296 | // LAST strip wins -- which is the right answer for the block below/right |
| 13297 | // of the 32x32, the only reader outside it. Written after this strip's |
| 13298 | // own context read above, never before. |
| 13299 | for cell in 0..bw.div_ceil(SUB) { |
| 13300 | neighbours.above_mode[c + cell] = mode; |
| 13301 | neighbours.above_uv_mode[c + cell] = uv_predict_mode; |
| 13302 | neighbours.above_side[c + cell] = bw; |
| 13303 | } |
| 13304 | for cell in 0..bh.div_ceil(SUB) { |
| 13305 | neighbours.left_mode[r + cell] = mode; |
| 13306 | neighbours.left_uv_mode[r + cell] = uv_predict_mode; |
| 13307 | neighbours.left_side[r + cell] = bh; |
| 13308 | } |
| 13309 | // ...and the mi-EXACT maps the coarse cells alias away, exactly as |
| 13310 | // [`decode_leaf_rect`] does (the split arm above records these through |
| 13311 | // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left |
| 13312 | // `sub8_mode_row` holding the previous block, and the next 32x32's |
| 13313 | // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band |
| 13314 | // fixture). |
| 13315 | neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode); |
| 13316 | neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode); |
| 13317 | let (px, py) = (mi_c * MI, mi_r * MI); |
| 13318 | let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); |
| 13319 | let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); |
| 13320 | let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 13321 | // lane-av1-444: the strip's chroma shape follows the subsampling. |
| 13322 | // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip |
| 13323 | // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` = |
| 13324 | // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set, |
| 13325 | // `TxbSet::Chroma16`). The caller set is closed -- this reader only |
| 13326 | // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0 |
| 13327 | // and 1/1 only -- so the table is exhaustive. |
| 13328 | let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) { |
| 13329 | (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]), |
| 13330 | (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]), |
| 13331 | (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]), |
| 13332 | (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]), |
| 13333 | _ => unreachable!("decode_block_rect4 chroma shape set is closed"), |
| 13334 | }; |
| 13335 | let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 }; |
| 13336 | let (luma_levels, u_levels, v_levels) = if skip { |
| 13337 | ( |
| 13338 | vec![0i32; bw * bh], |
| 13339 | vec![0i32; chroma_w * chroma_h], |
| 13340 | vec![0i32; chroma_w * chroma_h], |
| 13341 | ) |
| 13342 | } else { |
| 13343 | let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); |
| 13344 | let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode); |
| 13345 | let (luma_levels, luma_tx_type) = read_coeffs_rect( |
| 13346 | dec, |
| 13347 | &mut luma_coding, |
| 13348 | luma_scan, |
| 13349 | bw, |
| 13350 | bh, |
| 13351 | 0, |
| 13352 | dc_sign_ctx(around[0].2), |
| 13353 | TxType::DctDct, |
| 13354 | )?; |
| 13355 | let mut planes = Vec::with_capacity(2); |
| 13356 | for plane in 1..3 { |
| 13357 | // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type |
| 13358 | // stands only while it is a member of this tx size's set; a |
| 13359 | // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32, |
| 13360 | // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps |
| 13361 | // to DCT_DCT there, and ADST is undefined at widths above 16. |
| 13362 | let default_tx = if chroma_w.max(chroma_h) >= 32 { |
| 13363 | TxType::DctDct |
| 13364 | } else { |
| 13365 | default_intra_tx_type(uv_predict_mode as u8) |
| 13366 | }; |
| 13367 | let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); |
| 13368 | let mut coding = cdfs.txb(chroma_set, uv_predict_mode); |
| 13369 | let (levels, tx_type) = read_chroma_coeffs_rect( |
| 13370 | dec, |
| 13371 | &mut coding, |
| 13372 | chroma_scan, |
| 13373 | chroma_w, |
| 13374 | chroma_h, |
| 13375 | skip_ctx, |
| 13376 | dc_sign_ctx(around[plane].2), |
| 13377 | default_tx, |
| 13378 | fctx, |
| 13379 | )?; |
| 13380 | planes.push((levels, tx_type)); |
| 13381 | } |
| 13382 | let (v_levels, v_tx_type) = planes.pop().expect("plane 2"); |
| 13383 | let (u_levels, u_tx_type) = planes.pop().expect("plane 1"); |
| 13384 | hit!(RECT4_COEFF_HITS); |
| 13385 | let luma_residual = dequant_and_inverse_typed_wh( |
| 13386 | &luma_levels, |
| 13387 | bw, |
| 13388 | bh, |
| 13389 | crate::decode::bit_depth(fctx), |
| 13390 | block_q_idx(fctx), |
| 13391 | plane_q_delta(0, fctx).0, |
| 13392 | plane_q_delta(0, fctx).1, |
| 13393 | luma_tx_type, |
| 13394 | block_iqmatrix(fctx, 0, bw, bh, luma_tx_type), |
| 13395 | ); |
| 13396 | if let Some(b) = &palette_y_buf { |
| 13397 | set_palette_pred(b.clone(), fctx); |
| 13398 | } |
| 13399 | push_intra_rect(0, |
| 13400 | px, |
| 13401 | py, |
| 13402 | bw, |
| 13403 | bh, |
| 13404 | mode, |
| 13405 | angle_delta_y, |
| 13406 | reach, |
| 13407 | &luma_residual, |
| 13408 | None, |
| 13409 | filter_intra, |
| 13410 | smooth_neighbor, fctx, |
| 13411 | ); |
| 13412 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 13413 | for (plane, _buf, levels, tx_type) in [ |
| 13414 | (1usize, &mut *u, &u_levels, u_tx_type), |
| 13415 | (2, &mut *v, &v_levels, v_tx_type), |
| 13416 | ] { |
| 13417 | let residual = dequant_and_inverse_typed_wh( |
| 13418 | levels, |
| 13419 | chroma_w, |
| 13420 | chroma_h, |
| 13421 | crate::decode::bit_depth(fctx), |
| 13422 | block_q_idx(fctx), |
| 13423 | plane_q_delta(plane, fctx).0, |
| 13424 | plane_q_delta(plane, fctx).1, |
| 13425 | tx_type, |
| 13426 | block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type), |
| 13427 | ); |
| 13428 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 13429 | set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx); |
| 13430 | } |
| 13431 | push_intra_rect(plane, |
| 13432 | cpx, |
| 13433 | cpy, |
| 13434 | chroma_w, |
| 13435 | chroma_h, |
| 13436 | uv_predict_mode, |
| 13437 | angle_delta_uv, |
| 13438 | reach, |
| 13439 | &residual, |
| 13440 | alpha |
| 13441 | .zip(ac) |
| 13442 | .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), |
| 13443 | None, |
| 13444 | smooth_neighbor_uv, fctx, |
| 13445 | ); |
| 13446 | } |
| 13447 | neighbours.record_mi_rect( |
| 13448 | (mi_r, mi_c), |
| 13449 | bw, |
| 13450 | bh, |
| 13451 | &[&luma_levels[..], &u_levels[..], &v_levels[..]], |
| 13452 | ); |
| 13453 | neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip); |
| 13454 | neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx); |
| 13455 | record_strip_palette( |
| 13456 | neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, |
| 13457 | pal_uv_colors, |
| 13458 | ); |
| 13459 | if bw > bh { |
| 13460 | hit!(RECT4_32_HORZ_HITS); |
| 13461 | } else { |
| 13462 | hit!(RECT4_32_VERT_HITS); |
| 13463 | } |
| 13464 | // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, |
| 13465 | // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter |
| 13466 | // frame, so this 1:4 strip -- which is also the INTER frame's reader |
| 13467 | // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its |
| 13468 | // transform size in both TXFM_CONTEXT bands. Without it the next block |
| 13469 | // reads the row's stale value. |
| 13470 | txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh)); |
| 13471 | return Ok((mode, uv_predict_mode)); |
| 13472 | }; |
| 13473 | if let Some(b) = &palette_y_buf { |
| 13474 | set_palette_pred(b.clone(), fctx); |
| 13475 | } |
| 13476 | push_intra_rect(0, |
| 13477 | px, |
| 13478 | py, |
| 13479 | bw, |
| 13480 | bh, |
| 13481 | mode, |
| 13482 | angle_delta_y, |
| 13483 | reach, |
| 13484 | &luma_levels, |
| 13485 | None, |
| 13486 | filter_intra, |
| 13487 | smooth_neighbor, fctx, |
| 13488 | ); |
| 13489 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 13490 | if let Some((ub, _)) = &palette_uv_bufs { |
| 13491 | set_palette_pred(ub.clone(), fctx); |
| 13492 | } |
| 13493 | push_intra_rect(1, |
| 13494 | cpx, |
| 13495 | cpy, |
| 13496 | chroma_w, |
| 13497 | chroma_h, |
| 13498 | uv_predict_mode, |
| 13499 | angle_delta_uv, |
| 13500 | reach, |
| 13501 | &u_levels, |
| 13502 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 13503 | None, |
| 13504 | smooth_neighbor_uv, fctx, |
| 13505 | ); |
| 13506 | if let Some((_, vb)) = &palette_uv_bufs { |
| 13507 | set_palette_pred(vb.clone(), fctx); |
| 13508 | } |
| 13509 | push_intra_rect(2, |
| 13510 | cpx, |
| 13511 | cpy, |
| 13512 | chroma_w, |
| 13513 | chroma_h, |
| 13514 | uv_predict_mode, |
| 13515 | angle_delta_uv, |
| 13516 | reach, |
| 13517 | &v_levels, |
| 13518 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 13519 | None, |
| 13520 | smooth_neighbor_uv, fctx, |
| 13521 | ); |
| 13522 | neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]); |
| 13523 | neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip); |
| 13524 | neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx); |
| 13525 | record_strip_palette( |
| 13526 | neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, |
| 13527 | ); |
| 13528 | if bw > bh { |
| 13529 | hit!(RECT4_32_HORZ_HITS); |
| 13530 | } else { |
| 13531 | hit!(RECT4_32_VERT_HITS); |
| 13532 | } |
| 13533 | // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, |
| 13534 | // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter |
| 13535 | // frame, so this 1:4 strip -- which is also the INTER frame's reader |
| 13536 | // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its |
| 13537 | // transform size in both TXFM_CONTEXT bands. Without it the next block |
| 13538 | // reads the row's stale value. |
| 13539 | txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh)); |
| 13540 | Ok((mode, uv_predict_mode)) |
| 13541 | } |
| 13542 | |
| 13543 | /// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` / |
| 13544 | /// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level |
| 13545 | /// down, and the first shape here whose luma block is a single mi row (or |
| 13546 | /// column). |
| 13547 | /// |
| 13548 | /// What is new at this size is CHROMA. `is_chroma_reference` |
| 13549 | /// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an |
| 13550 | /// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/ |
| 13551 | /// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close |
| 13552 | /// the pair and carry the chroma of the whole 16x8 (8x16) luma pair -- |
| 13553 | /// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) && |
| 13554 | /// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma |
| 13555 | /// transform at the PAIR's origin, with CfL averaging over the pair's luma. |
| 13556 | /// |
| 13557 | /// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context |
| 13558 | /// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is |
| 13559 | /// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row); |
| 13560 | /// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is |
| 13561 | /// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE |
| 13562 | /// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and |
| 13563 | /// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this |
| 13564 | /// shape's own CDF row. |
| 13565 | /// |
| 13566 | /// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`) |
| 13567 | /// refuses by name rather than guess-decode. |
| 13568 | #[allow(clippy::too_many_arguments)] |
| 13569 | fn decode_rect4_16( |
| 13570 | dec: &mut SymbolDecoder, |
| 13571 | cdfs: &mut Cdfs, |
| 13572 | neighbours: &mut Neighbours, |
| 13573 | at16: (usize, usize), |
| 13574 | horz: bool, |
| 13575 | y: &mut PlaneBuf<'static>, |
| 13576 | u: &mut PlaneBuf<'static>, |
| 13577 | v: &mut PlaneBuf<'static>, |
| 13578 | enable_filter_intra: bool, |
| 13579 | allow_screen_content_tools: bool, |
| 13580 | base_q_idx: u8, |
| 13581 | tx_select: bool, |
| 13582 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 13583 | ) -> Result<()> { |
| 13584 | let (r, c) = at16; |
| 13585 | let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI)); |
| 13586 | let (bw, bh) = if horz { (16, 4) } else { (4, 16) }; |
| 13587 | let (_mi_w, _mi_h) = (bw / MI, bh / MI); |
| 13588 | let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 }; |
| 13589 | let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 }; |
| 13590 | let mut prev: Option<((usize, usize), usize)> = None; |
| 13591 | let mut last_mode = DC_PRED; |
| 13592 | let mut last_uv_mode = DC_PRED; |
| 13593 | for i in 0..4usize { |
| 13594 | let lmi = if horz { |
| 13595 | (mi_row0 + i, mi_col0) |
| 13596 | } else { |
| 13597 | (mi_row0, mi_col0 + i) |
| 13598 | }; |
| 13599 | // lane-av1-444: at 4:4:4 every strip is its own chroma reference |
| 13600 | // (no mi-parity test at ss 0/0, and the strip's own chroma block is |
| 13601 | // already >= 4x4) -- there is no 4:2:0 pair to close. |
| 13602 | let has_chroma = i % 2 == 1 || (ss_x(fctx) == 0 && ss_y(fctx) == 0); |
| 13603 | let (mode, uv, _tx) = decode_rect4_16_strip( |
| 13604 | dec, |
| 13605 | cdfs, |
| 13606 | neighbours, |
| 13607 | lmi, |
| 13608 | horz, |
| 13609 | has_chroma, |
| 13610 | prev, |
| 13611 | y, |
| 13612 | u, |
| 13613 | v, |
| 13614 | enable_filter_intra, |
| 13615 | allow_screen_content_tools, |
| 13616 | base_q_idx, |
| 13617 | tx_select, |
| 13618 | reduced_tx_set, fctx, |
| 13619 | )?; |
| 13620 | if let Some(m) = uv { |
| 13621 | last_uv_mode = m; |
| 13622 | } |
| 13623 | last_mode = mode; |
| 13624 | prev = Some((lmi, mode)); |
| 13625 | } |
| 13626 | // The coarse 16-px cell holds one entry for the whole 16x16: the last |
| 13627 | // strip is what a block below (right) sees through it, the mi-exact maps |
| 13628 | // above answering everything finer. |
| 13629 | neighbours.above_mode[c] = last_mode; |
| 13630 | neighbours.left_mode[r] = last_mode; |
| 13631 | neighbours.above_uv_mode[c] = last_uv_mode; |
| 13632 | neighbours.left_uv_mode[r] = last_uv_mode; |
| 13633 | neighbours.above_side[c] = bw; |
| 13634 | neighbours.left_side[r] = bh; |
| 13635 | Ok(()) |
| 13636 | } |
| 13637 | |
| 13638 | /// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded -- |
| 13639 | /// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER |
| 13640 | /// block path can decode a SINGLE intra strip of a partition whose other |
| 13641 | /// strips are inter. `prev` is the previous strip's `(mi, mode)` (the |
| 13642 | /// key-frame caller's coarse-cell stand-in; `None` on the inter path, where |
| 13643 | /// every strip publishes its own mi-exact mode). Returns |
| 13644 | /// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`. |
| 13645 | /// Intrabc reconstruction for a rect strip that OWNS its chroma |
| 13646 | /// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that |
| 13647 | /// pair goes through [`decode_rect4_16_intrabc`]. |
| 13648 | /// |
| 13649 | /// This is the same control flow as the unmerged lane's `decode_intrabc_rect` |
| 13650 | /// (predict once, then one residual per transform unit on the INTER sets, |
| 13651 | /// chroma inherits luma's `tx_type`), written against the helpers that exist |
| 13652 | /// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The |
| 13653 | /// merge with lane-av1-intrabc should keep one of the two bodies; the call |
| 13654 | /// shape is the same. |
| 13655 | #[allow(clippy::too_many_arguments)] |
| 13656 | fn decode_intrabc_owned_rect( |
| 13657 | dec: &mut SymbolDecoder, |
| 13658 | cdfs: &mut Cdfs, |
| 13659 | neighbours: &mut Neighbours, |
| 13660 | (mi_r, mi_c): (usize, usize), |
| 13661 | (bw, bh): (usize, usize), |
| 13662 | skip: bool, |
| 13663 | (dv_row, dv_col): (i32, i32), |
| 13664 | y: &mut PlaneBuf<'static>, |
| 13665 | u: &mut PlaneBuf<'static>, |
| 13666 | v: &mut PlaneBuf<'static>, |
| 13667 | base_q_idx: u8, |
| 13668 | tx_select: bool, |
| 13669 | reduced_tx_set: bool, |
| 13670 | fctx: &crate::decode::FrameCtx, |
| 13671 | ) -> Result<()> { |
| 13672 | let _ = base_q_idx; |
| 13673 | let (px, py) = (mi_c * MI, mi_r * MI); |
| 13674 | let (cw, ch) = (bw / 2, bh / 2); |
| 13675 | let side = bw.max(bh); |
| 13676 | let cside = cw.max(ch); |
| 13677 | let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); |
| 13678 | let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get); |
| 13679 | fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); |
| 13680 | // `read_block_tx_size_rect` keys on this cell. A key frame forces it |
| 13681 | // false; the real bit is the caller's `tx_select`. Restored before return. |
| 13682 | fctx.tx_select_inter.with(|c| c.set(tx_select)); |
| 13683 | let restore = ReducedTxRestore { fctx, saved_reduced, saved_tx }; |
| 13684 | |
| 13685 | flush_recon(fctx, y, u, v); |
| 13686 | let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx); |
| 13687 | let pred_u = predict_intrabc_window(u, px / 2, py / 2, cw, ch, dv_col, dv_row, false, cside, fctx); |
| 13688 | let pred_v = predict_intrabc_window(v, px / 2, py / 2, cw, ch, dv_col, dv_row, false, cside, fctx); |
| 13689 | |
| 13690 | let mi_cols = 2 * y.true_width.div_ceil(8); |
| 13691 | let mi_rows = 2 * y.true_height.div_ceil(8); |
| 13692 | let leaves = read_block_tx_size_rect( |
| 13693 | dec, cdfs, neighbours, (mi_r, mi_c), (bw, bh), (mi_cols, mi_rows), skip, fctx, |
| 13694 | )?; |
| 13695 | let mut luma_tx_type = TxType::DctDct; |
| 13696 | let luma_grid; |
| 13697 | let u_grid; |
| 13698 | let v_grid; |
| 13699 | if skip { |
| 13700 | // `reconstruct_mc_rect` indexes the residual at the square stride. |
| 13701 | // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136). |
| 13702 | push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx); |
| 13703 | push_mc_rect(1, px / 2, py / 2, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * ch], fctx); |
| 13704 | push_mc_rect(2, px / 2, py / 2, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * ch], fctx); |
| 13705 | if let Some(ls) = leaves.as_ref() { |
| 13706 | // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`, |
| 13707 | // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its |
| 13708 | // whole entropy-band footprint. The non-skip arm below writes |
| 13709 | // those bands per transform unit and the tail's |
| 13710 | // `record_split_luma_rect_mi` writes chroma only, so without |
| 13711 | // this walk a skipped strip whose `leaves` resolved (every |
| 13712 | // lossless frame -- `read_block_tx_size_rect`'s lossless arm |
| 13713 | // returns the 4x4 grid before it looks at `skip`) leaked the |
| 13714 | // PREVIOUS occupant's luma bands into the next block's |
| 13715 | // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped |
| 13716 | // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128 |
| 13717 | // stream left a stale 7 in left[48] and mi(48,68)'s first |
| 13718 | // transform unit read `txb_skip_ctx` 3 where aomdec reads 1). |
| 13719 | hit!(SKIP_LOSSLESS_BAND_RESET_HITS); |
| 13720 | for &(row, col, tw, th) in ls { |
| 13721 | neighbours.record_mi_luma_rect( |
| 13722 | (mi_r + row, mi_c + col), |
| 13723 | tw, |
| 13724 | th, |
| 13725 | &ZERO_RESIDUAL[..tw * th], |
| 13726 | ); |
| 13727 | } |
| 13728 | } |
| 13729 | luma_grid = Grid::Zero(side * side); |
| 13730 | u_grid = Grid::Zero(cside * cside); |
| 13731 | v_grid = Grid::Zero(cside * cside); |
| 13732 | } else if let Some(ls) = leaves.as_ref() { |
| 13733 | for (idx, &(row, col, tw, th)) in ls.iter().enumerate() { |
| 13734 | let tu_mi = (mi_r + row, mi_c + col); |
| 13735 | let (tu_px, tu_py) = (px + col * MI, py + row * MI); |
| 13736 | let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); |
| 13737 | let (g, tt) = if tw == th { |
| 13738 | read_inter_plane( |
| 13739 | dec, cdfs, inter_txbset_for(tw, reduced_tx_set), &default_scan(tw.min(32)), |
| 13740 | 0, neighbours.around_mi(tu_mi, tw)[0], 0, y, tu_px, tu_py, tw, base_q_idx, |
| 13741 | tu_pred, None, Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)), fctx, |
| 13742 | )? |
| 13743 | } else { |
| 13744 | read_inter_plane_rect( |
| 13745 | dec, cdfs, rect_inter_luma_set(tw, th, fctx)?, (tw, th), side, 0, |
| 13746 | neighbours.around_mi_rect(tu_mi, tw, th)[0], 0, y, tu_px, tu_py, tu_pred, |
| 13747 | None, Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)), fctx, |
| 13748 | )? |
| 13749 | }; |
| 13750 | if idx == 0 { |
| 13751 | luma_tx_type = tt; |
| 13752 | } |
| 13753 | neighbours.record_mi_luma_rect(tu_mi, tw, th, &g); |
| 13754 | if tw != th { |
| 13755 | neighbours.fill_lf_grid_leaf_luma((tu_mi.0, tu_mi.1), tw / MI, th / MI, tw as u8, th as u8); |
| 13756 | } |
| 13757 | } |
| 13758 | luma_grid = Grid::Zero(side * side); |
| 13759 | let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); |
| 13760 | let (ug, _) = read_inter_plane_rect( |
| 13761 | dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, |
| 13762 | u, px / 2, py / 2, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, |
| 13763 | )?; |
| 13764 | let (vg, _) = read_inter_plane_rect( |
| 13765 | dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, |
| 13766 | v, px / 2, py / 2, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, |
| 13767 | )?; |
| 13768 | u_grid = ug; |
| 13769 | v_grid = vg; |
| 13770 | } else { |
| 13771 | let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); |
| 13772 | let (g, tt) = read_inter_plane_rect( |
| 13773 | dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0, |
| 13774 | y, px, py, Pred::Inline(&pred_y, side), None, None, fctx, |
| 13775 | )?; |
| 13776 | luma_tx_type = tt; |
| 13777 | luma_grid = g; |
| 13778 | let (ug, _) = read_inter_plane_rect( |
| 13779 | dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, |
| 13780 | u, px / 2, py / 2, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, |
| 13781 | )?; |
| 13782 | let (vg, _) = read_inter_plane_rect( |
| 13783 | dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, |
| 13784 | v, px / 2, py / 2, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, |
| 13785 | )?; |
| 13786 | u_grid = ug; |
| 13787 | v_grid = vg; |
| 13788 | } |
| 13789 | drop(restore); |
| 13790 | if leaves.is_some() { |
| 13791 | neighbours.record_split_luma_rect_mi((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid]); |
| 13792 | } else { |
| 13793 | neighbours.record_rect_mi((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid]); |
| 13794 | } |
| 13795 | neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); |
| 13796 | neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); |
| 13797 | neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); |
| 13798 | neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, bw.min(64) as u8, bh.min(64) as u8, 0, fctx); |
| 13799 | record_intrabc_mi_rect(mi_r, mi_c, bw / MI, bh / MI, Some((dv_row, dv_col)), neighbours, fctx); |
| 13800 | let _ = luma_tx_type; |
| 13801 | Ok(()) |
| 13802 | } |
| 13803 | |
| 13804 | fn predict_intrabc_window( |
| 13805 | plane: &PlaneBuf<'_>, |
| 13806 | px: usize, |
| 13807 | py: usize, |
| 13808 | w: usize, |
| 13809 | h: usize, |
| 13810 | dv_col: i32, |
| 13811 | dv_row: i32, |
| 13812 | luma: bool, |
| 13813 | stride: usize, |
| 13814 | fctx: &crate::decode::FrameCtx, |
| 13815 | ) -> Vec<u16> { |
| 13816 | let mut dense = vec![0u16; w * h]; |
| 13817 | mc::predict_with_filter( |
| 13818 | &plane.data, plane.width, plane.true_width, plane.true_height, |
| 13819 | 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) }), |
| 13820 | w, h, mc::InterpFilterKind::Bilinear, &mut dense, fctx, |
| 13821 | ); |
| 13822 | let mut laid = vec![0u16; stride * stride]; |
| 13823 | for row in 0..h { |
| 13824 | laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]); |
| 13825 | } |
| 13826 | laid |
| 13827 | } |
| 13828 | |
| 13829 | struct ReducedTxRestore<'a> { |
| 13830 | fctx: &'a crate::decode::FrameCtx, |
| 13831 | saved_reduced: bool, |
| 13832 | saved_tx: bool, |
| 13833 | } |
| 13834 | impl Drop for ReducedTxRestore<'_> { |
| 13835 | fn drop(&mut self) { |
| 13836 | self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved_reduced)); |
| 13837 | self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx)); |
| 13838 | } |
| 13839 | } |
| 13840 | |
| 13841 | /// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14). |
| 13842 | /// |
| 13843 | /// A 1:4 strip is a PAIR. Both children share one chroma block, and only the |
| 13844 | /// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`: |
| 13845 | /// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma |
| 13846 | /// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and |
| 13847 | /// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s |
| 13848 | /// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this |
| 13849 | /// strip's own footprint, copied from this strip's DV. The block is |
| 13850 | /// `is_inter_block`, so the residual uses the INTER sets and chroma inherits |
| 13851 | /// the luma unit's coded `tx_type`. |
| 13852 | /// |
| 13853 | /// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this |
| 13854 | /// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that |
| 13855 | /// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it |
| 13856 | /// would code chroma on every strip. |
| 13857 | #[allow(clippy::too_many_arguments)] |
| 13858 | fn decode_rect4_16_intrabc( |
| 13859 | dec: &mut SymbolDecoder, |
| 13860 | cdfs: &mut Cdfs, |
| 13861 | neighbours: &mut Neighbours, |
| 13862 | lmi: (usize, usize), |
| 13863 | horz: bool, |
| 13864 | has_chroma: bool, |
| 13865 | skip: bool, |
| 13866 | (dv_row, dv_col): (i32, i32), |
| 13867 | y: &mut PlaneBuf<'static>, |
| 13868 | u: &mut PlaneBuf<'static>, |
| 13869 | v: &mut PlaneBuf<'static>, |
| 13870 | base_q_idx: u8, |
| 13871 | tx_select: bool, |
| 13872 | reduced_tx_set: bool, |
| 13873 | fctx: &crate::decode::FrameCtx, |
| 13874 | ) -> Result<(usize, Option<usize>, (usize, usize))> { |
| 13875 | let _ = base_q_idx; |
| 13876 | hit!(RECT4_16_INTRABC_HITS); |
| 13877 | let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) }; |
| 13878 | let (mi_w, mi_h) = (bw / MI, bh / MI); |
| 13879 | let (px, py) = (lmi.1 * MI, lmi.0 * MI); |
| 13880 | let side = bw.max(bh); |
| 13881 | // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder |
| 13882 | // publishes `reduced_tx_set` into it; set it here too so a caller that |
| 13883 | // passed the bit explicitly cannot disagree with the set we read. |
| 13884 | let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); |
| 13885 | fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); |
| 13886 | let restored = scopeguard_reduced(fctx, saved_reduced); |
| 13887 | |
| 13888 | flush_recon(fctx, y, u, v); |
| 13889 | let mut pred_y_dense = vec![0u16; bw * bh]; |
| 13890 | mc::predict_with_filter( |
| 13891 | &y.data, y.width, y.true_width, y.true_height, |
| 13892 | mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0), |
| 13893 | bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx, |
| 13894 | ); |
| 13895 | let mut pred_y = vec![0u16; side * side]; |
| 13896 | for row in 0..bh { |
| 13897 | pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]); |
| 13898 | } |
| 13899 | |
| 13900 | let (pw, ph) = if horz { (16usize, 8usize) } else { (8, 16) }; |
| 13901 | let (cw, ch) = (pw / 2, ph / 2); |
| 13902 | let pair_mi = if has_chroma { |
| 13903 | if horz { (lmi.0 - 1, lmi.1) } else { (lmi.0, lmi.1 - 1) } |
| 13904 | } else { |
| 13905 | lmi |
| 13906 | }; |
| 13907 | let (cpx, cpy) = if has_chroma { |
| 13908 | (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2) |
| 13909 | } else { |
| 13910 | (0, 0) |
| 13911 | }; |
| 13912 | let cside = cw.max(ch); |
| 13913 | let (pred_u, pred_v) = if has_chroma { |
| 13914 | let mut ud = vec![0u16; cw * ch]; |
| 13915 | mc::predict_with_filter( |
| 13916 | &u.data, u.width, u.true_width, u.true_height, |
| 13917 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), |
| 13918 | cw, ch, mc::InterpFilterKind::Bilinear, &mut ud, fctx, |
| 13919 | ); |
| 13920 | let mut us = vec![0u16; cside * cside]; |
| 13921 | for row in 0..ch { |
| 13922 | us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]); |
| 13923 | } |
| 13924 | let mut vd = vec![0u16; cw * ch]; |
| 13925 | mc::predict_with_filter( |
| 13926 | &v.data, v.width, v.true_width, v.true_height, |
| 13927 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)), |
| 13928 | cw, ch, mc::InterpFilterKind::Bilinear, &mut vd, fctx, |
| 13929 | ); |
| 13930 | let mut vs = vec![0u16; cside * cside]; |
| 13931 | for row in 0..ch { |
| 13932 | vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]); |
| 13933 | } |
| 13934 | (us, vs) |
| 13935 | } else { |
| 13936 | (Vec::new(), Vec::new()) |
| 13937 | }; |
| 13938 | |
| 13939 | // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced |
| 13940 | // false for a key frame, so `read_block_tx_size_rect` would skip the |
| 13941 | // symbol; read it here against the parameter the intra path already uses. |
| 13942 | // A skipped intrabc block predicts the whole footprint once and codes |
| 13943 | // no residual (`decode_token_recon_block`'s inter branch). Lossless |
| 13944 | // still forces TX_4X4 when the block is coded. |
| 13945 | let leaves = if skip || (!lossless(fctx) && !tx_select) { |
| 13946 | None |
| 13947 | } else if lossless(fctx) { |
| 13948 | let mut leaves = Vec::new(); |
| 13949 | for row in 0..bh / MI { |
| 13950 | for col in 0..bw / MI { |
| 13951 | leaves.push((row, col, 4usize, 4usize)); |
| 13952 | } |
| 13953 | } |
| 13954 | Some(leaves) |
| 13955 | } else { |
| 13956 | let ctx = txfm_partition_ctx_rect( |
| 13957 | neighbours.above_txfm[lmi.1], |
| 13958 | neighbours.left_txfm[lmi.0], |
| 13959 | side, |
| 13960 | bw, |
| 13961 | bh, |
| 13962 | ); |
| 13963 | let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; |
| 13964 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 13965 | let (rng, _) = dec.debug_state(); |
| 13966 | eprintln!( |
| 13967 | "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}", |
| 13968 | lmi.0, lmi.1, u8::from(split) |
| 13969 | ); |
| 13970 | } |
| 13971 | if !split { |
| 13972 | None |
| 13973 | } else { |
| 13974 | let (sub_w, sub_h) = sub_tx_size_map(bw, bh); |
| 13975 | let mi_cols = 2 * y.true_width.div_ceil(8); |
| 13976 | let mi_rows = 2 * y.true_height.div_ceil(8); |
| 13977 | let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1)); |
| 13978 | let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0)); |
| 13979 | let mut out = Vec::new(); |
| 13980 | for row in (0..bh / MI).step_by(sub_h / MI) { |
| 13981 | for col in (0..bw / MI).step_by(sub_w / MI) { |
| 13982 | read_var_tx_size( |
| 13983 | dec, cdfs, neighbours, lmi, side, (max_w_mi, max_h_mi), |
| 13984 | (sub_w, sub_h), 1, row, col, &mut out, |
| 13985 | ); |
| 13986 | } |
| 13987 | } |
| 13988 | Some(out) |
| 13989 | } |
| 13990 | }; |
| 13991 | let (tx_w, tx_h) = leaves.as_ref().and_then(|ls| ls.first()).map_or((bw, bh), |l| (l.2, l.3)); |
| 13992 | |
| 13993 | let mut luma_tx_type = TxType::DctDct; |
| 13994 | let luma_grid; |
| 13995 | let mut u_grid = Grid::Zero(cw * ch); |
| 13996 | let mut v_grid = Grid::Zero(cw * ch); |
| 13997 | let chroma_stamped_per_unit; |
| 13998 | |
| 13999 | if skip { |
| 14000 | push_mc_rect( |
| 14001 | 0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx, |
| 14002 | ); |
| 14003 | luma_grid = Grid::Zero(bw * bh); |
| 14004 | if has_chroma { |
| 14005 | push_mc_rect( |
| 14006 | 1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), |
| 14007 | &ZERO_RESIDUAL[..cside * ch], fctx, |
| 14008 | ); |
| 14009 | push_mc_rect( |
| 14010 | 2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), |
| 14011 | &ZERO_RESIDUAL[..cside * ch], fctx, |
| 14012 | ); |
| 14013 | } |
| 14014 | chroma_stamped_per_unit = false; |
| 14015 | } else if let Some(ls) = leaves.as_ref() { |
| 14016 | if lossless(fctx) { |
| 14017 | for &(row, col, _tw, _th) in ls { |
| 14018 | let tu_mi = (lmi.0 + row, lmi.1 + col); |
| 14019 | let (tu_px, tu_py) = (px + col * MI, py + row * MI); |
| 14020 | let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); |
| 14021 | let (g, _) = read_inter_plane( |
| 14022 | dec, cdfs, |
| 14023 | if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 }, |
| 14024 | &default_scan(4), 0, neighbours.around_mi(tu_mi, 4)[0], 0, |
| 14025 | y, tu_px, tu_py, 4, base_q_idx, tu_pred, None, |
| 14026 | Some(neighbours.luma_skip_ctx(tu_mi, 1)), fctx, |
| 14027 | )?; |
| 14028 | neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g); |
| 14029 | } |
| 14030 | } else { |
| 14031 | for (idx, &(row, col, tw, th)) in ls.iter().enumerate() { |
| 14032 | let tu_mi = (lmi.0 + row, lmi.1 + col); |
| 14033 | let (tu_px, tu_py) = (px + col * MI, py + row * MI); |
| 14034 | let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); |
| 14035 | let (g, tt) = if tw == th { |
| 14036 | read_inter_plane( |
| 14037 | dec, cdfs, inter_txbset_for(tw, reduced_tx_set), |
| 14038 | &default_scan(tw.min(32)), 0, neighbours.around_mi(tu_mi, tw)[0], 0, |
| 14039 | y, tu_px, tu_py, tw, base_q_idx, tu_pred, None, |
| 14040 | Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)), fctx, |
| 14041 | )? |
| 14042 | } else { |
| 14043 | read_inter_plane_rect( |
| 14044 | dec, cdfs, rect_inter_luma_set(tw, th, fctx)?, (tw, th), side, 0, |
| 14045 | neighbours.around_mi_rect(tu_mi, tw, th)[0], 0, y, tu_px, tu_py, tu_pred, |
| 14046 | None, Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)), fctx, |
| 14047 | )? |
| 14048 | }; |
| 14049 | if idx == 0 { |
| 14050 | luma_tx_type = tt; |
| 14051 | } |
| 14052 | neighbours.record_mi_luma_rect(tu_mi, tw, th, &g); |
| 14053 | } |
| 14054 | } |
| 14055 | luma_grid = Grid::Zero(bw * bh); |
| 14056 | chroma_stamped_per_unit = has_chroma && lossless(fctx); |
| 14057 | if has_chroma && lossless(fctx) { |
| 14058 | let (mut uo, mut vo) = (Vec::new(), Vec::new()); |
| 14059 | read_inter_chroma_lossless( |
| 14060 | dec, cdfs, neighbours, u, v, |
| 14061 | Pred::Inline(&pred_u, cside), Pred::Inline(&pred_v, cside), |
| 14062 | pair_mi, (cpx, cpy), (0, 0), (cw, ch), (cw, ch), cside, 0, base_q_idx, |
| 14063 | &mut uo, &mut vo, fctx, |
| 14064 | )?; |
| 14065 | u_grid = if uo.is_empty() { Grid::Zero(cw * ch) } else { Grid::Own(uo) }; |
| 14066 | v_grid = if vo.is_empty() { Grid::Zero(cw * ch) } else { Grid::Own(vo) }; |
| 14067 | } else if has_chroma { |
| 14068 | let around = neighbours.around_mi_rect(pair_mi, pw, ph); |
| 14069 | let (ug, _) = read_inter_plane_rect( |
| 14070 | dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, |
| 14071 | u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, |
| 14072 | )?; |
| 14073 | u_grid = ug; |
| 14074 | let (vg, _) = read_inter_plane_rect( |
| 14075 | dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, |
| 14076 | v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, |
| 14077 | )?; |
| 14078 | v_grid = vg; |
| 14079 | } |
| 14080 | } else { |
| 14081 | let around = neighbours.around_mi_rect(lmi, bw, bh); |
| 14082 | let (g, tt) = read_inter_plane_rect( |
| 14083 | dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0, |
| 14084 | y, px, py, Pred::Inline(&pred_y, side), None, None, fctx, |
| 14085 | )?; |
| 14086 | luma_tx_type = tt; |
| 14087 | luma_grid = g; |
| 14088 | chroma_stamped_per_unit = false; |
| 14089 | if has_chroma { |
| 14090 | let around = neighbours.around_mi_rect(pair_mi, pw, ph); |
| 14091 | let (ug, _) = read_inter_plane_rect( |
| 14092 | dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0, |
| 14093 | u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx, |
| 14094 | )?; |
| 14095 | u_grid = ug; |
| 14096 | let (vg, _) = read_inter_plane_rect( |
| 14097 | dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0, |
| 14098 | v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx, |
| 14099 | )?; |
| 14100 | v_grid = vg; |
| 14101 | } |
| 14102 | } |
| 14103 | drop(restored); |
| 14104 | |
| 14105 | if leaves.is_none() { |
| 14106 | neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid); |
| 14107 | } |
| 14108 | neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED); |
| 14109 | neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip); |
| 14110 | neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx); |
| 14111 | for cell in 0..mi_w { |
| 14112 | if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) { |
| 14113 | *slot = bw as u8; |
| 14114 | } |
| 14115 | } |
| 14116 | for cell in 0..mi_h { |
| 14117 | if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) { |
| 14118 | *slot = bh as u8; |
| 14119 | } |
| 14120 | } |
| 14121 | let mut last_uv = None; |
| 14122 | if has_chroma { |
| 14123 | hit!(RECT4_16_CHROMA_HITS); |
| 14124 | neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED); |
| 14125 | if !chroma_stamped_per_unit { |
| 14126 | let u_state = neighbour_state(&u_grid); |
| 14127 | let v_state = neighbour_state(&v_grid); |
| 14128 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 14129 | let bound_h = round_up_even(neighbours.mi_rows); |
| 14130 | let bound_w = round_up_even(neighbours.mi_cols); |
| 14131 | for cell in 0..(ph / MI) { |
| 14132 | if pair_mi.0 + cell < bound_h |
| 14133 | && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell) |
| 14134 | { |
| 14135 | slot[1] = u_state; |
| 14136 | slot[2] = v_state; |
| 14137 | } |
| 14138 | } |
| 14139 | for cell in 0..(pw / MI) { |
| 14140 | if pair_mi.1 + cell < bound_w |
| 14141 | && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell) |
| 14142 | { |
| 14143 | slot[1] = u_state; |
| 14144 | slot[2] = v_state; |
| 14145 | } |
| 14146 | } |
| 14147 | } |
| 14148 | last_uv = Some(DC_PRED); |
| 14149 | } |
| 14150 | if horz { |
| 14151 | hit!(RECT4_16_HORZ_HITS); |
| 14152 | } else { |
| 14153 | hit!(RECT4_16_VERT_HITS); |
| 14154 | } |
| 14155 | record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]); |
| 14156 | if leaves.is_none() { |
| 14157 | // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs` |
| 14158 | // with `skip && is_inter`, or the unsplit unit). A split tree already |
| 14159 | // published per leaf inside `read_var_tx_size`. |
| 14160 | txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh)); |
| 14161 | } |
| 14162 | record_intrabc_mi_rect( |
| 14163 | lmi.0, lmi.1, mi_w, mi_h, Some((dv_row, dv_col)), neighbours, fctx, |
| 14164 | ); |
| 14165 | Ok((DC_PRED, last_uv, (tx_w, tx_h))) |
| 14166 | } |
| 14167 | |
| 14168 | /// Restores `reduced_tx_set_inter` when the intrabc pair reader returns, |
| 14169 | /// including through `?`. |
| 14170 | struct ReducedRestore<'a> { |
| 14171 | fctx: &'a crate::decode::FrameCtx, |
| 14172 | saved: bool, |
| 14173 | } |
| 14174 | impl Drop for ReducedRestore<'_> { |
| 14175 | fn drop(&mut self) { |
| 14176 | self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved)); |
| 14177 | } |
| 14178 | } |
| 14179 | fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> { |
| 14180 | ReducedRestore { fctx, saved } |
| 14181 | } |
| 14182 | |
| 14183 | #[allow(clippy::too_many_arguments)] |
| 14184 | fn decode_rect4_16_strip( |
| 14185 | dec: &mut SymbolDecoder, |
| 14186 | cdfs: &mut Cdfs, |
| 14187 | neighbours: &mut Neighbours, |
| 14188 | lmi: (usize, usize), |
| 14189 | horz: bool, |
| 14190 | has_chroma: bool, |
| 14191 | prev: Option<((usize, usize), usize)>, |
| 14192 | y: &mut PlaneBuf<'static>, |
| 14193 | u: &mut PlaneBuf<'static>, |
| 14194 | v: &mut PlaneBuf<'static>, |
| 14195 | enable_filter_intra: bool, |
| 14196 | allow_screen_content_tools: bool, |
| 14197 | base_q_idx: u8, |
| 14198 | tx_select: bool, |
| 14199 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 14200 | ) -> Result<(usize, Option<usize>, (usize, usize))> { |
| 14201 | let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI)); |
| 14202 | let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) }; |
| 14203 | let (mi_w, mi_h) = (bw / MI, bh / MI); |
| 14204 | let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 }; |
| 14205 | let mut last_uv_mode: Option<usize> = None; |
| 14206 | // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell |
| 14207 | // aliases all four strips onto one entry, so the mi-exact map wins and |
| 14208 | // the previous strip stands in on the split axis. |
| 14209 | let mut above_mode = neighbours.above_mode[c]; |
| 14210 | let mut left_mode = neighbours.left_mode[r]; |
| 14211 | if let Some(((pr, pc), pmode)) = prev { |
| 14212 | if pc == lmi.1 && lmi.0 == pr + mi_h { |
| 14213 | above_mode = pmode; |
| 14214 | } else if pr == lmi.0 && lmi.1 == pc + mi_w { |
| 14215 | left_mode = pmode; |
| 14216 | } |
| 14217 | } |
| 14218 | let (above_mode, left_mode) = |
| 14219 | neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode)); |
| 14220 | // lane-kf900 r4: the strip's real palette ctx + colour cache (see |
| 14221 | // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode` |
| 14222 | // off CDF row 0 and every cache hit off an empty cache. |
| 14223 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi); |
| 14224 | let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi); |
| 14225 | let ( |
| 14226 | skip, |
| 14227 | mode, |
| 14228 | angle_delta_y, |
| 14229 | uv_mode, |
| 14230 | angle_delta_uv, |
| 14231 | alpha, |
| 14232 | filter_intra, |
| 14233 | palette_y, |
| 14234 | palette_uv, |
| 14235 | intrabc, |
| 14236 | ) = read_intra_mode_rect( |
| 14237 | dec, |
| 14238 | cdfs, |
| 14239 | above_mode, |
| 14240 | left_mode, |
| 14241 | true, |
| 14242 | has_chroma, |
| 14243 | bw, |
| 14244 | bh, |
| 14245 | enable_filter_intra, |
| 14246 | neighbours.skip_txfm_ctx(lmi.0, lmi.1), |
| 14247 | allow_screen_content_tools, |
| 14248 | Some((palette_ctx, &palette_cache)), |
| 14249 | &palette_uv_cache, |
| 14250 | lmi.0, |
| 14251 | lmi.1, fctx, |
| 14252 | )?; |
| 14253 | if let Some(dv) = intrabc { |
| 14254 | return decode_rect4_16_intrabc( |
| 14255 | dec, cdfs, neighbours, lmi, horz, has_chroma, skip, dv, y, u, v, |
| 14256 | base_q_idx, tx_select, reduced_tx_set, fctx, |
| 14257 | ); |
| 14258 | } |
| 14259 | if palette_y.is_some() || palette_uv.is_some() { |
| 14260 | hit!(RECT4_PALETTE_HITS); |
| 14261 | } |
| 14262 | // The colour-index map through the base colours IS the prediction. |
| 14263 | // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one |
| 14264 | // chroma transform this closing strip codes. |
| 14265 | let palette_y_buf: Option<Vec<u16>> = palette_y |
| 14266 | .as_ref() |
| 14267 | .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); |
| 14268 | let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| { |
| 14269 | ( |
| 14270 | p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), |
| 14271 | p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), |
| 14272 | ) |
| 14273 | }); |
| 14274 | let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); |
| 14275 | if smooth_neighbor { |
| 14276 | hit!(SMOOTH_LUMA_HITS); |
| 14277 | } |
| 14278 | if filter_intra.is_some() { |
| 14279 | hit!(FILTER_INTRA_RECT_HITS); |
| 14280 | } |
| 14281 | // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is |
| 14282 | // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the |
| 14283 | // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol |
| 14284 | // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does. |
| 14285 | // lane-av1mixloss: the lossless-segment early return |
| 14286 | // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a |
| 14287 | // lossless-segment strip codes no depth symbol here either (class |
| 14288 | // sweep of the sub8 leaf's fix). |
| 14289 | let depth = if tx_select && !lossless(fctx) { |
| 14290 | // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands |
| 14291 | // (`get_tx_size_context`, libaom `pred_common.h:342`). |
| 14292 | let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); |
| 14293 | let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]); |
| 14294 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 14295 | eprintln!( |
| 14296 | "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}", |
| 14297 | lmi.0, |
| 14298 | lmi.1, |
| 14299 | dec.debug_state().0 |
| 14300 | ); |
| 14301 | } |
| 14302 | d |
| 14303 | } else { |
| 14304 | 0 |
| 14305 | }; |
| 14306 | if depth != 0 { |
| 14307 | hit!(TX_DEPTH_HITS); |
| 14308 | hit!(RECT4_16_SPLIT_HITS); |
| 14309 | } |
| 14310 | let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); |
| 14311 | let (px, py) = (lmi.1 * MI, lmi.0 * MI); |
| 14312 | let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 14313 | neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode); |
| 14314 | if depth != 0 || lossless(fctx) { |
| 14315 | // [`decode_rect_split`]'s per-unit walk, inlined because the |
| 14316 | // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to |
| 14317 | // the strip (that function codes one chroma transform per block). |
| 14318 | // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8 |
| 14319 | // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each |
| 14320 | // unit predicts off the units before it in raster order. |
| 14321 | let rect_unit = tx_w != tx_h; |
| 14322 | let zero_tu = vec![0i32; tx_w * tx_h]; |
| 14323 | for tu_row in 0..bh / tx_h { |
| 14324 | for tu_col in 0..bw / tx_w { |
| 14325 | let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI)); |
| 14326 | let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h); |
| 14327 | let tu_reach = Reach::of_tu( |
| 14328 | bw, |
| 14329 | bh, |
| 14330 | tu_col * tx_w, |
| 14331 | tu_row * tx_h, |
| 14332 | tx_w, |
| 14333 | tx_h, |
| 14334 | reach, |
| 14335 | ); |
| 14336 | if let Some(b) = &palette_y_buf { |
| 14337 | let tu_buf: Vec<u16> = (0..tx_h) |
| 14338 | .flat_map(|i| { |
| 14339 | let base = (tu_row * tx_h + i) * bw + tu_col * tx_w; |
| 14340 | b[base..base + tx_w].iter().copied() |
| 14341 | }) |
| 14342 | .collect(); |
| 14343 | set_palette_pred(tu_buf, fctx); |
| 14344 | } |
| 14345 | if skip { |
| 14346 | push_intra_rect(0, |
| 14347 | tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu, |
| 14348 | None, filter_intra, smooth_neighbor, fctx, |
| 14349 | ); |
| 14350 | neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu); |
| 14351 | } else if rect_unit { |
| 14352 | // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with |
| 14353 | // 32 coded positions and the `TX_4X4` `tx_type` row: |
| 14354 | // exactly [`TxbSet::LumaRect4x8`]. |
| 14355 | let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; |
| 14356 | let tu_skip_ctx = |
| 14357 | neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI); |
| 14358 | let set = if reduced_tx_set { |
| 14359 | TxbSet::LumaRect4x8 |
| 14360 | } else { |
| 14361 | TxbSet::LumaRect4x8Set1 |
| 14362 | }; |
| 14363 | let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 }; |
| 14364 | let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); |
| 14365 | let (tu_grid, tu_tx_type) = read_coeffs_rect( |
| 14366 | dec, |
| 14367 | &mut coding, |
| 14368 | tu_scan, |
| 14369 | tx_w, |
| 14370 | tx_h, |
| 14371 | tu_skip_ctx, |
| 14372 | dc_sign_ctx(tu_around.2), |
| 14373 | TxType::DctDct, |
| 14374 | )?; |
| 14375 | let residual = dequant_and_inverse_typed_wh( |
| 14376 | &tu_grid, |
| 14377 | tx_w, |
| 14378 | tx_h, |
| 14379 | crate::decode::bit_depth(fctx), |
| 14380 | block_q_idx(fctx), |
| 14381 | plane_q_delta(0, fctx).0, |
| 14382 | plane_q_delta(0, fctx).1, |
| 14383 | tu_tx_type, |
| 14384 | block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type), |
| 14385 | ); |
| 14386 | push_intra_rect(0, |
| 14387 | tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual, |
| 14388 | None, filter_intra, smooth_neighbor, fctx, |
| 14389 | ); |
| 14390 | if tu_grid.iter().any(|&l| l != 0) { |
| 14391 | hit!(RECT4_16_COEFF_HITS); |
| 14392 | } |
| 14393 | neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); |
| 14394 | } else { |
| 14395 | let tu_around = neighbours.around_mi(tu_mi, tx_w)[0]; |
| 14396 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI); |
| 14397 | let tu_grid = read_plane( |
| 14398 | dec, |
| 14399 | cdfs, |
| 14400 | txbset_for(tx_w, reduced_tx_set), |
| 14401 | default_scan(tx_w), |
| 14402 | 0, |
| 14403 | tu_around, |
| 14404 | mode, |
| 14405 | mode, |
| 14406 | angle_delta_y, |
| 14407 | tu_reach, |
| 14408 | y, |
| 14409 | tu_px, |
| 14410 | tu_py, |
| 14411 | tx_w, |
| 14412 | tx_w, |
| 14413 | base_q_idx, |
| 14414 | None, |
| 14415 | filter_intra, |
| 14416 | Some(tu_skip_ctx), |
| 14417 | smooth_neighbor, fctx, |
| 14418 | )?; |
| 14419 | if tu_grid.iter().any(|&l| l != 0) { |
| 14420 | hit!(RECT4_16_COEFF_HITS); |
| 14421 | } |
| 14422 | neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid); |
| 14423 | } |
| 14424 | } |
| 14425 | } |
| 14426 | } else { |
| 14427 | let levels = if skip { |
| 14428 | let zeros = Grid::Zero(bw * bh); |
| 14429 | if let Some(b) = &palette_y_buf { |
| 14430 | set_palette_pred(b.clone(), fctx); |
| 14431 | } |
| 14432 | push_intra_rect(0, |
| 14433 | px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra, |
| 14434 | smooth_neighbor, fctx, |
| 14435 | ); |
| 14436 | zeros |
| 14437 | } else { |
| 14438 | // The strip's luma TU *is* the strip (`plane_bsize == |
| 14439 | // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes |
| 14440 | // `txb_skip_ctx` at 0. |
| 14441 | let around = neighbours.around_mi_rect(lmi, bw, bh)[0]; |
| 14442 | let set = if reduced_tx_set { |
| 14443 | TxbSet::LumaRect16x4 |
| 14444 | } else { |
| 14445 | TxbSet::LumaRect16x4Set1 |
| 14446 | }; |
| 14447 | let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); |
| 14448 | let (levels, tx_type) = read_coeffs_rect( |
| 14449 | dec, |
| 14450 | &mut coding, |
| 14451 | scan, |
| 14452 | bw, |
| 14453 | bh, |
| 14454 | 0, |
| 14455 | dc_sign_ctx(around.2), |
| 14456 | TxType::DctDct, |
| 14457 | )?; |
| 14458 | let residual = dequant_and_inverse_typed_wh( |
| 14459 | &levels, |
| 14460 | bw, |
| 14461 | bh, |
| 14462 | crate::decode::bit_depth(fctx), |
| 14463 | block_q_idx(fctx), |
| 14464 | plane_q_delta(0, fctx).0, |
| 14465 | plane_q_delta(0, fctx).1, |
| 14466 | tx_type, |
| 14467 | block_iqmatrix(fctx, 0, bw, bh, tx_type), |
| 14468 | ); |
| 14469 | if let Some(b) = &palette_y_buf { |
| 14470 | set_palette_pred(b.clone(), fctx); |
| 14471 | } |
| 14472 | push_intra_rect(0, |
| 14473 | px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra, |
| 14474 | smooth_neighbor, fctx, |
| 14475 | ); |
| 14476 | hit!(RECT4_16_COEFF_HITS); |
| 14477 | levels |
| 14478 | }; |
| 14479 | neighbours.record_mi_luma_rect(lmi, bw, bh, &levels); |
| 14480 | } |
| 14481 | neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip); |
| 14482 | neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx); |
| 14483 | // `update_partition_context` writes `partition_context_lookup[ |
| 14484 | // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on |
| 14485 | // the left (mirrored under VERT_4). |
| 14486 | for cell in 0..mi_w { |
| 14487 | if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) { |
| 14488 | *slot = bw as u8; |
| 14489 | } |
| 14490 | } |
| 14491 | for cell in 0..mi_h { |
| 14492 | if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) { |
| 14493 | *slot = bh as u8; |
| 14494 | } |
| 14495 | } |
| 14496 | if has_chroma { |
| 14497 | hit!(RECT4_16_CHROMA_HITS); |
| 14498 | // lane-av1-444: at 4:4:4 there is no pair -- every strip is its |
| 14499 | // own chroma reference and codes its own 16x4 / 4x16 chroma |
| 14500 | // block. (`set_mi_offsets`'s chroma snap is the zero offset at |
| 14501 | // ss 0/0, so the neighbour reads below anchor at the strip.) |
| 14502 | let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 { |
| 14503 | (lmi, bw, bh) |
| 14504 | } else if horz { |
| 14505 | ((lmi.0 - 1, lmi.1), 16, 8) |
| 14506 | } else { |
| 14507 | ((lmi.0, lmi.1 - 1), 8, 16) |
| 14508 | }; |
| 14509 | let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI); |
| 14510 | let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx)); |
| 14511 | let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx)); |
| 14512 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 14513 | if (V_PRED..=D67_PRED).contains(&uv_predict_mode) { |
| 14514 | hit!(RECT4_16_CHROMA_DIR_HITS); |
| 14515 | } |
| 14516 | let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx); |
| 14517 | // lane-kf1200 r1: the chroma edge-filter type reads the neighbours |
| 14518 | // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s |
| 14519 | // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/ |
| 14520 | // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col |
| 14521 | // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e. |
| 14522 | // the pair's top-left luma mi, never this leaf's odd row/column. |
| 14523 | // Reading `lmi` here named the leaf directly above (a non-chroma |
| 14524 | // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a |
| 14525 | // SMOOTH neighbour: filt_type 0 instead of 1 turned |
| 14526 | // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a |
| 14527 | // directional chroma strip, moving 4 samples by 1. |
| 14528 | let smooth_neighbor_uv = |
| 14529 | neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx); |
| 14530 | if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c) |
| 14531 | { |
| 14532 | hit!(RECT4_16_UV_PAIR_FILT_HITS); |
| 14533 | } |
| 14534 | // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane |
| 14535 | // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is |
| 14536 | // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major |
| 14537 | // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading |
| 14538 | // the rect here consumed one symbol block too few and desynced |
| 14539 | // the next strip's `skip` (measured: lossless sb128 320x240, |
| 14540 | // mi(1,20) uv_mode matched, the following skip did not). |
| 14541 | let lossless_pair = lossless(fctx); |
| 14542 | let (u_levels, v_levels) = if lossless_pair { |
| 14543 | hit!(RECT4_16_LOSSLESS_CHROMA_HITS); |
| 14544 | if skip { |
| 14545 | for plane in 1..3usize { |
| 14546 | for rr in 0..ch / 4 { |
| 14547 | for cc in 0..cw / 4 { |
| 14548 | let (ox, oy) = (cc * 4, rr * 4); |
| 14549 | let cu_reach = tu_reach( |
| 14550 | pw, ph, ox * 2, oy * 2, 8, pair_reach, ppx, ppy, |
| 14551 | y.width, y.height, fctx, |
| 14552 | ); |
| 14553 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 14554 | let buf = if plane == 1 { ub } else { vb }; |
| 14555 | set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx); |
| 14556 | } |
| 14557 | push_intra( |
| 14558 | plane, cpx + ox, cpy + oy, 4, uv_predict_mode, |
| 14559 | angle_delta_uv, cu_reach, &ZERO_RESIDUAL[..16], None, None, |
| 14560 | smooth_neighbor_uv, fctx, |
| 14561 | ); |
| 14562 | let cu_mi = (pair_mi.0 + oy / 2, pair_mi.1 + ox / 2); |
| 14563 | neighbours.record_mi_chroma( |
| 14564 | cu_mi, 8, 8, plane, &ZERO_RESIDUAL[..16], |
| 14565 | ); |
| 14566 | } |
| 14567 | } |
| 14568 | } |
| 14569 | (Grid::Zero(cw * ch), Grid::Zero(cw * ch)) |
| 14570 | } else { |
| 14571 | let scan4 = default_scan(4); |
| 14572 | // `get_txb_ctx`: offset 10 (our tables store it at +3) |
| 14573 | // when the plane block is larger than the transform. |
| 14574 | let offset = Some(3usize); |
| 14575 | let mut uo = vec![0i32; cw * ch]; |
| 14576 | let mut vo = vec![0i32; cw * ch]; |
| 14577 | for plane in 1..3usize { |
| 14578 | for rr in 0..ch / 4 { |
| 14579 | for cc in 0..cw / 4 { |
| 14580 | let (ox, oy) = (cc * 4, rr * 4); |
| 14581 | if cpx + ox >= u.true_width || cpy + oy >= u.true_height { |
| 14582 | continue; |
| 14583 | } |
| 14584 | let cu_mi = (pair_mi.0 + oy / 2, pair_mi.1 + ox / 2); |
| 14585 | // One luma-mi cell: the chroma entropy arrays |
| 14586 | // are subsampled, and our bands replicate that |
| 14587 | // one entry over the unit's two cells |
| 14588 | // (`read_intra_chroma_lossless`). |
| 14589 | let cu_around = neighbours.around_mi(cu_mi, MI); |
| 14590 | let cu_reach = tu_reach( |
| 14591 | pw, ph, ox * 2, oy * 2, 8, pair_reach, ppx, ppy, |
| 14592 | y.width, y.height, fctx, |
| 14593 | ); |
| 14594 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 14595 | let buf = if plane == 1 { ub } else { vb }; |
| 14596 | set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx); |
| 14597 | } |
| 14598 | let buf: &mut PlaneBuf<'static> = |
| 14599 | if plane == 1 { &mut *u } else { &mut *v }; |
| 14600 | let cu_grid = read_plane( |
| 14601 | dec, cdfs, TxbSet::Chroma4, &scan4, plane, |
| 14602 | cu_around[plane], mode, uv_predict_mode, angle_delta_uv, |
| 14603 | cu_reach, buf, cpx + ox, cpy + oy, 4, 4, base_q_idx, |
| 14604 | None, None, offset, smooth_neighbor_uv, fctx, |
| 14605 | )?; |
| 14606 | neighbours.record_mi_chroma(cu_mi, 8, 8, plane, &cu_grid); |
| 14607 | hit!(CHROMA_SPLIT_TX_HITS); |
| 14608 | let dst = if plane == 1 { &mut uo } else { &mut vo }; |
| 14609 | for row in 0..4 { |
| 14610 | let start = (oy + row) * cw + ox; |
| 14611 | dst[start..start + 4] |
| 14612 | .copy_from_slice(&cu_grid[row * 4..][..4]); |
| 14613 | } |
| 14614 | } |
| 14615 | } |
| 14616 | } |
| 14617 | (Grid::Own(uo), Grid::Own(vo)) |
| 14618 | } |
| 14619 | } else if skip { |
| 14620 | let zeros = Grid::Zero(cw * ch); |
| 14621 | // libaom `predict_and_reconstruct_intra_block` (decodeframe.c |
| 14622 | // ~1000) predicts EVERY plane and only guards the residual on |
| 14623 | // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still |
| 14624 | // DC + alpha * luma-AC. Dropping the CfL term here left a |
| 14625 | // chroma-only bounded box on ReelC's key frames. |
| 14626 | let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph)); |
| 14627 | if alpha.is_some() { |
| 14628 | hit!(CHROMA_SKIP_CFL_HITS); |
| 14629 | } |
| 14630 | for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] { |
| 14631 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 14632 | set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx); |
| 14633 | } |
| 14634 | push_intra_rect(plane, |
| 14635 | cpx, |
| 14636 | cpy, |
| 14637 | cw, |
| 14638 | ch, |
| 14639 | uv_predict_mode, |
| 14640 | angle_delta_uv, |
| 14641 | pair_reach, |
| 14642 | &zeros, |
| 14643 | alpha |
| 14644 | .zip(ac) |
| 14645 | .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), |
| 14646 | None, |
| 14647 | smooth_neighbor_uv, fctx, |
| 14648 | ); |
| 14649 | } |
| 14650 | (zeros.clone(), zeros) |
| 14651 | } else { |
| 14652 | let around = neighbours.around_mi_rect(pair_mi, pw, ph); |
| 14653 | // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0 |
| 14654 | // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` = |
| 14655 | // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8. |
| 14656 | let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) { |
| 14657 | (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]), |
| 14658 | (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]), |
| 14659 | (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]), |
| 14660 | (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]), |
| 14661 | _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"), |
| 14662 | }; |
| 14663 | let mut planes = Vec::with_capacity(2); |
| 14664 | for plane in 1..3 { |
| 14665 | let default_tx = default_intra_tx_type(uv_predict_mode as u8); |
| 14666 | let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); |
| 14667 | let mut coding = cdfs.txb(chroma_set, uv_predict_mode); |
| 14668 | let (levels, tx_type) = read_chroma_coeffs_rect( |
| 14669 | dec, |
| 14670 | &mut coding, |
| 14671 | chroma_scan, |
| 14672 | cw, |
| 14673 | ch, |
| 14674 | skip_ctx, |
| 14675 | dc_sign_ctx(around[plane].2), |
| 14676 | default_tx, |
| 14677 | fctx, |
| 14678 | )?; |
| 14679 | planes.push((levels, tx_type)); |
| 14680 | } |
| 14681 | let (v_levels, v_tx_type) = planes.pop().expect("plane 2"); |
| 14682 | let (u_levels, u_tx_type) = planes.pop().expect("plane 1"); |
| 14683 | // CfL averages the luma of the WHOLE pair, the region this one |
| 14684 | // chroma transform covers. |
| 14685 | let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph)); |
| 14686 | for (plane, _buf, levels, tx_type) in [ |
| 14687 | (1usize, &mut *u, &u_levels, u_tx_type), |
| 14688 | (2, &mut *v, &v_levels, v_tx_type), |
| 14689 | ] { |
| 14690 | let residual = dequant_and_inverse_typed_wh( |
| 14691 | levels, |
| 14692 | cw, |
| 14693 | ch, |
| 14694 | crate::decode::bit_depth(fctx), |
| 14695 | block_q_idx(fctx), |
| 14696 | plane_q_delta(plane, fctx).0, |
| 14697 | plane_q_delta(plane, fctx).1, |
| 14698 | tx_type, |
| 14699 | block_iqmatrix(fctx, plane, cw, ch, tx_type), |
| 14700 | ); |
| 14701 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 14702 | set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx); |
| 14703 | } |
| 14704 | push_intra_rect(plane, |
| 14705 | cpx, |
| 14706 | cpy, |
| 14707 | cw, |
| 14708 | ch, |
| 14709 | uv_predict_mode, |
| 14710 | angle_delta_uv, |
| 14711 | pair_reach, |
| 14712 | &residual, |
| 14713 | alpha |
| 14714 | .zip(ac) |
| 14715 | .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), |
| 14716 | None, |
| 14717 | smooth_neighbor_uv, fctx, |
| 14718 | ); |
| 14719 | } |
| 14720 | (u_levels, v_levels) |
| 14721 | }; |
| 14722 | neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode); |
| 14723 | // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`). |
| 14724 | // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8. |
| 14725 | if !lossless_pair { |
| 14726 | // The chroma planes' coefficient context, over the PAIR's mi span |
| 14727 | // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is |
| 14728 | // the luma one rounded up to its 4x4 unit). |
| 14729 | let u_state = neighbour_state(&u_levels); |
| 14730 | let v_state = neighbour_state(&v_levels); |
| 14731 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 14732 | let bound_h = round_up_even(neighbours.mi_rows); |
| 14733 | let bound_w = round_up_even(neighbours.mi_cols); |
| 14734 | for cell in 0..(ph / MI) { |
| 14735 | if pair_mi.0 + cell < bound_h |
| 14736 | && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell) |
| 14737 | { |
| 14738 | slot[1] = u_state; |
| 14739 | slot[2] = v_state; |
| 14740 | } |
| 14741 | } |
| 14742 | for cell in 0..(pw / MI) { |
| 14743 | if pair_mi.1 + cell < bound_w |
| 14744 | && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell) |
| 14745 | { |
| 14746 | slot[1] = u_state; |
| 14747 | slot[2] = v_state; |
| 14748 | } |
| 14749 | } |
| 14750 | } |
| 14751 | last_uv_mode = Some(uv_predict_mode); |
| 14752 | } |
| 14753 | if horz { |
| 14754 | hit!(RECT4_16_HORZ_HITS); |
| 14755 | } else { |
| 14756 | hit!(RECT4_16_VERT_HITS); |
| 14757 | } |
| 14758 | let (pal_y_size, pal_y_colors) = |
| 14759 | palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 14760 | let (pal_uv_size, pal_uv_colors) = |
| 14761 | palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 14762 | record_strip_palette( |
| 14763 | neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, |
| 14764 | ); |
| 14765 | // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)` |
| 14766 | // (libaom `decode_token_recon_block`, run for EVERY block of an inter |
| 14767 | // frame): the above row records `tx_size_wide` over the block's width and |
| 14768 | // the left column `tx_size_high` over its height. This 1:4 strip reader is |
| 14769 | // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]), |
| 14770 | // and it published neither band -- so the block after a 64x16 strip read |
| 14771 | // the row's init value 64 as its left transform height and took |
| 14772 | // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the |
| 14773 | // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at |
| 14774 | // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware. |
| 14775 | txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh)); |
| 14776 | Ok((mode, last_uv_mode, (tx_w, tx_h))) |
| 14777 | } |
| 14778 | |
| 14779 | |
| 14780 | /// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/ |
| 14781 | /// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` / |
| 14782 | /// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike |
| 14783 | /// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient |
| 14784 | /// cap, so LUMA needs the same corner truncation [`decode_block`] already |
| 14785 | /// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx` |
| 14786 | /// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see |
| 14787 | /// this function's own charter/report), so both strips read a real 32x32 |
| 14788 | /// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and |
| 14789 | /// embed it top-left of a zeroed `bw`x`bh` grid, mirroring |
| 14790 | /// [`read_plane`]'s `tx_side != side` branch generalized to non-square. |
| 14791 | /// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated* |
| 14792 | /// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with |
| 14793 | /// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/ |
| 14794 | /// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like |
| 14795 | /// that function, only the single-transform-unit (`tx_depth == 0`) case is |
| 14796 | /// supported: a split transform refuses by name rather than guess-decode. |
| 14797 | #[allow(clippy::too_many_arguments)] |
| 14798 | fn decode_block_rect64( |
| 14799 | dec: &mut SymbolDecoder, |
| 14800 | cdfs: &mut Cdfs, |
| 14801 | neighbours: &mut Neighbours, |
| 14802 | at: (usize, usize), |
| 14803 | bw: usize, |
| 14804 | bh: usize, |
| 14805 | y: &mut PlaneBuf<'static>, |
| 14806 | u: &mut PlaneBuf<'static>, |
| 14807 | v: &mut PlaneBuf<'static>, |
| 14808 | enable_filter_intra: bool, |
| 14809 | allow_screen_content_tools: bool, |
| 14810 | base_q_idx: u8, |
| 14811 | tx_select: bool, |
| 14812 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 14813 | ) -> Result<()> { |
| 14814 | let (r, c) = at; |
| 14815 | let (px, py) = (c * SUB, r * SUB); |
| 14816 | let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); |
| 14817 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); |
| 14818 | let palette_uv_cache = neighbours.palette_uv_cache(at); |
| 14819 | let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) = |
| 14820 | read_intra_mode_rect( |
| 14821 | dec, |
| 14822 | cdfs, |
| 14823 | nb_above_mode, |
| 14824 | nb_left_mode, |
| 14825 | // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these |
| 14826 | // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike |
| 14827 | // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is |
| 14828 | // correct), CFL must never be offered here -- passing `true` |
| 14829 | // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of |
| 14830 | // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile |
| 14831 | // from this block's very first symbol (lane-sbpart r3 bisect). |
| 14832 | false, |
| 14833 | true, |
| 14834 | bw, |
| 14835 | bh, |
| 14836 | enable_filter_intra, |
| 14837 | neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), |
| 14838 | allow_screen_content_tools, |
| 14839 | Some((palette_ctx, &palette_cache)), |
| 14840 | &palette_uv_cache, |
| 14841 | r * (SUB / MI), |
| 14842 | c * (SUB / MI), fctx, |
| 14843 | )?; |
| 14844 | if let Some((dv_row, dv_col)) = intrabc { |
| 14845 | return decode_intrabc_owned_rect( |
| 14846 | dec, cdfs, neighbours, (r * (SUB / MI), c * (SUB / MI)), (bw, bh), skip, |
| 14847 | (dv_row, dv_col), y, u, v, base_q_idx, tx_select, reduced_tx_set, fctx, |
| 14848 | ); |
| 14849 | } |
| 14850 | if (palette_y.is_some() || palette_uv.is_some()) && !skip { |
| 14851 | // lane-t900 r34: a non-skip palette block on a superblock-level strip |
| 14852 | // -- counted so its gate cannot go vacuous (this was a refusal until |
| 14853 | // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_ |
| 14854 | // decodes_pixel_exact`). |
| 14855 | hit!(PALETTE_SB_STRIP_HITS); |
| 14856 | } |
| 14857 | let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); |
| 14858 | if smooth_neighbor { |
| 14859 | hit!(SMOOTH_LUMA_HITS); |
| 14860 | } |
| 14861 | let smooth_neighbor_uv = |
| 14862 | neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx); |
| 14863 | if filter_intra.is_some() { |
| 14864 | // `filter_intra_size_class_rect` already returns `None` for both |
| 14865 | // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at |
| 14866 | // 32 on both axes), so this symbol is never read at this level -- |
| 14867 | // kept only as the same defensive refusal [`decode_block_rect`] has. |
| 14868 | return Err(unsupported( |
| 14869 | "filter intra on a superblock-level HORZ/VERT strip (never expected -- \ |
| 14870 | av1_filter_intra_allowed_bsize caps at 32x32)", |
| 14871 | )); |
| 14872 | } |
| 14873 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { |
| 14874 | DC_PRED |
| 14875 | } else { |
| 14876 | uv_mode |
| 14877 | }; |
| 14878 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); |
| 14879 | // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) |
| 14880 | // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes |
| 14881 | // no depth symbol here either (class sweep of the sub8 leaf's fix). |
| 14882 | let depth = if tx_select && !lossless(fctx) { |
| 14883 | // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT` |
| 14884 | // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an |
| 14885 | // intra-only frame publishes them from every block too |
| 14886 | // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit |
| 14887 | // 1920x792 128-superblock stream, |
| 14888 | // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read |
| 14889 | // `tx_size_cat2` row 1 where libaom reads row 2. |
| 14890 | let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); |
| 14891 | // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`) |
| 14892 | // counts `sub_tx_size_map` steps from the block's own max rect |
| 14893 | // transform down to TX_4X4, minus one -- BLOCK_64X32's chain |
| 14894 | // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four |
| 14895 | // steps, so this level's category is 3 (the same one a 64x64 square |
| 14896 | // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF |
| 14897 | // here was a wrong-table read of a real symbol. |
| 14898 | let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]); |
| 14899 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 14900 | eprintln!( |
| 14901 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}", |
| 14902 | dec.debug_state().0 |
| 14903 | ); |
| 14904 | } |
| 14905 | d |
| 14906 | } else { |
| 14907 | 0 |
| 14908 | }; |
| 14909 | // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra |
| 14910 | // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`]. |
| 14911 | publish_txfm_bands_if_in_inter( |
| 14912 | neighbours, |
| 14913 | (mi_r, mi_c), |
| 14914 | depth_to_tx_wh(bw, bh, depth, fctx), |
| 14915 | (bw, bh), fctx, |
| 14916 | ); |
| 14917 | if depth != 0 || lossless(fctx) { |
| 14918 | hit!(TX_DEPTH_HITS); |
| 14919 | // lane-rectsplit r1/r4: the superblock-level strip splits its |
| 14920 | // transform through the very same per-unit path as its 32x32-level |
| 14921 | // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64 |
| 14922 | // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1 |
| 14923 | // measured the old square formula mis-tiling exactly that strip). |
| 14924 | let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); |
| 14925 | if bw.max(bh) / bw.min(bh) == 4 { |
| 14926 | let which = if depth == 1 { |
| 14927 | &RECT4_SPLIT_DEPTH1_HITS |
| 14928 | } else { |
| 14929 | &RECT4_SPLIT_DEPTH2_HITS |
| 14930 | }; |
| 14931 | hit_do! { which.with(|c| c.set(c.get() + 1)); } |
| 14932 | } |
| 14933 | if crate::envflags::env_flag!("EC_SBPART_DUMP64") { |
| 14934 | eprintln!( |
| 14935 | "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ |
| 14936 | depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \ |
| 14937 | angle_y={angle_delta_y}" |
| 14938 | ); |
| 14939 | } |
| 14940 | let modes = RectStripModes { |
| 14941 | skip, |
| 14942 | mode, |
| 14943 | angle_delta_y, |
| 14944 | uv_predict_mode, |
| 14945 | angle_delta_uv, |
| 14946 | alpha, |
| 14947 | filter_intra, |
| 14948 | smooth_neighbor, |
| 14949 | smooth_neighbor_uv, |
| 14950 | palette_y: palette_y |
| 14951 | .as_ref() |
| 14952 | .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), |
| 14953 | palette_uv: palette_uv.as_ref().map(|p| { |
| 14954 | ( |
| 14955 | p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), |
| 14956 | p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), |
| 14957 | ) |
| 14958 | }), |
| 14959 | }; |
| 14960 | if palette_y.is_some() || palette_uv.is_some() { |
| 14961 | hit!(PALETTE_SPLIT_TX_HITS); |
| 14962 | } |
| 14963 | decode_rect_split( |
| 14964 | dec, |
| 14965 | cdfs, |
| 14966 | neighbours, |
| 14967 | (mi_r, mi_c), |
| 14968 | bw, |
| 14969 | bh, |
| 14970 | tx_w, |
| 14971 | tx_h, |
| 14972 | &modes, |
| 14973 | y, |
| 14974 | u, |
| 14975 | v, |
| 14976 | base_q_idx, |
| 14977 | reduced_tx_set, fctx, |
| 14978 | )?; |
| 14979 | // Same early-return palette stamp as [`decode_block_rect`]'s split arm |
| 14980 | // (lane-palette2 r10): this return skips the fn's own tail, so a |
| 14981 | // split-tx superblock strip would otherwise leave the above/left |
| 14982 | // palette arrays holding a dead block's colours. |
| 14983 | let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 14984 | neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors); |
| 14985 | let (puv_size, puv_colors) = |
| 14986 | palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 14987 | neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); |
| 14988 | // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early |
| 14989 | // return skips the fn's own tail, so a SPLIT superblock-level strip |
| 14990 | // published no TXFM_CONTEXT band and the next block read the row's init |
| 14991 | // value 64 as its left transform height. Measured on the 10-bit |
| 14992 | // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip |
| 14993 | // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at |
| 14994 | // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The |
| 14995 | // bands carry the SPLIT unit's size, not the block's. |
| 14996 | txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); |
| 14997 | hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS); |
| 14998 | hit!(RECT_PARTITION_HITS); |
| 14999 | return Ok(()); |
| 15000 | } |
| 15001 | let (tx_w, tx_h) = (bw, bh); |
| 15002 | let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); |
| 15003 | let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); |
| 15004 | let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 15005 | if let Some(ref pyv) = palette_y { |
| 15006 | let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect(); |
| 15007 | set_palette_pred(buf, fctx); |
| 15008 | } |
| 15009 | let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| { |
| 15010 | ( |
| 15011 | puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(), |
| 15012 | puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), |
| 15013 | ) |
| 15014 | }); |
| 15015 | if skip { |
| 15016 | push_intra_rect(0, |
| 15017 | px, |
| 15018 | py, |
| 15019 | bw, |
| 15020 | bh, |
| 15021 | mode, |
| 15022 | angle_delta_y, |
| 15023 | reach, |
| 15024 | &ZERO_RESIDUAL[..bw * bh], |
| 15025 | None, |
| 15026 | filter_intra, |
| 15027 | smooth_neighbor, fctx, |
| 15028 | ); |
| 15029 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 15030 | if let Some((ub, _)) = &palette_uv_bufs { |
| 15031 | set_palette_pred(ub.clone(), fctx); |
| 15032 | } |
| 15033 | push_intra_rect(1, |
| 15034 | cpx, |
| 15035 | cpy, |
| 15036 | chroma_w, |
| 15037 | chroma_h, |
| 15038 | uv_predict_mode, |
| 15039 | angle_delta_uv, |
| 15040 | reach, |
| 15041 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 15042 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 15043 | None, |
| 15044 | smooth_neighbor_uv, fctx, |
| 15045 | ); |
| 15046 | if let Some((_, vb)) = &palette_uv_bufs { |
| 15047 | set_palette_pred(vb.clone(), fctx); |
| 15048 | } |
| 15049 | push_intra_rect(2, |
| 15050 | cpx, |
| 15051 | cpy, |
| 15052 | chroma_w, |
| 15053 | chroma_h, |
| 15054 | uv_predict_mode, |
| 15055 | angle_delta_uv, |
| 15056 | reach, |
| 15057 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 15058 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 15059 | None, |
| 15060 | smooth_neighbor_uv, fctx, |
| 15061 | ); |
| 15062 | neighbours.record_rect( |
| 15063 | at, |
| 15064 | bw, |
| 15065 | bh, |
| 15066 | mode, |
| 15067 | uv_predict_mode, |
| 15068 | &[ |
| 15069 | &ZERO_RESIDUAL[..bw * bh], |
| 15070 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 15071 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 15072 | ], |
| 15073 | ); |
| 15074 | } else { |
| 15075 | let around = neighbours.around_rect(at, bw, bh); |
| 15076 | // LUMA: the coded corner, embedded top-left of the true bw x bh grid |
| 15077 | // (see this function's own doc comment). A 64-length axis codes only |
| 15078 | // its low 32 coefficients, so the corner is `min(bw, 32)` x |
| 15079 | // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and |
| 15080 | // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16). |
| 15081 | let (luma_cw, luma_ch) = (bw.min(32), bh.min(32)); |
| 15082 | let scan32 = default_scan(TX32); |
| 15083 | if coeff_trace_on() { |
| 15084 | let (rng, _) = dec.debug_state(); |
| 15085 | eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"); |
| 15086 | } |
| 15087 | let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) { |
| 15088 | let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode); |
| 15089 | read_coeffs( |
| 15090 | dec, |
| 15091 | &mut luma_coding, |
| 15092 | &scan32, |
| 15093 | 0, |
| 15094 | dc_sign_ctx(around[0].2), |
| 15095 | TxType::DctDct, |
| 15096 | Some((bw, bh)), |
| 15097 | )? |
| 15098 | } else { |
| 15099 | // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 -> |
| 15100 | // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders` |
| 15101 | // (`scan.c`) gives both the very same `default_scan_32x16` / |
| 15102 | // `default_scan_16x32` the 2:1 sizes use ("Half of the |
| 15103 | // coefficients of tx64 at higher frequencies are set to zeros. So |
| 15104 | // tx32's scan order is used"). `get_txsize_entropy_ctx` is |
| 15105 | // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 + |
| 15106 | // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a |
| 15107 | // 512-position eob group) -- BOTH identical to TX_32X16, so the |
| 15108 | // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table |
| 15109 | // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally |
| 15110 | // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is |
| 15111 | // what `base_ctx_rect` computes at (32, 16). |
| 15112 | let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 }; |
| 15113 | let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode); |
| 15114 | read_coeffs_rect( |
| 15115 | dec, |
| 15116 | &mut luma_coding, |
| 15117 | luma_scan, |
| 15118 | luma_cw, |
| 15119 | luma_ch, |
| 15120 | 0, |
| 15121 | dc_sign_ctx(around[0].2), |
| 15122 | TxType::DctDct, |
| 15123 | )? |
| 15124 | }; |
| 15125 | if coeff_trace_on() { |
| 15126 | let (rng, _) = dec.debug_state(); |
| 15127 | eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}"); |
| 15128 | } |
| 15129 | let mut luma_levels = vec![0i32; bw * bh]; |
| 15130 | for row in 0..luma_ch { |
| 15131 | luma_levels[row * bw..][..luma_cw] |
| 15132 | .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]); |
| 15133 | } |
| 15134 | { |
| 15135 | let cur = block_q_idx(fctx); |
| 15136 | if cur != i32::from(base_q_idx) { |
| 15137 | hit!(RECT64_QIDX_DRIFT_HITS); |
| 15138 | } |
| 15139 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 15140 | eprintln!( |
| 15141 | "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}" |
| 15142 | ); |
| 15143 | } |
| 15144 | } |
| 15145 | let luma_residual = dequant_and_inverse_typed_wh( |
| 15146 | &luma_levels, |
| 15147 | bw, |
| 15148 | bh, |
| 15149 | crate::decode::bit_depth(fctx), |
| 15150 | block_q_idx(fctx), |
| 15151 | plane_q_delta(0, fctx).0, |
| 15152 | plane_q_delta(0, fctx).1, |
| 15153 | luma_tx_type, |
| 15154 | block_iqmatrix(fctx, 0, bw, bh, luma_tx_type), |
| 15155 | ); |
| 15156 | push_intra_rect(0, |
| 15157 | px, |
| 15158 | py, |
| 15159 | bw, |
| 15160 | bh, |
| 15161 | mode, |
| 15162 | angle_delta_y, |
| 15163 | reach, |
| 15164 | &luma_residual, |
| 15165 | None, |
| 15166 | filter_intra, |
| 15167 | smooth_neighbor, fctx, |
| 15168 | ); |
| 15169 | if crate::envflags::env_flag!("EC_SBPART_DUMP64") { |
| 15170 | let leftcol: Vec<u16> = if px > 0 { |
| 15171 | (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect() |
| 15172 | } else { |
| 15173 | vec![] |
| 15174 | }; |
| 15175 | eprintln!( |
| 15176 | "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \ |
| 15177 | skip={skip} eob_nonzero={} row0={:?} leftcol={:?}", |
| 15178 | luma_corner.iter().any(|&v| v != 0), |
| 15179 | &y.data[py * y.width + px..][..bw], |
| 15180 | leftcol, |
| 15181 | ); |
| 15182 | } |
| 15183 | // CHROMA. At 4:2:0 the plane block is already one adjusted UV |
| 15184 | // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma |
| 15185 | // is larger than that, so it is tiled into 32-capped units. |
| 15186 | let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 15187 | let (uw, uh) = (chroma_w.min(32), chroma_h.min(32)); |
| 15188 | let (nw, nh) = (chroma_w / uw, chroma_h / uh); |
| 15189 | let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) { |
| 15190 | (32, 32) => (TxbSet::Chroma32, default_scan(32)), |
| 15191 | (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16), |
| 15192 | (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32), |
| 15193 | (32, 8) => (TxbSet::Chroma16, &SCAN_32X8), |
| 15194 | (8, 32) => (TxbSet::Chroma16, &SCAN_8X32), |
| 15195 | _ => { |
| 15196 | return Err(unsupported( |
| 15197 | "a 64-axis strip whose chroma unit has no coefficient table", |
| 15198 | )) |
| 15199 | } |
| 15200 | }; |
| 15201 | let bigger = nw * nh > 1; |
| 15202 | let mut u_levels = vec![0i32; chroma_w * chroma_h]; |
| 15203 | let mut v_levels = vec![0i32; chroma_w * chroma_h]; |
| 15204 | // The tiled units below stamp their own coefficient context |
| 15205 | // immediately, then the whole-strip `record_rect` rewrite paints |
| 15206 | // every chroma cell with ONE whole-strip state and the per-unit DC |
| 15207 | // signs and levels are lost (class `override-slot-on-one-arm`, same |
| 15208 | // shape as `decode_rect_split`'s chroma_tiled clobber). Collected |
| 15209 | // here and replayed after that record, the c8 `mu_chroma_units` way. |
| 15210 | let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); |
| 15211 | for plane_idx in 1..=2 { |
| 15212 | for cu_row in 0..nh { |
| 15213 | for cu_col in 0..nw { |
| 15214 | let cu_around = if nw == 1 && nh == 1 { |
| 15215 | around |
| 15216 | } else { |
| 15217 | let lsx = uw << ss_x(fctx); |
| 15218 | let lsy = uh << ss_y(fctx); |
| 15219 | let cu_mi = ( |
| 15220 | mi_r + cu_row * (lsy / MI), |
| 15221 | mi_c + cu_col * (lsx / MI), |
| 15222 | ); |
| 15223 | neighbours.around_mi_rect(cu_mi, lsx, lsy) |
| 15224 | }; |
| 15225 | let lsx = uw << ss_x(fctx); |
| 15226 | let lsy = uh << ss_y(fctx); |
| 15227 | let cfl = alpha.map(|(au, av)| { |
| 15228 | let a = if plane_idx == 1 { au } else { av }; |
| 15229 | (a, cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy)) |
| 15230 | }); |
| 15231 | let levels = if uw == uh { |
| 15232 | let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; |
| 15233 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 15234 | set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx); |
| 15235 | } |
| 15236 | read_plane( |
| 15237 | dec, cdfs, chroma_set, chroma_scan, plane_idx, cu_around[plane_idx], |
| 15238 | mode, uv_predict_mode, angle_delta_uv, reach, plane, |
| 15239 | cpx + cu_col * uw, cpy + cu_row * uh, uw, uw, base_q_idx, |
| 15240 | cfl, None, bigger.then_some(3), smooth_neighbor_uv, fctx, |
| 15241 | )? |
| 15242 | } else { |
| 15243 | let skip_ctx = usize::from(cu_around[plane_idx].0) |
| 15244 | + usize::from(cu_around[plane_idx].1) |
| 15245 | + usize::from(bigger) * 3; |
| 15246 | let mut coding = cdfs.txb(chroma_set, uv_predict_mode); |
| 15247 | let (levels, tx_type) = read_chroma_coeffs_rect( |
| 15248 | dec, &mut coding, chroma_scan, uw, uh, skip_ctx, |
| 15249 | dc_sign_ctx(cu_around[plane_idx].2), TxType::DctDct, fctx, |
| 15250 | )?; |
| 15251 | let residual = dequant_and_inverse_typed_wh( |
| 15252 | &levels, uw, uh, crate::decode::bit_depth(fctx), |
| 15253 | block_q_idx(fctx), |
| 15254 | plane_q_delta(plane_idx, fctx).0, |
| 15255 | plane_q_delta(plane_idx, fctx).1, |
| 15256 | tx_type, |
| 15257 | block_iqmatrix(fctx, plane_idx, uw, uh, tx_type), |
| 15258 | ); |
| 15259 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 15260 | set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx); |
| 15261 | } |
| 15262 | push_intra_rect( |
| 15263 | plane_idx, cpx + cu_col * uw, cpy + cu_row * uh, uw, uh, |
| 15264 | uv_predict_mode, angle_delta_uv, reach, &residual, |
| 15265 | cfl, None, smooth_neighbor_uv, fctx, |
| 15266 | ); |
| 15267 | levels |
| 15268 | }; |
| 15269 | let dst = if plane_idx == 1 { &mut u_levels } else { &mut v_levels }; |
| 15270 | for row in 0..uh { |
| 15271 | let d = (cu_row * uh + row) * chroma_w + cu_col * uw; |
| 15272 | dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]); |
| 15273 | } |
| 15274 | if bigger { |
| 15275 | neighbours.record_mi_chroma( |
| 15276 | (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)), |
| 15277 | lsx, lsy, plane_idx, &levels, |
| 15278 | ); |
| 15279 | tiled_chroma_units.push(( |
| 15280 | (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)), |
| 15281 | plane_idx, |
| 15282 | levels.clone(), |
| 15283 | lsx, |
| 15284 | lsy, |
| 15285 | )); |
| 15286 | } |
| 15287 | } |
| 15288 | } |
| 15289 | } |
| 15290 | neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]); |
| 15291 | // The per-unit re-stamp: `record_rect` above wrote the whole strip's |
| 15292 | // chroma cells from the assembled grids' one whole-strip state, |
| 15293 | // overwriting exactly the stamps the tiled loop just made. |
| 15294 | for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units { |
| 15295 | neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit); |
| 15296 | } |
| 15297 | hit!(RECT_COEFF_HITS); |
| 15298 | } |
| 15299 | let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 15300 | neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors); |
| 15301 | let (puv_size, puv_colors) = |
| 15302 | palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 15303 | neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); |
| 15304 | neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); |
| 15305 | neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx); |
| 15306 | // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)` |
| 15307 | // (libaom `decode_token_recon_block`, run for EVERY block of an inter |
| 15308 | // frame): the above row records `tx_size_wide` over the block's width and |
| 15309 | // the left column `tx_size_high` over its height. This 1:4 strip reader is |
| 15310 | // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]), |
| 15311 | // and it published neither band -- so the block after a 64x16 strip read |
| 15312 | // the row's init value 64 as its left transform height and took |
| 15313 | // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the |
| 15314 | // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at |
| 15315 | // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware. |
| 15316 | txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); |
| 15317 | hit!(SB_RECT_HITS); |
| 15318 | match (bw, bh) { |
| 15319 | (64, 16) => hit!(SB_RECT4_HORZ_HITS), |
| 15320 | (16, 64) => hit!(SB_RECT4_VERT_HITS), |
| 15321 | _ => {} |
| 15322 | } |
| 15323 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 15324 | let (rng, _) = dec.debug_state(); |
| 15325 | eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}"); |
| 15326 | } |
| 15327 | Ok(()) |
| 15328 | } |
| 15329 | |
| 15330 | /// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus |
| 15331 | /// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA` |
| 15332 | /// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever |
| 15333 | /// it lands away from zero, for gate tests to prove a real stream fired one. |
| 15334 | fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 { |
| 15335 | let symbol = dec.symbol(cdf); |
| 15336 | if symbol != ANGLE_DELTA_ZERO { |
| 15337 | hit!(ANGLE_DELTA_HITS); |
| 15338 | } |
| 15339 | symbol as i32 - ANGLE_DELTA_ZERO as i32 |
| 15340 | } |
| 15341 | |
| 15342 | #[allow(clippy::too_many_arguments)] |
| 15343 | fn read_intra_mode( |
| 15344 | dec: &mut SymbolDecoder, |
| 15345 | cdfs: &mut Cdfs, |
| 15346 | above_mode: usize, |
| 15347 | left_mode: usize, |
| 15348 | cfl: bool, |
| 15349 | side: usize, |
| 15350 | enable_filter_intra: bool, |
| 15351 | skip_ctx: usize, |
| 15352 | allow_screen_content_tools: bool, |
| 15353 | allow_intrabc: bool, |
| 15354 | // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's |
| 15355 | // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx` |
| 15356 | // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]); |
| 15357 | // `None` at the excluded call sites (the 8x8-leaf path), which still read |
| 15358 | // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real |
| 15359 | // decoder reads either way -- but refuse by name the moment it fires, |
| 15360 | // exactly the old behaviour. |
| 15361 | palette: Option<(usize, &[u16])>, |
| 15362 | // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]), |
| 15363 | // `&[]` at the excluded call sites -- same corner-cut as `palette` above, |
| 15364 | // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read |
| 15365 | // `use_palette_y`, not a neighbour lookup). |
| 15366 | palette_uv_cache: &[u16], |
| 15367 | mi_r: usize, |
| 15368 | mi_c: usize, fctx: &crate::decode::FrameCtx, |
| 15369 | ) -> Result<( |
| 15370 | bool, |
| 15371 | usize, |
| 15372 | i32, |
| 15373 | usize, |
| 15374 | i32, |
| 15375 | Option<(i32, i32)>, |
| 15376 | Option<usize>, |
| 15377 | Option<PaletteY>, |
| 15378 | Option<PaletteUv>, |
| 15379 | )> { |
| 15380 | let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); |
| 15381 | // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..." |
| 15382 | // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints |
| 15383 | // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for |
| 15384 | // line against the instrumented aomdec, not just `tell()`. |
| 15385 | let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); |
| 15386 | if ec_istep { |
| 15387 | // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line |
| 15388 | // (decodemv.c:818), printed at the same point: before the first |
| 15389 | // mode-info symbol of the block, so a cross-decoder range ladder can |
| 15390 | // be keyed on the BLOCK, not just on the symbol sequence. |
| 15391 | eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0); |
| 15392 | } |
| 15393 | macro_rules! istep { |
| 15394 | ($name:literal, $val:expr) => { |
| 15395 | if ec_istep { |
| 15396 | let (rng, _) = dec.debug_state(); |
| 15397 | eprintln!( |
| 15398 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}", |
| 15399 | $name, $val |
| 15400 | ); |
| 15401 | } |
| 15402 | }; |
| 15403 | } |
| 15404 | // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single |
| 15405 | // point every square caller routes through (see `read_intra_mode_rect`). |
| 15406 | let cfl = if cfl && side > 32 { |
| 15407 | hit!(NOCFL_UV_MODE_HITS); |
| 15408 | false |
| 15409 | } else { |
| 15410 | cfl |
| 15411 | }; |
| 15412 | // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE |
| 15413 | // `skip` when `SegIdPreSkip`, and after it otherwise. |
| 15414 | let (seg_w_mi, seg_h_mi) = (side / 4, side / 4); |
| 15415 | if seg_id_pre_skip(fctx) { |
| 15416 | intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx); |
| 15417 | } |
| 15418 | let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; |
| 15419 | if trace { |
| 15420 | eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0); |
| 15421 | } |
| 15422 | istep!("skip", skip as i32); |
| 15423 | if !seg_id_pre_skip(fctx) { |
| 15424 | intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx); |
| 15425 | } |
| 15426 | // spec order (see the comment below on `read_intrabc_info`): `skip`, |
| 15427 | // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here. |
| 15428 | maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx); |
| 15429 | istep!("cdef", 0); |
| 15430 | // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not |
| 15431 | // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole |
| 15432 | // superblock and skips `delta_q` exactly like a 64 one under a 64 root. |
| 15433 | let whole_sb = side == sb_mi_cur(fctx) as usize * 4; |
| 15434 | maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx); |
| 15435 | maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx); |
| 15436 | istep!("dq", 0); |
| 15437 | // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at |
| 15438 | // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before |
| 15439 | // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an |
| 15440 | // intra frame whose header set `allow_intrabc`. Actual intra block copy |
| 15441 | // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`, |
| 15442 | // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope |
| 15443 | // draws the line at consuming this one flag symbol and refusing by name |
| 15444 | // when it fires, so the arithmetic decoder still resyncs for a stream |
| 15445 | // that merely allows (but never uses) intrabc. |
| 15446 | if allow_intrabc { |
| 15447 | let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; |
| 15448 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 15449 | eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", u8::from(use_intrabc), dec.debug_state().0); |
| 15450 | } |
| 15451 | if trace { |
| 15452 | eprintln!("TRACE use_intrabc value={}", use_intrabc as i32); |
| 15453 | } |
| 15454 | if use_intrabc { |
| 15455 | let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx); |
| 15456 | if trace { |
| 15457 | eprintln!("TRACE intrabc dv={dv:?}"); |
| 15458 | } |
| 15459 | fctx.intrabc_dv.with(|c| c.set(Some(dv))); |
| 15460 | hit!(INTRABC_HITS); |
| 15461 | // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the |
| 15462 | // moment `is_intrabc_block`: no y/uv mode, angle delta, palette, |
| 15463 | // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced |
| 15464 | // `DC_PRED` (which is also what the neighbour mode contexts and |
| 15465 | // the loop filter then see). |
| 15466 | return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None)); |
| 15467 | } |
| 15468 | } |
| 15469 | let above_ctx = INTRA_MODE_CTX[above_mode]; |
| 15470 | let left_ctx = INTRA_MODE_CTX[left_mode]; |
| 15471 | let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); |
| 15472 | if trace { |
| 15473 | eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0); |
| 15474 | } |
| 15475 | istep!("mode", mode as i32); |
| 15476 | let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { |
| 15477 | let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]); |
| 15478 | if trace { |
| 15479 | eprintln!( |
| 15480 | "TRACE angle_delta value={}", |
| 15481 | delta + ANGLE_DELTA_ZERO as i32 |
| 15482 | ); |
| 15483 | } |
| 15484 | delta |
| 15485 | } else { |
| 15486 | 0 |
| 15487 | }; |
| 15488 | istep!("angle_y", angle_delta_y); |
| 15489 | // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette |
| 15490 | // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref` |
| 15491 | // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader |
| 15492 | // gates its chroma symbols on. |
| 15493 | let has_chroma = !mono(fctx); |
| 15494 | let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx); |
| 15495 | let uv_mode = if !has_chroma { |
| 15496 | DC_PRED |
| 15497 | } else if cfl { |
| 15498 | dec.symbol(&mut cdfs.uv_mode_cfl[mode]) |
| 15499 | } else { |
| 15500 | dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) |
| 15501 | }; |
| 15502 | if trace { |
| 15503 | eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0); |
| 15504 | } |
| 15505 | istep!("uv_mode", uv_mode as i32); |
| 15506 | let alpha = if cfl && uv_mode == UV_CFL_PRED { |
| 15507 | Some(read_cfl_alphas(dec, cdfs)) |
| 15508 | } else { |
| 15509 | None |
| 15510 | }; |
| 15511 | // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap |
| 15512 | // from this lane's directional chroma: a corner block with neither |
| 15513 | // `above` nor `left` (both `Edges::build`'s no-neighbour fallback, |
| 15514 | // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta |
| 15515 | // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched |
| 15516 | // bug in that fallback this lane's own scope does not cover. Keep it |
| 15517 | // refused here rather than ship a silently-wrong decode. |
| 15518 | if (9..=12).contains(&uv_mode) { |
| 15519 | hit!(SMOOTH_UV_HITS); |
| 15520 | } |
| 15521 | // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the |
| 15522 | // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads |
| 15523 | // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw, |
| 15524 | // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes |
| 15525 | // the `else` branch below and never reads one either way. |
| 15526 | let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 15527 | hit!(DIRECTIONAL_UV_HITS); |
| 15528 | read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) |
| 15529 | } else { |
| 15530 | 0 |
| 15531 | }; |
| 15532 | istep!("angle_uv", angle_delta_uv); |
| 15533 | if angle_delta_uv != 0 { |
| 15534 | hit!(UV_ANGLE_DELTA_HITS); |
| 15535 | } |
| 15536 | // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called |
| 15537 | // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`): |
| 15538 | // gated by `av1_allow_palette` (blockd.h -- size bound only, |
| 15539 | // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller |
| 15540 | // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old |
| 15541 | // behaviour, bit-identical since a hardcoded ctx-0 read and a real one |
| 15542 | // read the same CDF row whenever every neighbour really is non-palette). |
| 15543 | // `palette_uv_mode_ctx` is this block's own just-decided Y palette use, |
| 15544 | // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a |
| 15545 | // neighbour lookup at all), so it is exact even at the excluded call |
| 15546 | // sites once Y decodes real syntax there too. |
| 15547 | // |
| 15548 | // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called |
| 15549 | // inline from `read_palette_mode_info` -- it runs later, from |
| 15550 | // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`), |
| 15551 | // after the WHOLE mode-info read for the block, including UV palette |
| 15552 | // mode_info (`read_palette_mode_info`'s own second half, right below) |
| 15553 | // and `read_filter_intra_mode_info`. So this branch now only reads |
| 15554 | // mode/size/colours for both planes (deferring the two colour-index-map |
| 15555 | // decodes to after `filter_intra`, below) -- r6's range trace pinned |
| 15556 | // this exact ordering bug (`compare-range-not-tell`: ranges matched |
| 15557 | // bit-for-bit through the Y colours, diverged only at the old inline |
| 15558 | // `decode_color_index_map` call). |
| 15559 | let mut palette_y_pending: Option<(usize, [u16; 8])> = None; |
| 15560 | let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; |
| 15561 | if allow_screen_content_tools |
| 15562 | && let Some(bsize_ctx) = palette_bsize_ctx(side) |
| 15563 | { |
| 15564 | let (mode_ctx, cache) = palette.unwrap_or((0, &[])); |
| 15565 | if mode == DC_PRED { |
| 15566 | if trace { |
| 15567 | let (rng, _) = dec.debug_state(); |
| 15568 | eprintln!( |
| 15569 | "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}" |
| 15570 | ); |
| 15571 | } |
| 15572 | } |
| 15573 | let use_palette_y = |
| 15574 | mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0; |
| 15575 | if mode == DC_PRED && trace { |
| 15576 | let (rng, _) = dec.debug_state(); |
| 15577 | eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32); |
| 15578 | } |
| 15579 | if use_palette_y { |
| 15580 | let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); |
| 15581 | if trace { |
| 15582 | let (rng, _) = dec.debug_state(); |
| 15583 | eprintln!("TRACE palette_y_size n={n} rng={rng}"); |
| 15584 | } |
| 15585 | let colors = read_palette_colors_y(dec, n, cache, fctx); |
| 15586 | if trace { |
| 15587 | let (rng, _) = dec.debug_state(); |
| 15588 | eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]); |
| 15589 | } |
| 15590 | palette_y_pending = Some((n, colors)); |
| 15591 | } |
| 15592 | // `read_palette_mode_info`'s UV half (decodemv.c:588): read |
| 15593 | // unconditionally at this bit position whenever `uv_mode == |
| 15594 | // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's |
| 15595 | // scope always reconstructs chroma alongside luma (`decode_block` |
| 15596 | // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref` |
| 15597 | // is always true here and does not need threading in. |
| 15598 | // |
| 15599 | // lane-av1mono: libaom's actual guard is `num_planes > 1 && |
| 15600 | // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a |
| 15601 | // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size` |
| 15602 | // symbol even at this chroma-owning square block. |
| 15603 | let palette_uv_mode_ctx = usize::from(use_palette_y); |
| 15604 | if has_chroma |
| 15605 | && uv_mode == DC_PRED |
| 15606 | && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 |
| 15607 | { |
| 15608 | let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); |
| 15609 | let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx); |
| 15610 | palette_uv_pending = Some((n, u_colors, v_colors)); |
| 15611 | } |
| 15612 | } |
| 15613 | // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a |
| 15614 | // `use_filter_intra` symbol this decoder never read at all until |
| 15615 | // lane-av1real r10 -- silently skipping it left every bit past a |
| 15616 | // DC_PRED block at <=32x32 read one symbol short of libaom for the rest |
| 15617 | // of the tile (the pinned CfL stream's actual bug: partition/skip/mode |
| 15618 | // matched bit-exact, then `eob_pt` read 5 instead of 6, because this |
| 15619 | // symbol's bits were never consumed). |
| 15620 | let mut filter_intra = None; |
| 15621 | // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires |
| 15622 | // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO |
| 15623 | // `use_filter_intra` symbol for a Y-palette block, and reading one here |
| 15624 | // desynced every screen-content stream from the first palette block on |
| 15625 | // (it surfaced as a bogus "partition below 8x8" refusal further down the |
| 15626 | // tile). |
| 15627 | if mode == DC_PRED |
| 15628 | && enable_filter_intra |
| 15629 | && palette_y_pending.is_none() |
| 15630 | && let Some(class) = filter_intra_size_class(side) |
| 15631 | { |
| 15632 | let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0; |
| 15633 | if trace { |
| 15634 | eprintln!( |
| 15635 | "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0, |
| 15636 | use_filter_intra as i32 |
| 15637 | ); |
| 15638 | } |
| 15639 | istep!("use_filter_intra", use_filter_intra as i32); |
| 15640 | if use_filter_intra { |
| 15641 | hit!(FILTER_INTRA_HITS); |
| 15642 | let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); |
| 15643 | if trace { |
| 15644 | eprintln!("TRACE filter_intra_mode value={fi_mode}"); |
| 15645 | } |
| 15646 | istep!("filter_intra_mode", fi_mode as i32); |
| 15647 | filter_intra = Some(fi_mode); |
| 15648 | } |
| 15649 | } |
| 15650 | // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma, |
| 15651 | // shared U/V map) -- the same order libaom's own loop visits them in. |
| 15652 | let palette_y = palette_y_pending.map(|(n, colors)| { |
| 15653 | let map = |
| 15654 | decode_color_index_map(dec, cdfs, n, side, palette_onscreen(mi_r, mi_c, side, side, fctx), false); |
| 15655 | hit!(PALETTE_HITS); |
| 15656 | if trace { |
| 15657 | eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]); |
| 15658 | } |
| 15659 | PaletteY { size: n, colors, map } |
| 15660 | }); |
| 15661 | let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { |
| 15662 | let on = palette_onscreen_uv( |
| 15663 | (side, side), |
| 15664 | palette_onscreen(mi_r, mi_c, side, side, fctx), |
| 15665 | (side >> ss_x(fctx), side >> ss_y(fctx)), |
| 15666 | (ss_x(fctx), ss_y(fctx)), |
| 15667 | ); |
| 15668 | let map = decode_color_index_map(dec, cdfs, n, side >> ss_x(fctx), on, true); |
| 15669 | hit!(PALETTE_UV_HITS); |
| 15670 | if trace { |
| 15671 | eprintln!( |
| 15672 | "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}", |
| 15673 | &u_colors[..n], |
| 15674 | &v_colors[..n] |
| 15675 | ); |
| 15676 | } |
| 15677 | PaletteUv { size: n, u_colors, v_colors, map } |
| 15678 | }); |
| 15679 | Ok(( |
| 15680 | skip, |
| 15681 | mode, |
| 15682 | angle_delta_y, |
| 15683 | uv_mode, |
| 15684 | angle_delta_uv, |
| 15685 | alpha, |
| 15686 | filter_intra, |
| 15687 | palette_y, |
| 15688 | palette_uv, |
| 15689 | )) |
| 15690 | } |
| 15691 | |
| 15692 | /// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth |
| 15693 | /// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary |
| 15694 | /// intra modes. |
| 15695 | const UV_CFL_PRED: usize = 13; |
| 15696 | |
| 15697 | /// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec |
| 15698 | /// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol |
| 15699 | /// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context |
| 15700 | /// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the |
| 15701 | /// joint sign the same way. Returns each plane's final signed `alpha_q3` |
| 15702 | /// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0. |
| 15703 | fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) { |
| 15704 | hit!(CFL_BLOCK_HITS); |
| 15705 | let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32; |
| 15706 | let sign_u = ((joint_sign + 1) * 11) >> 5; |
| 15707 | let sign_v = (joint_sign + 1) - 3 * sign_u; |
| 15708 | let alpha_u = if sign_u == 0 { |
| 15709 | 0 |
| 15710 | } else { |
| 15711 | let ctx_u = (joint_sign + 1 - 3) as usize; |
| 15712 | let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1; |
| 15713 | if sign_u == 2 { mag } else { -mag } |
| 15714 | }; |
| 15715 | let alpha_v = if sign_v == 0 { |
| 15716 | 0 |
| 15717 | } else { |
| 15718 | let ctx_v = (sign_v * 3 + sign_u - 3) as usize; |
| 15719 | let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1; |
| 15720 | if sign_v == 2 { mag } else { -mag } |
| 15721 | }; |
| 15722 | (alpha_u, alpha_v) |
| 15723 | } |
| 15724 | |
| 15725 | /// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c): |
| 15726 | /// the reconstructed luma samples under a `side`-square block, subsampled |
| 15727 | /// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average |
| 15728 | /// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`) |
| 15729 | /// to give the AC values [`cfl_scaled`] scales by alpha. |
| 15730 | fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> { |
| 15731 | cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx])) |
| 15732 | } |
| 15733 | |
| 15734 | /// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma |
| 15735 | /// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder |
| 15736 | /// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8` |
| 15737 | /// reconstruction through THIS function rather than a second transcription of |
| 15738 | /// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`. |
| 15739 | /// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4 |
| 15740 | /// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`). |
| 15741 | fn cfl_ac_ss( |
| 15742 | y: &PlaneBuf<'_>, |
| 15743 | px: usize, |
| 15744 | py: usize, |
| 15745 | bw: usize, |
| 15746 | bh: usize, |
| 15747 | ss_x: usize, |
| 15748 | ss_y: usize, |
| 15749 | ) -> Vec<i32> { |
| 15750 | if ss_x == 0 && ss_y == 0 { |
| 15751 | let mut ac = vec![0i32; bw * bh]; |
| 15752 | let mut sum = 0i32; |
| 15753 | for row in 0..bh { |
| 15754 | for col in 0..bw { |
| 15755 | let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3; |
| 15756 | ac[row * bw + col] = q3; |
| 15757 | sum += q3; |
| 15758 | } |
| 15759 | } |
| 15760 | let num_pel = (bw * bh) as i32; |
| 15761 | let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros(); |
| 15762 | ac.iter_mut().for_each(|v| *v -= avg); |
| 15763 | ac |
| 15764 | } else if bw == bh { |
| 15765 | cfl_ac_q3(y, px, py, bw) |
| 15766 | } else { |
| 15767 | cfl_ac_q3_rect(y, px, py, bw, bh) |
| 15768 | } |
| 15769 | } |
| 15770 | |
| 15771 | pub(crate) fn cfl_ac_q3_at( |
| 15772 | px: usize, |
| 15773 | py: usize, |
| 15774 | bw: usize, |
| 15775 | bh: usize, |
| 15776 | sample: impl Fn(usize, usize) -> i32, |
| 15777 | ) -> Vec<i32> { |
| 15778 | let (cw, ch) = (bw / 2, bh / 2); |
| 15779 | let mut ac = vec![0i32; cw * ch]; |
| 15780 | let mut sum = 0i32; |
| 15781 | for cy in 0..ch { |
| 15782 | for cx in 0..cw { |
| 15783 | let (lx, ly) = (px + cx * 2, py + cy * 2); |
| 15784 | let q3 = (sample(lx, ly) |
| 15785 | + sample(lx + 1, ly) |
| 15786 | + sample(lx, ly + 1) |
| 15787 | + sample(lx + 1, ly + 1)) |
| 15788 | << 1; |
| 15789 | ac[cy * cw + cx] = q3; |
| 15790 | sum += q3; |
| 15791 | } |
| 15792 | } |
| 15793 | let num_pel = (cw * ch) as i32; |
| 15794 | let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros(); |
| 15795 | ac.iter_mut().for_each(|v| *v -= avg); |
| 15796 | ac |
| 15797 | } |
| 15798 | |
| 15799 | /// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6 |
| 15800 | /// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest, |
| 15801 | /// ties away from zero on the shifted-out sign). |
| 15802 | pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { |
| 15803 | let v = alpha_q3 * ac_q3; |
| 15804 | if v >= 0 { |
| 15805 | (v + 32) >> 6 |
| 15806 | } else { |
| 15807 | -((-v + 32) >> 6) |
| 15808 | } |
| 15809 | } |
| 15810 | |
| 15811 | /// One plane's reconstruction buffer, `width * height` samples, and the |
| 15812 | /// prediction/residual reads and writes into it — the decode-side twin of |
| 15813 | /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly |
| 15814 | /// (own-edge and reach clamps both), passing what it gathers straight to |
| 15815 | /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone. |
| 15816 | /// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written |
| 15817 | /// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`. |
| 15818 | /// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of |
| 15819 | /// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) -- |
| 15820 | /// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE). |
| 15821 | /// lane-mc64 r1: the decode-order index the stage dumps below key their file |
| 15822 | /// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the |
| 15823 | /// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` -- |
| 15824 | /// without this every frame overwrote `.f0` and a per-frame bisection silently |
| 15825 | /// compared the LAST decoded frame (ledger, class stale-output-faked-measurement). |
| 15826 | #[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live |
| 15827 | fn stage_dump_idx() -> usize { |
| 15828 | PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1) |
| 15829 | } |
| 15830 | |
| 15831 | fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) { |
| 15832 | use std::io::Write; |
| 15833 | // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by |
| 15834 | // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed |
| 15835 | // `.f0` name kept only the LAST frame, so a mid-sequence divergence could |
| 15836 | // not be read out at all. |
| 15837 | if let Ok(path) = crate::envflags::var(var) |
| 15838 | && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var))) |
| 15839 | { |
| 15840 | 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))] { |
| 15841 | for row in 0..h { |
| 15842 | let mut bytes = Vec::with_capacity(w * 2); |
| 15843 | for &s in &p.data[row * p.width..][..w] { |
| 15844 | bytes.extend_from_slice(&s.to_le_bytes()); |
| 15845 | } |
| 15846 | let _ = f.write_all(&bytes); |
| 15847 | } |
| 15848 | } |
| 15849 | } |
| 15850 | } |
| 15851 | |
| 15852 | /// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a |
| 15853 | /// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so |
| 15854 | /// every frame overwrote the previous one and only the LAST frame survived, |
| 15855 | /// which silently defeats any per-frame filter-stage bisection. |
| 15856 | fn dump_stage_idx(var: &str) -> usize { |
| 15857 | use std::collections::HashMap; |
| 15858 | use std::sync::{Mutex, OnceLock}; |
| 15859 | static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new(); |
| 15860 | let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); |
| 15861 | let e = m.entry(var.to_string()).or_insert(0); |
| 15862 | let i = *e; |
| 15863 | *e += 1; |
| 15864 | i |
| 15865 | } |
| 15866 | |
| 15867 | fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { |
| 15868 | use std::io::Write; |
| 15869 | if let Ok(path) = crate::envflags::var(var) |
| 15870 | && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var))) |
| 15871 | { |
| 15872 | for p in [y, u, v] { |
| 15873 | let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect(); |
| 15874 | let _ = f.write_all(&narrow); |
| 15875 | } |
| 15876 | } |
| 15877 | } |
| 15878 | |
| 15879 | /// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no |
| 15880 | /// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`, |
| 15881 | /// at most 4095), so a decode that hashes identically under the flag proves |
| 15882 | /// the output does not depend on the plane buffer's initial content. |
| 15883 | const PLANE_SENTINEL: u16 = 0xDEAD; |
| 15884 | |
| 15885 | /// A frame plane's own backing store, `n` samples, UNINITIALISED. |
| 15886 | /// |
| 15887 | /// (lane-picalloc) The SB-padded coding surface is written sample-for-sample |
| 15888 | /// by the tile walk's reconstruction before anything reads it, so the |
| 15889 | /// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles |
| 15890 | /// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at |
| 15891 | /// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the |
| 15892 | /// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both |
| 15893 | /// ways (see the lane report) and the two agree, which is the proof that no |
| 15894 | /// unwritten sample reaches the output. |
| 15895 | fn fresh_plane(n: usize) -> Vec<u16> { |
| 15896 | if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") { |
| 15897 | return vec![PLANE_SENTINEL; n]; |
| 15898 | } |
| 15899 | let mut v: Vec<u16> = Vec::with_capacity(n); |
| 15900 | // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the |
| 15901 | // capacity was just reserved, so the vector owns `n` initialised-or-not |
| 15902 | // `u16` slots. Every one is written by reconstruction before it is read |
| 15903 | // (proven by the sentinel gate above). |
| 15904 | #[allow(unsafe_code)] |
| 15905 | unsafe { |
| 15906 | v.set_len(n); |
| 15907 | } |
| 15908 | v |
| 15909 | } |
| 15910 | |
| 15911 | #[derive(Clone)] |
| 15912 | struct PlaneBuf<'a> { |
| 15913 | data: std::borrow::Cow<'a, [u16]>, |
| 15914 | width: usize, |
| 15915 | height: usize, |
| 15916 | /// The frame's true, decodable extent in this plane's own units — past |
| 15917 | /// this, samples are the padded coding surface's invented tail, never a |
| 15918 | /// real decoder's edge or reach reads. |
| 15919 | true_width: usize, |
| 15920 | true_height: usize, |
| 15921 | /// This plane's own tile's top-left pixel origin (spec: intra prediction |
| 15922 | /// never reaches across a tile boundary even though an earlier-decoded |
| 15923 | /// tile's real pixels sit right there in the shared buffer) — set via |
| 15924 | /// [`Self::set_tile_origin`] before each tile's own superblock walk, |
| 15925 | /// `0` for the single-tile case. lane-tiles r2: only the left/top bound |
| 15926 | /// is threaded (the two-tile column-split stage 1 fixture's tile always |
| 15927 | /// ends at the frame's own right/bottom edge); a non-last tile's own |
| 15928 | /// right/bottom reach bound is still open, tracked in the report. |
| 15929 | tile_x0: usize, |
| 15930 | tile_y0: usize, |
| 15931 | /// lane-tiles r5: this plane's own tile's right/bottom pixel bound |
| 15932 | /// (exclusive) -- a non-last tile column/row's own reach must stop at |
| 15933 | /// its own SB-aligned tile boundary. `width`/`height` (this plane's |
| 15934 | /// full padded extent) for the single-tile/last-tile case, matching the |
| 15935 | /// old unclipped behaviour exactly. |
| 15936 | tile_x1: usize, |
| 15937 | tile_y1: usize, |
| 15938 | } |
| 15939 | |
| 15940 | /// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/ |
| 15941 | /// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this |
| 15942 | /// frame's own `ref_frame_idx` names a DPB slot that has a picture in it |
| 15943 | /// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already |
| 15944 | /// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/ |
| 15945 | /// `ALTREF2`/`ALTREF`). |
| 15946 | |
| 15947 | impl PlaneBuf<'_> { |
| 15948 | /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/ |
| 15949 | /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0` |
| 15950 | /// are already in this plane's own units (luma pixels for `y`, chroma |
| 15951 | /// pixels — halved — for `u`/`v`). |
| 15952 | fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) { |
| 15953 | self.tile_x0 = x0; |
| 15954 | self.tile_y0 = y0; |
| 15955 | self.tile_x1 = x1; |
| 15956 | self.tile_y1 = y1; |
| 15957 | } |
| 15958 | |
| 15959 | fn edges( |
| 15960 | &self, |
| 15961 | x: usize, |
| 15962 | y: usize, |
| 15963 | side: usize, |
| 15964 | reach: Reach, |
| 15965 | ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) { |
| 15966 | let own_across = x + side.min(self.true_width.saturating_sub(x)); |
| 15967 | let across = if reach.above_right { |
| 15968 | own_across + side.min(self.true_width.saturating_sub(own_across)) |
| 15969 | } else { |
| 15970 | own_across |
| 15971 | } |
| 15972 | .min(self.width) |
| 15973 | .min(self.tile_x1); |
| 15974 | let own_down = y + side.min(self.true_height.saturating_sub(y)); |
| 15975 | let down = if reach.below_left { |
| 15976 | own_down + side.min(self.true_height.saturating_sub(own_down)) |
| 15977 | } else { |
| 15978 | own_down |
| 15979 | } |
| 15980 | .min(self.height) |
| 15981 | .min(self.tile_y1); |
| 15982 | let above = (y > self.tile_y0 && across > x) |
| 15983 | .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec()); |
| 15984 | let left = (x > self.tile_x0 && down > y).then(|| { |
| 15985 | (y..down) |
| 15986 | .map(|row| self.data[row * self.width + x - 1]) |
| 15987 | .collect::<Vec<_>>() |
| 15988 | }); |
| 15989 | let corner = |
| 15990 | (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]); |
| 15991 | (above, left, corner) |
| 15992 | } |
| 15993 | |
| 15994 | /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1): |
| 15995 | /// the above/left reach each extend by their OWN axis (`bw` across, |
| 15996 | /// `bh` down), not one shared `side`. |
| 15997 | fn edges_rect( |
| 15998 | &self, |
| 15999 | x: usize, |
| 16000 | y: usize, |
| 16001 | bw: usize, |
| 16002 | bh: usize, |
| 16003 | reach: Reach, |
| 16004 | ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) { |
| 16005 | let own_across = x + bw.min(self.true_width.saturating_sub(x)); |
| 16006 | let across = if reach.above_right { |
| 16007 | own_across + bw.min(self.true_width.saturating_sub(own_across)) |
| 16008 | } else { |
| 16009 | own_across |
| 16010 | } |
| 16011 | .min(self.width) |
| 16012 | .min(self.tile_x1); |
| 16013 | let own_down = y + bh.min(self.true_height.saturating_sub(y)); |
| 16014 | let down = if reach.below_left { |
| 16015 | own_down + bh.min(self.true_height.saturating_sub(own_down)) |
| 16016 | } else { |
| 16017 | own_down |
| 16018 | } |
| 16019 | .min(self.height) |
| 16020 | .min(self.tile_y1); |
| 16021 | let above = (y > self.tile_y0 && across > x) |
| 16022 | .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec()); |
| 16023 | let left = (x > self.tile_x0 && down > y).then(|| { |
| 16024 | (y..down) |
| 16025 | .map(|row| self.data[row * self.width + x - 1]) |
| 16026 | .collect::<Vec<_>>() |
| 16027 | }); |
| 16028 | let corner = |
| 16029 | (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]); |
| 16030 | if matches!((bw, bh), (16, 8) | (8, 16)) { |
| 16031 | hit!(RECT_STRIP_PRED_HITS); |
| 16032 | if across > own_across || down > own_down { |
| 16033 | hit!(RECT_STRIP_REACH_HITS); |
| 16034 | } |
| 16035 | } |
| 16036 | (above, left, corner) |
| 16037 | } |
| 16038 | |
| 16039 | /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1), |
| 16040 | /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own |
| 16041 | /// already-rect-capable `(bw, bh)` pair. |
| 16042 | #[allow(clippy::too_many_arguments)] |
| 16043 | #[track_caller] |
| 16044 | fn reconstruct_rect( |
| 16045 | &mut self, |
| 16046 | x: usize, |
| 16047 | y: usize, |
| 16048 | bw: usize, |
| 16049 | bh: usize, |
| 16050 | mode: usize, |
| 16051 | angle_delta: i32, |
| 16052 | reach: Reach, |
| 16053 | residual: &[i32], |
| 16054 | cfl: Option<(i32, &[i32])>, |
| 16055 | filter_intra: Option<usize>, |
| 16056 | smooth_neighbor: bool, |
| 16057 | // lane-wave1 step (i): the palette/intrabc prediction override, taken |
| 16058 | // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather |
| 16059 | // than by this replay. |
| 16060 | pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx, |
| 16061 | ) { |
| 16062 | // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override |
| 16063 | // (lane-palette2 r4): a palette block's prediction is the |
| 16064 | // reconstructed colour-index map, needing no edge pixels at all. |
| 16065 | let prediction = if let Some(buf) = pred { |
| 16066 | buf |
| 16067 | } else { |
| 16068 | let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach); |
| 16069 | if crate::envflags::env_flag!("EC_DEBUG_EDGES") { |
| 16070 | eprintln!( |
| 16071 | "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}", |
| 16072 | above.as_ref().map(|a| (a.len(), a[0])), |
| 16073 | left.as_ref().map(|l| l.len()), |
| 16074 | left.as_ref().map(|l| l[0]), |
| 16075 | self.tile_x0, self.tile_y0, self.true_width, self.true_height |
| 16076 | ); |
| 16077 | } |
| 16078 | let mut prediction = vec![0u16; bw * bh]; |
| 16079 | if let Some(fi_mode) = filter_intra { |
| 16080 | crate::intra::predict_filter_intra( |
| 16081 | fi_mode, |
| 16082 | above.as_deref(), |
| 16083 | left.as_deref(), |
| 16084 | corner, |
| 16085 | bw, |
| 16086 | bh, |
| 16087 | &mut prediction, fctx, |
| 16088 | ); |
| 16089 | } else { |
| 16090 | let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get); |
| 16091 | predict( |
| 16092 | mode as u8, |
| 16093 | angle_delta, |
| 16094 | above.as_deref(), |
| 16095 | left.as_deref(), |
| 16096 | corner, |
| 16097 | bw, |
| 16098 | bh, |
| 16099 | enable_edge_filter, |
| 16100 | smooth_neighbor, |
| 16101 | &mut prediction, fctx, |
| 16102 | ); |
| 16103 | } |
| 16104 | prediction |
| 16105 | }; |
| 16106 | // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's |
| 16107 | // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). |
| 16108 | if crate::envflags::env_flag!("EC_PRED") { |
| 16109 | let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); |
| 16110 | let row0: Vec<u16> = prediction[..bw.min(8)].to_vec(); |
| 16111 | let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect(); |
| 16112 | eprintln!( |
| 16113 | "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor) |
| 16114 | ); |
| 16115 | } |
| 16116 | let residual = dense_residual(residual, bw * bh); |
| 16117 | if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) { |
| 16118 | let res0: Vec<i32> = residual[..bw.min(8)].to_vec(); |
| 16119 | let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec(); |
| 16120 | eprintln!("DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"); |
| 16121 | } |
| 16122 | for row in 0..bh { |
| 16123 | // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s |
| 16124 | // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame |
| 16125 | // whose padded width is not superblock aligned hangs past it. |
| 16126 | if y + row >= self.height { |
| 16127 | break; |
| 16128 | } |
| 16129 | for col in 0..bw { |
| 16130 | if x + col >= self.width { |
| 16131 | break; |
| 16132 | } |
| 16133 | let idx = row * bw + col; |
| 16134 | let mut base = i32::from(prediction[idx]); |
| 16135 | if let Some((alpha_q3, ac_q3)) = cfl { |
| 16136 | base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx)); |
| 16137 | } |
| 16138 | let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16; |
| 16139 | self.data.to_mut()[(y + row) * self.width + x + col] = sample; |
| 16140 | } |
| 16141 | } |
| 16142 | // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one |
| 16143 | // -- a block whose prediction matches the oracle's but whose written |
| 16144 | // samples do not is either a residual defect or a later overwrite, and |
| 16145 | // only this print separates the two. |
| 16146 | if crate::envflags::env_flag!("EC_PRED") { |
| 16147 | let row0: Vec<u16> = |
| 16148 | (0..bw.min(8)).map(|c| self.data[y * self.width + x + c]).collect(); |
| 16149 | let col0: Vec<u16> = |
| 16150 | (0..bh.min(8)).map(|r| self.data[(y + r) * self.width + x]).collect(); |
| 16151 | eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}"); |
| 16152 | } |
| 16153 | } |
| 16154 | |
| 16155 | /// Predicts under `mode` then adds `residual` (side*side, raster), |
| 16156 | /// writing the clamped reconstruction back into the plane at `(x, y)`. |
| 16157 | /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block), |
| 16158 | /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the |
| 16159 | /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual |
| 16160 | /// order (cfl.c). |
| 16161 | #[track_caller] |
| 16162 | fn reconstruct( |
| 16163 | &mut self, |
| 16164 | x: usize, |
| 16165 | y: usize, |
| 16166 | side: usize, |
| 16167 | mode: usize, |
| 16168 | angle_delta: i32, |
| 16169 | reach: Reach, |
| 16170 | residual: &[i32], |
| 16171 | cfl: Option<(i32, &[i32])>, |
| 16172 | filter_intra: Option<usize>, |
| 16173 | // `smooth_neighbor` (spec `get_intra_edge_filter_type` / |
| 16174 | // libaom `get_filt_type`): true when the block's above OR left |
| 16175 | // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`). |
| 16176 | // Callers pass their own plane's neighbour-mode check |
| 16177 | // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its |
| 16178 | // callers until a smooth/paeth `uv_mode` can reach this call at all |
| 16179 | // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which |
| 16180 | // keeps `false` exact for chroma without this fn needing to know why. |
| 16181 | smooth_neighbor: bool, |
| 16182 | // lane-wave1 step (i): the palette/intrabc prediction override, taken |
| 16183 | // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather |
| 16184 | // than by this replay. |
| 16185 | pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx, |
| 16186 | ) { |
| 16187 | // A palette block's own [`PALETTE_PRED`] override (lane-palette r2) |
| 16188 | // takes priority over `predict()`/`predict_filter_intra` entirely -- |
| 16189 | // palette prediction needs no edge pixels at all. |
| 16190 | let prediction = if let Some(buf) = pred { |
| 16191 | buf |
| 16192 | } else { |
| 16193 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 16194 | if crate::envflags::env_flag!("EC_DEBUG_EDGES") { |
| 16195 | eprintln!( |
| 16196 | "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}", |
| 16197 | above.as_deref(), |
| 16198 | left.as_deref(), |
| 16199 | ); |
| 16200 | } |
| 16201 | let mut prediction = vec![0u16; side * side]; |
| 16202 | if let Some(fi_mode) = filter_intra { |
| 16203 | crate::intra::predict_filter_intra( |
| 16204 | fi_mode, |
| 16205 | above.as_deref(), |
| 16206 | left.as_deref(), |
| 16207 | corner, |
| 16208 | side, |
| 16209 | side, |
| 16210 | &mut prediction, fctx, |
| 16211 | ); |
| 16212 | } else { |
| 16213 | // `enable_intra_edge_filter` is the sequence header's own flag |
| 16214 | // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs` |
| 16215 | // call, never per-block) -- threading it through every |
| 16216 | // `read_plane`/`decode_block`/`decode_leaf8` call would touch two |
| 16217 | // dozen sites for a value that never changes mid-decode, so it |
| 16218 | // rides a thread-local instead (this decoder is single-threaded |
| 16219 | // per stream). |
| 16220 | let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get); |
| 16221 | predict( |
| 16222 | mode as u8, |
| 16223 | angle_delta, |
| 16224 | above.as_deref(), |
| 16225 | left.as_deref(), |
| 16226 | corner, |
| 16227 | side, |
| 16228 | side, |
| 16229 | enable_edge_filter, |
| 16230 | smooth_neighbor, |
| 16231 | &mut prediction, fctx, |
| 16232 | ); |
| 16233 | } |
| 16234 | prediction |
| 16235 | }; |
| 16236 | // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's |
| 16237 | // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). |
| 16238 | if crate::envflags::env_flag!("EC_PRED") { |
| 16239 | let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); |
| 16240 | let row0: Vec<u16> = prediction[..side.min(8)].to_vec(); |
| 16241 | let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect(); |
| 16242 | eprintln!( |
| 16243 | "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor) |
| 16244 | ); |
| 16245 | } |
| 16246 | let residual = dense_residual(residual, side * side); |
| 16247 | if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) { |
| 16248 | let res0: Vec<i32> = residual[..side.min(8)].to_vec(); |
| 16249 | let pred0: Vec<u16> = prediction[..side.min(8)].to_vec(); |
| 16250 | eprintln!("DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}", cfl.is_some()); |
| 16251 | } |
| 16252 | for row in 0..side { |
| 16253 | // lane-sb128c r8: libaom's frame buffer is superblock |
| 16254 | // aligned; ours is padded to 32 (`block_grid`), so a 64x64 |
| 16255 | // transform unit of a 128x64 block at the BOTTOM frame edge |
| 16256 | // can hang past the last padded row (1920x792: a unit at |
| 16257 | // y=768 wants 832 rows of an 800-row buffer, which panicked |
| 16258 | // the film's key frames). Those samples are outside the |
| 16259 | // frame: never output, and no block below ever references |
| 16260 | // them. |
| 16261 | if y + row >= self.height { |
| 16262 | break; |
| 16263 | } |
| 16264 | for col in 0..side { |
| 16265 | if x + col >= self.width { |
| 16266 | break; |
| 16267 | } |
| 16268 | let idx = row * side + col; |
| 16269 | let mut base = i32::from(prediction[idx]); |
| 16270 | if let Some((alpha_q3, ac_q3)) = cfl { |
| 16271 | base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx)); |
| 16272 | } |
| 16273 | let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16; |
| 16274 | self.data.to_mut()[(y + row) * self.width + x + col] = sample; |
| 16275 | } |
| 16276 | } |
| 16277 | } |
| 16278 | } |
| 16279 | |
| 16280 | /// Reads one plane's transform block, reconstructs it into `plane` at |
| 16281 | /// `(x, y)`/`side`, and records what it leaves behind in `neighbours`. |
| 16282 | #[allow(clippy::too_many_arguments)] |
| 16283 | fn read_plane( |
| 16284 | dec: &mut SymbolDecoder, |
| 16285 | cdfs: &mut Cdfs, |
| 16286 | set: TxbSet, |
| 16287 | scan: &[u16], |
| 16288 | plane_idx: usize, |
| 16289 | around: (bool, bool, i32), |
| 16290 | // The block's own luma mode — [`crate::tile::write_block_planes`] passes |
| 16291 | // it for every plane's `txb` lookup (it is what an intra transform type's |
| 16292 | // CDF is indexed by, spec 9.3), never the plane's own predicted mode. |
| 16293 | tx_mode: usize, |
| 16294 | predict_mode: usize, |
| 16295 | angle_delta: i32, |
| 16296 | reach: Reach, |
| 16297 | // lane-wave1 step (i): unread -- this reader records its write |
| 16298 | // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow |
| 16299 | // stays in the signature so every call site still proves the plane is |
| 16300 | // exclusively held while its coefficients are parsed. |
| 16301 | _plane: &mut PlaneBuf<'static>, |
| 16302 | x: usize, |
| 16303 | y: usize, |
| 16304 | side: usize, |
| 16305 | tx_side: usize, |
| 16306 | base_q_idx: u8, |
| 16307 | cfl: Option<(i32, CflSrc)>, |
| 16308 | filter_intra: Option<usize>, |
| 16309 | // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is |
| 16310 | // smaller than its own block (spec `get_txb_ctx_general`'s |
| 16311 | // `plane_bsize != tx_size` branch), carrying the already-looked-up |
| 16312 | // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any |
| 16313 | // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours |
| 16314 | // formula below. |
| 16315 | luma_skip_ctx: Option<usize>, |
| 16316 | // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check. |
| 16317 | smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, |
| 16318 | ) -> Result<Grid> { |
| 16319 | // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's |
| 16320 | // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) |
| 16321 | // never reaches a chroma plane -- no u/v coefficient symbol is coded and |
| 16322 | // no chroma write is recorded. Return the all-zero grid the caller's |
| 16323 | // neighbour bookkeeping reads, without consuming a bit. |
| 16324 | if plane_idx > 0 && mono(fctx) { |
| 16325 | return Ok(Grid::Zero(side * side)); |
| 16326 | } |
| 16327 | let skip_ctx = if plane_idx == 0 { |
| 16328 | luma_skip_ctx.unwrap_or(0) |
| 16329 | } else { |
| 16330 | // libaom `get_txb_ctx`: a chroma unit's context is |
| 16331 | // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the |
| 16332 | // plane block is bigger than the transform. Our chroma tables hold the |
| 16333 | // offset-7 rows first, so the caller adds 3 for the bigger-block case |
| 16334 | // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3). |
| 16335 | usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0) |
| 16336 | }; |
| 16337 | // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's |
| 16338 | // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`, |
| 16339 | // not by the block's ordinary `mode` (which is always DC_PRED whenever |
| 16340 | // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in |
| 16341 | // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no |
| 16342 | // filter-intra in AV1). |
| 16343 | let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode }; |
| 16344 | let mut coding = cdfs.txb(set, tx_mode); |
| 16345 | // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read |
| 16346 | // transform type for lossless mode(qindex==0)" -- the symbol is not coded |
| 16347 | // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every |
| 16348 | // plane of a lossless block (the residual then goes through the WHT, so |
| 16349 | // the type only picks the scan, which is the default one). |
| 16350 | if lossless(fctx) { |
| 16351 | coding.tx_type = None; |
| 16352 | } |
| 16353 | // Luma's `default_tx_type` is only a fallback for the sizes whose |
| 16354 | // `TxbSet` carries no symbol at all (32-point and up), which the spec |
| 16355 | // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is |
| 16356 | // *never* its own coded symbol (`coding.tx_type` is always `None` for |
| 16357 | // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of |
| 16358 | // the plane's own predicted mode (`default_intra_tx_type`) -- except |
| 16359 | // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr |
| 16360 | // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to |
| 16361 | // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8` |
| 16362 | // and `Chroma16` never hit this — every value `default_intra_tx_type` can |
| 16363 | // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing |
| 16364 | // narrows there — only `Chroma32` and up do). |
| 16365 | let default_tx_type = if plane_idx == 0 || side >= 32 { |
| 16366 | TxType::DctDct |
| 16367 | } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) { |
| 16368 | // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for |
| 16369 | // `av1_get_tx_type`, so chroma inherits luma's coded type (the |
| 16370 | // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY` |
| 16371 | // clamp at `tx_size_sqr_up >= TX_32X32`, matching |
| 16372 | // [`read_inter_plane`]'s own `side < 32` guard). |
| 16373 | inherited |
| 16374 | } else { |
| 16375 | default_intra_tx_type(predict_mode as u8) |
| 16376 | }; |
| 16377 | // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is |
| 16378 | // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one. |
| 16379 | let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type }; |
| 16380 | let (grid, tx_type) = read_coeffs( |
| 16381 | dec, |
| 16382 | &mut coding, |
| 16383 | scan, |
| 16384 | skip_ctx, |
| 16385 | dc_sign_ctx(around.2), |
| 16386 | default_tx_type, |
| 16387 | None, |
| 16388 | )?; |
| 16389 | note_chroma_class1(plane_idx, tx_type); |
| 16390 | if plane_idx == 0 { |
| 16391 | fctx.luma_tx_type.with(|c| c.set(tx_type)); |
| 16392 | } |
| 16393 | // A 64x64 luma block's transform covers the whole 64x64 area, but only its |
| 16394 | // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the |
| 16395 | // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32` |
| 16396 | // guard also assumes. |
| 16397 | // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse` |
| 16398 | // wants the true `side x side` transform, with dqDenom (spec 7.12.3) |
| 16399 | // keyed by that true size, not the coded corner's -- so the corner |
| 16400 | // goes into the top-left of a `side`-sized grid, not the reverse. |
| 16401 | let levels = extend_corner(grid, tx_side, tx_side, side, side); |
| 16402 | let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx); |
| 16403 | let tx = TxParams { |
| 16404 | w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, |
| 16405 | ac_delta, tx_type, qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type), stride: 0, |
| 16406 | lossless: lossless(fctx), |
| 16407 | }; |
| 16408 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 16409 | let residual = tx.run(&levels); |
| 16410 | eprintln!( |
| 16411 | "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels, |
| 16412 | ); |
| 16413 | } |
| 16414 | push_intra_tx( |
| 16415 | plane_idx, |
| 16416 | x, |
| 16417 | y, |
| 16418 | side, |
| 16419 | side, |
| 16420 | false, |
| 16421 | predict_mode, |
| 16422 | angle_delta, |
| 16423 | reach, |
| 16424 | tx, |
| 16425 | &levels, |
| 16426 | cfl, |
| 16427 | filter_intra, |
| 16428 | smooth_neighbor, fctx, |
| 16429 | ); |
| 16430 | // `record`'s neighbour state only reads whether *the coded grid* (not the |
| 16431 | // residual) has nonzero entries, so the levels this function already |
| 16432 | // built are what it wants back -- both arms of the old `tx_side == side` |
| 16433 | // branch returned exactly that, one of them through a full `to_vec` copy |
| 16434 | // of the grid per intra transform unit (lane-coefbuf). |
| 16435 | Ok(levels) |
| 16436 | } |
| 16437 | |
| 16438 | /// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its |
| 16439 | /// three planes, reconstructing them into `y`/`u`/`v` and updating |
| 16440 | /// `neighbours`. |
| 16441 | #[allow(clippy::too_many_arguments)] |
| 16442 | fn decode_block( |
| 16443 | dec: &mut SymbolDecoder, |
| 16444 | cdfs: &mut Cdfs, |
| 16445 | neighbours: &mut Neighbours, |
| 16446 | at: (usize, usize), |
| 16447 | side: usize, |
| 16448 | luma_set: TxbSet, |
| 16449 | chroma_set: TxbSet, |
| 16450 | luma_tx: usize, |
| 16451 | chroma_tx: usize, |
| 16452 | scans: (&[u16], &[u16]), |
| 16453 | cfl: bool, |
| 16454 | y: &mut PlaneBuf<'static>, |
| 16455 | u: &mut PlaneBuf<'static>, |
| 16456 | v: &mut PlaneBuf<'static>, |
| 16457 | base_q_idx: u8, |
| 16458 | enable_filter_intra: bool, |
| 16459 | allow_screen_content_tools: bool, |
| 16460 | allow_intrabc: bool, |
| 16461 | scan32: &[u16], |
| 16462 | scan16: &[u16], |
| 16463 | scan8: &[u16], |
| 16464 | scan4: &[u16], |
| 16465 | tx_select: bool, |
| 16466 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 16467 | ) -> Result<()> { |
| 16468 | let (r, c) = at; |
| 16469 | let (px, py) = (c * SUB, r * SUB); |
| 16470 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); |
| 16471 | let palette_uv_cache = neighbours.palette_uv_cache(at); |
| 16472 | let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); |
| 16473 | let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI); |
| 16474 | let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = |
| 16475 | read_intra_mode( |
| 16476 | dec, |
| 16477 | cdfs, |
| 16478 | nb_above_mode, |
| 16479 | nb_left_mode, |
| 16480 | cfl, |
| 16481 | side, |
| 16482 | enable_filter_intra, |
| 16483 | neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), |
| 16484 | allow_screen_content_tools, |
| 16485 | allow_intrabc, |
| 16486 | Some((palette_ctx, &palette_cache)), |
| 16487 | &palette_uv_cache, |
| 16488 | r * (SUB / MI), |
| 16489 | c * (SUB / MI), fctx, |
| 16490 | )?; |
| 16491 | if at_tile_left && palette_y.is_some() { |
| 16492 | hit!(PALETTE_TILE_LEFT_HITS); |
| 16493 | } |
| 16494 | // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane |
| 16495 | // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size |
| 16496 | // tables/scans are replaced by the 4x4 ones and the block always takes the |
| 16497 | // multi-transform-unit path below. lane-av1mixloss: this rewrite used to |
| 16498 | // sit at the TOP of the function -- before `read_intra_mode`, which is |
| 16499 | // where the block's own `segment_id` is read -- so a mixed frame resolved |
| 16500 | // every block's geometry against the PREVIOUS block's segment (a lossless |
| 16501 | // neighbour forced 4x4 units on a lossy block; a lossy one handed the |
| 16502 | // lossless TxParams an 8x8 grid). libaom's order is the opposite one: |
| 16503 | // `decode_mbmi_block` (segment id included) runs before any tx-size rule. |
| 16504 | // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this |
| 16505 | // rewrite (which sat above `read_intra_mode`) rides along here -- same |
| 16506 | // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own |
| 16507 | // segment like the lossless arm above it. |
| 16508 | let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) { |
| 16509 | (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4)) |
| 16510 | } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 { |
| 16511 | let tx = if side >= 64 { 32 } else { side }; |
| 16512 | let (set, scan): (TxbSet, &[u16]) = match tx { |
| 16513 | 32 => (TxbSet::Chroma32, scan32), |
| 16514 | 16 => (TxbSet::Chroma16, scan16), |
| 16515 | 8 => (TxbSet::Chroma8, scan8), |
| 16516 | _ => (TxbSet::Chroma4, scan4), |
| 16517 | }; |
| 16518 | (luma_set, set, luma_tx, tx, (scans.0, scan)) |
| 16519 | } else { |
| 16520 | (luma_set, chroma_set, luma_tx, chroma_tx, scans) |
| 16521 | }; |
| 16522 | let intrabc_dv = fctx.intrabc_dv.with(|c| c.take()); |
| 16523 | // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED` |
| 16524 | // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the |
| 16525 | // actual chroma-from-luma correlation, same as this decoder always did. |
| 16526 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { |
| 16527 | DC_PRED |
| 16528 | } else { |
| 16529 | uv_mode |
| 16530 | }; |
| 16531 | let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); |
| 16532 | if smooth_neighbor { |
| 16533 | hit!(SMOOTH_LUMA_HITS); |
| 16534 | } |
| 16535 | let smooth_neighbor_uv = |
| 16536 | neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx); |
| 16537 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 16538 | eprintln!( |
| 16539 | "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \ |
| 16540 | angle_delta_uv={angle_delta_uv}" |
| 16541 | ); |
| 16542 | } |
| 16543 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); |
| 16544 | // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra |
| 16545 | // block, skipped or not. `logical_tx` is what the loop filter's edge |
| 16546 | // lookup and the next block's own `get_tx_size_context` want (the *nominal* |
| 16547 | // transform size -- 64 even for the 64x64 corner-scanned case, spec |
| 16548 | // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side, |
| 16549 | // which only differs from it at that one corner case. |
| 16550 | // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth` |
| 16551 | // symbol on `allowSelect = !skip || !is_inter`, and libaom's |
| 16552 | // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED |
| 16553 | // intrabc block reads NO tx-size symbol at all -- it takes |
| 16554 | // `maxRectTxSize` -- while every ordinary skipped intra block does read |
| 16555 | // one. Reading it anyway consumed a symbol libaom never wrote and desynced |
| 16556 | // the tile from that block on (class `equal-range-means-unread`). |
| 16557 | // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition |
| 16558 | // tree instead (`read_var_tx_size`), the same syntax the inter block path |
| 16559 | // has always read -- libaom's `parse_decode_block` dispatches on |
| 16560 | // `is_inter_block`, so both branches of `read_block_tx_size` treat an |
| 16561 | // intrabc block as inter. |
| 16562 | let intrabc_skip_tx = intrabc_dv.is_some() && skip; |
| 16563 | // libaom `parse_decode_block`'s var-tx tree condition carries |
| 16564 | // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc |
| 16565 | // block inside a LOSSLESS segment of a mixed frame reads NO |
| 16566 | // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line |
| 16567 | // hands back TX_4X4. Invisible while every lossless frame was also |
| 16568 | // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which |
| 16569 | // is why the mixed frame is the first stream to reach it. |
| 16570 | let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx); |
| 16571 | let intrabc_leaves = if intrabc_vartx { |
| 16572 | let max_tx = side.min(64); |
| 16573 | // `max_block_wide`/`max_block_high`: the frame's own mi grid |
| 16574 | // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the |
| 16575 | // right/bottom edge reads no split symbol for the units outside it. |
| 16576 | let mi_cols = 2 * y.true_width.div_ceil(8); |
| 16577 | let mi_rows = 2 * y.true_height.div_ceil(8); |
| 16578 | let side_mi = side / MI; |
| 16579 | let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c)); |
| 16580 | let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r)); |
| 16581 | let mut leaves = Vec::new(); |
| 16582 | for row in (0..side_mi).step_by(max_tx / MI) { |
| 16583 | for col in (0..side_mi).step_by(max_tx / MI) { |
| 16584 | read_var_tx_size( |
| 16585 | dec, cdfs, neighbours, (mi_r, mi_c), side, |
| 16586 | (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves, |
| 16587 | ); |
| 16588 | } |
| 16589 | } |
| 16590 | hit!(INTRABC_VARTX_HITS); |
| 16591 | // The luma reconstruct loop below is a UNIFORM grid of one square |
| 16592 | // transform (the intra `tx_depth` shape), so a tree that resolved to |
| 16593 | // mixed leaf sizes is refused by name rather than reconstructed at the |
| 16594 | // wrong stride. |
| 16595 | let uniform = leaves |
| 16596 | .first() |
| 16597 | .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)); |
| 16598 | if !uniform { |
| 16599 | return Err(unsupported( |
| 16600 | "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes", |
| 16601 | )); |
| 16602 | } |
| 16603 | Some(leaves[0].2) |
| 16604 | } else { |
| 16605 | None |
| 16606 | }; |
| 16607 | let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves { |
| 16608 | (tx, if tx == 64 { 32 } else { tx }) |
| 16609 | } else if tx_select && !intrabc_skip_tx { |
| 16610 | let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx); |
| 16611 | (resolved, if resolved == 64 { 32 } else { resolved }) |
| 16612 | } else { |
| 16613 | // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is |
| 16614 | // TX_64X64, so a 128x128 block is always FOUR luma transform units |
| 16615 | // even with `tx_select` off -- the TU loop below, never the |
| 16616 | // single-unit path. |
| 16617 | (lossless_tx(side.min(64), fctx), luma_tx) |
| 16618 | }; |
| 16619 | if tx_select && logical_tx < side && uv_mode != DC_PRED { |
| 16620 | hit!(SQ_CHROMA_TX_HITS); |
| 16621 | } |
| 16622 | let luma_set = if tx_select { |
| 16623 | txbset_for(logical_tx, reduced_tx_set) |
| 16624 | } else { |
| 16625 | luma_set |
| 16626 | }; |
| 16627 | let luma_set = if intrabc_dv.is_some() { |
| 16628 | inter_txbset_for(logical_tx, reduced_tx_set) |
| 16629 | } else { |
| 16630 | luma_set |
| 16631 | }; |
| 16632 | let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4); |
| 16633 | let reach = Reach::of(side, px, py, y.width, y.height, fctx); |
| 16634 | let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); |
| 16635 | let chroma_side = side >> ss_x(fctx); |
| 16636 | // spec 7.11.3.4 with `use_intrabc`: the reference is the *current* |
| 16637 | // frame's own pre-loop-filter reconstruction (all loop filters are off |
| 16638 | // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel |
| 16639 | // block vector, with the BILINEAR kernel libaom forces for intrabc -- |
| 16640 | // luma is a straight copy, chroma lands half-pel whenever the luma DV is |
| 16641 | // odd, which is exactly what the bilinear taps then interpolate. |
| 16642 | flush_recon(fctx, y, u, v); |
| 16643 | let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| { |
| 16644 | let mut yb = vec![0u16; side * side]; |
| 16645 | mc::predict_with_filter( |
| 16646 | &y.data, y.width, y.true_width, y.true_height, |
| 16647 | mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0), |
| 16648 | side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx, |
| 16649 | ); |
| 16650 | let mut ub = vec![0u16; chroma_side * chroma_side]; |
| 16651 | mc::predict_with_filter( |
| 16652 | &u.data, u.width, u.true_width, u.true_height, |
| 16653 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_x(fctx)), |
| 16654 | chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx, |
| 16655 | ); |
| 16656 | let mut vb = vec![0u16; chroma_side * chroma_side]; |
| 16657 | mc::predict_with_filter( |
| 16658 | &v.data, v.width, v.true_width, v.true_height, |
| 16659 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_x(fctx)), |
| 16660 | chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx, |
| 16661 | ); |
| 16662 | (yb, ub, vb) |
| 16663 | }); |
| 16664 | // A palette-Y block's own prediction is the reconstructed colour-index |
| 16665 | // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it |
| 16666 | // to [`PlaneBuf::reconstruct`]'s next call rather than threading a |
| 16667 | // parameter through this function's dozen `y.reconstruct`/`read_plane` |
| 16668 | // sites. A split luma transform (`tx_select && logical_tx != side`) |
| 16669 | // would need the map sliced per-TU -- untested against a real |
| 16670 | // `--enable-palette=1` stream this round, so refuse by name rather than |
| 16671 | // guess at the slicing (charter's own named-acceptable fallback). |
| 16672 | let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| { |
| 16673 | py.map |
| 16674 | .iter() |
| 16675 | .map(|&idx| py.colors[idx as usize]) |
| 16676 | .collect() |
| 16677 | }); |
| 16678 | // lane-t900 r32: the intrabc luma prediction rides the very same |
| 16679 | // whole-block override slot, so the multi-TU loop below windows it per |
| 16680 | // transform unit exactly like a palette map -- setting it once up front |
| 16681 | // handed the whole `side`x`side` buffer to the FIRST unit and left every |
| 16682 | // later one predicting off block edges (the var-tx tree above is what |
| 16683 | // first makes `logical_tx < side` reachable for an intrabc block). |
| 16684 | let palette_y_buf = match &intrabc_bufs { |
| 16685 | Some((yb, _, _)) => Some(yb.clone()), |
| 16686 | None => palette_y_buf, |
| 16687 | }; |
| 16688 | // With one luma transform unit the whole `side`x`side` map is the |
| 16689 | // prediction; with several (`logical_tx != side`) each unit takes its own |
| 16690 | // `logical_tx`-sized window of that same map, set fresh inside the TU loop |
| 16691 | // below (lane-palette2 r7) -- setting the full-block buffer here would be |
| 16692 | // taken by the FIRST unit and indexed at the wrong stride. |
| 16693 | // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call |
| 16694 | // (the `else` arm below -- a palette/intrabc block never takes the per-unit |
| 16695 | // `split_tx_skip` walk), so its map must be armed here even when the |
| 16696 | // transform is split. Gating the arm on `logical_tx == side` alone left a |
| 16697 | // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC |
| 16698 | // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen |
| 16699 | // key frame; class override-slot-on-one-arm). Neither prediction is |
| 16700 | // edge-derived, so the whole-block buffer at the block's own stride is |
| 16701 | // exactly what that single call wants. |
| 16702 | // Counted on the SHAPE, not on the arm below, so a gate can tell a stream |
| 16703 | // that reaches this block apart from one that never does (class |
| 16704 | // gate-blind-to-feature). |
| 16705 | if palette_y_buf.is_some() && skip && logical_tx < side { |
| 16706 | hit!(SKIP_SPLIT_TX_OVERRIDE_HITS); |
| 16707 | } |
| 16708 | if let Some(buf) = &palette_y_buf |
| 16709 | && (logical_tx == side || skip) |
| 16710 | { |
| 16711 | set_palette_pred(buf.clone(), fctx); |
| 16712 | } |
| 16713 | // A UV-palette block's own chroma prediction override (lane-palette2 r1), |
| 16714 | // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each |
| 16715 | // plane's own `reconstruct`/`read_plane` call below (never both planes at |
| 16716 | // once), since Y's own set-then-take already emptied the slot by the time |
| 16717 | // either of these run. |
| 16718 | let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| { |
| 16719 | ( |
| 16720 | puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(), |
| 16721 | puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), |
| 16722 | ) |
| 16723 | }); |
| 16724 | // The chroma half of the intrabc prediction rides the same per-plane |
| 16725 | // override slot the UV-palette buffers do (set fresh before each plane's |
| 16726 | // own `reconstruct`/`read_plane` call below). |
| 16727 | let palette_uv_bufs = match &intrabc_bufs { |
| 16728 | Some((_, ub, vb)) => Some((ub.clone(), vb.clone())), |
| 16729 | None => palette_uv_bufs, |
| 16730 | }; |
| 16731 | if skip { |
| 16732 | // A skipped block codes no residual syntax at all (spec 5.11.34): |
| 16733 | // straight prediction, on every plane. |
| 16734 | // |
| 16735 | // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it |
| 16736 | // is skipped (only an INTER skip forces the largest transform), and |
| 16737 | // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts |
| 16738 | // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units |
| 16739 | // already written left/above of it inside this same block. Predicting |
| 16740 | // the whole `side`x`side` at once gives a different (uniformly off by |
| 16741 | // ~1) answer, which is exactly the residue this lane was chasing. |
| 16742 | // The palette/intrabc override path keeps the single-call shape (its |
| 16743 | // per-TU windowing is the non-skip loop's own `palette_y_buf` slice, |
| 16744 | // untested for skip and unreachable in these streams). |
| 16745 | // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with |
| 16746 | // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the |
| 16747 | // per-unit prediction is keyed on the transform being smaller than |
| 16748 | // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's |
| 16749 | // narrower meaning (a READ split tx depth). |
| 16750 | let split_tx_skip = |
| 16751 | logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none(); |
| 16752 | if split_tx_skip { |
| 16753 | if tx_select { |
| 16754 | hit!(SKIP_SPLIT_TX_HITS); |
| 16755 | } |
| 16756 | let n_axis = side / logical_tx; |
| 16757 | for tu_row in 0..n_axis { |
| 16758 | for tu_col in 0..n_axis { |
| 16759 | let tu_px = px + tu_col * logical_tx; |
| 16760 | let tu_py = py + tu_row * logical_tx; |
| 16761 | if tu_px >= y.true_width || tu_py >= y.true_height { |
| 16762 | continue; |
| 16763 | } |
| 16764 | let tu_reach = tu_reach( |
| 16765 | side, |
| 16766 | side, |
| 16767 | tu_col * logical_tx, |
| 16768 | tu_row * logical_tx, |
| 16769 | logical_tx, |
| 16770 | reach, |
| 16771 | px, |
| 16772 | py, |
| 16773 | y.width, |
| 16774 | y.height, fctx, |
| 16775 | ); |
| 16776 | push_intra(0, |
| 16777 | tu_px, |
| 16778 | tu_py, |
| 16779 | logical_tx, |
| 16780 | mode, |
| 16781 | angle_delta_y, |
| 16782 | tu_reach, |
| 16783 | &ZERO_RESIDUAL[..logical_tx * logical_tx], |
| 16784 | None, |
| 16785 | filter_intra, |
| 16786 | smooth_neighbor, fctx, |
| 16787 | ); |
| 16788 | } |
| 16789 | } |
| 16790 | } else { |
| 16791 | push_intra(0, |
| 16792 | px, |
| 16793 | py, |
| 16794 | side, |
| 16795 | mode, |
| 16796 | angle_delta_y, |
| 16797 | reach, |
| 16798 | &ZERO_RESIDUAL[..side * side], |
| 16799 | None, |
| 16800 | filter_intra, |
| 16801 | smooth_neighbor, fctx, |
| 16802 | ); |
| 16803 | } |
| 16804 | let ac = alpha.map(|_| cfl_src(px, py, side)); |
| 16805 | let cn = (chroma_side / chroma_tx).max(1); |
| 16806 | for cu_row in 0..cn { |
| 16807 | for cu_col in 0..cn { |
| 16808 | let luma_span = chroma_tx << ss_x(fctx); |
| 16809 | let cu_r = if cn == 1 { |
| 16810 | reach |
| 16811 | } else { |
| 16812 | tu_reach( |
| 16813 | side, side, |
| 16814 | cu_col * luma_span, cu_row * luma_span, luma_span, |
| 16815 | reach, px, py, y.width, y.height, fctx, |
| 16816 | ) |
| 16817 | }; |
| 16818 | let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx); |
| 16819 | if let Some((ub, _)) = &palette_uv_bufs { |
| 16820 | set_palette_pred(ub.clone(), fctx); |
| 16821 | } |
| 16822 | push_intra(1, |
| 16823 | cu_x, |
| 16824 | cu_y, |
| 16825 | chroma_tx, |
| 16826 | uv_predict_mode, |
| 16827 | angle_delta_uv, |
| 16828 | cu_r, |
| 16829 | &ZERO_RESIDUAL[..chroma_tx * chroma_tx], |
| 16830 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 16831 | None, |
| 16832 | smooth_neighbor_uv, fctx, |
| 16833 | ); |
| 16834 | if let Some((_, vb)) = &palette_uv_bufs { |
| 16835 | set_palette_pred(vb.clone(), fctx); |
| 16836 | } |
| 16837 | push_intra(2, |
| 16838 | cu_x, |
| 16839 | cu_y, |
| 16840 | chroma_tx, |
| 16841 | uv_predict_mode, |
| 16842 | angle_delta_uv, |
| 16843 | cu_r, |
| 16844 | &ZERO_RESIDUAL[..chroma_tx * chroma_tx], |
| 16845 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 16846 | None, |
| 16847 | smooth_neighbor_uv, fctx, |
| 16848 | ); |
| 16849 | } |
| 16850 | } |
| 16851 | let luma_grid = vec![0i32; side * side]; |
| 16852 | let u_grid = vec![0i32; chroma_side * chroma_side]; |
| 16853 | let v_grid = vec![0i32; chroma_side * chroma_side]; |
| 16854 | neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); |
| 16855 | } else if logical_tx == side { |
| 16856 | // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`. |
| 16857 | // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so |
| 16858 | // that arm was redundant -- and wrong at 128, where |
| 16859 | // `max_txsize_rect_lookup` caps the block's transform at 64 and the |
| 16860 | // block is four units whether or not `tx_select` is on. |
| 16861 | // A single luma transform unit -- the old path, unchanged (including |
| 16862 | // the 64x64 corner case, `logical_tx == side == 64` with |
| 16863 | // `coeff_tx_side == 32`). |
| 16864 | let around = neighbours.around(at, side); |
| 16865 | let luma_grid = read_plane( |
| 16866 | dec, |
| 16867 | cdfs, |
| 16868 | luma_set, |
| 16869 | luma_scan, |
| 16870 | 0, |
| 16871 | around[0], |
| 16872 | mode, |
| 16873 | mode, |
| 16874 | angle_delta_y, |
| 16875 | reach, |
| 16876 | y, |
| 16877 | px, |
| 16878 | py, |
| 16879 | side, |
| 16880 | coeff_tx_side, |
| 16881 | base_q_idx, |
| 16882 | None, |
| 16883 | filter_intra, |
| 16884 | None, |
| 16885 | smooth_neighbor, fctx, |
| 16886 | )?; |
| 16887 | let ac = alpha.map(|_| cfl_src(px, py, side)); |
| 16888 | // Armed for exactly this block's two chroma reads (see |
| 16889 | // [`INTRABC_CHROMA_TX`]); the luma call above just set |
| 16890 | // [`LUMA_TX_TYPE`] to the type it coded. |
| 16891 | if intrabc_dv.is_some() { |
| 16892 | fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get)))); |
| 16893 | } |
| 16894 | // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including |
| 16895 | // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane |
| 16896 | // is the same size as luma and `av1_get_max_uv_txsize` caps it at |
| 16897 | // TX_32X32, so a 64x64 block codes four chroma units, plane-major |
| 16898 | // (every U, then every V) — the same loop the multi-TU arm runs. |
| 16899 | // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read. |
| 16900 | let cn = (chroma_side / chroma_tx).max(1); |
| 16901 | let (u_grid, v_grid, chroma_units) = if cn == 1 { |
| 16902 | if let Some((ub, _)) = &palette_uv_bufs { |
| 16903 | set_palette_pred(ub.clone(), fctx); |
| 16904 | } |
| 16905 | let u_grid = read_plane( |
| 16906 | dec, |
| 16907 | cdfs, |
| 16908 | chroma_set, |
| 16909 | scans.1, |
| 16910 | 1, |
| 16911 | around[1], |
| 16912 | mode, |
| 16913 | uv_predict_mode, |
| 16914 | angle_delta_uv, |
| 16915 | reach, |
| 16916 | u, |
| 16917 | cpx, |
| 16918 | cpy, |
| 16919 | chroma_side, |
| 16920 | chroma_tx, |
| 16921 | base_q_idx, |
| 16922 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 16923 | None, |
| 16924 | None, |
| 16925 | smooth_neighbor_uv, fctx, |
| 16926 | )?; |
| 16927 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 16928 | eprintln!( |
| 16929 | "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}", |
| 16930 | &u.data[cpy * u.width + cpx..][..chroma_side] |
| 16931 | ); |
| 16932 | } |
| 16933 | if let Some((_, vb)) = &palette_uv_bufs { |
| 16934 | set_palette_pred(vb.clone(), fctx); |
| 16935 | } |
| 16936 | let v_grid = read_plane( |
| 16937 | dec, |
| 16938 | cdfs, |
| 16939 | chroma_set, |
| 16940 | scans.1, |
| 16941 | 2, |
| 16942 | around[2], |
| 16943 | mode, |
| 16944 | uv_predict_mode, |
| 16945 | angle_delta_uv, |
| 16946 | reach, |
| 16947 | v, |
| 16948 | cpx, |
| 16949 | cpy, |
| 16950 | chroma_side, |
| 16951 | chroma_tx, |
| 16952 | base_q_idx, |
| 16953 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 16954 | None, |
| 16955 | None, |
| 16956 | smooth_neighbor_uv, fctx, |
| 16957 | )?; |
| 16958 | (u_grid, v_grid, Vec::new()) |
| 16959 | } else { |
| 16960 | let chroma_ctx_offset = Some(3); |
| 16961 | let mut u_pass: Vec<Grid> = Vec::new(); |
| 16962 | let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new(); |
| 16963 | let mut last_grids = [Grid::Zero(0), Grid::Zero(0)]; |
| 16964 | for plane_pass in 1..=2usize { |
| 16965 | let mut pass_idx = 0usize; |
| 16966 | for cu_row in 0..cn { |
| 16967 | for cu_col in 0..cn { |
| 16968 | let luma_span = chroma_tx << ss_x(fctx); |
| 16969 | let cu_mi = ( |
| 16970 | mi_r + cu_row * (luma_span / MI), |
| 16971 | mi_c + cu_col * (luma_span / MI), |
| 16972 | ); |
| 16973 | let cu_around = neighbours.around_mi(cu_mi, luma_span); |
| 16974 | let cu_reach = tu_reach( |
| 16975 | side, |
| 16976 | side, |
| 16977 | cu_col * luma_span, |
| 16978 | cu_row * luma_span, |
| 16979 | luma_span, |
| 16980 | reach, |
| 16981 | px, |
| 16982 | py, |
| 16983 | y.width, |
| 16984 | y.height, fctx, |
| 16985 | ); |
| 16986 | let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx); |
| 16987 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 16988 | let pbuf = if plane_pass == 1 { ub } else { vb }; |
| 16989 | set_palette_pred( |
| 16990 | palette_window( |
| 16991 | pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx, |
| 16992 | chroma_tx, chroma_tx, |
| 16993 | ), |
| 16994 | fctx, |
| 16995 | ); |
| 16996 | } |
| 16997 | let buf: &mut PlaneBuf<'static> = |
| 16998 | if plane_pass == 1 { &mut *u } else { &mut *v }; |
| 16999 | let cu_grid = read_plane( |
| 17000 | dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode, |
| 17001 | uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y, |
| 17002 | chroma_tx, chroma_tx, base_q_idx, |
| 17003 | alpha.zip(ac).map(|((au, av), ac)| { |
| 17004 | (if plane_pass == 1 { au } else { av }, ac) |
| 17005 | }), |
| 17006 | None, chroma_ctx_offset, smooth_neighbor_uv, fctx, |
| 17007 | )?; |
| 17008 | hit!(CHROMA_SPLIT_TX_HITS); |
| 17009 | // Immediately, so the next unit of this block reads this |
| 17010 | // one's coefficient context. `record` below stamps one |
| 17011 | // chroma state across the whole block; the replay after |
| 17012 | // it puts the per-unit state back. |
| 17013 | neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid); |
| 17014 | if plane_pass == 1 { |
| 17015 | u_pass.push(cu_grid); |
| 17016 | } else { |
| 17017 | let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0)); |
| 17018 | units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone())); |
| 17019 | last_grids = [u_grid, cu_grid]; |
| 17020 | } |
| 17021 | pass_idx += 1; |
| 17022 | } |
| 17023 | } |
| 17024 | } |
| 17025 | (last_grids[0].clone(), last_grids[1].clone(), units) |
| 17026 | }; |
| 17027 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 17028 | neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); |
| 17029 | for (cu_mi, luma_span, u_unit, v_unit) in &chroma_units { |
| 17030 | neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_unit); |
| 17031 | neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_unit); |
| 17032 | } |
| 17033 | } else { |
| 17034 | // Several luma transform units, raster order (spec |
| 17035 | // `transform_block`'s loop): the block's resolved transform is |
| 17036 | // genuinely smaller than its own side, so each tile of it predicts |
| 17037 | // and codes independently, its own context read fresh off whatever |
| 17038 | // the earlier tiles in this same block already wrote -- the same |
| 17039 | // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf. |
| 17040 | let n_axis = side / logical_tx; |
| 17041 | let cn = (chroma_side / chroma_tx).max(1); |
| 17042 | // libaom's transform-block loop is over 64x64 luma "mu" chunks |
| 17043 | // (`decode_token_recon_block`: `mu_blocks_wide/high` = |
| 17044 | // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk |
| 17045 | // before moving to the next one. Below 128 a block is a single chunk, |
| 17046 | // so this is byte-for-byte the all-luma-then-all-chroma order that has |
| 17047 | // always run; at 128 the four quadrants interleave Y,U,V per quadrant |
| 17048 | // and reading all four luma units first desyncs the tile at the second |
| 17049 | // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`). |
| 17050 | let nchunk = (side / 64).max(1); |
| 17051 | // `cn > 1` means the uv plane block is larger than the uv transform, |
| 17052 | // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10. |
| 17053 | let chroma_ctx_offset = if cn > 1 { Some(3) } else { None }; |
| 17054 | let tpc = (n_axis / nchunk).max(1); |
| 17055 | let cpc = (cn / nchunk).max(1); |
| 17056 | let mut last_grids = [Grid::Zero(0), Grid::Zero(0)]; |
| 17057 | let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new(); |
| 17058 | for ch_row in 0..nchunk { |
| 17059 | for ch_col in 0..nchunk { |
| 17060 | for tu_row in ch_row * tpc..(ch_row + 1) * tpc { |
| 17061 | for tu_col in ch_col * tpc..(ch_col + 1) * tpc { |
| 17062 | let tu_mi = ( |
| 17063 | mi_r + tu_row * (logical_tx / MI), |
| 17064 | mi_c + tu_col * (logical_tx / MI), |
| 17065 | ); |
| 17066 | let tu_px = px + tu_col * logical_tx; |
| 17067 | let tu_py = py + tu_row * logical_tx; |
| 17068 | // Same libaom clip as `decode_rect_split`'s loop above; a |
| 17069 | // square block only hangs off the frame when the frame's mi |
| 17070 | // dimensions are odd at the block's own level. |
| 17071 | if tu_px >= y.true_width || tu_py >= y.true_height { |
| 17072 | continue; |
| 17073 | } |
| 17074 | let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0]; |
| 17075 | // A transform unit inside a block is NOT a block at that |
| 17076 | // position (lane-palette2 r12): `Reach::of` granted the |
| 17077 | // top-right 8x8 unit of a 16x16 D203 block bottom-left |
| 17078 | // pixels libaom refuses outright (`col_off > 0`), which is |
| 17079 | // the diagonal wedge seed 46 reconstructed wrong. |
| 17080 | let tu_reach = tu_reach( |
| 17081 | side, |
| 17082 | side, |
| 17083 | tu_col * logical_tx, |
| 17084 | tu_row * logical_tx, |
| 17085 | logical_tx, |
| 17086 | reach, |
| 17087 | px, |
| 17088 | py, |
| 17089 | y.width, |
| 17090 | y.height, fctx, |
| 17091 | ); |
| 17092 | // This transform unit's own bsize (`logical_tx`) is smaller |
| 17093 | // than the block it sits in (`side`), so `txb_skip_ctx` is |
| 17094 | // the neighbour-magnitude table, not the lone-TU 0 (spec |
| 17095 | // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch). |
| 17096 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI); |
| 17097 | if let Some(buf) = &palette_y_buf { |
| 17098 | hit!(PALETTE_SPLIT_TX_HITS); |
| 17099 | let mut window = vec![0u16; logical_tx * logical_tx]; |
| 17100 | for row in 0..logical_tx { |
| 17101 | let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx; |
| 17102 | window[row * logical_tx..][..logical_tx] |
| 17103 | .copy_from_slice(&buf[src..][..logical_tx]); |
| 17104 | } |
| 17105 | set_palette_pred(window, fctx); |
| 17106 | } |
| 17107 | let tu_grid = read_plane( |
| 17108 | dec, |
| 17109 | cdfs, |
| 17110 | luma_set, |
| 17111 | luma_scan, |
| 17112 | 0, |
| 17113 | tu_around, |
| 17114 | mode, |
| 17115 | mode, |
| 17116 | angle_delta_y, |
| 17117 | tu_reach, |
| 17118 | y, |
| 17119 | tu_px, |
| 17120 | tu_py, |
| 17121 | logical_tx, |
| 17122 | // The unit's own COEFFICIENT grid, half its side at |
| 17123 | // TX_64X64 (a 64-point transform codes nothing past 32); |
| 17124 | // identical to `logical_tx` at every smaller size |
| 17125 | // (lane-sb128b r1). |
| 17126 | coeff_tx_side, |
| 17127 | base_q_idx, |
| 17128 | None, |
| 17129 | filter_intra, |
| 17130 | Some(tu_skip_ctx), |
| 17131 | smooth_neighbor, fctx, |
| 17132 | )?; |
| 17133 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 17134 | eprintln!( |
| 17135 | "TRACE tu_bitpos mi=({},{}) tell={}", |
| 17136 | tu_mi.0, |
| 17137 | tu_mi.1, |
| 17138 | dec.debug_bitpos() |
| 17139 | ); |
| 17140 | } |
| 17141 | neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid); |
| 17142 | } |
| 17143 | } |
| 17144 | // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where |
| 17145 | // this still runs after every luma unit of the block. |
| 17146 | let ac = alpha.map(|_| cfl_src(px, py, side)); |
| 17147 | // The block's uv plane block is `chroma_side` across but its uv |
| 17148 | // transform is `chroma_tx` (`av1_get_max_uv_txsize` = |
| 17149 | // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`): |
| 17150 | // identical at every size up to 64x64, but a 128x128 block's 64x64 uv |
| 17151 | // plane block adjusts TX_64X64 down to TX_32X32, so each plane is |
| 17152 | // FOUR units (lane-sb128b r2) -- one per mu chunk. |
| 17153 | // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR |
| 17154 | // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of |
| 17155 | // the chunk, then every V unit. At one unit per plane per chunk -- |
| 17156 | // every non-lossless case this decoder reaches -- that is the same |
| 17157 | // symbol order as the interleaved pair this loop used to read; a |
| 17158 | // lossless frame's 4x4 chroma units are the case where it differs |
| 17159 | // (lane-lossless2). |
| 17160 | let mut u_pass: Vec<Grid> = Vec::new(); |
| 17161 | for plane_pass in 1..=2usize { |
| 17162 | let mut pass_idx = 0usize; |
| 17163 | for cu_row in ch_row * cpc..(ch_row + 1) * cpc { |
| 17164 | for cu_col in ch_col * cpc..(ch_col + 1) * cpc { |
| 17165 | // libaom `decode_reconstruct_tx`'s frame-edge clip |
| 17166 | // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col |
| 17167 | // >= max_blocks_wide` returns before ANY symbol is read): a |
| 17168 | // transform unit whose 4x4 origin sits outside the frame's mi |
| 17169 | // grid is not coded at all. The luma loop above carries the |
| 17170 | // same clip; its absence here read `txb_skip` (+coeffs) for |
| 17171 | // chroma units libaom never wrote -- the lossless 64x64 block |
| 17172 | // at mi(48,0) of a 320x240 frame overhangs the bottom edge by |
| 17173 | // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not |
| 17174 | // eight (lane-av1-loss64; 48 chroma units per plane in |
| 17175 | // aomdec's EC_COEFF census vs the 64 this loop read). |
| 17176 | // `max_block_wide/high` (av1_common_int.h:1565): the plane |
| 17177 | // block's pixel span (4:2:0 halves the luma span, clamped to |
| 17178 | // 4 by `set_plane_n4`) plus the negative overhang |
| 17179 | // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4 |
| 17180 | // units. |
| 17181 | let span_mi = side / MI; |
| 17182 | let over_w_mi = |
| 17183 | (2 * y.true_width.div_ceil(8)) as i32 - mi_c as i32 - span_mi as i32; |
| 17184 | let over_h_mi = |
| 17185 | (2 * y.true_height.div_ceil(8)) as i32 - mi_r as i32 - span_mi as i32; |
| 17186 | let plane_px = ((span_mi * 2).max(4)) as i32; |
| 17187 | let max_units_w = ((plane_px + 2 * over_w_mi.min(0)) >> 2).max(0) as usize; |
| 17188 | let max_units_h = ((plane_px + 2 * over_h_mi.min(0)) >> 2).max(0) as usize; |
| 17189 | let unit = chroma_tx / 4; // TU side in 4x4 chroma units |
| 17190 | if cu_col * unit >= max_units_w || cu_row * unit >= max_units_h { |
| 17191 | hit!(CHROMA_EDGE_TU_CLIP_HITS); |
| 17192 | continue; |
| 17193 | } |
| 17194 | // The chroma context arrays are indexed in LUMA mi, so this |
| 17195 | // unit's anchor is its own luma quadrant: `chroma_tx` chroma |
| 17196 | // pixels span `2 * chroma_tx` luma ones. |
| 17197 | let luma_span = chroma_tx << ss_x(fctx); |
| 17198 | let cu_mi = ( |
| 17199 | mi_r + cu_row * (luma_span / MI), |
| 17200 | mi_c + cu_col * (luma_span / MI), |
| 17201 | ); |
| 17202 | let cu_around = neighbours.around_mi(cu_mi, luma_span); |
| 17203 | let cu_reach = if cn == 1 { |
| 17204 | reach |
| 17205 | } else { |
| 17206 | tu_reach( |
| 17207 | side, side, |
| 17208 | cu_col * luma_span, cu_row * luma_span, luma_span, |
| 17209 | reach, px, py, y.width, y.height, fctx, |
| 17210 | ) |
| 17211 | }; |
| 17212 | let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx); |
| 17213 | if let Some((ub, vb)) = &palette_uv_bufs { |
| 17214 | let pbuf = if plane_pass == 1 { ub } else { vb }; |
| 17215 | set_palette_pred( |
| 17216 | palette_window( |
| 17217 | pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx, |
| 17218 | chroma_tx, chroma_tx, |
| 17219 | ), |
| 17220 | fctx, |
| 17221 | ); |
| 17222 | } |
| 17223 | let buf: &mut PlaneBuf<'static> = |
| 17224 | if plane_pass == 1 { &mut *u } else { &mut *v }; |
| 17225 | let cu_grid = read_plane( |
| 17226 | dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode, |
| 17227 | uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y, |
| 17228 | chroma_tx, chroma_tx, base_q_idx, |
| 17229 | alpha.zip(ac).map(|((au, av), ac)| { |
| 17230 | (if plane_pass == 1 { au } else { av }, ac) |
| 17231 | }), |
| 17232 | None, chroma_ctx_offset, smooth_neighbor_uv, fctx, |
| 17233 | )?; |
| 17234 | if cn > 1 { |
| 17235 | hit!(CHROMA_SPLIT_TX_HITS); |
| 17236 | // Immediately, so the NEXT unit of this same block reads |
| 17237 | // this one's coefficient context (libaom's chroma |
| 17238 | // `txb_skip_ctx` for the second quadrant is 11, i.e. base |
| 17239 | // 1 from this left neighbour -- measured against aomdec). |
| 17240 | // The same writes are replayed after `record_split_luma` |
| 17241 | // below, which would otherwise clobber them whole-block. |
| 17242 | neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid); |
| 17243 | } |
| 17244 | if plane_pass == 1 { |
| 17245 | u_pass.push(cu_grid); |
| 17246 | } else { |
| 17247 | let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0)); |
| 17248 | if cn > 1 { |
| 17249 | units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone())); |
| 17250 | } |
| 17251 | last_grids = [u_grid, cu_grid]; |
| 17252 | } |
| 17253 | pass_idx += 1; |
| 17254 | } |
| 17255 | } |
| 17256 | } |
| 17257 | } |
| 17258 | } |
| 17259 | // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma |
| 17260 | // context write; at `cn > 1` the per-unit writes above are what the |
| 17261 | // next block reads, so they run after this (last writer wins). |
| 17262 | neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]); |
| 17263 | for (cu_mi, luma_span, u_grid, v_grid) in &units { |
| 17264 | neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid); |
| 17265 | neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid); |
| 17266 | } |
| 17267 | } |
| 17268 | // Unconditional, `size == 0` for a non-palette block: clears any stale |
| 17269 | // neighbour palette state the same way [`Neighbours::record`] always |
| 17270 | // overwrites `above_mode`/`left_mode` regardless of this block's own mode |
| 17271 | // (the split-luma-TU branch above always refuses before reaching here |
| 17272 | // when `palette_y` is `Some`, so it is never live for that branch). |
| 17273 | let (py_size, py_colors) = palette_y |
| 17274 | .as_ref() |
| 17275 | .map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 17276 | neighbours.record_palette_y(at, side, py_size, py_colors); |
| 17277 | let (puv_size, puv_colors) = palette_uv |
| 17278 | .as_ref() |
| 17279 | .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 17280 | neighbours.record_palette_uv(at, side, puv_size, puv_colors); |
| 17281 | neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip); |
| 17282 | neighbours.fill_lf_grid( |
| 17283 | (r * (SUB / MI), c * (SUB / MI)), |
| 17284 | side / MI, |
| 17285 | logical_tx as u8, |
| 17286 | 0, fctx, |
| 17287 | ); |
| 17288 | // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size, |
| 17289 | // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY |
| 17290 | // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM |
| 17291 | // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express |
| 17292 | // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED |
| 17293 | // intrabc block publish its BLOCK size instead, intrabc being the only |
| 17294 | // "inter" block an intra-only frame codes (`blockd.h:373`). So this call |
| 17295 | // stays the authority wherever one can appear; with `allow_intrabc` unset |
| 17296 | // it writes exactly what the grid already did. |
| 17297 | if allow_intrabc { |
| 17298 | set_txfm_ctxs( |
| 17299 | neighbours, |
| 17300 | (mi_r, mi_c), |
| 17301 | logical_tx, |
| 17302 | side / MI, |
| 17303 | side / MI, |
| 17304 | skip && intrabc_dv.is_some(), |
| 17305 | ); |
| 17306 | } |
| 17307 | record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx); |
| 17308 | Ok(()) |
| 17309 | } |
| 17310 | |
| 17311 | thread_local! { |
| 17312 | /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128 |
| 17313 | /// root's HORZ arm, and 64x128 ones at its VERT arm. |
| 17314 | pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 17315 | pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 17316 | /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units, |
| 17317 | /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read. |
| 17318 | pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; |
| 17319 | /// lane-inter128intra r1: the same shapes decoded on the INTER block path |
| 17320 | /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an |
| 17321 | /// inter frame) -- (128x64, 64x128). |
| 17322 | pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; |
| 17323 | /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still |
| 17324 | /// handed back var-tx leaves, so the per-transform-unit luma publication |
| 17325 | /// loop never ran and the block has to clear its own luma coefficient |
| 17326 | /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under |
| 17327 | /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate |
| 17328 | /// non-vacuous. |
| 17329 | pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 17330 | /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded |
| 17331 | /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the |
| 17332 | /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this |
| 17333 | /// shape non-vacuous -- a stream that never codes one reads 0. |
| 17334 | pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; |
| 17335 | } |
| 17336 | |
| 17337 | /// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta. |
| 17338 | pub fn skip_vartx_luma_reset_hits() -> usize { |
| 17339 | SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get) |
| 17340 | } |
| 17341 | |
| 17342 | /// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta. |
| 17343 | pub(crate) fn intra128_lossless_hits() -> usize { |
| 17344 | INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get) |
| 17345 | } |
| 17346 | |
| 17347 | /// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta. |
| 17348 | pub(crate) fn intra128_in_inter_hits() -> [usize; 2] { |
| 17349 | INTRA128_IN_INTER_HITS.with(std::cell::Cell::get) |
| 17350 | } |
| 17351 | |
| 17352 | /// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] / |
| 17353 | /// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta. |
| 17354 | pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) { |
| 17355 | ( |
| 17356 | INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get), |
| 17357 | INTRA_SB128_VERT_HITS.with(std::cell::Cell::get), |
| 17358 | INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get), |
| 17359 | ) |
| 17360 | } |
| 17361 | |
| 17362 | /// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or |
| 17363 | /// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is |
| 17364 | /// `decode_inter_block`'s own rect path). |
| 17365 | /// |
| 17366 | /// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per |
| 17367 | /// transform unit, with the 128-specific geometry: |
| 17368 | /// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit |
| 17369 | /// is SQUARE and there are at least two of them -- depth 0: 64x64 x2, |
| 17370 | /// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts |
| 17371 | /// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the |
| 17372 | /// same CDF a 64x64 square block reads). |
| 17373 | /// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size( |
| 17374 | /// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's |
| 17375 | /// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per |
| 17376 | /// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of |
| 17377 | /// a chunk before moving to the next (the interleave lane-sb128b r3 |
| 17378 | /// measured at the 128x128 NONE root). |
| 17379 | /// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so |
| 17380 | /// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3). |
| 17381 | /// No CfL, no filter intra (both cap at 32x32) and no palette |
| 17382 | /// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode |
| 17383 | /// reader's own size gates already say so, and the guard below is defensive. |
| 17384 | /// |
| 17385 | /// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to |
| 17386 | /// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size |
| 17387 | /// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything |
| 17388 | /// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units |
| 17389 | /// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma |
| 17390 | /// units, plane-major inside each 64x64 mu chunk exactly as |
| 17391 | /// `decode_token_recon_block` codes them. Reading the 64-point geometry there |
| 17392 | /// reconstructs into a `side`-sized plane with a 16-sample residual (the panic |
| 17393 | /// this lane closed); the geometry and the unit walks below are normalized on |
| 17394 | /// `lossless_frame`. |
| 17395 | #[allow(clippy::too_many_arguments)] |
| 17396 | fn decode_block_128rect( |
| 17397 | dec: &mut SymbolDecoder, |
| 17398 | cdfs: &mut Cdfs, |
| 17399 | neighbours: &mut Neighbours, |
| 17400 | at: (usize, usize), |
| 17401 | bw: usize, |
| 17402 | bh: usize, |
| 17403 | y: &mut PlaneBuf<'static>, |
| 17404 | u: &mut PlaneBuf<'static>, |
| 17405 | v: &mut PlaneBuf<'static>, |
| 17406 | base_q_idx: u8, |
| 17407 | enable_filter_intra: bool, |
| 17408 | allow_screen_content_tools: bool, |
| 17409 | tx_select: bool, |
| 17410 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 17411 | ) -> Result<()> { |
| 17412 | let (r, c) = at; |
| 17413 | let (px, py) = (c * SUB, r * SUB); |
| 17414 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); |
| 17415 | let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); |
| 17416 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); |
| 17417 | let palette_uv_cache = neighbours.palette_uv_cache(at); |
| 17418 | let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) = |
| 17419 | read_intra_mode_rect( |
| 17420 | dec, |
| 17421 | cdfs, |
| 17422 | nb_above_mode, |
| 17423 | nb_left_mode, |
| 17424 | // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the |
| 17425 | // 13-symbol no-CFL CDF here, never the 14-symbol one. |
| 17426 | false, |
| 17427 | true, |
| 17428 | bw, |
| 17429 | bh, |
| 17430 | enable_filter_intra, |
| 17431 | neighbours.skip_txfm_ctx(mi_r, mi_c), |
| 17432 | allow_screen_content_tools, |
| 17433 | Some((palette_ctx, &palette_cache)), |
| 17434 | &palette_uv_cache, |
| 17435 | mi_r, |
| 17436 | mi_c, fctx, |
| 17437 | )?; |
| 17438 | if let Some((dv_row, dv_col)) = intrabc { |
| 17439 | // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block |
| 17440 | // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip |
| 17441 | // from this frame's own reconstruction and runs the INTER residual |
| 17442 | // walk (`decode_token_recon_block`'s else arm) over it. |
| 17443 | return decode_intrabc_128rect( |
| 17444 | dec, |
| 17445 | cdfs, |
| 17446 | neighbours, |
| 17447 | (mi_r, mi_c), |
| 17448 | (bw, bh), |
| 17449 | skip, |
| 17450 | (dv_row, dv_col), |
| 17451 | y, |
| 17452 | u, |
| 17453 | v, |
| 17454 | base_q_idx, fctx, |
| 17455 | ); |
| 17456 | } |
| 17457 | if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() { |
| 17458 | return Err(unsupported( |
| 17459 | "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \ |
| 17460 | their size gates caps at 64x64 or below, so none of these symbols exists there)", |
| 17461 | )); |
| 17462 | } |
| 17463 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 17464 | let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); |
| 17465 | if smooth_neighbor { |
| 17466 | hit!(SMOOTH_LUMA_HITS); |
| 17467 | } |
| 17468 | let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx); |
| 17469 | // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or |
| 17470 | // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc). |
| 17471 | // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all -- |
| 17472 | // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame |
| 17473 | // before the symbol is even considered (`decodeframe.c:141`) and |
| 17474 | // `read_tx_size` returns `TX_4X4` before it looks at anything |
| 17475 | // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as |
| 17476 | // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed. |
| 17477 | let lossless_frame = lossless(fctx); |
| 17478 | let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some(); |
| 17479 | let depth = if tx_select && !lossless_frame { |
| 17480 | // lane-inter128intra r1: `get_tx_size_context` compares the bands |
| 17481 | // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- |
| 17482 | // TX_64X64 for every 128-axis block, hence the `min(64)`. |
| 17483 | let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx); |
| 17484 | dec.symbol(&mut cdfs.tx_size_cat3[ctx]) |
| 17485 | } else { |
| 17486 | 0 |
| 17487 | }; |
| 17488 | if depth != 0 { |
| 17489 | hit!(TX_DEPTH_HITS); |
| 17490 | } |
| 17491 | hit_do! { |
| 17492 | INTRA_SB128_DEPTH_HITS.with(|c| { |
| 17493 | let mut h = c.get(); |
| 17494 | h[depth.min(2)] += 1; |
| 17495 | c.set(h); |
| 17496 | }); |
| 17497 | } |
| 17498 | let logical_tx = if lossless_frame { 4 } else { 64 >> depth }; |
| 17499 | if lossless_frame { |
| 17500 | hit!(INTRA128_LOSSLESS_HITS); |
| 17501 | } |
| 17502 | // A 64-point transform codes nothing past its low 32 coefficients. |
| 17503 | let coeff_tx_side = logical_tx.min(32); |
| 17504 | let luma_set = if lossless_frame { |
| 17505 | TxbSet::Luma4 |
| 17506 | } else { |
| 17507 | txbset_for(logical_tx, reduced_tx_set) |
| 17508 | }; |
| 17509 | let luma_scan = default_scan(coeff_tx_side); |
| 17510 | // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame |
| 17511 | // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan). |
| 17512 | let chroma_tx = if lossless_frame { 4 } else { 32 }; |
| 17513 | let chroma_set = if lossless_frame { |
| 17514 | TxbSet::Chroma4 |
| 17515 | } else { |
| 17516 | TxbSet::Chroma32 |
| 17517 | }; |
| 17518 | let chroma_scan = default_scan(chroma_tx); |
| 17519 | let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); |
| 17520 | let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); |
| 17521 | let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 17522 | let (nch_x, nch_y) = (bw / 64, bh / 64); |
| 17523 | // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's |
| 17524 | // `decode_token_recon_block` clips each vector's walk to |
| 17525 | // `max_block_wide/high`, so a chroma unit whose top-left is off the frame |
| 17526 | // codes nothing. |
| 17527 | let mi_cols = 2 * y.true_width.div_ceil(8); |
| 17528 | let mi_rows = 2 * y.true_height.div_ceil(8); |
| 17529 | let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c)); |
| 17530 | let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r)); |
| 17531 | // Non-lossless: one 32x32 chroma unit per mu chunk, per plane. |
| 17532 | debug_assert!(lossless_frame || (chroma_w / chroma_tx, chroma_h / chroma_tx) == (nch_x, nch_y)); |
| 17533 | let tpc = 64 / logical_tx; |
| 17534 | let zero_tu = vec![0i32; logical_tx * logical_tx]; |
| 17535 | let zero_cu = vec![0i32; chroma_tx * chroma_tx]; |
| 17536 | let mut last_grids = [Grid::Zero(0), Grid::Zero(0)]; |
| 17537 | let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new(); |
| 17538 | // The chroma context arrays are indexed in LUMA mi; every chroma unit of |
| 17539 | // every chunk shares this luma span (2 chroma pixels per luma unit). |
| 17540 | let luma_span = chroma_tx << ss_x(fctx); |
| 17541 | for ch_row in 0..nch_y { |
| 17542 | for ch_col in 0..nch_x { |
| 17543 | for tu_row in ch_row * tpc..(ch_row + 1) * tpc { |
| 17544 | for tu_col in ch_col * tpc..(ch_col + 1) * tpc { |
| 17545 | let tu_mi = ( |
| 17546 | mi_r + tu_row * (logical_tx / MI), |
| 17547 | mi_c + tu_col * (logical_tx / MI), |
| 17548 | ); |
| 17549 | let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx); |
| 17550 | // libaom clips the transform loop to |
| 17551 | // `max_blocks_wide/high`: a unit whose top-left sample is |
| 17552 | // outside the frame is never coded. |
| 17553 | if tu_px >= y.true_width || tu_py >= y.true_height { |
| 17554 | continue; |
| 17555 | } |
| 17556 | // Edge availability of a unit INSIDE a block, with the |
| 17557 | // 128 geometry -- `has_top_right` is false for a block |
| 17558 | // whose largest side is > 64, which [`Reach::of_rect`] |
| 17559 | // already answered for the block and [`tu_reach`] carries |
| 17560 | // down to the units on its own top row. |
| 17561 | let tu_r = tu_reach( |
| 17562 | bw, |
| 17563 | bh, |
| 17564 | tu_col * logical_tx, |
| 17565 | tu_row * logical_tx, |
| 17566 | logical_tx, |
| 17567 | reach, |
| 17568 | px, |
| 17569 | py, |
| 17570 | y.width, |
| 17571 | y.height, fctx, |
| 17572 | ); |
| 17573 | if skip { |
| 17574 | push_intra(0, |
| 17575 | tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None, |
| 17576 | None, smooth_neighbor, fctx, |
| 17577 | ); |
| 17578 | neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu); |
| 17579 | continue; |
| 17580 | } |
| 17581 | // The unit is smaller than its block, so `txb_skip_ctx` |
| 17582 | // is the neighbour-magnitude table, never the lone-TU 0. |
| 17583 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI); |
| 17584 | let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0]; |
| 17585 | let tu_grid = read_plane( |
| 17586 | dec, |
| 17587 | cdfs, |
| 17588 | luma_set, |
| 17589 | &luma_scan, |
| 17590 | 0, |
| 17591 | tu_around, |
| 17592 | mode, |
| 17593 | mode, |
| 17594 | angle_delta_y, |
| 17595 | tu_r, |
| 17596 | y, |
| 17597 | tu_px, |
| 17598 | tu_py, |
| 17599 | logical_tx, |
| 17600 | coeff_tx_side, |
| 17601 | base_q_idx, |
| 17602 | None, |
| 17603 | None, |
| 17604 | Some(tu_skip_ctx), |
| 17605 | smooth_neighbor, fctx, |
| 17606 | )?; |
| 17607 | neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid); |
| 17608 | } |
| 17609 | } |
| 17610 | // Transform units per axis inside this mu chunk's 32x32 chroma |
| 17611 | // span: one 32x32 unit normally, 8x8 TX_4X4 units when lossless. |
| 17612 | let cn = (32 / chroma_tx).max(1); |
| 17613 | // libaom's per-chunk `unit_width/height` (plane-mi units of the |
| 17614 | // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`. |
| 17615 | let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx); |
| 17616 | let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx); |
| 17617 | let stepc = (chroma_tx / 4).max(1); |
| 17618 | // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U |
| 17619 | // unit of the chunk, then every V unit. At one unit per plane per |
| 17620 | // chunk (every non-lossless 128-axis block) that is the same |
| 17621 | // symbol order the interleaved pair used to read; a lossless |
| 17622 | // frame's 4x4 chroma units are where it becomes observable. |
| 17623 | for plane_pass in 1..=2usize { |
| 17624 | for ci_row in 0..cn { |
| 17625 | for ci_col in 0..cn { |
| 17626 | if ch_col * 8 + ci_col * stepc >= unit_w |
| 17627 | || ch_row * 8 + ci_row * stepc >= unit_h |
| 17628 | { |
| 17629 | continue; |
| 17630 | } |
| 17631 | let cu_x = cpx + ch_col * 32 + ci_col * chroma_tx; |
| 17632 | let cu_y = cpy + ch_row * 32 + ci_row * chroma_tx; |
| 17633 | let cu_mi = ( |
| 17634 | mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4), |
| 17635 | mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4), |
| 17636 | ); |
| 17637 | let cu_r = tu_reach( |
| 17638 | bw, |
| 17639 | bh, |
| 17640 | ch_col * 64 + ci_col * luma_span, |
| 17641 | ch_row * 64 + ci_row * luma_span, |
| 17642 | luma_span, |
| 17643 | reach, |
| 17644 | px, |
| 17645 | py, |
| 17646 | y.width, |
| 17647 | y.height, fctx, |
| 17648 | ); |
| 17649 | if skip { |
| 17650 | push_intra(plane_pass, |
| 17651 | cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, |
| 17652 | &zero_cu, None, None, smooth_neighbor_uv, fctx, |
| 17653 | ); |
| 17654 | continue; |
| 17655 | } |
| 17656 | let cu_around = neighbours.around_mi(cu_mi, luma_span); |
| 17657 | let buf: &mut PlaneBuf<'static> = |
| 17658 | if plane_pass == 1 { &mut *u } else { &mut *v }; |
| 17659 | let grid = read_plane( |
| 17660 | dec, cdfs, chroma_set, &chroma_scan, plane_pass, cu_around[plane_pass], |
| 17661 | mode, uv_predict_mode, angle_delta_uv, cu_r, buf, cu_x, cu_y, |
| 17662 | chroma_tx, chroma_tx, base_q_idx, None, None, Some(3), |
| 17663 | smooth_neighbor_uv, fctx, |
| 17664 | )?; |
| 17665 | last_grids[plane_pass - 1] = grid.clone(); |
| 17666 | // Immediately, so the NEXT unit of this same block |
| 17667 | // reads this one's coefficient context; replayed after |
| 17668 | // `record_split_luma_rect` below, which would otherwise |
| 17669 | // clobber them whole-block. |
| 17670 | neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &grid); |
| 17671 | units.push((plane_pass, cu_mi, grid)); |
| 17672 | } |
| 17673 | } |
| 17674 | } |
| 17675 | if !skip { |
| 17676 | hit!(CHROMA_SPLIT_TX_HITS); |
| 17677 | } |
| 17678 | } |
| 17679 | } |
| 17680 | if skip { |
| 17681 | neighbours.record_rect( |
| 17682 | at, |
| 17683 | bw, |
| 17684 | bh, |
| 17685 | mode, |
| 17686 | uv_predict_mode, |
| 17687 | &[ |
| 17688 | &ZERO_RESIDUAL[..bw * bh], |
| 17689 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 17690 | &ZERO_RESIDUAL[..chroma_w * chroma_h], |
| 17691 | ], |
| 17692 | ); |
| 17693 | } else { |
| 17694 | neighbours.record_split_luma_rect( |
| 17695 | at, |
| 17696 | bw, |
| 17697 | bh, |
| 17698 | mode, |
| 17699 | uv_predict_mode, |
| 17700 | [&last_grids[0], &last_grids[1]], |
| 17701 | ); |
| 17702 | for (plane, cu_mi, grid) in &units { |
| 17703 | neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span, *plane, grid); |
| 17704 | } |
| 17705 | } |
| 17706 | // No palette exists at this size; the unconditional stamp clears any |
| 17707 | // stale neighbour palette state, as every other block path does. |
| 17708 | neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]); |
| 17709 | neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]); |
| 17710 | neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); |
| 17711 | neighbours.fill_lf_grid_rect( |
| 17712 | (mi_r, mi_c), |
| 17713 | bw / MI, |
| 17714 | bh / MI, |
| 17715 | logical_tx as u8, |
| 17716 | logical_tx as u8, |
| 17717 | 0, fctx, |
| 17718 | ); |
| 17719 | if in_inter || allow_intrabc_frame(fctx) { |
| 17720 | // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` |
| 17721 | // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an |
| 17722 | // inter frame, intra ones included: an intra block stamps its |
| 17723 | // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands. |
| 17724 | // A key frame reads those bands only when it allows intrabc |
| 17725 | // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom |
| 17726 | // stamps here too -- lane-av1-intrabc r3. |
| 17727 | txfm_partition_update_rect( |
| 17728 | neighbours, |
| 17729 | (mi_r, mi_c), |
| 17730 | (logical_tx, logical_tx), |
| 17731 | (bw, bh), |
| 17732 | ); |
| 17733 | } |
| 17734 | if in_inter { |
| 17735 | hit_do! { |
| 17736 | INTRA128_IN_INTER_HITS.with(|c| { |
| 17737 | let mut h = c.get(); |
| 17738 | h[usize::from(bw < bh)] += 1; |
| 17739 | c.set(h); |
| 17740 | }); |
| 17741 | } |
| 17742 | } else if bw > bh { |
| 17743 | hit!(INTRA_SB128_HORZ_HITS); |
| 17744 | } else { |
| 17745 | hit!(INTRA_SB128_VERT_HITS); |
| 17746 | } |
| 17747 | Ok(()) |
| 17748 | } |
| 17749 | |
| 17750 | |
| 17751 | /// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring |
| 17752 | /// [`crate::tile::write_leaf8`]: its intra-mode context comes from the |
| 17753 | /// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid), |
| 17754 | /// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's |
| 17755 | /// just-decoded mode, not the enclosing slot's stale one, is the true |
| 17756 | /// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info |
| 17757 | /// units, which is what its coefficient context (finer than [`SUB`]) is read |
| 17758 | /// at. Returns the mode this leaf decoded, for the caller's own |
| 17759 | /// `prev_leaf`/final mode-writeback bookkeeping. |
| 17760 | #[allow(clippy::too_many_arguments)] |
| 17761 | /// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one |
| 17762 | /// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads |
| 17763 | /// `above_mode[col]`, and its true above neighbour is the mi directly above |
| 17764 | /// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one |
| 17765 | /// decoded; the next block RIGHT reads `left_mode[row]`, whose true left |
| 17766 | /// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf |
| 17767 | /// (bottom-right) into both, as this path did, is right only when all four |
| 17768 | /// leaves happen to share a mode. `done` may be short at the true frame edge |
| 17769 | /// (the straddle caller filters positions off the frame), so each side falls |
| 17770 | /// back to the last leaf actually decoded. |
| 17771 | fn write_back_split_modes( |
| 17772 | neighbours: &mut Neighbours, |
| 17773 | done: &[((usize, usize), usize)], |
| 17774 | parent_mi: (usize, usize), |
| 17775 | slot: (usize, usize), |
| 17776 | ) { |
| 17777 | let (sr, sc) = slot; |
| 17778 | let Some(&(_, last)) = done.last() else { |
| 17779 | return; |
| 17780 | }; |
| 17781 | let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m); |
| 17782 | neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last); |
| 17783 | neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last); |
| 17784 | } |
| 17785 | |
| 17786 | fn decode_leaf8( |
| 17787 | dec: &mut SymbolDecoder, |
| 17788 | cdfs: &mut Cdfs, |
| 17789 | neighbours: &mut Neighbours, |
| 17790 | outer_at: (usize, usize), |
| 17791 | leaf_mi: (usize, usize), |
| 17792 | scans: (&[u16], &[u16]), |
| 17793 | prev_leaf: Option<((usize, usize), usize)>, |
| 17794 | y: &mut PlaneBuf<'static>, |
| 17795 | u: &mut PlaneBuf<'static>, |
| 17796 | v: &mut PlaneBuf<'static>, |
| 17797 | base_q_idx: u8, |
| 17798 | enable_filter_intra: bool, |
| 17799 | allow_screen_content_tools: bool, |
| 17800 | allow_intrabc: bool, |
| 17801 | tx_select: bool, |
| 17802 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 17803 | ) -> Result<usize> { |
| 17804 | let (r, c) = outer_at; |
| 17805 | // lane-modectx r1: the group's own availability-correct fallback pair, not |
| 17806 | // the raw coarse bands (which leak across a tile edge -- see |
| 17807 | // `modes_above_left`). |
| 17808 | let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c); |
| 17809 | if let Some(((pr, pc), pmode)) = prev_leaf { |
| 17810 | if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { |
| 17811 | above_mode = pmode; |
| 17812 | } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { |
| 17813 | left_mode = pmode; |
| 17814 | } |
| 17815 | } |
| 17816 | // The mi-exact neighbour wins over both the coarse 16x16 slot and |
| 17817 | // `prev_leaf`: one 16x16 slot cannot hold the two different modes its |
| 17818 | // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left |
| 17819 | // neighbour sits in a split cell read the wrong `kf_y_mode` row. |
| 17820 | // lane-rectsplitx r2 swept this arm into |
| 17821 | // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer |
| 17822 | // "no neighbour" at a tile edge, where the coarse cell holds the block |
| 17823 | // above/left of it inside the same 16x16. |
| 17824 | let (above_mode, left_mode) = |
| 17825 | neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode)); |
| 17826 | let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); |
| 17827 | // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode` |
| 17828 | // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode |
| 17829 | // this leaf's `smooth_neighbor` is built from -- passing `false` here |
| 17830 | // filtered a directional chroma block's edge at the wrong strength |
| 17831 | // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3). |
| 17832 | // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`), |
| 17833 | // with the coarse [`SUB`] slot as the fallback when no block recorded |
| 17834 | // that exact mi cell. |
| 17835 | let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx); |
| 17836 | if smooth_neighbor { |
| 17837 | hit!(SMOOTH_LUMA_HITS); |
| 17838 | } |
| 17839 | // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec |
| 17840 | // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other |
| 17841 | // `decode_block` caller at 16x16 and up. |
| 17842 | // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache |
| 17843 | // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567, |
| 17844 | // `read_palette_mode_info`), at its REAL mi position -- passing |
| 17845 | // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the |
| 17846 | // moment a real 8x8 palette block fired, which is where every 8-bit |
| 17847 | // `--tune-content=screen --min-partition-size=8` stream stopped. |
| 17848 | let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi); |
| 17849 | let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi); |
| 17850 | let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = |
| 17851 | read_intra_mode( |
| 17852 | dec, |
| 17853 | cdfs, |
| 17854 | above_mode, |
| 17855 | left_mode, |
| 17856 | true, |
| 17857 | 8, |
| 17858 | enable_filter_intra, |
| 17859 | neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1), |
| 17860 | allow_screen_content_tools, |
| 17861 | allow_intrabc, |
| 17862 | Some((palette_ctx, &palette_cache)), |
| 17863 | &palette_uv_cache, |
| 17864 | leaf_mi.0, |
| 17865 | leaf_mi.1, fctx, |
| 17866 | )?; |
| 17867 | // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through |
| 17868 | // `read_intra_mode` and then decoded the block as if it were ordinary |
| 17869 | // intra. libaom's `is_inter_block` counts an intrabc block |
| 17870 | // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set |
| 17871 | // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`, |
| 17872 | // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the |
| 17873 | // same value with a different interval, so the tile desynced at the very |
| 17874 | // next symbol (class `wrong-alphabet-same-value`). Everything below |
| 17875 | // mirrors `decode_block`'s own intrabc handling at 16x16 and up. |
| 17876 | let intrabc_dv = fctx.intrabc_dv.with(|c| c.take()); |
| 17877 | if intrabc_dv.is_some() { |
| 17878 | hit!(LEAF8_INTRABC_HITS); |
| 17879 | } |
| 17880 | // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour |
| 17881 | // index map, mapped through the base colours, IS the block's prediction -- |
| 17882 | // carried to the next `reconstruct`/`read_plane` through the same |
| 17883 | // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up. |
| 17884 | let palette_y_buf: Option<Vec<u16>> = palette_y |
| 17885 | .as_ref() |
| 17886 | .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); |
| 17887 | let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| { |
| 17888 | ( |
| 17889 | p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), |
| 17890 | p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), |
| 17891 | ) |
| 17892 | }); |
| 17893 | let (pal_y_size, pal_y_colors) = |
| 17894 | palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); |
| 17895 | let (pal_uv_size, pal_uv_colors) = |
| 17896 | palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); |
| 17897 | if palette_y.is_some() || palette_uv.is_some() { |
| 17898 | hit!(PALETTE_LEAF8_HITS); |
| 17899 | } |
| 17900 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { |
| 17901 | DC_PRED |
| 17902 | } else { |
| 17903 | uv_mode |
| 17904 | }; |
| 17905 | neighbours.above_uv_mode[c] = uv_predict_mode; |
| 17906 | neighbours.left_uv_mode[r] = uv_predict_mode; |
| 17907 | neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); |
| 17908 | // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only |
| 17909 | // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1, |
| 17910 | // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4 |
| 17911 | // transform units, same raster-order per-TU pattern `decode_block`'s |
| 17912 | // multi-TU branch runs). |
| 17913 | // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom |
| 17914 | // dispatches `read_block_tx_size` on `is_inter_block`, which counts an |
| 17915 | // intrabc block, so a SKIPPED one takes the largest transform and an |
| 17916 | // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that |
| 17917 | // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi |
| 17918 | // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return). |
| 17919 | // `parse_decode_block`'s tree condition carries |
| 17920 | // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy): |
| 17921 | // a lossless segment's intrabc leaf reads no tree, TX_4X4 via |
| 17922 | // `read_tx_size`'s first line (lane-av1mixloss). |
| 17923 | let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) { |
| 17924 | let mut leaves = Vec::new(); |
| 17925 | let mi_cols = 2 * y.true_width.div_ceil(8); |
| 17926 | let mi_rows = 2 * y.true_height.div_ceil(8); |
| 17927 | read_var_tx_size( |
| 17928 | dec, |
| 17929 | cdfs, |
| 17930 | neighbours, |
| 17931 | leaf_mi, |
| 17932 | 8, |
| 17933 | ( |
| 17934 | 2usize.min(mi_cols.saturating_sub(leaf_mi.1)), |
| 17935 | 2usize.min(mi_rows.saturating_sub(leaf_mi.0)), |
| 17936 | ), |
| 17937 | (8, 8), |
| 17938 | 0, |
| 17939 | 0, |
| 17940 | 0, |
| 17941 | &mut leaves, |
| 17942 | ); |
| 17943 | hit!(INTRABC_VARTX_HITS); |
| 17944 | leaves.first().map_or(8, |l| l.2) |
| 17945 | } else if tx_select && intrabc_dv.is_none() { |
| 17946 | read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx) |
| 17947 | } else { |
| 17948 | // lane-lossless: TX_4X4 on a lossless frame, no symbol |
| 17949 | // (libaom `read_tx_size`). |
| 17950 | lossless_tx(8, fctx) |
| 17951 | }; |
| 17952 | let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); |
| 17953 | let reach = Reach::of(8, px, py, y.width, y.height, fctx); |
| 17954 | let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); |
| 17955 | // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma, |
| 17956 | // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for. |
| 17957 | let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; |
| 17958 | let (csz, cset, cscan) = if chroma_444 { |
| 17959 | (8usize, TxbSet::Chroma8, scans.0) |
| 17960 | } else { |
| 17961 | (4usize, TxbSet::Chroma4, scans.1) |
| 17962 | }; |
| 17963 | // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from |
| 17964 | // the CURRENT frame's own pre-loop-filter reconstruction (every loop |
| 17965 | // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at |
| 17966 | // the full-pel block vector, with the BILINEAR kernel libaom forces. |
| 17967 | flush_recon(fctx, y, u, v); |
| 17968 | let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| { |
| 17969 | let mut yb = vec![0u16; 8 * 8]; |
| 17970 | mc::predict_with_filter( |
| 17971 | &y.data, y.width, y.true_width, y.true_height, |
| 17972 | mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0), |
| 17973 | 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx, |
| 17974 | ); |
| 17975 | let mut ub = vec![0u16; 4 * 4]; |
| 17976 | mc::predict_with_filter( |
| 17977 | &u.data, u.width, u.true_width, u.true_height, |
| 17978 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_x(fctx)), |
| 17979 | 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx, |
| 17980 | ); |
| 17981 | let mut vb = vec![0u16; 4 * 4]; |
| 17982 | mc::predict_with_filter( |
| 17983 | &v.data, v.width, v.true_width, v.true_height, |
| 17984 | mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_x(fctx)), |
| 17985 | 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx, |
| 17986 | ); |
| 17987 | (yb, ub, vb) |
| 17988 | }); |
| 17989 | // The per-plane prediction override rides the same [`PALETTE_PRED`] slot |
| 17990 | // `decode_block` uses: set fresh right before each plane's own |
| 17991 | // `reconstruct`/`read_plane` call (the slot is taken, not copied). |
| 17992 | // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows |
| 17993 | // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the |
| 17994 | // first shape that reaches that loop with an override set). |
| 17995 | let palette_y_buf = match &intrabc_bufs { |
| 17996 | Some((yb, _, _)) => Some(yb.clone()), |
| 17997 | None => palette_y_buf, |
| 17998 | }; |
| 17999 | let (luma_grid, u_grid, v_grid); |
| 18000 | if skip { |
| 18001 | // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an |
| 18002 | // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4 |
| 18003 | // transform units, each off the units already written left/above of |
| 18004 | // it inside this same leaf -- an intra block's transform size is read |
| 18005 | // whether or not it is skipped, and spec 7.11.2 predicts per unit. |
| 18006 | // A palette block's prediction is the whole-block index map, never |
| 18007 | // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip` |
| 18008 | // rule) -- so a palette leaf takes the single 8x8 reconstruct below |
| 18009 | // even when `tx_depth` resolved to TX_4X4. |
| 18010 | if resolved == 4 && palette_y_buf.is_none() { |
| 18011 | hit!(SKIP_SPLIT_TX_HITS); |
| 18012 | for tu_row in 0..2 { |
| 18013 | for tu_col in 0..2 { |
| 18014 | let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4); |
| 18015 | if tu_px >= y.true_width || tu_py >= y.true_height { |
| 18016 | continue; |
| 18017 | } |
| 18018 | let tu_reach = tu_reach( |
| 18019 | 8, |
| 18020 | 8, |
| 18021 | tu_col * 4, |
| 18022 | tu_row * 4, |
| 18023 | 4, |
| 18024 | reach, |
| 18025 | px, |
| 18026 | py, |
| 18027 | y.width, |
| 18028 | y.height, fctx, |
| 18029 | ); |
| 18030 | push_intra(0, |
| 18031 | tu_px, |
| 18032 | tu_py, |
| 18033 | 4, |
| 18034 | mode, |
| 18035 | angle_delta_y, |
| 18036 | tu_reach, |
| 18037 | &ZERO_RESIDUAL[..16], |
| 18038 | None, |
| 18039 | filter_intra, |
| 18040 | smooth_neighbor, fctx, |
| 18041 | ); |
| 18042 | } |
| 18043 | } |
| 18044 | } else { |
| 18045 | if let Some(buf) = &palette_y_buf { |
| 18046 | set_palette_pred(buf.clone(), fctx); |
| 18047 | } |
| 18048 | push_intra(0, |
| 18049 | px, |
| 18050 | py, |
| 18051 | 8, |
| 18052 | mode, |
| 18053 | angle_delta_y, |
| 18054 | reach, |
| 18055 | &ZERO_RESIDUAL[..64], |
| 18056 | None, |
| 18057 | filter_intra, |
| 18058 | smooth_neighbor, fctx, |
| 18059 | ); |
| 18060 | } |
| 18061 | let ac = alpha.map(|_| cfl_src(px, py, 8)); |
| 18062 | if let Some((_, ub, _)) = &intrabc_bufs { |
| 18063 | set_palette_pred(ub.clone(), fctx); |
| 18064 | } else if let Some((ub, _)) = &palette_uv_bufs { |
| 18065 | set_palette_pred(ub.clone(), fctx); |
| 18066 | } |
| 18067 | push_intra(1, |
| 18068 | cpx, |
| 18069 | cpy, |
| 18070 | csz, |
| 18071 | uv_predict_mode, |
| 18072 | angle_delta_uv, |
| 18073 | reach, |
| 18074 | &ZERO_RESIDUAL[..csz * csz], |
| 18075 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 18076 | None, |
| 18077 | smooth_neighbor_uv, fctx, |
| 18078 | ); |
| 18079 | if let Some((_, _, vb)) = &intrabc_bufs { |
| 18080 | set_palette_pred(vb.clone(), fctx); |
| 18081 | } else if let Some((_, vb)) = &palette_uv_bufs { |
| 18082 | set_palette_pred(vb.clone(), fctx); |
| 18083 | } |
| 18084 | push_intra(2, |
| 18085 | cpx, |
| 18086 | cpy, |
| 18087 | csz, |
| 18088 | uv_predict_mode, |
| 18089 | angle_delta_uv, |
| 18090 | reach, |
| 18091 | &ZERO_RESIDUAL[..csz * csz], |
| 18092 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 18093 | None, |
| 18094 | smooth_neighbor_uv, fctx, |
| 18095 | ); |
| 18096 | luma_grid = Grid::Zero(64); |
| 18097 | u_grid = Grid::Zero(csz * csz); |
| 18098 | v_grid = Grid::Zero(csz * csz); |
| 18099 | } else if resolved != 4 { |
| 18100 | let around = neighbours.around_mi(leaf_mi, 8); |
| 18101 | if let Some(buf) = &palette_y_buf { |
| 18102 | set_palette_pred(buf.clone(), fctx); |
| 18103 | } |
| 18104 | luma_grid = read_plane( |
| 18105 | dec, |
| 18106 | cdfs, |
| 18107 | if intrabc_dv.is_some() { |
| 18108 | inter_txbset_for(8, reduced_tx_set) |
| 18109 | } else if reduced_tx_set { |
| 18110 | TxbSet::Luma8 |
| 18111 | } else { |
| 18112 | TxbSet::Luma8Set1 |
| 18113 | }, |
| 18114 | scans.0, |
| 18115 | 0, |
| 18116 | around[0], |
| 18117 | mode, |
| 18118 | mode, |
| 18119 | angle_delta_y, |
| 18120 | reach, |
| 18121 | y, |
| 18122 | px, |
| 18123 | py, |
| 18124 | 8, |
| 18125 | TX8, |
| 18126 | base_q_idx, |
| 18127 | None, |
| 18128 | filter_intra, |
| 18129 | None, |
| 18130 | smooth_neighbor, fctx, |
| 18131 | )?; |
| 18132 | // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so |
| 18133 | // an intrabc block's chroma tx_type is the colocated LUMA transform's |
| 18134 | // coded type (lane-kf900 r6's own fix, `decode_block`'s line). |
| 18135 | if intrabc_dv.is_some() { |
| 18136 | fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get)))); |
| 18137 | } |
| 18138 | let ac = alpha.map(|_| cfl_src(px, py, 8)); |
| 18139 | if let Some((_, ub, _)) = &intrabc_bufs { |
| 18140 | set_palette_pred(ub.clone(), fctx); |
| 18141 | } else if let Some((ub, _)) = &palette_uv_bufs { |
| 18142 | set_palette_pred(ub.clone(), fctx); |
| 18143 | } |
| 18144 | u_grid = read_plane( |
| 18145 | dec, |
| 18146 | cdfs, |
| 18147 | cset, |
| 18148 | cscan, |
| 18149 | 1, |
| 18150 | around[1], |
| 18151 | mode, |
| 18152 | uv_predict_mode, |
| 18153 | angle_delta_uv, |
| 18154 | reach, |
| 18155 | u, |
| 18156 | cpx, |
| 18157 | cpy, |
| 18158 | csz, |
| 18159 | csz, |
| 18160 | base_q_idx, |
| 18161 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 18162 | None, |
| 18163 | None, |
| 18164 | smooth_neighbor_uv, fctx, |
| 18165 | )?; |
| 18166 | if let Some((_, _, vb)) = &intrabc_bufs { |
| 18167 | set_palette_pred(vb.clone(), fctx); |
| 18168 | } else if let Some((_, vb)) = &palette_uv_bufs { |
| 18169 | set_palette_pred(vb.clone(), fctx); |
| 18170 | } |
| 18171 | v_grid = read_plane( |
| 18172 | dec, |
| 18173 | cdfs, |
| 18174 | cset, |
| 18175 | cscan, |
| 18176 | 2, |
| 18177 | around[2], |
| 18178 | mode, |
| 18179 | uv_predict_mode, |
| 18180 | angle_delta_uv, |
| 18181 | reach, |
| 18182 | v, |
| 18183 | cpx, |
| 18184 | cpy, |
| 18185 | csz, |
| 18186 | csz, |
| 18187 | base_q_idx, |
| 18188 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 18189 | None, |
| 18190 | None, |
| 18191 | smooth_neighbor_uv, fctx, |
| 18192 | )?; |
| 18193 | // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's |
| 18194 | // two chroma reads (`decode_block`'s own tail does the same) -- left |
| 18195 | // set, every later chroma block would inherit this luma tx_type, |
| 18196 | // which picks the scan and the inverse transform. |
| 18197 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 18198 | } else { |
| 18199 | // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order |
| 18200 | // grid of 4x4 transform units, each predicted from the leaf's own |
| 18201 | // 8x8 `mode` and reading its own fresh context off the earlier |
| 18202 | // units in this same leaf (the same per-TU pattern `decode_block`'s |
| 18203 | // multi-TU branch runs at bigger blocks). |
| 18204 | for tu_row in 0..2 { |
| 18205 | for tu_col in 0..2 { |
| 18206 | let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col); |
| 18207 | let tu_px = px + tu_col * 4; |
| 18208 | let tu_py = py + tu_row * 4; |
| 18209 | let tu_around = neighbours.around_mi(tu_mi, 4)[0]; |
| 18210 | if crate::encode::Reach::in_vert_ab() { |
| 18211 | hit!(VERT_AB_TX4_HITS); |
| 18212 | } |
| 18213 | let tu_reach = tu_reach( |
| 18214 | 8, |
| 18215 | 8, |
| 18216 | tu_col * 4, |
| 18217 | tu_row * 4, |
| 18218 | 4, |
| 18219 | reach, |
| 18220 | px, |
| 18221 | py, |
| 18222 | y.width, |
| 18223 | y.height, fctx, |
| 18224 | ); |
| 18225 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); |
| 18226 | // Each 4x4 unit predicts from its own window of the block's |
| 18227 | // 8x8 colour-index map ([`decode_block`]'s per-TU slice at |
| 18228 | // 16x16 and up) -- the whole-block buffer would be taken by |
| 18229 | // the FIRST unit and indexed at the wrong stride. |
| 18230 | if let Some(buf) = &palette_y_buf { |
| 18231 | hit!(PALETTE_SPLIT_TX_HITS); |
| 18232 | let mut window = vec![0u16; 16]; |
| 18233 | for row in 0..4 { |
| 18234 | let src = (tu_row * 4 + row) * 8 + tu_col * 4; |
| 18235 | window[row * 4..][..4].copy_from_slice(&buf[src..][..4]); |
| 18236 | } |
| 18237 | set_palette_pred(window, fctx); |
| 18238 | } |
| 18239 | let tu_grid = read_plane( |
| 18240 | dec, |
| 18241 | cdfs, |
| 18242 | if intrabc_dv.is_some() { |
| 18243 | inter_txbset_for(4, reduced_tx_set) |
| 18244 | } else if reduced_tx_set { |
| 18245 | TxbSet::Luma4 |
| 18246 | } else { |
| 18247 | TxbSet::Luma4Set1 |
| 18248 | }, |
| 18249 | scans.1, |
| 18250 | 0, |
| 18251 | tu_around, |
| 18252 | mode, |
| 18253 | mode, |
| 18254 | angle_delta_y, |
| 18255 | tu_reach, |
| 18256 | y, |
| 18257 | tu_px, |
| 18258 | tu_py, |
| 18259 | 4, |
| 18260 | 4, |
| 18261 | base_q_idx, |
| 18262 | None, |
| 18263 | filter_intra, |
| 18264 | Some(tu_skip_ctx), |
| 18265 | smooth_neighbor, fctx, |
| 18266 | )?; |
| 18267 | if crate::envflags::env_flag!("EC_AV1_TRACE") { |
| 18268 | eprintln!( |
| 18269 | "TRACE tu_bitpos mi=({},{}) tell={}", |
| 18270 | tu_mi.0, |
| 18271 | tu_mi.1, |
| 18272 | dec.debug_bitpos() |
| 18273 | ); |
| 18274 | } |
| 18275 | neighbours.record_mi_luma(tu_mi, 4, &tu_grid); |
| 18276 | } |
| 18277 | } |
| 18278 | let ac = alpha.map(|_| cfl_src(px, py, 8)); |
| 18279 | let chroma_around = neighbours.around_mi(leaf_mi, 8); |
| 18280 | if let Some((ub, _)) = &palette_uv_bufs { |
| 18281 | set_palette_pred(ub.clone(), fctx); |
| 18282 | } |
| 18283 | u_grid = read_plane( |
| 18284 | dec, |
| 18285 | cdfs, |
| 18286 | cset, |
| 18287 | cscan, |
| 18288 | 1, |
| 18289 | chroma_around[1], |
| 18290 | mode, |
| 18291 | uv_predict_mode, |
| 18292 | angle_delta_uv, |
| 18293 | reach, |
| 18294 | u, |
| 18295 | cpx, |
| 18296 | cpy, |
| 18297 | csz, |
| 18298 | csz, |
| 18299 | base_q_idx, |
| 18300 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), |
| 18301 | None, |
| 18302 | None, |
| 18303 | smooth_neighbor_uv, fctx, |
| 18304 | )?; |
| 18305 | if let Some((_, vb)) = &palette_uv_bufs { |
| 18306 | set_palette_pred(vb.clone(), fctx); |
| 18307 | } |
| 18308 | v_grid = read_plane( |
| 18309 | dec, |
| 18310 | cdfs, |
| 18311 | cset, |
| 18312 | cscan, |
| 18313 | 2, |
| 18314 | chroma_around[2], |
| 18315 | mode, |
| 18316 | uv_predict_mode, |
| 18317 | angle_delta_uv, |
| 18318 | reach, |
| 18319 | v, |
| 18320 | cpx, |
| 18321 | cpy, |
| 18322 | csz, |
| 18323 | csz, |
| 18324 | base_q_idx, |
| 18325 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), |
| 18326 | None, |
| 18327 | None, |
| 18328 | smooth_neighbor_uv, fctx, |
| 18329 | )?; |
| 18330 | // `record_split_luma` expects a `record`-style `(r, c)` position in |
| 18331 | // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is |
| 18332 | // already in mi units, so calling it here double-scaled the |
| 18333 | // position. Plane 0 is already correct per-TU from the |
| 18334 | // `record_mi_luma` calls above; this inlines `record_mi`'s tail |
| 18335 | // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for |
| 18336 | // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this |
| 18337 | // leaf's own 8x8 side over `MI`). |
| 18338 | let side_mi = 2; |
| 18339 | for cell in 0..side_mi { |
| 18340 | neighbours.left_side_mi[leaf_mi.0 + cell] = 8; |
| 18341 | neighbours.above_side_mi[leaf_mi.1 + cell] = 8; |
| 18342 | } |
| 18343 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 18344 | let bound_h = round_up_even(neighbours.mi_rows); |
| 18345 | let bound_w = round_up_even(neighbours.mi_cols); |
| 18346 | let u_state = neighbour_state(&u_grid); |
| 18347 | let v_state = neighbour_state(&v_grid); |
| 18348 | for cell in 0..side_mi { |
| 18349 | if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) { |
| 18350 | neighbours.left[leaf_mi.0 + cell][1] = u_state; |
| 18351 | neighbours.left[leaf_mi.0 + cell][2] = v_state; |
| 18352 | } |
| 18353 | if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) { |
| 18354 | neighbours.above[leaf_mi.1 + cell][1] = u_state; |
| 18355 | neighbours.above[leaf_mi.1 + cell][2] = v_state; |
| 18356 | } |
| 18357 | } |
| 18358 | // This leaf's own palette state into the mi-granular above/left bands |
| 18359 | // (sizes 0 when it used none, which is what clears a previous block's |
| 18360 | // palette out of the next block's ctx and colour cache). |
| 18361 | { |
| 18362 | neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors); |
| 18363 | neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors); |
| 18364 | } |
| 18365 | neighbours.fill_skip_grid(leaf_mi, 2, skip); |
| 18366 | neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx); |
| 18367 | // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s |
| 18368 | // own copy; only an intrabc var-tx read consumes these bands on the intra |
| 18369 | // path, so the write is armed by `allow_intrabc`. |
| 18370 | if allow_intrabc { |
| 18371 | set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some()); |
| 18372 | } |
| 18373 | neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); |
| 18374 | record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx); |
| 18375 | return Ok(mode); |
| 18376 | } |
| 18377 | neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]); |
| 18378 | // This leaf's own palette state into the mi-granular above/left bands |
| 18379 | // (sizes 0 when it used none, which is what clears a previous block's |
| 18380 | // palette out of the next block's ctx and colour cache). |
| 18381 | { |
| 18382 | neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors); |
| 18383 | neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors); |
| 18384 | } |
| 18385 | hit!(INTER8_SKIP_BAND_HITS); |
| 18386 | neighbours.fill_skip_grid(leaf_mi, 2, skip); |
| 18387 | // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal |
| 18388 | // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm && |
| 18389 | // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip |
| 18390 | // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to |
| 18391 | // TX_4X4 still publishes 4 to the next block's `get_tx_size_context` |
| 18392 | // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf |
| 18393 | // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet, |
| 18394 | // wrong CDF row, so the msac range diverged mid-frame with no refusal |
| 18395 | // (class `wrong-alphabet-same-value`; the ReelB key frame at |
| 18396 | // -ss 900, first bad luma sample row 186 col 1803). |
| 18397 | neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx); |
| 18398 | // lane-t900 r32 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see |
| 18399 | // `decode_block`'s own copy for why this stays beside |
| 18400 | // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc |
| 18401 | // BLOCK-size term). |
| 18402 | if allow_intrabc { |
| 18403 | set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some()); |
| 18404 | } |
| 18405 | neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); |
| 18406 | // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME` |
| 18407 | // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to |
| 18408 | // publish its own cells exactly like `decode_block` does. |
| 18409 | record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx); |
| 18410 | Ok(mode) |
| 18411 | } |
| 18412 | |
| 18413 | /// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf |
| 18414 | /// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8` |
| 18415 | /// bottom, where no partition symbol is read at all -- `decode_block` runs |
| 18416 | /// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec |
| 18417 | /// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always |
| 18418 | /// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference` |
| 18419 | /// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf |
| 18420 | /// of the 2x2 4x4 group carries chroma syntax at all. |
| 18421 | #[allow(clippy::too_many_arguments)] |
| 18422 | fn read_intra_mode_sub8( |
| 18423 | dec: &mut SymbolDecoder, |
| 18424 | cdfs: &mut Cdfs, |
| 18425 | above_mode: usize, |
| 18426 | left_mode: usize, |
| 18427 | has_chroma: bool, |
| 18428 | enable_filter_intra: bool, |
| 18429 | // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a |
| 18430 | // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag |
| 18431 | // from the wrong row is the same VALUE with a different interval, so it |
| 18432 | // desyncs a block or two later, not here (class `wrong-alphabet-same-value`). |
| 18433 | fi_class: usize, |
| 18434 | skip_ctx: usize, |
| 18435 | allow_intrabc: bool, |
| 18436 | mi_r: usize, |
| 18437 | mi_c: usize, |
| 18438 | // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4` |
| 18439 | // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf |
| 18440 | // left the second mi column at segment 0, which reads back as a |
| 18441 | // neighbour's `cdf_index`/prediction two blocks later. |
| 18442 | seg_w_mi: usize, |
| 18443 | seg_h_mi: usize, fctx: &crate::decode::FrameCtx, |
| 18444 | ) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>, Option<(i32, i32)>)> { |
| 18445 | // lane-av1mono: a monochrome leaf codes no chroma mode (libaom |
| 18446 | // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`. |
| 18447 | let has_chroma = has_chroma && !mono(fctx); |
| 18448 | let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); |
| 18449 | let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); |
| 18450 | if ec_istep { |
| 18451 | eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0); |
| 18452 | } |
| 18453 | // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder |
| 18454 | // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block. |
| 18455 | macro_rules! istep { |
| 18456 | ($name:literal, $val:expr) => { |
| 18457 | if ec_istep { |
| 18458 | eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}", $name, $val, dec.debug_state().0); |
| 18459 | } |
| 18460 | }; |
| 18461 | } |
| 18462 | // lane-seg2: same `intra_segment_id` placement as the square and rect |
| 18463 | // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id` |
| 18464 | // like any other block, over its own 1x1 mi footprint. Dropping it here |
| 18465 | // both ate a symbol (the tile desynced at the frame's first sub-8x8 |
| 18466 | // split) and left `cur_segment_id` on the previous block, so the leaf |
| 18467 | // dequantized with a neighbour's `SEG_LVL_ALT_Q`. |
| 18468 | if seg_id_pre_skip(fctx) { |
| 18469 | intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx); |
| 18470 | } |
| 18471 | let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; |
| 18472 | if trace { |
| 18473 | eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0); |
| 18474 | } |
| 18475 | istep!("skip", skip as i32); |
| 18476 | if !seg_id_pre_skip(fctx) { |
| 18477 | intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx); |
| 18478 | } |
| 18479 | maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx); |
| 18480 | istep!("cdef", 0); |
| 18481 | maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx); |
| 18482 | maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx); |
| 18483 | istep!("dq", 0); |
| 18484 | if allow_intrabc { |
| 18485 | let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; |
| 18486 | if ec_istep { |
| 18487 | eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", u8::from(use_intrabc), dec.debug_state().0); |
| 18488 | } |
| 18489 | if use_intrabc { |
| 18490 | // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block |
| 18491 | // vector right after the flag and RETURNS -- no y/uv mode, angle |
| 18492 | // delta, palette, CfL or filter-intra syntax follows, and the |
| 18493 | // block is reconstructed by the INTER path (libaom's |
| 18494 | // `is_inter_block` counts an intrabc block), so the caller takes |
| 18495 | // the frame-copy prediction + inter residual. |
| 18496 | let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx); |
| 18497 | // lane-av1txr: the DV travels back in the RETURN value -- it is |
| 18498 | // NOT published through `FrameCtx::intrabc_dv`. That slot is the |
| 18499 | // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it, |
| 18500 | // then `take()` it in the same call), so a sub-8x8 leaf that |
| 18501 | // armed it left the vector standing for the NEXT >=8x8 block: |
| 18502 | // `warped.obu`'s (38,60) 8x8 intra block took it as its own |
| 18503 | // intrabc and read an inter var-tx `txfm_split` where libaom read |
| 18504 | // an intra `tx_depth` (class `stale-slot-handoff`). |
| 18505 | hit!(INTRABC_HITS); |
| 18506 | return Ok((skip, DC_PRED, 0, None, None, Some(dv))); |
| 18507 | } |
| 18508 | } |
| 18509 | let above_ctx = INTRA_MODE_CTX[above_mode]; |
| 18510 | let left_ctx = INTRA_MODE_CTX[left_mode]; |
| 18511 | let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); |
| 18512 | istep!("mode", mode); |
| 18513 | if trace { |
| 18514 | eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0); |
| 18515 | } |
| 18516 | // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/ |
| 18517 | // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`, |
| 18518 | // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta |
| 18519 | // symbol. Reading one consumed a symbol the encoder never wrote and |
| 18520 | // desynced the tile at the very next element. |
| 18521 | let angle_delta_y = 0; |
| 18522 | let chroma = if has_chroma { |
| 18523 | let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); |
| 18524 | if trace { |
| 18525 | eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0); |
| 18526 | } |
| 18527 | if (9..=12).contains(&uv_mode) { |
| 18528 | hit!(SMOOTH_UV_HITS); |
| 18529 | } |
| 18530 | let alpha = if uv_mode == UV_CFL_PRED { |
| 18531 | Some(read_cfl_alphas(dec, cdfs)) |
| 18532 | } else { |
| 18533 | None |
| 18534 | }; |
| 18535 | if (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 18536 | hit!(DIRECTIONAL_UV_HITS); |
| 18537 | } |
| 18538 | // See the luma comment above: no angle delta below 8x8. |
| 18539 | let angle_delta_uv = 0; |
| 18540 | Some((uv_mode, angle_delta_uv, alpha)) |
| 18541 | } else { |
| 18542 | None |
| 18543 | }; |
| 18544 | let mut filter_intra = None; |
| 18545 | if mode == DC_PRED && enable_filter_intra { |
| 18546 | let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0; |
| 18547 | if trace { |
| 18548 | eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32); |
| 18549 | } |
| 18550 | if use_filter_intra { |
| 18551 | hit!(FILTER_INTRA_HITS); |
| 18552 | let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); |
| 18553 | filter_intra = Some(fi_mode); |
| 18554 | } |
| 18555 | } |
| 18556 | Ok((skip, mode, angle_delta_y, chroma, filter_intra, None)) |
| 18557 | } |
| 18558 | /// 4:4:4 sub-8x8 key-frame leaf chroma (lane-av1-444). At subsampling 0/0 |
| 18559 | /// `is_chroma_reference` (av1_common_int.h:1459) is unconditional, so EVERY |
| 18560 | /// 4x4 / 4x8 / 8x4 leaf codes its own full-resolution chroma unit right |
| 18561 | /// after its own luma (`read_intra_mode_sub8` already read this leaf's own |
| 18562 | /// `uv_mode`), not the one shared 4x4 unit [`decode_leaf_split4`] / |
| 18563 | /// [`decode_leaf_rect8`]'s group tails decode at 4:2:0. Mirrors those tails |
| 18564 | /// arm for arm at leaf scale: a skipped leaf keeps its CfL contribution, an |
| 18565 | /// intrabc leaf predicts a frame copy at its DV with the luma `tx_type` |
| 18566 | /// inherited through [`INTRABC_CHROMA_TX`] (the caller arms it right after |
| 18567 | /// the luma read). The chroma position, reach and entropy-context span are |
| 18568 | /// the leaf's own (ss 0/0); the 4x8/8x4 unit reads the same |
| 18569 | /// `ChromaRect8x4` tables [`decode_rect_split`] proves for that shape. |
| 18570 | /// Records the leaf's own `uv_mode` map entry and chroma above/left state, |
| 18571 | /// and returns the (u, v) grids for the caller's coarse slots. |
| 18572 | #[allow(clippy::too_many_arguments)] |
| 18573 | fn sub8_leaf_chroma444( |
| 18574 | dec: &mut SymbolDecoder, |
| 18575 | cdfs: &mut Cdfs, |
| 18576 | neighbours: &mut Neighbours, |
| 18577 | lmi: (usize, usize), |
| 18578 | bw: usize, |
| 18579 | bh: usize, |
| 18580 | uv_mode: usize, |
| 18581 | alpha: Option<(i32, i32)>, |
| 18582 | skip: bool, |
| 18583 | intrabc_dv: Option<(i32, i32)>, |
| 18584 | y: &PlaneBuf<'static>, |
| 18585 | u: &mut PlaneBuf<'static>, |
| 18586 | v: &mut PlaneBuf<'static>, |
| 18587 | scan4: &[u16], |
| 18588 | base_q_idx: u8, |
| 18589 | smooth_neighbor_uv: bool, |
| 18590 | fctx: &crate::decode::FrameCtx, |
| 18591 | ) -> Result<(Grid, Grid)> { |
| 18592 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 18593 | let (w_mi, h_mi) = (bw / MI, bh / MI); |
| 18594 | neighbours.record_uv_mode_mi(lmi.0, lmi.1, w_mi, h_mi, uv_predict_mode); |
| 18595 | let (px, py) = (lmi.1 * MI, lmi.0 * MI); |
| 18596 | let square = (bw, bh) == (4, 4); |
| 18597 | // `Reach::of_rect` has no 4x4 table (`rect_reach_tables` starts at 4x8); |
| 18598 | // the square unit takes the leaf's own `Reach::of`, as its luma does. |
| 18599 | let reach = if square { |
| 18600 | Reach::of(4, px, py, y.width, y.height, fctx) |
| 18601 | } else { |
| 18602 | Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx) |
| 18603 | }; |
| 18604 | let grids = if skip { |
| 18605 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 18606 | if square { |
| 18607 | 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); |
| 18608 | 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); |
| 18609 | } else { |
| 18610 | 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); |
| 18611 | 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); |
| 18612 | } |
| 18613 | // The same arm-without-clear route the 4:2:0 tails count: a skipped |
| 18614 | // leaf reads no coefficient, so an armed intrabc slot is dropped. |
| 18615 | if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { |
| 18616 | hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); |
| 18617 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 18618 | } |
| 18619 | (Grid::Zero(bw * bh), Grid::Zero(bw * bh)) |
| 18620 | } else if let Some(dv) = intrabc_dv { |
| 18621 | // Frame copy at the DV; the residual still reads the ordinary chroma |
| 18622 | // tables with the inherited luma `tx_type` (see the 4:2:0 tails). |
| 18623 | let mut ub = vec![0u16; bw * bh]; |
| 18624 | mc::predict_with_filter( |
| 18625 | &u.data, u.width, u.true_width, u.true_height, |
| 18626 | mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0), |
| 18627 | bw, bh, mc::InterpFilterKind::Bilinear, &mut ub, fctx, |
| 18628 | ); |
| 18629 | let mut vb = vec![0u16; bw * bh]; |
| 18630 | mc::predict_with_filter( |
| 18631 | &v.data, v.width, v.true_width, v.true_height, |
| 18632 | mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0), |
| 18633 | bw, bh, mc::InterpFilterKind::Bilinear, &mut vb, fctx, |
| 18634 | ); |
| 18635 | let around = neighbours.around_mi_rect(lmi, bw, bh); |
| 18636 | let pair = if square { |
| 18637 | set_palette_pred(ub, fctx); |
| 18638 | let ug = read_plane( |
| 18639 | dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], DC_PRED, DC_PRED, |
| 18640 | 0, reach, u, px, py, 4, TX4, base_q_idx, |
| 18641 | None, None, None, smooth_neighbor_uv, fctx, |
| 18642 | )?; |
| 18643 | set_palette_pred(vb, fctx); |
| 18644 | let vg = read_plane( |
| 18645 | dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], DC_PRED, DC_PRED, |
| 18646 | 0, reach, v, px, py, 4, TX4, base_q_idx, |
| 18647 | None, None, None, smooth_neighbor_uv, fctx, |
| 18648 | )?; |
| 18649 | (ug, vg) |
| 18650 | } else { |
| 18651 | let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 }; |
| 18652 | let default_tx = |
| 18653 | fctx.intrabc_chroma_tx.with(std::cell::Cell::get).unwrap_or(TxType::DctDct); |
| 18654 | let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh)); |
| 18655 | for (plane_idx, buf) in [(1usize, ub), (2usize, vb)] { |
| 18656 | let skip_ctx = |
| 18657 | usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1); |
| 18658 | let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, DC_PRED); |
| 18659 | let (levels, tx_type) = read_coeffs_rect( |
| 18660 | dec, &mut coding, scan, bw, bh, skip_ctx, |
| 18661 | dc_sign_ctx(around[plane_idx].2), default_tx, |
| 18662 | )?; |
| 18663 | let residual = dequant_and_inverse_typed_wh( |
| 18664 | &levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), |
| 18665 | plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, |
| 18666 | tx_type, |
| 18667 | block_iqmatrix(fctx, plane_idx, bw, bh, tx_type), |
| 18668 | ); |
| 18669 | set_palette_pred(buf, fctx); |
| 18670 | push_intra_rect( |
| 18671 | plane_idx, px, py, bw, bh, DC_PRED, 0, reach, &residual, |
| 18672 | None, None, smooth_neighbor_uv, fctx, |
| 18673 | ); |
| 18674 | if plane_idx == 1 { out.0 = levels; } else { out.1 = levels; } |
| 18675 | } |
| 18676 | out |
| 18677 | }; |
| 18678 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 18679 | pair |
| 18680 | } else { |
| 18681 | let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh)); |
| 18682 | let around = neighbours.around_mi_rect(lmi, bw, bh); |
| 18683 | if square { |
| 18684 | let ug = read_plane( |
| 18685 | dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], uv_mode, uv_predict_mode, |
| 18686 | 0, reach, u, px, py, 4, TX4, base_q_idx, |
| 18687 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, |
| 18688 | )?; |
| 18689 | let vg = read_plane( |
| 18690 | dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], uv_mode, uv_predict_mode, |
| 18691 | 0, reach, v, px, py, 4, TX4, base_q_idx, |
| 18692 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, |
| 18693 | )?; |
| 18694 | (ug, vg) |
| 18695 | } else { |
| 18696 | // `av1_get_max_uv_txsize(BLOCK_4X8/8X4)` at ss 0/0 is the rect |
| 18697 | // transform itself; its `tx_type` is mode-derived with the |
| 18698 | // <32 set (`decode_rect_split`'s own rule for this shape). |
| 18699 | let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 }; |
| 18700 | let default_tx = default_intra_tx_type(uv_predict_mode as u8); |
| 18701 | let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh)); |
| 18702 | for plane_idx in 1..=2usize { |
| 18703 | let skip_ctx = |
| 18704 | usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1); |
| 18705 | let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); |
| 18706 | let (levels, tx_type) = read_coeffs_rect( |
| 18707 | dec, &mut coding, scan, bw, bh, skip_ctx, |
| 18708 | dc_sign_ctx(around[plane_idx].2), default_tx, |
| 18709 | )?; |
| 18710 | let residual = dequant_and_inverse_typed_wh( |
| 18711 | &levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx), |
| 18712 | plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, |
| 18713 | tx_type, |
| 18714 | block_iqmatrix(fctx, plane_idx, bw, bh, tx_type), |
| 18715 | ); |
| 18716 | let cfl = alpha |
| 18717 | .zip(ac) |
| 18718 | .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)); |
| 18719 | push_intra_rect( |
| 18720 | plane_idx, px, py, bw, bh, uv_predict_mode, 0, reach, &residual, |
| 18721 | cfl, None, smooth_neighbor_uv, fctx, |
| 18722 | ); |
| 18723 | if plane_idx == 1 { out.0 = levels; } else { out.1 = levels; } |
| 18724 | } |
| 18725 | out |
| 18726 | } |
| 18727 | }; |
| 18728 | // libaom `av1_set_entropy_contexts` stamps above/left PER TRANSFORM UNIT: |
| 18729 | // the leaf's own chroma span, not the 8x8 group's. |
| 18730 | let (u_grid, v_grid) = grids; |
| 18731 | let u_state = neighbour_state(&u_grid); |
| 18732 | let v_state = neighbour_state(&v_grid); |
| 18733 | for cell in 0..h_mi { |
| 18734 | if lmi.0 + cell < neighbours.mi_rows { |
| 18735 | neighbours.left[lmi.0 + cell][1] = u_state; |
| 18736 | neighbours.left[lmi.0 + cell][2] = v_state; |
| 18737 | } |
| 18738 | } |
| 18739 | for cell in 0..w_mi { |
| 18740 | if lmi.1 + cell < neighbours.mi_cols { |
| 18741 | neighbours.above[lmi.1 + cell][1] = u_state; |
| 18742 | neighbours.above[lmi.1 + cell][2] = v_state; |
| 18743 | } |
| 18744 | } |
| 18745 | Ok((u_grid, v_grid)) |
| 18746 | } |
| 18747 | |
| 18748 | |
| 18749 | /// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves |
| 18750 | /// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s |
| 18751 | /// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode` |
| 18752 | /// bookkeeping needs no change. Each leaf reads its own luma mode info, |
| 18753 | /// neighboured off the *previously decoded leaf in this same group* on |
| 18754 | /// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf` |
| 18755 | /// pattern, one level deeper); chroma is read and reconstructed exactly |
| 18756 | /// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4 |
| 18757 | /// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference` |
| 18758 | /// derivation. |
| 18759 | #[allow(clippy::too_many_arguments)] |
| 18760 | fn decode_leaf_split4( |
| 18761 | dec: &mut SymbolDecoder, |
| 18762 | cdfs: &mut Cdfs, |
| 18763 | neighbours: &mut Neighbours, |
| 18764 | outer_at: (usize, usize), |
| 18765 | leaf_mi: (usize, usize), |
| 18766 | scan4: &[u16], |
| 18767 | prev_leaf: Option<((usize, usize), usize)>, |
| 18768 | y: &mut PlaneBuf<'static>, |
| 18769 | u: &mut PlaneBuf<'static>, |
| 18770 | v: &mut PlaneBuf<'static>, |
| 18771 | base_q_idx: u8, |
| 18772 | enable_filter_intra: bool, |
| 18773 | allow_intrabc: bool, |
| 18774 | reduced_tx_set: bool, |
| 18775 | // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8 |
| 18776 | // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the |
| 18777 | // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx |
| 18778 | fctx: &crate::decode::FrameCtx, |
| 18779 | ) -> Result<(usize, usize)> { |
| 18780 | hit!(SUB8_SPLIT_HITS); |
| 18781 | let (r, c) = outer_at; |
| 18782 | let mut above_mode = neighbours.above_mode[c]; |
| 18783 | let mut left_mode = neighbours.left_mode[r]; |
| 18784 | if let Some(((pr, pc), pmode)) = prev_leaf { |
| 18785 | if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { |
| 18786 | above_mode = pmode; |
| 18787 | } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { |
| 18788 | left_mode = pmode; |
| 18789 | } |
| 18790 | } |
| 18791 | // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter |
| 18792 | // type is the chroma neighbours' `uv_mode`, mi-exact where recorded. |
| 18793 | let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx); |
| 18794 | let mut leaf_modes = [0usize; 4]; |
| 18795 | let mut leaf_skips = [false; 4]; |
| 18796 | let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None; |
| 18797 | // lane-av1txr: the chroma-reference (i==3) leaf's block vector when that |
| 18798 | // leaf is an intrabc block -- its prediction/reconstruction below is a |
| 18799 | // frame copy at this DV, not an intra one. |
| 18800 | let mut last_intrabc: Option<(i32, i32)> = None; |
| 18801 | // 4:4:4 (lane-av1-444): `is_chroma_reference` (av1_common_int.h:1459) is |
| 18802 | // unconditional at subsampling 0/0, so EVERY 4x4 leaf reads its own |
| 18803 | // `uv_mode` and codes its own full-resolution 4x4 chroma unit right |
| 18804 | // after its luma -- there is no shared group unit at all. |
| 18805 | let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; |
| 18806 | // The last leaf's own `uv_predict_mode`, for the coarse above/left slots |
| 18807 | // the 4:2:0 tail fills from the group's single unit. |
| 18808 | let mut last_uv444 = DC_PRED; |
| 18809 | for i in 0..4usize { |
| 18810 | let (dr, dc) = (i / 2, i % 2); |
| 18811 | let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc); |
| 18812 | // Neighbour modes at real mi granularity: inside the group the |
| 18813 | // sibling leaf, outside it the split-leaf map when the adjacent mi |
| 18814 | // was itself a 4x4 leaf, else the coarse 16x16 slot (see |
| 18815 | // `sub8_mode_col`'s doc). |
| 18816 | let leaf_above = if dr == 0 { |
| 18817 | neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode) |
| 18818 | } else { |
| 18819 | leaf_modes[i - 2] |
| 18820 | }; |
| 18821 | let leaf_left = if dc == 0 { |
| 18822 | neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode) |
| 18823 | } else { |
| 18824 | leaf_modes[i - 1] |
| 18825 | }; |
| 18826 | let has_chroma = chroma_444 || i == 3; |
| 18827 | let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1); |
| 18828 | let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = read_intra_mode_sub8( |
| 18829 | dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, |
| 18830 | filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"), |
| 18831 | skip_ctx, allow_intrabc, lmi.0, lmi.1, 1, 1, fctx, |
| 18832 | )?; |
| 18833 | leaf_modes[i] = mode; |
| 18834 | leaf_skips[i] = skip; |
| 18835 | neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode); |
| 18836 | // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this |
| 18837 | // `BLOCK_4X4` leaf -- EVERY block publishes its transform size into |
| 18838 | // the TXFM context bands, and an intrabc block's later `txfm_split` |
| 18839 | // context is read off them (`txfm_partition_context`). A 4x4 never |
| 18840 | // signals a tx size, so it is always TX_4X4 (`set_txfm_ctxs`'s |
| 18841 | // `skip && is_inter` branch writes the block's own 4 pixels -- the |
| 18842 | // same value). |
| 18843 | set_txfm_ctxs(neighbours, lmi, 4, 1, 1, false); |
| 18844 | let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); |
| 18845 | if smooth_neighbor { |
| 18846 | hit!(SMOOTH_LUMA_HITS); |
| 18847 | } |
| 18848 | let (px, py) = (lmi.1 * MI, lmi.0 * MI); |
| 18849 | let reach = Reach::of(4, px, py, y.width, y.height, fctx); |
| 18850 | if let Some(dv) = intrabc { |
| 18851 | // lane-av1txr: an intrabc `BLOCK_4X4` leaf -- prediction is the |
| 18852 | // CURRENT frame at the block vector (`predict_inter_block`'s |
| 18853 | // intrabc arm, spec 7.11.3.4), residual the INTER coefficient set |
| 18854 | // (libaom reads `tx_type` off `inter_ext_tx_cdf` for |
| 18855 | // `is_inter_block`, which counts intrabc). Published into |
| 18856 | // `intrabc_dv` so the group's chroma arm (below, when the |
| 18857 | // chroma-reference leaf is the intrabc one) and |
| 18858 | // [`record_intrabc_mi`] see it. |
| 18859 | flush_recon(fctx, y, u, v); |
| 18860 | let mut yb = vec![0u16; 16]; |
| 18861 | mc::predict_with_filter( |
| 18862 | &y.data, y.width, y.true_width, y.true_height, |
| 18863 | mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0), |
| 18864 | 4, 4, mc::InterpFilterKind::Bilinear, &mut yb, fctx, |
| 18865 | ); |
| 18866 | set_palette_pred(yb.clone(), fctx); |
| 18867 | if skip { |
| 18868 | push_intra(0, px, py, 4, DC_PRED, 0, reach, &ZERO_RESIDUAL[..16], None, None, smooth_neighbor, fctx); |
| 18869 | neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]); |
| 18870 | } else { |
| 18871 | let tu_around = neighbours.around_mi(lmi, 4)[0]; |
| 18872 | let tu_grid = read_plane( |
| 18873 | dec, |
| 18874 | cdfs, |
| 18875 | if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 }, |
| 18876 | scan4, |
| 18877 | 0, |
| 18878 | tu_around, |
| 18879 | DC_PRED, |
| 18880 | DC_PRED, |
| 18881 | 0, |
| 18882 | reach, |
| 18883 | y, |
| 18884 | px, |
| 18885 | py, |
| 18886 | 4, |
| 18887 | 4, |
| 18888 | base_q_idx, |
| 18889 | None, |
| 18890 | None, |
| 18891 | None, |
| 18892 | smooth_neighbor, fctx, |
| 18893 | )?; |
| 18894 | neighbours.record_mi_luma(lmi, 4, &tu_grid); |
| 18895 | } |
| 18896 | neighbours.fill_skip_grid(lmi, 1, skip); |
| 18897 | neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx); |
| 18898 | record_intrabc_mi(lmi.0, lmi.1, 1, Some(dv), neighbours, fctx); |
| 18899 | if has_chroma { |
| 18900 | // An intrabc block is an INTER block for `av1_get_tx_type`, so |
| 18901 | // the chroma inherits the LUMA's coded transform type |
| 18902 | // (`xd->tx_type_map` at the co-located luma position) -- the |
| 18903 | // luma `read_plane` above just set [`LUMA_TX_TYPE`]. Armed for |
| 18904 | // exactly this leaf's two chroma reads. |
| 18905 | fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get)))); |
| 18906 | if chroma_444 { |
| 18907 | // lane-av1-444: this leaf codes its OWN 4x4 chroma unit |
| 18908 | // right here (frame copy at the DV); no group tail. |
| 18909 | sub8_leaf_chroma444( |
| 18910 | dec, cdfs, neighbours, lmi, 4, 4, DC_PRED, None, skip, |
| 18911 | Some(dv), y, u, v, scan4, base_q_idx, |
| 18912 | neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, |
| 18913 | )?; |
| 18914 | last_uv444 = DC_PRED; |
| 18915 | } else { |
| 18916 | last_uv = Some((DC_PRED, 0, None)); |
| 18917 | // lane-av1txbands: the group's chroma is the CHROMA-REFERENCE |
| 18918 | // leaf's own block -- libaom codes one chroma unit under the |
| 18919 | // last sub-block only (`is_chroma_reference`), so its prediction |
| 18920 | // is that leaf's `uv_mode` (CfL alpha and all) unless THAT leaf |
| 18921 | // is the intrabc one. Arming this from a non-chroma-reference |
| 18922 | // leaf's DV made `warped.obu`'s 8x8 group at mi(40,62) copy |
| 18923 | // frame bytes at mi(41,62)'s vector where aomdec predicts |
| 18924 | // `uv_mode=UV_CFL_PRED`: luma stayed byte-exact and only chroma |
| 18925 | // moved (class chroma-keyed-at-a-non-chroma-leaf). Mirrors |
| 18926 | // [`decode_leaf_rect8`]'s own placement. |
| 18927 | last_intrabc = Some(dv); |
| 18928 | } |
| 18929 | } |
| 18930 | continue; |
| 18931 | } |
| 18932 | if skip { |
| 18933 | push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx); |
| 18934 | neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]); |
| 18935 | } else { |
| 18936 | let tu_around = neighbours.around_mi(lmi, 4)[0]; |
| 18937 | // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's |
| 18938 | // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]` |
| 18939 | // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table |
| 18940 | // (`txb_common.h:400`). Reading the table here decoded `all_zero` |
| 18941 | // off the wrong CDF on the very first leaf and desynced the tile. |
| 18942 | let tu_grid = read_plane( |
| 18943 | dec, |
| 18944 | cdfs, |
| 18945 | if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 }, |
| 18946 | scan4, |
| 18947 | 0, |
| 18948 | tu_around, |
| 18949 | mode, |
| 18950 | mode, |
| 18951 | angle_delta_y, |
| 18952 | reach, |
| 18953 | y, |
| 18954 | px, |
| 18955 | py, |
| 18956 | 4, |
| 18957 | 4, |
| 18958 | base_q_idx, |
| 18959 | None, |
| 18960 | filter_intra, |
| 18961 | None, |
| 18962 | smooth_neighbor, fctx, |
| 18963 | )?; |
| 18964 | neighbours.record_mi_luma(lmi, 4, &tu_grid); |
| 18965 | } |
| 18966 | neighbours.fill_skip_grid(lmi, 1, skip); |
| 18967 | neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx); |
| 18968 | if has_chroma { |
| 18969 | if chroma_444 { |
| 18970 | // lane-av1-444: the leaf's own 4x4 chroma unit, coded right |
| 18971 | // after its luma (no shared group unit at ss 0/0). |
| 18972 | let (uv_mode, _, alpha) = |
| 18973 | chroma.expect("4:4:4 reads uv_mode on every leaf"); |
| 18974 | sub8_leaf_chroma444( |
| 18975 | dec, cdfs, neighbours, lmi, 4, 4, uv_mode, alpha, skip, |
| 18976 | None, y, u, v, scan4, base_q_idx, |
| 18977 | neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, |
| 18978 | )?; |
| 18979 | last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 18980 | } else { |
| 18981 | last_uv = chroma; |
| 18982 | } |
| 18983 | } |
| 18984 | } |
| 18985 | // lane-av1mono: as [`decode_leaf_rect8`] -- a monochrome frame has no |
| 18986 | // chroma to reconstruct and no uv_mode was read. |
| 18987 | let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) { |
| 18988 | (Grid::Zero(16), Grid::Zero(16)) |
| 18989 | } else if chroma_444 { |
| 18990 | // lane-av1-444: every leaf coded and reconstructed its own chroma in |
| 18991 | // the loop above ([`sub8_leaf_chroma444`] stamped the mi-exact maps |
| 18992 | // and per-leaf entropy state); only the coarse slots remain, filled |
| 18993 | // from the bottom-right leaf like the 4:2:0 tail's single unit. |
| 18994 | neighbours.above_uv_mode[c] = last_uv444; |
| 18995 | neighbours.left_uv_mode[r] = last_uv444; |
| 18996 | (Grid::Zero(16), Grid::Zero(16)) |
| 18997 | } else { |
| 18998 | let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); |
| 18999 | let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx)); |
| 19000 | let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx); |
| 19001 | let (uv_mode, angle_delta_uv, alpha) = |
| 19002 | last_uv.expect("i==3 always sets has_chroma, so chroma is always Some"); |
| 19003 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 19004 | neighbours.above_uv_mode[c] = uv_predict_mode; |
| 19005 | neighbours.left_uv_mode[r] = uv_predict_mode; |
| 19006 | neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); |
| 19007 | let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] { |
| 19008 | // A skipped chroma block still gets its CfL contribution: libaom's |
| 19009 | // `predict_and_reconstruct_intra_block` calls `cfl_predict_block` |
| 19010 | // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719) |
| 19011 | // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is |
| 19012 | // added -- `skip_txfm` only drops the residual, never the alpha. |
| 19013 | // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the |
| 19014 | // merge keeps one fix and feeds both lanes' counters so neither of |
| 19015 | // their gates goes vacuous. |
| 19016 | let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); |
| 19017 | if alpha.is_some() { |
| 19018 | hit!(CHROMA_SKIP_CFL_HITS); |
| 19019 | hit!(SKIP_CFL_HITS); |
| 19020 | } |
| 19021 | 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); |
| 19022 | 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); |
| 19023 | // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma |
| 19024 | // coefficient, so it never consults the inherited luma transform type |
| 19025 | // -- but an intrabc chroma-reference leaf did arm |
| 19026 | // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient |
| 19027 | // branches below are the only ones that disarm it. Left armed, the slot |
| 19028 | // picks the NEXT block's chroma scan and inverse transform (class |
| 19029 | // arm-without-clear-on-a-skip-route). Counted so a gate can tell a |
| 19030 | // stream that reaches this route from one that never does. |
| 19031 | if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { |
| 19032 | hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); |
| 19033 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 19034 | } |
| 19035 | (Grid::Zero(16), Grid::Zero(16)) |
| 19036 | } else if let Some(dv) = last_intrabc { |
| 19037 | // lane-av1txr: the chroma-reference leaf was an intrabc block, so the |
| 19038 | // group's one chroma unit is a frame copy at that DV too (its residual |
| 19039 | // still reads the ordinary `Chroma4` coefficient tables -- libaom |
| 19040 | // codes a chroma `tx_type` nowhere). |
| 19041 | let mut ub = vec![0u16; 16]; |
| 19042 | mc::predict_with_filter( |
| 19043 | &u.data, u.width, u.true_width, u.true_height, |
| 19044 | mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_x(fctx)), |
| 19045 | 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx, |
| 19046 | ); |
| 19047 | let mut vb = vec![0u16; 16]; |
| 19048 | mc::predict_with_filter( |
| 19049 | &v.data, v.width, v.true_width, v.true_height, |
| 19050 | mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_x(fctx)), |
| 19051 | 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx, |
| 19052 | ); |
| 19053 | let chroma_around = neighbours.around_mi(leaf_mi, 8); |
| 19054 | set_palette_pred(ub, fctx); |
| 19055 | let ug = read_plane( |
| 19056 | dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED, |
| 19057 | 0, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, |
| 19058 | None, None, None, smooth_neighbor_uv, fctx, |
| 19059 | )?; |
| 19060 | set_palette_pred(vb, fctx); |
| 19061 | let vg = read_plane( |
| 19062 | dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED, |
| 19063 | 0, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, |
| 19064 | None, None, None, smooth_neighbor_uv, fctx, |
| 19065 | )?; |
| 19066 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 19067 | (ug, vg) |
| 19068 | } else { |
| 19069 | let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); |
| 19070 | let chroma_around = neighbours.around_mi(leaf_mi, 8); |
| 19071 | let ug = read_plane( |
| 19072 | dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode, |
| 19073 | angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, |
| 19074 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, |
| 19075 | )?; |
| 19076 | let vg = read_plane( |
| 19077 | dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode, |
| 19078 | angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, |
| 19079 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, |
| 19080 | )?; |
| 19081 | (ug, vg) |
| 19082 | }; |
| 19083 | (u_grid, v_grid) |
| 19084 | }; |
| 19085 | // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors |
| 19086 | // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s |
| 19087 | // rescaling is wrong for an already-mi-unit position, so this inlines |
| 19088 | // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition |
| 19089 | // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one |
| 19090 | // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is |
| 19091 | // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8 |
| 19092 | // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion |
| 19093 | // bottom). libaom's `update_ext_partition_context` writes |
| 19094 | // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for |
| 19095 | // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via |
| 19096 | // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and |
| 19097 | // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs |
| 19098 | // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this |
| 19099 | // round's bug) makes the very next sibling 8x8's `partition_w8` read |
| 19100 | // with the wrong context and desync immediately. |
| 19101 | let side_mi = 2; |
| 19102 | for cell in 0..side_mi { |
| 19103 | neighbours.left_side_mi[leaf_mi.0 + cell] = 4; |
| 19104 | neighbours.above_side_mi[leaf_mi.1 + cell] = 4; |
| 19105 | } |
| 19106 | // lane-av1-444: at 4:4:4 [`sub8_leaf_chroma444`] already stamped each |
| 19107 | // leaf's own span as it decoded; these placeholder grids carry no state. |
| 19108 | if !chroma_444 { |
| 19109 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 19110 | let bound_h = round_up_even(neighbours.mi_rows); |
| 19111 | let bound_w = round_up_even(neighbours.mi_cols); |
| 19112 | let u_state = neighbour_state(&u_grid); |
| 19113 | let v_state = neighbour_state(&v_grid); |
| 19114 | for cell in 0..side_mi { |
| 19115 | if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) { |
| 19116 | neighbours.left[leaf_mi.0 + cell][1] = u_state; |
| 19117 | neighbours.left[leaf_mi.0 + cell][2] = v_state; |
| 19118 | } |
| 19119 | if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) { |
| 19120 | neighbours.above[leaf_mi.1 + cell][1] = u_state; |
| 19121 | neighbours.above[leaf_mi.1 + cell][2] = v_state; |
| 19122 | } |
| 19123 | } |
| 19124 | } |
| 19125 | // lane-dkey: a sub-8x8 leaf can never use palette (`av1_allow_palette` |
| 19126 | // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its |
| 19127 | // `palette_size` is 0 in every one of these mi cells, so the NEXT block's |
| 19128 | // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder |
| 19129 | // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette |
| 19130 | // block above a 4x4 group left its size/colours standing in the mi-granular |
| 19131 | // bands: the block below the group read `palette_y_mode` off CDF row 1 |
| 19132 | // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a |
| 19133 | // palette libaom never coded, and then skipped the `use_filter_intra` |
| 19134 | // symbol that a palette block has none of -- one symbol short, tile |
| 19135 | // desynced. Publishing the group's own zeros is the clear. |
| 19136 | neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]); |
| 19137 | neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]); |
| 19138 | Ok((leaf_modes[2], leaf_modes[1])) |
| 19139 | } |
| 19140 | |
| 19141 | /// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two |
| 19142 | /// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape |
| 19143 | /// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for |
| 19144 | /// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no |
| 19145 | /// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at |
| 19146 | /// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for |
| 19147 | /// every sub-block one mi wide or high but the last) -- differing only where |
| 19148 | /// the shape does: |
| 19149 | /// |
| 19150 | /// * the transform is a true `TX_4X8`/`TX_8X4` |
| 19151 | /// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and |
| 19152 | /// `av1_inv_txfm_shift_ls` row already cover this size pair); |
| 19153 | /// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares |
| 19154 | /// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type` |
| 19155 | /// row -- see that variant's doc comment; |
| 19156 | /// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings |
| 19157 | /// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`; |
| 19158 | /// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows |
| 19159 | /// ([`Reach::of_rect`]); |
| 19160 | /// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]` |
| 19161 | /// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a |
| 19162 | /// `BLOCK_4X4` split writes. |
| 19163 | /// |
| 19164 | /// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is |
| 19165 | /// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes |
| 19166 | /// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`] |
| 19167 | /// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's |
| 19168 | /// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is |
| 19169 | /// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`. |
| 19170 | #[allow(clippy::too_many_arguments)] |
| 19171 | fn decode_leaf_rect8( |
| 19172 | dec: &mut SymbolDecoder, |
| 19173 | cdfs: &mut Cdfs, |
| 19174 | neighbours: &mut Neighbours, |
| 19175 | outer_at: (usize, usize), |
| 19176 | leaf_mi: (usize, usize), |
| 19177 | vert: bool, |
| 19178 | scan4: &[u16], |
| 19179 | y: &mut PlaneBuf<'static>, |
| 19180 | u: &mut PlaneBuf<'static>, |
| 19181 | v: &mut PlaneBuf<'static>, |
| 19182 | base_q_idx: u8, |
| 19183 | enable_filter_intra: bool, |
| 19184 | allow_intrabc: bool, |
| 19185 | tx_select: bool, |
| 19186 | reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, |
| 19187 | ) -> Result<(usize, usize)> { |
| 19188 | let (r, c) = outer_at; |
| 19189 | // lane-modectx r1: availability-correct fallback pair (see |
| 19190 | // `modes_above_left`), not the raw coarse bands. |
| 19191 | let (above_mode, left_mode) = neighbours.modes_above_left(r, c); |
| 19192 | let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx); |
| 19193 | let (bw, bh) = if vert { (4, 8) } else { (8, 4) }; |
| 19194 | let (w_mi, h_mi) = (bw / MI, bh / MI); |
| 19195 | let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 }; |
| 19196 | let mut leaf_modes = [0usize; 2]; |
| 19197 | let mut leaf_skips = [false; 2]; |
| 19198 | let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None; |
| 19199 | // lane-av1txr: as [`decode_leaf_split4`]'s own `last_intrabc`. |
| 19200 | let mut last_intrabc: Option<(i32, i32)> = None; |
| 19201 | // 4:4:4 (lane-av1-444): as [`decode_leaf_split4`] -- at subsampling 0/0 |
| 19202 | // EVERY 4x8/8x4 leaf reads its own `uv_mode` and codes its own |
| 19203 | // full-resolution rect chroma unit right after its luma. |
| 19204 | let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; |
| 19205 | let mut last_uv444 = DC_PRED; |
| 19206 | for i in 0..2usize { |
| 19207 | let lmi = if vert { |
| 19208 | (leaf_mi.0, leaf_mi.1 + i) |
| 19209 | } else { |
| 19210 | (leaf_mi.0 + i, leaf_mi.1) |
| 19211 | }; |
| 19212 | // Inside the pair the sibling is the neighbour on the split axis; |
| 19213 | // outside it the mi-granular map, else the coarse 16x16 slot. |
| 19214 | let leaf_above = if !vert && i == 1 { |
| 19215 | leaf_modes[0] |
| 19216 | } else { |
| 19217 | neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode) |
| 19218 | }; |
| 19219 | let leaf_left = if vert && i == 1 { |
| 19220 | leaf_modes[0] |
| 19221 | } else { |
| 19222 | neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode) |
| 19223 | }; |
| 19224 | let has_chroma = chroma_444 || i == 1; |
| 19225 | let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1); |
| 19226 | let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = read_intra_mode_sub8( |
| 19227 | dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, |
| 19228 | filter_intra_size_class_rect(bw, bh) |
| 19229 | .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"), |
| 19230 | skip_ctx, allow_intrabc, lmi.0, lmi.1, bw / 4, bh / 4, fctx, |
| 19231 | )?; |
| 19232 | leaf_modes[i] = mode; |
| 19233 | leaf_skips[i] = skip; |
| 19234 | neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode); |
| 19235 | let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); |
| 19236 | if let Some(dv) = intrabc { |
| 19237 | // lane-av1txr: an intrabc `BLOCK_4X8`/`BLOCK_8X4` leaf. The |
| 19238 | // prediction is a frame copy at the DV and the residual reads the |
| 19239 | // INTER `LumaRect8x4` set -- but with `TxMode::Select` the leaf |
| 19240 | // reads the INTER var-tx tree, exactly like every other intrabc |
| 19241 | // block: libaom's `block_signals_txsize` is `bsize > BLOCK_4X4` |
| 19242 | // (`blockd.h:1027`), TRUE at `BLOCK_4X8`/`BLOCK_8X4`, so |
| 19243 | // `parse_decode_block` sends an unskipped `inter_block_tx` block |
| 19244 | // (intrabc counts, `is_inter_block`) of a signalling bsize into |
| 19245 | // `read_tx_size_vartx` over `max_txsize_rect_lookup[BLOCK_4X8] == |
| 19246 | // TX_4X8`; only `BLOCK_4X4` reads no tx symbol at all. Measured on |
| 19247 | // `warped.obu` mi (37,62): reading NO symbol here left the |
| 19248 | // arithmetic decoder one symbol short and desynced the very next |
| 19249 | // block's `skip` (ours 60320 vs aomdec 48630, class |
| 19250 | // `symbol-consumption-gap`). |
| 19251 | let (px, py) = (lmi.1 * MI, lmi.0 * MI); |
| 19252 | let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 19253 | flush_recon(fctx, y, u, v); |
| 19254 | let mut luma_leaves: Vec<(usize, usize, usize, usize)> = Vec::new(); |
| 19255 | if tx_select && !skip { |
| 19256 | // `max_block_wide`/`max_block_high`: the frame's own mi grid, |
| 19257 | // so a leaf hanging over the right/bottom edge reads no split |
| 19258 | // symbol for the units outside it (as in `decode_block`). |
| 19259 | let mi_cols = 2 * y.true_width.div_ceil(8); |
| 19260 | let mi_rows = 2 * y.true_height.div_ceil(8); |
| 19261 | let max_w_mi = w_mi.min(mi_cols.saturating_sub(lmi.1)); |
| 19262 | let max_h_mi = h_mi.min(mi_rows.saturating_sub(lmi.0)); |
| 19263 | read_var_tx_size( |
| 19264 | dec, |
| 19265 | cdfs, |
| 19266 | neighbours, |
| 19267 | lmi, |
| 19268 | bw.max(bh), |
| 19269 | (max_w_mi, max_h_mi), |
| 19270 | (bw, bh), |
| 19271 | 0, |
| 19272 | 0, |
| 19273 | 0, |
| 19274 | &mut luma_leaves, |
| 19275 | ); |
| 19276 | hit!(RECT_INTRABC_VARTX_HITS); |
| 19277 | } else { |
| 19278 | luma_leaves.push((0, 0, bw, bh)); |
| 19279 | // The non-var-tx arm: a SKIPPED intrabc leaf (or a frame |
| 19280 | // outside `TxMode::Select`) publishes its own rect transform |
| 19281 | // (`set_txfm_ctxs`'s `skip && is_inter` branch writes the |
| 19282 | // block's own pixels -- the same size here). |
| 19283 | txfm_partition_update_rect(neighbours, lmi, (bw, bh), (bw, bh)); |
| 19284 | } |
| 19285 | // The transform type an intrabc block's CHROMA inherits is the |
| 19286 | // `tx_type_map` entry at the chroma unit's co-located luma |
| 19287 | // position (`av1_get_tx_type`, `blockd.h:1278`), i.e. the FIRST |
| 19288 | // luma unit the tree resolved. |
| 19289 | let single = luma_leaves.len() == 1; |
| 19290 | let mut chroma_tx = TxType::DctDct; |
| 19291 | let mut grid = Grid::Zero(bw * bh); |
| 19292 | for (li, &(tu_row, tu_col, tw, th)) in luma_leaves.iter().enumerate() { |
| 19293 | let tu_mi = (lmi.0 + tu_row, lmi.1 + tu_col); |
| 19294 | let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI); |
| 19295 | let tu_reach = if single { |
| 19296 | reach |
| 19297 | } else { |
| 19298 | tu_reach( |
| 19299 | bw, bh, tu_px - px, tu_py - py, tw, reach, px, py, y.width, y.height, fctx, |
| 19300 | ) |
| 19301 | }; |
| 19302 | let mut yb = vec![0u16; tw * th]; |
| 19303 | mc::predict_with_filter( |
| 19304 | &y.data, y.width, y.true_width, y.true_height, |
| 19305 | mv_to_q4(tu_px, dv.1, 0), mv_to_q4(tu_py, dv.0, 0), |
| 19306 | tw, th, mc::InterpFilterKind::Bilinear, &mut yb, fctx, |
| 19307 | ); |
| 19308 | set_palette_pred(yb, fctx); |
| 19309 | let tu_grid = if skip { |
| 19310 | let zeros = Grid::Zero(tw * th); |
| 19311 | if (tw, th) == (4, 4) { |
| 19312 | push_intra(0, tu_px, tu_py, 4, DC_PRED, 0, tu_reach, &zeros, None, None, smooth_neighbor, fctx); |
| 19313 | } else { |
| 19314 | push_intra_rect(0, tu_px, tu_py, tw, th, DC_PRED, 0, tu_reach, &zeros, None, None, smooth_neighbor, fctx); |
| 19315 | } |
| 19316 | zeros |
| 19317 | } else { |
| 19318 | // A unit smaller than its own block (the var-tx split) |
| 19319 | // reads its `txb_skip_ctx` off the neighbours; the |
| 19320 | // whole-leaf unit's `plane_bsize == txsize_to_bsize` fixes |
| 19321 | // it at 0. |
| 19322 | let (set, tu_scan, around, skip_ctx) = if (tw, th) == (4, 4) { |
| 19323 | ( |
| 19324 | inter_txbset_for(4, reduced_tx_set), |
| 19325 | scan4, |
| 19326 | neighbours.around_mi(tu_mi, 4)[0], |
| 19327 | neighbours.luma_skip_ctx(tu_mi, 1), |
| 19328 | ) |
| 19329 | } else { |
| 19330 | ( |
| 19331 | if reduced_tx_set { |
| 19332 | TxbSet::LumaRect8x4Inter |
| 19333 | } else { |
| 19334 | TxbSet::LumaRect8x4InterSet1 |
| 19335 | }, |
| 19336 | scan, |
| 19337 | neighbours.around_mi_rect(tu_mi, tw, th)[0], |
| 19338 | 0, |
| 19339 | ) |
| 19340 | }; |
| 19341 | let mut coding = cdfs.txb(set, DC_PRED); |
| 19342 | let (levels, tx_type) = read_coeffs_rect( |
| 19343 | dec, &mut coding, tu_scan, tw, th, skip_ctx, dc_sign_ctx(around.2), |
| 19344 | TxType::DctDct, |
| 19345 | )?; |
| 19346 | if li == 0 { |
| 19347 | chroma_tx = tx_type; |
| 19348 | fctx.luma_tx_type.with(|c| c.set(tx_type)); |
| 19349 | } |
| 19350 | let residual = dequant_and_inverse_typed_wh( |
| 19351 | &levels, tw, th, crate::decode::bit_depth(fctx), block_q_idx(fctx), |
| 19352 | plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type, |
| 19353 | block_iqmatrix(fctx, 0, tw, th, tx_type), |
| 19354 | ); |
| 19355 | if (tw, th) == (4, 4) { |
| 19356 | push_intra(0, tu_px, tu_py, 4, DC_PRED, 0, tu_reach, &residual, None, None, smooth_neighbor, fctx); |
| 19357 | } else { |
| 19358 | push_intra_rect(0, tu_px, tu_py, tw, th, DC_PRED, 0, tu_reach, &residual, None, None, smooth_neighbor, fctx); |
| 19359 | } |
| 19360 | levels |
| 19361 | }; |
| 19362 | if single { |
| 19363 | grid = tu_grid; |
| 19364 | } else { |
| 19365 | // Per-unit neighbour state, the same shape the intra rect |
| 19366 | // leaf's own split path runs (`decode_leaf8`'s depth-1 |
| 19367 | // loop): a transform unit inside a block is not a block at |
| 19368 | // that position. |
| 19369 | neighbours.record_mi_luma(tu_mi, 4, &tu_grid); |
| 19370 | } |
| 19371 | } |
| 19372 | if single { |
| 19373 | let state = neighbour_state(&grid); |
| 19374 | for cell in 0..h_mi { |
| 19375 | if lmi.0 + cell < neighbours.mi_rows { |
| 19376 | neighbours.left[lmi.0 + cell][0] = state; |
| 19377 | } |
| 19378 | } |
| 19379 | for cell in 0..w_mi { |
| 19380 | if lmi.1 + cell < neighbours.mi_cols { |
| 19381 | neighbours.above[lmi.1 + cell][0] = state; |
| 19382 | } |
| 19383 | } |
| 19384 | } |
| 19385 | neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); |
| 19386 | neighbours.fill_lf_grid_rect( |
| 19387 | lmi, |
| 19388 | w_mi, |
| 19389 | h_mi, |
| 19390 | if single { bw as u8 } else { 4 }, |
| 19391 | if single { bh as u8 } else { 4 }, |
| 19392 | 0, |
| 19393 | fctx, |
| 19394 | ); |
| 19395 | // `record_intrabc_mi` publishes a square `n4`x`n4` footprint; a |
| 19396 | // 4x8/8x4 leaf needs its true `w_mi`x`h_mi` (lane-av1txr). |
| 19397 | record_intrabc_mi_rect(lmi.0, lmi.1, w_mi, h_mi, Some(dv), neighbours, fctx); |
| 19398 | if has_chroma { |
| 19399 | // See [`decode_leaf_split4`]: an intrabc block's chroma |
| 19400 | // inherits the luma transform type. |
| 19401 | fctx.intrabc_chroma_tx.with(|c| c.set(Some(chroma_tx))); |
| 19402 | if chroma_444 { |
| 19403 | // lane-av1-444: this leaf codes its OWN rect chroma unit |
| 19404 | // right here (frame copy at the DV); no group tail. |
| 19405 | sub8_leaf_chroma444( |
| 19406 | dec, cdfs, neighbours, lmi, bw, bh, DC_PRED, None, skip, |
| 19407 | Some(dv), y, u, v, scan4, base_q_idx, |
| 19408 | neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, |
| 19409 | )?; |
| 19410 | last_uv444 = DC_PRED; |
| 19411 | } else { |
| 19412 | last_uv = Some((DC_PRED, 0, None)); |
| 19413 | last_intrabc = Some(dv); |
| 19414 | } |
| 19415 | } |
| 19416 | continue; |
| 19417 | } |
| 19418 | if filter_intra.is_some() { |
| 19419 | // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over |
| 19420 | // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the |
| 19421 | // same `reconstruct_rect`/`reconstruct` calls below -- and under |
| 19422 | // a split transform, per 4x4 unit with that unit's own edge, |
| 19423 | // which is exactly what the depth-1 loop already does. |
| 19424 | hit!(FILTER_INTRA_RECT_HITS); |
| 19425 | hit!(FILTER_INTRA_RECT_SUB8_HITS); |
| 19426 | } |
| 19427 | // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4 |
| 19428 | // leaf too, and is read for every intra block, skipped or not. Its |
| 19429 | // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` -- |
| 19430 | // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the |
| 19431 | // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol |
| 19432 | // `tx_size_cat2` the 32x16 strips read -- with the rect context |
| 19433 | // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh). |
| 19434 | // Missing this read consumed one symbol fewer than the encoder wrote |
| 19435 | // and desynced the tile at the very first rect leaf (class |
| 19436 | // `symbol-consumption-gap`). |
| 19437 | // lane-av1mix: libaom `read_tx_size`'s FIRST line |
| 19438 | // (`decodeframe.c:1203`, `if (xd->lossless[...]) return TX_4X4`) |
| 19439 | // fires before the `TX_MODE_SELECT` test, so a lossless-segment leaf |
| 19440 | // codes NO depth symbol even in `TxMode::Select` -- the mixed-lossless |
| 19441 | // frame's sub8 leaves forked exactly here (ours read the symbol at |
| 19442 | // (12477,50864) bit 3011, the oracle's all_zero used it). |
| 19443 | let depth = if tx_select && !lossless(fctx) { |
| 19444 | // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect |
| 19445 | // reader already does. |
| 19446 | let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); |
| 19447 | dec.symbol(&mut cdfs.tx_size_cat0[ctx]) |
| 19448 | } else { |
| 19449 | 0 |
| 19450 | }; |
| 19451 | if depth != 0 { |
| 19452 | hit!(TX_DEPTH_HITS); |
| 19453 | hit!(RECT8_SPLIT_TX_HITS); |
| 19454 | } |
| 19455 | if smooth_neighbor { |
| 19456 | hit!(SMOOTH_LUMA_HITS); |
| 19457 | } |
| 19458 | let (px, py) = (lmi.1 * MI, lmi.0 * MI); |
| 19459 | let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); |
| 19460 | // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into |
| 19461 | // two 4x4 transform units along its long axis, each predicted from |
| 19462 | // the previous unit's reconstruction and reading its own `txb_skip` |
| 19463 | // context -- `decode_leaf8`'s own depth-1 loop, two units instead of |
| 19464 | // four. The per-TU path writes its own neighbour state, so the |
| 19465 | // block-level write below is skipped for it. |
| 19466 | let split = depth != 0 || lossless(fctx); |
| 19467 | // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this |
| 19468 | // leaf -- the size the `tx_depth` symbol resolved (depth 1 -> TX_4X4, |
| 19469 | // else the leaf's own rect transform), published over the leaf's own |
| 19470 | // mi span. An intrabc block's `txfm_partition_context` reads these |
| 19471 | // bands, and the key-frame sub-8x8 leaves had no write at all: |
| 19472 | // `warped.obu` mi (37,62) read a stale 8 where aomdec read 4 (ctx 18 |
| 19473 | // vs 19) and the tile desynced (class `context-band-not-published`). |
| 19474 | let (ctx_tx_w, ctx_tx_h) = if split { (4, 4) } else { (bw, bh) }; |
| 19475 | txfm_partition_update_rect(neighbours, lmi, (ctx_tx_w, ctx_tx_h), (bw, bh)); |
| 19476 | if split { |
| 19477 | let mut done = 0usize; |
| 19478 | for tu in 0..2usize { |
| 19479 | let tu_mi = if vert { |
| 19480 | (lmi.0 + tu, lmi.1) |
| 19481 | } else { |
| 19482 | (lmi.0, lmi.1 + tu) |
| 19483 | }; |
| 19484 | let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI); |
| 19485 | let tu_around = neighbours.around_mi(tu_mi, 4)[0]; |
| 19486 | // Same per-TU rule as every other split-transform site |
| 19487 | // (lane-palette2 r12): a transform unit inside a block is not |
| 19488 | // a block at that position, so its reach comes from the |
| 19489 | // block's own row, offset by the unit's position. |
| 19490 | let tu_reach = tu_reach( |
| 19491 | bw, |
| 19492 | bh, |
| 19493 | tu_px - px, |
| 19494 | tu_py - py, |
| 19495 | 4, |
| 19496 | reach, |
| 19497 | px, |
| 19498 | py, |
| 19499 | y.width, |
| 19500 | y.height, fctx, |
| 19501 | ); |
| 19502 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); |
| 19503 | if skip { |
| 19504 | // A skipped leaf still predicts per transform unit: the |
| 19505 | // second 4x4 takes its above/left edge from the first |
| 19506 | // one's reconstruction, which is NOT what a single 4x8 |
| 19507 | // prediction of the same mode produces. |
| 19508 | let zeros = vec![0i32; 16]; |
| 19509 | push_intra(0, |
| 19510 | tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None, |
| 19511 | filter_intra, smooth_neighbor, fctx, |
| 19512 | ); |
| 19513 | neighbours.record_mi_luma(tu_mi, 4, &zeros); |
| 19514 | continue; |
| 19515 | } |
| 19516 | let tu_grid = read_plane( |
| 19517 | dec, |
| 19518 | cdfs, |
| 19519 | if reduced_tx_set { |
| 19520 | TxbSet::Luma4 |
| 19521 | } else { |
| 19522 | TxbSet::Luma4Set1 |
| 19523 | }, |
| 19524 | scan4, |
| 19525 | 0, |
| 19526 | tu_around, |
| 19527 | mode, |
| 19528 | mode, |
| 19529 | angle_delta_y, |
| 19530 | tu_reach, |
| 19531 | y, |
| 19532 | tu_px, |
| 19533 | tu_py, |
| 19534 | 4, |
| 19535 | TX4, |
| 19536 | base_q_idx, |
| 19537 | None, |
| 19538 | filter_intra, |
| 19539 | Some(tu_skip_ctx), |
| 19540 | smooth_neighbor, fctx, |
| 19541 | )?; |
| 19542 | if tu_grid.iter().any(|&l| l != 0) { |
| 19543 | done += 1; |
| 19544 | } |
| 19545 | neighbours.record_mi_luma(tu_mi, 4, &tu_grid); |
| 19546 | } |
| 19547 | if done > 0 { |
| 19548 | if vert { |
| 19549 | hit!(TX4X8_CODED_HITS); |
| 19550 | } else { |
| 19551 | hit!(TX8X4_CODED_HITS); |
| 19552 | } |
| 19553 | } |
| 19554 | neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); |
| 19555 | neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx); |
| 19556 | if has_chroma { |
| 19557 | if chroma_444 { |
| 19558 | // lane-av1-444: the leaf's own rect chroma unit after its |
| 19559 | // split luma (no shared group unit at ss 0/0). |
| 19560 | let (uv_mode, _, alpha) = |
| 19561 | chroma.expect("4:4:4 reads uv_mode on every leaf"); |
| 19562 | sub8_leaf_chroma444( |
| 19563 | dec, cdfs, neighbours, lmi, bw, bh, uv_mode, alpha, skip, |
| 19564 | None, y, u, v, scan4, base_q_idx, |
| 19565 | neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, |
| 19566 | )?; |
| 19567 | last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 19568 | } else { |
| 19569 | last_uv = chroma; |
| 19570 | } |
| 19571 | } |
| 19572 | continue; |
| 19573 | } |
| 19574 | let grid = if skip { |
| 19575 | let zeros = Grid::Zero(bw * bh); |
| 19576 | push_intra_rect(0, |
| 19577 | px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra, |
| 19578 | smooth_neighbor, fctx, |
| 19579 | ); |
| 19580 | zeros |
| 19581 | } else { |
| 19582 | // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's |
| 19583 | // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx` |
| 19584 | // at 0 -- see `decode_leaf_split4`'s own note. |
| 19585 | let around = neighbours.around_mi_rect(lmi, bw, bh)[0]; |
| 19586 | let set = if reduced_tx_set { |
| 19587 | TxbSet::LumaRect4x8 |
| 19588 | } else { |
| 19589 | TxbSet::LumaRect4x8Set1 |
| 19590 | }; |
| 19591 | let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); |
| 19592 | let (levels, tx_type) = read_coeffs_rect( |
| 19593 | dec, |
| 19594 | &mut coding, |
| 19595 | scan, |
| 19596 | bw, |
| 19597 | bh, |
| 19598 | 0, |
| 19599 | dc_sign_ctx(around.2), |
| 19600 | TxType::DctDct, |
| 19601 | )?; |
| 19602 | if levels.iter().any(|&l| l != 0) { |
| 19603 | if vert { |
| 19604 | hit!(TX4X8_CODED_HITS); |
| 19605 | } else { |
| 19606 | hit!(TX8X4_CODED_HITS); |
| 19607 | } |
| 19608 | } |
| 19609 | let residual = dequant_and_inverse_typed_wh( |
| 19610 | &levels, |
| 19611 | bw, |
| 19612 | bh, |
| 19613 | crate::decode::bit_depth(fctx), |
| 19614 | // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at |
| 19615 | // every other dequant site (class `parsed-then-discarded`). |
| 19616 | block_q_idx(fctx), |
| 19617 | plane_q_delta(0, fctx).0, |
| 19618 | plane_q_delta(0, fctx).1, |
| 19619 | tx_type, |
| 19620 | block_iqmatrix(fctx, 0, bw, bh, tx_type), |
| 19621 | ); |
| 19622 | push_intra_rect(0, |
| 19623 | px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra, |
| 19624 | smooth_neighbor, fctx, |
| 19625 | ); |
| 19626 | levels |
| 19627 | }; |
| 19628 | // Plane 0's per-TU coefficient context over this leaf's own mi span |
| 19629 | // (`record_mi_luma`'s rect twin -- the chroma planes are written once |
| 19630 | // for the whole 8x8 group below). |
| 19631 | let state = neighbour_state(&grid); |
| 19632 | for cell in 0..h_mi { |
| 19633 | if lmi.0 + cell < neighbours.mi_rows { |
| 19634 | neighbours.left[lmi.0 + cell][0] = state; |
| 19635 | } |
| 19636 | } |
| 19637 | for cell in 0..w_mi { |
| 19638 | if lmi.1 + cell < neighbours.mi_cols { |
| 19639 | neighbours.above[lmi.1 + cell][0] = state; |
| 19640 | } |
| 19641 | } |
| 19642 | neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); |
| 19643 | let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) }; |
| 19644 | neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx); |
| 19645 | if has_chroma { |
| 19646 | if chroma_444 { |
| 19647 | // lane-av1-444: the leaf's own rect chroma unit after its |
| 19648 | // luma (no shared group unit at ss 0/0). |
| 19649 | let (uv_mode, _, alpha) = |
| 19650 | chroma.expect("4:4:4 reads uv_mode on every leaf"); |
| 19651 | sub8_leaf_chroma444( |
| 19652 | dec, cdfs, neighbours, lmi, bw, bh, uv_mode, alpha, skip, |
| 19653 | None, y, u, v, scan4, base_q_idx, |
| 19654 | neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, |
| 19655 | )?; |
| 19656 | last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 19657 | } else { |
| 19658 | last_uv = chroma; |
| 19659 | } |
| 19660 | } |
| 19661 | } |
| 19662 | // lane-av1mono: a monochrome frame codes no chroma at all -- no |
| 19663 | // `uv_mode` was read ([`read_intra_mode_sub8`] folds the plane count in), |
| 19664 | // so there is no chroma to reconstruct and no chroma coefficient to read. |
| 19665 | let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) { |
| 19666 | (Grid::Zero(16), Grid::Zero(16)) |
| 19667 | } else if chroma_444 { |
| 19668 | // lane-av1-444: every leaf coded and reconstructed its own chroma in |
| 19669 | // the loop above; only the coarse slots remain (last leaf's mode). |
| 19670 | neighbours.above_uv_mode[c] = last_uv444; |
| 19671 | neighbours.left_uv_mode[r] = last_uv444; |
| 19672 | (Grid::Zero(16), Grid::Zero(16)) |
| 19673 | } else { |
| 19674 | let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); |
| 19675 | let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx)); |
| 19676 | let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx); |
| 19677 | let (uv_mode, angle_delta_uv, alpha) = |
| 19678 | last_uv.expect("i==1 always sets has_chroma, so chroma is always Some"); |
| 19679 | let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; |
| 19680 | neighbours.above_uv_mode[c] = uv_predict_mode; |
| 19681 | neighbours.left_uv_mode[r] = uv_predict_mode; |
| 19682 | neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); |
| 19683 | let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] && last_intrabc.is_none() { |
| 19684 | // A skipped chroma block still gets its CfL contribution: libaom's |
| 19685 | // `predict_and_reconstruct_intra_block` calls `cfl_predict_block` |
| 19686 | // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719) |
| 19687 | // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is |
| 19688 | // added -- `skip_txfm` only drops the residual, never the alpha. |
| 19689 | // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the |
| 19690 | // merge keeps one fix and feeds both lanes' counters so neither of |
| 19691 | // their gates goes vacuous. |
| 19692 | let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); |
| 19693 | if alpha.is_some() { |
| 19694 | hit!(CHROMA_SKIP_CFL_HITS); |
| 19695 | hit!(SKIP_CFL_HITS); |
| 19696 | } |
| 19697 | 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); |
| 19698 | 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); |
| 19699 | // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma |
| 19700 | // coefficient, so it never consults the inherited luma transform type |
| 19701 | // -- but an intrabc chroma-reference leaf did arm |
| 19702 | // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient |
| 19703 | // branches below are the only ones that disarm it. Left armed, the slot |
| 19704 | // picks the NEXT block's chroma scan and inverse transform (class |
| 19705 | // arm-without-clear-on-a-skip-route). Counted so a gate can tell a |
| 19706 | // stream that reaches this route from one that never does. |
| 19707 | if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { |
| 19708 | hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); |
| 19709 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 19710 | } |
| 19711 | (Grid::Zero(16), Grid::Zero(16)) |
| 19712 | } else if let Some(dv) = last_intrabc { |
| 19713 | // A 4:2:0 `BLOCK_4X8`/`BLOCK_8X4` leaf maps to a clamped chroma |
| 19714 | // `BLOCK_4X4` (`get_plane_block_size`, blockd.h:1184; `set_plane_n4`, |
| 19715 | // av1_common_int.h:1344). The chroma reference is still the whole |
| 19716 | // 8x8 group's 4x4 plane block at `(cpx, cpy)`, so prediction uses the |
| 19717 | // group's destination origin, not the odd-mi leaf's nominal 2x4/4x2 |
| 19718 | // extent. The old route treated a skipped intrabc leaf as skipped |
| 19719 | // intra and predicted this block with DC, first differing at |
| 19720 | // mi(46,52), U(104,92), while consuming identical symbols. |
| 19721 | // `decode_reconstruct_tx` reads no chroma coefficients for a skipped |
| 19722 | // intrabc block, but an unskipped one reads the ordinary Chroma4 |
| 19723 | // tables; chroma inherits no coded tx_type of its own. |
| 19724 | let mut ub = vec![0u16; 16]; |
| 19725 | mc::predict_with_filter( |
| 19726 | &u.data, u.width, u.true_width, u.true_height, |
| 19727 | mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_x(fctx)), |
| 19728 | 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx, |
| 19729 | ); |
| 19730 | let mut vb = vec![0u16; 16]; |
| 19731 | mc::predict_with_filter( |
| 19732 | &v.data, v.width, v.true_width, v.true_height, |
| 19733 | mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_x(fctx)), |
| 19734 | 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx, |
| 19735 | ); |
| 19736 | if leaf_skips[1] { |
| 19737 | // `skip_txfm` still reconstructs an intrabc prediction, but |
| 19738 | // libaom's `decode_reconstruct_tx` reads NO chroma coefficients. |
| 19739 | // The ordinary skipped-intra arm above is therefore not valid for |
| 19740 | // an intrabc leaf: use the copied, clamped 4x4 prediction directly. |
| 19741 | push_mc_rect( |
| 19742 | 1, cpx, cpy, 4, 4, 4, Pred::Inline(&ub, 4), |
| 19743 | &ZERO_RESIDUAL[..16], fctx, |
| 19744 | ); |
| 19745 | push_mc_rect( |
| 19746 | 2, cpx, cpy, 4, 4, 4, Pred::Inline(&vb, 4), |
| 19747 | &ZERO_RESIDUAL[..16], fctx, |
| 19748 | ); |
| 19749 | hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); |
| 19750 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 19751 | (Grid::Zero(16), Grid::Zero(16)) |
| 19752 | } else { |
| 19753 | let chroma_around = neighbours.around_mi(leaf_mi, 8); |
| 19754 | set_palette_pred(ub, fctx); |
| 19755 | let ug = read_plane( |
| 19756 | dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED, |
| 19757 | 0, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, |
| 19758 | None, None, None, smooth_neighbor_uv, fctx, |
| 19759 | )?; |
| 19760 | set_palette_pred(vb, fctx); |
| 19761 | let vg = read_plane( |
| 19762 | dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED, |
| 19763 | 0, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, |
| 19764 | None, None, None, smooth_neighbor_uv, fctx, |
| 19765 | )?; |
| 19766 | fctx.intrabc_chroma_tx.with(|c| c.set(None)); |
| 19767 | (ug, vg) |
| 19768 | } |
| 19769 | } else { |
| 19770 | let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); |
| 19771 | let chroma_around = neighbours.around_mi(leaf_mi, 8); |
| 19772 | let ug = read_plane( |
| 19773 | dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode, |
| 19774 | angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, |
| 19775 | alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, |
| 19776 | )?; |
| 19777 | let vg = read_plane( |
| 19778 | dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode, |
| 19779 | angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, |
| 19780 | alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx, |
| 19781 | )?; |
| 19782 | (ug, vg) |
| 19783 | }; |
| 19784 | (u_grid, v_grid) |
| 19785 | }; |
| 19786 | // `update_partition_context` at the 8x8 level writes |
| 19787 | // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8 |
| 19788 | // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}` |
| 19789 | // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which |
| 19790 | // `partition_ctx_mi` reads back off these side values. |
| 19791 | for cell in 0..2 { |
| 19792 | neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8; |
| 19793 | neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8; |
| 19794 | } |
| 19795 | // lane-av1-444: at 4:4:4 [`sub8_leaf_chroma444`] already stamped each |
| 19796 | // leaf's own span as it decoded; these placeholder grids carry no state. |
| 19797 | if !chroma_444 { |
| 19798 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 19799 | let bound_h = round_up_even(neighbours.mi_rows); |
| 19800 | let bound_w = round_up_even(neighbours.mi_cols); |
| 19801 | let u_state = neighbour_state(&u_grid); |
| 19802 | let v_state = neighbour_state(&v_grid); |
| 19803 | for cell in 0..2usize { |
| 19804 | if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) { |
| 19805 | neighbours.left[leaf_mi.0 + cell][1] = u_state; |
| 19806 | neighbours.left[leaf_mi.0 + cell][2] = v_state; |
| 19807 | } |
| 19808 | if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) { |
| 19809 | neighbours.above[leaf_mi.1 + cell][1] = u_state; |
| 19810 | neighbours.above[leaf_mi.1 + cell][2] = v_state; |
| 19811 | } |
| 19812 | } |
| 19813 | } |
| 19814 | // lane-dkey (same clear as `decode_leaf_split4`): a sub-8x8 leaf can never use palette (`av1_allow_palette` |
| 19815 | // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its |
| 19816 | // `palette_size` is 0 in every one of these mi cells, so the NEXT block's |
| 19817 | // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder |
| 19818 | // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette |
| 19819 | // block above a 4x4 group left its size/colours standing in the mi-granular |
| 19820 | // bands: the block below the group read `palette_y_mode` off CDF row 1 |
| 19821 | // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a |
| 19822 | // palette libaom never coded, and then skipped the `use_filter_intra` |
| 19823 | // symbol that a palette block has none of -- one symbol short, tile |
| 19824 | // desynced. Publishing the group's own zeros is the clear. |
| 19825 | neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]); |
| 19826 | neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]); |
| 19827 | // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the |
| 19828 | // bottom one (the second under HORZ, the left one under VERT), the one a |
| 19829 | // neighbour to the right sees is the top-right (the second under VERT). |
| 19830 | Ok(if vert { |
| 19831 | (leaf_modes[0], leaf_modes[1]) |
| 19832 | } else { |
| 19833 | (leaf_modes[1], leaf_modes[0]) |
| 19834 | }) |
| 19835 | } |
| 19836 | |
| 19837 | /// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary |
| 19838 | /// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2` |
| 19839 | /// (mod 8) reuse the same table. |
| 19840 | const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [ |
| 19841 | [(-1, 1), (-2, 2)], |
| 19842 | [(0, 1), (-1, 2)], |
| 19843 | [(0, 1), (0, 2)], |
| 19844 | [(0, 1), (1, 2)], |
| 19845 | [(1, 1), (2, 2)], |
| 19846 | [(1, 0), (2, 1)], |
| 19847 | [(1, 0), (2, 0)], |
| 19848 | [(1, 0), (2, -1)], |
| 19849 | ]; |
| 19850 | /// A neighbour tap outside the frame's true extent -- `constrain` reads this |
| 19851 | /// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`). |
| 19852 | const CDEF_VERY_LARGE: i32 = 0x4000; |
| 19853 | const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]]; |
| 19854 | const CDEF_SEC_TAPS: [i32; 2] = [2, 1]; |
| 19855 | |
| 19856 | fn cdef_msb(x: i32) -> i32 { |
| 19857 | 31 - x.leading_zeros() as i32 |
| 19858 | } |
| 19859 | |
| 19860 | /// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the |
| 19861 | /// centre sample a filter tap is allowed to contribute. |
| 19862 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 19863 | fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 { |
| 19864 | if threshold == 0 { |
| 19865 | return 0; |
| 19866 | } |
| 19867 | cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping)) |
| 19868 | } |
| 19869 | |
| 19870 | /// `constrain`'s damping shift: a function of the block's threshold and |
| 19871 | /// damping alone, so the filter loop computes it once per block instead of |
| 19872 | /// the `leading_zeros` + branch it used to do twice per tap read. |
| 19873 | fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 { |
| 19874 | (damping - cdef_msb(threshold)).max(0) |
| 19875 | } |
| 19876 | |
| 19877 | /// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is |
| 19878 | /// non-zero on every call (the caller only filters when its strength is). |
| 19879 | fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 { |
| 19880 | let a = diff.abs(); |
| 19881 | diff.signum() * (threshold - (a >> shift)).clamp(0, a) |
| 19882 | } |
| 19883 | |
| 19884 | /// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads |
| 19885 | /// lies inside its own samples grown by this much. |
| 19886 | const CDEF_BORDER: usize = 2; |
| 19887 | |
| 19888 | /// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the |
| 19889 | /// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row |
| 19890 | /// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops |
| 19891 | /// index a small contiguous window instead of re-deriving the frame-bounds |
| 19892 | /// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get |
| 19893 | /// `CDEF_VERY_LARGE`, exactly as the per-sample closure did. |
| 19894 | fn cdef_gather( |
| 19895 | src: &[u16], |
| 19896 | stride: usize, |
| 19897 | true_w: usize, |
| 19898 | true_h: usize, |
| 19899 | ox: usize, |
| 19900 | oy: usize, |
| 19901 | bw: usize, |
| 19902 | bh: usize, |
| 19903 | buf: &mut [i16], |
| 19904 | ) { |
| 19905 | let bstride = bw + 2 * CDEF_BORDER; |
| 19906 | let rows = bh + 2 * CDEF_BORDER; |
| 19907 | if oy >= CDEF_BORDER |
| 19908 | && ox >= CDEF_BORDER |
| 19909 | && oy + bh + CDEF_BORDER <= true_h |
| 19910 | && ox + bw + CDEF_BORDER <= true_w |
| 19911 | { |
| 19912 | // Interior block: every tap is inside the frame, so the whole window |
| 19913 | // is `rows` contiguous runs. |
| 19914 | for r in 0..rows { |
| 19915 | let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER); |
| 19916 | let src_row = &src[s0..s0 + bstride]; |
| 19917 | let dst_row = &mut buf[r * bstride..r * bstride + bstride]; |
| 19918 | for (d, &v) in dst_row.iter_mut().zip(src_row) { |
| 19919 | *d = v as i16; |
| 19920 | } |
| 19921 | } |
| 19922 | return; |
| 19923 | } |
| 19924 | for r in 0..rows { |
| 19925 | let ny = oy as isize + r as isize - CDEF_BORDER as isize; |
| 19926 | for c in 0..bstride { |
| 19927 | let nx = ox as isize + c as isize - CDEF_BORDER as isize; |
| 19928 | buf[r * bstride + c] = |
| 19929 | if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w { |
| 19930 | CDEF_VERY_LARGE as i16 |
| 19931 | } else { |
| 19932 | src[ny as usize * stride + nx as usize] as i16 |
| 19933 | }; |
| 19934 | } |
| 19935 | } |
| 19936 | } |
| 19937 | |
| 19938 | /// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each |
| 19939 | /// array takes the row, its reverse, its pairwise sums or its total added |
| 19940 | /// into consecutive slots, so the 512 scalar read-modify-writes on i64 the |
| 19941 | /// per-sample form did become a handful of lane-wide adds per row. i32 is |
| 19942 | /// exact here: every partial is a sum of at most eight values in -128..127, |
| 19943 | /// and slot 15 exists only so an eight-lane store at offset 7 fits. |
| 19944 | fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] { |
| 19945 | fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) { |
| 19946 | for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) { |
| 19947 | *d += x; |
| 19948 | } |
| 19949 | } |
| 19950 | let mut partial = [[0i32; 16]; 8]; |
| 19951 | for i in 0..8usize { |
| 19952 | let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER; |
| 19953 | // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before |
| 19954 | // accumulating, same as `constrain`'s threshold shift. |
| 19955 | let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128); |
| 19956 | let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]); |
| 19957 | let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]); |
| 19958 | let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]); |
| 19959 | let (p, rest) = partial.split_at_mut(1); |
| 19960 | add_at(&mut p[0], i, &row); // partial[0][i + j] |
| 19961 | add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2] |
| 19962 | rest[1][i] = row.iter().sum(); // partial[2][i] |
| 19963 | add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2] |
| 19964 | add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j] |
| 19965 | add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j] |
| 19966 | add_at(&mut rest[5], 0, &row); // partial[6][j] |
| 19967 | add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j] |
| 19968 | } |
| 19969 | partial |
| 19970 | } |
| 19971 | |
| 19972 | /// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant |
| 19973 | /// direction of an 8x8 luma window and the variance gap between it and its |
| 19974 | /// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the |
| 19975 | /// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`). |
| 19976 | fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) { |
| 19977 | const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105]; |
| 19978 | #[cfg(target_arch = "x86_64")] |
| 19979 | let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 { |
| 19980 | // SAFETY: reached only when the CPU reports avx2; the kernel reads |
| 19981 | // the same eight rows of eight samples the scalar form does. |
| 19982 | #[allow(unsafe_code)] |
| 19983 | unsafe { |
| 19984 | cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift) |
| 19985 | } |
| 19986 | } else { |
| 19987 | cdef_find_dir_partials(win, bstride, coeff_shift) |
| 19988 | }; |
| 19989 | #[cfg(not(target_arch = "x86_64"))] |
| 19990 | let partial = cdef_find_dir_partials(win, bstride, coeff_shift); |
| 19991 | let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) }; |
| 19992 | let mut cost = [0i64; 8]; |
| 19993 | for i in 0..8usize { |
| 19994 | cost[2] += sq(partial[2][i]); |
| 19995 | cost[6] += sq(partial[6][i]); |
| 19996 | } |
| 19997 | cost[2] *= DIV_TABLE[8]; |
| 19998 | cost[6] *= DIV_TABLE[8]; |
| 19999 | for i in 0..7usize { |
| 20000 | cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1]; |
| 20001 | cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1]; |
| 20002 | } |
| 20003 | cost[0] += sq(partial[0][7]) * DIV_TABLE[8]; |
| 20004 | cost[4] += sq(partial[4][7]) * DIV_TABLE[8]; |
| 20005 | for i in (1..8).step_by(2) { |
| 20006 | for j in 0..5usize { |
| 20007 | cost[i] += sq(partial[i][3 + j]); |
| 20008 | } |
| 20009 | cost[i] *= DIV_TABLE[8]; |
| 20010 | for j in 0..3usize { |
| 20011 | cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2]; |
| 20012 | } |
| 20013 | } |
| 20014 | let mut best_cost = 0i64; |
| 20015 | let mut best_dir = 0usize; |
| 20016 | for (i, &c) in cost.iter().enumerate() { |
| 20017 | if c > best_cost { |
| 20018 | best_cost = c; |
| 20019 | best_dir = i; |
| 20020 | } |
| 20021 | } |
| 20022 | let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10; |
| 20023 | (best_dir, var as i32) |
| 20024 | } |
| 20025 | |
| 20026 | /// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8 |
| 20027 | /// (high variance gap) gets more deringing than a flat or non-directional |
| 20028 | /// one, only ever applied to the luma primary strength. |
| 20029 | fn cdef_adjust_strength(strength: i32, var: i32) -> i32 { |
| 20030 | if var == 0 { |
| 20031 | return 0; |
| 20032 | } |
| 20033 | let i = if var >> 6 != 0 { |
| 20034 | cdef_msb(var >> 6).min(12) |
| 20035 | } else { |
| 20036 | 0 |
| 20037 | }; |
| 20038 | (strength * (4 + i) + 8) >> 4 |
| 20039 | } |
| 20040 | |
| 20041 | /// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0 |
| 20042 | /// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a |
| 20043 | /// previously-filtered neighbour must never feed this block's own sum). |
| 20044 | #[allow(clippy::too_many_arguments)] |
| 20045 | #[allow(unsafe_code)] |
| 20046 | fn cdef_filter_block( |
| 20047 | src: &[i16], |
| 20048 | dst: &mut PlaneBuf<'static>, |
| 20049 | ox: usize, |
| 20050 | oy: usize, |
| 20051 | bw: usize, |
| 20052 | bh: usize, |
| 20053 | pri_strength: i32, |
| 20054 | sec_strength: i32, |
| 20055 | dir: usize, |
| 20056 | pri_damping: i32, |
| 20057 | sec_damping: i32, |
| 20058 | enable_primary: bool, |
| 20059 | enable_secondary: bool, |
| 20060 | coeff_shift: i32, fctx: &crate::decode::FrameCtx, |
| 20061 | ) { |
| 20062 | let (stride, smax) = (dst.width, sample_max(fctx)); |
| 20063 | #[cfg(target_arch = "x86_64")] |
| 20064 | if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0 |
| 20065 | { |
| 20066 | // SAFETY: reached only when the CPU reports avx2; the kernel reads |
| 20067 | // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the |
| 20068 | // `bh` runs of `bw` samples the scalar form writes. |
| 20069 | unsafe { |
| 20070 | cdef_simd::filter_block_avx2( |
| 20071 | src, |
| 20072 | dst.data.to_mut(), |
| 20073 | stride, |
| 20074 | ox, |
| 20075 | oy, |
| 20076 | bw, |
| 20077 | bh, |
| 20078 | pri_strength, |
| 20079 | sec_strength, |
| 20080 | dir, |
| 20081 | pri_damping, |
| 20082 | sec_damping, |
| 20083 | enable_primary, |
| 20084 | enable_secondary, |
| 20085 | coeff_shift, |
| 20086 | smax, |
| 20087 | ) |
| 20088 | }; |
| 20089 | return; |
| 20090 | } |
| 20091 | cdef_filter_block_scalar( |
| 20092 | src, |
| 20093 | dst.data.to_mut(), |
| 20094 | stride, |
| 20095 | ox, |
| 20096 | oy, |
| 20097 | bw, |
| 20098 | bh, |
| 20099 | pri_strength, |
| 20100 | sec_strength, |
| 20101 | dir, |
| 20102 | pri_damping, |
| 20103 | sec_damping, |
| 20104 | enable_primary, |
| 20105 | enable_secondary, |
| 20106 | coeff_shift, |
| 20107 | smax, |
| 20108 | ); |
| 20109 | } |
| 20110 | |
| 20111 | /// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample, |
| 20112 | /// the form every non-AVX2 build decodes through and the one |
| 20113 | /// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against. |
| 20114 | #[allow(clippy::too_many_arguments)] |
| 20115 | fn cdef_filter_block_scalar( |
| 20116 | src: &[i16], |
| 20117 | dst: &mut [u16], |
| 20118 | stride: usize, |
| 20119 | ox: usize, |
| 20120 | oy: usize, |
| 20121 | bw: usize, |
| 20122 | bh: usize, |
| 20123 | pri_strength: i32, |
| 20124 | sec_strength: i32, |
| 20125 | dir: usize, |
| 20126 | pri_damping: i32, |
| 20127 | sec_damping: i32, |
| 20128 | enable_primary: bool, |
| 20129 | enable_secondary: bool, |
| 20130 | coeff_shift: i32, |
| 20131 | smax: i32, |
| 20132 | ) { |
| 20133 | let clipping_required = enable_primary && enable_secondary; |
| 20134 | // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >> |
| 20135 | // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength` |
| 20136 | // derivative) carries the bit-depth shift, so the tap-set parity bit |
| 20137 | // must be read back above that shift, not off the raw low bit. |
| 20138 | let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize]; |
| 20139 | // Both damping shifts depend only on this block's strengths (spec 7.15.3's |
| 20140 | // `constrain`), so they are resolved here rather than per tap read. |
| 20141 | let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping); |
| 20142 | let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping); |
| 20143 | let bstride = bw + 2 * CDEF_BORDER; |
| 20144 | // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps |
| 20145 | // reaching +-CDEF_BORDER, so every index below is in range by construction. |
| 20146 | let at = |i: i32, j: i32| -> i32 { |
| 20147 | i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize]) |
| 20148 | }; |
| 20149 | let (pri_dir, sec_dir0, sec_dir1) = |
| 20150 | (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]); |
| 20151 | for i in 0..bh { |
| 20152 | for j in 0..bw { |
| 20153 | let (i32i, i32j) = (i as i32, j as i32); |
| 20154 | let x = at(i32i, i32j); |
| 20155 | let mut sum = 0i32; |
| 20156 | let mut max = x; |
| 20157 | let mut min = x; |
| 20158 | for k in 0..2usize { |
| 20159 | if enable_primary { |
| 20160 | let (tr, tc) = pri_dir[k]; |
| 20161 | let p0 = at(i32i + tr, i32j + tc); |
| 20162 | let p1 = at(i32i - tr, i32j - tc); |
| 20163 | sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift); |
| 20164 | sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift); |
| 20165 | if clipping_required { |
| 20166 | if p0 != CDEF_VERY_LARGE { |
| 20167 | max = max.max(p0); |
| 20168 | } |
| 20169 | if p1 != CDEF_VERY_LARGE { |
| 20170 | max = max.max(p1); |
| 20171 | } |
| 20172 | min = min.min(p0).min(p1); |
| 20173 | } |
| 20174 | } |
| 20175 | if enable_secondary { |
| 20176 | let (tr0, tc0) = sec_dir0[k]; |
| 20177 | let (tr1, tc1) = sec_dir1[k]; |
| 20178 | let s0 = at(i32i + tr0, i32j + tc0); |
| 20179 | let s1 = at(i32i - tr0, i32j - tc0); |
| 20180 | let s2 = at(i32i + tr1, i32j + tc1); |
| 20181 | let s3 = at(i32i - tr1, i32j - tc1); |
| 20182 | if clipping_required { |
| 20183 | for s in [s0, s1, s2, s3] { |
| 20184 | if s != CDEF_VERY_LARGE { |
| 20185 | max = max.max(s); |
| 20186 | } |
| 20187 | } |
| 20188 | min = min.min(s0).min(s1).min(s2).min(s3); |
| 20189 | } |
| 20190 | sum += CDEF_SEC_TAPS[k] |
| 20191 | * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift) |
| 20192 | + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift) |
| 20193 | + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift) |
| 20194 | + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift)); |
| 20195 | } |
| 20196 | } |
| 20197 | let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4); |
| 20198 | if clipping_required { |
| 20199 | y = y.clamp(min, max); |
| 20200 | } |
| 20201 | dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16; |
| 20202 | } |
| 20203 | } |
| 20204 | } |
| 20205 | |
| 20206 | /// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar |
| 20207 | /// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic: |
| 20208 | /// the same taps, the same `constrain`, the same `min`/`max` clamp with the |
| 20209 | /// `CDEF_VERY_LARGE` sentinel excluded from the max, the same |
| 20210 | /// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at |
| 20211 | /// a time in 16-bit lanes. |
| 20212 | /// |
| 20213 | /// 16-bit lanes are exact for every value this filter sees: window samples |
| 20214 | /// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in |
| 20215 | /// `i16`, a `constrain` result is bounded by the threshold (at most |
| 20216 | /// `15 << 4`), and the tap-weighted sum by `24 *` that. |
| 20217 | #[cfg(target_arch = "x86_64")] |
| 20218 | #[allow(unsafe_code)] |
| 20219 | #[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract |
| 20220 | mod cdef_simd { |
| 20221 | use super::{ |
| 20222 | cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS, |
| 20223 | CDEF_VERY_LARGE, |
| 20224 | }; |
| 20225 | use std::arch::x86_64::*; |
| 20226 | |
| 20227 | /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit |
| 20228 | /// register (low half = row `i`). |
| 20229 | /// |
| 20230 | /// # Safety |
| 20231 | /// Requires AVX2; `off + bstride + 8` must be inside `w`. |
| 20232 | #[target_feature(enable = "avx2")] |
| 20233 | #[inline] |
| 20234 | unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i { |
| 20235 | let lo = _mm_loadu_si128(w.offset(off).cast()); |
| 20236 | let hi = _mm_loadu_si128(w.offset(off + bstride).cast()); |
| 20237 | _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1) |
| 20238 | } |
| 20239 | |
| 20240 | /// Spec 7.15.3's `constrain`, lane-parallel: |
| 20241 | /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`. |
| 20242 | /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the |
| 20243 | /// clamped magnitude is already 0 where `diff` is). |
| 20244 | /// |
| 20245 | /// # Safety |
| 20246 | /// Requires AVX2. |
| 20247 | #[target_feature(enable = "avx2")] |
| 20248 | #[inline] |
| 20249 | unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i { |
| 20250 | let diff = _mm256_sub_epi16(p, x); |
| 20251 | let a = _mm256_abs_epi16(diff); |
| 20252 | let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift)); |
| 20253 | let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a); |
| 20254 | _mm256_sign_epi16(t, diff) |
| 20255 | } |
| 20256 | |
| 20257 | /// [`super::cdef_find_dir_partials`] in AVX2 (libaom |
| 20258 | /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the |
| 20259 | /// four the auto-vectorised scalar form gets without the feature. |
| 20260 | /// |
| 20261 | /// # Safety |
| 20262 | /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window |
| 20263 | /// grown by `CDEF_BORDER` at row stride `bstride`. |
| 20264 | #[target_feature(enable = "avx2")] |
| 20265 | pub unsafe fn find_dir_partials_avx2( |
| 20266 | win: &[i16], |
| 20267 | bstride: usize, |
| 20268 | coeff_shift: i32, |
| 20269 | ) -> [[i32; 16]; 8] { |
| 20270 | #[target_feature(enable = "avx2")] |
| 20271 | unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) { |
| 20272 | let p = dst.as_mut_ptr().add(off) as *mut __m256i; |
| 20273 | _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v)); |
| 20274 | } |
| 20275 | #[target_feature(enable = "avx2")] |
| 20276 | unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) { |
| 20277 | let p = dst.as_mut_ptr().add(off) as *mut __m128i; |
| 20278 | _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v)); |
| 20279 | } |
| 20280 | let mut partial = [[0i32; 16]; 8]; |
| 20281 | let shift = _mm_cvtsi32_si128(coeff_shift); |
| 20282 | let c128 = _mm256_set1_epi32(128); |
| 20283 | let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0); |
| 20284 | let mut p6 = _mm256_setzero_si256(); |
| 20285 | for i in 0..8usize { |
| 20286 | let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER; |
| 20287 | let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i); |
| 20288 | let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128); |
| 20289 | let rev = _mm256_permutevar8x32_epi32(row, revidx); |
| 20290 | // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the |
| 20291 | // four pairwise sums are the two lanes' low halves joined. |
| 20292 | let h = _mm256_hadd_epi32(row, row); |
| 20293 | let pair = |
| 20294 | _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1)); |
| 20295 | let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11); |
| 20296 | let hs = _mm_hadd_epi32(pair, pair); |
| 20297 | let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs)); |
| 20298 | add8(&mut partial[0], i, row); |
| 20299 | add4(&mut partial[1], i, pair); |
| 20300 | partial[2][i] = total; |
| 20301 | add4(&mut partial[3], i, rpair); |
| 20302 | add8(&mut partial[4], i, rev); |
| 20303 | add8(&mut partial[5], 3 - i / 2, row); |
| 20304 | p6 = _mm256_add_epi32(p6, row); |
| 20305 | add8(&mut partial[7], i / 2, row); |
| 20306 | } |
| 20307 | _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6); |
| 20308 | partial |
| 20309 | } |
| 20310 | |
| 20311 | /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per |
| 20312 | /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for |
| 20313 | /// `bw == 4` the upper four lanes of each half are window samples read |
| 20314 | /// past the row (never past the buffer -- `w` is padded to 256 entries), |
| 20315 | /// computed and then dropped by the 64-bit store. |
| 20316 | /// |
| 20317 | /// # Safety |
| 20318 | /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window |
| 20319 | /// buffer (the tap loads read up to 152 entries past its start, i.e. past |
| 20320 | /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows |
| 20321 | /// of `bw` samples at `(ox, oy)`. |
| 20322 | #[target_feature(enable = "avx2")] |
| 20323 | #[allow(clippy::too_many_arguments)] |
| 20324 | pub unsafe fn filter_block_avx2( |
| 20325 | src: &[i16], |
| 20326 | dst: &mut [u16], |
| 20327 | stride: usize, |
| 20328 | ox: usize, |
| 20329 | oy: usize, |
| 20330 | bw: usize, |
| 20331 | bh: usize, |
| 20332 | pri_strength: i32, |
| 20333 | sec_strength: i32, |
| 20334 | dir: usize, |
| 20335 | pri_damping: i32, |
| 20336 | sec_damping: i32, |
| 20337 | enable_primary: bool, |
| 20338 | enable_secondary: bool, |
| 20339 | coeff_shift: i32, |
| 20340 | smax: i32, |
| 20341 | ) { |
| 20342 | let bstride = bw + 2 * CDEF_BORDER; |
| 20343 | // The caller's window is already `i16` and 256 entries long, so the |
| 20344 | // kernel taps it in place: the largest two-row load is |
| 20345 | // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the |
| 20346 | // 4x4 chroma one, both inside the buffer's zeroed tail. |
| 20347 | let w = src; |
| 20348 | let clipping_required = enable_primary && enable_secondary; |
| 20349 | let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize]; |
| 20350 | let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping)); |
| 20351 | let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping)); |
| 20352 | let pri_thr = _mm256_set1_epi16(pri_strength as i16); |
| 20353 | let sec_thr = _mm256_set1_epi16(sec_strength as i16); |
| 20354 | let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16); |
| 20355 | let zero = _mm256_setzero_si256(); |
| 20356 | let eight = _mm256_set1_epi16(8); |
| 20357 | let smaxv = _mm256_set1_epi16(smax as i16); |
| 20358 | let (pri_dir, sec_dir0, sec_dir1) = |
| 20359 | (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]); |
| 20360 | let wp = w.as_ptr(); |
| 20361 | let bs = bstride as isize; |
| 20362 | let dp = dst.as_mut_ptr(); |
| 20363 | let mut i = 0usize; |
| 20364 | while i < bh { |
| 20365 | let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize; |
| 20366 | let x = ld2(wp, base, bs); |
| 20367 | let mut sum = zero; |
| 20368 | let mut max = x; |
| 20369 | let mut min = x; |
| 20370 | for k in 0..2usize { |
| 20371 | if enable_primary { |
| 20372 | let (tr, tc) = pri_dir[k]; |
| 20373 | let off = tr as isize * bs + tc as isize; |
| 20374 | let p0 = ld2(wp, base + off, bs); |
| 20375 | let p1 = ld2(wp, base - off, bs); |
| 20376 | let tap = _mm256_set1_epi16(pri_taps[k] as i16); |
| 20377 | sum = _mm256_add_epi16( |
| 20378 | sum, |
| 20379 | _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)), |
| 20380 | ); |
| 20381 | sum = _mm256_add_epi16( |
| 20382 | sum, |
| 20383 | _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)), |
| 20384 | ); |
| 20385 | if clipping_required { |
| 20386 | // The sentinel is excluded from the max exactly as the |
| 20387 | // scalar `if p != CDEF_VERY_LARGE` does: masking it to |
| 20388 | // 0 cannot win a max whose seed `x` is non-negative. |
| 20389 | max = _mm256_max_epi16( |
| 20390 | max, |
| 20391 | _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0), |
| 20392 | ); |
| 20393 | max = _mm256_max_epi16( |
| 20394 | max, |
| 20395 | _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1), |
| 20396 | ); |
| 20397 | min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1)); |
| 20398 | } |
| 20399 | } |
| 20400 | if enable_secondary { |
| 20401 | let (tr0, tc0) = sec_dir0[k]; |
| 20402 | let (tr1, tc1) = sec_dir1[k]; |
| 20403 | let off0 = tr0 as isize * bs + tc0 as isize; |
| 20404 | let off1 = tr1 as isize * bs + tc1 as isize; |
| 20405 | let s0 = ld2(wp, base + off0, bs); |
| 20406 | let s1 = ld2(wp, base - off0, bs); |
| 20407 | let s2 = ld2(wp, base + off1, bs); |
| 20408 | let s3 = ld2(wp, base - off1, bs); |
| 20409 | if clipping_required { |
| 20410 | for s in [s0, s1, s2, s3] { |
| 20411 | max = _mm256_max_epi16( |
| 20412 | max, |
| 20413 | _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s), |
| 20414 | ); |
| 20415 | } |
| 20416 | min = _mm256_min_epi16( |
| 20417 | min, |
| 20418 | _mm256_min_epi16( |
| 20419 | _mm256_min_epi16(s0, s1), |
| 20420 | _mm256_min_epi16(s2, s3), |
| 20421 | ), |
| 20422 | ); |
| 20423 | } |
| 20424 | let c = _mm256_add_epi16( |
| 20425 | _mm256_add_epi16( |
| 20426 | constrain(s0, x, sec_thr, sec_shift), |
| 20427 | constrain(s1, x, sec_thr, sec_shift), |
| 20428 | ), |
| 20429 | _mm256_add_epi16( |
| 20430 | constrain(s2, x, sec_thr, sec_shift), |
| 20431 | constrain(s3, x, sec_thr, sec_shift), |
| 20432 | ), |
| 20433 | ); |
| 20434 | sum = _mm256_add_epi16( |
| 20435 | sum, |
| 20436 | _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c), |
| 20437 | ); |
| 20438 | } |
| 20439 | } |
| 20440 | // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`. |
| 20441 | let neg = _mm256_cmpgt_epi16(zero, sum); |
| 20442 | let mut y = _mm256_add_epi16( |
| 20443 | x, |
| 20444 | _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4), |
| 20445 | ); |
| 20446 | if clipping_required { |
| 20447 | y = _mm256_min_epi16(_mm256_max_epi16(y, min), max); |
| 20448 | } |
| 20449 | y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv); |
| 20450 | let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1)); |
| 20451 | let o0 = ((oy + i) * stride + ox) as isize; |
| 20452 | let o1 = o0 + stride as isize; |
| 20453 | if bw == 8 { |
| 20454 | _mm_storeu_si128(dp.offset(o0).cast(), lo); |
| 20455 | _mm_storeu_si128(dp.offset(o1).cast(), hi); |
| 20456 | } else { |
| 20457 | _mm_storel_epi64(dp.offset(o0).cast(), lo); |
| 20458 | _mm_storel_epi64(dp.offset(o1).cast(), hi); |
| 20459 | } |
| 20460 | i += 2; |
| 20461 | } |
| 20462 | } |
| 20463 | } |
| 20464 | |
| 20465 | /// Spec 7.14: the in-loop deblocking filter, applied once per frame after |
| 20466 | /// tile reconstruction and before [`apply_cdef`]. Uniform-level path only -- |
| 20467 | /// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so |
| 20468 | /// every block's level comes from [`LoopFilterParams::level`] plus the |
| 20469 | /// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's |
| 20470 | /// `get_filter_level`, precomputed per-block here rather than cached in a |
| 20471 | /// table the way libaom's `av1_loop_filter_frame_init` does). |
| 20472 | /// |
| 20473 | /// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision) |
| 20474 | /// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels). |
| 20475 | fn apply_deblock( |
| 20476 | y: &mut PlaneBuf<'static>, |
| 20477 | u: &mut PlaneBuf<'static>, |
| 20478 | v: &mut PlaneBuf<'static>, |
| 20479 | lf: &LoopFilterParams, |
| 20480 | n: &Neighbours, |
| 20481 | frame_width: usize, |
| 20482 | frame_height: usize, fctx: &crate::decode::FrameCtx, |
| 20483 | ) { |
| 20484 | // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel |
| 20485 | // mismatch between the raw reconstruction and post-filter output. |
| 20486 | if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") { |
| 20487 | return; |
| 20488 | } |
| 20489 | if lf.level[0] != 0 || lf.level[1] != 0 { |
| 20490 | deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx); |
| 20491 | } |
| 20492 | if lf.level[2] != 0 { |
| 20493 | deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx); |
| 20494 | } |
| 20495 | if lf.level[3] != 0 { |
| 20496 | deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx); |
| 20497 | } |
| 20498 | } |
| 20499 | |
| 20500 | /// [`apply_deblock`] for ONE pass over ONE band of luma rows |
| 20501 | /// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three |
| 20502 | /// planes' vertical passes and then their three horizontal ones is the same |
| 20503 | /// output as `apply_deblock`'s plane-at-a-time order: the planes are |
| 20504 | /// separate buffers and neither pass reads another plane. |
| 20505 | #[allow(clippy::too_many_arguments)] |
| 20506 | fn deblock_span( |
| 20507 | y: &mut PlaneBuf<'static>, |
| 20508 | u: &mut PlaneBuf<'static>, |
| 20509 | v: &mut PlaneBuf<'static>, |
| 20510 | lf: &LoopFilterParams, |
| 20511 | n: &Neighbours, |
| 20512 | frame_width: usize, |
| 20513 | frame_height: usize, |
| 20514 | y_lo: usize, |
| 20515 | y_hi: usize, |
| 20516 | horz: bool, |
| 20517 | fctx: &crate::decode::FrameCtx, |
| 20518 | ) { |
| 20519 | if lf.level[0] != 0 || lf.level[1] != 0 { |
| 20520 | deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx); |
| 20521 | } |
| 20522 | if lf.level[2] != 0 { |
| 20523 | deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo >> ss_y(fctx), y_hi >> ss_y(fctx), horz, fctx); |
| 20524 | } |
| 20525 | if lf.level[3] != 0 { |
| 20526 | deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo >> ss_y(fctx), y_hi >> ss_y(fctx), horz, fctx); |
| 20527 | } |
| 20528 | } |
| 20529 | |
| 20530 | /// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls |
| 20531 | /// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma |
| 20532 | /// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per |
| 20533 | /// mi unit under this decoder's assumed 4:2:0 subsampling). |
| 20534 | /// |
| 20535 | /// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as |
| 20536 | /// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz | |
| 20537 | /// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma |
| 20538 | /// prediction mode is obtained from the bottom/right mi structure of the |
| 20539 | /// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col |
| 20540 | /// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which |
| 20541 | /// is the same cell for every block 8x8 and larger and a DIFFERENT coded |
| 20542 | /// block (different tx size, ref frame, skip flag and delta_lf) as soon as |
| 20543 | /// the group is split into 4x4 luma blocks (class |
| 20544 | /// `context-read-from-one-cell`). |
| 20545 | fn plane_to_mi(chroma: bool, coord: usize, ss: usize) -> usize { |
| 20546 | // scale | ((coord << scale) >> 2). ss=1 is (coord/2)|1; ss=0 is coord/4. |
| 20547 | if chroma { ss | ((coord << ss) >> 2) } else { coord / 4 } |
| 20548 | } |
| 20549 | |
| 20550 | /// This plane's own transform width in pixels at the covering block, spec |
| 20551 | /// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma |
| 20552 | /// width directly; chroma halves it (this decoder's UV transform is always |
| 20553 | /// half its coded block's luma transform, spec's `av1_get_max_uv_txsize` |
| 20554 | /// under 4:2:0 and a block that never splits its own transform). |
| 20555 | fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { |
| 20556 | let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid }; |
| 20557 | grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32 |
| 20558 | } |
| 20559 | |
| 20560 | /// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal |
| 20561 | /// edges step and gate by transform height, which differs from width only |
| 20562 | /// on rect partition strips. |
| 20563 | fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { |
| 20564 | let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid }; |
| 20565 | grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32 |
| 20566 | } |
| 20567 | |
| 20568 | /// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom |
| 20569 | /// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each |
| 20570 | /// present only when its neighbour exists inside the true frame -- whether |
| 20571 | /// the block immediately above (at this block's own leftmost mi column) or |
| 20572 | /// to the left (at its own topmost mi row) coded a transform at least as wide |
| 20573 | /// (tall) as this block's own `max_txsize_rect_lookup[bsize]`. |
| 20574 | /// |
| 20575 | /// lane-av1txbands: this reads the real `TXFM_CONTEXT` bands |
| 20576 | /// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`]) for EVERY frame |
| 20577 | /// now -- libaom maintains them on intra-only frames too (`parse_decode_block` |
| 20578 | /// runs `set_txfm_ctxs` for every block, and |
| 20579 | /// [`Neighbours::fill_lf_grid_rect`] publishes them there), except that an |
| 20580 | /// *inter* neighbour contributes its own BLOCK size rather than its transform |
| 20581 | /// size -- and libaom's `is_inter_block` counts an INTRABC block |
| 20582 | /// (`blockd.h:373`), which is what the `above_inter`/`left_inter` bands carry. |
| 20583 | /// The previous deblock-grid approximation coincided with this only while |
| 20584 | /// every neighbour coded one whole-block transform, which is exactly what |
| 20585 | /// `TxMode::Select` ends. |
| 20586 | /// |
| 20587 | /// The rect form (lane-intrasplit r1): `get_tx_size_context` compares the |
| 20588 | /// neighbour ABOVE against `tx_size_wide[max_txsize_rect_lookup[bsize]]` and |
| 20589 | /// the neighbour to the LEFT against `tx_size_high[...]` (libaom |
| 20590 | /// `pred_common.h:342`), which for a 2:1 strip are two different numbers. |
| 20591 | fn tx_size_context_txfm_rect( |
| 20592 | n: &Neighbours, |
| 20593 | (mi_r, mi_c): (usize, usize), |
| 20594 | own_w: usize, |
| 20595 | own_h: usize, fctx: &crate::decode::FrameCtx, |
| 20596 | ) -> usize { |
| 20597 | hit!(INTRA_IN_INTER_TXCTX_HITS); |
| 20598 | // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is |
| 20599 | // wider or taller than 64, so a block with a 128 side resolves against 64 |
| 20600 | // (lane-sb128b r1). |
| 20601 | let (own_w, own_h) = (own_w.min(64), own_h.min(64)); |
| 20602 | let has_above = mi_r > n.tile_row0_mi; |
| 20603 | let has_left = mi_c > n.tile_col0_mi; |
| 20604 | let mut above = usize::from(n.above_txfm[mi_c]) >= own_w; |
| 20605 | let mut left = usize::from(n.left_txfm[mi_r]) >= own_h; |
| 20606 | if has_above && n.above_inter[mi_c] { |
| 20607 | above = usize::from(n.above_side_mi[mi_c]) >= own_w; |
| 20608 | } |
| 20609 | if has_left && n.left_inter[mi_r] { |
| 20610 | left = usize::from(n.left_side_mi[mi_r]) >= own_h; |
| 20611 | } |
| 20612 | if crate::envflags::env_flag!("EC_TXCTX") { |
| 20613 | eprintln!( |
| 20614 | "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \ |
| 20615 | intra_only={} above_txfm={} left_txfm={} above_inter={} left_inter={} \ |
| 20616 | above_side={} left_side={} above={above} left={left}", |
| 20617 | fctx.intra_only.with(std::cell::Cell::get), |
| 20618 | n.above_txfm[mi_c], |
| 20619 | n.left_txfm[mi_r], |
| 20620 | n.above_inter[mi_c], |
| 20621 | n.left_inter[mi_r], |
| 20622 | n.above_side_mi[mi_c], |
| 20623 | n.left_side_mi[mi_r], |
| 20624 | ); |
| 20625 | } |
| 20626 | let ctx = match (has_above, has_left) { |
| 20627 | (true, true) => usize::from(above) + usize::from(left), |
| 20628 | (true, false) => usize::from(above), |
| 20629 | (false, true) => usize::from(left), |
| 20630 | (false, false) => 0, |
| 20631 | }; |
| 20632 | { |
| 20633 | let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w) |
| 20634 | + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h); |
| 20635 | if ctx != stale { |
| 20636 | hit!(TXCTX_DEBLOCK_DIVERGENCE_HITS); |
| 20637 | } |
| 20638 | } |
| 20639 | ctx |
| 20640 | } |
| 20641 | |
| 20642 | /// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they |
| 20643 | /// are written and read everywhere else with a raw mi index); the SUB-cell |
| 20644 | /// division this pair used read a cell four blocks away, so the inter-neighbour |
| 20645 | /// override above fired on the wrong neighbour -- the first divergence of the |
| 20646 | /// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1, |
| 20647 | /// at the intra block right of an inter one). |
| 20648 | fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize { |
| 20649 | let has_above = mi_r > n.tile_row0_mi; |
| 20650 | let has_left = mi_c > n.tile_col0_mi; |
| 20651 | let mut above = usize::from(n.above_txfm[mi_c]) >= side; |
| 20652 | let mut left = usize::from(n.left_txfm[mi_r]) >= side; |
| 20653 | // lane-angledelta r1 (class [[context-read-from-one-cell]]): both |
| 20654 | // `above_inter`/`left_inter` bands are written per MI unit |
| 20655 | // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB / |
| 20656 | // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different |
| 20657 | // block whenever the neighbour column/row is not the cell's first. A |
| 20658 | // 16x16 intra block whose left neighbour is an inter block at mi row 4 |
| 20659 | // then missed libaom's "an inter neighbour contributes its BLOCK size" |
| 20660 | // override and read `tx_size_cat1` row 1 where aomdec reads row 2. |
| 20661 | if has_above && n.above_inter[mi_c] { |
| 20662 | above = usize::from(n.above_side_mi[mi_c]) >= side; |
| 20663 | } |
| 20664 | if has_left && n.left_inter[mi_r] { |
| 20665 | left = usize::from(n.left_side_mi[mi_r]) >= side; |
| 20666 | } |
| 20667 | if crate::envflags::env_flag!("EC_TXCTX") { |
| 20668 | eprintln!( |
| 20669 | "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \ |
| 20670 | above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \ |
| 20671 | above={above} left={left}", |
| 20672 | n.above_txfm[mi_c], |
| 20673 | n.left_txfm[mi_r], |
| 20674 | n.above_inter[mi_c], |
| 20675 | n.left_inter[mi_r], |
| 20676 | n.above_side_mi[mi_c], |
| 20677 | n.left_side_mi[mi_r], |
| 20678 | ); |
| 20679 | } |
| 20680 | match (has_above, has_left) { |
| 20681 | (true, true) => usize::from(above) + usize::from(left), |
| 20682 | (true, false) => usize::from(above), |
| 20683 | (false, true) => usize::from(left), |
| 20684 | (false, false) => 0, |
| 20685 | } |
| 20686 | } |
| 20687 | |
| 20688 | /// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under |
| 20689 | /// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to |
| 20690 | /// the transform's own side in pixels (`side >> depth`) -- this decoder's |
| 20691 | /// four square categories (8/16/32/64) each halve at most twice, matching |
| 20692 | /// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`). |
| 20693 | fn read_tx_size( |
| 20694 | dec: &mut SymbolDecoder, |
| 20695 | cdfs: &mut Cdfs, |
| 20696 | n: &Neighbours, |
| 20697 | at_mi: (usize, usize), |
| 20698 | side: usize, |
| 20699 | fctx: &crate::decode::FrameCtx, |
| 20700 | ) -> usize { |
| 20701 | // libaom `read_tx_size`'s FIRST line (decodeframe.c:1203): |
| 20702 | // `if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;` -- before the |
| 20703 | // `tx_mode == TX_MODE_SELECT` test and before any symbol. Invisible while |
| 20704 | // every lossless frame was ALSO `CodedLossless` (its `tx_mode` is forced |
| 20705 | // `Only4x4`, so this function never ran); a MIXED frame keeps |
| 20706 | // `TxMode::Select`, so its lossless segments reach the symbol read and |
| 20707 | // must take the early return (lane-av1mixloss). |
| 20708 | if lossless(fctx) { |
| 20709 | return 4; |
| 20710 | } |
| 20711 | // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` / |
| 20712 | // `get_tx_size_context`): a block wider than 64 still tops out at |
| 20713 | // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth |
| 20714 | // chain 64->32->16->8->4 is the same four steps) and resolves against 64, |
| 20715 | // never against its own 128 side (lane-sb128b r1). |
| 20716 | let max_tx = side.min(64); |
| 20717 | let ctx = tx_size_context_txfm(n, at_mi, max_tx); |
| 20718 | let depth = match max_tx { |
| 20719 | 8 => { |
| 20720 | dec.symbol(&mut cdfs.tx_size_cat0[ctx]) |
| 20721 | } |
| 20722 | 16 => { |
| 20723 | dec.symbol(&mut cdfs.tx_size_cat1[ctx]) |
| 20724 | } |
| 20725 | 32 => { |
| 20726 | dec.symbol(&mut cdfs.tx_size_cat2[ctx]) |
| 20727 | } |
| 20728 | 64 => { |
| 20729 | dec.symbol(&mut cdfs.tx_size_cat3[ctx]) |
| 20730 | } |
| 20731 | _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"), |
| 20732 | }; |
| 20733 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 20734 | let (rng, _) = dec.debug_state(); |
| 20735 | let (mi_r, mi_c) = at_mi; |
| 20736 | eprintln!( |
| 20737 | "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}" |
| 20738 | ); |
| 20739 | } |
| 20740 | if depth != 0 { |
| 20741 | hit!(TX_DEPTH_HITS); |
| 20742 | } |
| 20743 | max_tx >> depth |
| 20744 | } |
| 20745 | |
| 20746 | /// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's |
| 20747 | /// `txfm_split` context -- a category from the block's own largest square |
| 20748 | /// transform and whether this unit already sits below it, times three, plus |
| 20749 | /// the two neighbour terms (whether the transform last written above/left of |
| 20750 | /// this unit is narrower/shorter than the unit itself). |
| 20751 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 20752 | fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize { |
| 20753 | txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px) |
| 20754 | } |
| 20755 | |
| 20756 | /// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2): |
| 20757 | /// libaom's `txfm_partition_context` compares the above context against |
| 20758 | /// `tx_size_wide` and the left one against `tx_size_high`, and takes its |
| 20759 | /// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one |
| 20760 | /// side for a square transform, which is why the square form above is a |
| 20761 | /// special case of this one. |
| 20762 | pub(crate) fn txfm_partition_ctx_rect( |
| 20763 | above_px: u8, |
| 20764 | left_px: u8, |
| 20765 | blk_max_px: usize, |
| 20766 | tx_w: usize, |
| 20767 | tx_h: usize, |
| 20768 | ) -> usize { |
| 20769 | let above = usize::from(usize::from(above_px) < tx_w); |
| 20770 | let left = usize::from(usize::from(left_px) < tx_h); |
| 20771 | let tx_px = tx_w.max(tx_h); |
| 20772 | // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the |
| 20773 | // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as |
| 20774 | // `log2(px) - 2`. |
| 20775 | let max_tx = blk_max_px.min(64); |
| 20776 | let max_idx = max_tx.trailing_zeros() as usize - 2; |
| 20777 | let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2; |
| 20778 | category * 3 + above + left |
| 20779 | } |
| 20780 | |
| 20781 | /// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit |
| 20782 | /// resolves, every mi cell its *parent* unit (`txb_px`) spans records the |
| 20783 | /// resolved transform's own size. |
| 20784 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 20785 | fn txfm_partition_update( |
| 20786 | n: &mut Neighbours, |
| 20787 | at_mi: (usize, usize), |
| 20788 | tx_px: usize, |
| 20789 | txb_px: usize, |
| 20790 | ) { |
| 20791 | txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px)); |
| 20792 | } |
| 20793 | |
| 20794 | /// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2): |
| 20795 | /// the left column records `tx_size_high` over the parent's own height and |
| 20796 | /// the above row records `tx_size_wide` over its width. |
| 20797 | /// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of |
| 20798 | /// `decode_token_recon_block`): EVERY block of an inter frame publishes its |
| 20799 | /// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The |
| 20800 | /// key frame writes neither (its readers use the deblock grid), so the |
| 20801 | /// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it |
| 20802 | /// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it |
| 20803 | /// at the call site (the transform size comes back to them); the 1:4 arms |
| 20804 | /// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside, |
| 20805 | /// so they call this where their own depth resolves. A no-op on a key frame |
| 20806 | /// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all. |
| 20807 | /// |
| 20808 | /// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an |
| 20809 | /// inter frame left `left_txfm[0]` at a stale 32 where libaom's own |
| 20810 | /// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read |
| 20811 | /// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF, |
| 20812 | /// range 39156 where the reference has 54736 (class tx-grid-published-block-side |
| 20813 | /// / early-return-skips-tail). |
| 20814 | /// |
| 20815 | /// lane-av1-intrabc r3: an `allow_intrabc` KEY frame reads the same bands -- |
| 20816 | /// `read_intra_frame_mode_info` returns early for an intrabc block, so |
| 20817 | /// [`read_block_tx_size_rect`]'s var-tx tree is the intra path's one |
| 20818 | /// `txfm_partition_context` reader, and it reads whatever the block ABOVE and |
| 20819 | /// the block LEFT published. [`decode_block`] has published on such a frame |
| 20820 | /// since lane-t900 r32; the RECT strips did not, so the band still held the |
| 20821 | /// value of an older, smaller neighbour -- measured on the 256x192 testsrc2 |
| 20822 | /// cq45 var-tx arm: the coded 16x8 intrabc strip at mi(38,48) read ctx 14 |
| 20823 | /// where libaom reads 13 (`left_ctx` 4 vs the 8 the 16x8 intra strip at |
| 20824 | /// mi(38,44) should have published), desyncing the tile there. |
| 20825 | fn publish_txfm_bands_if_in_inter( |
| 20826 | n: &mut Neighbours, |
| 20827 | at_mi: (usize, usize), |
| 20828 | (tx_w, tx_h): (usize, usize), |
| 20829 | (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx, |
| 20830 | ) { |
| 20831 | if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() |
| 20832 | && !allow_intrabc_frame(fctx) |
| 20833 | { |
| 20834 | return; |
| 20835 | } |
| 20836 | let (mi_r, mi_c) = at_mi; |
| 20837 | txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); |
| 20838 | for i in 0..bw / MI { |
| 20839 | if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { |
| 20840 | *cell = tx_w as u8; |
| 20841 | } |
| 20842 | } |
| 20843 | for i in 0..bh / MI { |
| 20844 | if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { |
| 20845 | *cell = tx_h as u8; |
| 20846 | } |
| 20847 | } |
| 20848 | } |
| 20849 | |
| 20850 | fn txfm_partition_update_rect( |
| 20851 | n: &mut Neighbours, |
| 20852 | (mi_r, mi_c): (usize, usize), |
| 20853 | (tx_w, tx_h): (usize, usize), |
| 20854 | (txb_w, txb_h): (usize, usize), |
| 20855 | ) { |
| 20856 | if crate::envflags::env_flag!("EC_TXUPD") { |
| 20857 | eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c); |
| 20858 | } |
| 20859 | for i in 0..txb_h / MI { |
| 20860 | if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { |
| 20861 | *cell = tx_h as u8; |
| 20862 | } |
| 20863 | } |
| 20864 | for i in 0..txb_w / MI { |
| 20865 | if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { |
| 20866 | *cell = tx_w as u8; |
| 20867 | } |
| 20868 | } |
| 20869 | } |
| 20870 | |
| 20871 | /// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the |
| 20872 | /// same contexts -- a skipped *inter* block records its own block size rather |
| 20873 | /// than its transform size. |
| 20874 | fn set_txfm_ctxs( |
| 20875 | n: &mut Neighbours, |
| 20876 | (mi_r, mi_c): (usize, usize), |
| 20877 | tx_px: usize, |
| 20878 | w_mi: usize, |
| 20879 | h_mi: usize, |
| 20880 | skip_inter: bool, |
| 20881 | ) { |
| 20882 | if crate::envflags::env_flag!("EC_TXUPD") { |
| 20883 | eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}"); |
| 20884 | } |
| 20885 | let bw = if skip_inter { w_mi * MI } else { tx_px }; |
| 20886 | let bh = if skip_inter { h_mi * MI } else { tx_px }; |
| 20887 | for i in 0..w_mi { |
| 20888 | if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { |
| 20889 | *cell = bw as u8; |
| 20890 | } |
| 20891 | } |
| 20892 | for i in 0..h_mi { |
| 20893 | if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { |
| 20894 | *cell = bh as u8; |
| 20895 | } |
| 20896 | } |
| 20897 | } |
| 20898 | |
| 20899 | /// The value libaom initialises both transform contexts to -- NOT zero: |
| 20900 | /// `av1_zero_above_context` memsets the txfm row to |
| 20901 | /// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same |
| 20902 | /// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64 |
| 20903 | /// pixels, so an unwritten neighbour reads as the *widest* possible |
| 20904 | /// transform, not the narrowest. |
| 20905 | pub(crate) const TXFM_CTX_INIT: u8 = 64; |
| 20906 | |
| 20907 | /// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most |
| 20908 | /// twice below its own largest transform. |
| 20909 | const MAX_VARTX_DEPTH: usize = 2; |
| 20910 | |
| 20911 | /// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform |
| 20912 | /// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes |
| 20913 | /// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1 |
| 20914 | /// small ones, square everywhere else. |
| 20915 | fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) { |
| 20916 | match (tx_w, tx_h) { |
| 20917 | (4, 4) => (4, 4), |
| 20918 | (8, 8) => (4, 4), |
| 20919 | (16, 16) => (8, 8), |
| 20920 | (32, 32) => (16, 16), |
| 20921 | (64, 64) => (32, 32), |
| 20922 | (4, 8) | (8, 4) => (4, 4), |
| 20923 | (8, 16) | (16, 8) => (8, 8), |
| 20924 | (16, 32) | (32, 16) => (16, 16), |
| 20925 | (32, 64) | (64, 32) => (32, 32), |
| 20926 | (4, 16) => (4, 8), |
| 20927 | (16, 4) => (8, 4), |
| 20928 | (8, 32) => (8, 16), |
| 20929 | (32, 8) => (16, 8), |
| 20930 | (16, 64) => (16, 32), |
| 20931 | (64, 16) => (32, 16), |
| 20932 | _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"), |
| 20933 | } |
| 20934 | } |
| 20935 | |
| 20936 | #[test] |
| 20937 | fn sub_tx_size_map_matches_libaom() { |
| 20938 | // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order. |
| 20939 | const TABLE: [((usize, usize), (usize, usize)); 19] = [ |
| 20940 | ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)), |
| 20941 | ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)), |
| 20942 | ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)), |
| 20943 | ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)), |
| 20944 | ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)), |
| 20945 | ]; |
| 20946 | for (tx, want) in TABLE { |
| 20947 | assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})"); |
| 20948 | } |
| 20949 | } |
| 20950 | |
| 20951 | /// The domain of var-tx leaf sizes, enumerated against the two refusals that |
| 20952 | /// name a leaf "larger than 32x32" / "larger than 64x64". |
| 20953 | /// |
| 20954 | /// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is |
| 20955 | /// either the unit it was entered with or a `sub_tx_size_map` step below it: |
| 20956 | /// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early |
| 20957 | /// return. So the leaf set reachable from an entry unit is that unit plus the |
| 20958 | /// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` -- |
| 20959 | /// which this test enumerates, and over which no leaf is ever larger than the |
| 20960 | /// entry. |
| 20961 | /// |
| 20962 | /// That closes both refusals: |
| 20963 | /// |
| 20964 | /// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit |
| 20965 | /// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than |
| 20966 | /// 64x64" names a leaf the tree cannot produce; |
| 20967 | /// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32 |
| 20968 | /// below the 128 root. The only entry that exceeds that ceiling is 64x64, |
| 20969 | /// reached only when `side == 64`, and then the block is ONE unit whose only |
| 20970 | /// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single` |
| 20971 | /// case the refusal is guarded by. |
| 20972 | #[test] |
| 20973 | fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() { |
| 20974 | // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h). |
| 20975 | fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) { |
| 20976 | out.push((depth, entry.0, entry.1)); |
| 20977 | if depth == MAX_VARTX_DEPTH { |
| 20978 | return; |
| 20979 | } |
| 20980 | let sub = sub_tx_size_map(entry.0, entry.1); |
| 20981 | if sub == (4, 4) { |
| 20982 | out.push((depth + 1, 4, 4)); |
| 20983 | return; |
| 20984 | } |
| 20985 | reachable(sub, depth + 1, out); |
| 20986 | } |
| 20987 | |
| 20988 | for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] { |
| 20989 | let mut leaves = Vec::new(); |
| 20990 | reachable(entry, 0, &mut leaves); |
| 20991 | for (depth, w, h) in &leaves { |
| 20992 | assert!( |
| 20993 | w.max(h) <= &entry.0.max(entry.1), |
| 20994 | "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}", |
| 20995 | entry.0, |
| 20996 | entry.1 |
| 20997 | ); |
| 20998 | } |
| 20999 | // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0. |
| 21000 | if entry == (64, 64) { |
| 21001 | let above: Vec<&(usize, usize, usize)> = |
| 21002 | leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect(); |
| 21003 | assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32"); |
| 21004 | } |
| 21005 | } |
| 21006 | |
| 21007 | // The entry size and ceiling each caller uses, over the block sides that |
| 21008 | // reach them (`read_block_tx_size`'s square path; the 128-root rect path |
| 21009 | // enters at a fixed 64). |
| 21010 | for side in [8usize, 16, 32, 64, 128] { |
| 21011 | let max_tx = side.min(64); |
| 21012 | let ceiling = if side > 64 { 64 } else { 32 }; |
| 21013 | let units = (side / max_tx) * (side / max_tx); |
| 21014 | if max_tx <= ceiling { |
| 21015 | continue; |
| 21016 | } |
| 21017 | assert_eq!( |
| 21018 | (side, units), |
| 21019 | (64, 1), |
| 21020 | "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \ |
| 21021 | {units} units -- an above-ceiling leaf there would NOT be the `single` case" |
| 21022 | ); |
| 21023 | } |
| 21024 | } |
| 21025 | |
| 21026 | /// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c` |
| 21027 | /// `read_tx_size_vartx`): the recursive `txfm_split` tree of one |
| 21028 | /// max-transform-sized unit of an inter block, collecting the resolved leaf |
| 21029 | /// transform units into `out` as `(row offset, col offset, side)` in mi units |
| 21030 | /// -- exactly the order `decode_reconstruct_tx` later reads their |
| 21031 | /// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block; |
| 21032 | /// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/ |
| 21033 | /// `max_block_high`). |
| 21034 | #[allow(clippy::too_many_arguments)] |
| 21035 | fn read_var_tx_size( |
| 21036 | dec: &mut SymbolDecoder, |
| 21037 | cdfs: &mut Cdfs, |
| 21038 | n: &mut Neighbours, |
| 21039 | at_mi: (usize, usize), |
| 21040 | blk_max_px: usize, |
| 21041 | (max_w_mi, max_h_mi): (usize, usize), |
| 21042 | (tx_w, tx_h): (usize, usize), |
| 21043 | depth: usize, |
| 21044 | blk_row: usize, |
| 21045 | blk_col: usize, |
| 21046 | out: &mut Vec<(usize, usize, usize, usize)>, |
| 21047 | ) { |
| 21048 | if blk_row >= max_h_mi || blk_col >= max_w_mi { |
| 21049 | return; |
| 21050 | } |
| 21051 | let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col); |
| 21052 | if depth == MAX_VARTX_DEPTH { |
| 21053 | out.push((blk_row, blk_col, tx_w, tx_h)); |
| 21054 | txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h)); |
| 21055 | return; |
| 21056 | } |
| 21057 | let ctx = txfm_partition_ctx_rect( |
| 21058 | n.above_txfm[unit.1], |
| 21059 | n.left_txfm[unit.0], |
| 21060 | blk_max_px, |
| 21061 | tx_w, |
| 21062 | tx_h, |
| 21063 | ); |
| 21064 | let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; |
| 21065 | hit!(TXFM_SPLIT_READS); |
| 21066 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 21067 | let (rng, _) = dec.debug_state(); |
| 21068 | eprintln!( |
| 21069 | "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}", |
| 21070 | unit.0, |
| 21071 | unit.1, |
| 21072 | u8::from(split) |
| 21073 | ); |
| 21074 | } |
| 21075 | if !split { |
| 21076 | out.push((blk_row, blk_col, tx_w, tx_h)); |
| 21077 | txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h)); |
| 21078 | return; |
| 21079 | } |
| 21080 | hit!(TXFM_SPLIT_HITS); |
| 21081 | let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h); |
| 21082 | if (sub_w, sub_h) == (4, 4) { |
| 21083 | // libaom's `sub_txs == TX_4X4` early return: every mi cell of the |
| 21084 | // unit is marked 4x4 (raster order) without recursing. |
| 21085 | for row in 0..tx_h / MI { |
| 21086 | for col in 0..tx_w / MI { |
| 21087 | if blk_row + row < max_h_mi && blk_col + col < max_w_mi { |
| 21088 | out.push((blk_row + row, blk_col + col, 4, 4)); |
| 21089 | } |
| 21090 | } |
| 21091 | } |
| 21092 | txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h)); |
| 21093 | return; |
| 21094 | } |
| 21095 | for row in (0..tx_h / MI).step_by(sub_h / MI) { |
| 21096 | for col in (0..tx_w / MI).step_by(sub_w / MI) { |
| 21097 | read_var_tx_size( |
| 21098 | dec, |
| 21099 | cdfs, |
| 21100 | n, |
| 21101 | at_mi, |
| 21102 | blk_max_px, |
| 21103 | (max_w_mi, max_h_mi), |
| 21104 | (sub_w, sub_h), |
| 21105 | depth + 1, |
| 21106 | blk_row + row, |
| 21107 | blk_col + col, |
| 21108 | out, |
| 21109 | ); |
| 21110 | } |
| 21111 | } |
| 21112 | } |
| 21113 | |
| 21114 | /// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx |
| 21115 | /// branch): every block of a `TxMode::Select` inter frame codes its transform |
| 21116 | /// size right after its own mode info -- an inter non-skip block through the |
| 21117 | /// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns), |
| 21118 | /// every other block through the intra `tx_depth` symbol (a skipped inter |
| 21119 | /// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the |
| 21120 | /// block's own resolved transform side and the leaf list, the latter only |
| 21121 | /// when the tree resolved to more than one transform unit. |
| 21122 | #[allow(clippy::too_many_arguments)] |
| 21123 | fn read_block_tx_size( |
| 21124 | dec: &mut SymbolDecoder, |
| 21125 | cdfs: &mut Cdfs, |
| 21126 | n: &mut Neighbours, |
| 21127 | at_mi: (usize, usize), |
| 21128 | side: usize, |
| 21129 | (mi_cols, mi_rows): (usize, usize), |
| 21130 | is_inter: bool, |
| 21131 | skip: bool, fctx: &crate::decode::FrameCtx, |
| 21132 | ) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> { |
| 21133 | // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom |
| 21134 | // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the |
| 21135 | // `read_tx_size` arm, which returns TX_4X4 before it reads anything. |
| 21136 | if lossless(fctx) { |
| 21137 | let mut leaves = Vec::new(); |
| 21138 | for row in 0..side / MI { |
| 21139 | for col in 0..side / MI { |
| 21140 | leaves.push((row, col, 4, 4)); |
| 21141 | } |
| 21142 | } |
| 21143 | return Ok((4, Some(leaves))); |
| 21144 | } |
| 21145 | if !fctx.tx_select_inter.with(std::cell::Cell::get) { |
| 21146 | // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64, |
| 21147 | // so a 128x128 inter block is FOUR luma units even with `tx_mode == |
| 21148 | // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back. |
| 21149 | // lane-sb128c r3: intra too -- an INTRA 128x128 block under |
| 21150 | // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units. |
| 21151 | if side > 64 { |
| 21152 | let step = 64 / MI; |
| 21153 | let mut leaves = Vec::new(); |
| 21154 | for row in (0..side / MI).step_by(step) { |
| 21155 | for col in (0..side / MI).step_by(step) { |
| 21156 | leaves.push((row, col, 64, 64)); |
| 21157 | } |
| 21158 | } |
| 21159 | return Ok((64, Some(leaves))); |
| 21160 | } |
| 21161 | return Ok((side, None)); |
| 21162 | } |
| 21163 | let side_mi = side / MI; |
| 21164 | if is_inter && !skip { |
| 21165 | let max_tx = side.min(64); |
| 21166 | let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1)); |
| 21167 | let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0)); |
| 21168 | let mut leaves = Vec::new(); |
| 21169 | let step = max_tx / MI; |
| 21170 | for row in (0..side_mi).step_by(step) { |
| 21171 | for col in (0..side_mi).step_by(step) { |
| 21172 | read_var_tx_size( |
| 21173 | dec, |
| 21174 | cdfs, |
| 21175 | n, |
| 21176 | at_mi, |
| 21177 | side, |
| 21178 | (max_w_mi, max_h_mi), |
| 21179 | (max_tx, max_tx), |
| 21180 | 0, |
| 21181 | row, |
| 21182 | col, |
| 21183 | &mut leaves, |
| 21184 | ); |
| 21185 | } |
| 21186 | } |
| 21187 | let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side; |
| 21188 | // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32 |
| 21189 | // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128 |
| 21190 | // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves, |
| 21191 | // which the mu-chunk reader above codes as their 32x32 coded corner. |
| 21192 | let leaf_ceiling = if side > 64 { 64 } else { 32 }; |
| 21193 | if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) { |
| 21194 | // Only a block wider than a superblock's own 64x64 max transform |
| 21195 | // reaches here; this crate has no 64-point *inter* coefficient |
| 21196 | // table set ([`inter_txbset_for`] stops at 32). |
| 21197 | return Err(unsupported( |
| 21198 | "an inter var-tx tree with a leaf transform larger than 32x32", |
| 21199 | )); |
| 21200 | } |
| 21201 | let resolved = leaves.last().map_or(side, |l| l.2); |
| 21202 | return Ok((resolved, (!single).then_some(leaves))); |
| 21203 | } |
| 21204 | let tx = if is_inter { |
| 21205 | side.min(64) |
| 21206 | } else { |
| 21207 | read_tx_size(dec, cdfs, n, at_mi, side, fctx) |
| 21208 | }; |
| 21209 | set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter); |
| 21210 | if !is_inter && tx != side { |
| 21211 | // lane-intrainter r1: an intra block inside an inter frame whose |
| 21212 | // `tx_depth` split its luma transform codes exactly the key-frame |
| 21213 | // split path's transform units (`decode_block`'s multi-TU loop), |
| 21214 | // raster order over the block. Handed back in the same leaf shape the |
| 21215 | // inter var-tx tree uses, so the caller's per-TU luma loop, the |
| 21216 | // `record_split_luma` neighbour write-back and the per-TU deblock |
| 21217 | // edges are the ones it already runs for a var-tx inter block. A |
| 21218 | // caller that has no per-TU intra loop (the 8x8 leaf) refuses on |
| 21219 | // seeing `Some` here. |
| 21220 | let step = tx / MI; |
| 21221 | let mut leaves = Vec::new(); |
| 21222 | for row in (0..side_mi).step_by(step) { |
| 21223 | for col in (0..side_mi).step_by(step) { |
| 21224 | leaves.push((row, col, tx, tx)); |
| 21225 | } |
| 21226 | } |
| 21227 | hit_do! { |
| 21228 | INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| { |
| 21229 | let mut h = c.get(); |
| 21230 | h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1; |
| 21231 | c.set(h); |
| 21232 | }); |
| 21233 | } |
| 21234 | return Ok((tx, Some(leaves))); |
| 21235 | } |
| 21236 | Ok((tx, None)) |
| 21237 | } |
| 21238 | |
| 21239 | /// lane-inter4 r2: the shapes whose *rectangular inter* residual this |
| 21240 | /// decoder codes -- a 2:1 strip whose own max rect transform |
| 21241 | /// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a |
| 21242 | /// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient |
| 21243 | /// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a |
| 21244 | /// 64-point rect transform, and 16x8/8x16 needs |
| 21245 | /// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol |
| 21246 | /// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a |
| 21247 | /// rect transform), neither of which exists yet -- both stay refused by name. |
| 21248 | pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool { |
| 21249 | matches!( |
| 21250 | (w, h), |
| 21251 | // 2:1 strips whose transform is coded in full (lane-inter4). |
| 21252 | (32, 16) | (16, 32) | (16, 8) | (8, 16) |
| 21253 | // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16 |
| 21254 | // codes all 64 of its positions, and its chroma pair is an 8x4 / |
| 21255 | // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4). |
| 21256 | | (16, 4) | (4, 16) |
| 21257 | // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes |
| 21258 | // only the low 32 coefficients of a 64-length axis, so these read |
| 21259 | // exactly the truncated corner the INTRA superblock-strip path |
| 21260 | // already reads (`read_intra_mode_rect`), through |
| 21261 | // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is |
| 21262 | // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no |
| 21263 | // `tx_type` symbol is coded at all. |
| 21264 | | (64, 32) | (32, 64) | (64, 16) | (16, 64) |
| 21265 | // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a |
| 21266 | // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves. |
| 21267 | // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is |
| 21268 | // refused earlier ("an inter partition below 8x8"). |
| 21269 | | (8, 4) | (4, 8) |
| 21270 | // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT |
| 21271 | // one rectangular transform -- `max_txsize_rect_lookup |
| 21272 | // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square |
| 21273 | // TX_64X64 units read through the mu-chunk loop, same as the |
| 21274 | // 128x128 NONE block's four. |
| 21275 | | (128, 64) | (64, 128) |
| 21276 | // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both |
| 21277 | // 10-bit film cuts and every measured 1080p offset stop on |
| 21278 | // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else). |
| 21279 | // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 |
| 21280 | // positions, and its chroma pair is a 16x4 / 4x16 unit |
| 21281 | // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4). |
| 21282 | | (32, 8) | (8, 32) |
| 21283 | ) |
| 21284 | } |
| 21285 | |
| 21286 | // lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path |
| 21287 | // actually PRESENTS, as a thread-local bitmask -- the measured domain behind |
| 21288 | // the "rectangular ... has no ... here" refusals. `side` is the square context |
| 21289 | // a block reads its CDFs at and `write_w`/`write_h` its true footprint; |
| 21290 | // `inter_piece!` derives `reject_residual` from exactly that inequality, so |
| 21291 | // these triples are what decides whether those refusals can fire at all. Bit |
| 21292 | // 31 is "a triple this table does not list", which is what makes the gate a |
| 21293 | // census rather than a restatement of its own table. |
| 21294 | pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [ |
| 21295 | (16, 16, 16), |
| 21296 | (32, 32, 32), |
| 21297 | (32, 16, 32), |
| 21298 | (32, 32, 16), |
| 21299 | (16, 8, 16), |
| 21300 | (16, 16, 8), |
| 21301 | (32, 8, 32), |
| 21302 | (64, 64, 64), |
| 21303 | (32, 32, 8), |
| 21304 | (64, 16, 64), |
| 21305 | (128, 128, 128), |
| 21306 | (64, 32, 64), |
| 21307 | (64, 64, 32), |
| 21308 | (16, 4, 16), |
| 21309 | (64, 64, 16), |
| 21310 | (16, 16, 4), |
| 21311 | (128, 128, 64), |
| 21312 | (128, 64, 128), |
| 21313 | ]; |
| 21314 | |
| 21315 | /// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple |
| 21316 | /// outside [`INTER_BLOCK_SHAPES`]. |
| 21317 | pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31; |
| 21318 | |
| 21319 | thread_local! { |
| 21320 | static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; |
| 21321 | } |
| 21322 | |
| 21323 | /// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a |
| 21324 | /// gate reading it sees only the streams it decoded itself). |
| 21325 | pub fn inter_block_shape_mask() -> u32 { |
| 21326 | INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get) |
| 21327 | } |
| 21328 | |
| 21329 | /// Records one block's shape. The table is ordered by measured frequency over |
| 21330 | /// the three witnesses the census gate decodes, so the common square shapes |
| 21331 | /// leave the scan on their first comparison. |
| 21332 | fn census_inter_block_shape(side: usize, w: usize, h: usize) { |
| 21333 | let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) { |
| 21334 | Some(i) => 1u32 << i, |
| 21335 | None => INTER_BLOCK_SHAPE_UNLISTED, |
| 21336 | }; |
| 21337 | let seen = inter_block_shape_mask(); |
| 21338 | if seen & bit == 0 { |
| 21339 | INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit)); |
| 21340 | } |
| 21341 | } |
| 21342 | |
| 21343 | /// The luma coefficient/`tx_type` table set of a whole-block rectangular |
| 21344 | /// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits |
| 21345 | /// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so |
| 21346 | /// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of |
| 21347 | /// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and |
| 21348 | /// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced |
| 21349 | /// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF |
| 21350 | /// row (`txsize_sqr_map`), never the 16x16 one. |
| 21351 | fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> { |
| 21352 | Ok(match (w, h) { |
| 21353 | (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter, |
| 21354 | // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip. |
| 21355 | // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up == |
| 21356 | // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced, |
| 21357 | // ALL16 otherwise -- both at the TX_4X4 row. |
| 21358 | (8, 4) | (4, 8) => { |
| 21359 | if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) { |
| 21360 | TxbSet::LumaRect8x4Inter |
| 21361 | } else { |
| 21362 | TxbSet::LumaRect8x4InterSet1 |
| 21363 | } |
| 21364 | } |
| 21365 | (16, 4) | (4, 16) => { |
| 21366 | if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) { |
| 21367 | TxbSet::LumaRect16x4Inter |
| 21368 | } else { |
| 21369 | TxbSet::LumaRect16x4Inter1 |
| 21370 | } |
| 21371 | } |
| 21372 | (16, 8) | (8, 16) => { |
| 21373 | if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) { |
| 21374 | TxbSet::LumaRect16x8Inter |
| 21375 | } else { |
| 21376 | TxbSet::LumaRect16x8InterSet1 |
| 21377 | } |
| 21378 | } |
| 21379 | // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to |
| 21380 | // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and |
| 21381 | // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the |
| 21382 | // adjusted size, so the existing sets are bit-exact. Neither carries a |
| 21383 | // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot. |
| 21384 | // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so |
| 21385 | // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or |
| 21386 | // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER` |
| 21387 | // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row. |
| 21388 | (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter, |
| 21389 | (64, 32) | (32, 64) => TxbSet::Luma64, |
| 21390 | (64, 16) | (16, 64) => TxbSet::LumaRect32x16, |
| 21391 | _ => { |
| 21392 | return Err(unsupported( |
| 21393 | "a rectangular inter luma transform unit whose shape has no coefficient table set here", |
| 21394 | )); |
| 21395 | } |
| 21396 | }) |
| 21397 | } |
| 21398 | |
| 21399 | /// The chroma table set of the same block's single rectangular chroma unit |
| 21400 | /// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8 |
| 21401 | /// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit |
| 21402 | /// the luma unit's. |
| 21403 | fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> { |
| 21404 | Ok(match (w, h) { |
| 21405 | (16, 8) | (8, 16) => TxbSet::ChromaRect16x8, |
| 21406 | (8, 4) | (4, 8) => TxbSet::ChromaRect8x4, |
| 21407 | // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a |
| 21408 | // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma |
| 21409 | // unit has a 64-px axis, so both are coded in full; `Chroma16` is the |
| 21410 | // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16, |
| 21411 | // `txsize_log2_minus4` = 4), same as the intra strip path uses. |
| 21412 | (32, 16) | (16, 32) => TxbSet::ChromaRect32x16, |
| 21413 | (32, 8) | (8, 32) => TxbSet::Chroma16, |
| 21414 | // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact |
| 21415 | // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8, |
| 21416 | // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`). |
| 21417 | (16, 4) | (4, 16) => TxbSet::Chroma8, |
| 21418 | // lane-av1-444: one 32x32 unit of a 4:4:4 64x32/32x64 chroma plane |
| 21419 | // block (`av1_get_max_uv_txsize` adjusts `TX_64X32`/`TX_32X64` to |
| 21420 | // `TX_32X32`); `get_txsize_entropy_ctx(TX_32X32)` is the 32x32 set. |
| 21421 | (32, 32) => TxbSet::Chroma32, |
| 21422 | _ => { |
| 21423 | return Err(unsupported( |
| 21424 | "a rectangular inter chroma transform unit whose shape has no coefficient table set here", |
| 21425 | )); |
| 21426 | } |
| 21427 | }) |
| 21428 | } |
| 21429 | |
| 21430 | |
| 21431 | /// libaom `size_group_lookup[bsize]` for the block shapes this decoder's |
| 21432 | /// inter path reaches, from the block's TRUE footprint rather than the |
| 21433 | /// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2, |
| 21434 | /// everything 32 and above -> 3. |
| 21435 | fn size_group_wh(w: usize, h: usize) -> usize { |
| 21436 | // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom |
| 21437 | // `common_data.h:60`) is 0 for every block with a 4-px side |
| 21438 | // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old |
| 21439 | // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0. |
| 21440 | match w.min(h) { |
| 21441 | 0..=4 => 0, |
| 21442 | 8 => 1, |
| 21443 | 16 => 2, |
| 21444 | _ => 3, |
| 21445 | } |
| 21446 | } |
| 21447 | |
| 21448 | #[test] |
| 21449 | fn size_group_wh_matches_libaom_size_group_lookup() { |
| 21450 | // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s |
| 21451 | // transcribed values (common_data.h:60-62). |
| 21452 | const TABLE: [((usize, usize), usize); 22] = [ |
| 21453 | ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1), |
| 21454 | ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3), |
| 21455 | ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3), |
| 21456 | ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2), |
| 21457 | ]; |
| 21458 | for ((w, h), want) in TABLE { |
| 21459 | assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})"); |
| 21460 | } |
| 21461 | } |
| 21462 | |
| 21463 | /// The default (2D) coefficient scan of a rectangular transform. |
| 21464 | fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> { |
| 21465 | Ok(match (w, h) { |
| 21466 | (32, 16) => &SCAN_32X16, |
| 21467 | (16, 32) => &SCAN_16X32, |
| 21468 | (16, 8) => &SCAN_16X8, |
| 21469 | (8, 16) => &SCAN_8X16, |
| 21470 | (16, 4) => &SCAN_16X4, |
| 21471 | (4, 16) => &SCAN_4X16, |
| 21472 | (8, 4) => &SCAN_8X4, |
| 21473 | (4, 8) => &SCAN_4X8, |
| 21474 | (32, 8) => &SCAN_32X8, |
| 21475 | (8, 32) => &SCAN_8X32, |
| 21476 | _ => { |
| 21477 | return Err(unsupported( |
| 21478 | "a rectangular transform unit whose shape has no coefficient scan table here", |
| 21479 | )); |
| 21480 | } |
| 21481 | }) |
| 21482 | } |
| 21483 | |
| 21484 | /// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma |
| 21485 | /// transform unit whose shape has no coefficient table set here" / "a |
| 21486 | /// rectangular transform unit whose shape has no coefficient scan table here" |
| 21487 | /// arms, enumerated against the MEASURED domain of the inter block path |
| 21488 | /// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate |
| 21489 | /// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`). |
| 21490 | /// |
| 21491 | /// What each helper is actually handed: |
| 21492 | /// |
| 21493 | /// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the |
| 21494 | /// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is |
| 21495 | /// square for every rect transform except TX_16X4/TX_4X16, whose leaves are |
| 21496 | /// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8. |
| 21497 | /// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0 |
| 21498 | /// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8. |
| 21499 | /// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect |
| 21500 | /// unit, and only when that corner is not 32x32 (a square corner goes |
| 21501 | /// through the square reader with `rect_shape = Some((w, h))`). |
| 21502 | /// |
| 21503 | /// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is |
| 21504 | /// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk |
| 21505 | /// loop, which is why they are skipped below. |
| 21506 | #[test] |
| 21507 | fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() { |
| 21508 | let fctx = &crate::decode::FrameCtx::new(); |
| 21509 | let corner_scan = |w: usize, h: usize| { |
| 21510 | let (cw, ch) = (w.min(32), h.min(32)); |
| 21511 | if (cw, ch) == (32, 32) { |
| 21512 | return; // the square coefficient reader, not `rect_scan` |
| 21513 | } |
| 21514 | assert!( |
| 21515 | rect_scan(cw, ch).is_ok(), |
| 21516 | "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table" |
| 21517 | ); |
| 21518 | }; |
| 21519 | let mut checked = 0; |
| 21520 | for &(side, w, h) in &INTER_BLOCK_SHAPES { |
| 21521 | if (w, h) == (side, side) || w.max(h) > 64 { |
| 21522 | continue; |
| 21523 | } |
| 21524 | assert!( |
| 21525 | rect_inter_luma_set(w, h, fctx).is_ok(), |
| 21526 | "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one" |
| 21527 | ); |
| 21528 | corner_scan(w, h); |
| 21529 | // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved |
| 21530 | // footprint for every other shape. |
| 21531 | let (cw, ch) = match (w, h) { |
| 21532 | (16, 4) => (8, 4), |
| 21533 | (4, 16) => (4, 8), |
| 21534 | _ => (w / 2, h / 2), |
| 21535 | }; |
| 21536 | assert!( |
| 21537 | rect_inter_chroma_set(cw, ch).is_ok(), |
| 21538 | "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set" |
| 21539 | ); |
| 21540 | corner_scan(cw, ch); |
| 21541 | checked += 1; |
| 21542 | } |
| 21543 | assert_eq!( |
| 21544 | checked, 12, |
| 21545 | "the block-shape census changed: {checked} rect shapes reach the rect transform \ |
| 21546 | tables, not the 12 this claim was measured over" |
| 21547 | ); |
| 21548 | // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf |
| 21549 | // shapes, which reach `rect_inter_luma_set` as `(tw, th)`. |
| 21550 | for (w, h) in [(8usize, 4usize), (4, 8)] { |
| 21551 | assert!( |
| 21552 | rect_inter_luma_set(w, h, fctx).is_ok(), |
| 21553 | "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set" |
| 21554 | ); |
| 21555 | corner_scan(w, h); |
| 21556 | } |
| 21557 | } |
| 21558 | |
| 21559 | /// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2): |
| 21560 | /// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own |
| 21561 | /// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The |
| 21562 | /// depth-0 `txfm_partition` symbol reads its context off the rect transform's |
| 21563 | /// own width/height; a `0` leaves one whole-block rect transform unit |
| 21564 | /// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE |
| 21565 | /// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the |
| 21566 | /// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so |
| 21567 | /// every leaf of a split rect block is square and the existing square leaf |
| 21568 | /// loop reconstructs it unchanged. |
| 21569 | #[allow(clippy::too_many_arguments)] |
| 21570 | fn read_block_tx_size_rect( |
| 21571 | dec: &mut SymbolDecoder, |
| 21572 | cdfs: &mut Cdfs, |
| 21573 | n: &mut Neighbours, |
| 21574 | at_mi: (usize, usize), |
| 21575 | (bw, bh): (usize, usize), |
| 21576 | (mi_cols, mi_rows): (usize, usize), |
| 21577 | skip: bool, fctx: &crate::decode::FrameCtx, |
| 21578 | ) -> Result<Option<Vec<(usize, usize, usize, usize)>>> { |
| 21579 | if lossless(fctx) { |
| 21580 | let mut leaves = Vec::new(); |
| 21581 | for row in 0..bh / MI { |
| 21582 | for col in 0..bw / MI { |
| 21583 | leaves.push((row, col, 4, 4)); |
| 21584 | } |
| 21585 | } |
| 21586 | return Ok(Some(leaves)); |
| 21587 | } |
| 21588 | if skip { |
| 21589 | // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records |
| 21590 | // its own BLOCK size -- width above, height left -- not a transform. |
| 21591 | txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh)); |
| 21592 | return Ok(None); |
| 21593 | } |
| 21594 | // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and |
| 21595 | // `rect_inter_residual_supported` has already excluded everything above 32. |
| 21596 | // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup |
| 21597 | // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block |
| 21598 | // is TWO square top-level transform units side by side and a 64x128 one is |
| 21599 | // two stacked -- exactly what libaom `read_block_tx_size` |
| 21600 | // (decodeframe.c:1140) codes with its `idy/idx` loop over |
| 21601 | // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its |
| 21602 | // own `txfm_partition` symbol at depth 0. |
| 21603 | if bw.max(bh) > 64 { |
| 21604 | let tx = 64usize; |
| 21605 | let (max_w_mi, max_h_mi) = ( |
| 21606 | (bw / MI).min(mi_cols.saturating_sub(at_mi.1)), |
| 21607 | (bh / MI).min(mi_rows.saturating_sub(at_mi.0)), |
| 21608 | ); |
| 21609 | let mut leaves = Vec::new(); |
| 21610 | if !fctx.tx_select_frame.with(std::cell::Cell::get) { |
| 21611 | for row in (0..bh / MI).step_by(tx / MI) { |
| 21612 | for col in (0..bw / MI).step_by(tx / MI) { |
| 21613 | leaves.push((row, col, tx, tx)); |
| 21614 | } |
| 21615 | } |
| 21616 | for &(row, col, tw, th) in &leaves { |
| 21617 | txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th)); |
| 21618 | } |
| 21619 | return Ok(Some(leaves)); |
| 21620 | } |
| 21621 | for row in (0..bh / MI).step_by(tx / MI) { |
| 21622 | for col in (0..bw / MI).step_by(tx / MI) { |
| 21623 | read_var_tx_size( |
| 21624 | dec, |
| 21625 | cdfs, |
| 21626 | n, |
| 21627 | at_mi, |
| 21628 | bw.max(bh), |
| 21629 | (max_w_mi, max_h_mi), |
| 21630 | (tx, tx), |
| 21631 | 0, |
| 21632 | row, |
| 21633 | col, |
| 21634 | &mut leaves, |
| 21635 | ); |
| 21636 | } |
| 21637 | } |
| 21638 | if leaves.iter().any(|l| l.2.max(l.3) > 64) { |
| 21639 | return Err(unsupported( |
| 21640 | "an inter var-tx tree with a leaf transform larger than 64x64", |
| 21641 | )); |
| 21642 | } |
| 21643 | return Ok(Some(leaves)); |
| 21644 | } |
| 21645 | let (tx_w, tx_h) = (bw, bh); |
| 21646 | if !fctx.tx_select_frame.with(std::cell::Cell::get) { |
| 21647 | // `TX_MODE_LARGEST`: no symbol at all, the whole block is one |
| 21648 | // transform, and `set_txfm_ctxs` records exactly what |
| 21649 | // `txfm_partition_update` would for that same unit. |
| 21650 | txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); |
| 21651 | hit!(RECT_INTER_TU_HITS); |
| 21652 | return Ok(None); |
| 21653 | } |
| 21654 | let ctx = txfm_partition_ctx_rect( |
| 21655 | n.above_txfm[at_mi.1], |
| 21656 | n.left_txfm[at_mi.0], |
| 21657 | bw.max(bh), |
| 21658 | tx_w, |
| 21659 | tx_h, |
| 21660 | ); |
| 21661 | let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; |
| 21662 | hit!(TXFM_SPLIT_READS); |
| 21663 | if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { |
| 21664 | let (rng, _) = dec.debug_state(); |
| 21665 | eprintln!( |
| 21666 | "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}", |
| 21667 | at_mi.0, |
| 21668 | at_mi.1, |
| 21669 | u8::from(split) |
| 21670 | ); |
| 21671 | } |
| 21672 | if !split { |
| 21673 | txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); |
| 21674 | hit!(RECT_INTER_TU_HITS); |
| 21675 | return Ok(None); |
| 21676 | } |
| 21677 | hit!(TXFM_SPLIT_HITS); |
| 21678 | hit!(RECT_INTER_TXSPLIT_HITS); |
| 21679 | // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays |
| 21680 | // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`, |
| 21681 | // `[TX_16X64] == TX_16X32` -- so the recursion below is the general |
| 21682 | // rect one and its leaves carry their own width and height. |
| 21683 | let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h); |
| 21684 | let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1)); |
| 21685 | let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0)); |
| 21686 | let mut leaves = Vec::new(); |
| 21687 | for row in (0..bh / MI).step_by(sub_h / MI) { |
| 21688 | for col in (0..bw / MI).step_by(sub_w / MI) { |
| 21689 | read_var_tx_size( |
| 21690 | dec, |
| 21691 | cdfs, |
| 21692 | n, |
| 21693 | at_mi, |
| 21694 | bw.max(bh), |
| 21695 | (max_w_mi, max_h_mi), |
| 21696 | (sub_w, sub_h), |
| 21697 | 1, |
| 21698 | row, |
| 21699 | col, |
| 21700 | &mut leaves, |
| 21701 | ); |
| 21702 | } |
| 21703 | } |
| 21704 | Ok(Some(leaves)) |
| 21705 | } |
| 21706 | |
| 21707 | /// The chroma half of a whole-block rectangular INTER transform unit (both |
| 21708 | /// [`decode_inter_block`] rect readers): `av1_get_max_uv_txsize(bsize)` gives |
| 21709 | /// the strip's own rect chroma size at 4:2:0 (one unit for the whole block), |
| 21710 | /// but at 4:4:4 the chroma plane block keeps the luma block's 64-px axis, |
| 21711 | /// which `av1_get_adjusted_tx_size` caps at 32 (`TX_64X16` -> `TX_32X16`), |
| 21712 | /// so it codes TWO units plane-major (every U, then every V -- |
| 21713 | /// `decode_token_recon_block`'s inter branch loops `for plane` outside |
| 21714 | /// `for blk_row/blk_col` inside the one mu chunk). No unit codes a `tx_type` |
| 21715 | /// symbol: each inherits the block-wide luma one (`av1_get_tx_type`'s inter |
| 21716 | /// UV lookup at ss 0 reads the tx_type_map at its own mi, which a single-TU |
| 21717 | /// luma block fills uniformly). |
| 21718 | #[allow(clippy::too_many_arguments)] |
| 21719 | fn read_inter_rect_chroma( |
| 21720 | dec: &mut SymbolDecoder, |
| 21721 | cdfs: &mut Cdfs, |
| 21722 | neighbours: &mut Neighbours, |
| 21723 | around: [(bool, bool, i32); 3], |
| 21724 | u: &mut PlaneBuf<'static>, |
| 21725 | v: &mut PlaneBuf<'static>, |
| 21726 | su: Pred<'_>, |
| 21727 | sv: Pred<'_>, |
| 21728 | at_mi: (usize, usize), |
| 21729 | (cpx, cpy): (usize, usize), |
| 21730 | (write_chroma_w, write_chroma_h): (usize, usize), |
| 21731 | chroma_side: usize, |
| 21732 | mode_for_tx: usize, |
| 21733 | luma_tx_type: TxType, |
| 21734 | fctx: &crate::decode::FrameCtx, |
| 21735 | ) -> Result<(Grid, Grid, Vec<((usize, usize), usize, Grid, usize, usize)>)> { |
| 21736 | let (uw, uh) = (write_chroma_w.min(32), write_chroma_h.min(32)); |
| 21737 | let (nx, ny) = (write_chroma_w / uw, write_chroma_h / uh); |
| 21738 | let multi = nx * ny > 1; |
| 21739 | let set = rect_inter_chroma_set(uw, uh)?; |
| 21740 | let mut assembled: [Vec<i32>; 2] = [Vec::new(), Vec::new()]; |
| 21741 | // The multi-unit stamps below are rewritten by the caller's whole-block |
| 21742 | // record (`record_rect_mi`/`record_split_luma_rect_mi` write ONE |
| 21743 | // whole-block chroma state, class `override-slot-on-one-arm`). The |
| 21744 | // block tail's square-mu derivation cannot express a non-square strip's |
| 21745 | // units, so the TRUE units travel back for the tail's `mu_chroma_units` |
| 21746 | // replay (the c8 re-stamp, at the strip's own tiling). |
| 21747 | let mut units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); |
| 21748 | if multi { |
| 21749 | hit!(CHROMA_SPLIT_TX_HITS); |
| 21750 | assembled = [ |
| 21751 | vec![0i32; chroma_side * chroma_side], |
| 21752 | vec![0i32; chroma_side * chroma_side], |
| 21753 | ]; |
| 21754 | } |
| 21755 | for plane_idx in 1..=2 { |
| 21756 | let (src, buf) = if plane_idx == 1 { (su, &mut *u) } else { (sv, &mut *v) }; |
| 21757 | for cu_row in 0..ny { |
| 21758 | for cu_col in 0..nx { |
| 21759 | let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx)); |
| 21760 | let cu_mi = ( |
| 21761 | at_mi.0 + cu_row * (span_y / MI), |
| 21762 | at_mi.1 + cu_col * (span_x / MI), |
| 21763 | ); |
| 21764 | let cu_around = if multi { |
| 21765 | neighbours.around_mi_rect(cu_mi, span_x, span_y) |
| 21766 | } else { |
| 21767 | around |
| 21768 | }; |
| 21769 | let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh); |
| 21770 | let cu_pred = src.offset(cu_row * uh * chroma_side + cu_col * uw); |
| 21771 | let cu_grid = read_inter_plane_rect( |
| 21772 | dec, |
| 21773 | cdfs, |
| 21774 | set, |
| 21775 | (uw, uh), |
| 21776 | chroma_side, |
| 21777 | plane_idx, |
| 21778 | cu_around[plane_idx], |
| 21779 | mode_for_tx, |
| 21780 | buf, |
| 21781 | cu_x, |
| 21782 | cu_y, |
| 21783 | cu_pred, |
| 21784 | Some(luma_tx_type), |
| 21785 | multi.then_some(3), fctx, |
| 21786 | )? |
| 21787 | .0; |
| 21788 | if multi { |
| 21789 | // Immediately, so the next unit of this block reads this |
| 21790 | // one's coefficient context (libaom updates the chroma |
| 21791 | // above/left contexts per unit). |
| 21792 | neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid); |
| 21793 | let dst = &mut assembled[plane_idx - 1]; |
| 21794 | for rr in 0..uh { |
| 21795 | let start = (cu_row * uh + rr) * chroma_side + cu_col * uw; |
| 21796 | dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]); |
| 21797 | } |
| 21798 | units.push((cu_mi, plane_idx, cu_grid, span_x, span_y)); |
| 21799 | } else { |
| 21800 | assembled[plane_idx - 1] = embed_rect_grid(&cu_grid, uw, uh, chroma_side); |
| 21801 | } |
| 21802 | } |
| 21803 | } |
| 21804 | } |
| 21805 | let [ug, vg] = assembled; |
| 21806 | Ok((Grid::Own(ug), Grid::Own(vg), units)) |
| 21807 | } |
| 21808 | |
| 21809 | /// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2): |
| 21810 | /// the coefficients are read with the rect coefficient machinery |
| 21811 | /// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*` |
| 21812 | /// types), inverted with the rect inverse transform |
| 21813 | /// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale), |
| 21814 | /// and added onto the top-left `w x h` of the block's own square-strided |
| 21815 | /// motion-compensated prediction buffer. Returns the *rect* coefficient grid |
| 21816 | /// and the coded `tx_type`. |
| 21817 | /// |
| 21818 | /// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e. |
| 21819 | /// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch. |
| 21820 | #[allow(clippy::too_many_arguments)] |
| 21821 | fn read_inter_plane_rect( |
| 21822 | dec: &mut SymbolDecoder, |
| 21823 | cdfs: &mut Cdfs, |
| 21824 | set: TxbSet, |
| 21825 | (w, h): (usize, usize), |
| 21826 | stride: usize, |
| 21827 | plane_idx: usize, |
| 21828 | around: (bool, bool, i32), |
| 21829 | tx_mode: usize, |
| 21830 | // lane-wave1 step (i): unread -- this reader records its write |
| 21831 | // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow |
| 21832 | // stays in the signature so every call site still proves the plane is |
| 21833 | // exclusively held while its coefficients are parsed. |
| 21834 | _plane: &mut PlaneBuf<'static>, |
| 21835 | x: usize, |
| 21836 | y: usize, |
| 21837 | prediction: Pred<'_>, |
| 21838 | inherited_luma_tx_type: Option<TxType>, |
| 21839 | luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx, |
| 21840 | ) -> Result<(Grid, TxType)> { |
| 21841 | // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma |
| 21842 | // coefficients (`plane < av1_num_planes == 1`). |
| 21843 | if plane_idx > 0 && mono(fctx) { |
| 21844 | return Ok((Grid::Zero(w * h), TxType::DctDct)); |
| 21845 | } |
| 21846 | let skip_ctx = if plane_idx == 0 { |
| 21847 | // `get_txb_ctx_general`: 0 only when this unit IS the whole plane |
| 21848 | // block; a var-tx leaf passes its own neighbour-table context. |
| 21849 | luma_skip_ctx.unwrap_or(0) |
| 21850 | } else { |
| 21851 | // libaom `get_txb_ctx`: a chroma unit's context is |
| 21852 | // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the |
| 21853 | // plane block is bigger than the transform. Our chroma tables hold the |
| 21854 | // offset-7 rows first, so a multi-unit caller adds 3 through |
| 21855 | // `luma_skip_ctx` (same convention as [`read_plane`]). |
| 21856 | usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0) |
| 21857 | }; |
| 21858 | let mut coding = cdfs.txb(set, tx_mode); |
| 21859 | // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read |
| 21860 | // transform type for lossless mode(qindex==0)" -- the symbol is not coded |
| 21861 | // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every |
| 21862 | // plane of a lossless block (the residual then goes through the WHT, so |
| 21863 | // the type only picks the scan, which is the default one). |
| 21864 | if lossless(fctx) { |
| 21865 | coding.tx_type = None; |
| 21866 | } |
| 21867 | // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e. |
| 21868 | // the *longer* side of this rect transform. |
| 21869 | let default_tx_type = match inherited_luma_tx_type { |
| 21870 | Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx), |
| 21871 | None => TxType::DctDct, |
| 21872 | }; |
| 21873 | // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is |
| 21874 | // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one. |
| 21875 | let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type }; |
| 21876 | // lane-r14 r2: a 64-length axis codes only its low 32 coefficients |
| 21877 | // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)` |
| 21878 | // corner, zero-extended into the true `w x h` grid before the inverse |
| 21879 | // transform -- exactly what the intra superblock-strip path does. A |
| 21880 | // corner that comes out square (32x32, under a 64x32/32x64 strip) reads |
| 21881 | // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`, |
| 21882 | // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted |
| 21883 | // rectangular shape (lane-sbpart r8). |
| 21884 | let (cw, ch) = (w.min(32), h.min(32)); |
| 21885 | if plane_idx == 0 && w.max(h) == 64 { |
| 21886 | hit!(RECT64_INTER_TU_HITS); |
| 21887 | } |
| 21888 | if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) { |
| 21889 | hit_do! { |
| 21890 | RECT32X8_INTER_TU_HITS.with(|c| { |
| 21891 | let mut v = c.get(); |
| 21892 | v[usize::from(w == 8)] += 1; |
| 21893 | c.set(v); |
| 21894 | }); |
| 21895 | } |
| 21896 | } |
| 21897 | let (corner, tx_type) = if (cw, ch) == (32, 32) { |
| 21898 | let scan32 = default_scan(TX32); |
| 21899 | read_coeffs( |
| 21900 | dec, |
| 21901 | &mut coding, |
| 21902 | &scan32, |
| 21903 | skip_ctx, |
| 21904 | dc_sign_ctx(around.2), |
| 21905 | default_tx_type, |
| 21906 | Some((w, h)), |
| 21907 | )? |
| 21908 | } else { |
| 21909 | read_coeffs_rect( |
| 21910 | dec, |
| 21911 | &mut coding, |
| 21912 | rect_scan(cw, ch)?, |
| 21913 | cw, |
| 21914 | ch, |
| 21915 | skip_ctx, |
| 21916 | dc_sign_ctx(around.2), |
| 21917 | default_tx_type, |
| 21918 | )? |
| 21919 | }; |
| 21920 | let grid = extend_corner(corner, cw, ch, w, h); |
| 21921 | let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx); |
| 21922 | if crate::envflags::env_flag!("EC_TRACE_TXTYPE") { |
| 21923 | eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}"); |
| 21924 | } |
| 21925 | // `reconstruct_mc_rect` reads both buffers at the square prediction |
| 21926 | // stride, so the dense `w x h` residual is re-laid at that stride |
| 21927 | // (`TxParams::stride`) after the inverse transform. |
| 21928 | let tx = TxParams { |
| 21929 | w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type, |
| 21930 | qm: block_iqmatrix(fctx, plane_idx, w, h, tx_type), |
| 21931 | stride, lossless: lossless(fctx), |
| 21932 | }; |
| 21933 | push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx); |
| 21934 | Ok((grid, tx_type)) |
| 21935 | } |
| 21936 | |
| 21937 | /// The coded `cw x ch` corner of a transform zero-extended into its true |
| 21938 | /// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A |
| 21939 | /// corner that coded nothing stays the shared zero grid -- no allocation |
| 21940 | /// (lane-coefgrid). |
| 21941 | fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid { |
| 21942 | if (cw, ch) == (w, h) { |
| 21943 | return corner; |
| 21944 | } |
| 21945 | if let Grid::Zero(_) = corner { |
| 21946 | return Grid::Zero(w * h); |
| 21947 | } |
| 21948 | let mut full = vec![0i32; w * h]; |
| 21949 | for row in 0..ch { |
| 21950 | full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]); |
| 21951 | } |
| 21952 | Grid::Own(full) |
| 21953 | } |
| 21954 | |
| 21955 | /// [`embed_rect_grid`] that keeps the shared zero marker zero: an all-zero |
| 21956 | /// transform unit's grid IS `Grid::Zero` (whose deref is the shared |
| 21957 | /// `ZERO_RESIDUAL`), so re-laying it would read a zero-length slice. |
| 21958 | fn embed_grid_stride(grid: &Grid, w: usize, h: usize, stride: usize) -> Grid { |
| 21959 | if is_zero_grid(grid) { |
| 21960 | return Grid::Zero(stride * stride); |
| 21961 | } |
| 21962 | Grid::Own(embed_rect_grid(grid, w, h, stride)) |
| 21963 | } |
| 21964 | |
| 21965 | /// A rect coefficient grid re-laid into the square `stride x stride` grid the |
| 21966 | /// neighbour/deblock stamps downstream of the residual expect. |
| 21967 | fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> { |
| 21968 | let mut full = vec![0i32; stride * stride]; |
| 21969 | for row in 0..h { |
| 21970 | full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]); |
| 21971 | } |
| 21972 | full |
| 21973 | } |
| 21974 | |
| 21975 | /// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8 |
| 21976 | /// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single |
| 21977 | /// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in |
| 21978 | /// raster order, each reading its own coefficient context off the units |
| 21979 | /// already decoded before it. Returns the block's luma grid (all-zero in the |
| 21980 | /// split case, whose reconstruction has already happened unit by unit) and |
| 21981 | /// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup, |
| 21982 | /// which for a split block lands on the top-left unit. |
| 21983 | #[allow(clippy::too_many_arguments)] |
| 21984 | fn read_inter_luma8( |
| 21985 | dec: &mut SymbolDecoder, |
| 21986 | cdfs: &mut Cdfs, |
| 21987 | neighbours: &mut Neighbours, |
| 21988 | leaf_mi: (usize, usize), |
| 21989 | y: &mut PlaneBuf<'static>, |
| 21990 | px: usize, |
| 21991 | py: usize, |
| 21992 | pred_y: Pred<'_>, |
| 21993 | mode_for_tx: usize, |
| 21994 | base_q_idx: u8, |
| 21995 | scan8: &[u16], |
| 21996 | scan4: &[u16], |
| 21997 | reduced_tx_set: bool, |
| 21998 | split: bool, fctx: &crate::decode::FrameCtx, |
| 21999 | ) -> Result<(Grid, TxType)> { |
| 22000 | // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom |
| 22001 | // `read_block_tx_size`'s lossless TX_4X4), tree or no tree. |
| 22002 | let split = split || lossless(fctx); |
| 22003 | if !split { |
| 22004 | return read_inter_plane( |
| 22005 | dec, |
| 22006 | cdfs, |
| 22007 | if reduced_tx_set { |
| 22008 | TxbSet::Luma8Inter |
| 22009 | } else { |
| 22010 | TxbSet::Luma8InterSet1 |
| 22011 | }, |
| 22012 | scan8, |
| 22013 | 0, |
| 22014 | neighbours.around_mi(leaf_mi, 8)[0], |
| 22015 | mode_for_tx, |
| 22016 | y, |
| 22017 | px, |
| 22018 | py, |
| 22019 | 8, |
| 22020 | base_q_idx, |
| 22021 | pred_y, |
| 22022 | None, |
| 22023 | None, fctx, |
| 22024 | ); |
| 22025 | } |
| 22026 | let mut first = TxType::DctDct; |
| 22027 | for tu_row in 0..2 { |
| 22028 | for tu_col in 0..2 { |
| 22029 | let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col); |
| 22030 | let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4); |
| 22031 | let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); |
| 22032 | let (tu_grid, tu_tx_type) = read_inter_plane( |
| 22033 | dec, |
| 22034 | cdfs, |
| 22035 | if reduced_tx_set { |
| 22036 | TxbSet::Luma4Inter |
| 22037 | } else { |
| 22038 | TxbSet::Luma4InterSet1 |
| 22039 | }, |
| 22040 | scan4, |
| 22041 | 0, |
| 22042 | neighbours.around_mi(tu_mi, 4)[0], |
| 22043 | mode_for_tx, |
| 22044 | y, |
| 22045 | px + tu_col * 4, |
| 22046 | py + tu_row * 4, |
| 22047 | 4, |
| 22048 | base_q_idx, |
| 22049 | tu_pred, |
| 22050 | None, |
| 22051 | Some(tu_skip_ctx), fctx, |
| 22052 | )?; |
| 22053 | if tu_row == 0 && tu_col == 0 { |
| 22054 | first = tu_tx_type; |
| 22055 | } |
| 22056 | neighbours.record_mi_luma(tu_mi, 4, &tu_grid); |
| 22057 | } |
| 22058 | } |
| 22059 | Ok((Grid::Zero(64), first)) |
| 22060 | } |
| 22061 | |
| 22062 | /// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its |
| 22063 | /// coefficient tables from -- the inter counterpart of [`txbset_for`]. |
| 22064 | /// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`): |
| 22065 | /// an inter block's chroma transform inherits the *colocated luma* unit's |
| 22066 | /// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member |
| 22067 | /// of the extended set the CHROMA transform size selects |
| 22068 | /// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`, |
| 22069 | /// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at |
| 22070 | /// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is |
| 22071 | /// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads |
| 22072 | /// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded |
| 22073 | /// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are |
| 22074 | /// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in |
| 22075 | /// sync and only corrupted the inverse transform (one 64x64 superblock of |
| 22076 | /// high-frequency chroma noise, luma bit-exact). |
| 22077 | pub(crate) fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType { |
| 22078 | reduce_inherited_chroma_tx_type_flagged(t, w, h, fctx.reduced_tx_set_inter.with(std::cell::Cell::get)) |
| 22079 | } |
| 22080 | |
| 22081 | /// [`reduce_inherited_chroma_tx_type`] against an explicit `reduced_tx_set` |
| 22082 | /// bit (lane-intertx): the WRITER calls this with the frame's own header bit |
| 22083 | /// ([`crate::cdf_state::Cdfs::reduced_tx_set`]) to derive the type an inter |
| 22084 | /// block's chroma transform is coded with, the same derivation its reader |
| 22085 | /// makes -- it has no `FrameCtx` in reach and must not silently read one |
| 22086 | /// whose value can lag the frame being written (class `stale-context-bit`). |
| 22087 | pub(crate) fn reduce_inherited_chroma_tx_type_flagged(t: TxType, w: usize, h: usize, reduced: bool) -> TxType { |
| 22088 | use TxType::*; |
| 22089 | let sqr_up = w.max(h); |
| 22090 | let sqr = w.min(h); |
| 22091 | // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`. |
| 22092 | let allowed: &[TxType] = if sqr_up > 32 { |
| 22093 | // EXT_TX_SET_DCTONLY |
| 22094 | &[DctDct] |
| 22095 | } else if sqr_up == 32 || reduced { |
| 22096 | // EXT_TX_SET_DCT_IDTX |
| 22097 | &[DctDct, Idtx] |
| 22098 | } else if sqr == 16 { |
| 22099 | // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but |
| 22100 | // the four 1D ADST/FLIPADST types. |
| 22101 | &[ |
| 22102 | DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst, |
| 22103 | AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct, |
| 22104 | ] |
| 22105 | } else { |
| 22106 | // EXT_TX_SET_ALL16 |
| 22107 | return t; |
| 22108 | }; |
| 22109 | if allowed.contains(&t) { t } else { DctDct } |
| 22110 | } |
| 22111 | |
| 22112 | /// The [`TxbSet`] a resolved luma transform side reads its coefficient tables |
| 22113 | /// from for a block libaom's `is_inter_block` calls inter -- which an intrabc |
| 22114 | /// block is (`blockd.h:373`), so its `tx_type` comes off the inter `ext_tx` |
| 22115 | /// sets, never the mode-indexed intra ones ([`txbset_for`]). |
| 22116 | /// |
| 22117 | /// 64 is only ever the 64x64-block, depth-0, corner-scanned case |
| 22118 | /// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching |
| 22119 | /// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at |
| 22120 | /// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2` |
| 22121 | /// regardless of the flag (`av1_get_ext_tx_set_type`'s |
| 22122 | /// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past |
| 22123 | /// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a |
| 22124 | /// second table ([`TxbSet::Luma8Inter`]/[`TxbSet::Luma4Inter`]). |
| 22125 | /// |
| 22126 | /// lane-av1txr: the intrabc leaf sites used to call a near-duplicate |
| 22127 | /// `txbset_for_inter` whose `4` fell through to `Luma64` -- 32x32-class tables |
| 22128 | /// (a 1024-entry grid) handed to a 4x4 dequant, which panicked at |
| 22129 | /// `transform.rs`'s `inverse_transform_2d_typed_wh` the first time an intrabc |
| 22130 | /// 4x4 TU coded a non-zero coefficient (`allintra0`/cpu-used=0). The |
| 22131 | /// duplicate is gone; every inter-table site goes through this one mapping. |
| 22132 | fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet { |
| 22133 | match tx_px { |
| 22134 | // lane-sb128c r1: a 128x128 inter block's own luma unit |
| 22135 | // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`). |
| 22136 | // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up == |
| 22137 | // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets |
| 22138 | // coincide -- exactly the set the whole-64x64 inter block already uses. |
| 22139 | 64 => TxbSet::Luma64, |
| 22140 | 32 => TxbSet::Luma32Inter, |
| 22141 | 16 if reduced_tx_set => TxbSet::Luma16Inter, |
| 22142 | 16 => TxbSet::Luma16InterSet1, |
| 22143 | 8 if reduced_tx_set => TxbSet::Luma8Inter, |
| 22144 | 8 => TxbSet::Luma8InterSet1, |
| 22145 | 4 if reduced_tx_set => TxbSet::Luma4Inter, |
| 22146 | 4 => TxbSet::Luma4InterSet1, |
| 22147 | _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"), |
| 22148 | } |
| 22149 | } |
| 22150 | |
| 22151 | /// The luma coefficient scan table for a resolved transform side -- 32/16/8/4, |
| 22152 | /// the only four sizes a `TxMode::Select` block's coded coefficient grid |
| 22153 | /// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be. |
| 22154 | fn scan_for<'a>( |
| 22155 | tx_px: usize, |
| 22156 | scan32: &'a [u16], |
| 22157 | scan16: &'a [u16], |
| 22158 | scan8: &'a [u16], |
| 22159 | scan4: &'a [u16], |
| 22160 | ) -> &'a [u16] { |
| 22161 | match tx_px { |
| 22162 | 32 => scan32, |
| 22163 | 16 => scan16, |
| 22164 | 8 => scan8, |
| 22165 | 4 => scan4, |
| 22166 | _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"), |
| 22167 | } |
| 22168 | } |
| 22169 | |
| 22170 | |
| 22171 | fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet { |
| 22172 | match tx_px { |
| 22173 | 64 => TxbSet::Luma64, |
| 22174 | 32 => TxbSet::Luma32, |
| 22175 | 16 => TxbSet::Luma16, |
| 22176 | 8 if reduced_tx_set => TxbSet::Luma8, |
| 22177 | 8 => TxbSet::Luma8Set1, |
| 22178 | 4 if reduced_tx_set => TxbSet::Luma4, |
| 22179 | 4 => TxbSet::Luma4Set1, |
| 22180 | _ => unreachable!("read_tx_size never resolves a block's own side to anything else"), |
| 22181 | } |
| 22182 | } |
| 22183 | |
| 22184 | /// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the |
| 22185 | /// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on. |
| 22186 | fn unit_log2(px: u32) -> i32 { |
| 22187 | if px == 0 { |
| 22188 | 0 |
| 22189 | } else { |
| 22190 | px.trailing_zeros() as i32 - 2 |
| 22191 | } |
| 22192 | } |
| 22193 | |
| 22194 | /// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's |
| 22195 | /// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for |
| 22196 | /// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode |
| 22197 | /// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell: |
| 22198 | /// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2: |
| 22199 | /// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable |
| 22200 | /// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME` |
| 22201 | /// block anywhere aborted the whole stream's decode before comparison). |
| 22202 | fn lf_level( |
| 22203 | lf: &LoopFilterParams, |
| 22204 | plane_idx: usize, |
| 22205 | dir: usize, |
| 22206 | ref_frame: i8, |
| 22207 | delta_lf: i32, |
| 22208 | segment_id: u8, fctx: &crate::decode::FrameCtx, |
| 22209 | ) -> i32 { |
| 22210 | let base = i32::from(if plane_idx == 0 { |
| 22211 | lf.level[dir] |
| 22212 | } else if plane_idx == 1 { |
| 22213 | lf.level[2] |
| 22214 | } else { |
| 22215 | lf.level[3] |
| 22216 | }); |
| 22217 | // spec 7.14.4: the per-superblock `DeltaLF` term applies before the |
| 22218 | // ref/mode delta scaling below, and regardless of `delta_enabled` |
| 22219 | // (that flag only gates `ref_deltas`/`mode_deltas`). |
| 22220 | let base = (base + delta_lf).clamp(0, 63); |
| 22221 | // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this |
| 22222 | // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the |
| 22223 | // per-superblock `DeltaLF` term and before the ref/mode deltas below. |
| 22224 | // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4) |
| 22225 | // for chroma. |
| 22226 | let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 }; |
| 22227 | // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely |
| 22228 | // when the frame codes no segmentation (`seg_lf_active`), which is what |
| 22229 | // spares the deblock loop two thread-local reads per 4x4 edge. |
| 22230 | let base = match seg_feature(usize::from(segment_id), feature, fctx) { |
| 22231 | Some(data) => (base + data).clamp(0, 63), |
| 22232 | None => base, |
| 22233 | }; |
| 22234 | if !lf.delta_enabled { |
| 22235 | return base; |
| 22236 | } |
| 22237 | let scale = 1i32 << (base >> 5); |
| 22238 | let is_inter = ref_frame != 0; |
| 22239 | let is_globalmv = ref_frame < 0; |
| 22240 | let ref_idx = ref_frame.unsigned_abs() as usize; |
| 22241 | let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale; |
| 22242 | if is_inter { |
| 22243 | lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale; |
| 22244 | } |
| 22245 | lvl.clamp(0, 63) |
| 22246 | } |
| 22247 | |
| 22248 | thread_local! { |
| 22249 | /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table |
| 22250 | /// is a pure function of the frame's [`LoopFilterParams`], the plane, the |
| 22251 | /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing |
| 22252 | /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one |
| 22253 | /// build per plane and pass serves the whole frame. The pipeline builds |
| 22254 | /// an `EdgeCtx` per superblock-row band rather than per frame, which |
| 22255 | /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each. |
| 22256 | static LVL_CACHE: std::cell::RefCell< |
| 22257 | Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>, |
| 22258 | > = const { std::cell::RefCell::new(Vec::new()) }; |
| 22259 | } |
| 22260 | |
| 22261 | /// `lf_level` over the whole `(base level, ref frame)` domain -- see |
| 22262 | /// [`LVL_CACHE`]. `lf_level`'s own first step is |
| 22263 | /// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at |
| 22264 | /// `b` and the rest of the function is a pure function of `(b, ref_frame)`. |
| 22265 | fn lvl_table( |
| 22266 | lf: &LoopFilterParams, |
| 22267 | plane_idx: usize, |
| 22268 | dir: usize, |
| 22269 | base0: i32, |
| 22270 | fctx: &crate::decode::FrameCtx, |
| 22271 | ) -> [[u8; 15]; 64] { |
| 22272 | let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 }; |
| 22273 | let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx)); |
| 22274 | if let Some(t) = LVL_CACHE.with(|c| { |
| 22275 | c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t) |
| 22276 | }) { |
| 22277 | return t; |
| 22278 | } |
| 22279 | let mut lvl = [[0u8; 15]; 64]; |
| 22280 | for (b, row) in lvl.iter_mut().enumerate() { |
| 22281 | for (r, cell) in row.iter_mut().enumerate() { |
| 22282 | *cell = |
| 22283 | lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8; |
| 22284 | } |
| 22285 | } |
| 22286 | LVL_CACHE.with(|c| { |
| 22287 | let mut c = c.borrow_mut(); |
| 22288 | if c.len() >= 8 { |
| 22289 | c.remove(0); |
| 22290 | } |
| 22291 | c.push((key, lvl)); |
| 22292 | }); |
| 22293 | lvl |
| 22294 | } |
| 22295 | |
| 22296 | /// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level, |
| 22297 | /// no-segmentation, no-delta-LF path and to this decoder's own invariant |
| 22298 | /// that a coded block's transform is always its own full size -- so a TU |
| 22299 | /// edge is always also a PU edge, and the "both sides skipped, not a PU |
| 22300 | /// edge" suppression (which only ever fires at a non-PU-edge TU boundary) |
| 22301 | /// never applies here, letting this skip the `skip`/`skip_txfm` lookup |
| 22302 | /// entirely. Returns `None` when this 4-pixel edge group is not filtered. |
| 22303 | /// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the |
| 22304 | /// seven values that used to be re-passed per 4-pixel edge group -- half of |
| 22305 | /// them on the stack, into an `inline(never)` body -- plus libaom's |
| 22306 | /// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the |
| 22307 | /// filter level for every `(base level, ref frame)` pair once per frame |
| 22308 | /// instead of running `av1_get_filter_level`'s delta arithmetic per edge. |
| 22309 | struct EdgeCtx<'a> { |
| 22310 | lf: &'a LoopFilterParams, |
| 22311 | n: &'a Neighbours, |
| 22312 | fctx: &'a crate::decode::FrameCtx, |
| 22313 | plane_idx: usize, |
| 22314 | dir: usize, |
| 22315 | chroma: bool, |
| 22316 | seg_lf_active: bool, |
| 22317 | /// `delta_lf_grid`'s column for this plane and direction. |
| 22318 | delta_idx: usize, |
| 22319 | /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for |
| 22320 | /// chroma. |
| 22321 | step: usize, |
| 22322 | /// This pass's own `lf.level[..]`, the LUT's base. |
| 22323 | base0: i32, |
| 22324 | /// `lf_level` at `[base level][ref frame + 7]`, with no segment |
| 22325 | /// override -- the whole domain, since a level is `0..=63` and a ref |
| 22326 | /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8 |
| 22327 | /// entries and is indexed by the ref frame's magnitude). |
| 22328 | lvl: [[u8; 15]; 64], |
| 22329 | } |
| 22330 | |
| 22331 | impl<'a> EdgeCtx<'a> { |
| 22332 | fn new( |
| 22333 | lf: &'a LoopFilterParams, |
| 22334 | n: &'a Neighbours, |
| 22335 | plane_idx: usize, |
| 22336 | dir: usize, |
| 22337 | chroma: bool, |
| 22338 | seg_lf_active: bool, |
| 22339 | fctx: &'a crate::decode::FrameCtx, |
| 22340 | ) -> Self { |
| 22341 | let base0 = i32::from(if plane_idx == 0 { |
| 22342 | lf.level[dir] |
| 22343 | } else if plane_idx == 1 { |
| 22344 | lf.level[2] |
| 22345 | } else { |
| 22346 | lf.level[3] |
| 22347 | }); |
| 22348 | let lvl = lvl_table(lf, plane_idx, dir, base0, fctx); |
| 22349 | Self { |
| 22350 | lf, |
| 22351 | n, |
| 22352 | fctx, |
| 22353 | plane_idx, |
| 22354 | dir, |
| 22355 | chroma, |
| 22356 | seg_lf_active, |
| 22357 | delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 }, |
| 22358 | step: if chroma { 1 << (if dir == 0 { ss_x(fctx) } else { ss_y(fctx) }) } else { 1 }, |
| 22359 | base0, |
| 22360 | lvl, |
| 22361 | } |
| 22362 | } |
| 22363 | |
| 22364 | /// Spec 7.14.4's `get_filter_level`, off the table when no segment can |
| 22365 | /// override it (which is every frame that codes no segmentation). |
| 22366 | #[inline(always)] |
| 22367 | fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 { |
| 22368 | if self.seg_lf_active { |
| 22369 | return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx); |
| 22370 | } |
| 22371 | let b = (self.base0 + delta_lf).clamp(0, 63) as usize; |
| 22372 | debug_assert!((-7..=7).contains(&ref_frame)); |
| 22373 | let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize; |
| 22374 | i32::from(self.lvl[b][r]) |
| 22375 | } |
| 22376 | } |
| 22377 | |
| 22378 | /// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level, |
| 22379 | /// no-segmentation, no-delta-LF path and to this decoder's own invariant |
| 22380 | /// that a coded block's transform is always its own full size -- so a TU |
| 22381 | /// edge is always also a PU edge, and the "both sides skipped, not a PU |
| 22382 | /// edge" suppression (which only ever fires at a non-PU-edge TU boundary) |
| 22383 | /// never applies here, letting this skip the `skip`/`skip_txfm` lookup |
| 22384 | /// entirely. Returns `None` when this 4-pixel edge group is not filtered. |
| 22385 | #[inline(always)] |
| 22386 | fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> { |
| 22387 | let (mi_r, mi_c) = ( |
| 22388 | plane_to_mi(c.chroma, y0, if c.chroma { ss_y(c.fctx) } else { 0 }), |
| 22389 | plane_to_mi(c.chroma, x0, if c.chroma { ss_x(c.fctx) } else { 0 }), |
| 22390 | ); |
| 22391 | let cur_tx = if c.dir == 0 { |
| 22392 | tx_px_at(c.n, c.chroma, mi_r, mi_c) |
| 22393 | } else { |
| 22394 | tx_h_px_at(c.n, c.chroma, mi_r, mi_c) |
| 22395 | }; |
| 22396 | // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment |
| 22397 | // test is a mask, not the hardware `divl` this used to emit (10.7% of |
| 22398 | // `edge_params`' own samples sat on that divide's result test). |
| 22399 | // |
| 22400 | // Most 4-pixel edge groups die right here (a 4-aligned coordinate that |
| 22401 | // the covering transform does not start at), so this head is inlined |
| 22402 | // into the deblock loops and only survivors pay the call and the |
| 22403 | // register-spilling prologue of the body below. |
| 22404 | if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 { |
| 22405 | return None; |
| 22406 | } |
| 22407 | edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx) |
| 22408 | } |
| 22409 | |
| 22410 | /// [`edge_params`] past its transform-alignment gate. |
| 22411 | #[inline(never)] |
| 22412 | fn edge_params_body( |
| 22413 | c: &EdgeCtx, |
| 22414 | x0: usize, |
| 22415 | y0: usize, |
| 22416 | mi_r: usize, |
| 22417 | mi_c: usize, |
| 22418 | cur_tx: u32, |
| 22419 | ) -> Option<(u8, i32)> { |
| 22420 | let n = c.n; |
| 22421 | let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c]; |
| 22422 | // The previous cell must keep the odd parity `plane_to_mi` just |
| 22423 | // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group, |
| 22424 | // not the other half of this one. |
| 22425 | let (pv_mi_r, pv_mi_c) = if c.dir == 0 { |
| 22426 | (mi_r, mi_c - c.step) |
| 22427 | } else { |
| 22428 | (mi_r - c.step, mi_c) |
| 22429 | }; |
| 22430 | let pv_tx = if c.dir == 0 { |
| 22431 | tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c) |
| 22432 | } else { |
| 22433 | tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c) |
| 22434 | }; |
| 22435 | let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c]; |
| 22436 | let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]); |
| 22437 | let pv_delta_lf = |
| 22438 | i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]); |
| 22439 | |
| 22440 | // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two |
| 22441 | // SKIPPED INTER blocks is filtered only when it is also a prediction |
| 22442 | // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The |
| 22443 | // omission of this term (on the stale invariant "a coded block's transform |
| 22444 | // is always its own full size", which var-tx broke) had us filtering an |
| 22445 | // interior 8-px lattice the reference never touches: on the pinned 192x68 |
| 22446 | // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0. |
| 22447 | // libaom prices `pu_edge` in the PLANE's own pixels against the plane's |
| 22448 | // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] - |
| 22449 | // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma |
| 22450 | // edge of a sub-8x8 group is a prediction edge, even though the group's |
| 22451 | // bottom/right mi does not start there. Comparing mi origins instead is |
| 22452 | // the same test only while the block's own origin is aligned to its |
| 22453 | // size, which a 4x4 luma block read at the `| 1` mi is not. |
| 22454 | let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c]; |
| 22455 | let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim); |
| 22456 | let (org_px, dim_mi) = if c.dir == 0 { |
| 22457 | (usize::from(cur_org[1]), usize::from(cur_dim[0])) |
| 22458 | } else { |
| 22459 | (usize::from(cur_org[0]), usize::from(cur_dim[1])) |
| 22460 | }; |
| 22461 | let pu_edge = if c.chroma { |
| 22462 | let ss = if c.dir == 0 { ss_x(c.fctx) } else { ss_y(c.fctx) }; |
| 22463 | let plane_dim = ((dim_mi * MI) >> ss).max(4); |
| 22464 | (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0 |
| 22465 | } else { |
| 22466 | plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }, 0) == org_px |
| 22467 | }; |
| 22468 | if !pu_edge |
| 22469 | && cur_ref != 0 |
| 22470 | && pv_ref != 0 |
| 22471 | && n.skip_at(mi_r, mi_c) |
| 22472 | && n.skip_at(pv_mi_r, pv_mi_c) |
| 22473 | { |
| 22474 | return None; |
| 22475 | } |
| 22476 | let (cur_seg, pv_seg) = if c.seg_lf_active { |
| 22477 | (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx)) |
| 22478 | } else { |
| 22479 | (0, 0) |
| 22480 | }; |
| 22481 | let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg); |
| 22482 | let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg); |
| 22483 | if cur_level == 0 && pv_level == 0 { |
| 22484 | return None; |
| 22485 | } |
| 22486 | let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize; |
| 22487 | let len: u8 = if c.chroma { |
| 22488 | if dim == 0 { 4 } else { 6 } |
| 22489 | } else { |
| 22490 | [4, 8, 14, 14, 14][dim] |
| 22491 | }; |
| 22492 | let level = if cur_level != 0 { cur_level } else { pv_level }; |
| 22493 | hit!(DEBLOCK_HITS); |
| 22494 | Some((len, level)) |
| 22495 | } |
| 22496 | |
| 22497 | /// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple. |
| 22498 | fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) { |
| 22499 | let sharpness = i32::from(sharpness); |
| 22500 | let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4); |
| 22501 | let mut lim = level >> shift; |
| 22502 | if sharpness > 0 { |
| 22503 | lim = lim.min(9 - sharpness); |
| 22504 | } |
| 22505 | lim = lim.max(1); |
| 22506 | (2 * (level + 2) + lim, lim, level >> 4) |
| 22507 | } |
| 22508 | |
| 22509 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 22510 | fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 { |
| 22511 | // libaom's `signed_char_clamp_high`: the clamp range scales with |
| 22512 | // `128 << (bit_depth - 8)` alongside the centering constant below. |
| 22513 | let scale = 1i32 << (bit_depth(fctx) - 8); |
| 22514 | v.clamp(-128 * scale, 128 * scale - 1) |
| 22515 | } |
| 22516 | |
| 22517 | fn round_pow2(v: i32, n: u32) -> i32 { |
| 22518 | (v + (1 << (n - 1))) >> n |
| 22519 | } |
| 22520 | |
| 22521 | /// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat |
| 22522 | /// fallback. |
| 22523 | fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] { |
| 22524 | if !mask { |
| 22525 | return [p1, p0, q0, q1]; |
| 22526 | } |
| 22527 | let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh; |
| 22528 | // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of |
| 22529 | // this kernel's eight clamps, and this kernel runs per deblocked sample. |
| 22530 | // Same bound, resolved once. |
| 22531 | let scale = 1i32 << (bit_depth(fctx) - 8); |
| 22532 | let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1); |
| 22533 | let centre = 128i32 * scale; |
| 22534 | let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre); |
| 22535 | let outer = if hev { sclamp(ps1 - qs1) } else { 0 }; |
| 22536 | let filter = sclamp(outer + 3 * (qs0 - ps0)); |
| 22537 | let filter1 = sclamp(filter + 4) >> 3; |
| 22538 | let filter2 = sclamp(filter + 3) >> 3; |
| 22539 | let oq0 = sclamp(qs0 - filter1) + centre; |
| 22540 | let op0 = sclamp(ps0 + filter2) + centre; |
| 22541 | let tap = if hev { 0 } else { round_pow2(filter1, 1) }; |
| 22542 | let oq1 = sclamp(qs1 - tap) + centre; |
| 22543 | let op1 = sclamp(ps1 + tap) + centre; |
| 22544 | [op1, op0, oq0, oq1] |
| 22545 | } |
| 22546 | |
| 22547 | /// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over |
| 22548 | /// `filter4`'s narrow taps. |
| 22549 | #[allow(clippy::too_many_arguments)] |
| 22550 | fn filter6( |
| 22551 | mask: bool, |
| 22552 | thresh: i32, |
| 22553 | flat: bool, |
| 22554 | p2: i32, |
| 22555 | p1: i32, |
| 22556 | p0: i32, |
| 22557 | q0: i32, |
| 22558 | q1: i32, |
| 22559 | q2: i32, fctx: &crate::decode::FrameCtx, |
| 22560 | ) -> [i32; 4] { |
| 22561 | if flat && mask { |
| 22562 | [ |
| 22563 | round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3), |
| 22564 | round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3), |
| 22565 | round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3), |
| 22566 | round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3), |
| 22567 | ] |
| 22568 | } else { |
| 22569 | filter4(mask, thresh, p1, p0, q0, q1, fctx) |
| 22570 | } |
| 22571 | } |
| 22572 | |
| 22573 | /// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`). |
| 22574 | #[allow(clippy::too_many_arguments)] |
| 22575 | fn filter8( |
| 22576 | mask: bool, |
| 22577 | thresh: i32, |
| 22578 | flat: bool, |
| 22579 | p3: i32, |
| 22580 | p2: i32, |
| 22581 | p1: i32, |
| 22582 | p0: i32, |
| 22583 | q0: i32, |
| 22584 | q1: i32, |
| 22585 | q2: i32, |
| 22586 | q3: i32, fctx: &crate::decode::FrameCtx, |
| 22587 | ) -> [i32; 6] { |
| 22588 | if flat && mask { |
| 22589 | [ |
| 22590 | round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3), |
| 22591 | round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3), |
| 22592 | round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3), |
| 22593 | round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3), |
| 22594 | round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3), |
| 22595 | round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3), |
| 22596 | ] |
| 22597 | } else { |
| 22598 | let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx); |
| 22599 | [p2, op1, op0, oq0, oq1, q2] |
| 22600 | } |
| 22601 | } |
| 22602 | |
| 22603 | /// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform |
| 22604 | /// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either |
| 22605 | /// way -- they are only ever taps here, never written). |
| 22606 | #[allow(clippy::too_many_arguments)] |
| 22607 | fn filter14( |
| 22608 | mask: bool, |
| 22609 | thresh: i32, |
| 22610 | flat: bool, |
| 22611 | flat2: bool, |
| 22612 | p6: i32, |
| 22613 | p5: i32, |
| 22614 | p4: i32, |
| 22615 | p3: i32, |
| 22616 | p2: i32, |
| 22617 | p1: i32, |
| 22618 | p0: i32, |
| 22619 | q0: i32, |
| 22620 | q1: i32, |
| 22621 | q2: i32, |
| 22622 | q3: i32, |
| 22623 | q4: i32, |
| 22624 | q5: i32, |
| 22625 | q6: i32, fctx: &crate::decode::FrameCtx, |
| 22626 | ) -> [i32; 12] { |
| 22627 | if flat2 && flat && mask { |
| 22628 | [ |
| 22629 | round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4), |
| 22630 | round_pow2( |
| 22631 | p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1, |
| 22632 | 4, |
| 22633 | ), |
| 22634 | round_pow2( |
| 22635 | p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2, |
| 22636 | 4, |
| 22637 | ), |
| 22638 | round_pow2( |
| 22639 | p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3, |
| 22640 | 4, |
| 22641 | ), |
| 22642 | round_pow2( |
| 22643 | p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4, |
| 22644 | 4, |
| 22645 | ), |
| 22646 | round_pow2( |
| 22647 | p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5, |
| 22648 | 4, |
| 22649 | ), |
| 22650 | round_pow2( |
| 22651 | p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6, |
| 22652 | 4, |
| 22653 | ), |
| 22654 | round_pow2( |
| 22655 | p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2, |
| 22656 | 4, |
| 22657 | ), |
| 22658 | round_pow2( |
| 22659 | p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3, |
| 22660 | 4, |
| 22661 | ), |
| 22662 | round_pow2( |
| 22663 | p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4, |
| 22664 | 4, |
| 22665 | ), |
| 22666 | round_pow2( |
| 22667 | p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5, |
| 22668 | 4, |
| 22669 | ), |
| 22670 | round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4), |
| 22671 | ] |
| 22672 | } else { |
| 22673 | let [op2, op1, op0, oq0, oq1, oq2] = |
| 22674 | filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx); |
| 22675 | [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5] |
| 22676 | } |
| 22677 | } |
| 22678 | |
| 22679 | /// Filters one 4-pixel edge group: `base` is the plane-local byte offset of |
| 22680 | /// the first (`q0`) sample past the edge, `outer_stride` advances to the |
| 22681 | /// next of the 4 perpendicular samples, `tap_stride` steps from one tap to |
| 22682 | /// the next along the edge's own filtering direction. |
| 22683 | #[allow(clippy::too_many_arguments)] |
| 22684 | fn filter_edge( |
| 22685 | data: &mut [u16], |
| 22686 | base: usize, |
| 22687 | outer_stride: isize, |
| 22688 | tap_stride: isize, |
| 22689 | len: u8, |
| 22690 | level: i32, |
| 22691 | sharpness: u8, fctx: &crate::decode::FrameCtx, |
| 22692 | ) { |
| 22693 | let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness); |
| 22694 | // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`: |
| 22695 | // every 8-bit threshold (including the flat masks' fixed `1`) is |
| 22696 | // compared against a raw pixel difference on the stream's own bit-depth |
| 22697 | // scale, so each is shifted left by `bit_depth - 8` before use. |
| 22698 | let shift = bit_depth(fctx) - 8; |
| 22699 | let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift); |
| 22700 | let flat_thresh = 1i32 << shift; |
| 22701 | let smax = sample_max(fctx); |
| 22702 | for i in 0..4isize { |
| 22703 | let center = (base as isize + i * outer_stride) as usize; |
| 22704 | let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize }; |
| 22705 | let px = |k: isize| -> i32 { i32::from(data[idx(k)]) }; |
| 22706 | match len { |
| 22707 | 4 => { |
| 22708 | let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1)); |
| 22709 | let mask = (p1 - p0).abs() <= limit |
| 22710 | && (q1 - q0).abs() <= limit |
| 22711 | && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; |
| 22712 | let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx); |
| 22713 | data[idx(-2)] = op1.clamp(0, smax) as u16; |
| 22714 | data[idx(-1)] = op0.clamp(0, smax) as u16; |
| 22715 | data[idx(0)] = oq0.clamp(0, smax) as u16; |
| 22716 | data[idx(1)] = oq1.clamp(0, smax) as u16; |
| 22717 | } |
| 22718 | 6 => { |
| 22719 | let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2)); |
| 22720 | let mask = (p2 - p1).abs() <= limit |
| 22721 | && (p1 - p0).abs() <= limit |
| 22722 | && (q1 - q0).abs() <= limit |
| 22723 | && (q2 - q1).abs() <= limit |
| 22724 | && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; |
| 22725 | let flat = (p1 - p0).abs() <= flat_thresh |
| 22726 | && (q1 - q0).abs() <= flat_thresh |
| 22727 | && (p2 - p0).abs() <= flat_thresh |
| 22728 | && (q2 - q0).abs() <= flat_thresh; |
| 22729 | let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx); |
| 22730 | data[idx(-2)] = op1.clamp(0, smax) as u16; |
| 22731 | data[idx(-1)] = op0.clamp(0, smax) as u16; |
| 22732 | data[idx(0)] = oq0.clamp(0, smax) as u16; |
| 22733 | data[idx(1)] = oq1.clamp(0, smax) as u16; |
| 22734 | } |
| 22735 | 8 => { |
| 22736 | let (p3, p2, p1, p0, q0, q1, q2, q3) = |
| 22737 | (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3)); |
| 22738 | let mask = (p3 - p2).abs() <= limit |
| 22739 | && (p2 - p1).abs() <= limit |
| 22740 | && (p1 - p0).abs() <= limit |
| 22741 | && (q1 - q0).abs() <= limit |
| 22742 | && (q2 - q1).abs() <= limit |
| 22743 | && (q3 - q2).abs() <= limit |
| 22744 | && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; |
| 22745 | let flat = (p1 - p0).abs() <= flat_thresh |
| 22746 | && (q1 - q0).abs() <= flat_thresh |
| 22747 | && (p2 - p0).abs() <= flat_thresh |
| 22748 | && (q2 - q0).abs() <= flat_thresh |
| 22749 | && (p3 - p0).abs() <= flat_thresh |
| 22750 | && (q3 - q0).abs() <= flat_thresh; |
| 22751 | let [op2, op1, op0, oq0, oq1, oq2] = |
| 22752 | filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx); |
| 22753 | data[idx(-3)] = op2.clamp(0, smax) as u16; |
| 22754 | data[idx(-2)] = op1.clamp(0, smax) as u16; |
| 22755 | data[idx(-1)] = op0.clamp(0, smax) as u16; |
| 22756 | data[idx(0)] = oq0.clamp(0, smax) as u16; |
| 22757 | data[idx(1)] = oq1.clamp(0, smax) as u16; |
| 22758 | data[idx(2)] = oq2.clamp(0, smax) as u16; |
| 22759 | } |
| 22760 | _ => { |
| 22761 | let (p6, p5, p4, p3, p2, p1, p0) = |
| 22762 | (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1)); |
| 22763 | let (q0, q1, q2, q3, q4, q5, q6) = |
| 22764 | (px(0), px(1), px(2), px(3), px(4), px(5), px(6)); |
| 22765 | let mask = (p3 - p2).abs() <= limit |
| 22766 | && (p2 - p1).abs() <= limit |
| 22767 | && (p1 - p0).abs() <= limit |
| 22768 | && (q1 - q0).abs() <= limit |
| 22769 | && (q2 - q1).abs() <= limit |
| 22770 | && (q3 - q2).abs() <= limit |
| 22771 | && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit; |
| 22772 | let flat = (p1 - p0).abs() <= flat_thresh |
| 22773 | && (q1 - q0).abs() <= flat_thresh |
| 22774 | && (p2 - p0).abs() <= flat_thresh |
| 22775 | && (q2 - q0).abs() <= flat_thresh |
| 22776 | && (p3 - p0).abs() <= flat_thresh |
| 22777 | && (q3 - q0).abs() <= flat_thresh; |
| 22778 | let flat2 = (p4 - p0).abs() <= flat_thresh |
| 22779 | && (q4 - q0).abs() <= flat_thresh |
| 22780 | && (p5 - p0).abs() <= flat_thresh |
| 22781 | && (q5 - q0).abs() <= flat_thresh |
| 22782 | && (p6 - p0).abs() <= flat_thresh |
| 22783 | && (q6 - q0).abs() <= flat_thresh; |
| 22784 | let out = filter14( |
| 22785 | mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5, |
| 22786 | q6, fctx, |
| 22787 | ); |
| 22788 | for (k, v) in (-6..=5isize).zip(out) { |
| 22789 | data[idx(k)] = v.clamp(0, smax) as u16; |
| 22790 | } |
| 22791 | } |
| 22792 | } |
| 22793 | } |
| 22794 | } |
| 22795 | |
| 22796 | /// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a |
| 22797 | /// 4K decode's self time, spent almost entirely on the per-tap strided |
| 22798 | /// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the |
| 22799 | /// arithmetic). Nothing here is spec logic: the same masks, the same |
| 22800 | /// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same |
| 22801 | /// rounding, done for 16 edge lines at once. |
| 22802 | /// |
| 22803 | /// 16-bit lanes are exact for every value these filters see. Samples are in |
| 22804 | /// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| + |
| 22805 | /// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain |
| 22806 | /// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the |
| 22807 | /// wide kernels' weights each total 8 or 16, so their sums (at most |
| 22808 | /// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their |
| 22809 | /// rounding shift, which is the unsigned shift the scalar's non-negative sum |
| 22810 | /// takes. |
| 22811 | #[cfg(target_arch = "x86_64")] |
| 22812 | #[allow(unsafe_code)] |
| 22813 | #[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract |
| 22814 | mod deblock_simd { |
| 22815 | use std::arch::x86_64::*; |
| 22816 | |
| 22817 | /// `a <= b` lane-wise, as a full-width mask. |
| 22818 | /// |
| 22819 | /// # Safety |
| 22820 | /// Requires AVX2. |
| 22821 | #[target_feature(enable = "avx2")] |
| 22822 | #[inline] |
| 22823 | unsafe fn le(a: __m256i, b: __m256i) -> __m256i { |
| 22824 | _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b) |
| 22825 | } |
| 22826 | |
| 22827 | /// `|a - b|` lane-wise. |
| 22828 | /// |
| 22829 | /// # Safety |
| 22830 | /// Requires AVX2. |
| 22831 | #[target_feature(enable = "avx2")] |
| 22832 | #[inline] |
| 22833 | unsafe fn ad(a: __m256i, b: __m256i) -> __m256i { |
| 22834 | _mm256_abs_epi16(_mm256_sub_epi16(a, b)) |
| 22835 | } |
| 22836 | |
| 22837 | /// `signed_char_clamp_high`, lane-wise. |
| 22838 | /// |
| 22839 | /// # Safety |
| 22840 | /// Requires AVX2. |
| 22841 | #[target_feature(enable = "avx2")] |
| 22842 | #[inline] |
| 22843 | unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i { |
| 22844 | _mm256_min_epi16(_mm256_max_epi16(v, lo), hi) |
| 22845 | } |
| 22846 | |
| 22847 | /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the |
| 22848 | /// 128-bit lane swap AVX2's in-lane unpacks leave behind). |
| 22849 | /// |
| 22850 | /// # Safety |
| 22851 | /// Requires AVX2. |
| 22852 | #[target_feature(enable = "avx2")] |
| 22853 | unsafe fn transpose16(t: &mut [__m256i; 16]) { |
| 22854 | let mut a = [_mm256_setzero_si256(); 16]; |
| 22855 | for k in 0..8 { |
| 22856 | a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]); |
| 22857 | a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]); |
| 22858 | } |
| 22859 | let mut b = [_mm256_setzero_si256(); 16]; |
| 22860 | for g in 0..4 { |
| 22861 | let s = 4 * g; |
| 22862 | b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]); |
| 22863 | b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]); |
| 22864 | b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]); |
| 22865 | b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]); |
| 22866 | } |
| 22867 | let mut c = [_mm256_setzero_si256(); 16]; |
| 22868 | for g in 0..2 { |
| 22869 | let s = 8 * g; |
| 22870 | for j in 0..4 { |
| 22871 | c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]); |
| 22872 | c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]); |
| 22873 | } |
| 22874 | } |
| 22875 | for i in 0..8 { |
| 22876 | t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20); |
| 22877 | t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31); |
| 22878 | } |
| 22879 | } |
| 22880 | |
| 22881 | /// The wide kernels' tap weights, in tap order and with the spec's |
| 22882 | /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8` |
| 22883 | /// over `p3..q3`, `filter14` over `p6..q6`. |
| 22884 | const W6: [[i16; 6]; 4] = [ |
| 22885 | [3, 2, 2, 1, 0, 0], |
| 22886 | [1, 2, 2, 2, 1, 0], |
| 22887 | [0, 1, 2, 2, 2, 1], |
| 22888 | [0, 0, 1, 2, 2, 3], |
| 22889 | ]; |
| 22890 | const W8: [[i16; 8]; 6] = [ |
| 22891 | [3, 2, 1, 1, 1, 0, 0, 0], |
| 22892 | [2, 1, 2, 1, 1, 1, 0, 0], |
| 22893 | [1, 1, 1, 2, 1, 1, 1, 0], |
| 22894 | [0, 1, 1, 1, 2, 1, 1, 1], |
| 22895 | [0, 0, 1, 1, 1, 2, 1, 2], |
| 22896 | [0, 0, 0, 1, 1, 1, 2, 3], |
| 22897 | ]; |
| 22898 | #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement |
| 22899 | const W14: [[i16; 14]; 12] = [ |
| 22900 | [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], |
| 22901 | [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], |
| 22902 | [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0], |
| 22903 | [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0], |
| 22904 | [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0], |
| 22905 | [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0], |
| 22906 | [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1], |
| 22907 | [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2], |
| 22908 | [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3], |
| 22909 | [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4], |
| 22910 | [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5], |
| 22911 | [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7], |
| 22912 | ]; |
| 22913 | |
| 22914 | /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows, |
| 22915 | /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and |
| 22916 | /// below `1 << 16`, so the logical shift is the arithmetic one. |
| 22917 | /// |
| 22918 | /// # Safety |
| 22919 | /// Requires AVX2. |
| 22920 | /// |
| 22921 | /// lane-deblock: the tap count, the weights and the shift are all const |
| 22922 | /// here (they were slice parameters, which left the weight `match` as a |
| 22923 | /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were |
| 22924 | /// 34% of this kernel's samples, and the spilled tap slices another 17%). |
| 22925 | #[target_feature(enable = "avx2")] |
| 22926 | #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn |
| 22927 | unsafe fn wsum<const N: usize, const SHIFT: i32>( |
| 22928 | taps: &[__m256i; N], |
| 22929 | w: &[i16; N], |
| 22930 | ) -> __m256i { |
| 22931 | let mut s = _mm256_setzero_si256(); |
| 22932 | for i in 0..N { |
| 22933 | match w[i] { |
| 22934 | 0 => {} |
| 22935 | 1 => s = _mm256_add_epi16(s, taps[i]), |
| 22936 | 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])), |
| 22937 | k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))), |
| 22938 | } |
| 22939 | } |
| 22940 | let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1))); |
| 22941 | if SHIFT == 3 { |
| 22942 | _mm256_srli_epi16(s, 3) |
| 22943 | } else { |
| 22944 | _mm256_srli_epi16(s, 4) |
| 22945 | } |
| 22946 | } |
| 22947 | |
| 22948 | /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in |
| 22949 | /// `t[8]`; the filtered taps are written back in place. Returns `false` |
| 22950 | /// when the filter mask is empty on every one of the 16 lines -- nothing |
| 22951 | /// was written and the caller can skip the whole write-back. |
| 22952 | /// |
| 22953 | /// # Safety |
| 22954 | /// Requires AVX2. |
| 22955 | /// |
| 22956 | /// lane-deblock2: `LEN` is a const parameter, so each edge length gets |
| 22957 | /// its own kernel holding only its own taps, and every wide row is |
| 22958 | /// clamped straight into `t` instead of into a shared twelve-entry |
| 22959 | /// result array (which the register allocator spilled -- 35% of this |
| 22960 | /// kernel's samples were `vmovdqa` to the stack). |
| 22961 | #[target_feature(enable = "avx2")] |
| 22962 | #[allow(clippy::too_many_arguments)] |
| 22963 | unsafe fn filter16<const LEN: u8>( |
| 22964 | t: &mut [__m256i; 16], |
| 22965 | blimit: i32, |
| 22966 | limit: i32, |
| 22967 | hev_thr: i32, |
| 22968 | flat_thresh: i32, |
| 22969 | scale: i32, |
| 22970 | smax: i32, |
| 22971 | ) -> bool { |
| 22972 | let lim = _mm256_set1_epi16(limit as i16); |
| 22973 | let blim = _mm256_set1_epi16(blimit as i16); |
| 22974 | let hthr = _mm256_set1_epi16(hev_thr as i16); |
| 22975 | let fthr = _mm256_set1_epi16(flat_thresh as i16); |
| 22976 | let zero = _mm256_setzero_si256(); |
| 22977 | let smaxv = _mm256_set1_epi16(smax as i16); |
| 22978 | macro_rules! put { |
| 22979 | ($i:expr, $v:expr) => { |
| 22980 | t[$i] = _mm256_min_epi16(_mm256_max_epi16($v, zero), smaxv); |
| 22981 | }; |
| 22982 | } |
| 22983 | let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]); |
| 22984 | let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]); |
| 22985 | |
| 22986 | // `highbd_filter_mask`: the neighbour steps this kernel's length |
| 22987 | // reaches, plus the shared `blimit` term. |
| 22988 | let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0)); |
| 22989 | let mut md = d1; |
| 22990 | if LEN >= 6 { |
| 22991 | md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1))); |
| 22992 | } |
| 22993 | if LEN >= 8 { |
| 22994 | md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2))); |
| 22995 | } |
| 22996 | let bl = _mm256_add_epi16( |
| 22997 | _mm256_slli_epi16(ad(p0, q0), 1), |
| 22998 | _mm256_srli_epi16(ad(p1, q1), 1), |
| 22999 | ); |
| 23000 | let mask = _mm256_and_si256(le(md, lim), le(bl, blim)); |
| 23001 | // lane-deblock2: an empty mask leaves every tap at its loaded value |
| 23002 | // (the flat masks are `& mask`, so they are empty too, and the final |
| 23003 | // clamp is the identity on samples that came out of the plane), so |
| 23004 | // the whole write-back -- including the vertical edge's second |
| 23005 | // transpose -- is dead. |
| 23006 | if _mm256_testz_si256(mask, mask) != 0 { |
| 23007 | return false; |
| 23008 | } |
| 23009 | let hev = _mm256_cmpgt_epi16(d1, hthr); |
| 23010 | |
| 23011 | // `filter4`, in the centred domain. |
| 23012 | let centre = _mm256_set1_epi16((128 * scale) as i16); |
| 23013 | let lo = _mm256_set1_epi16((-128 * scale) as i16); |
| 23014 | let hi = _mm256_set1_epi16((128 * scale - 1) as i16); |
| 23015 | let ps1 = _mm256_sub_epi16(p1, centre); |
| 23016 | let ps0 = _mm256_sub_epi16(p0, centre); |
| 23017 | let qs0 = _mm256_sub_epi16(q0, centre); |
| 23018 | let qs1 = _mm256_sub_epi16(q1, centre); |
| 23019 | let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi)); |
| 23020 | let f = sclamp( |
| 23021 | _mm256_add_epi16( |
| 23022 | outer, |
| 23023 | _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)), |
| 23024 | ), |
| 23025 | lo, |
| 23026 | hi, |
| 23027 | ); |
| 23028 | let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3); |
| 23029 | let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3); |
| 23030 | let tap = _mm256_andnot_si256( |
| 23031 | hev, |
| 23032 | _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1), |
| 23033 | ); |
| 23034 | let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre); |
| 23035 | let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre); |
| 23036 | let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre); |
| 23037 | let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre); |
| 23038 | let b_p1 = _mm256_blendv_epi8(p1, n_p1, mask); |
| 23039 | let b_p0 = _mm256_blendv_epi8(p0, n_p0, mask); |
| 23040 | let b_q0 = _mm256_blendv_epi8(q0, n_q0, mask); |
| 23041 | let b_q1 = _mm256_blendv_epi8(q1, n_q1, mask); |
| 23042 | if LEN == 4 { |
| 23043 | put!(6, b_p1); |
| 23044 | put!(7, b_p0); |
| 23045 | put!(8, b_q0); |
| 23046 | put!(9, b_q1); |
| 23047 | return true; |
| 23048 | } |
| 23049 | |
| 23050 | // `highbd_flat_mask4`, over the same reach as this length's mask. |
| 23051 | let mut fl = _mm256_max_epi16( |
| 23052 | _mm256_max_epi16(ad(p1, p0), ad(q1, q0)), |
| 23053 | _mm256_max_epi16(ad(p2, p0), ad(q2, q0)), |
| 23054 | ); |
| 23055 | if LEN >= 8 { |
| 23056 | fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0))); |
| 23057 | } |
| 23058 | let flat = _mm256_and_si256(le(fl, fthr), mask); |
| 23059 | let any_flat = _mm256_testz_si256(flat, flat) == 0; |
| 23060 | if LEN == 6 { |
| 23061 | if any_flat { |
| 23062 | let taps = [p2, p1, p0, q0, q1, q2]; |
| 23063 | put!(6, _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W6[0]), flat)); |
| 23064 | put!(7, _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W6[1]), flat)); |
| 23065 | put!(8, _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W6[2]), flat)); |
| 23066 | put!(9, _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W6[3]), flat)); |
| 23067 | } else { |
| 23068 | put!(6, b_p1); |
| 23069 | put!(7, b_p0); |
| 23070 | put!(8, b_q0); |
| 23071 | put!(9, b_q1); |
| 23072 | } |
| 23073 | return true; |
| 23074 | } |
| 23075 | |
| 23076 | // `filter8`'s six rows over `p2..q2`, the wide kernel's base. |
| 23077 | let (o0, o1, o2, o3, o4, o5) = if any_flat { |
| 23078 | let taps = [p3, p2, p1, p0, q0, q1, q2, q3]; |
| 23079 | ( |
| 23080 | _mm256_blendv_epi8(p2, wsum::<_, 3>(&taps, &W8[0]), flat), |
| 23081 | _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W8[1]), flat), |
| 23082 | _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W8[2]), flat), |
| 23083 | _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W8[3]), flat), |
| 23084 | _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W8[4]), flat), |
| 23085 | _mm256_blendv_epi8(q2, wsum::<_, 3>(&taps, &W8[5]), flat), |
| 23086 | ) |
| 23087 | } else { |
| 23088 | (p2, b_p1, b_p0, b_q0, b_q1, q2) |
| 23089 | }; |
| 23090 | macro_rules! put8 { |
| 23091 | () => { |
| 23092 | put!(5, o0); |
| 23093 | put!(6, o1); |
| 23094 | put!(7, o2); |
| 23095 | put!(8, o3); |
| 23096 | put!(9, o4); |
| 23097 | put!(10, o5); |
| 23098 | }; |
| 23099 | } |
| 23100 | if LEN == 8 { |
| 23101 | put8!(); |
| 23102 | return true; |
| 23103 | } |
| 23104 | |
| 23105 | let fl2 = _mm256_max_epi16( |
| 23106 | _mm256_max_epi16( |
| 23107 | _mm256_max_epi16(ad(p4, p0), ad(q4, q0)), |
| 23108 | _mm256_max_epi16(ad(p5, p0), ad(q5, q0)), |
| 23109 | ), |
| 23110 | _mm256_max_epi16(ad(p6, p0), ad(q6, q0)), |
| 23111 | ); |
| 23112 | let flat2 = _mm256_and_si256(le(fl2, fthr), flat); |
| 23113 | if _mm256_testz_si256(flat2, flat2) != 0 { |
| 23114 | // No line takes the wide rows: `t[2..5]`/`t[11..14]` keep the |
| 23115 | // taps they were loaded with, exactly as the blend would. |
| 23116 | put8!(); |
| 23117 | return true; |
| 23118 | } |
| 23119 | // lane-deblock: `filter14`'s twelve rows as a RUNNING sum. |
| 23120 | // Consecutive `W14` rows differ by three or four taps (row j+1 - row |
| 23121 | // j is a constant vector with two negative and two positive |
| 23122 | // entries), so each output costs one add, one sub and the rounding |
| 23123 | // shift instead of a fresh 14-tap weighted sum -- 168 tap operations |
| 23124 | // become 44. Exact: every partial sum is taken mod 2^16 by |
| 23125 | // `add/sub_epi16` and every ROW sum is a real `W14` row, at most |
| 23126 | // `16 * 4095 + 8 < 2^16`, so the unsigned rounding shift sees the |
| 23127 | // true value. `deblock_simd_kernel_matches_the_scalar_filter` pins |
| 23128 | // it against `filter_edge` at 8/10/12-bit. |
| 23129 | let mut s = _mm256_add_epi16( |
| 23130 | _mm256_add_epi16( |
| 23131 | _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)), |
| 23132 | _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1), |
| 23133 | ), |
| 23134 | _mm256_add_epi16( |
| 23135 | _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)), |
| 23136 | q0, |
| 23137 | ), |
| 23138 | ); |
| 23139 | let add2 = |a, b| _mm256_add_epi16(a, b); |
| 23140 | macro_rules! row14 { |
| 23141 | ($idx:literal, $base:expr) => { |
| 23142 | put!( |
| 23143 | $idx, |
| 23144 | _mm256_blendv_epi8( |
| 23145 | $base, |
| 23146 | _mm256_srli_epi16(_mm256_add_epi16(s, _mm256_set1_epi16(8)), 4), |
| 23147 | flat2, |
| 23148 | ) |
| 23149 | ); |
| 23150 | }; |
| 23151 | ($idx:literal, $base:expr, $plus:expr, $minus:expr) => { |
| 23152 | s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus); |
| 23153 | row14!($idx, $base); |
| 23154 | }; |
| 23155 | } |
| 23156 | row14!(2, p5); |
| 23157 | row14!(3, p4, add2(p3, q1), _mm256_slli_epi16(p6, 1)); |
| 23158 | row14!(4, p3, add2(p2, q2), add2(p6, p5)); |
| 23159 | row14!(5, o0, add2(p1, q3), add2(p6, p4)); |
| 23160 | row14!(6, o1, add2(p0, q4), add2(p6, p3)); |
| 23161 | row14!(7, o2, add2(q0, q5), add2(p6, p2)); |
| 23162 | row14!(8, o3, add2(q1, q6), add2(p6, p1)); |
| 23163 | row14!(9, o4, add2(q2, q6), add2(p5, p0)); |
| 23164 | row14!(10, o5, add2(q3, q6), add2(p4, q0)); |
| 23165 | row14!(11, q3, add2(q4, q6), add2(p3, q1)); |
| 23166 | row14!(12, q4, add2(q5, q6), add2(p2, q2)); |
| 23167 | row14!(13, q5, _mm256_slli_epi16(q6, 1), add2(p1, q3)); |
| 23168 | true |
| 23169 | } |
| 23170 | |
| 23171 | /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's |
| 23172 | /// 16 lines are 16 consecutive rows and its taps are consecutive samples |
| 23173 | /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16 |
| 23174 | /// consecutive columns with each tap a whole row segment. |
| 23175 | /// |
| 23176 | /// # Safety |
| 23177 | /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base % |
| 23178 | /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`; |
| 23179 | /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride` |
| 23180 | /// must be inside it. |
| 23181 | #[target_feature(enable = "avx2")] |
| 23182 | #[allow(clippy::too_many_arguments)] |
| 23183 | pub unsafe fn edge16( |
| 23184 | data: &mut [u16], |
| 23185 | base: usize, |
| 23186 | stride: usize, |
| 23187 | vertical: bool, |
| 23188 | len: u8, |
| 23189 | blimit: i32, |
| 23190 | limit: i32, |
| 23191 | hev_thr: i32, |
| 23192 | flat_thresh: i32, |
| 23193 | scale: i32, |
| 23194 | smax: i32, |
| 23195 | ) { |
| 23196 | let p = data.as_mut_ptr(); |
| 23197 | let mut t = [_mm256_setzero_si256(); 16]; |
| 23198 | // The taps this length reads, as `t` indices. |
| 23199 | let (lo, hi) = match len { |
| 23200 | 4 => (6, 10), |
| 23201 | 6 => (5, 11), |
| 23202 | 8 => (4, 12), |
| 23203 | _ => (1, 15), |
| 23204 | }; |
| 23205 | if vertical { |
| 23206 | for j in 0..16 { |
| 23207 | t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast()); |
| 23208 | } |
| 23209 | transpose16(&mut t); |
| 23210 | } else { |
| 23211 | let top = base - 8 * stride; |
| 23212 | for i in lo..hi { |
| 23213 | t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast()); |
| 23214 | } |
| 23215 | } |
| 23216 | // lane-deblock2: one monomorphised kernel per edge length, and an |
| 23217 | // empty filter mask returns without any write-back at all. |
| 23218 | let modified = match len { |
| 23219 | 4 => filter16::<4>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax), |
| 23220 | 6 => filter16::<6>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax), |
| 23221 | 8 => filter16::<8>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax), |
| 23222 | _ => filter16::<14>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax), |
| 23223 | }; |
| 23224 | if !modified { |
| 23225 | return; |
| 23226 | } |
| 23227 | if vertical { |
| 23228 | transpose16(&mut t); |
| 23229 | for j in 0..16 { |
| 23230 | _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]); |
| 23231 | } |
| 23232 | } else { |
| 23233 | let top = base - 8 * stride; |
| 23234 | let (a, b) = match len { |
| 23235 | 4 | 6 => (6, 10), |
| 23236 | 8 => (5, 11), |
| 23237 | _ => (2, 14), |
| 23238 | }; |
| 23239 | for i in a..b { |
| 23240 | _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]); |
| 23241 | } |
| 23242 | } |
| 23243 | } |
| 23244 | } |
| 23245 | |
| 23246 | /// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`' |
| 23247 | /// output. Returns `false` when this build or CPU has no kernel, leaving the |
| 23248 | /// caller on the scalar path. |
| 23249 | #[allow(unused_variables)] |
| 23250 | fn filter_edge16( |
| 23251 | data: &mut [u16], |
| 23252 | base: usize, |
| 23253 | stride: usize, |
| 23254 | vertical: bool, |
| 23255 | len: u8, |
| 23256 | level: i32, |
| 23257 | sharpness: u8, fctx: &crate::decode::FrameCtx, |
| 23258 | ) -> bool { |
| 23259 | #[cfg(target_arch = "x86_64")] |
| 23260 | { |
| 23261 | if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 { |
| 23262 | let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness); |
| 23263 | let shift = bit_depth(fctx) - 8; |
| 23264 | // SAFETY: the avx2 arm is reached only when the CPU reports it, |
| 23265 | // and `deblock_plane` checks the kernel's edge bounds. |
| 23266 | #[allow(unsafe_code)] |
| 23267 | unsafe { |
| 23268 | deblock_simd::edge16( |
| 23269 | data, |
| 23270 | base, |
| 23271 | stride, |
| 23272 | vertical, |
| 23273 | len, |
| 23274 | blimit << shift, |
| 23275 | limit << shift, |
| 23276 | hev_thr << shift, |
| 23277 | 1 << shift, |
| 23278 | 1 << shift, |
| 23279 | sample_max(fctx), |
| 23280 | ) |
| 23281 | }; |
| 23282 | return true; |
| 23283 | } |
| 23284 | } |
| 23285 | false |
| 23286 | } |
| 23287 | |
| 23288 | /// One plane's worth of spec 7.14: every vertical edge across the plane, |
| 23289 | /// then every horizontal edge (the order the spec and libaom both use). |
| 23290 | fn deblock_plane( |
| 23291 | plane: &mut PlaneBuf<'static>, |
| 23292 | plane_idx: usize, |
| 23293 | lf: &LoopFilterParams, |
| 23294 | n: &Neighbours, |
| 23295 | frame_width: usize, |
| 23296 | frame_height: usize, fctx: &crate::decode::FrameCtx, |
| 23297 | ) { |
| 23298 | // spec 7.14's order: this plane's whole vertical pass, then its whole |
| 23299 | // horizontal one. lane-pipefilt split the two into one row-ranged |
| 23300 | // function so the per-superblock-row pipeline can run them a band at a |
| 23301 | // time; `0..usize::MAX` is the whole plane, i.e. exactly this call. |
| 23302 | deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx); |
| 23303 | deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx); |
| 23304 | } |
| 23305 | |
| 23306 | /// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or |
| 23307 | /// horizontal ones -- restricted to the plane rows `span_lo..span_hi`. |
| 23308 | /// |
| 23309 | /// A row span is a legal cut of either pass because a band boundary is a |
| 23310 | /// multiple of 16 rows and every edge's kernel stays inside its own |
| 23311 | /// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are |
| 23312 | /// what keep the two passes in spec order across bands. |
| 23313 | #[allow(clippy::too_many_arguments)] |
| 23314 | fn deblock_plane_span( |
| 23315 | plane: &mut PlaneBuf<'static>, |
| 23316 | plane_idx: usize, |
| 23317 | lf: &LoopFilterParams, |
| 23318 | n: &Neighbours, |
| 23319 | frame_width: usize, |
| 23320 | frame_height: usize, |
| 23321 | span_lo: usize, |
| 23322 | span_hi: usize, |
| 23323 | horz: bool, |
| 23324 | fctx: &crate::decode::FrameCtx, |
| 23325 | ) { |
| 23326 | let chroma = plane_idx != 0; |
| 23327 | // r7: libaom clips the deblock loop to the CODED frame's own |
| 23328 | // width/height, not the mi-aligned `true_width`/`true_height` margin |
| 23329 | // (the padding up to the next 8-pixel/superblock boundary that |
| 23330 | // reconstruction still fills in but the loop filter never visits). |
| 23331 | // Confirmed against the superres gate: with the margin included, the |
| 23332 | // last coded mi column's horizontal edges were filtered when libaom's |
| 23333 | // real output leaves them untouched (r6's post-deblock diff, 37 px, all |
| 23334 | // in columns 44-47); clipping here closes it (3/3 frames pixel-exact). |
| 23335 | // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded |
| 23336 | // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock |
| 23337 | // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which |
| 23338 | // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the |
| 23339 | // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column |
| 23340 | // 72 and the verti |
Showing the first 1 MiB of this file. View raw.