forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcd61dc0Tahinli3 months ago728 commits

decode.rs3797 lines, 140.1 KiBHistoryRawDownload
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
24use ec_av1_syntax::CdefParams;
25use ec_core::{Error, Result};
26
27use crate::cdf;
28use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
29use crate::encode::{Picture, Reach};
30use crate::intra::predict;
31use crate::mc;
32use crate::msac::SymbolDecoder;
33use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
34use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
35use crate::transform::{TxType, dequant_and_inverse_typed};
36
37const PARTITION_NONE: usize = 0;
38const PARTITION_SPLIT: usize = 3;
39const SB_MI: u32 = 16;
40const BLOCK_MI: u32 = 8;
41
42/// How many `use_filter_intra` symbols this decoder has read as `1`, across
43/// every call in the process -- the cheap counter [`filter_intra_hits`] gate
44/// tests read (before/after, not the absolute value) to prove a stream
45/// actually exercised the filter-intra predictor rather than silently
46/// skipping it.
47static FILTER_INTRA_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
48
49/// Current value of [`FILTER_INTRA_HITS`].
50pub(crate) fn filter_intra_hits() -> usize {
51 FILTER_INTRA_HITS.load(std::sync::atomic::Ordering::Relaxed)
52}
53const SUB_MI: u32 = 4;
54const MI: usize = 4;
55const SB: usize = 64;
56const BLOCK: usize = 32;
57const SUB: usize = 16;
58const TX32: usize = 32;
59const TX16: usize = 16;
60const TX8: usize = 8;
61const TX4: usize = 4;
62const DC_PRED: usize = 0;
63/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
64/// carries an angle delta — [`crate::tile`]'s own private copy of the same
65/// constant.
66const V_PRED: usize = 1;
67/// The last directional mode, `D67_PRED`.
68const D67_PRED: usize = 8;
69/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
70/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
71/// codes anything else, so this decoder never reads anything else either.
72const ANGLE_DELTA_ZERO: usize = 3;
73const NUM_BASE_LEVELS: i32 = 2;
74const COEFF_BASE_RANGE: i32 = 12;
75const BR_STEP: i32 = 3;
76const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
77
78/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
79/// whose probability mass a superblock or block half outside the frame
80/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
81/// duplicated here (that module is another lane's territory this round) and
82/// kept in step with it by the byte-exact round-trip tests below rather than
83/// by sharing code.
84const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
85const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
86
87fn element_prob(cdf: &[u16], element: usize) -> u16 {
88 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
89}
90
91/// The two-symbol CDF a partial superblock/block's forced-split flag is read
92/// with: the mass of `elements` becomes the probability of the one partition
93/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
94/// (the encoder's non-adapting counterpart to this read).
95fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
96 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
97 [32768 - split, 32768, 0]
98}
99
100fn unsupported(what: impl Into<String>) -> Error {
101 Error::unsupported("AV1 tile", what.into())
102}
103
104/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
105/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
106/// same rule.
107fn q_ctx_of(base_q_idx: u8) -> usize {
108 match base_q_idx {
109 0..=20 => 0,
110 21..=60 => 1,
111 61..=120 => 2,
112 _ => 3,
113 }
114}
115
116/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
117/// [`crate::tile`]'s writer generates its scan tables with.
118fn default_scan(side: usize) -> Vec<u16> {
119 let mut scan = Vec::with_capacity(side * side);
120 for d in 0..(2 * side - 1) {
121 let lo = d.saturating_sub(side - 1);
122 let hi = d.min(side - 1);
123 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
124 if d % 2 == 0 {
125 scan.extend(diagonal.rev());
126 } else {
127 scan.extend(diagonal);
128 }
129 }
130 scan
131}
132
133fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
134 match scan_idx {
135 0 => 0,
136 i if i <= area / 8 => 1,
137 i if i <= area / 4 => 2,
138 _ => 3,
139 }
140}
141
142fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
143 if row >= side || col >= side {
144 0
145 } else {
146 grid[row * side + col]
147 }
148}
149
150fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
151 if row == 0 && col == 0 {
152 return 0;
153 }
154 let mag: i32 = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
155 .iter()
156 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
157 .sum();
158 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
159 (((mag + 1) >> 1).min(4) as usize) + offset
160}
161
162fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
163 let mag: i32 = [(1, 0), (0, 1), (1, 1)]
164 .iter()
165 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
166 .sum();
167 let mag = (((mag + 1) >> 1).min(6)) as usize;
168 if row == 0 && col == 0 {
169 mag
170 } else if row < 2 && col < 2 {
171 mag + 7
172 } else {
173 mag + 14
174 }
175}
176
177fn dc_vote(dc: Option<bool>) -> i32 {
178 match dc {
179 None => 0,
180 Some(true) => -1,
181 Some(false) => 1,
182 }
183}
184
185fn dc_sign_ctx(vote: i32) -> usize {
186 match vote.signum() {
187 0 => 0,
188 -1 => 1,
189 _ => 2,
190 }
191}
192
193/// The remainder of a level the base and base-range syntax could not reach
194/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
195/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
196fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
197 let mut length = 1u32;
198 while dec.literal(1) == 0 {
199 length += 1;
200 if length > 20 {
201 return Err(unsupported("a Golomb tail longer than this decoder reads"));
202 }
203 }
204 let mut x = 1u32;
205 for _ in 1..length {
206 x = (x << 1) | dec.literal(1);
207 }
208 Ok(x - 1)
209}
210
211/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
212/// [`crate::tile`]'s `write_eob`.
213fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables) -> usize {
214 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
215 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
216
217 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
218 let group = dec.symbol(coding.eob_pt) + 1;
219 if trace {
220 eprintln!("TRACE eob_pt value={group}");
221 }
222 let bits = OFFSET_BITS[group];
223 let mut offset = 0u32;
224 if bits > 0 {
225 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
226 if trace {
227 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
228 }
229 offset = top << (bits - 1);
230 if bits > 1 {
231 offset |= dec.literal(bits - 1);
232 }
233 }
234 GROUP_START[group] + offset as usize
235}
236
237/// One transform block's levels, the inverse of [`crate::tile`]'s
238/// `write_coeffs`, returned as a `side * side` grid in raster order, along
239/// with the transform type that grid was coded under (`DCT_DCT` when the
240/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
241/// 64-point transforms, which never code anything else).
242///
243/// # Errors
244/// Returns an error if the `tx_type` symbol decodes to a value outside its
245/// CDF's own set (a corrupt or unsupported bitstream) — every value the
246/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
247/// produce dispatches to a real inverse transform.
248fn read_coeffs(
249 dec: &mut SymbolDecoder,
250 coding: &mut TxbTables,
251 scan: &[u16],
252 skip_ctx: usize,
253 sign_ctx: usize,
254) -> Result<(Vec<i32>, TxType)> {
255 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
256 let side = coding.side;
257 let mut grid = vec![0i32; side * side];
258 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
259 if trace {
260 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
261 }
262 if all_zero {
263 return Ok((grid, TxType::DctDct));
264 }
265 let mut tx_type = TxType::DctDct;
266 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
267 let t = dec.symbol(tx_type_cdf);
268 if trace {
269 eprintln!("TRACE tx_type value={t}");
270 }
271 tx_type = TxType::from_symbol(t).ok_or_else(|| {
272 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
273 })?;
274 }
275
276 let eob = read_eob(dec, coding);
277 if trace {
278 eprintln!("TRACE eob value={eob}");
279 }
280 let mut levels = vec![0i32; side * side];
281 for scan_idx in (0..eob).rev() {
282 let pos = scan[scan_idx] as usize;
283 let (row, col) = (pos / side, pos % side);
284 let level = if scan_idx == eob - 1 {
285 let ctx = eob_coeff_ctx(scan_idx, side * side);
286 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
287 if trace {
288 eprintln!(
289 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
290 );
291 }
292 v
293 } else {
294 let ctx = base_ctx(&levels, side, row, col);
295 let v = dec.symbol(&mut coding.base[ctx]) as i32;
296 if trace {
297 eprintln!(
298 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
299 );
300 }
301 v
302 };
303 let level = if level > NUM_BASE_LEVELS {
304 let ctx = br_ctx(&levels, side, row, col);
305 let mut level = level;
306 let mut sent = 0;
307 loop {
308 let k = dec.symbol(&mut coding.br[ctx]) as i32;
309 if trace {
310 eprintln!(
311 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
312 );
313 }
314 level += k;
315 sent += BR_STEP;
316 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
317 break;
318 }
319 }
320 level
321 } else {
322 level
323 };
324 levels[pos] = level;
325 }
326
327 for &pos in &scan[..eob] {
328 let level = levels[pos as usize];
329 if level == 0 {
330 continue;
331 }
332 let negative = if pos == 0 {
333 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
334 if trace {
335 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
336 }
337 v
338 } else {
339 dec.literal(1) == 1
340 };
341 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
342 let g = read_golomb(dec)?;
343 if trace {
344 eprintln!("TRACE golomb pos={pos} value={g}");
345 }
346 level + g as i32
347 } else {
348 level
349 };
350 grid[pos as usize] = if negative { -level } else { level };
351 }
352 Ok((grid, tx_type))
353}
354
355/// What one coded block leaves behind for the blocks that read it as a
356/// neighbour: whether it coded anything at all, and the sign of its DC —
357/// [`crate::tile`]'s own private `Neighbour`.
358#[derive(Clone, Copy, Default)]
359struct Neighbour {
360 coded: bool,
361 dc: Option<bool>,
362}
363
364fn neighbour_state(grid: &[i32]) -> Neighbour {
365 Neighbour {
366 coded: grid.iter().any(|&l| l != 0),
367 dc: (grid[0] != 0).then_some(grid[0] < 0),
368 }
369}
370
371/// The neighbour state a block's contexts are read from — a duplicate of
372/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
373/// territory this round), kept at the same two granularities the real writer
374/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
375/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
376/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
377/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
378/// chroma transform straddling the true, odd-sized frame edge see its
379/// neighbour's state clamped at its own subsampled edge rather than luma's.
380struct Neighbours {
381 above: Vec<[Neighbour; 3]>,
382 left: Vec<[Neighbour; 3]>,
383 above_mode: Vec<usize>,
384 left_mode: Vec<usize>,
385 above_side: Vec<usize>,
386 left_side: Vec<usize>,
387 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
388 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
389 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
390 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
391 /// array cannot tell the second leaf's partition symbol that the first
392 /// one was coded at 8x8.
393 above_side_mi: Vec<usize>,
394 left_side_mi: Vec<usize>,
395 /// Whether the block above/left of this column/row was coded `skip` --
396 /// an inter frame's own `skip` context (spec `SkipContext`), which the
397 /// key-frame writer never tracks (its skip context is always zero); a
398 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
399 /// `left_skip`.
400 above_skip: Vec<bool>,
401 left_skip: Vec<bool>,
402 /// Whether the block above/left was coded inter -- the `is_inter`
403 /// context (spec `av1_get_intra_inter_context`), a duplicate of
404 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
405 above_inter: Vec<bool>,
406 left_inter: Vec<bool>,
407 mi_cols: usize,
408 mi_rows: usize,
409 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
410 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
411 /// 7.15) never filters an 8x8 luma block whose covering coded block read
412 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
413 /// grain [`Self::record_mi`] already writes at), read back at 8x8
414 /// granularity by [`apply_cdef`] since `skip` is constant across every
415 /// mi cell one coded block covers.
416 skip_grid: Vec<bool>,
417 skip_grid_cols_mi: usize,
418}
419
420impl Neighbours {
421 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
422 /// true (unpadded) size in 4x4 mode-info units.
423 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
424 Self {
425 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
426 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
427 above_mode: vec![DC_PRED; cols],
428 left_mode: vec![DC_PRED; rows],
429 above_side: vec![SB; cols],
430 left_side: vec![SB; rows],
431 above_side_mi: vec![SB; cols * (SUB / MI)],
432 left_side_mi: vec![SB; rows * (SUB / MI)],
433 above_skip: vec![false; cols],
434 left_skip: vec![false; rows],
435 above_inter: vec![false; cols],
436 left_inter: vec![false; rows],
437 mi_cols,
438 mi_rows,
439 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
440 skip_grid_cols_mi: cols * (SUB / MI),
441 }
442 }
443
444 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
445 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
446 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
447 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
448 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
449 let (mi_r, mi_c) = at_mi;
450 for rr in 0..side_mi {
451 for cc in 0..side_mi {
452 if let Some(cell) = self
453 .skip_grid
454 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
455 {
456 *cell = skip;
457 }
458 }
459 }
460 }
461
462 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
463 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
464 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
465 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
466 /// straddle the region with a mix of skip/non-skip blocks).
467 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
468 (0..2).all(|rr| {
469 (0..2).all(|cc| {
470 self.skip_grid
471 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
472 .copied()
473 .unwrap_or(false)
474 })
475 })
476 }
477
478 fn start_row(&mut self) {
479 self.left.iter_mut().for_each(|l| *l = Default::default());
480 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
481 self.left_side.iter_mut().for_each(|s| *s = SB);
482 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
483 self.left_skip.iter_mut().for_each(|s| *s = false);
484 self.left_inter.iter_mut().for_each(|i| *i = false);
485 }
486
487 /// Records a block's `skip`/`is_inter` state for the next block that
488 /// reads it as a neighbour -- [`crate::tile`]'s `record_inter`.
489 fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool) {
490 let (r, c) = at;
491 for cell in 0..side / SUB {
492 self.above_skip[c + cell] = skip;
493 self.left_skip[r + cell] = skip;
494 self.above_inter[c + cell] = is_inter;
495 self.left_inter[r + cell] = is_inter;
496 }
497 }
498
499 /// The context of a block's partition symbol: delegates to the mi-precise
500 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
501 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
502 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
503 /// only touches the finer mi arrays -- leaves them stale for the *next*
504 /// sibling's own partition symbol.
505 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
506 let (r, c) = at;
507 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
508 }
509
510 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
511 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
512 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
513 /// than the enclosing 16x16 slot's stale, shared state.
514 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
515 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
516 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
517 }
518
519 /// The gathered coded/DC-sign state of the blocks above and to the left
520 /// of a block `side` samples across, per plane.
521 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
522 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
523 }
524
525 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
526 /// units, for the same reason [`Self::record_mi`] does.
527 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
528 let side_mi = side / MI;
529 std::array::from_fn(|plane| {
530 let mut above_coded = false;
531 let mut left_coded = false;
532 let mut vote = 0;
533 for cell in 0..side_mi {
534 let above = &self.above[mi_c + cell][plane];
535 let left = &self.left[mi_r + cell][plane];
536 above_coded |= above.coded;
537 left_coded |= left.coded;
538 vote += dc_vote(above.dc) + dc_vote(left.dc);
539 }
540 (above_coded, left_coded, vote)
541 })
542 }
543
544 /// Writes one coded block into every cell it covers, on both grids: the
545 /// mode/side arrays up to `side`'s own width, and the coefficient-context
546 /// arrays up to the true frame edge — the units past it are left at their
547 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
548 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
549 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
550 /// not from this block's own side).
551 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
552 let (r, c) = at;
553 for cell in 0..side / SUB {
554 self.above_mode[c + cell] = mode;
555 self.left_mode[r + cell] = mode;
556 self.above_side[c + cell] = side;
557 self.left_side[r + cell] = side;
558 }
559 self.record_mi((r * (SUB / MI), c * (SUB / MI)), side, grids);
560 }
561
562 /// The coefficient-context half of [`Self::record`], taking the block's
563 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
564 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
565 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
566 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
567 let (mi_r, mi_c) = at_mi;
568 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
569 let side_mi = side / MI;
570 for cell in 0..side_mi {
571 self.left_side_mi[mi_r + cell] = side;
572 self.above_side_mi[mi_c + cell] = side;
573 }
574 // A chroma 4x4 unit straddling the true luma edge is still whole in
575 // chroma's own halved grid, so libaom rounds the luma bound up to the
576 // plane's own 4x4 unit before clamping a subsampled plane
577 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
578 let round_up_even = |n: usize| n.div_ceil(2) * 2;
579 let bound_h = [
580 self.mi_rows,
581 round_up_even(self.mi_rows),
582 round_up_even(self.mi_rows),
583 ];
584 let bound_w = [
585 self.mi_cols,
586 round_up_even(self.mi_cols),
587 round_up_even(self.mi_cols),
588 ];
589 for cell in 0..side_mi {
590 self.left[mi_r + cell] = std::array::from_fn(|plane| {
591 if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {
592 states[plane]
593 } else {
594 Default::default()
595 }
596 });
597 self.above[mi_c + cell] = std::array::from_fn(|plane| {
598 if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) {
599 states[plane]
600 } else {
601 Default::default()
602 }
603 });
604 }
605 }
606}
607
608/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
609/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
610/// exactly — including its skip context, which the real key-frame writer
611/// always writes at a fixed context of zero (it never tracks a neighbour-based
612/// one for intra blocks; that is the inter-frame writer's rule instead).
613/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
614/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
615/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
616/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
617/// plain DC chroma.
618/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
619/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
620/// bound (spec `filter_intra_mode_info` never reads a symbol there).
621fn filter_intra_size_class(side: usize) -> Option<usize> {
622 match side {
623 4 => Some(0),
624 8 => Some(1),
625 16 => Some(2),
626 32 => Some(3),
627 _ => None,
628 }
629}
630
631fn read_intra_mode(
632 dec: &mut SymbolDecoder,
633 cdfs: &mut Cdfs,
634 above_mode: usize,
635 left_mode: usize,
636 cfl: bool,
637 side: usize,
638 enable_filter_intra: bool,
639) -> Result<(bool, usize, Option<(i32, i32)>, Option<usize>)> {
640 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
641 let skip = dec.symbol(&mut cdfs.skip[0]) != 0;
642 if trace {
643 eprintln!("TRACE skip value={}", skip as i32);
644 }
645 let above_ctx = INTRA_MODE_CTX[above_mode];
646 let left_ctx = INTRA_MODE_CTX[left_mode];
647 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
648 if trace {
649 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
650 }
651 if (V_PRED..=D67_PRED).contains(&mode) {
652 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
653 if trace {
654 eprintln!("TRACE angle_delta value={angle}");
655 }
656 if angle != ANGLE_DELTA_ZERO {
657 return Err(unsupported(
658 "a nonzero angle delta (this encoder never writes one)",
659 ));
660 }
661 }
662 let uv_mode = if cfl {
663 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
664 } else {
665 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
666 };
667 if trace {
668 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
669 }
670 let alpha = if uv_mode == DC_PRED {
671 None
672 } else if cfl && uv_mode == UV_CFL_PRED {
673 Some(read_cfl_alphas(dec, cdfs))
674 } else {
675 return Err(unsupported("a directional chroma mode (round 2)"));
676 };
677 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
678 // `use_filter_intra` symbol this decoder never read at all until
679 // lane-av1real r10 -- silently skipping it left every bit past a
680 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
681 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
682 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
683 // symbol's bits were never consumed).
684 let mut filter_intra = None;
685 if mode == DC_PRED
686 && enable_filter_intra
687 && let Some(class) = filter_intra_size_class(side)
688 {
689 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
690 if trace {
691 eprintln!(
692 "TRACE use_filter_intra side={side} value={}",
693 use_filter_intra as i32
694 );
695 }
696 if use_filter_intra {
697 FILTER_INTRA_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
698 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
699 if trace {
700 eprintln!("TRACE filter_intra_mode value={fi_mode}");
701 }
702 filter_intra = Some(fi_mode);
703 }
704 }
705 Ok((skip, mode, alpha, filter_intra))
706}
707
708/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
709/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
710/// intra modes.
711const UV_CFL_PRED: usize = 13;
712
713/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
714/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
715/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
716/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
717/// joint sign the same way. Returns each plane's final signed `alpha_q3`
718/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
719fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
720 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
721 let sign_u = ((joint_sign + 1) * 11) >> 5;
722 let sign_v = (joint_sign + 1) - 3 * sign_u;
723 let alpha_u = if sign_u == 0 {
724 0
725 } else {
726 let ctx_u = (joint_sign + 1 - 3) as usize;
727 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
728 if sign_u == 2 { mag } else { -mag }
729 };
730 let alpha_v = if sign_v == 0 {
731 0
732 } else {
733 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
734 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
735 if sign_v == 2 { mag } else { -mag }
736 };
737 (alpha_u, alpha_v)
738}
739
740/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
741/// the reconstructed luma samples under a `side`-square block, subsampled
742/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
743/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
744/// to give the AC values [`cfl_scaled`] scales by alpha.
745fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
746 let cside = side / 2;
747 let mut ac = vec![0i32; cside * cside];
748 let mut sum = 0i32;
749 for cy in 0..cside {
750 for cx in 0..cside {
751 let (lx, ly) = (px + cx * 2, py + cy * 2);
752 let q3 = (i32::from(y.data[ly * y.width + lx])
753 + i32::from(y.data[ly * y.width + lx + 1])
754 + i32::from(y.data[(ly + 1) * y.width + lx])
755 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
756 << 1;
757 ac[cy * cside + cx] = q3;
758 sum += q3;
759 }
760 }
761 let num_pel = (cside * cside) as i32;
762 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
763 ac.iter_mut().for_each(|v| *v -= avg);
764 ac
765}
766
767/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
768/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
769/// ties away from zero on the shifted-out sign).
770fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
771 let v = alpha_q3 * ac_q3;
772 if v >= 0 {
773 (v + 32) >> 6
774 } else {
775 -((-v + 32) >> 6)
776 }
777}
778
779/// One plane's reconstruction buffer, `width * height` samples, and the
780/// prediction/residual reads and writes into it — the decode-side twin of
781/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
782/// (own-edge and reach clamps both), passing what it gathers straight to
783/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
784struct PlaneBuf {
785 data: Vec<u8>,
786 width: usize,
787 height: usize,
788 /// The frame's true, decodable extent in this plane's own units — past
789 /// this, samples are the padded coding surface's invented tail, never a
790 /// real decoder's edge or reach reads.
791 true_width: usize,
792 true_height: usize,
793}
794
795impl PlaneBuf {
796 fn edges(
797 &self,
798 x: usize,
799 y: usize,
800 side: usize,
801 reach: Reach,
802 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
803 let own_across = x + side.min(self.true_width.saturating_sub(x));
804 let across = if reach.above_right {
805 own_across + side.min(self.true_width.saturating_sub(own_across))
806 } else {
807 own_across
808 }
809 .min(self.width);
810 let own_down = y + side.min(self.true_height.saturating_sub(y));
811 let down = if reach.below_left {
812 own_down + side.min(self.true_height.saturating_sub(own_down))
813 } else {
814 own_down
815 }
816 .min(self.height);
817 let above = (y > 0 && across > x)
818 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
819 let left = (x > 0 && down > y).then(|| {
820 (y..down)
821 .map(|row| self.data[row * self.width + x - 1])
822 .collect::<Vec<_>>()
823 });
824 let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);
825 (above, left, corner)
826 }
827
828 /// Predicts under `mode` then adds `residual` (side*side, raster),
829 /// writing the clamped reconstruction back into the plane at `(x, y)`.
830 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
831 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
832 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
833 /// order (cfl.c).
834 fn reconstruct(
835 &mut self,
836 x: usize,
837 y: usize,
838 side: usize,
839 mode: usize,
840 reach: Reach,
841 residual: &[i32],
842 cfl: Option<(i32, &[i32])>,
843 filter_intra: Option<usize>,
844 ) {
845 let (above, left, corner) = self.edges(x, y, side, reach);
846 let mut prediction = vec![0u8; side * side];
847 if let Some(fi_mode) = filter_intra {
848 crate::intra::predict_filter_intra(
849 fi_mode,
850 above.as_deref(),
851 left.as_deref(),
852 corner,
853 side,
854 &mut prediction,
855 );
856 } else {
857 predict(
858 mode as u8,
859 above.as_deref(),
860 left.as_deref(),
861 corner,
862 side,
863 &mut prediction,
864 );
865 }
866 for row in 0..side {
867 for col in 0..side {
868 let idx = row * side + col;
869 let mut base = i32::from(prediction[idx]);
870 if let Some((alpha_q3, ac_q3)) = cfl {
871 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
872 }
873 let sample = (base + residual[idx]).clamp(0, 255) as u8;
874 self.data[(y + row) * self.width + x + col] = sample;
875 }
876 }
877 }
878}
879
880/// Reads one plane's transform block, reconstructs it into `plane` at
881/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
882#[allow(clippy::too_many_arguments)]
883fn read_plane(
884 dec: &mut SymbolDecoder,
885 cdfs: &mut Cdfs,
886 set: TxbSet,
887 scan: &[u16],
888 plane_idx: usize,
889 around: (bool, bool, i32),
890 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
891 // it for every plane's `txb` lookup (it is what an intra transform type's
892 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
893 tx_mode: usize,
894 predict_mode: usize,
895 reach: Reach,
896 plane: &mut PlaneBuf,
897 x: usize,
898 y: usize,
899 side: usize,
900 tx_side: usize,
901 base_q_idx: u8,
902 cfl: Option<(i32, &[i32])>,
903 filter_intra: Option<usize>,
904) -> Result<Vec<i32>> {
905 let skip_ctx = if plane_idx == 0 {
906 0
907 } else {
908 usize::from(around.0) + usize::from(around.1)
909 };
910 let mut coding = cdfs.txb(set, tx_mode);
911 let (grid, tx_type) = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?;
912 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
913 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
914 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
915 // guard also assumes.
916 let levels = if tx_side == side {
917 grid
918 } else {
919 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
920 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
921 // keyed by that true size, not the coded corner's -- so the corner
922 // goes into the top-left of a `side`-sized grid, not the reverse.
923 let mut full = vec![0i32; side * side];
924 for row in 0..tx_side {
925 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
926 }
927 full
928 };
929 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);
930 if std::env::var_os("EC_AV1_TRACE").is_some() {
931 eprintln!(
932 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} levels[0..4]={:?} residual[0..4]={:?}",
933 &levels[..4.min(levels.len())],
934 &residual[..4.min(residual.len())]
935 );
936 }
937 plane.reconstruct(
938 x,
939 y,
940 side,
941 predict_mode,
942 reach,
943 &residual,
944 cfl,
945 filter_intra,
946 );
947 Ok(if tx_side == side {
948 residual_grid_placeholder(&levels, side)
949 } else {
950 levels
951 })
952}
953
954/// `record`'s neighbour state only reads whether *the coded grid* (not the
955/// residual) has nonzero entries, so the levels this function already built
956/// are what it wants back; this helper exists only to name that clearly at
957/// the one call site where `tx_side == side`.
958fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
959 levels.to_vec()
960}
961
962/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
963/// three planes, reconstructing them into `y`/`u`/`v` and updating
964/// `neighbours`.
965#[allow(clippy::too_many_arguments)]
966fn decode_block(
967 dec: &mut SymbolDecoder,
968 cdfs: &mut Cdfs,
969 neighbours: &mut Neighbours,
970 at: (usize, usize),
971 side: usize,
972 luma_set: TxbSet,
973 chroma_set: TxbSet,
974 luma_tx: usize,
975 chroma_tx: usize,
976 scans: (&[u16], &[u16]),
977 cfl: bool,
978 y: &mut PlaneBuf,
979 u: &mut PlaneBuf,
980 v: &mut PlaneBuf,
981 base_q_idx: u8,
982 enable_filter_intra: bool,
983) -> Result<()> {
984 let (r, c) = at;
985 let (px, py) = (c * SUB, r * SUB);
986 let (skip, mode, alpha, filter_intra) = read_intra_mode(
987 dec,
988 cdfs,
989 neighbours.above_mode[c],
990 neighbours.left_mode[r],
991 cfl,
992 side,
993 enable_filter_intra,
994 )?;
995 let reach = Reach::of(side, px, py, y.width, y.height);
996 let (luma_grid, u_grid, v_grid);
997 let (cpx, cpy) = (px / 2, py / 2);
998 let chroma_side = side / 2;
999 if skip {
1000 // A skipped block codes no residual syntax at all (spec 5.11.34):
1001 // straight prediction, on every plane.
1002 y.reconstruct(
1003 px,
1004 py,
1005 side,
1006 mode,
1007 reach,
1008 &vec![0i32; side * side],
1009 None,
1010 filter_intra,
1011 );
1012 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
1013 u.reconstruct(
1014 cpx,
1015 cpy,
1016 chroma_side,
1017 DC_PRED,
1018 Reach::none(),
1019 &vec![0i32; chroma_side * chroma_side],
1020 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1021 None,
1022 );
1023 v.reconstruct(
1024 cpx,
1025 cpy,
1026 chroma_side,
1027 DC_PRED,
1028 Reach::none(),
1029 &vec![0i32; chroma_side * chroma_side],
1030 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1031 None,
1032 );
1033 luma_grid = vec![0i32; side * side];
1034 u_grid = vec![0i32; chroma_side * chroma_side];
1035 v_grid = vec![0i32; chroma_side * chroma_side];
1036 } else {
1037 let around = neighbours.around(at, side);
1038 luma_grid = read_plane(
1039 dec,
1040 cdfs,
1041 luma_set,
1042 scans.0,
1043 0,
1044 around[0],
1045 mode,
1046 mode,
1047 reach,
1048 y,
1049 px,
1050 py,
1051 side,
1052 luma_tx,
1053 base_q_idx,
1054 None,
1055 filter_intra,
1056 )?;
1057 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
1058 u_grid = read_plane(
1059 dec,
1060 cdfs,
1061 chroma_set,
1062 scans.1,
1063 1,
1064 around[1],
1065 mode,
1066 DC_PRED,
1067 Reach::none(),
1068 u,
1069 cpx,
1070 cpy,
1071 chroma_side,
1072 chroma_tx,
1073 base_q_idx,
1074 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1075 None,
1076 )?;
1077 v_grid = read_plane(
1078 dec,
1079 cdfs,
1080 chroma_set,
1081 scans.1,
1082 2,
1083 around[2],
1084 mode,
1085 DC_PRED,
1086 Reach::none(),
1087 v,
1088 cpx,
1089 cpy,
1090 chroma_side,
1091 chroma_tx,
1092 base_q_idx,
1093 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1094 None,
1095 )?;
1096 }
1097 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
1098 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
1099 Ok(())
1100}
1101
1102/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
1103/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
1104/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
1105/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
1106/// just-decoded mode, not the enclosing slot's stale one, is the true
1107/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
1108/// units, which is what its coefficient context (finer than [`SUB`]) is read
1109/// at. Returns the mode this leaf decoded, for the caller's own
1110/// `prev_leaf`/final mode-writeback bookkeeping.
1111#[allow(clippy::too_many_arguments)]
1112fn decode_leaf8(
1113 dec: &mut SymbolDecoder,
1114 cdfs: &mut Cdfs,
1115 neighbours: &mut Neighbours,
1116 outer_at: (usize, usize),
1117 leaf_mi: (usize, usize),
1118 scans: (&[u16], &[u16]),
1119 prev_leaf: Option<((usize, usize), usize)>,
1120 y: &mut PlaneBuf,
1121 u: &mut PlaneBuf,
1122 v: &mut PlaneBuf,
1123 base_q_idx: u8,
1124 enable_filter_intra: bool,
1125) -> Result<usize> {
1126 let (r, c) = outer_at;
1127 let mut above_mode = neighbours.above_mode[c];
1128 let mut left_mode = neighbours.left_mode[r];
1129 if let Some(((pr, pc), pmode)) = prev_leaf {
1130 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
1131 above_mode = pmode;
1132 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
1133 left_mode = pmode;
1134 }
1135 }
1136 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
1137 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
1138 // `decode_block` caller at 16x16 and up.
1139 let (skip, mode, alpha, filter_intra) = read_intra_mode(
1140 dec,
1141 cdfs,
1142 above_mode,
1143 left_mode,
1144 true,
1145 8,
1146 enable_filter_intra,
1147 )?;
1148 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
1149 let reach = Reach::of(8, px, py, y.width, y.height);
1150 let (cpx, cpy) = (px / 2, py / 2);
1151 let (luma_grid, u_grid, v_grid);
1152 if skip {
1153 y.reconstruct(px, py, 8, mode, reach, &vec![0i32; 64], None, filter_intra);
1154 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
1155 u.reconstruct(
1156 cpx,
1157 cpy,
1158 4,
1159 DC_PRED,
1160 Reach::none(),
1161 &vec![0i32; 16],
1162 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1163 None,
1164 );
1165 v.reconstruct(
1166 cpx,
1167 cpy,
1168 4,
1169 DC_PRED,
1170 Reach::none(),
1171 &vec![0i32; 16],
1172 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1173 None,
1174 );
1175 luma_grid = vec![0i32; 64];
1176 u_grid = vec![0i32; 16];
1177 v_grid = vec![0i32; 16];
1178 } else {
1179 let around = neighbours.around_mi(leaf_mi, 8);
1180 luma_grid = read_plane(
1181 dec,
1182 cdfs,
1183 TxbSet::Luma8,
1184 scans.0,
1185 0,
1186 around[0],
1187 mode,
1188 mode,
1189 reach,
1190 y,
1191 px,
1192 py,
1193 8,
1194 TX8,
1195 base_q_idx,
1196 None,
1197 filter_intra,
1198 )?;
1199 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
1200 u_grid = read_plane(
1201 dec,
1202 cdfs,
1203 TxbSet::Chroma4,
1204 scans.1,
1205 1,
1206 around[1],
1207 mode,
1208 DC_PRED,
1209 Reach::none(),
1210 u,
1211 cpx,
1212 cpy,
1213 4,
1214 TX4,
1215 base_q_idx,
1216 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1217 None,
1218 )?;
1219 v_grid = read_plane(
1220 dec,
1221 cdfs,
1222 TxbSet::Chroma4,
1223 scans.1,
1224 2,
1225 around[2],
1226 mode,
1227 DC_PRED,
1228 Reach::none(),
1229 v,
1230 cpx,
1231 cpy,
1232 4,
1233 TX4,
1234 base_q_idx,
1235 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1236 None,
1237 )?;
1238 }
1239 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
1240 neighbours.fill_skip_grid(leaf_mi, 2, skip);
1241 Ok(mode)
1242}
1243
1244/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
1245/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
1246/// (mod 8) reuse the same table.
1247const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
1248 [(-1, 1), (-2, 2)],
1249 [(0, 1), (-1, 2)],
1250 [(0, 1), (0, 2)],
1251 [(0, 1), (1, 2)],
1252 [(1, 1), (2, 2)],
1253 [(1, 0), (2, 1)],
1254 [(1, 0), (2, 0)],
1255 [(1, 0), (2, -1)],
1256];
1257/// A neighbour tap outside the frame's true extent -- `constrain` reads this
1258/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
1259const CDEF_VERY_LARGE: i32 = 0x4000;
1260const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
1261const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
1262
1263fn cdef_msb(x: i32) -> i32 {
1264 31 - x.leading_zeros() as i32
1265}
1266
1267/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
1268/// centre sample a filter tap is allowed to contribute.
1269fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
1270 if threshold == 0 {
1271 return 0;
1272 }
1273 let shift = (damping - cdef_msb(threshold)).max(0);
1274 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
1275}
1276
1277/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
1278/// direction of an 8x8 luma window and the variance gap between it and its
1279/// orthogonal, `sample(row, col)` reading that window's own pixels.
1280fn cdef_find_dir(sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
1281 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
1282 let mut partial = [[0i64; 15]; 8];
1283 for i in 0..8i64 {
1284 for j in 0..8i64 {
1285 let x = i64::from(sample(i as usize, j as usize)) - 128;
1286 partial[0][(i + j) as usize] += x;
1287 partial[1][(i + j / 2) as usize] += x;
1288 partial[2][i as usize] += x;
1289 partial[3][(3 + i - j / 2) as usize] += x;
1290 partial[4][(7 + i - j) as usize] += x;
1291 partial[5][(3 - i / 2 + j) as usize] += x;
1292 partial[6][j as usize] += x;
1293 partial[7][(i / 2 + j) as usize] += x;
1294 }
1295 }
1296 let mut cost = [0i64; 8];
1297 for i in 0..8usize {
1298 cost[2] += partial[2][i] * partial[2][i];
1299 cost[6] += partial[6][i] * partial[6][i];
1300 }
1301 cost[2] *= DIV_TABLE[8];
1302 cost[6] *= DIV_TABLE[8];
1303 for i in 0..7usize {
1304 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
1305 * DIV_TABLE[i + 1];
1306 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
1307 * DIV_TABLE[i + 1];
1308 }
1309 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
1310 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
1311 for i in (1..8).step_by(2) {
1312 for j in 0..5usize {
1313 cost[i] += partial[i][3 + j] * partial[i][3 + j];
1314 }
1315 cost[i] *= DIV_TABLE[8];
1316 for j in 0..3usize {
1317 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
1318 * DIV_TABLE[2 * j + 2];
1319 }
1320 }
1321 let mut best_cost = 0i64;
1322 let mut best_dir = 0usize;
1323 for (i, &c) in cost.iter().enumerate() {
1324 if c > best_cost {
1325 best_cost = c;
1326 best_dir = i;
1327 }
1328 }
1329 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
1330 (best_dir, var as i32)
1331}
1332
1333/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
1334/// (high variance gap) gets more deringing than a flat or non-directional
1335/// one, only ever applied to the luma primary strength.
1336fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
1337 if var == 0 {
1338 return 0;
1339 }
1340 let i = if var >> 6 != 0 {
1341 cdef_msb(var >> 6).min(12)
1342 } else {
1343 0
1344 };
1345 (strength * (4 + i) + 8) >> 4
1346}
1347
1348/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
1349/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
1350/// previously-filtered neighbour must never feed this block's own sum).
1351#[allow(clippy::too_many_arguments)]
1352fn cdef_filter_block(
1353 sample: impl Fn(i32, i32) -> i32,
1354 dst: &mut PlaneBuf,
1355 ox: usize,
1356 oy: usize,
1357 bw: usize,
1358 bh: usize,
1359 pri_strength: i32,
1360 sec_strength: i32,
1361 dir: usize,
1362 pri_damping: i32,
1363 sec_damping: i32,
1364 enable_primary: bool,
1365 enable_secondary: bool,
1366) {
1367 let clipping_required = enable_primary && enable_secondary;
1368 let pri_taps = CDEF_PRI_TAPS[(pri_strength & 1) as usize];
1369 for i in 0..bh {
1370 for j in 0..bw {
1371 let x = sample(i as i32, j as i32);
1372 let mut sum = 0i32;
1373 let mut max = x;
1374 let mut min = x;
1375 for k in 0..2usize {
1376 if enable_primary {
1377 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
1378 let p0 = sample(i as i32 + tr, j as i32 + tc);
1379 let p1 = sample(i as i32 - tr, j as i32 - tc);
1380 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
1381 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
1382 if clipping_required {
1383 if p0 != CDEF_VERY_LARGE {
1384 max = max.max(p0);
1385 }
1386 if p1 != CDEF_VERY_LARGE {
1387 max = max.max(p1);
1388 }
1389 min = min.min(p0).min(p1);
1390 }
1391 }
1392 if enable_secondary {
1393 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
1394 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
1395 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
1396 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
1397 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
1398 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
1399 if clipping_required {
1400 for s in [s0, s1, s2, s3] {
1401 if s != CDEF_VERY_LARGE {
1402 max = max.max(s);
1403 }
1404 }
1405 min = min.min(s0).min(s1).min(s2).min(s3);
1406 }
1407 sum += CDEF_SEC_TAPS[k]
1408 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
1409 + cdef_constrain(s1 - x, sec_strength, sec_damping)
1410 + cdef_constrain(s2 - x, sec_strength, sec_damping)
1411 + cdef_constrain(s3 - x, sec_strength, sec_damping));
1412 }
1413 }
1414 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
1415 if clipping_required {
1416 y = y.clamp(min, max);
1417 }
1418 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, 255) as u8;
1419 }
1420 }
1421}
1422
1423/// Applies CDEF (spec 7.15) to the whole reconstructed frame, over its true
1424/// (unpadded) `mi_cols`/`mi_rows` extent, before it is cropped to its display
1425/// size. `cdef_bits == 0` is this crate's only supported case so far (see the
1426/// refusal in `stream.rs`), so every 64x64 filter block always uses index 0's
1427/// strengths -- no per-block `cdef_idx` selection is implemented yet.
1428fn apply_cdef(
1429 y: &mut PlaneBuf,
1430 u: &mut PlaneBuf,
1431 v: &mut PlaneBuf,
1432 cdef: &CdefParams,
1433 skip_grid: &Neighbours,
1434) {
1435 if cdef.y_pri_strength[0] == 0
1436 && cdef.y_sec_strength[0] == 0
1437 && cdef.uv_pri_strength[0] == 0
1438 && cdef.uv_sec_strength[0] == 0
1439 {
1440 return;
1441 }
1442 let src_y = y.data.clone();
1443 let src_u = u.data.clone();
1444 let src_v = v.data.clone();
1445 let damping = i32::from(cdef.damping);
1446 let damping_uv = (damping - 1).max(0);
1447 let mut mi_r = 0usize;
1448 while mi_r < skip_grid.mi_rows {
1449 let mut mi_c = 0usize;
1450 while mi_c < skip_grid.mi_cols {
1451 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
1452 let (ox, oy) = (mi_c * 4, mi_r * 4);
1453 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
1454 let sample_y = |r: i32, c: i32| -> i32 {
1455 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
1456 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
1457 CDEF_VERY_LARGE
1458 } else {
1459 i32::from(src_y[ny as usize * y_stride + nx as usize])
1460 }
1461 };
1462 let (dir, var) = cdef_find_dir(|r, c| {
1463 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
1464 i32::from(src_y[ny * y_stride + nx])
1465 });
1466
1467 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
1468 // -- each plane zeroes the shared direction when *its own*
1469 // frame-level primary strength is 0, independent of the
1470 // per-block adjusted `t` and of the other plane's strength.
1471 let y_dir = if cdef.y_pri_strength[0] != 0 { dir } else { 0 };
1472 let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[0]), var);
1473 let enable_primary = t != 0;
1474 let enable_secondary = cdef.y_sec_strength[0] != 0;
1475 if enable_primary || enable_secondary {
1476 cdef_filter_block(
1477 sample_y,
1478 y,
1479 ox,
1480 oy,
1481 8,
1482 8,
1483 t,
1484 i32::from(cdef.y_sec_strength[0]),
1485 y_dir,
1486 damping,
1487 damping,
1488 enable_primary,
1489 enable_secondary,
1490 );
1491 }
1492
1493 let t_uv = i32::from(cdef.uv_pri_strength[0]);
1494 let uv_dir = if t_uv != 0 { dir } else { 0 };
1495 let enable_primary_uv = t_uv != 0;
1496 let enable_secondary_uv = cdef.uv_sec_strength[0] != 0;
1497 if enable_primary_uv || enable_secondary_uv {
1498 let (cox, coy) = (ox / 2, oy / 2);
1499 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
1500 let (tw, th) = (plane.true_width, plane.true_height);
1501 let stride = plane.width;
1502 let sample_uv = |r: i32, c: i32| -> i32 {
1503 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
1504 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
1505 CDEF_VERY_LARGE
1506 } else {
1507 i32::from(src_p[ny as usize * stride + nx as usize])
1508 }
1509 };
1510 cdef_filter_block(
1511 sample_uv,
1512 plane,
1513 cox,
1514 coy,
1515 4,
1516 4,
1517 t_uv,
1518 i32::from(cdef.uv_sec_strength[0]),
1519 uv_dir,
1520 damping_uv,
1521 damping_uv,
1522 enable_primary_uv,
1523 enable_secondary_uv,
1524 );
1525 }
1526 }
1527 }
1528 mi_c += 2;
1529 }
1530 mi_r += 2;
1531 }
1532}
1533
1534/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
1535/// returning the picture it reconstructs to.
1536///
1537/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
1538/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
1539/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
1540/// `compute_image_size` derives one from the other, but not losslessly: a
1541/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
1542/// what the reconstruction is cropped to on the way out, mirroring
1543/// [`crate::encode::crop_encoded`].
1544///
1545/// # Errors
1546/// Returns an error when a block's partition, mode, skip flag or transform
1547/// type is anything this decoder does not reconstruct (round 2: inter, tx
1548/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
1549/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
1550/// or when the tile payload runs out of the symbols this decode expects (a
1551/// genuinely foreign stream).
1552pub fn decode_key_frame_tile(
1553 data: &[u8],
1554 mi_cols: u32,
1555 mi_rows: u32,
1556 base_q_idx: u8,
1557 frame_width: u32,
1558 frame_height: u32,
1559 enable_filter_intra: bool,
1560 cdef: &CdefParams,
1561) -> Result<Picture> {
1562 if mi_cols == 0 || mi_rows == 0 {
1563 return Err(unsupported("a frame with no mode-info grid"));
1564 }
1565 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
1566 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
1567 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
1568 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
1569
1570 let mut y = PlaneBuf {
1571 data: vec![0u8; width * height],
1572 width,
1573 height,
1574 true_width,
1575 true_height,
1576 };
1577 let mut u = PlaneBuf {
1578 data: vec![0u8; width * height / 4],
1579 width: width / 2,
1580 height: height / 2,
1581 true_width: true_width / 2,
1582 true_height: true_height / 2,
1583 };
1584 let mut v = PlaneBuf {
1585 data: vec![0u8; width * height / 4],
1586 width: width / 2,
1587 height: height / 2,
1588 true_width: true_width / 2,
1589 true_height: true_height / 2,
1590 };
1591
1592 let scan32 = default_scan(TX32);
1593 let scan16 = default_scan(TX16);
1594 let scan8 = default_scan(TX8);
1595 let scan4 = default_scan(TX4);
1596
1597 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1598 if std::env::var_os("EC_AV1_TRACE").is_some() {
1599 eprintln!(
1600 "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
1601 data.len(),
1602 &data[..data.len().min(8)]
1603 );
1604 }
1605 let mut dec = SymbolDecoder::new(data);
1606 let mut neighbours = Neighbours::new(
1607 cols32 as usize * 2,
1608 rows32 as usize * 2,
1609 mi_cols as usize,
1610 mi_rows as usize,
1611 );
1612
1613 for sb_r in 0..sb_rows {
1614 neighbours.start_row();
1615 for sb_c in 0..sb_cols {
1616 let at = (sb_r as usize * 4, sb_c as usize * 4);
1617 let ctx = neighbours.partition_ctx(at, SB);
1618 let (has_cols, has_rows) = (
1619 sb_c * SB_MI + SB_MI / 2 < mi_cols,
1620 sb_r * SB_MI + SB_MI / 2 < mi_rows,
1621 );
1622 // Recomputed at this superblock's own half (spec
1623 // `decode_partition`): a full alphabet symbol when both halves are
1624 // inside the true frame, a single gathered bit when just one is
1625 // (the superblock cannot be left whole, so this is forced split),
1626 // and nothing at all (SPLIT inferred, no bits) when neither is —
1627 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
1628 // three-way write exactly.
1629 let part = if has_cols && has_rows {
1630 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
1631 if std::env::var_os("EC_AV1_TRACE").is_some() {
1632 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
1633 }
1634 p
1635 } else {
1636 match (has_cols, has_rows) {
1637 (true, false) => {
1638 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
1639 }
1640 (false, true) => {
1641 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
1642 }
1643 _ => {}
1644 }
1645 PARTITION_SPLIT
1646 };
1647 match part {
1648 PARTITION_NONE => {
1649 decode_block(
1650 &mut dec,
1651 &mut cdfs,
1652 &mut neighbours,
1653 at,
1654 SB,
1655 TxbSet::Luma64,
1656 TxbSet::Chroma32,
1657 TX32,
1658 TX32,
1659 (&scan32, &scan32),
1660 false,
1661 &mut y,
1662 &mut u,
1663 &mut v,
1664 base_q_idx,
1665 enable_filter_intra,
1666 )?;
1667 }
1668 PARTITION_SPLIT => {
1669 for q in 0..4 {
1670 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
1671 if r32 >= rows32 || c32 >= cols32 {
1672 continue;
1673 }
1674 let at32 = (r32 as usize * 2, c32 as usize * 2);
1675 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
1676 let (has_cols32, has_rows32) = (
1677 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
1678 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
1679 );
1680 let part32 = if has_cols32 && has_rows32 {
1681 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
1682 if std::env::var_os("EC_AV1_TRACE").is_some() {
1683 eprintln!("TRACE partition_w32 ctx={ctx32} value={p}");
1684 }
1685 p
1686 } else {
1687 match (has_cols32, has_rows32) {
1688 (true, false) => {
1689 dec.symbol_fixed(&gather(
1690 &cdfs.partition_w32[ctx32],
1691 VERT_ALIKE,
1692 ));
1693 }
1694 (false, true) => {
1695 dec.symbol_fixed(&gather(
1696 &cdfs.partition_w32[ctx32],
1697 HORZ_ALIKE,
1698 ));
1699 }
1700 _ => {}
1701 }
1702 PARTITION_SPLIT
1703 };
1704 match part32 {
1705 PARTITION_NONE => {
1706 decode_block(
1707 &mut dec,
1708 &mut cdfs,
1709 &mut neighbours,
1710 at32,
1711 BLOCK,
1712 TxbSet::Luma32,
1713 TxbSet::Chroma16,
1714 TX32,
1715 TX16,
1716 (&scan32, &scan16),
1717 true,
1718 &mut y,
1719 &mut u,
1720 &mut v,
1721 base_q_idx,
1722 enable_filter_intra,
1723 )?;
1724 }
1725 PARTITION_SPLIT => {
1726 for sub in 0..4 {
1727 let (sr, sc) =
1728 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
1729 if (sr as u32) * SUB_MI >= mi_rows
1730 || (sc as u32) * SUB_MI >= mi_cols
1731 {
1732 continue;
1733 }
1734 let (has_cols16, has_rows16) = (
1735 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
1736 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
1737 );
1738 let at16 = (sr, sc);
1739 let ctx16 = neighbours.partition_ctx(at16, SUB);
1740 if has_cols16 && has_rows16 {
1741 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
1742 if part16 == PARTITION_NONE {
1743 decode_block(
1744 &mut dec,
1745 &mut cdfs,
1746 &mut neighbours,
1747 at16,
1748 SUB,
1749 TxbSet::Luma16,
1750 TxbSet::Chroma8,
1751 TX16,
1752 TX8,
1753 (&scan16, &scan8),
1754 true,
1755 &mut y,
1756 &mut u,
1757 &mut v,
1758 base_q_idx,
1759 enable_filter_intra,
1760 )?;
1761 continue;
1762 }
1763 if part16 != PARTITION_SPLIT {
1764 return Err(unsupported(
1765 "a partition below 16x16 other than a clean split (this encoder never writes one)",
1766 ));
1767 }
1768 // A real (non-straddle) SPLIT of a
1769 // whole 16x16 into four 8x8 leaves --
1770 // the same recursion the straddle
1771 // path below already runs when the
1772 // true frame edge forces it, just
1773 // over all four positions instead of
1774 // the one or two the edge leaves.
1775 let (mi_row0, mi_col0) =
1776 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
1777 let mut prev_leaf: Option<((usize, usize), usize)> = None;
1778 for i in 0..4 {
1779 let (mr, mc) =
1780 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
1781 let leaf_mi = (mr as usize, mc as usize);
1782 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
1783 let part8 =
1784 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
1785 if part8 != PARTITION_NONE {
1786 return Err(unsupported(
1787 "a partition below 8x8 (this encoder never writes one)",
1788 ));
1789 }
1790 let leaf_mode = decode_leaf8(
1791 &mut dec,
1792 &mut cdfs,
1793 &mut neighbours,
1794 at16,
1795 leaf_mi,
1796 (&scan8, &scan4),
1797 prev_leaf,
1798 &mut y,
1799 &mut u,
1800 &mut v,
1801 base_q_idx,
1802 enable_filter_intra,
1803 )?;
1804 prev_leaf = Some((leaf_mi, leaf_mode));
1805 }
1806 if let Some((_, mode)) = prev_leaf {
1807 neighbours.above_mode[sc] = mode;
1808 neighbours.left_mode[sr] = mode;
1809 }
1810 continue;
1811 }
1812 // The true edge falls inside this 16x16
1813 // leaf itself (mod-32==8 target sizes,
1814 // lane-av1-rect): one axis only -- an 8x8
1815 // leaf never itself straddles, so the
1816 // block splits cleanly along whichever
1817 // axis is short.
1818 if !has_cols16 && !has_rows16 {
1819 return Err(unsupported(
1820 "a 16x16 block whose true edge cuts through both \
1821 axes needs a rectangular transform this decoder \
1822 does not code yet",
1823 ));
1824 }
1825 if has_cols16 {
1826 dec.symbol_fixed(&gather(
1827 &cdfs.partition_w16[ctx16],
1828 VERT_ALIKE,
1829 ));
1830 } else {
1831 dec.symbol_fixed(&gather(
1832 &cdfs.partition_w16[ctx16],
1833 HORZ_ALIKE,
1834 ));
1835 }
1836 let (mi_row0, mi_col0) =
1837 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
1838 let leaf_positions: Vec<(u32, u32)> = (0..4)
1839 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
1840 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
1841 .collect();
1842 let mut prev_leaf: Option<((usize, usize), usize)> = None;
1843 for (mr, mc) in leaf_positions {
1844 let leaf_mi = (mr as usize, mc as usize);
1845 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
1846 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
1847 if part8 != PARTITION_NONE {
1848 return Err(unsupported(
1849 "a partition below 8x8 (this encoder never writes one)",
1850 ));
1851 }
1852 let leaf_mode = decode_leaf8(
1853 &mut dec,
1854 &mut cdfs,
1855 &mut neighbours,
1856 at16,
1857 leaf_mi,
1858 (&scan8, &scan4),
1859 prev_leaf,
1860 &mut y,
1861 &mut u,
1862 &mut v,
1863 base_q_idx,
1864 enable_filter_intra,
1865 )?;
1866 prev_leaf = Some((leaf_mi, leaf_mode));
1867 }
1868 // `record()`'s `above_mode`/`left_mode`
1869 // write is a no-op at an 8x8 leaf's own
1870 // side, so force the write once the whole
1871 // 16x16 slot's leaves are done, from the
1872 // last leaf (mirrors the writer's r15
1873 // fix).
1874 if let Some((_, mode)) = prev_leaf {
1875 neighbours.above_mode[sc] = mode;
1876 neighbours.left_mode[sr] = mode;
1877 }
1878 }
1879 }
1880 _ => {
1881 return Err(unsupported(
1882 "a partition type this encoder never writes",
1883 ));
1884 }
1885 }
1886 }
1887 }
1888 _ => {
1889 return Err(unsupported("a partition type this encoder never writes"));
1890 }
1891 }
1892 }
1893 }
1894
1895 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
1896
1897 let (fw, fh) = (frame_width as usize, frame_height as usize);
1898 if fw == width && fh == height {
1899 return Ok(Picture {
1900 width,
1901 height,
1902 y: y.data,
1903 u: u.data,
1904 v: v.data,
1905 });
1906 }
1907 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
1908 let mut out = Vec::with_capacity(w * h);
1909 for row in 0..h {
1910 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
1911 }
1912 out
1913 };
1914 Ok(Picture {
1915 width: fw,
1916 height: fh,
1917 y: crop(&y, fw, fh),
1918 u: crop(&u, fw / 2, fh / 2),
1919 v: crop(&v, fw / 2, fh / 2),
1920 })
1921}
1922
1923/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
1924/// duplicating [`crate::tile`]'s private copy of the same rule.
1925fn intra_inter_ctx(has_above: bool, has_left: bool, above_inter: bool, left_inter: bool) -> usize {
1926 match (has_above, has_left) {
1927 (true, true) => {
1928 let (above_intra, left_intra) = (!above_inter, !left_inter);
1929 if above_intra && left_intra {
1930 3
1931 } else {
1932 usize::from(above_intra || left_intra)
1933 }
1934 }
1935 (true, false) => 2 * usize::from(!above_inter),
1936 (false, true) => 2 * usize::from(!left_inter),
1937 (false, false) => 0,
1938 }
1939}
1940
1941/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
1942/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
1943/// bits start counting from.
1944fn mv_class_base(class: usize) -> i32 {
1945 if class == 0 { 0 } else { 2i32 << (class + 2) }
1946}
1947
1948/// One motion vector component's non-zero diff (spec 5.11.32
1949/// `read_mv_component`), the inverse of [`crate::tile`]'s private
1950/// `write_mv_component`.
1951fn read_mv_component(dec: &mut SymbolDecoder, c: &mut MvComponentCdfs) -> i32 {
1952 let sign = dec.symbol(&mut c.sign);
1953 let class = dec.symbol(&mut c.class);
1954 let local = if class == 0 {
1955 let bit = dec.symbol(&mut c.class0_bit);
1956 let fr = dec.symbol(&mut c.class0_fr[bit]);
1957 (bit << 3) | (fr << 1) | 1
1958 } else {
1959 let mut d = 0;
1960 for i in 0..class {
1961 d |= dec.symbol(&mut c.bit[i]) << i;
1962 }
1963 let fr = dec.symbol(&mut c.fr);
1964 (d << 3) | (fr << 1) | 1
1965 };
1966 let mag = mv_class_base(class) + local as i32 + 1;
1967 if sign == 1 { -mag } else { mag }
1968}
1969
1970/// A motion vector coded as a residual against `pred` (spec 5.11.32
1971/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
1972fn read_mv(
1973 dec: &mut SymbolDecoder,
1974 mv_comp: &mut [MvComponentCdfs; 2],
1975 mv_joint: &mut [u16; 5],
1976 pred: (i32, i32),
1977) -> (i32, i32) {
1978 let joint = dec.symbol(mv_joint);
1979 let mut diff = (0, 0);
1980 if joint == 2 || joint == 3 {
1981 diff.0 = read_mv_component(dec, &mut mv_comp[0]);
1982 }
1983 if joint == 1 || joint == 3 {
1984 diff.1 = read_mv_component(dec, &mut mv_comp[1]);
1985 }
1986 (pred.0 + diff.0, pred.1 + diff.1)
1987}
1988
1989/// A 1/8-pel motion vector component converted to the 1/16-pel offset
1990/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
1991/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
1992fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
1993 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
1994}
1995
1996impl PlaneBuf {
1997 /// Adds `residual` onto an already-computed `prediction` (motion
1998 /// compensation's output, rather than [`predict`]'s intra one), writing
1999 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
2000 /// counterpart of [`PlaneBuf::reconstruct`].
2001 fn reconstruct_mc(
2002 &mut self,
2003 x: usize,
2004 y: usize,
2005 side: usize,
2006 prediction: &[u8],
2007 residual: &[i32],
2008 ) {
2009 for row in 0..side {
2010 for col in 0..side {
2011 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
2012 .clamp(0, 255) as u8;
2013 self.data[(y + row) * self.width + x + col] = sample;
2014 }
2015 }
2016 }
2017}
2018
2019/// Reads one inter-coded plane's transform block and reconstructs it by
2020/// adding its residual onto a motion-compensated `prediction` -- the inter
2021/// counterpart of [`read_plane`] (every inter transform this decoder reads is
2022/// `side`-square with no oversized-64 case, so there is no padded-grid
2023/// branch to mirror).
2024#[allow(clippy::too_many_arguments)]
2025fn read_inter_plane(
2026 dec: &mut SymbolDecoder,
2027 cdfs: &mut Cdfs,
2028 set: TxbSet,
2029 scan: &[u16],
2030 plane_idx: usize,
2031 around: (bool, bool, i32),
2032 tx_mode: usize,
2033 plane: &mut PlaneBuf,
2034 x: usize,
2035 y: usize,
2036 side: usize,
2037 base_q_idx: u8,
2038 prediction: &[u8],
2039) -> Result<Vec<i32>> {
2040 let skip_ctx = if plane_idx == 0 {
2041 0
2042 } else {
2043 usize::from(around.0) + usize::from(around.1)
2044 };
2045 let mut coding = cdfs.txb(set, tx_mode);
2046 let (grid, tx_type) = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?;
2047 let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type);
2048 plane.reconstruct_mc(x, y, side, prediction, &residual);
2049 Ok(grid)
2050}
2051
2052/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
2053/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
2054/// and motion-compensated reconstruction, or the inter frame's own intra
2055/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
2056/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
2057/// private `write_inter_frame_leaf` -- both share this one function here,
2058/// parameterised by `side`/the transform sets/scan tables/size group they
2059/// each use.
2060///
2061/// # Errors
2062/// Returns an error when a symbol names anything this decoder does not
2063/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
2064/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
2065/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
2066/// refuse.
2067#[allow(clippy::too_many_arguments)]
2068fn decode_inter_block(
2069 dec: &mut SymbolDecoder,
2070 cdfs: &mut Cdfs,
2071 neighbours: &mut Neighbours,
2072 grid: &mut MiGrid,
2073 at: (usize, usize),
2074 side: usize,
2075 mi_cols: u32,
2076 mi_rows: u32,
2077 y: &mut PlaneBuf,
2078 u: &mut PlaneBuf,
2079 v: &mut PlaneBuf,
2080 ref_y: &PlaneBuf,
2081 ref_u: &PlaneBuf,
2082 ref_v: &PlaneBuf,
2083 base_q_idx: u8,
2084 luma_set_intra: TxbSet,
2085 luma_set_inter: TxbSet,
2086 chroma_set: TxbSet,
2087 luma_tx: usize,
2088 chroma_tx: usize,
2089 scan_luma: &[u16],
2090 scan_chroma: &[u16],
2091 size_group: usize,
2092) -> Result<()> {
2093 const LAST_FRAME: i8 = 1;
2094
2095 let (r, c) = at;
2096 let (px, py) = (c * SUB, r * SUB);
2097 let (cpx, cpy) = (px / 2, py / 2);
2098 let chroma_side = side / 2;
2099
2100 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
2101 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
2102
2103 let (has_above, has_left) = (r > 0, c > 0);
2104 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
2105 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
2106 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
2107
2108 let mode_for_tx;
2109 let (luma_grid, u_grid, v_grid);
2110 if is_inter {
2111 let sr_ctx = single_ref_ctx(above_inter || left_inter);
2112 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
2113 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
2114 let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]);
2115 if (p1, p3, p4) != (0, 0, 0) {
2116 return Err(unsupported(
2117 "a reference frame other than LAST_FRAME (round 2)",
2118 ));
2119 }
2120
2121 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
2122 let bw4 = side / 4;
2123 let stack = find_mv_stack(
2124 grid,
2125 mi_row,
2126 mi_col,
2127 bw4,
2128 bw4,
2129 LAST_FRAME,
2130 mi_cols as usize,
2131 mi_rows as usize,
2132 );
2133
2134 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
2135 let (mv, is_new_mv) = if !not_new {
2136 if stack.entries.len() > 1 {
2137 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
2138 }
2139 (
2140 read_mv(dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, stack.pred_mv),
2141 true,
2142 )
2143 } else {
2144 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
2145 if !not_zero {
2146 return Err(unsupported("GLOBALMV (round 3)"));
2147 }
2148 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
2149 let mv = if nearest {
2150 stack.nearest_mv
2151 } else {
2152 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
2153 // at 1): read at most two more `drl_mode` bits, one per stack
2154 // entry past the second, stopping at the first `0`.
2155 // `drl_ctx[idx]` is the context between `entries[idx]` and
2156 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
2157 // exactly the pair this index is choosing between.
2158 let mut idx = 1usize;
2159 while idx < 3 && stack.entries.len() > idx + 1 {
2160 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
2161 break;
2162 }
2163 idx += 1;
2164 }
2165 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
2166 };
2167 (mv, false)
2168 };
2169 for dr in 0..bw4 {
2170 for dc in 0..bw4 {
2171 grid.set(
2172 mi_row + dr,
2173 mi_col + dc,
2174 MiInfo {
2175 is_inter: true,
2176 ref_frame: LAST_FRAME,
2177 mv,
2178 is_new_mv,
2179 size: bw4,
2180 },
2181 );
2182 }
2183 }
2184 mode_for_tx = 0;
2185
2186 let mut pred_y = vec![0u8; side * side];
2187 mc::predict(
2188 &ref_y.data,
2189 ref_y.width,
2190 ref_y.true_width,
2191 ref_y.true_height,
2192 mv_to_q4(px, mv.1, true),
2193 mv_to_q4(py, mv.0, true),
2194 side,
2195 side,
2196 &mut pred_y,
2197 );
2198 let mut pred_u = vec![0u8; chroma_side * chroma_side];
2199 mc::predict(
2200 &ref_u.data,
2201 ref_u.width,
2202 ref_u.true_width,
2203 ref_u.true_height,
2204 mv_to_q4(cpx, mv.1, false),
2205 mv_to_q4(cpy, mv.0, false),
2206 chroma_side,
2207 chroma_side,
2208 &mut pred_u,
2209 );
2210 let mut pred_v = vec![0u8; chroma_side * chroma_side];
2211 mc::predict(
2212 &ref_v.data,
2213 ref_v.width,
2214 ref_v.true_width,
2215 ref_v.true_height,
2216 mv_to_q4(cpx, mv.1, false),
2217 mv_to_q4(cpy, mv.0, false),
2218 chroma_side,
2219 chroma_side,
2220 &mut pred_v,
2221 );
2222
2223 if skip {
2224 y.reconstruct_mc(px, py, side, &pred_y, &vec![0i32; side * side]);
2225 u.reconstruct_mc(
2226 cpx,
2227 cpy,
2228 chroma_side,
2229 &pred_u,
2230 &vec![0i32; chroma_side * chroma_side],
2231 );
2232 v.reconstruct_mc(
2233 cpx,
2234 cpy,
2235 chroma_side,
2236 &pred_v,
2237 &vec![0i32; chroma_side * chroma_side],
2238 );
2239 luma_grid = vec![0i32; side * side];
2240 u_grid = vec![0i32; chroma_side * chroma_side];
2241 v_grid = vec![0i32; chroma_side * chroma_side];
2242 } else {
2243 let around = neighbours.around(at, side);
2244 luma_grid = read_inter_plane(
2245 dec,
2246 cdfs,
2247 luma_set_inter,
2248 scan_luma,
2249 0,
2250 around[0],
2251 mode_for_tx,
2252 y,
2253 px,
2254 py,
2255 side,
2256 base_q_idx,
2257 &pred_y,
2258 )?;
2259 u_grid = read_inter_plane(
2260 dec,
2261 cdfs,
2262 chroma_set,
2263 scan_chroma,
2264 1,
2265 around[1],
2266 mode_for_tx,
2267 u,
2268 cpx,
2269 cpy,
2270 chroma_side,
2271 base_q_idx,
2272 &pred_u,
2273 )?;
2274 v_grid = read_inter_plane(
2275 dec,
2276 cdfs,
2277 chroma_set,
2278 scan_chroma,
2279 2,
2280 around[2],
2281 mode_for_tx,
2282 v,
2283 cpx,
2284 cpy,
2285 chroma_side,
2286 base_q_idx,
2287 &pred_v,
2288 )?;
2289 }
2290 } else {
2291 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
2292 if mode >= 13 {
2293 return Err(unsupported(
2294 "an intra mode this decoder does not code (round 2)",
2295 ));
2296 }
2297 if (V_PRED..=D67_PRED).contains(&mode) {
2298 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
2299 if angle != ANGLE_DELTA_ZERO {
2300 return Err(unsupported(
2301 "a nonzero angle delta (this encoder never writes one)",
2302 ));
2303 }
2304 }
2305 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
2306 let alpha = if uv_mode == DC_PRED {
2307 None
2308 } else if uv_mode == UV_CFL_PRED {
2309 Some(read_cfl_alphas(dec, cdfs))
2310 } else {
2311 return Err(unsupported("a directional chroma mode (round 2)"));
2312 };
2313 mode_for_tx = mode;
2314 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
2315 for dr in 0..side / 4 {
2316 for dc in 0..side / 4 {
2317 grid.set(
2318 mi_row + dr,
2319 mi_col + dc,
2320 MiInfo {
2321 is_inter: false,
2322 ref_frame: -1,
2323 mv: (0, 0),
2324 is_new_mv: false,
2325 size: side / 4,
2326 },
2327 );
2328 }
2329 }
2330
2331 let reach = Reach::of(side, px, py, y.width, y.height);
2332 if skip {
2333 y.reconstruct(
2334 px,
2335 py,
2336 side,
2337 mode,
2338 reach,
2339 &vec![0i32; side * side],
2340 None,
2341 None,
2342 );
2343 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
2344 u.reconstruct(
2345 cpx,
2346 cpy,
2347 chroma_side,
2348 DC_PRED,
2349 Reach::none(),
2350 &vec![0i32; chroma_side * chroma_side],
2351 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2352 None,
2353 );
2354 v.reconstruct(
2355 cpx,
2356 cpy,
2357 chroma_side,
2358 DC_PRED,
2359 Reach::none(),
2360 &vec![0i32; chroma_side * chroma_side],
2361 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2362 None,
2363 );
2364 luma_grid = vec![0i32; side * side];
2365 u_grid = vec![0i32; chroma_side * chroma_side];
2366 v_grid = vec![0i32; chroma_side * chroma_side];
2367 } else {
2368 let around = neighbours.around(at, side);
2369 luma_grid = read_plane(
2370 dec,
2371 cdfs,
2372 luma_set_intra,
2373 scan_luma,
2374 0,
2375 around[0],
2376 mode,
2377 mode,
2378 reach,
2379 y,
2380 px,
2381 py,
2382 side,
2383 luma_tx,
2384 base_q_idx,
2385 None,
2386 None,
2387 )?;
2388 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
2389 u_grid = read_plane(
2390 dec,
2391 cdfs,
2392 chroma_set,
2393 scan_chroma,
2394 1,
2395 around[1],
2396 mode,
2397 DC_PRED,
2398 Reach::none(),
2399 u,
2400 cpx,
2401 cpy,
2402 chroma_side,
2403 chroma_tx,
2404 base_q_idx,
2405 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2406 None,
2407 )?;
2408 v_grid = read_plane(
2409 dec,
2410 cdfs,
2411 chroma_set,
2412 scan_chroma,
2413 2,
2414 around[2],
2415 mode,
2416 DC_PRED,
2417 Reach::none(),
2418 v,
2419 cpx,
2420 cpy,
2421 chroma_side,
2422 chroma_tx,
2423 base_q_idx,
2424 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2425 None,
2426 )?;
2427 }
2428 }
2429 neighbours.record(at, side, mode_for_tx, &[luma_grid, u_grid, v_grid]);
2430 neighbours.record_inter(at, side, skip, is_inter);
2431 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
2432 Ok(())
2433}
2434
2435/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
2436/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
2437/// exact symbol order: its own skip flag, intra/inter choice and (when
2438/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
2439/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
2440/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
2441/// same as [`decode_leaf8`]'s coefficient layer but with
2442/// motion-compensated prediction instead of intra prediction when inter.
2443/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
2444/// skip/intra-inter context, overridden by `prev_leaf` exactly as
2445/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
2446/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
2447/// and intra/inter choice, for the next leaf or the caller's final
2448/// write-back.
2449#[allow(clippy::too_many_arguments)]
2450fn decode_inter_block8(
2451 dec: &mut SymbolDecoder,
2452 cdfs: &mut Cdfs,
2453 neighbours: &mut Neighbours,
2454 grid: &mut MiGrid,
2455 mi_cols: u32,
2456 mi_rows: u32,
2457 outer_at: (usize, usize),
2458 leaf_mi: (usize, usize),
2459 y: &mut PlaneBuf,
2460 u: &mut PlaneBuf,
2461 v: &mut PlaneBuf,
2462 ref_y: &PlaneBuf,
2463 ref_u: &PlaneBuf,
2464 ref_v: &PlaneBuf,
2465 base_q_idx: u8,
2466 scan8: &[u16],
2467 scan4: &[u16],
2468 prev_leaf: Option<((usize, usize), bool, bool)>,
2469) -> Result<(bool, bool)> {
2470 const LAST_FRAME: i8 = 1;
2471 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
2472 const SIZE_GROUP_8: usize = 1;
2473
2474 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
2475 let (cpx, cpy) = (px / 2, py / 2);
2476 const SIDE: usize = 8;
2477 const CHROMA_SIDE: usize = 4;
2478
2479 let (r, c) = outer_at;
2480 let mut above_skip = neighbours.above_skip[c];
2481 let mut left_skip = neighbours.left_skip[r];
2482 let mut above_inter = neighbours.above_inter[c];
2483 let mut left_inter = neighbours.left_inter[r];
2484 if let Some(((pr, pc), pskip, pinter)) = prev_leaf {
2485 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
2486 above_skip = pskip;
2487 above_inter = pinter;
2488 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
2489 left_skip = pskip;
2490 left_inter = pinter;
2491 }
2492 }
2493 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
2494 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
2495
2496 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
2497 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
2498 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
2499
2500 let mode_for_tx;
2501 let (luma_grid, u_grid, v_grid);
2502 if is_inter {
2503 let sr_ctx = single_ref_ctx(above_inter || left_inter);
2504 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
2505 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
2506 let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]);
2507 if (p1, p3, p4) != (0, 0, 0) {
2508 return Err(unsupported(
2509 "a reference frame other than LAST_FRAME (round 2)",
2510 ));
2511 }
2512
2513 let (mi_row, mi_col) = leaf_mi;
2514 let stack = find_mv_stack(
2515 grid,
2516 mi_row,
2517 mi_col,
2518 2,
2519 2,
2520 LAST_FRAME,
2521 mi_cols as usize,
2522 mi_rows as usize,
2523 );
2524
2525 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
2526 let (mv, is_new_mv) = if !not_new {
2527 if stack.entries.len() > 1 {
2528 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
2529 }
2530 (
2531 read_mv(dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, stack.pred_mv),
2532 true,
2533 )
2534 } else {
2535 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
2536 if !not_zero {
2537 return Err(unsupported("GLOBALMV (round 3)"));
2538 }
2539 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
2540 let mv = if nearest {
2541 stack.nearest_mv
2542 } else {
2543 let mut idx = 1usize;
2544 while idx < 3 && stack.entries.len() > idx + 1 {
2545 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
2546 break;
2547 }
2548 idx += 1;
2549 }
2550 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
2551 };
2552 (mv, false)
2553 };
2554 for dr in 0..2 {
2555 for dc in 0..2 {
2556 grid.set(
2557 mi_row + dr,
2558 mi_col + dc,
2559 MiInfo {
2560 is_inter: true,
2561 ref_frame: LAST_FRAME,
2562 mv,
2563 is_new_mv,
2564 size: 2,
2565 },
2566 );
2567 }
2568 }
2569 mode_for_tx = 0;
2570
2571 let mut pred_y = vec![0u8; SIDE * SIDE];
2572 mc::predict(
2573 &ref_y.data,
2574 ref_y.width,
2575 ref_y.true_width,
2576 ref_y.true_height,
2577 mv_to_q4(px, mv.1, true),
2578 mv_to_q4(py, mv.0, true),
2579 SIDE,
2580 SIDE,
2581 &mut pred_y,
2582 );
2583 let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
2584 mc::predict(
2585 &ref_u.data,
2586 ref_u.width,
2587 ref_u.true_width,
2588 ref_u.true_height,
2589 mv_to_q4(cpx, mv.1, false),
2590 mv_to_q4(cpy, mv.0, false),
2591 CHROMA_SIDE,
2592 CHROMA_SIDE,
2593 &mut pred_u,
2594 );
2595 let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
2596 mc::predict(
2597 &ref_v.data,
2598 ref_v.width,
2599 ref_v.true_width,
2600 ref_v.true_height,
2601 mv_to_q4(cpx, mv.1, false),
2602 mv_to_q4(cpy, mv.0, false),
2603 CHROMA_SIDE,
2604 CHROMA_SIDE,
2605 &mut pred_v,
2606 );
2607
2608 if skip {
2609 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
2610 u.reconstruct_mc(
2611 cpx,
2612 cpy,
2613 CHROMA_SIDE,
2614 &pred_u,
2615 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
2616 );
2617 v.reconstruct_mc(
2618 cpx,
2619 cpy,
2620 CHROMA_SIDE,
2621 &pred_v,
2622 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
2623 );
2624 luma_grid = vec![0i32; SIDE * SIDE];
2625 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
2626 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
2627 } else {
2628 let around = neighbours.around_mi(leaf_mi, 8);
2629 luma_grid = read_inter_plane(
2630 dec,
2631 cdfs,
2632 TxbSet::Luma8Inter,
2633 scan8,
2634 0,
2635 around[0],
2636 mode_for_tx,
2637 y,
2638 px,
2639 py,
2640 SIDE,
2641 base_q_idx,
2642 &pred_y,
2643 )?;
2644 u_grid = read_inter_plane(
2645 dec,
2646 cdfs,
2647 TxbSet::Chroma4,
2648 scan4,
2649 1,
2650 around[1],
2651 mode_for_tx,
2652 u,
2653 cpx,
2654 cpy,
2655 CHROMA_SIDE,
2656 base_q_idx,
2657 &pred_u,
2658 )?;
2659 v_grid = read_inter_plane(
2660 dec,
2661 cdfs,
2662 TxbSet::Chroma4,
2663 scan4,
2664 2,
2665 around[2],
2666 mode_for_tx,
2667 v,
2668 cpx,
2669 cpy,
2670 CHROMA_SIDE,
2671 base_q_idx,
2672 &pred_v,
2673 )?;
2674 }
2675 } else {
2676 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
2677 if mode >= 13 {
2678 return Err(unsupported(
2679 "an intra mode this decoder does not code (round 2)",
2680 ));
2681 }
2682 if (V_PRED..=D67_PRED).contains(&mode) {
2683 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
2684 if angle != ANGLE_DELTA_ZERO {
2685 return Err(unsupported(
2686 "a nonzero angle delta (this encoder never writes one)",
2687 ));
2688 }
2689 }
2690 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
2691 if uv_mode != DC_PRED {
2692 return Err(unsupported(
2693 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
2694 ));
2695 }
2696 mode_for_tx = mode;
2697 let (mi_row, mi_col) = leaf_mi;
2698 for dr in 0..2 {
2699 for dc in 0..2 {
2700 grid.set(
2701 mi_row + dr,
2702 mi_col + dc,
2703 MiInfo {
2704 is_inter: false,
2705 ref_frame: -1,
2706 mv: (0, 0),
2707 is_new_mv: false,
2708 size: 2,
2709 },
2710 );
2711 }
2712 }
2713
2714 let reach = Reach::of(SIDE, px, py, y.width, y.height);
2715 if skip {
2716 y.reconstruct(
2717 px,
2718 py,
2719 SIDE,
2720 mode,
2721 reach,
2722 &vec![0i32; SIDE * SIDE],
2723 None,
2724 None,
2725 );
2726 u.reconstruct(
2727 cpx,
2728 cpy,
2729 CHROMA_SIDE,
2730 DC_PRED,
2731 Reach::none(),
2732 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
2733 None,
2734 None,
2735 );
2736 v.reconstruct(
2737 cpx,
2738 cpy,
2739 CHROMA_SIDE,
2740 DC_PRED,
2741 Reach::none(),
2742 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
2743 None,
2744 None,
2745 );
2746 luma_grid = vec![0i32; SIDE * SIDE];
2747 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
2748 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
2749 } else {
2750 let around = neighbours.around_mi(leaf_mi, 8);
2751 luma_grid = read_plane(
2752 dec,
2753 cdfs,
2754 TxbSet::Luma8,
2755 scan8,
2756 0,
2757 around[0],
2758 mode,
2759 mode,
2760 reach,
2761 y,
2762 px,
2763 py,
2764 SIDE,
2765 TX8,
2766 base_q_idx,
2767 None,
2768 None,
2769 )?;
2770 u_grid = read_plane(
2771 dec,
2772 cdfs,
2773 TxbSet::Chroma4,
2774 scan4,
2775 1,
2776 around[1],
2777 mode,
2778 DC_PRED,
2779 Reach::none(),
2780 u,
2781 cpx,
2782 cpy,
2783 CHROMA_SIDE,
2784 TX4,
2785 base_q_idx,
2786 None,
2787 None,
2788 )?;
2789 v_grid = read_plane(
2790 dec,
2791 cdfs,
2792 TxbSet::Chroma4,
2793 scan4,
2794 2,
2795 around[2],
2796 mode,
2797 DC_PRED,
2798 Reach::none(),
2799 v,
2800 cpx,
2801 cpy,
2802 CHROMA_SIDE,
2803 TX4,
2804 base_q_idx,
2805 None,
2806 None,
2807 )?;
2808 }
2809 }
2810 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
2811 Ok((skip, is_inter))
2812}
2813
2814/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
2815/// against `reference` (the previous frame's own decoded picture, at this
2816/// frame's true size -- a decoder's single-slot DPB, matching what this
2817/// crate's encoder always predicts from), returning the picture it
2818/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
2819/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
2820/// `frame_width`/`frame_height` its true render size).
2821///
2822/// # Errors
2823/// Returns an error under the same conditions [`decode_inter_block`] does,
2824/// or when `reference` is not this frame's own true size, or when the tile
2825/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
2826/// refusal [`crate::tile`]'s writer gives its encoder).
2827pub fn decode_inter_frame_tile(
2828 data: &[u8],
2829 mi_cols: u32,
2830 mi_rows: u32,
2831 base_q_idx: u8,
2832 frame_width: u32,
2833 frame_height: u32,
2834 reference: &Picture,
2835 cdef: &CdefParams,
2836) -> Result<Picture> {
2837 if mi_cols == 0 || mi_rows == 0 {
2838 return Err(unsupported("a frame with no mode-info grid"));
2839 }
2840 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
2841 if reference.width != true_width || reference.height != true_height {
2842 return Err(unsupported(
2843 "a reference picture that is not this frame's own true size",
2844 ));
2845 }
2846 let (cols, rows) = block_grid(mi_cols, mi_rows);
2847 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
2848 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
2849
2850 let ref_y = PlaneBuf {
2851 data: reference.y.clone(),
2852 width: reference.width,
2853 height: reference.height,
2854 true_width: reference.width,
2855 true_height: reference.height,
2856 };
2857 let ref_u = PlaneBuf {
2858 data: reference.u.clone(),
2859 width: reference.width / 2,
2860 height: reference.height / 2,
2861 true_width: reference.width / 2,
2862 true_height: reference.height / 2,
2863 };
2864 let ref_v = PlaneBuf {
2865 data: reference.v.clone(),
2866 width: reference.width / 2,
2867 height: reference.height / 2,
2868 true_width: reference.width / 2,
2869 true_height: reference.height / 2,
2870 };
2871
2872 let mut y = PlaneBuf {
2873 data: vec![0u8; width * height],
2874 width,
2875 height,
2876 true_width,
2877 true_height,
2878 };
2879 let mut u = PlaneBuf {
2880 data: vec![0u8; width * height / 4],
2881 width: width / 2,
2882 height: height / 2,
2883 true_width: true_width / 2,
2884 true_height: true_height / 2,
2885 };
2886 let mut v = PlaneBuf {
2887 data: vec![0u8; width * height / 4],
2888 width: width / 2,
2889 height: height / 2,
2890 true_width: true_width / 2,
2891 true_height: true_height / 2,
2892 };
2893
2894 let scan32 = default_scan(TX32);
2895 let scan16 = default_scan(TX16);
2896 let scan8 = default_scan(TX8);
2897 let scan4 = default_scan(TX4);
2898
2899 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
2900 let mut dec = SymbolDecoder::new(data);
2901 let mut neighbours = Neighbours::new(
2902 cols as usize * 2,
2903 rows as usize * 2,
2904 mi_cols as usize,
2905 mi_rows as usize,
2906 );
2907 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
2908
2909 for sb_r in 0..sb_rows {
2910 neighbours.start_row();
2911 for sb_c in 0..sb_cols {
2912 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
2913 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
2914 let (has_cols, has_rows) = (
2915 sb_c * SB_MI + SB_MI / 2 < mi_cols,
2916 sb_r * SB_MI + SB_MI / 2 < mi_rows,
2917 );
2918 match (has_cols, has_rows) {
2919 (true, true) => {
2920 dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
2921 }
2922 (true, false) => {
2923 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
2924 }
2925 (false, true) => {
2926 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
2927 }
2928 (false, false) => {}
2929 }
2930
2931 for quadrant in 0..4 {
2932 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
2933 if r32 >= rows || c32 >= cols {
2934 continue;
2935 }
2936 let at = (r32 as usize * 2, c32 as usize * 2);
2937 let ctx32 = neighbours.partition_ctx(at, BLOCK);
2938 let (has_cols32, has_rows32) = (
2939 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
2940 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
2941 );
2942 let part32 = if has_cols32 && has_rows32 {
2943 dec.symbol(&mut cdfs.partition_w32[ctx32])
2944 } else {
2945 match (has_cols32, has_rows32) {
2946 (true, false) => {
2947 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
2948 }
2949 (false, true) => {
2950 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
2951 }
2952 _ => {}
2953 }
2954 PARTITION_SPLIT
2955 };
2956 match part32 {
2957 PARTITION_NONE => {
2958 decode_inter_block(
2959 &mut dec,
2960 &mut cdfs,
2961 &mut neighbours,
2962 &mut grid,
2963 at,
2964 BLOCK,
2965 mi_cols,
2966 mi_rows,
2967 &mut y,
2968 &mut u,
2969 &mut v,
2970 &ref_y,
2971 &ref_u,
2972 &ref_v,
2973 base_q_idx,
2974 TxbSet::Luma32,
2975 TxbSet::Luma32Inter,
2976 TxbSet::Chroma16,
2977 TX32,
2978 TX16,
2979 &scan32,
2980 &scan16,
2981 3,
2982 )?;
2983 }
2984 PARTITION_SPLIT => {
2985 for sub in 0..4 {
2986 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
2987 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
2988 continue;
2989 }
2990 let (has_cols16, has_rows16) = (
2991 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
2992 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
2993 );
2994 if !has_cols16 && !has_rows16 {
2995 return Err(unsupported(
2996 "a 16x16 inter block whose true edge cuts through both \
2997 axes needs a rectangular transform this decoder does \
2998 not code yet",
2999 ));
3000 }
3001 let at16 = (sr, sc);
3002 if has_cols16 && has_rows16 {
3003 let ctx16 = neighbours.partition_ctx(at16, SUB);
3004 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
3005 if part16 != PARTITION_NONE {
3006 return Err(unsupported(
3007 "a partition below 16x16 (this encoder never writes one)",
3008 ));
3009 }
3010 decode_inter_block(
3011 &mut dec,
3012 &mut cdfs,
3013 &mut neighbours,
3014 &mut grid,
3015 at16,
3016 SUB,
3017 mi_cols,
3018 mi_rows,
3019 &mut y,
3020 &mut u,
3021 &mut v,
3022 &ref_y,
3023 &ref_u,
3024 &ref_v,
3025 base_q_idx,
3026 TxbSet::Luma16,
3027 TxbSet::Luma16Inter,
3028 TxbSet::Chroma8,
3029 TX16,
3030 TX8,
3031 &scan16,
3032 &scan8,
3033 2,
3034 )?;
3035 } else {
3036 let ctx16 = neighbours.partition_ctx(at16, SUB);
3037 if has_cols16 {
3038 dec.symbol_fixed(&gather(
3039 &cdfs.partition_w16[ctx16],
3040 VERT_ALIKE,
3041 ));
3042 } else {
3043 dec.symbol_fixed(&gather(
3044 &cdfs.partition_w16[ctx16],
3045 HORZ_ALIKE,
3046 ));
3047 }
3048 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
3049 let leaf_positions: Vec<(u32, u32)> = (0..4)
3050 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
3051 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
3052 .collect();
3053 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
3054 for (mr, mc) in leaf_positions {
3055 let leaf_mi = (mr as usize, mc as usize);
3056 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
3057 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
3058 if part8 != PARTITION_NONE {
3059 return Err(unsupported(
3060 "a partition below 8x8 (this encoder never writes one)",
3061 ));
3062 }
3063 let (skip, is_inter) = decode_inter_block8(
3064 &mut dec,
3065 &mut cdfs,
3066 &mut neighbours,
3067 &mut grid,
3068 mi_cols,
3069 mi_rows,
3070 at16,
3071 leaf_mi,
3072 &mut y,
3073 &mut u,
3074 &mut v,
3075 &ref_y,
3076 &ref_u,
3077 &ref_v,
3078 base_q_idx,
3079 &scan8,
3080 &scan4,
3081 prev_leaf,
3082 )?;
3083 prev_leaf = Some((leaf_mi, skip, is_inter));
3084 }
3085 if let Some((_, skip, is_inter)) = prev_leaf {
3086 neighbours.record_inter(at16, SUB, skip, is_inter);
3087 }
3088 }
3089 }
3090 }
3091 _ => {
3092 return Err(unsupported("a partition type this encoder never writes"));
3093 }
3094 }
3095 }
3096 }
3097 }
3098
3099 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
3100
3101 let (fw, fh) = (frame_width as usize, frame_height as usize);
3102 if fw == width && fh == height {
3103 return Ok(Picture {
3104 width,
3105 height,
3106 y: y.data,
3107 u: u.data,
3108 v: v.data,
3109 });
3110 }
3111 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
3112 let mut out = Vec::with_capacity(w * h);
3113 for row in 0..h {
3114 out.extend_from_slice(&plane.data[row * plane.width..][..w]);
3115 }
3116 out
3117 };
3118 Ok(Picture {
3119 width: fw,
3120 height: fh,
3121 y: crop(&y, fw, fh),
3122 u: crop(&u, fw / 2, fh / 2),
3123 v: crop(&v, fw / 2, fh / 2),
3124 })
3125}
3126
3127#[cfg(test)]
3128mod tests {
3129 use super::*;
3130
3131 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
3132 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
3133 // single-purpose writers with their own skip-context rule (keyed to
3134 // superblock position, not the neighbour-tracked one every real block
3135 // uses), never reached by `encode_key_frame_with_modes` — decoding them
3136 // would need a second, throwaway context convention next to the real
3137 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
3138 // this decoder's one target, and the round-trip test below is against
3139 // that path with real quantised residual, not a synthetic all-DC frame.
3140
3141 #[test]
3142 fn a_frame_with_no_mode_info_grid_is_refused() {
3143 assert!(
3144 decode_key_frame_tile(&[0u8; 4], 0, 32, 32, 0, 128, false, &CdefParams::default())
3145 .is_err()
3146 );
3147 }
3148
3149 /// Encodes and decodes one picture with `modes`, asserting the decoder's
3150 /// planes are byte-exact against the encoder's own reconstruction.
3151 fn round_trips(w: usize, h: usize, modes: &[u8]) {
3152 use crate::encode::{Encoded, Picture as Pic};
3153 let mut source = vec![0u8; w * h];
3154 for row in 0..h {
3155 for col in 0..w {
3156 source[row * w + col] = ((row * 3 + col * 5) % 251) as u8;
3157 }
3158 }
3159 let picture = Pic {
3160 width: w,
3161 height: h,
3162 y: source,
3163 u: vec![128; w * h / 4],
3164 v: vec![128; w * h / 4],
3165 };
3166 let Encoded {
3167 tile,
3168 reconstruction,
3169 mi_cols,
3170 mi_rows,
3171 base_q_idx,
3172 ..
3173 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
3174 let decoded = decode_key_frame_tile(
3175 &tile,
3176 mi_cols,
3177 mi_rows,
3178 base_q_idx,
3179 w as u32,
3180 h as u32,
3181 false,
3182 &CdefParams::default(),
3183 )
3184 .unwrap();
3185 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
3186 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
3187 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
3188 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
3189 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
3190 }
3191
3192 #[test]
3193 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
3194 for (w, h) in [(128usize, 128usize), (192, 128)] {
3195 round_trips(w, h, &[DC_PRED as u8]);
3196 }
3197 }
3198
3199 /// Every one of the thirteen key-frame intra modes, at their base angle,
3200 /// on real (non-flat) content: the mode search picks whichever wins each
3201 /// block, so this exercises the directional edge/reach plumbing this
3202 /// decoder round adds, not just `DC_PRED`.
3203 #[test]
3204 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
3205 for (w, h) in [(128usize, 128usize), (192, 128)] {
3206 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
3207 }
3208 }
3209
3210 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
3211 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
3212 /// this decoder round adds.
3213 #[test]
3214 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
3215 for (w, h) in [(854usize, 480usize), (216, 96)] {
3216 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
3217 }
3218 }
3219
3220 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
3221 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
3222 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
3223 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
3224 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
3225 /// bit, `partition_w8` leaves).
3226 #[test]
3227 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
3228 for (w, h) in [(40usize, 32usize), (640, 360)] {
3229 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
3230 }
3231 }
3232
3233 /// A skipped block codes no residual syntax at all (spec 5.11.34):
3234 /// straight prediction on every plane. The real key-frame writer never
3235 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
3236 /// `0`), so this constructs the exact symbol sequence a writer that did
3237 /// emit it would produce, by hand, and asserts the decoded reconstruction
3238 /// is pure DC prediction (mid-grey, with no neighbours) rather than
3239 /// refusing.
3240 #[test]
3241 fn a_skipped_block_decodes_to_pure_prediction() {
3242 use crate::msac::SymbolEncoder;
3243 let mut cdfs = Cdfs::new(q_ctx_of(40));
3244 let mut enc = SymbolEncoder::new();
3245 // One whole, unsplit 64x64 superblock, coded skip = true.
3246 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
3247 enc.symbol(1, &mut cdfs.skip[0]);
3248 enc.symbol(
3249 DC_PRED,
3250 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
3251 );
3252 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
3253 let data = enc.finish();
3254 let decoded =
3255 decode_key_frame_tile(&data, 16, 16, 40, 64, 64, false, &CdefParams::default())
3256 .unwrap();
3257 assert!(
3258 decoded.y.iter().all(|&s| s == 128),
3259 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
3260 );
3261 }
3262
3263 // ffmpeg cross-oracle: an independent decoder (not this crate's own
3264 // encoder-side reconstruction) agrees with what this module decodes,
3265 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
3266 // name (that module is another lane's territory this round, and the
3267 // helpers are `#[cfg(test)]`-private to it).
3268 use std::io::Write;
3269 use std::process::{Command, Stdio};
3270
3271 fn have_ffmpeg() -> bool {
3272 Command::new("ffmpeg")
3273 .arg("-version")
3274 .stdout(Stdio::null())
3275 .stderr(Stdio::null())
3276 .status()
3277 .is_ok_and(|s| s.success())
3278 }
3279
3280 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
3281 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
3282 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
3283 let mut child = Command::new("ffmpeg")
3284 .args([
3285 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3286 ])
3287 .stdin(Stdio::piped())
3288 .stdout(Stdio::piped())
3289 .stderr(Stdio::piped())
3290 .spawn()
3291 .expect("ffmpeg failed to start");
3292 child
3293 .stdin
3294 .take()
3295 .expect("ffmpeg stdin")
3296 .write_all(stream)
3297 .expect("writing the stream to ffmpeg");
3298 let out = child.wait_with_output().expect("ffmpeg failed to run");
3299 assert!(
3300 out.status.success(),
3301 "ffmpeg refused the stream: {}",
3302 String::from_utf8_lossy(&out.stderr)
3303 );
3304 let (luma, chroma) = (width * height, width * height / 4);
3305 assert_eq!(
3306 out.stdout.len(),
3307 luma + 2 * chroma,
3308 "expected one 4:2:0 frame"
3309 );
3310 Picture {
3311 width,
3312 height,
3313 y: out.stdout[..luma].to_vec(),
3314 u: out.stdout[luma..luma + chroma].to_vec(),
3315 v: out.stdout[luma + chroma..].to_vec(),
3316 }
3317 }
3318
3319 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
3320 fn ffmpeg_decode_sequence(
3321 stream: &[u8],
3322 width: usize,
3323 height: usize,
3324 frames: usize,
3325 ) -> Vec<Picture> {
3326 let mut child = Command::new("ffmpeg")
3327 .args([
3328 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3329 ])
3330 .stdin(Stdio::piped())
3331 .stdout(Stdio::piped())
3332 .stderr(Stdio::piped())
3333 .spawn()
3334 .expect("ffmpeg failed to start");
3335 child
3336 .stdin
3337 .take()
3338 .expect("ffmpeg stdin")
3339 .write_all(stream)
3340 .expect("writing the stream to ffmpeg");
3341 let out = child.wait_with_output().expect("ffmpeg failed to run");
3342 assert!(
3343 out.status.success(),
3344 "ffmpeg refused the stream: {}",
3345 String::from_utf8_lossy(&out.stderr)
3346 );
3347 let (luma, chroma) = (width * height, width * height / 4);
3348 let frame_bytes = luma + 2 * chroma;
3349 assert_eq!(
3350 out.stdout.len(),
3351 frame_bytes * frames,
3352 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
3353 String::from_utf8_lossy(&out.stderr)
3354 );
3355 (0..frames)
3356 .map(|i| {
3357 let base = i * frame_bytes;
3358 Picture {
3359 width,
3360 height,
3361 y: out.stdout[base..base + luma].to_vec(),
3362 u: out.stdout[base + luma..base + luma + chroma].to_vec(),
3363 v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
3364 }
3365 })
3366 .collect()
3367 }
3368
3369 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
3370 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
3371 /// test binary runs callers on parallel threads, and a shared name lets
3372 /// one test's cleanup race another's still-reading ffprobe --
3373 /// pid-keyed-temp-path class).
3374 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
3375 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3376 let path = std::env::temp_dir().join(format!(
3377 "ec-av1-decode-probe-{}-{}.obu",
3378 std::process::id(),
3379 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
3380 ));
3381 let _ = std::fs::remove_file(&path);
3382 std::fs::write(&path, stream).expect("writing the probe stream");
3383 let out = Command::new("ffprobe")
3384 .args([
3385 "-v",
3386 "error",
3387 "-f",
3388 "obu",
3389 "-select_streams",
3390 "v:0",
3391 "-show_entries",
3392 "stream=width,height",
3393 "-of",
3394 "csv=p=0",
3395 ])
3396 .arg(&path)
3397 .output()
3398 .expect("ffprobe failed to run");
3399 let _ = std::fs::remove_file(&path);
3400 assert!(
3401 out.status.success(),
3402 "ffprobe refused the stream: {}",
3403 String::from_utf8_lossy(&out.stderr)
3404 );
3405 let text = String::from_utf8_lossy(&out.stdout);
3406 let mut fields = text.trim().split(',');
3407 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
3408 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
3409 (width, height)
3410 }
3411
3412 /// This module's own decoder against an independent one (ffmpeg), not
3413 /// just against this crate's encoder-side reconstruction: both decoders
3414 /// read the identical tile bytes, so agreement here rules out a bug this
3415 /// crate's own writer and reader could otherwise share.
3416 #[test]
3417 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
3418 if !have_ffmpeg() {
3419 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
3420 return;
3421 }
3422 use crate::encode::encode_key_frame;
3423 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
3424 let picture = round_trip_test_card(width, height);
3425 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3426 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
3427 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
3428 let ours = decode_key_frame_tile(
3429 &encoded.tile,
3430 encoded.mi_cols,
3431 encoded.mi_rows,
3432 encoded.base_q_idx,
3433 coded_w,
3434 coded_h,
3435 false,
3436 &CdefParams::default(),
3437 )
3438 .unwrap();
3439 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
3440 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
3441 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
3442 }
3443 }
3444
3445 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
3446 let mut picture = crate::encode::Picture::grey(width, height);
3447 for row in 0..height {
3448 for col in 0..width {
3449 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u8;
3450 }
3451 }
3452 for row in 0..height / 2 {
3453 for col in 0..width / 2 {
3454 let i = row * width / 2 + col;
3455 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u8;
3456 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u8;
3457 }
3458 }
3459 picture
3460 }
3461
3462 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
3463 let mut picture = crate::encode::Picture::grey(width, height);
3464 for y in 0..height {
3465 for x in 0..width {
3466 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
3467 let gradient = sx * 200.0 / width as f64;
3468 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u8;
3469 }
3470 }
3471 for y in 0..height / 2 {
3472 for x in 0..width / 2 {
3473 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
3474 let i = y * width / 2 + x;
3475 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
3476 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
3477 }
3478 }
3479 picture
3480 }
3481
3482 /// A GOP (one key frame plus several inter frames, each panned so its
3483 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
3484 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
3485 /// reconstruction, frame by frame, chaining each decoded frame straight
3486 /// into the next as its reference -- exactly the single-slot DPB
3487 /// [`crate::encode::encode_sequence`] itself threads.
3488 fn gop_round_trips(width: usize, height: usize) {
3489 use crate::encode::encode_sequence;
3490 let pictures: Vec<_> = (0..4)
3491 .map(|i| panned_test_card(width, height, i * 3))
3492 .collect();
3493 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
3494 assert_eq!(encoded.frames.len(), 4);
3495
3496 let key = &encoded.frames[0];
3497 let mut reference = decode_key_frame_tile(
3498 &key.tile,
3499 key.mi_cols,
3500 key.mi_rows,
3501 key.base_q_idx,
3502 width as u32,
3503 height as u32,
3504 false,
3505 &CdefParams::default(),
3506 )
3507 .unwrap();
3508 assert_eq!(
3509 reference.y, key.reconstruction.y,
3510 "{width}x{height} frame 0 luma"
3511 );
3512 assert_eq!(
3513 reference.u, key.reconstruction.u,
3514 "{width}x{height} frame 0 U"
3515 );
3516 assert_eq!(
3517 reference.v, key.reconstruction.v,
3518 "{width}x{height} frame 0 V"
3519 );
3520
3521 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
3522 let decoded = decode_inter_frame_tile(
3523 &frame.tile,
3524 frame.mi_cols,
3525 frame.mi_rows,
3526 frame.base_q_idx,
3527 width as u32,
3528 height as u32,
3529 &reference,
3530 &CdefParams::default(),
3531 )
3532 .unwrap();
3533 assert_eq!(
3534 decoded.y, frame.reconstruction.y,
3535 "{width}x{height} frame {i} luma"
3536 );
3537 assert_eq!(
3538 decoded.u, frame.reconstruction.u,
3539 "{width}x{height} frame {i} U"
3540 );
3541 assert_eq!(
3542 decoded.v, frame.reconstruction.v,
3543 "{width}x{height} frame {i} V"
3544 );
3545 reference = decoded;
3546 }
3547 }
3548
3549 #[test]
3550 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
3551 gop_round_trips(128, 64);
3552 }
3553
3554 /// Same claim, at a size that is not a whole number of 32x32 blocks
3555 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
3556 /// split path is exercised too.
3557 #[test]
3558 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
3559 gop_round_trips(216, 96);
3560 }
3561
3562 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
3563 /// this module does, frame for frame.
3564 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
3565 /// MV stack's *second* candidate (`near_mv`), not its first
3566 /// (`nearest_mv`) -- a hand-built symbol stream drives
3567 /// [`decode_inter_block`] directly, since this crate's own encoder never
3568 /// writes NEARMV (round 3: it never chooses the mode).
3569 #[test]
3570 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
3571 use crate::msac::SymbolEncoder;
3572 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
3573
3574 const LAST_FRAME: i8 = 1;
3575 let (mi_cols, mi_rows) = (12u32, 12u32);
3576 let side = 16usize; // one 16x16 leaf block
3577 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
3578 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
3579 let bw4 = side / 4;
3580
3581 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
3582 let (above_mv, left_mv) = ((4, 4), (8, 8));
3583 let neighbour = |mv| MiInfo {
3584 is_inter: true,
3585 ref_frame: LAST_FRAME,
3586 mv,
3587 is_new_mv: false,
3588 size: 1,
3589 };
3590 for col in mi_col..mi_col + bw4 {
3591 grid.set(mi_row - 1, col, neighbour(above_mv));
3592 }
3593 for row in mi_row..mi_row + bw4 {
3594 grid.set(row, mi_col - 1, neighbour(left_mv));
3595 }
3596
3597 let stack = find_mv_stack(
3598 &grid,
3599 mi_row,
3600 mi_col,
3601 bw4,
3602 bw4,
3603 LAST_FRAME,
3604 mi_cols as usize,
3605 mi_rows as usize,
3606 );
3607 // Sanity on the test's own setup, not the code under test: two equal-
3608 // weight candidates keep scan order (above, then left -- module doc).
3609 assert_eq!(stack.entries.len(), 2);
3610 assert_eq!(stack.nearest_mv, above_mv);
3611 assert_eq!(stack.near_mv, left_mv);
3612
3613 let (skip_ctx, ii_ctx, sr_ctx) = (
3614 0usize,
3615 intra_inter_ctx(true, true, false, false),
3616 single_ref_ctx(false),
3617 );
3618
3619 let mut cdfs = Cdfs::new(q_ctx_of(100));
3620 let mut enc = SymbolEncoder::new();
3621 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
3622 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
3623 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
3624 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
3625 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
3626 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
3627 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
3628 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
3629 let data = enc.finish();
3630
3631 let (width, height) = (64usize, 64usize);
3632 let ref_pattern: Vec<u8> = (0..width * height).map(|i| (i % 251) as u8).collect();
3633 let ref_plane = |scale: usize| PlaneBuf {
3634 data: ref_pattern
3635 .iter()
3636 .step_by(scale.max(1))
3637 .take((width / scale) * (height / scale))
3638 .copied()
3639 .collect(),
3640 width: width / scale,
3641 height: height / scale,
3642 true_width: width / scale,
3643 true_height: height / scale,
3644 };
3645 let ref_y = PlaneBuf {
3646 data: ref_pattern.clone(),
3647 width,
3648 height,
3649 true_width: width,
3650 true_height: height,
3651 };
3652 let ref_u = ref_plane(2);
3653 let ref_v = ref_plane(2);
3654
3655 let mut y = PlaneBuf {
3656 data: vec![0u8; width * height],
3657 width,
3658 height,
3659 true_width: width,
3660 true_height: height,
3661 };
3662 let mut u = PlaneBuf {
3663 data: vec![0u8; (width / 2) * (height / 2)],
3664 width: width / 2,
3665 height: height / 2,
3666 true_width: width / 2,
3667 true_height: height / 2,
3668 };
3669 let mut v = PlaneBuf {
3670 data: vec![0u8; (width / 2) * (height / 2)],
3671 width: width / 2,
3672 height: height / 2,
3673 true_width: width / 2,
3674 true_height: height / 2,
3675 };
3676
3677 let mut cdfs = Cdfs::new(q_ctx_of(100));
3678 let mut dec = SymbolDecoder::new(&data);
3679 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
3680 decode_inter_block(
3681 &mut dec,
3682 &mut cdfs,
3683 &mut neighbours,
3684 &mut grid,
3685 (r, c),
3686 side,
3687 mi_cols,
3688 mi_rows,
3689 &mut y,
3690 &mut u,
3691 &mut v,
3692 &ref_y,
3693 &ref_u,
3694 &ref_v,
3695 100,
3696 TxbSet::Luma16,
3697 TxbSet::Luma16Inter,
3698 TxbSet::Chroma8,
3699 TX16,
3700 TX8,
3701 &[],
3702 &[],
3703 0,
3704 )
3705 .unwrap();
3706
3707 let (px, py) = (c * SUB, r * SUB);
3708 let mut want_near = vec![0u8; side * side];
3709 crate::mc::predict(
3710 &ref_y.data,
3711 ref_y.width,
3712 ref_y.true_width,
3713 ref_y.true_height,
3714 mv_to_q4(px, left_mv.1, true),
3715 mv_to_q4(py, left_mv.0, true),
3716 side,
3717 side,
3718 &mut want_near,
3719 );
3720 let mut want_nearest = vec![0u8; side * side];
3721 crate::mc::predict(
3722 &ref_y.data,
3723 ref_y.width,
3724 ref_y.true_width,
3725 ref_y.true_height,
3726 mv_to_q4(px, above_mv.1, true),
3727 mv_to_q4(py, above_mv.0, true),
3728 side,
3729 side,
3730 &mut want_nearest,
3731 );
3732 assert_ne!(
3733 want_near, want_nearest,
3734 "test setup: the two candidate MVs must predict differently"
3735 );
3736
3737 let mut got = vec![0u8; side * side];
3738 for row in 0..side {
3739 got[row * side..(row + 1) * side].copy_from_slice(
3740 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
3741 );
3742 }
3743 assert_eq!(
3744 got, want_near,
3745 "NEARMV predicted from the wrong stack entry"
3746 );
3747 }
3748
3749 #[test]
3750 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
3751 if !have_ffmpeg() {
3752 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
3753 return;
3754 }
3755 use crate::encode::encode_sequence;
3756 let (width, height) = (128usize, 64usize);
3757 let pictures: Vec<_> = (0..3)
3758 .map(|i| panned_test_card(width, height, i * 3))
3759 .collect();
3760 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
3761 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
3762 let ffmpeg_frames =
3763 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
3764
3765 let key = &encoded.frames[0];
3766 let mut reference = decode_key_frame_tile(
3767 &key.tile,
3768 key.mi_cols,
3769 key.mi_rows,
3770 key.base_q_idx,
3771 coded_w,
3772 coded_h,
3773 false,
3774 &CdefParams::default(),
3775 )
3776 .unwrap();
3777 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
3778
3779 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
3780 let decoded = decode_inter_frame_tile(
3781 &frame.tile,
3782 frame.mi_cols,
3783 frame.mi_rows,
3784 frame.base_q_idx,
3785 coded_w,
3786 coded_h,
3787 &reference,
3788 &CdefParams::default(),
3789 )
3790 .unwrap();
3791 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
3792 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
3793 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
3794 reference = decoded;
3795 }
3796 }
3797}