forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

tile.rs5319 lines, 217.8 KiBHistoryRawDownload
1//! Tile payload writer (spec 5.11), for the one block coding the encoder can
2//! produce today: a key frame whose every superblock is a single 64x64
3//! DC-predicted block with no residual.
4//!
5//! That frame decodes to a flat mid-grey picture — every sample is the value a
6//! DC prediction with no neighbours produces — which is what makes it a usable
7//! gate: any desync between this writer and a real decoder shows up as a
8//! decode failure or a sample that is not mid-grey, with no metric in the way.
9//! It is the skeleton the block modes, transform sizes and coefficients hang
10//! off as they arrive.
11
12use std::sync::LazyLock;
13
14use ec_core::{Error, Result};
15
16use crate::cdf;
17use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
18use crate::msac::SymbolEncoder;
19use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
20
21/// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
22/// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
23/// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
24/// same variable, so the two traces line up symbol for symbol. Checked once
25/// per process, so unset (the default) costs one atomic load per call and no
26/// allocation. Only the real tile writer below calls this -- the mode/rate
27/// search's own trial encoders never do -- so the trace does not need the
28/// throwaway-encoder gating a whole-encoder trace would.
29fn ec_rng_trace(msg: impl FnOnce() -> String) {
30 use std::sync::atomic::{AtomicU8, Ordering};
31 static ON: AtomicU8 = AtomicU8::new(2); // 2 = unknown, 1 = on, 0 = off
32 let on = match ON.load(Ordering::Relaxed) {
33 2 => {
34 let on = u8::from(std::env::var_os("EC_RNG").is_some());
35 ON.store(on, Ordering::Relaxed);
36 on
37 }
38 v => v,
39 };
40 if on == 1 {
41 eprintln!("{}", msg());
42 }
43}
44
45/// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
46const PARTITION_NONE: usize = 0;
47/// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants.
48const PARTITION_SPLIT: usize = 3;
49
50/// The partition types whose probability mass the split-or-horizontal flag of
51/// a superblock hanging off the bottom of the frame gathers (spec 9.3,
52/// `partition_gather_vert_alike`): the flag says split, so everything vertical
53/// or split lands on it.
54const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
55
56/// The same for a superblock hanging off the right-hand edge
57/// (`partition_gather_horz_alike`).
58const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
59
60/// Mode-info units across a 32x32 block.
61pub(crate) const BLOCK_MI: u32 = SB_MI / 2;
62
63/// Mode-info units across a 16x16 block, the smallest this crate's key-frame
64/// writer codes.
65pub(crate) const SUB_MI: u32 = BLOCK_MI / 2;
66
67/// spec `decode_partition`'s `hasRows`/`hasCols` (5.11.4), recomputed at
68/// whichever block size is asking: a block of `side_mi` mode-info units at mi
69/// position `pos` may be coded unsplit (its own `PARTITION_NONE`) only when
70/// this is true in both directions -- the frame's *true* size can put the
71/// boundary inside a superblock, a 32x32 quadrant or (since this writer's
72/// smallest block is 16x16) even a leaf, and each level must ask again with
73/// its own half, not just once at the superblock.
74pub(crate) fn has_half(pos: u32, side_mi: u32, bound: u32) -> bool {
75 pos + side_mi / 2 < bound
76}
77
78/// The number of 32x32 block columns/rows a frame whose *true* (unpadded)
79/// size gives `mi_cols`/`mi_rows` is coded over: every block whose mi origin
80/// (`col * BLOCK_MI`) is inside the true bound is coded, so this is a
81/// ceiling, not the exact division a block-aligned frame would give. Shared
82/// by the tile writer's own iteration and by [`crate::encode`]'s block/
83/// superblock generation, which must agree with it exactly.
84pub(crate) fn block_grid(mi_cols: u32, mi_rows: u32) -> (u32, u32) {
85 (mi_cols.div_ceil(BLOCK_MI), mi_rows.div_ceil(BLOCK_MI))
86}
87/// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode.
88const DC_PRED: usize = 0;
89
90/// `V_PRED` (spec 6.10.2), the first of the eight directional intra modes and
91/// so the first mode that carries an angle delta.
92const V_PRED: usize = 1;
93
94/// `H_PRED`, which predicts every row from the column to the block's left.
95#[cfg(test)]
96const H_PRED: usize = 2;
97
98/// The last directional mode, `D67_PRED`.
99const D67_PRED: usize = 8;
100
101/// The number of intra modes a key frame's luma block chooses from,
102/// `INTRA_MODES` (spec 3).
103const INTRA_MODES: usize = 13;
104
105/// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts
106/// its neighbours in when they pick the CDF for the next block's mode.
107pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0];
108
109/// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
110/// +3, so `MAX_ANGLE_DELTA` is the middle of it.
111const ANGLE_DELTA_ZERO: usize = 3;
112/// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
113const SB_MI: u32 = 16;
114
115/// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
116const NUM_BASE_LEVELS: i32 = 2;
117/// Where DCT_DCT sits in the spec's `Tx_Type_Intra_Inv_Set2`, the set a 16x16
118/// intra luma transform picks its type from.
119const TX_TYPE_DCT_DCT_SET2: usize = 1;
120/// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
121/// Golomb tail takes over.
122const COEFF_BASE_RANGE: i32 = 12;
123/// `BR_CDF_SIZE - 1` (spec 3): the largest increment one base-range symbol
124/// carries.
125const BR_STEP: i32 = 3;
126/// The largest level the base and base-range syntax carry between them.
127/// Anything above it is written as a Golomb tail on top of this.
128const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
129/// The largest level this writer codes. The Golomb tail is a length in unary
130/// followed by that many bits, and the spec's decoder reads at most twenty of
131/// each, so a level a decoder cannot read back is refused rather than written.
132const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
133
134/// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s
135/// leading index) a frame's `base_q_idx` picks its default CDFs from.
136/// [`crate::cdf`] carries all four, one constant set per context.
137fn q_ctx_of(base_q_idx: u8) -> usize {
138 match base_q_idx {
139 0..=20 => 0,
140 21..=60 => 1,
141 61..=120 => 2,
142 _ => 3,
143 }
144}
145
146/// Both writers here code whole superblocks only: a partial one forces the
147/// partition syntax down the block tree, which they do not code yet.
148/// The probability the CDF gives one symbol on its own.
149fn element_prob(cdf: &[u16], element: usize) -> u16 {
150 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
151}
152
153/// The two-symbol CDF a partial superblock's partition flag is coded with: the
154/// mass of the listed partition types becomes the probability of a split, and
155/// the rest is the one partition the frame edge still allows.
156fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
157 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
158 [32768 - split, 32768, 0]
159}
160
161fn check_superblocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
162 if mi_cols == 0
163 || mi_rows == 0
164 || !mi_cols.is_multiple_of(SB_MI)
165 || !mi_rows.is_multiple_of(SB_MI)
166 {
167 return Err(Error::unsupported(
168 "AV1 tile",
169 "a key frame is written only for frames that are a whole number \
170 of 64x64 superblocks",
171 ));
172 }
173 Ok(())
174}
175
176/// Writes the payload of a one-tile key frame in which every superblock is a
177/// skipped 64x64 DC-predicted block.
178///
179/// `mi_cols` and `mi_rows` are the frame's dimensions in 4x4 mode-info units,
180/// as the frame header carries them.
181///
182/// # Errors
183/// Returns an error when the frame is not a whole number of 64x64 superblocks:
184/// a partial superblock forces the partition syntax down the block tree, which
185/// this writer does not code yet.
186pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {
187 check_superblocks(mi_cols, mi_rows)?;
188 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
189
190 let mut enc = SymbolEncoder::new();
191 for r in 0..sb_rows {
192 for c in 0..sb_cols {
193 // decode_partition (spec 5.11.4). Every neighbour is a 64x64 block,
194 // whose stored partition context has a zero bit at this block
195 // size, so the context is 0 wherever the block sits.
196 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
197
198 // intra_frame_mode_info (spec 5.11.16). Segmentation, delta q,
199 // delta lf, palette, filter intra and intrabc are all off in the
200 // frame header, and a skipped block codes no CDEF index, so the
201 // block is three symbols: the skip flag and the two modes.
202 let skip_ctx = usize::from(r > 0) + usize::from(c > 0);
203 enc.symbol_fixed(1, &cdf::SKIP[skip_ctx]);
204 // Both neighbours are DC-predicted, and an unavailable neighbour
205 // counts as DC too, so both mode contexts are 0.
206 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
207 // Chroma from luma is only offered up to 32x32, so the CFL-free
208 // table is the one a 64x64 block reads.
209 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
210
211 // read_block_tx_size codes nothing while the frame's tx_mode is
212 // TX_MODE_LARGEST, and a skipped block has no residual, so the
213 // block ends here.
214 }
215 }
216 Ok(enc.finish())
217}
218
219/// Writes the payload of a one-tile key frame in which every superblock is a
220/// 64x64 DC-predicted block carrying one luma DC coefficient of `dc_level` and
221/// no chroma residual.
222///
223/// `dc_level` is a quantised level, not a sample value: the decoder multiplies
224/// it by the frame's DC quantiser and inverse-transforms it over the whole
225/// block, so the picture it makes is a flat grey some distance either side of
226/// the mid-grey a zero level gives. `base_q_idx` is the frame header's, and
227/// picks the coefficient CDFs.
228///
229/// # Errors
230/// As [`dc_key_frame_tile_levels`], which this is the one-level case of.
231pub fn dc_key_frame_tile(
232 mi_cols: u32,
233 mi_rows: u32,
234 base_q_idx: u8,
235 dc_level: i32,
236) -> Result<Vec<u8>> {
237 check_superblocks(mi_cols, mi_rows)?;
238 let blocks = ((mi_cols / SB_MI) * (mi_rows / SB_MI)) as usize;
239 dc_key_frame_tile_levels(mi_cols, mi_rows, base_q_idx, &vec![dc_level; blocks])
240}
241
242/// Writes the payload of a one-tile key frame carrying one luma DC coefficient
243/// per superblock, `levels` giving them in the raster order the superblocks are
244/// coded in.
245///
246/// Each superblock decodes to a flat block of its own grey, so a frame written
247/// here is a grid of greys the caller chooses — which is what makes the sign
248/// context observable: a block's sign context is read off its coded neighbours,
249/// and a frame whose levels differ in sign exercises the three-way split that a
250/// single-sign frame cannot reach.
251///
252/// # Errors
253/// Returns an error when the frame is not a whole number of 64x64 superblocks,
254/// when `levels` does not carry exactly one level per superblock, when a level
255/// is outside the range the base and base-range syntax carry (`-14..=14`
256/// without zero).
257pub fn dc_key_frame_tile_levels(
258 mi_cols: u32,
259 mi_rows: u32,
260 base_q_idx: u8,
261 levels: &[i32],
262) -> Result<Vec<u8>> {
263 check_superblocks(mi_cols, mi_rows)?;
264 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
265 check_levels(levels, (sb_cols * sb_rows) as usize)?;
266 let q_ctx = q_ctx_of(base_q_idx);
267 let txb_skip_luma_64 = crate::cdf_state::pick(
268 q_ctx,
269 cdf::TXB_SKIP_LUMA_64_Q0,
270 cdf::TXB_SKIP_LUMA_64_Q1,
271 cdf::TXB_SKIP_LUMA_64,
272 cdf::TXB_SKIP_LUMA_64_Q3,
273 );
274 let base_eob_luma_64_dc = crate::cdf_state::pick(
275 q_ctx,
276 cdf::COEFF_BASE_EOB_LUMA_64_Q0[0],
277 cdf::COEFF_BASE_EOB_LUMA_64_Q1[0],
278 cdf::COEFF_BASE_EOB_LUMA_64[0],
279 cdf::COEFF_BASE_EOB_LUMA_64_Q3[0],
280 );
281 let txb_skip_chroma_32_none = crate::cdf_state::pick(
282 q_ctx,
283 cdf::TXB_SKIP_CHROMA_32_Q0[0],
284 cdf::TXB_SKIP_CHROMA_32_Q1[0],
285 cdf::TXB_SKIP_CHROMA_32[0],
286 cdf::TXB_SKIP_CHROMA_32_Q3[0],
287 );
288
289 // The sign of the DC each coded block left behind, for the two neighbours
290 // the sign context is read from: one row of them above, and the block to
291 // the left, which is dropped at the start of every superblock row the way a
292 // decoder clears its left context there.
293 let mut above: Vec<Option<bool>> = vec![None; sb_cols as usize];
294 let mut enc = SymbolEncoder::new();
295 for r in 0..sb_rows {
296 let mut left: Option<bool> = None;
297 for c in 0..sb_cols {
298 let dc_level = levels[(r * sb_cols + c) as usize];
299 let negative = dc_level < 0;
300
301 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
302
303 // Nothing is skipped now, so every neighbour's skip flag is 0 and
304 // the skip context stays 0 across the frame.
305 enc.symbol_fixed(0, &cdf::SKIP[0]);
306 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
307 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
308
309 write_dc_coeffs(
310 &mut enc,
311 dc_level,
312 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)),
313 q_ctx,
314 &txb_skip_luma_64,
315 &base_eob_luma_64_dc,
316 );
317
318 // Both chroma transform blocks are all-zero. Their planes carry no
319 // coded coefficient anywhere in the frame, so the neighbour halves
320 // of their context stay 0 and only the offset for a transform block
321 // that covers its whole plane block is left: context 7.
322 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
323 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
324
325 above[c as usize] = Some(negative);
326 left = Some(negative);
327 }
328 }
329 Ok(enc.finish())
330}
331
332/// Writes the payload of a one-tile key frame in which every superblock is
333/// split into four 32x32 DC-predicted blocks, each carrying one luma DC
334/// coefficient and no chroma residual.
335///
336/// `levels` gives one level per 32x32 block in raster order across the frame,
337/// so the grid is twice as wide and twice as tall as the superblock grid. The
338/// blocks are coded in the z-order a superblock's split walks, but every
339/// block's neighbours above and to its left are coded before it either way, so
340/// the picture reads in raster order.
341///
342/// # Errors
343/// As [`dc_key_frame_tile_levels`], with `levels` sized for the 32x32 grid.
344pub fn split_dc_key_frame_tile(
345 mi_cols: u32,
346 mi_rows: u32,
347 base_q_idx: u8,
348 levels: &[i32],
349) -> Result<Vec<u8>> {
350 check_superblocks(mi_cols, mi_rows)?;
351 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
352 let (cols, rows) = (sb_cols * 2, sb_rows * 2);
353 check_levels(levels, (cols * rows) as usize)?;
354 let q_ctx = q_ctx_of(base_q_idx);
355 let txb_skip_luma_32 = crate::cdf_state::pick(
356 q_ctx,
357 cdf::TXB_SKIP_LUMA_32_Q0,
358 cdf::TXB_SKIP_LUMA_32_Q1,
359 cdf::TXB_SKIP_LUMA_32,
360 cdf::TXB_SKIP_LUMA_32_Q3,
361 );
362 let base_eob_luma_32 = crate::cdf_state::pick(
363 q_ctx,
364 cdf::COEFF_BASE_EOB_LUMA_32_Q0[0],
365 cdf::COEFF_BASE_EOB_LUMA_32_Q1[0],
366 cdf::COEFF_BASE_EOB_LUMA_32[0],
367 cdf::COEFF_BASE_EOB_LUMA_32_Q3[0],
368 );
369 let txb_skip_chroma_16_0 = crate::cdf_state::pick(
370 q_ctx,
371 cdf::TXB_SKIP_CHROMA_16_Q0[0],
372 cdf::TXB_SKIP_CHROMA_16_Q1[0],
373 cdf::TXB_SKIP_CHROMA_16[0],
374 cdf::TXB_SKIP_CHROMA_16_Q3[0],
375 );
376
377 let mut above: Vec<Option<bool>> = vec![None; cols as usize];
378 let mut left: Vec<Option<bool>> = vec![None; rows as usize];
379
380 let mut enc = SymbolEncoder::new();
381 for sb_r in 0..sb_rows {
382 // A decoder clears its left context at the start of every superblock
383 // row, and so does the partition context the 64x64 symbol reads.
384 left.iter_mut().for_each(|l| *l = None);
385 for sb_c in 0..sb_cols {
386 // The partition context of a 64x64 block reads the bit its
387 // neighbours' block size sets at this depth: a 32x32 neighbour sets
388 // it, and an uncoded one leaves it clear, so the context is just
389 // which neighbours exist. The 32x32 blocks below read a bit their
390 // own size leaves clear, so their context is 0 throughout.
391 // Every superblock here is split, so an existing neighbour always
392 // sets that bit.
393 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
394 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
395
396 for quadrant in 0..4 {
397 let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
398 let dc_level = levels[(r * cols + c) as usize];
399 let negative = dc_level < 0;
400
401 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
402 enc.symbol_fixed(0, &cdf::SKIP[0]);
403 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
404 // Chroma from luma is offered up to 32x32, so the block reads
405 // the wider table even though it does not take the mode.
406 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL[DC_PRED]);
407
408 write_dc_coeffs(
409 &mut enc,
410 dc_level,
411 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])),
412 q_ctx,
413 &txb_skip_luma_32,
414 &base_eob_luma_32,
415 );
416 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
417 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
418
419 above[c as usize] = Some(negative);
420 left[r as usize] = Some(negative);
421 }
422 }
423 }
424 Ok(enc.finish())
425}
426
427/// One quantised coefficient of a transform block.
428///
429/// `row` and `col` are its position in the transform it belongs to — 32x32 for
430/// luma, 16x16 for each chroma plane — not in the picture: a coefficient at
431/// row 0 varies along the picture's width and one at column 0 along its
432/// height, and the coefficient at the origin is the DC the block's average
433/// sample value rides on.
434#[derive(Clone, Copy, Debug, PartialEq, Eq)]
435pub struct Coeff {
436 /// The coefficient's row in the transform.
437 pub row: u8,
438 /// The coefficient's column in the transform.
439 pub col: u8,
440 /// Its quantised level, which the base and base-range syntax carry for
441 /// magnitudes up to [`MAX_LEVEL`].
442 pub level: i32,
443}
444
445/// The coefficients of one coded block: a 32x32 luma transform and, at 4:2:0,
446/// the 16x16 transform each chroma plane covers the same area with.
447#[derive(Clone, Debug, Default, PartialEq, Eq)]
448pub struct BlockCoeffs {
449 /// The luma transform's coefficients.
450 pub luma: Vec<Coeff>,
451 /// The U plane's.
452 pub u: Vec<Coeff>,
453 /// The V plane's.
454 pub v: Vec<Coeff>,
455 /// The luma intra mode the block is predicted with, one of the thirteen
456 /// modes a key frame codes (`DC_PRED` is zero, which is what
457 /// [`Default`] and a plain coefficient list give). Chroma stays on
458 /// `DC_PRED`.
459 pub mode: u8,
460 /// Whether the block carries no residual at all (spec `skip`). An intra
461 /// block may still be skipped; `false` (the [`Default`]) codes whatever
462 /// `luma`/`u`/`v` carry.
463 pub skip: bool,
464 /// The block's inter mode and motion vector, or `None` for an intra
465 /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key
466 /// frame writers never read this field.
467 pub inter: Option<InterInfo>,
468 /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect),
469 /// each with its own 8x8 luma transform and 4x4 chroma transforms, in
470 /// raster order among the leaves that are inside the true frame. `Some`
471 /// overrides this `BlockCoeffs`'s own `luma`/`u`/`v`/`mode`, which are left
472 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
473 /// per-quadrant fields are unused.
474 pub eight: Option<Vec<BlockCoeffs>>,
475}
476
477/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec
478/// 5.11.24 `read_inter_mode`), reduced to the two branches its symbol chain
479/// needs to prove out: the stack's own top candidate outright, or a coded
480/// residual against it. `NEARMV`/`GLOBALMV` are never written.
481#[derive(Clone, Copy, Debug, PartialEq, Eq)]
482pub enum InterMode {
483 /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
484 NearestMv,
485 /// `NEWMV`: codes `mv` as a residual against `MvStack::pred_mv`, through
486 /// a DRL index this writer always leaves at zero.
487 NewMv,
488}
489
490/// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
491/// `(row, col)` units. For [`InterMode::NearestMv`] this writer ignores `mv`
492/// and codes the stack's own candidate instead — the decoder derives it, so
493/// nothing here can disagree with it.
494#[derive(Clone, Copy, Debug, PartialEq, Eq)]
495pub struct InterInfo {
496 /// The mode this block is coded with.
497 pub mode: InterMode,
498 /// The motion vector a [`InterMode::NewMv`] block's residual targets.
499 pub mv: (i32, i32),
500}
501
502impl From<Vec<Coeff>> for BlockCoeffs {
503 /// A block that codes luma only.
504 fn from(luma: Vec<Coeff>) -> Self {
505 Self {
506 luma,
507 ..Self::default()
508 }
509 }
510}
511
512/// Side of the luma transform the coefficient writer codes.
513const TX32: usize = 32;
514/// Side of the larger of the two blocks a superblock splits into, in samples.
515const BLOCK: usize = 32;
516/// Side of the chroma transform beside it at 4:2:0, and of the luma transform
517/// of a 16x16 block.
518const TX16: usize = 16;
519/// Side of the chroma transform of a 16x16 block at 4:2:0, and of the luma
520/// transform of an 8x8 leaf under a straddling 16x16 (lane-av1-rect).
521const TX8: usize = 8;
522/// Side of the chroma transform of an 8x8 leaf at 4:2:0 (lane-av1-rect).
523const TX4: usize = 4;
524/// Side of a superblock, in samples, which is the size a block outside the
525/// tile reads as.
526const SB: usize = 64;
527/// Side of the smallest block the writer codes, in samples, which is the grid
528/// the neighbour bookkeeping is kept on.
529const SUB: usize = 16;
530/// Side of a 4x4 mode-info unit, in samples: the granularity libaom's above
531/// and left entropy-context arrays are actually kept on (spec
532/// `get_txb_ctx`/`av1_set_entropy_contexts`), finer than [`SUB`].
533const MI: usize = 4;
534
535/// What one coded block leaves behind for the blocks that read it as a
536/// neighbour: whether it coded anything at all, and the sign of its DC.
537#[derive(Clone, Copy, Default)]
538struct Neighbour {
539 /// Whether the plane's transform block carried a coefficient.
540 coded: bool,
541 /// The sign of its DC, absent when the DC itself is zero.
542 dc: Option<bool>,
543}
544
545/// Rejects a frame with no mode-info grid at all.
546///
547/// `mi_cols`/`mi_rows` are the frame's *true* (unpadded) size in 4x4 units
548/// (spec `compute_image_size`), not necessarily a multiple of the 32x32 block
549/// grid: a block whose origin sits at or past this bound is not coded (spec's
550/// `decode_partition` never visits it), and one that straddles the bound is
551/// coded whole, its samples coming from the padded planes.
552fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
553 if mi_cols == 0 || mi_rows == 0 {
554 return Err(Error::unsupported(
555 "AV1 tile",
556 "a coefficient key frame needs a nonzero mode-info grid",
557 ));
558 }
559 Ok(())
560}
561
562/// The coefficients of one superblock: either one 64x64 block covering it, or
563/// the four 32x32 blocks it is split into.
564///
565/// A superblock at the right-hand or bottom edge of the frame may be half
566/// outside it, and such a superblock cannot be left whole — the spec has no
567/// partition that keeps a block outside the frame — so it must be
568/// [`Split`](Superblock::Split), and carries only the quadrants that are
569/// inside, in raster order among themselves.
570#[derive(Clone, Debug, PartialEq, Eq)]
571pub enum Superblock {
572 /// One 64x64 block, whose luma transform is 64x64 — of which only the
573 /// top-left 32x32 carries coefficients — and whose chroma transforms are
574 /// 32x32 each at 4:2:0.
575 Whole(BlockCoeffs),
576 /// The 32x32 quadrants the superblock is split into, each either one
577 /// block or four 16x16 blocks of its own.
578 Split(Vec<Quadrant>),
579}
580
581/// One 32x32 quadrant of a split superblock.
582#[derive(Clone, Debug, PartialEq, Eq)]
583pub enum Quadrant {
584 /// One 32x32 block, with a 32x32 luma transform and a 16x16 transform per
585 /// chroma plane.
586 Whole(BlockCoeffs),
587 /// The four 16x16 blocks it is split into, in raster order, each with a
588 /// 16x16 luma transform and an 8x8 transform per chroma plane.
589 Split(Vec<BlockCoeffs>),
590}
591
592impl Quadrant {
593 /// The blocks it carries, in the order they are coded.
594 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {
595 match self {
596 Quadrant::Whole(block) => std::slice::from_ref(block),
597 Quadrant::Split(blocks) => blocks.as_slice(),
598 }
599 }
600}
601
602/// What the blocks above and to the left of the one being coded left behind,
603/// kept on the 16x16 grid the smallest block sits on.
604struct Neighbours {
605 /// Per plane, whether the neighbour coded anything and the sign of its DC.
606 above: Vec<[Neighbour; 3]>,
607 /// The same, down the left edge.
608 left: Vec<[Neighbour; 3]>,
609 /// The neighbour's luma intra mode, which picks the CDF the next block's
610 /// mode is coded with.
611 above_mode: Vec<usize>,
612 /// The same, down the left edge.
613 left_mode: Vec<usize>,
614 /// The side of the neighbour block, in samples, which is what the
615 /// partition symbol's context reads.
616 above_side: Vec<usize>,
617 /// The same, down the left edge.
618 left_side: Vec<usize>,
619 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
620 /// granularity [`Self::above`]/[`Self::left`] are, rather than [`SUB`]:
621 /// two 8x8 leaves of one straddling 16x16 block (lane-av1-rect) share a
622 /// single [`SUB`]-grid cell, so a coarse array cannot tell the second
623 /// leaf's partition symbol that the first one was coded at 8x8 (finer
624 /// than the 16x16 it sits in) -- exactly what its `above`/`left` context
625 /// needs to read (spec 9.3's `AbovePartitionContext`/`LeftPartitionContext`,
626 /// which libaom keeps per mi unit for this reason).
627 above_side_mi: Vec<usize>,
628 /// The same, down the left edge.
629 left_side_mi: Vec<usize>,
630 /// Whether the neighbour carried no residual, for [`sb_coeff_inter_frame_tile`]'s
631 /// skip context. Unused (and left at its default) by the key frame writers.
632 above_skip: Vec<bool>,
633 /// The same, down the left edge.
634 left_skip: Vec<bool>,
635 /// Whether the neighbour was coded inter, for the `is_inter` context.
636 /// Unused by the key frame writers.
637 above_inter: Vec<bool>,
638 /// The same, down the left edge.
639 left_inter: Vec<bool>,
640 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
641 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
642 /// `av1_set_entropy_contexts`): a block whose row or column run spills
643 /// past this bound leaves its trailing 4x4 units at their default,
644 /// mid-cell if need be.
645 mi_cols: usize,
646 mi_rows: usize,
647}
648
649/// What one plane's neighbours leave for a block, gathered across every cell
650/// the block spans -- which is what the decoder's own derivation reads
651/// (spec 5.11.39), and what a single cell only stands in for while every block
652/// is the same size.
653#[derive(Clone, Copy, Default)]
654struct Around {
655 /// Whether any transform block above this one carried a coefficient.
656 above_coded: bool,
657 /// The same, to the left.
658 left_coded: bool,
659 /// The running vote of the neighbours' DC signs: negative DCs count down,
660 /// positive ones up, and a neighbour with no DC does not count.
661 dc_vote: i32,
662}
663
664impl Neighbours {
665 /// The state a tile starts from: a block outside it reads as `DC_PRED`,
666 /// as having coded nothing, and as unsplit. `cols`/`rows` are in [`SUB`]
667 /// units; `mi_cols`/`mi_rows` are the frame's true (unpadded) size in 4x4
668 /// mode-info units.
669 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
670 Self {
671 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
672 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
673 above_mode: vec![DC_PRED; cols],
674 left_mode: vec![DC_PRED; rows],
675 above_side: vec![SB; cols],
676 left_side: vec![SB; rows],
677 above_side_mi: vec![SB; cols * (SUB / MI)],
678 left_side_mi: vec![SB; rows * (SUB / MI)],
679 above_skip: vec![false; cols],
680 left_skip: vec![false; rows],
681 above_inter: vec![false; cols],
682 left_inter: vec![false; rows],
683 mi_cols,
684 mi_rows,
685 }
686 }
687
688 /// Clears the left edge, which a tile starts every superblock row with.
689 fn start_row(&mut self) {
690 self.left.iter_mut().for_each(|l| *l = Default::default());
691 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
692 self.left_side.iter_mut().for_each(|s| *s = SB);
693 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
694 self.left_skip.iter_mut().for_each(|s| *s = false);
695 self.left_inter.iter_mut().for_each(|i| *i = false);
696 }
697
698 /// Writes one coded block into every 16x16 column and row it covers, and,
699 /// on the finer 4x4 grid libaom's entropy context arrays are actually
700 /// kept on, into every unit up to the true frame edge -- the units past
701 /// it are left at their default (uncoded), even mid-16x16-cell (spec
702 /// `av1_set_entropy_contexts`, which clamps to `blocks_wide`/`blocks_high`
703 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own
704 /// side).
705 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
706 let (r, c) = at;
707 for cell in 0..side / SUB {
708 self.above_mode[c + cell] = mode;
709 self.left_mode[r + cell] = mode;
710 self.above_side[c + cell] = side;
711 self.left_side[r + cell] = side;
712 }
713 self.record_mi((r * (SUB / MI), c * (SUB / MI)), side, grids);
714 }
715
716 /// The coefficient-context half of [`Self::record`], taking the block's
717 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
718 /// (r, c): an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at a
719 /// mi offset [`Self::record`]'s SUB-unit `at` cannot name, but the
720 /// `above`/`left` arrays it writes into are already sized to the full mi
721 /// grid, so no resizing is needed to write into them at this
722 /// finer-than-SUB granularity.
723 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
724 let (mi_r, mi_c) = at_mi;
725 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
726 let side_mi = side / MI;
727 for cell in 0..side_mi {
728 self.left_side_mi[mi_r + cell] = side;
729 self.above_side_mi[mi_c + cell] = side;
730 }
731 // libaom rounds the luma edge up to the plane's own 4x4 unit before
732 // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high,
733 // subsampling_y)` in av1_write_intra_coeffs_mb, encodetxb.c:456-459):
734 // a chroma 4x4 unit straddling the true luma edge is still whole in
735 // chroma's own halved grid, so it stays valid one luma-mi row/col
736 // past where luma's own edge falls when that edge is odd.
737 let round_up_even = |n: usize| n.div_ceil(2) * 2;
738 let bound_h = [
739 self.mi_rows,
740 round_up_even(self.mi_rows),
741 round_up_even(self.mi_rows),
742 ];
743 let bound_w = [
744 self.mi_cols,
745 round_up_even(self.mi_cols),
746 round_up_even(self.mi_cols),
747 ];
748 for cell in 0..side_mi {
749 self.left[mi_r + cell] = std::array::from_fn(|plane| {
750 if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {
751 states[plane]
752 } else {
753 Default::default()
754 }
755 });
756 self.above[mi_c + cell] = std::array::from_fn(|plane| {
757 if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) {
758 states[plane]
759 } else {
760 Default::default()
761 }
762 });
763 }
764 }
765
766 /// Writes one inter-frame block's skip flag and inter/intra state into
767 /// every 16x16 column and row it covers, the same span [`Self::record`]
768 /// fills for the coefficient and mode state.
769 fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool) {
770 let (r, c) = at;
771 for cell in 0..side / SUB {
772 self.above_skip[c + cell] = skip;
773 self.left_skip[r + cell] = skip;
774 self.above_inter[c + cell] = is_inter;
775 self.left_inter[r + cell] = is_inter;
776 }
777 }
778
779 /// The context of a block's partition symbol (spec 9.3): whether the
780 /// blocks above it and to its left were split finer than it is.
781 /// The gathered state of the blocks above and to the left of one block,
782 /// per plane.
783 fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] {
784 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
785 }
786
787 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
788 /// units, for the same reason [`Self::record_mi`] does.
789 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [Around; 3] {
790 let side_mi = side / MI;
791 std::array::from_fn(|plane| {
792 let mut around = Around::default();
793 for cell in 0..side_mi {
794 let (above, left) = (
795 &self.above[mi_c + cell][plane],
796 &self.left[mi_r + cell][plane],
797 );
798 around.above_coded |= above.coded;
799 around.left_coded |= left.coded;
800 around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc);
801 }
802 around
803 })
804 }
805
806 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
807 // Delegates to the mi-precise reader (same pattern as `around` /
808 // `around_mi`): `above_side`/`left_side` are only ever advanced in
809 // whole-[`SUB`] steps by [`Self::record`], so a leaf8's `record_mi`
810 // (lane-av1-rect) -- which only touches the finer mi arrays -- leaves
811 // them stale for the *next* sibling's own partition symbol, reading a
812 // 16x16-slot side that already split into 8x8s underneath it.
813 let (r, c) = at;
814 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
815 }
816
817 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
818 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
819 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
820 /// than the enclosing 16x16 slot's stale, shared state.
821 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
822 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
823 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
824 }
825}
826
827/// Writes the payload of a one-tile key frame built from `superblocks`, each
828/// either one 64x64 block or the 32x32 blocks it splits into.
829///
830/// `superblocks` gives one entry per superblock in raster order across the
831/// frame. Every block is DC-predicted unless its [`BlockCoeffs::mode`] says
832/// otherwise, and carries the coefficients its lists give; the coefficients
833/// may sit anywhere in their transform, so a block is a picture rather than a
834/// flat grey.
835///
836/// # Errors
837/// Returns an error when the frame is not a whole number of 32x32 blocks, when
838/// `superblocks` does not carry exactly one entry per superblock or an entry
839/// does not carry one block per quadrant inside the frame, when a superblock
840/// that is half outside the frame is left whole, when a block names an intra
841/// mode a key frame does not code, when a coefficient sits outside its
842/// transform, repeats a position, carries a zero level or one wider than the
843/// Golomb tail reaches.
844pub fn sb_coeff_key_frame_tile(
845 mi_cols: u32,
846 mi_rows: u32,
847 base_q_idx: u8,
848 superblocks: &[Superblock],
849) -> Result<Vec<u8>> {
850 check_blocks(mi_cols, mi_rows)?;
851 let (cols, rows) = block_grid(mi_cols, mi_rows);
852 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
853 if superblocks.len() != (sb_cols * sb_rows) as usize {
854 return Err(Error::unsupported(
855 "AV1 tile",
856 "a coefficient key frame needs one entry per superblock",
857 ));
858 }
859 let mut coded: Vec<&BlockCoeffs> = Vec::new();
860 for superblock in superblocks {
861 match superblock {
862 Superblock::Whole(block) => coded.push(block),
863 Superblock::Split(quadrants) => {
864 for block in quadrants.iter().flat_map(Quadrant::blocks) {
865 match &block.eight {
866 Some(leaves) => coded.extend(leaves.iter()),
867 None => coded.push(block),
868 }
869 }
870 }
871 }
872 }
873 if let Some(bad) = coded
874 .into_iter()
875 .find(|b| usize::from(b.mode) >= INTRA_MODES)
876 {
877 return Err(Error::unsupported(
878 "AV1 tile",
879 format!(
880 "intra mode {} is not one of the thirteen a key frame codes",
881 bad.mode
882 ),
883 ));
884 }
885
886 let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8];
887 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
888 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
889 let scans = [
890 default_scan(TX32),
891 default_scan(TX16),
892 default_scan(TX8),
893 default_scan(TX4),
894 ];
895 // The blocks above and to the left, on the 16x16 grid. The left edge is
896 // reset at every superblock row because a tile starts each row with no
897 // left neighbour.
898 let mut neighbours = Neighbours::new(
899 cols as usize * 2,
900 rows as usize * 2,
901 mi_cols as usize,
902 mi_rows as usize,
903 );
904
905 // The tile adapts every non-literal CDF it writes, exactly as the decoder
906 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
907 // off.
908 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
909 let mut enc = SymbolEncoder::new();
910 for sb_r in 0..sb_rows {
911 neighbours.start_row();
912 for sb_c in 0..sb_cols {
913 let at = (sb_r as usize * 4, sb_c as usize * 4);
914 let ctx = neighbours.partition_ctx(at, SB);
915 ec_rng_trace(|| {
916 format!(
917 "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={}",
918 at.0 * 4,
919 at.1 * 4,
920 ctx,
921 enc.tell()
922 )
923 });
924 // A superblock whose bottom or right half is outside the frame
925 // cannot be left unsplit, so the decoder reads a flag instead of
926 // the partition symbol — and reads nothing at all when both halves
927 // are outside, where the split is the only partition left.
928 let (has_cols, has_rows) = (
929 sb_c * SB_MI + SB_MI / 2 < mi_cols,
930 sb_r * SB_MI + SB_MI / 2 < mi_rows,
931 );
932 // The quadrants of this superblock that are inside the frame, as
933 // positions in the 32x32 block grid.
934 let quadrant_positions: Vec<(usize, usize)> = (0..4)
935 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
936 .filter(|&(r, c)| r < rows && c < cols)
937 .map(|(r, c)| (r as usize, c as usize))
938 .collect();
939
940 match &superblocks[(sb_r * sb_cols + sb_c) as usize] {
941 Superblock::Whole(block) => {
942 if !has_cols || !has_rows {
943 return Err(Error::unsupported(
944 "AV1 tile",
945 "a superblock that is half outside the frame cannot be left whole",
946 ));
947 }
948 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
949 let grids = [
950 level_grid(&block.luma, TX32)?,
951 level_grid(&block.u, TX32)?,
952 level_grid(&block.v, TX32)?,
953 ];
954 write_block(
955 &mut enc,
956 &mut cdfs,
957 &mut neighbours,
958 block,
959 at,
960 SB,
961 &whole_planes,
962 &grids,
963 [&scans[0], &scans[0], &scans[0]],
964 // A 64x64 block is too big to be offered chroma from
965 // luma, so its chroma mode reads the table without it.
966 false,
967 );
968 ec_rng_trace(|| {
969 format!(
970 "EC_TOK mi_row={} mi_col={} tell={}",
971 at.0 * 4,
972 at.1 * 4,
973 enc.tell()
974 )
975 });
976 }
977 Superblock::Split(quadrants) => {
978 match (has_cols, has_rows) {
979 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
980 // The gathered CDF an edge superblock reads is built
981 // for the read and thrown away: the decoder never
982 // stores it back, so nothing adapts here.
983 (true, false) => {
984 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
985 }
986 (false, true) => {
987 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
988 }
989 (false, false) => {}
990 }
991 if quadrants.len() != quadrant_positions.len() {
992 return Err(Error::unsupported(
993 "AV1 tile",
994 "a split superblock needs one block per quadrant inside the frame",
995 ));
996 }
997 for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) {
998 let at = (r * 2, c * 2);
999 let ctx = neighbours.partition_ctx(at, BLOCK);
1000 // Recomputed at this 32x32 block's own half (spec
1001 // `decode_partition`, called again at every size, not
1002 // just once for the superblock): the true frame edge
1003 // can fall inside this quadrant even when the
1004 // superblock it sits in was itself whole or safely
1005 // split above.
1006 let (has_cols32, has_rows32) = (
1007 has_half(c as u32 * BLOCK_MI, BLOCK_MI, mi_cols),
1008 has_half(r as u32 * BLOCK_MI, BLOCK_MI, mi_rows),
1009 );
1010 ec_rng_trace(|| {
1011 format!(
1012 "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={}",
1013 at.0 * 4,
1014 at.1 * 4,
1015 ctx,
1016 enc.tell()
1017 )
1018 });
1019 match quadrant {
1020 Quadrant::Whole(block) => {
1021 if !has_cols32 || !has_rows32 {
1022 return Err(Error::unsupported(
1023 "AV1 tile",
1024 "a 32x32 block that is half outside the true frame \
1025 cannot be left whole",
1026 ));
1027 }
1028 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]);
1029 let grids = [
1030 level_grid(&block.luma, TX32)?,
1031 level_grid(&block.u, TX16)?,
1032 level_grid(&block.v, TX16)?,
1033 ];
1034 write_block(
1035 &mut enc,
1036 &mut cdfs,
1037 &mut neighbours,
1038 block,
1039 at,
1040 BLOCK,
1041 &split_planes,
1042 &grids,
1043 [&scans[0], &scans[1], &scans[1]],
1044 true,
1045 );
1046 ec_rng_trace(|| {
1047 format!(
1048 "EC_TOK mi_row={} mi_col={} tell={}",
1049 at.0 * 4,
1050 at.1 * 4,
1051 enc.tell()
1052 )
1053 });
1054 }
1055 Quadrant::Split(blocks) => {
1056 // The 16x16 sub-blocks this quadrant's split
1057 // carries: only those whose own mi origin is
1058 // inside the true frame (spec `decode_partition`'s
1059 // `r >= MiRows || c >= MiCols` early return),
1060 // which need not be all four when the true
1061 // edge falls inside this quadrant.
1062 let sub_positions: Vec<(usize, usize)> = (0..4)
1063 .map(|i| (r * 2 + i / 2, c * 2 + i % 2))
1064 .filter(|&(sr, sc)| {
1065 (sr as u32) * SUB_MI < mi_rows
1066 && (sc as u32) * SUB_MI < mi_cols
1067 })
1068 .collect();
1069 if blocks.len() != sub_positions.len() {
1070 return Err(Error::unsupported(
1071 "AV1 tile",
1072 "a split 32x32 block needs one 16x16 entry per \
1073 sub-block inside the true frame",
1074 ));
1075 }
1076 // Same three-way spec signaling as the
1077 // superblock level above, recomputed at this
1078 // block's own half: a full alphabet symbol
1079 // only when both halves are inside, a single
1080 // gathered bit when just one is, and nothing
1081 // at all (SPLIT is inferred) when neither is.
1082 match (has_cols32, has_rows32) {
1083 (true, true) => {
1084 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]);
1085 }
1086 (true, false) => {
1087 enc.symbol_fixed(
1088 1,
1089 &gather(&cdfs.partition_w32[ctx], VERT_ALIKE),
1090 );
1091 }
1092 (false, true) => {
1093 enc.symbol_fixed(
1094 1,
1095 &gather(&cdfs.partition_w32[ctx], HORZ_ALIKE),
1096 );
1097 }
1098 (false, false) => {}
1099 }
1100 for (block, (sr, sc)) in blocks.iter().zip(sub_positions) {
1101 // A 16x16 leaf's own hasRows/hasCols,
1102 // recomputed at this leaf's own half
1103 // (same three-way signaling as the 32x32
1104 // and 64x64 levels above).
1105 let (has_cols16, has_rows16) = (
1106 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
1107 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
1108 );
1109 let at = (sr, sc);
1110 let ctx = neighbours.partition_ctx(at, SUB);
1111 ec_rng_trace(|| {
1112 format!(
1113 "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={}",
1114 at.0 * 4,
1115 at.1 * 4,
1116 ctx,
1117 enc.tell()
1118 )
1119 });
1120 if has_cols16 && has_rows16 {
1121 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]);
1122 let grids = [
1123 level_grid(&block.luma, TX16)?,
1124 level_grid(&block.u, TX8)?,
1125 level_grid(&block.v, TX8)?,
1126 ];
1127 write_block(
1128 &mut enc,
1129 &mut cdfs,
1130 &mut neighbours,
1131 block,
1132 at,
1133 SUB,
1134 &sub_planes,
1135 &grids,
1136 [&scans[1], &scans[2], &scans[2]],
1137 true,
1138 );
1139 ec_rng_trace(|| {
1140 format!(
1141 "EC_TOK mi_row={} mi_col={} tell={}",
1142 at.0 * 4,
1143 at.1 * 4,
1144 enc.tell()
1145 )
1146 });
1147 continue;
1148 }
1149 // The true edge falls inside this 16x16
1150 // leaf itself (mod-32==8 target sizes):
1151 // one axis only, per r6's charter -- an
1152 // 8x8 leaf never itself straddles, so the
1153 // block splits cleanly along whichever
1154 // axis is short and only the in-frame
1155 // 8x8s are coded, each its own leaf.
1156 if !has_cols16 && !has_rows16 {
1157 return Err(Error::unsupported(
1158 "AV1 tile",
1159 "a 16x16 block whose true edge cuts through both \
1160 axes needs a rectangular transform this writer \
1161 does not code yet",
1162 ));
1163 }
1164 if has_cols16 {
1165 enc.symbol_fixed(
1166 1,
1167 &gather(&cdfs.partition_w16[ctx], VERT_ALIKE),
1168 );
1169 } else {
1170 enc.symbol_fixed(
1171 1,
1172 &gather(&cdfs.partition_w16[ctx], HORZ_ALIKE),
1173 );
1174 }
1175 let leaves = block.eight.as_ref().ok_or_else(|| {
1176 Error::unsupported(
1177 "AV1 tile",
1178 "a 16x16 block the true frame edge cuts through \
1179 needs its `eight` leaves populated",
1180 )
1181 })?;
1182 let (mi_row0, mi_col0) =
1183 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
1184 let leaf_positions: Vec<(u32, u32)> = (0..4)
1185 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
1186 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
1187 .collect();
1188 if leaves.len() != leaf_positions.len() {
1189 return Err(Error::unsupported(
1190 "AV1 tile",
1191 "a straddling 16x16 block needs one `eight` entry \
1192 per 8x8 leaf inside the true frame",
1193 ));
1194 }
1195 // r11: the enclosing 16x16 slot's
1196 // above_mode/left_mode arrays are too
1197 // coarse for a second leaf whose true
1198 // above (or left) neighbour is the FIRST
1199 // leaf -- track it here and hand it to
1200 // write_leaf8 as a context override.
1201 let mut prev_leaf: Option<((usize, usize), usize)> = None;
1202 for (leaf, (mr, mc)) in leaves.iter().zip(leaf_positions) {
1203 let leaf_mi = (mr as usize, mc as usize);
1204 // r8: read at mi granularity, not the
1205 // enclosing 16x16 slot -- the first
1206 // leaf's `record_mi` call below
1207 // updates `above_side_mi`/
1208 // `left_side_mi` at this leaf's own
1209 // mi position, which the second
1210 // leaf's ctx lookup then sees.
1211 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
1212 ec_rng_trace(|| {
1213 format!(
1214 "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={}",
1215 leaf_mi.0,
1216 leaf_mi.1,
1217 leaf_ctx,
1218 enc.tell()
1219 )
1220 });
1221 enc.symbol(
1222 PARTITION_NONE,
1223 &mut cdfs.partition_w8[leaf_ctx],
1224 );
1225 let grids = [
1226 level_grid(&leaf.luma, TX8)?,
1227 level_grid(&leaf.u, TX4)?,
1228 level_grid(&leaf.v, TX4)?,
1229 ];
1230 let leaf_mode = write_leaf8(
1231 &mut enc,
1232 &mut cdfs,
1233 &mut neighbours,
1234 leaf,
1235 at,
1236 leaf_mi,
1237 &grids,
1238 [&scans[2], &scans[3], &scans[3]],
1239 prev_leaf,
1240 );
1241 prev_leaf = Some((leaf_mi, leaf_mode));
1242 ec_rng_trace(|| {
1243 format!(
1244 "EC_TOK mi_row={} mi_col={} tell={}",
1245 leaf_mi.0,
1246 leaf_mi.1,
1247 enc.tell()
1248 )
1249 });
1250 }
1251 // `record()`'s `above_mode`/`left_mode`
1252 // write is a no-op at an 8x8 leaf's own
1253 // side (`side / SUB == 0`), so the next
1254 // 16x16 quadrant beyond this straddling
1255 // one would otherwise see whatever stale
1256 // mode sat here before it: force the
1257 // write once the whole quadrant's leaves
1258 // are done, from the last (bottom/right-
1259 // most) leaf -- lane-av1-rect r15: doing
1260 // this *inside* `write_leaf8`, once per
1261 // leaf, let the first leaf's write
1262 // clobber the true external neighbour a
1263 // second leaf of the *same* quadrant
1264 // still needed to read on its
1265 // non-adjacency axis.
1266 if let Some((_, mode)) = prev_leaf {
1267 neighbours.above_mode[at.1] = mode;
1268 neighbours.left_mode[at.0] = mode;
1269 }
1270 }
1271 }
1272 }
1273 }
1274 }
1275 }
1276 }
1277 }
1278 Ok(enc.finish())
1279}
1280
1281/// Writes everything a key frame's block carries before its coefficients: the
1282/// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
1283/// the angle a directional mode is steered by, and its chroma mode. Hands back
1284/// the luma mode, which is what the blocks beside it read.
1285fn write_intra_mode(
1286 enc: &mut SymbolEncoder,
1287 cdfs: &mut Cdfs,
1288 block: &BlockCoeffs,
1289 above_mode: usize,
1290 left_mode: usize,
1291 cfl: bool,
1292) -> usize {
1293 let mode = usize::from(block.mode);
1294 enc.symbol(0, &mut cdfs.skip[0]);
1295 enc.symbol(
1296 mode,
1297 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
1298 );
1299 ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng()));
1300 if (V_PRED..=D67_PRED).contains(&mode) {
1301 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
1302 }
1303 // A block small enough to be offered chroma from luma reads the wider
1304 // table even when it does not take the mode.
1305 if cfl {
1306 enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
1307 } else {
1308 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[mode]);
1309 }
1310 mode
1311}
1312
1313/// Writes one coded block: its mode, its three transform blocks, and what it
1314/// leaves behind for the blocks beside it. Its partition symbol is already
1315/// written, because only the caller knows what tree led here.
1316#[allow(clippy::too_many_arguments)]
1317fn write_block(
1318 enc: &mut SymbolEncoder,
1319 cdfs: &mut Cdfs,
1320 neighbours: &mut Neighbours,
1321 block: &BlockCoeffs,
1322 at: (usize, usize),
1323 side: usize,
1324 planes: &[TxbSet; 3],
1325 grids: &[Vec<i32>; 3],
1326 scans: [&Vec<u16>; 3],
1327 cfl: bool,
1328) {
1329 let (r, c) = at;
1330 let mode = write_intra_mode(
1331 enc,
1332 cdfs,
1333 block,
1334 neighbours.above_mode[c],
1335 neighbours.left_mode[r],
1336 cfl,
1337 );
1338 write_block_planes(
1339 enc,
1340 cdfs,
1341 planes,
1342 grids,
1343 &scans,
1344 &neighbours.around(at, side),
1345 mode,
1346 );
1347 neighbours.record(at, side, mode, grids);
1348}
1349
1350/// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
1351/// luma transform and 4x4 chroma transforms, coded exactly like
1352/// [`write_block`] but reading its intra-mode context from the *enclosing*
1353/// 16x16 slot -- `outer_at`, in [`SUB`]-grid units -- rather than from its own
1354/// finer position, since [`Neighbours`]'s `above_mode`/`left_mode` arrays stay
1355/// at [`SUB`] (16-sample) granularity. `leaf_mi` is this leaf's own position
1356/// in 4x4 mode-info units, which is what its coefficient context (finer than
1357/// [`SUB`]) is kept and read at.
1358#[allow(clippy::too_many_arguments)]
1359fn write_leaf8(
1360 enc: &mut SymbolEncoder,
1361 cdfs: &mut Cdfs,
1362 neighbours: &mut Neighbours,
1363 block: &BlockCoeffs,
1364 outer_at: (usize, usize),
1365 leaf_mi: (usize, usize),
1366 grids: &[Vec<i32>; 3],
1367 scans: [&Vec<u16>; 3],
1368 prev_leaf: Option<((usize, usize), usize)>,
1369) -> usize {
1370 let (r, c) = outer_at;
1371 let mut above_mode = neighbours.above_mode[c];
1372 let mut left_mode = neighbours.left_mode[r];
1373 // The previous leaf sits directly above (same column, two mi rows up)
1374 // or directly to the left (same row, two mi cols over) of this one --
1375 // in either case its just-written mode, not the enclosing 16x16 slot's
1376 // stale neighbour, is what a decoder reads as this leaf's context.
1377 if let Some(((pr, pc), pmode)) = prev_leaf {
1378 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
1379 above_mode = pmode;
1380 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
1381 left_mode = pmode;
1382 }
1383 }
1384 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
1385 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF -- like every
1386 // other `write_block` caller at 16x16 and up -- not the narrower
1387 // no-CFL one: r12 lane-av1-rect, this leaf's own `cfl: false` was the
1388 // true first divergence (a differently-sized alphabet under the same
1389 // DC_PRED decision desyncs the coder even though the decoded mode is
1390 // unchanged).
1391 let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true);
1392 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
1393 write_block_planes(
1394 enc,
1395 cdfs,
1396 &planes,
1397 grids,
1398 &scans,
1399 &neighbours.around_mi(leaf_mi, 8),
1400 mode,
1401 );
1402 neighbours.record_mi(leaf_mi, 8, grids);
1403 mode
1404}
1405
1406/// Writes the three transform blocks of one coded block, in the order a
1407/// decoder reads them.
1408#[allow(clippy::too_many_arguments)]
1409fn write_block_planes(
1410 enc: &mut SymbolEncoder,
1411 cdfs: &mut Cdfs,
1412 planes: &[TxbSet; 3],
1413 grids: &[Vec<i32>; 3],
1414 scans: &[&Vec<u16>; 3],
1415 around: &[Around; 3],
1416 mode: usize,
1417) {
1418 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
1419 // Luma's transform covers its whole block, which fixes the all-zero
1420 // flag's context at zero; a chroma transform reads whether its
1421 // neighbours coded anything, on top of the offset the chroma tables
1422 // start at.
1423 let skip_ctx = if plane == 0 {
1424 0
1425 } else {
1426 usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
1427 };
1428 write_coeffs(
1429 enc,
1430 &mut cdfs.txb(planes[plane], mode),
1431 grid,
1432 scan,
1433 skip_ctx,
1434 dc_sign_ctx(around[plane].dc_vote),
1435 Some(plane),
1436 );
1437 ec_rng_trace(|| {
1438 format!(
1439 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
1440 grid.iter().filter(|&&l| l != 0).count(),
1441 enc.tell()
1442 )
1443 });
1444 }
1445}
1446
1447/// What a coded transform block leaves behind for the blocks that read it as a
1448/// neighbour.
1449fn neighbour_state(grid: &[i32]) -> Neighbour {
1450 Neighbour {
1451 coded: grid.iter().any(|&l| l != 0),
1452 dc: (grid[0] != 0).then_some(grid[0] < 0),
1453 }
1454}
1455
1456/// Writes the payload of a one-tile key frame in which every superblock is
1457/// split into 32x32 blocks, each carrying the coefficients `blocks` gives it.
1458///
1459/// `blocks` gives one coefficient set per 32x32 block in raster order across
1460/// the frame. This is [`sb_coeff_key_frame_tile`] with every superblock split.
1461///
1462/// # Errors
1463/// As [`sb_coeff_key_frame_tile`], with `blocks` sized for the 32x32 grid.
1464pub fn split_coeff_key_frame_tile(
1465 mi_cols: u32,
1466 mi_rows: u32,
1467 base_q_idx: u8,
1468 blocks: &[BlockCoeffs],
1469) -> Result<Vec<u8>> {
1470 check_blocks(mi_cols, mi_rows)?;
1471 let (cols, rows) = block_grid(mi_cols, mi_rows);
1472 if blocks.len() != (cols * rows) as usize {
1473 return Err(Error::unsupported(
1474 "AV1 tile",
1475 "a coefficient key frame needs one coefficient set per 32x32 block",
1476 ));
1477 }
1478 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
1479 let superblocks: Vec<Superblock> = (0..sb_rows)
1480 .flat_map(|sb_r| (0..sb_cols).map(move |sb_c| (sb_r, sb_c)))
1481 .map(|(sb_r, sb_c)| {
1482 Superblock::Split(
1483 (0..4)
1484 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
1485 .filter(|&(r, c)| r < rows && c < cols)
1486 .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone()))
1487 .collect(),
1488 )
1489 })
1490 .collect();
1491 sb_coeff_key_frame_tile(mi_cols, mi_rows, base_q_idx, &superblocks)
1492}
1493
1494/// Lays one plane's coefficient list out over its transform, rejecting the
1495/// positions and levels the writer does not code.
1496fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
1497 let mut grid = vec![0i32; side * side];
1498 for coeff in coeffs {
1499 if usize::from(coeff.row) >= side || usize::from(coeff.col) >= side {
1500 return Err(Error::unsupported(
1501 "AV1 tile",
1502 "a coefficient sits outside the transform of its plane",
1503 ));
1504 }
1505 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
1506 return Err(Error::unsupported(
1507 "AV1 tile",
1508 format!(
1509 "coefficients are written for levels -{MAX_LEVEL}..={MAX_LEVEL} without zero"
1510 ),
1511 ));
1512 }
1513 let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
1514 if grid[pos] != 0 {
1515 return Err(Error::unsupported(
1516 "AV1 tile",
1517 "two coefficients of one block share a position",
1518 ));
1519 }
1520 grid[pos] = coeff.level;
1521 }
1522 Ok(grid)
1523}
1524
1525/// The default scan of a square transform (spec 8.4.2's `Default_Scan_NxN`),
1526/// as raster positions in the order they are coded.
1527///
1528/// The table is a rule rather than hundreds of pinned numbers: the scan walks
1529/// the anti-diagonals of the transform outwards from the origin, each diagonal
1530/// from its top-right end on odd diagonals and from its bottom-left end on
1531/// even ones.
1532fn default_scan(side: usize) -> Vec<u16> {
1533 let mut scan = Vec::with_capacity(side * side);
1534 for d in 0..(2 * side - 1) {
1535 let lo = d.saturating_sub(side - 1);
1536 let hi = d.min(side - 1);
1537 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
1538 if d % 2 == 0 {
1539 scan.extend(diagonal.rev());
1540 } else {
1541 scan.extend(diagonal);
1542 }
1543 }
1544 scan
1545}
1546
1547/// What one 32x32 luma transform block's levels cost, in bits, priced through
1548/// the very CDFs [`write_coeffs`] will write them with -- end-of-block
1549/// position, base levels, base range, signs and the Golomb tail all included.
1550///
1551/// The mode search calls this before the block's neighbours exist, so the two
1552/// neighbour-derived contexts (the block-skip context and the DC sign context)
1553/// are taken as zero. Every other context inside the block is exact, because
1554/// those are read from the block's own levels.
1555///
1556/// The encoder codes 32x32 luma only -- every superblock it emits is split --
1557/// so one table is all the search needs; a second block size would need its
1558/// own entry point rather than a size argument, because the table and the scan
1559/// have to agree.
1560#[cfg(test)]
1561pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
1562 coeff_bits(grid, TxbSet::Luma32)
1563}
1564
1565/// What one transform block's levels cost through the CDFs of `set`, in bits.
1566///
1567/// The search runs before the tile is written, so the adapted state the block
1568/// will really be coded against does not exist yet: the price is taken against
1569/// the defaults every tile starts from, and against the contexts a block whose
1570/// neighbours coded nothing reads.
1571pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet) -> f64 {
1572 /// Built once per size: the search prices thirteen modes for every block,
1573 /// and the scan is the same table every time.
1574 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {
1575 [
1576 default_scan(TX4),
1577 default_scan(TX8),
1578 default_scan(TX16),
1579 default_scan(TX32),
1580 ]
1581 });
1582 let mut cdfs = Cdfs::new(2);
1583 let mut coding = cdfs.txb(set, DC_PRED);
1584 let scan = match coding.side {
1585 TX4 => &SCANS[0],
1586 TX8 => &SCANS[1],
1587 TX16 => &SCANS[2],
1588 _ => &SCANS[3],
1589 };
1590 let mut enc = SymbolEncoder::new();
1591 enc.reset_bits();
1592 write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);
1593 enc.bits()
1594}
1595
1596/// What the partition symbol of a block of `side` samples costs, in bits, when
1597/// it says the block is split (or that it is not).
1598///
1599/// The price is taken at context zero — a block whose neighbours are no finer
1600/// than it is — because the search that reads it runs before the tile knows
1601/// what its neighbours will be.
1602pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
1603 let cdfs = Cdfs::new(2);
1604 let cdf: &[u16] = match side {
1605 SB => &cdfs.partition_w64[0],
1606 BLOCK => &cdfs.partition_w32[0],
1607 _ => &cdfs.partition_w16[0],
1608 };
1609 let symbol = if split {
1610 PARTITION_SPLIT
1611 } else {
1612 PARTITION_NONE
1613 };
1614 crate::encode::symbol_bits(cdf, symbol)
1615}
1616
1617/// coeffs() for one plane's transform block of any coefficients the base and
1618/// base-range syntax reach (spec 5.11.39).
1619///
1620/// A 16x16 luma transform codes which transform type it is, because its set
1621/// holds more than one; 32x32 and 64x64 are DCT-only by spec 5.11.40. The
1622/// levels the contexts below are read from are the levels of
1623/// coefficients later in the scan, which a decoder walking the scan backwards
1624/// already has.
1625#[allow(clippy::too_many_arguments)]
1626fn write_coeffs(
1627 enc: &mut SymbolEncoder,
1628 coding: &mut TxbTables,
1629 grid: &[i32],
1630 scan: &[u16],
1631 skip_ctx: usize,
1632 sign_ctx: usize,
1633 plane: Option<usize>,
1634) {
1635 if let Some(plane) = plane {
1636 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));
1637 }
1638 let side = coding.side;
1639 let eob = scan
1640 .iter()
1641 .rposition(|&pos| grid[pos as usize] != 0)
1642 .map_or(0, |i| i + 1);
1643 enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]);
1644 if plane.is_some() {
1645 ec_rng_trace(|| {
1646 format!(
1647 "EC_TXBSKIP ctx={skip_ctx} eob0={} tell={} rng={}",
1648 usize::from(eob == 0),
1649 enc.tell(),
1650 enc.rng()
1651 )
1652 });
1653 }
1654 if eob == 0 {
1655 return;
1656 }
1657 // A luma transform whose type set holds more than one type codes which it
1658 // is, right after the all-zero flag (spec 5.11.39). The writer only ever
1659 // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.
1660 if let Some(tx_type) = coding.tx_type.as_deref_mut() {
1661 enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type);
1662 if plane.is_some() {
1663 ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng()));
1664 }
1665 }
1666
1667 write_eob(enc, coding, eob, plane);
1668
1669 for scan_idx in (0..eob).rev() {
1670 let pos = scan[scan_idx] as usize;
1671 let (row, col) = (pos / side, pos % side);
1672 let level = grid[pos].abs();
1673 if scan_idx == eob - 1 {
1674 let ctx = eob_coeff_ctx(scan_idx, side * side);
1675 let sym = (level.min(NUM_BASE_LEVELS + 1) - 1) as usize;
1676 enc.symbol(sym, &mut coding.base_eob[ctx]);
1677 if plane.is_some() {
1678 ec_rng_trace(|| {
1679 format!(
1680 "EC_BASEEOB scan_idx={scan_idx} ctx={ctx} level={} tell={}",
1681 sym + 1,
1682 enc.tell()
1683 )
1684 });
1685 }
1686 } else {
1687 let ctx = base_ctx(grid, side, row, col);
1688 let sym = level.min(NUM_BASE_LEVELS + 1) as usize;
1689 enc.symbol(sym, &mut coding.base[ctx]);
1690 if plane.is_some() {
1691 ec_rng_trace(|| {
1692 format!(
1693 "EC_BASE scan_idx={scan_idx} ctx={ctx} level={sym} tell={}",
1694 enc.tell()
1695 )
1696 });
1697 }
1698 }
1699 if level > NUM_BASE_LEVELS {
1700 let ctx = br_ctx(grid, side, row, col);
1701 let mut remaining = level - (NUM_BASE_LEVELS + 1);
1702 let mut sent = 0;
1703 while sent < COEFF_BASE_RANGE {
1704 let k = remaining.min(BR_STEP);
1705 enc.symbol(k as usize, &mut coding.br[ctx]);
1706 if plane.is_some() {
1707 ec_rng_trace(|| {
1708 format!(
1709 "EC_BR scan_idx={scan_idx} ctx={ctx} k={k} tell={}",
1710 enc.tell()
1711 )
1712 });
1713 }
1714 if k < BR_STEP {
1715 break;
1716 }
1717 remaining -= k;
1718 sent += BR_STEP;
1719 }
1720 }
1721 }
1722
1723 // The signs come after the levels, in scan order, the DC's from a CDF and
1724 // the rest as raw bits (spec 5.11.39).
1725 for &pos in &scan[..eob] {
1726 let level = grid[pos as usize];
1727 if level == 0 {
1728 continue;
1729 }
1730 if pos == 0 {
1731 enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]);
1732 if plane.is_some() {
1733 ec_rng_trace(|| {
1734 format!(
1735 "EC_DCSIGN ctx={sign_ctx} neg={} tell={}",
1736 usize::from(level < 0),
1737 enc.tell()
1738 )
1739 });
1740 }
1741 } else {
1742 enc.literal(u32::from(level < 0), 1);
1743 }
1744 // A level the base and base-range syntax cannot reach carries the rest
1745 // of itself here, after its own sign (spec 5.11.39).
1746 if level.abs() > MAX_BR_LEVEL {
1747 write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32);
1748 if plane.is_some() {
1749 ec_rng_trace(|| format!("EC_GOLOMB tell={}", enc.tell()));
1750 }
1751 }
1752 }
1753 if let Some(plane) = plane {
1754 ec_rng_trace(|| format!("EC_PLANE plane={plane} eob={eob} tell_after={}", enc.tell()));
1755 }
1756}
1757
1758/// The end-of-block position (spec 5.11.39): which group of scan positions the
1759/// last coded coefficient falls in, then its offset inside that group — the
1760/// offset's top bit from a CDF and the rest as raw bits.
1761fn write_eob(enc: &mut SymbolEncoder, coding: &mut TxbTables, eob: usize, plane: Option<usize>) {
1762 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
1763 /// end-of-block positions covers, indexed by the group's own number.
1764 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
1765 /// `Eob_Offset_Bits` (spec 5.11.39): how wide each group's offset is.
1766 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1767
1768 let group = GROUP_START
1769 .iter()
1770 .rposition(|&start| start <= eob)
1771 .expect("the first group starts at zero");
1772 // The groups are numbered from one, and how many of them the transform
1773 // reaches is the size of its own end-of-block alphabet.
1774 enc.symbol(group - 1, coding.eob_pt);
1775 if let Some(plane) = plane {
1776 ec_rng_trace(|| {
1777 format!(
1778 "EC_EOBPT plane={plane} eob_pt={group} tell={} rng={}",
1779 enc.tell(),
1780 enc.rng()
1781 )
1782 });
1783 }
1784
1785 let bits = OFFSET_BITS[group];
1786 if bits > 0 {
1787 let offset = (eob - GROUP_START[group]) as u32;
1788 let top = (offset >> (bits - 1)) & 1;
1789 enc.symbol(top as usize, &mut coding.eob_extra[group - 3]);
1790 if let Some(plane) = plane {
1791 ec_rng_trace(|| {
1792 format!(
1793 "EC_EOBEXTRA plane={plane} eob_ctx={} top={top} tell={}",
1794 group - 3,
1795 enc.tell()
1796 )
1797 });
1798 }
1799 if bits > 1 {
1800 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
1801 if let Some(plane) = plane {
1802 ec_rng_trace(|| {
1803 format!(
1804 "EC_EOBBITS plane={plane} eob_extra={offset} tell={}",
1805 enc.tell()
1806 )
1807 });
1808 }
1809 }
1810 }
1811}
1812
1813/// Writes the remainder of a level the base and base-range syntax could not
1814/// reach (spec 5.11.40): the value plus one, as its bit length in unary
1815/// followed by the value's own bits, most significant first.
1816pub(crate) fn write_golomb(enc: &mut SymbolEncoder, value: u32) {
1817 let x = value + 1;
1818 let length = 32 - x.leading_zeros();
1819 for _ in 0..length - 1 {
1820 enc.literal(0, 1);
1821 }
1822 for i in (0..length).rev() {
1823 enc.literal((x >> i) & 1, 1);
1824 }
1825}
1826
1827/// The context of the level of the last coded coefficient (spec 8.3.2): how
1828/// far into the scan it sits, in quarters and eighths of the transform.
1829fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
1830 match scan_idx {
1831 0 => 0,
1832 i if i <= area / 8 => 1,
1833 i if i <= area / 4 => 2,
1834 _ => 3,
1835 }
1836}
1837
1838/// The context of a coefficient's level (spec 8.3.2): the magnitudes of the
1839/// five neighbours below and to the right of it — the ones a decoder walking
1840/// the scan backwards already has — plus a term for where in the transform it
1841/// sits. The DC reads context 0 whatever its neighbours carry.
1842fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
1843 if row == 0 && col == 0 {
1844 return 0;
1845 }
1846 let mag: i32 = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
1847 .iter()
1848 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
1849 .sum();
1850 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
1851 (((mag + 1) >> 1).min(4) as usize) + offset
1852}
1853
1854/// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes
1855/// of its three closest neighbours below and to the right, uncapped, and a
1856/// term separating the DC, the corner of the transform, and the rest.
1857fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
1858 let mag: i32 = [(1, 0), (0, 1), (1, 1)]
1859 .iter()
1860 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
1861 .sum();
1862 let mag = (((mag + 1) >> 1).min(6)) as usize;
1863 if row == 0 && col == 0 {
1864 mag
1865 } else if row < 2 && col < 2 {
1866 mag + 7
1867 } else {
1868 mag + 14
1869 }
1870}
1871
1872/// A level at a position that may fall off the transform, where the levels a
1873/// context reads are zero.
1874fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
1875 if row >= side || col >= side {
1876 0
1877 } else {
1878 grid[row * side + col]
1879 }
1880}
1881
1882/// Shared by both DC writers: one level per block, none of them zero.
1883fn check_levels(levels: &[i32], blocks: usize) -> Result<()> {
1884 if levels.len() != blocks {
1885 return Err(Error::unsupported(
1886 "AV1 tile",
1887 "a DC-only key frame needs one level per coded block",
1888 ));
1889 }
1890 if levels.iter().any(|&l| l == 0 || l.abs() > MAX_BR_LEVEL) {
1891 return Err(Error::unsupported(
1892 "AV1 tile",
1893 "a DC-only key frame is written for levels -14..=14 without zero; \
1894 wider levels need the Golomb tail",
1895 ));
1896 }
1897 Ok(())
1898}
1899
1900/// coeffs() for a luma transform block whose only coefficient is the DC (spec
1901/// 5.11.39). The block size is the transform size, so the all-zero flag's
1902/// context is 0; an end-of-block of one is token 0 of the position alphabet
1903/// with no extra bits; the transform sizes here are all DCT-only, so no
1904/// transform type is coded; and the DC's own neighbours are zero, so its
1905/// magnitude contexts are 0 throughout.
1906fn write_dc_coeffs(
1907 enc: &mut SymbolEncoder,
1908 dc_level: i32,
1909 sign_ctx: usize,
1910 q_ctx: usize,
1911 txb_skip: &[u16],
1912 base_eob: &[u16],
1913) {
1914 use crate::cdf_state::pick;
1915 let level = dc_level.abs();
1916 let eob_pt = pick(
1917 q_ctx,
1918 cdf::EOB_PT_1024_LUMA_Q0,
1919 cdf::EOB_PT_1024_LUMA_Q1,
1920 cdf::EOB_PT_1024_LUMA,
1921 cdf::EOB_PT_1024_LUMA_Q3,
1922 );
1923 let br = pick(
1924 q_ctx,
1925 cdf::COEFF_BR_LUMA_32_Q0,
1926 cdf::COEFF_BR_LUMA_32_Q1,
1927 cdf::COEFF_BR_LUMA_32,
1928 cdf::COEFF_BR_LUMA_32_Q3,
1929 );
1930 enc.symbol_fixed(0, txb_skip);
1931 enc.symbol_fixed(0, &eob_pt);
1932 enc.symbol_fixed((level.min(NUM_BASE_LEVELS + 1) - 1) as usize, base_eob);
1933 if level > NUM_BASE_LEVELS {
1934 let mut remaining = level - (NUM_BASE_LEVELS + 1);
1935 let mut sent = 0;
1936 while sent < COEFF_BASE_RANGE {
1937 let k = remaining.min(BR_STEP);
1938 enc.symbol_fixed(k as usize, &br[0]);
1939 if k < BR_STEP {
1940 break;
1941 }
1942 remaining -= k;
1943 sent += BR_STEP;
1944 }
1945 }
1946 // The signs come after the levels, DC first (spec 5.11.39).
1947 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
1948}
1949
1950/// One 4x4 unit's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for a
1951/// positive DC, minus one for a negative one, nothing for a unit whose block
1952/// carried no DC or that sits past the frame's true edge (spec
1953/// `av1_set_entropy_contexts`), which is why the vote is gathered per 4x4
1954/// unit and not per coded cell -- a unit past the edge does not vote even
1955/// when the rest of its cell does.
1956fn dc_vote(dc: Option<bool>) -> i32 {
1957 match dc {
1958 None => 0,
1959 Some(true) => -1,
1960 Some(false) => 1,
1961 }
1962}
1963
1964/// Which of the three DC sign contexts a gathered vote picks.
1965fn dc_sign_ctx(vote: i32) -> usize {
1966 match vote.signum() {
1967 0 => 0,
1968 -1 => 1,
1969 _ => 2,
1970 }
1971}
1972
1973/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`,
1974/// `pred_common.c`): both neighbours' intra/inter state when both are
1975/// available, one neighbour's when only one is, and zero at a tile's own
1976/// top-left corner.
1977fn intra_inter_ctx(has_above: bool, has_left: bool, above_inter: bool, left_inter: bool) -> usize {
1978 match (has_above, has_left) {
1979 (true, true) => {
1980 let (above_intra, left_intra) = (!above_inter, !left_inter);
1981 if above_intra && left_intra {
1982 3
1983 } else {
1984 usize::from(above_intra || left_intra)
1985 }
1986 }
1987 (true, false) => 2 * usize::from(!above_inter),
1988 (false, true) => 2 * usize::from(!left_inter),
1989 (false, false) => 0,
1990 }
1991}
1992
1993/// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`
1994/// component's own bits start counting from; class zero starts at zero.
1995fn mv_class_base(class: usize) -> i32 {
1996 if class == 0 { 0 } else { 2i32 << (class + 2) }
1997}
1998
1999/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse
2000/// of `mv_class_base`'s doubling ranges, ported from libaom's
2001/// `av1_get_mv_class` (`mv.h`).
2002fn mv_class_of(z: i32) -> usize {
2003 let mut class = 0;
2004 while class < 10 && mv_class_base(class + 1) <= z {
2005 class += 1;
2006 }
2007 class
2008}
2009
2010/// Writes one motion vector component's non-zero diff (spec 5.11.32
2011/// `read_mv_component`, run backwards): sign, class, then the class's own
2012/// bits. `allow_high_precision_mv` is off in every frame this writer codes,
2013/// so the eighth-pel bit is always inferred as one rather than coded — which
2014/// means only diffs whose eighth-pel bit really is one are representable;
2015/// anything else is refused rather than rounded, since rounding would silently
2016/// code a different vector than the caller asked for.
2017///
2018/// # Errors
2019/// Returns an error when `diff` needs the eighth-pel precision this writer's
2020/// frames do not carry.
2021fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
2022 debug_assert_ne!(diff, 0);
2023 let sign = diff < 0;
2024 enc.symbol(usize::from(sign), &mut c.sign);
2025 let mag = diff.unsigned_abs() as i32;
2026 let z = mag - 1;
2027 if z & 1 == 0 {
2028 return Err(Error::unsupported(
2029 "AV1 tile",
2030 "a motion vector component needs eighth-pel precision, which \
2031 allow_high_precision_mv off does not carry",
2032 ));
2033 }
2034 let class = mv_class_of(z);
2035 enc.symbol(class, &mut c.class);
2036 let local = z - mv_class_base(class);
2037 if class == 0 {
2038 let bit = (local >> 3) & 1;
2039 let fr = (local >> 1) & 3;
2040 enc.symbol(bit as usize, &mut c.class0_bit);
2041 enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]);
2042 } else {
2043 let d = local >> 3;
2044 let fr = (local >> 1) & 3;
2045 for i in 0..class {
2046 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
2047 }
2048 enc.symbol(fr as usize, &mut c.fr);
2049 }
2050 // The eighth-pel bit itself is inferred, not coded (spec 5.11.32: "if
2051 // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
2052 Ok(())
2053}
2054
2055/// Writes a motion vector as a residual against `pred` (spec 5.11.32
2056/// `read_mv`): the joint symbol naming which components differ, then each
2057/// differing component.
2058fn write_mv(
2059 enc: &mut SymbolEncoder,
2060 mv_comp: &mut [MvComponentCdfs; 2],
2061 mv_joint: &mut [u16; 5],
2062 mv: (i32, i32),
2063 pred: (i32, i32),
2064) -> Result<()> {
2065 let diff = (mv.0 - pred.0, mv.1 - pred.1);
2066 let joint = match (diff.0 != 0, diff.1 != 0) {
2067 (false, false) => 0, // MV_JOINT_ZERO
2068 (false, true) => 1, // MV_JOINT_HNZVZ: column only
2069 (true, false) => 2, // MV_JOINT_HZVNZ: row only
2070 (true, true) => 3, // MV_JOINT_HNZVNZ
2071 };
2072 enc.symbol(joint, mv_joint);
2073 if diff.0 != 0 {
2074 write_mv_component(enc, &mut mv_comp[0], diff.0)?;
2075 }
2076 if diff.1 != 0 {
2077 write_mv_component(enc, &mut mv_comp[1], diff.1)?;
2078 }
2079 Ok(())
2080}
2081
2082/// Writes the payload of a one-tile inter frame built from `blocks`, one
2083/// 32x32 block per entry in raster order across the frame — every superblock
2084/// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
2085/// codes a key frame, because a mixed-size partition tree buys this writer's
2086/// gate nothing a flat grid does not already prove: the CDF state, the
2087/// neighbour contexts and the single-reference/MV-stack machinery below are
2088/// exactly as size-sensitive whether the tree recurses or not, and recursing
2089/// it would be undirected scaffolding — see `sb_coeff_key_frame_tile` for
2090/// where that tree already lives, ready to graft this block's mode reads
2091/// onto once a real partition search needs it.
2092///
2093/// A block whose [`BlockCoeffs::inter`] is `Some` is coded inter: `skip`,
2094/// then `is_inter`, then a single-reference chain that always names `LAST`
2095/// (spec 5.11.25 `single_ref_p1`/`p3`/`p4`, this crate's only reference so
2096/// far), then the two-mode `read_inter_mode` chain (spec 5.11.24) and, for
2097/// [`InterMode::NewMv`], a DRL index (always zero) and a coded motion vector
2098/// residual. A block whose `inter` is `None` codes intra, through the
2099/// *inter*-frame intra path (spec 5.11.16's `intra_frame_mode_info` is the
2100/// key frame writers' path; this is `inter_frame_mode_info`'s intra branch):
2101/// `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour context, since
2102/// an inter frame's intra blocks do not read their neighbours' modes.
2103///
2104/// # Errors
2105/// Returns an error when the frame is not a whole number of 64x64
2106/// superblocks, when `blocks` does not carry exactly one entry per 32x32
2107/// block, when an intra block names a mode a key frame does not code, when a
2108/// coefficient sits outside its transform or is one the writer cannot code,
2109/// when a `NEWMV` block's motion vector needs eighth-pel precision.
2110pub fn sb_coeff_inter_frame_tile(
2111 mi_cols: u32,
2112 mi_rows: u32,
2113 base_q_idx: u8,
2114 blocks: &[Quadrant],
2115) -> Result<Vec<u8>> {
2116 check_blocks(mi_cols, mi_rows)?;
2117 // `block_grid`'s ceiling, not a plain division: a true frame size that is
2118 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has
2119 // one more block/superblock whose own origin is inside the true frame,
2120 // same as `sb_coeff_key_frame_tile`.
2121 let (cols, rows) = block_grid(mi_cols, mi_rows);
2122 if blocks.len() != (cols * rows) as usize {
2123 return Err(Error::unsupported(
2124 "AV1 tile",
2125 "an inter frame needs one entry per 32x32 block inside the true frame",
2126 ));
2127 }
2128 let coded: Vec<&BlockCoeffs> = blocks.iter().flat_map(Quadrant::blocks).collect();
2129 if let Some(bad) = coded
2130 .into_iter()
2131 .find(|b| b.inter.is_none() && usize::from(b.mode) >= INTRA_MODES)
2132 {
2133 return Err(Error::unsupported(
2134 "AV1 tile",
2135 format!(
2136 "intra mode {} is not one of the thirteen this writer codes",
2137 bad.mode
2138 ),
2139 ));
2140 }
2141
2142 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only
2143 /// size this writer's inter branch codes.
2144 const SIZE_GROUP_32: usize = 3;
2145 /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this
2146 /// writer's single-reference chain ever names.
2147 const LAST_FRAME: i8 = 1;
2148
2149 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
2150 let mut neighbours = Neighbours::new(
2151 cols as usize * 2,
2152 rows as usize * 2,
2153 mi_cols as usize,
2154 mi_rows as usize,
2155 );
2156 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
2157 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
2158 let mut enc = SymbolEncoder::new();
2159 // An `is_inter` block's 32x32 luma transform reads a different
2160 // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see
2161 // `TxbSet::Luma32Inter`'s doc comment); chroma's transform type is
2162 // derived from luma's, not coded, so it never differs between the two.
2163 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
2164 let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16];
2165 let scan32 = default_scan(TX32);
2166 let scan16 = default_scan(TX16);
2167 let scan8 = default_scan(TX8);
2168 let scan4 = default_scan(TX4);
2169 let zero_grids = [
2170 vec![0i32; TX32 * TX32],
2171 vec![0i32; TX16 * TX16],
2172 vec![0i32; TX16 * TX16],
2173 ];
2174
2175 for sb_r in 0..sb_rows {
2176 neighbours.start_row();
2177 for sb_c in 0..sb_cols {
2178 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
2179 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
2180 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
2181 // whose bottom or right half falls outside the true frame cannot
2182 // be left whole, but this writer only ever splits a superblock
2183 // into its four 32x32 quadrants (never `PARTITION_NONE` at 64x64),
2184 // so the only question is which of the three partition symbols
2185 // that split takes — same three-way signaling as
2186 // `sb_coeff_key_frame_tile`'s superblock level.
2187 let (has_cols, has_rows) = (
2188 sb_c * SB_MI + SB_MI / 2 < mi_cols,
2189 sb_r * SB_MI + SB_MI / 2 < mi_rows,
2190 );
2191 match (has_cols, has_rows) {
2192 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]),
2193 (true, false) => {
2194 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
2195 }
2196 (false, true) => {
2197 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
2198 }
2199 (false, false) => {}
2200 }
2201
2202 for quadrant in 0..4 {
2203 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
2204 // Only a quadrant whose own mi origin is inside the true
2205 // frame is coded at all (spec `decode_partition`'s
2206 // `r >= MiRows || c >= MiCols` early return), same filter as
2207 // `sb_coeff_key_frame_tile`'s `quadrant_positions`.
2208 if r32 >= rows || c32 >= cols {
2209 continue;
2210 }
2211 let site = &blocks[(r32 * cols + c32) as usize];
2212 let at = (r32 as usize * 2, c32 as usize * 2);
2213 let ctx32 = neighbours.partition_ctx(at, BLOCK);
2214 // spec `decode_partition`'s hasRows/hasCols recomputed at this
2215 // quadrant's own half: a whole 32x32 block cannot be left
2216 // whole once its own half straddles the true edge, mirroring
2217 // `sb_coeff_key_frame_tile`'s "cannot be left whole" refusal.
2218 let (has_cols32, has_rows32) = (
2219 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
2220 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
2221 );
2222 let block = match site {
2223 Quadrant::Whole(block) => {
2224 if !has_cols32 || !has_rows32 {
2225 return Err(Error::unsupported(
2226 "AV1 tile",
2227 "a 32x32 block that is half outside the true frame \
2228 cannot be left whole",
2229 ));
2230 }
2231 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]);
2232 block
2233 }
2234 Quadrant::Split(sub_blocks) => {
2235 // Same filter as `sb_coeff_key_frame_tile`'s
2236 // `sub_positions`: only the 16x16 leaves whose own mi
2237 // origin is inside the true frame are coded.
2238 let sub_positions: Vec<(usize, usize)> = (0..4)
2239 .map(|i| (r32 as usize * 2 + i / 2, c32 as usize * 2 + i % 2))
2240 .filter(|&(sr, sc)| {
2241 (sr as u32) * SUB_MI < mi_rows && (sc as u32) * SUB_MI < mi_cols
2242 })
2243 .collect();
2244 if sub_blocks.len() != sub_positions.len() {
2245 return Err(Error::unsupported(
2246 "AV1 tile",
2247 "a split 32x32 inter-frame block needs one 16x16 entry \
2248 per sub-block inside the true frame",
2249 ));
2250 }
2251 // Same three-way spec signaling as the superblock
2252 // level above, recomputed at this quadrant's own half.
2253 match (has_cols32, has_rows32) {
2254 (true, true) => {
2255 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx32]);
2256 }
2257 (true, false) => {
2258 enc.symbol_fixed(
2259 1,
2260 &gather(&cdfs.partition_w32[ctx32], VERT_ALIKE),
2261 );
2262 }
2263 (false, true) => {
2264 enc.symbol_fixed(
2265 1,
2266 &gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE),
2267 );
2268 }
2269 (false, false) => {}
2270 }
2271 for (leaf, (sr, sc)) in sub_blocks.iter().zip(sub_positions) {
2272 // A 16x16 leaf whose own half straddles the true
2273 // frame edge on both axes needs a rectangular
2274 // transform this writer does not code yet; one
2275 // axis only is two (or, at a true corner, one)
2276 // 8x8 leaves (lane-av1inter8), same split the key
2277 // frame search takes at this geometry.
2278 let (has_cols16, has_rows16) = (
2279 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
2280 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
2281 );
2282 if !has_cols16 && !has_rows16 {
2283 return Err(Error::unsupported(
2284 "AV1 tile",
2285 "a 16x16 inter-frame block whose true edge cuts through \
2286 both axes needs a rectangular transform this writer \
2287 does not code yet",
2288 ));
2289 }
2290 let at16 = (sr, sc);
2291 if has_cols16 && has_rows16 {
2292 let ctx16 = neighbours.partition_ctx(at16, SUB);
2293 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]);
2294 write_inter_frame_leaf(
2295 &mut enc,
2296 &mut cdfs,
2297 &mut neighbours,
2298 &mut grid,
2299 mi_cols,
2300 mi_rows,
2301 leaf,
2302 at16,
2303 &scan16,
2304 &scan8,
2305 )?;
2306 } else {
2307 let ctx16 = neighbours.partition_ctx(at16, SUB);
2308 if has_cols16 {
2309 enc.symbol_fixed(
2310 1,
2311 &gather(&cdfs.partition_w16[ctx16], VERT_ALIKE),
2312 );
2313 } else {
2314 enc.symbol_fixed(
2315 1,
2316 &gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE),
2317 );
2318 }
2319 let leaves = leaf.eight.as_ref().ok_or_else(|| {
2320 Error::unsupported(
2321 "AV1 tile",
2322 "a 16x16 inter-frame block the true frame edge cuts \
2323 through needs its `eight` leaves populated",
2324 )
2325 })?;
2326 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
2327 let leaf_positions: Vec<(u32, u32)> = (0..4)
2328 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
2329 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
2330 .collect();
2331 if leaves.len() != leaf_positions.len() {
2332 return Err(Error::unsupported(
2333 "AV1 tile",
2334 "a straddling 16x16 inter-frame block needs one \
2335 `eight` entry per 8x8 leaf inside the true frame",
2336 ));
2337 }
2338 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
2339 for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) {
2340 let leaf_mi = (mr as usize, mc as usize);
2341 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
2342 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w8[leaf_ctx]);
2343 let (skip, is_inter) = write_inter_frame_leaf8(
2344 &mut enc,
2345 &mut cdfs,
2346 &mut neighbours,
2347 &mut grid,
2348 mi_cols,
2349 mi_rows,
2350 leaf8,
2351 at16,
2352 leaf_mi,
2353 &scan8,
2354 &scan4,
2355 prev_leaf,
2356 )?;
2357 prev_leaf = Some((leaf_mi, skip, is_inter));
2358 }
2359 // Same write-back-once-from-the-last-leaf rule
2360 // as the key frame search's `write_leaf8`
2361 // caller (r15): the SUB-grid skip/inter arrays
2362 // are otherwise left stale for the next
2363 // 16x16 slot.
2364 if let Some((_, skip, is_inter)) = prev_leaf {
2365 neighbours.record_inter(at16, SUB, skip, is_inter);
2366 }
2367 }
2368 }
2369 continue;
2370 }
2371 };
2372
2373 let (r, c) = at;
2374 let has_above = r32 > 0;
2375 let has_left = c32 > 0;
2376 let skip_ctx =
2377 usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
2378 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
2379
2380 let is_inter = block.inter.is_some();
2381 let (above_inter, left_inter) =
2382 (neighbours.above_inter[c], neighbours.left_inter[r]);
2383 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
2384 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
2385
2386 let mode_for_tx;
2387 if let Some(info) = block.inter {
2388 let sr_ctx = single_ref_ctx(above_inter || left_inter);
2389 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward
2390 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2
2391 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST
2392
2393 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
2394 let stack = find_mv_stack(
2395 &grid,
2396 mi_row,
2397 mi_col,
2398 8,
2399 8,
2400 LAST_FRAME,
2401 mi_cols as usize,
2402 mi_rows as usize,
2403 );
2404
2405 let is_new_mv = matches!(info.mode, InterMode::NewMv);
2406 if is_new_mv {
2407 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
2408 } else {
2409 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
2410 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
2411 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
2412 }
2413 // This writer always keeps the first DRL candidate, so the
2414 // loop (spec 5.11.24 `read_drl_idx`) only ever runs its
2415 // first, breaking iteration.
2416 if is_new_mv && stack.entries.len() > 1 {
2417 enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
2418 }
2419 let mv = if is_new_mv {
2420 write_mv(
2421 &mut enc,
2422 &mut cdfs.mv_comp,
2423 &mut cdfs.mv_joint,
2424 info.mv,
2425 stack.pred_mv,
2426 )?;
2427 info.mv
2428 } else {
2429 stack.nearest_mv
2430 };
2431 grid.set(
2432 mi_row,
2433 mi_col,
2434 MiInfo {
2435 is_inter: true,
2436 ref_frame: LAST_FRAME,
2437 ref_frame1: None,
2438 mv1: None,
2439 mv,
2440 is_new_mv,
2441 size: 8,
2442 size_h: 8,
2443 is_global_mv0: false,
2444 is_global_mv1: false,
2445 },
2446 );
2447 for dr in 0..8 {
2448 for dc in 0..8 {
2449 if dr == 0 && dc == 0 {
2450 continue;
2451 }
2452 grid.set(
2453 mi_row + dr,
2454 mi_col + dc,
2455 MiInfo {
2456 is_inter: true,
2457 ref_frame: LAST_FRAME,
2458 ref_frame1: None,
2459 mv1: None,
2460 mv,
2461 is_new_mv,
2462 size: 8,
2463 size_h: 8,
2464 is_global_mv0: false,
2465 is_global_mv1: false,
2466 },
2467 );
2468 }
2469 }
2470 mode_for_tx = 0;
2471 } else {
2472 let mode = usize::from(block.mode);
2473 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
2474 if (V_PRED..=D67_PRED).contains(&mode) {
2475 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
2476 }
2477 enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
2478 mode_for_tx = mode;
2479 // Intra: no vote, but still a coded cell -- mvstack's
2480 // extended-scan coverage must see it (module doc).
2481 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
2482 for dr in 0..8 {
2483 for dc in 0..8 {
2484 grid.set(
2485 mi_row + dr,
2486 mi_col + dc,
2487 MiInfo {
2488 is_inter: false,
2489 ref_frame: -1,
2490 ref_frame1: None,
2491 mv1: None,
2492 mv: (0, 0),
2493 is_new_mv: false,
2494 size: 8,
2495 size_h: 8,
2496 is_global_mv0: false,
2497 is_global_mv1: false,
2498 },
2499 );
2500 }
2501 }
2502 }
2503
2504 if block.skip {
2505 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
2506 } else {
2507 let grids = [
2508 level_grid(&block.luma, TX32)?,
2509 level_grid(&block.u, TX16)?,
2510 level_grid(&block.v, TX16)?,
2511 ];
2512 write_block_planes(
2513 &mut enc,
2514 &mut cdfs,
2515 if is_inter {
2516 &inter_planes
2517 } else {
2518 &intra_planes
2519 },
2520 &grids,
2521 &[&scan32, &scan16, &scan16],
2522 &neighbours.around(at, BLOCK),
2523 mode_for_tx,
2524 );
2525 neighbours.record(at, BLOCK, mode_for_tx, &grids);
2526 }
2527 neighbours.record_inter(at, BLOCK, block.skip, is_inter);
2528 }
2529 }
2530 }
2531 Ok(enc.finish())
2532}
2533
2534/// Writes one 16x16 leaf a straddling 32x32 quadrant's [`Quadrant::Split`]
2535/// splits into: intra (spec `inter_frame_mode_info`'s intra branch, the only
2536/// one this writer used to code here) or real inter (`is_inter` coded
2537/// `true`), `NEARESTMV` only -- `NEWMV` at this size is this function's
2538/// caller's to never build (`Quadrant::Split`'s `BlockCoeffs.inter`) -- same
2539/// `single_ref`/mv-stack/DRL symbol chain as the whole-32x32 branch above,
2540/// just at this leaf's own 4x4-mi window (`bw4`/`bh4` of 4, not 8) and coded
2541/// through [`TxbSet::Luma16Inter`] rather than [`TxbSet::Luma32Inter`]. Its
2542/// own `PARTITION_NONE` symbol is already written, same contract as
2543/// [`write_block`].
2544#[allow(clippy::too_many_arguments)]
2545fn write_inter_frame_leaf(
2546 enc: &mut SymbolEncoder,
2547 cdfs: &mut Cdfs,
2548 neighbours: &mut Neighbours,
2549 grid: &mut MiGrid,
2550 mi_cols: u32,
2551 mi_rows: u32,
2552 block: &BlockCoeffs,
2553 at: (usize, usize),
2554 scan16: &Vec<u16>,
2555 scan8: &Vec<u16>,
2556) -> Result<()> {
2557 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
2558 return Err(Error::unsupported(
2559 "AV1 tile",
2560 format!(
2561 "intra mode {} is not one of the thirteen this writer codes",
2562 block.mode
2563 ),
2564 ));
2565 }
2566 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
2567 /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size.
2568 const SIZE_GROUP_16: usize = 2;
2569 /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this
2570 /// writer's single-reference chain ever names, same as the 32x32 branch.
2571 const LAST_FRAME: i8 = 1;
2572
2573 let (r, c) = at;
2574 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
2575 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
2576
2577 let (has_above, has_left) = (r > 0, c > 0);
2578 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
2579 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
2580 let is_inter = block.inter.is_some();
2581 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
2582
2583 let mode_for_tx;
2584 if let Some(info) = block.inter {
2585 let sr_ctx = single_ref_ctx(above_inter || left_inter);
2586 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward
2587 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2
2588 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST
2589
2590 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
2591 let stack = find_mv_stack(
2592 grid,
2593 mi_row,
2594 mi_col,
2595 SUB_MI as usize,
2596 SUB_MI as usize,
2597 LAST_FRAME,
2598 mi_cols as usize,
2599 mi_rows as usize,
2600 );
2601
2602 let is_new_mv = matches!(info.mode, InterMode::NewMv);
2603 if is_new_mv {
2604 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
2605 } else {
2606 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
2607 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
2608 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
2609 }
2610 if is_new_mv && stack.entries.len() > 1 {
2611 enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
2612 }
2613 let mv = if is_new_mv {
2614 write_mv(
2615 enc,
2616 &mut cdfs.mv_comp,
2617 &mut cdfs.mv_joint,
2618 info.mv,
2619 stack.pred_mv,
2620 )?;
2621 info.mv
2622 } else {
2623 stack.nearest_mv
2624 };
2625 for dr in 0..SUB_MI as usize {
2626 for dc in 0..SUB_MI as usize {
2627 grid.set(
2628 mi_row + dr,
2629 mi_col + dc,
2630 MiInfo {
2631 is_inter: true,
2632 ref_frame: LAST_FRAME,
2633 ref_frame1: None,
2634 mv1: None,
2635 mv,
2636 is_new_mv,
2637 size: SUB_MI as usize,
2638 size_h: SUB_MI as usize,
2639 is_global_mv0: false,
2640 is_global_mv1: false,
2641 },
2642 );
2643 }
2644 }
2645 mode_for_tx = 0;
2646 } else {
2647 let mode = usize::from(block.mode);
2648 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);
2649 if (V_PRED..=D67_PRED).contains(&mode) {
2650 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
2651 }
2652 enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
2653 mode_for_tx = mode;
2654 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
2655 // coverage must see it (module doc).
2656 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
2657 for dr in 0..SUB_MI as usize {
2658 for dc in 0..SUB_MI as usize {
2659 grid.set(
2660 mi_row + dr,
2661 mi_col + dc,
2662 MiInfo {
2663 is_inter: false,
2664 ref_frame: -1,
2665 ref_frame1: None,
2666 mv1: None,
2667 mv: (0, 0),
2668 is_new_mv: false,
2669 size: SUB_MI as usize,
2670 size_h: SUB_MI as usize,
2671 is_global_mv0: false,
2672 is_global_mv1: false,
2673 },
2674 );
2675 }
2676 }
2677 }
2678
2679 if block.skip {
2680 let zero_grids = [
2681 vec![0i32; TX16 * TX16],
2682 vec![0i32; TX8 * TX8],
2683 vec![0i32; TX8 * TX8],
2684 ];
2685 neighbours.record(at, SUB, mode_for_tx, &zero_grids);
2686 } else {
2687 let grids = [
2688 level_grid(&block.luma, TX16)?,
2689 level_grid(&block.u, TX8)?,
2690 level_grid(&block.v, TX8)?,
2691 ];
2692 write_block_planes(
2693 enc,
2694 cdfs,
2695 if is_inter {
2696 &[TxbSet::Luma16Inter, TxbSet::Chroma8, TxbSet::Chroma8]
2697 } else {
2698 &[TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8]
2699 },
2700 &grids,
2701 &[scan16, scan8, scan8],
2702 &neighbours.around(at, SUB),
2703 mode_for_tx,
2704 );
2705 neighbours.record(at, SUB, mode_for_tx, &grids);
2706 }
2707 neighbours.record_inter(at, SUB, block.skip, is_inter);
2708 Ok(())
2709}
2710
2711/// Writes one 8x8 leaf of a straddling 16x16 inter-frame block
2712/// (lane-av1inter8): its own skip flag, intra/inter choice and (when inter)
2713/// `NEARESTMV`/`NEWMV` chain, or (when intra) `Y_MODE`, then its own luma and
2714/// two chroma transform blocks -- coded exactly like
2715/// [`write_inter_frame_leaf`] but through [`TxbSet::Luma8Inter`]/
2716/// [`TxbSet::Chroma4`] and at this leaf's own 2x2-mi mv-stack window, reading
2717/// its skip/intra-inter context from the *enclosing* 16x16 slot's
2718/// [`Neighbours`] arrays (`outer_at`, in [`SUB`]-grid units) unless
2719/// `prev_leaf` names this straddling block's own first leaf as the true
2720/// mi-adjacent neighbour -- the same override [`write_leaf8`] applies to its
2721/// mode context, needed for the same reason: `Neighbours`' above/left arrays
2722/// only resolve to [`SUB`] granularity, too coarse for the second leaf of a
2723/// straddling 16x16 to see the first. `Y_MODE`'s own context (`Size_Group`)
2724/// is not neighbour-dependent, unlike the key frame path's `kf_y_mode`, so no
2725/// override is needed there. Hands back this leaf's own skip flag and
2726/// intra/inter choice, which is what the next leaf (or the caller's final
2727/// write-back, mirroring `write_leaf8`'s caller) reads.
2728#[allow(clippy::too_many_arguments)]
2729fn write_inter_frame_leaf8(
2730 enc: &mut SymbolEncoder,
2731 cdfs: &mut Cdfs,
2732 neighbours: &mut Neighbours,
2733 grid: &mut MiGrid,
2734 mi_cols: u32,
2735 mi_rows: u32,
2736 block: &BlockCoeffs,
2737 outer_at: (usize, usize),
2738 leaf_mi: (usize, usize),
2739 scan8: &Vec<u16>,
2740 scan4: &Vec<u16>,
2741 prev_leaf: Option<((usize, usize), bool, bool)>,
2742) -> Result<(bool, bool)> {
2743 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
2744 return Err(Error::unsupported(
2745 "AV1 tile",
2746 format!(
2747 "intra mode {} is not one of the thirteen this writer codes",
2748 block.mode
2749 ),
2750 ));
2751 }
2752 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
2753 /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size.
2754 const SIZE_GROUP_8: usize = 1;
2755 /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3), same as the 16x16/32x32
2756 /// branches.
2757 const LAST_FRAME: i8 = 1;
2758
2759 let (r, c) = outer_at;
2760 let mut above_skip = neighbours.above_skip[c];
2761 let mut left_skip = neighbours.left_skip[r];
2762 let mut above_inter = neighbours.above_inter[c];
2763 let mut left_inter = neighbours.left_inter[r];
2764 if let Some(((pr, pc), pskip, pinter)) = prev_leaf {
2765 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
2766 above_skip = pskip;
2767 above_inter = pinter;
2768 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
2769 left_skip = pskip;
2770 left_inter = pinter;
2771 }
2772 }
2773 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
2774 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
2775
2776 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
2777 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
2778 let is_inter = block.inter.is_some();
2779 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
2780
2781 let mode_for_tx;
2782 if let Some(info) = block.inter {
2783 let sr_ctx = single_ref_ctx(above_inter || left_inter);
2784 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward
2785 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2
2786 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST
2787
2788 let (mi_row, mi_col) = leaf_mi;
2789 let stack = find_mv_stack(
2790 grid,
2791 mi_row,
2792 mi_col,
2793 2,
2794 2,
2795 LAST_FRAME,
2796 mi_cols as usize,
2797 mi_rows as usize,
2798 );
2799
2800 let is_new_mv = matches!(info.mode, InterMode::NewMv);
2801 if is_new_mv {
2802 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
2803 } else {
2804 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
2805 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
2806 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
2807 }
2808 if is_new_mv && stack.entries.len() > 1 {
2809 enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
2810 }
2811 let mv = if is_new_mv {
2812 write_mv(
2813 enc,
2814 &mut cdfs.mv_comp,
2815 &mut cdfs.mv_joint,
2816 info.mv,
2817 stack.pred_mv,
2818 )?;
2819 info.mv
2820 } else {
2821 stack.nearest_mv
2822 };
2823 for dr in 0..2 {
2824 for dc in 0..2 {
2825 grid.set(
2826 mi_row + dr,
2827 mi_col + dc,
2828 MiInfo {
2829 is_inter: true,
2830 ref_frame: LAST_FRAME,
2831 ref_frame1: None,
2832 mv1: None,
2833 mv,
2834 is_new_mv,
2835 size: 2,
2836 size_h: 2,
2837 is_global_mv0: false,
2838 is_global_mv1: false,
2839 },
2840 );
2841 }
2842 }
2843 mode_for_tx = 0;
2844 } else {
2845 let mode = usize::from(block.mode);
2846 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);
2847 if (V_PRED..=D67_PRED).contains(&mode) {
2848 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
2849 }
2850 enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
2851 mode_for_tx = mode;
2852 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
2853 // coverage must see it (module doc).
2854 let (mi_row, mi_col) = leaf_mi;
2855 for dr in 0..2 {
2856 for dc in 0..2 {
2857 grid.set(
2858 mi_row + dr,
2859 mi_col + dc,
2860 MiInfo {
2861 is_inter: false,
2862 ref_frame: -1,
2863 ref_frame1: None,
2864 mv1: None,
2865 mv: (0, 0),
2866 is_new_mv: false,
2867 size: 2,
2868 size_h: 2,
2869 is_global_mv0: false,
2870 is_global_mv1: false,
2871 },
2872 );
2873 }
2874 }
2875 }
2876
2877 let planes = if is_inter {
2878 [TxbSet::Luma8Inter, TxbSet::Chroma4, TxbSet::Chroma4]
2879 } else {
2880 [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]
2881 };
2882 if block.skip {
2883 let zero_grids = [
2884 vec![0i32; TX8 * TX8],
2885 vec![0i32; TX4 * TX4],
2886 vec![0i32; TX4 * TX4],
2887 ];
2888 neighbours.record_mi(leaf_mi, 8, &zero_grids);
2889 } else {
2890 let grids = [
2891 level_grid(&block.luma, TX8)?,
2892 level_grid(&block.u, TX4)?,
2893 level_grid(&block.v, TX4)?,
2894 ];
2895 write_block_planes(
2896 enc,
2897 cdfs,
2898 &planes,
2899 &grids,
2900 &[scan8, scan4, scan4],
2901 &neighbours.around_mi(leaf_mi, 8),
2902 mode_for_tx,
2903 );
2904 neighbours.record_mi(leaf_mi, 8, &grids);
2905 }
2906 Ok((block.skip, is_inter))
2907}
2908
2909#[cfg(test)]
2910mod tests {
2911 use super::*;
2912 use crate::frame::frame_obu;
2913 use crate::obu::temporal_delimiter;
2914 use crate::sequence::sequence_header_obu;
2915 use ec_av1_syntax::sequence::SequenceHeader;
2916 use ec_av1_syntax::{
2917 FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
2918 TxMode,
2919 };
2920 use std::io::Write;
2921 use std::process::{Command, Stdio};
2922
2923 /// A 64x64 sequence with every tool this writer does not code turned off:
2924 /// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter
2925 /// intra, and no screen content tools (which is what keeps intra block copy
2926 /// and palette out of the block syntax).
2927 fn sequence_64() -> SequenceHeader {
2928 let mut seq = crate::sequence::tests::sample_1080p();
2929 seq.frame_width_bits = 7;
2930 seq.frame_height_bits = 7;
2931 seq.max_frame_width = 64;
2932 seq.max_frame_height = 64;
2933 seq.use_128x128_superblock = false;
2934 seq.enable_filter_intra = false;
2935 seq.enable_cdef = false;
2936 seq.enable_restoration = false;
2937 seq.enable_superres = false;
2938 seq.seq_force_screen_content_tools = 0;
2939 seq.seq_force_integer_mv = 0;
2940 seq
2941 }
2942
2943 /// The key frame the tile above belongs to: one tile, quantised so nothing
2944 /// is lossless, one transform size per block, no in-loop filtering, and no
2945 /// CDF adaptation (the writer codes against the defaults).
2946 fn flat_key_frame() -> FrameHeader {
2947 FrameHeader {
2948 frame_type: FrameType::Key,
2949 frame_is_intra: true,
2950 show_frame: true,
2951 error_resilient_mode: true,
2952 disable_cdf_update: true,
2953 allow_screen_content_tools: false,
2954 force_integer_mv: true,
2955 refresh_frame_flags: 0xFF,
2956 primary_ref_frame: PRIMARY_REF_NONE,
2957 frame_width: 64,
2958 frame_height: 64,
2959 upscaled_width: 64,
2960 render_width: 64,
2961 render_height: 64,
2962 mi_cols: 16,
2963 mi_rows: 16,
2964 tile_info: TileInfo {
2965 uniform_spacing: true,
2966 cols: 1,
2967 rows: 1,
2968 cols_log2: 0,
2969 rows_log2: 0,
2970 mi_col_starts: vec![0, 16],
2971 mi_row_starts: vec![0, 16],
2972 context_update_tile_id: 0,
2973 tile_size_bytes: 1,
2974 },
2975 quantization: QuantizationParams {
2976 base_q_idx: 100,
2977 ..QuantizationParams::default()
2978 },
2979 loop_filter: LoopFilterParams::default(),
2980 tx_mode: TxMode::Largest,
2981 reduced_tx_set: false,
2982 ..FrameHeader::default()
2983 }
2984 }
2985
2986 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
2987 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
2988 /// aomenc gate decodes its stream through ffmpeg and is meaningless
2989 /// without it -- turns it into a hard failure. Without this the require
2990 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
2991 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
2992 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
2993 fn have_ffmpeg() -> bool {
2994 let present = Command::new("ffmpeg")
2995 .arg("-version")
2996 .stdout(Stdio::null())
2997 .stderr(Stdio::null())
2998 .status()
2999 .is_ok_and(|s| s.success());
3000 assert!(
3001 present
3002 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
3003 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
3004 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
3005 );
3006 present
3007 }
3008
3009 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
3010 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
3011 let mut child = Command::new("ffmpeg")
3012 .args([
3013 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3014 ])
3015 .stdin(Stdio::piped())
3016 .stdout(Stdio::piped())
3017 .stderr(Stdio::piped())
3018 .spawn()
3019 .expect("ffmpeg failed to start");
3020 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
3021 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
3022 // fills before the last input byte is written -- which is exactly what
3023 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
3024 // (measured: 45 min, both processes at 0% CPU). A write error here is
3025 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
3026 // below, are the real diagnosis.
3027 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
3028 let payload = stream.to_vec();
3029 let writer = std::thread::spawn(move || {
3030 let _ = stdin.write_all(&payload);
3031 });
3032 let out = child.wait_with_output().expect("ffmpeg failed to run");
3033 writer.join().expect("ffmpeg stdin writer thread");
3034 assert!(
3035 out.status.success(),
3036 "ffmpeg refused the stream: {}",
3037 String::from_utf8_lossy(&out.stderr)
3038 );
3039 assert_eq!(
3040 out.stdout.len(),
3041 w * h * 3 / 2,
3042 "expected one 4:2:0 frame, ffmpeg said: {}",
3043 String::from_utf8_lossy(&out.stderr)
3044 );
3045 out.stdout
3046 }
3047
3048 #[test]
3049 fn flat_key_frame_decodes_to_mid_grey() {
3050 if !have_ffmpeg() {
3051 eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH");
3052 return;
3053 }
3054 let seq = sequence_64();
3055 let header = flat_key_frame();
3056 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();
3057
3058 let mut stream = temporal_delimiter();
3059 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3060 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3061
3062 let planes = ffmpeg_decode(&stream, 64, 64);
3063 // A DC prediction with no neighbour to average is the middle of the
3064 // range, and a skipped block adds no residual, so every sample of every
3065 // plane is 128 — one wrong symbol anywhere in the tile shows up here.
3066 for (i, &s) in planes.iter().enumerate() {
3067 assert_eq!(s, 128, "sample {i} of the decoded frame");
3068 }
3069 }
3070
3071 /// The one q-context whose CDFs this crate carries; the decoded table
3072 /// below is pinned at this quantiser and nowhere else.
3073 const Q_IDX: u8 = 100;
3074
3075 /// Encode a 64x64 key frame carrying `dc_level` and hand back its planes.
3076 fn decode_dc_frame(dc_level: i32) -> Vec<u8> {
3077 let seq = sequence_64();
3078 let mut header = flat_key_frame();
3079 header.quantization.base_q_idx = Q_IDX;
3080 let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap();
3081 let mut stream = temporal_delimiter();
3082 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3083 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3084 ffmpeg_decode(&stream, 64, 64)
3085 }
3086
3087 /// What a reference decoder makes of each DC level at `base_q_idx` 100:
3088 /// the level times the DC quantiser, inverse-transformed over a whole
3089 /// 64x64 block — which spreads one coefficient over 4096 samples, so a
3090 /// level moves the picture by a sample or two, not by tens. These numbers
3091 /// are pinned from the decoder rather than derived: this crate has no
3092 /// inverse transform of its own yet to derive them with. What the test
3093 /// asserts around them — flat planes, untouched chroma, monotone in the
3094 /// level, and the sign going the right way — is derived, and it is what a
3095 /// desync in the coefficient syntax breaks first.
3096 const DECODED_AT_Q100: [(i32, u8); 28] = [
3097 (1, 128),
3098 (2, 128),
3099 (3, 129),
3100 (4, 129),
3101 (5, 129),
3102 (6, 129),
3103 (7, 129),
3104 (8, 129),
3105 (9, 130),
3106 (10, 130),
3107 (11, 130),
3108 (12, 130),
3109 (13, 130),
3110 (14, 131),
3111 (-1, 128),
3112 (-2, 128),
3113 (-3, 128),
3114 (-4, 127),
3115 (-5, 127),
3116 (-6, 127),
3117 (-7, 127),
3118 (-8, 127),
3119 (-9, 126),
3120 (-10, 126),
3121 (-11, 126),
3122 (-12, 126),
3123 (-13, 126),
3124 (-14, 126),
3125 ];
3126
3127 #[test]
3128 fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
3129 if !have_ffmpeg() {
3130 eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
3131 return;
3132 }
3133 let mut seen = Vec::new();
3134 for (level, want) in DECODED_AT_Q100 {
3135 let planes = decode_dc_frame(level);
3136 let (luma, chroma) = planes.split_at(64 * 64);
3137 for (i, &sample) in luma.iter().enumerate() {
3138 assert_eq!(sample, want, "luma sample {i} at dc level {level}");
3139 }
3140 // The chroma transform blocks are all-zero, so both planes stay at
3141 // the prediction. A desync in the luma coefficient syntax lands
3142 // here first: the chroma flags are the next symbols after it.
3143 for (i, &sample) in chroma.iter().enumerate() {
3144 assert_eq!(sample, 128, "chroma sample {i} at dc level {level}");
3145 }
3146 seen.push((level, want));
3147 }
3148 // The picture moves off mid-grey the way the level says: up for a
3149 // positive level, down for a negative one, and never back towards it
3150 // as the level grows.
3151 for w in seen.windows(2) {
3152 let ((prev_level, prev), (level, value)) = (w[0], w[1]);
3153 if prev_level.signum() != level.signum() {
3154 continue;
3155 }
3156 if level > 0 {
3157 assert!(
3158 value >= prev,
3159 "level {level} decoded below level {prev_level}"
3160 );
3161 assert!(value >= 128, "a positive level darkened the picture");
3162 } else {
3163 assert!(
3164 value <= prev,
3165 "level {level} decoded above level {prev_level}"
3166 );
3167 assert!(value <= 128, "a negative level brightened the picture");
3168 }
3169 }
3170 assert!(
3171 DECODED_AT_Q100.iter().any(|&(_, v)| v > 128)
3172 && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128),
3173 "the pinned table has to move the picture both ways"
3174 );
3175 }
3176
3177 /// Encode a grid of 64x64 superblocks, each carrying its own DC level, and
3178 /// hand back the decoded planes.
3179 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
3180 let (w, h) = (64 * sb_cols, 64 * sb_rows);
3181 let (seq, mut header) = frame_of(w, h);
3182 // The DC fixture writers code against the default CDFs and never
3183 // update them, so their frames say so.
3184 header.disable_cdf_update = true;
3185 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
3186 let mut stream = temporal_delimiter();
3187 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3188 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3189 ffmpeg_decode(&stream, w as usize, h as usize)
3190 }
3191
3192 /// A sequence and key frame header for a `w` by `h` frame of whole
3193 /// superblocks.
3194 fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) {
3195 let mut seq = sequence_64();
3196 seq.max_frame_width = w;
3197 seq.max_frame_height = h;
3198 let mut header = flat_key_frame();
3199 // Every tile these headers carry is written by the adapting writer.
3200 header.disable_cdf_update = false;
3201 header.frame_width = w;
3202 header.frame_height = h;
3203 header.upscaled_width = w;
3204 header.render_width = w;
3205 header.render_height = h;
3206 header.mi_cols = w / 4;
3207 header.mi_rows = h / 4;
3208 header.tile_info.mi_col_starts = vec![0, header.mi_cols];
3209 header.tile_info.mi_row_starts = vec![0, header.mi_rows];
3210 header.quantization.base_q_idx = Q_IDX;
3211 (seq, header)
3212 }
3213
3214 fn decoded_value(level: i32) -> u8 {
3215 DECODED_AT_Q100
3216 .iter()
3217 .find(|&&(l, _)| l == level)
3218 .map(|&(_, v)| v)
3219 .expect("the level is in the pinned table")
3220 }
3221
3222 /// `dc_predict` (spec 7.11.2) for the flat case: a block whose neighbours
3223 /// are themselves flat predicts their average, and predicts mid-grey with
3224 /// no neighbour at all. Every block here is a whole 64x64 superblock, so
3225 /// the above row and the left column weigh the same.
3226 fn dc_prediction(above: Option<u8>, left: Option<u8>) -> u8 {
3227 match (above, left) {
3228 (None, None) => 128,
3229 (Some(a), None) => a,
3230 (None, Some(l)) => l,
3231 (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8,
3232 }
3233 }
3234
3235 /// What a DC level adds to the prediction: the pinned table is that sum
3236 /// against a mid-grey prediction, and the residual does not depend on what
3237 /// it is added to.
3238 fn dc_residual(level: i32) -> i32 {
3239 i32::from(decoded_value(level)) - 128
3240 }
3241
3242 /// Every block reads its DC sign context off the coded blocks above and to
3243 /// its left, and the three ways that can land — no coded neighbour, the
3244 /// neighbours leaning one way, the neighbours cancelling — are only
3245 /// reachable in a frame whose levels differ in sign. Getting the context
3246 /// wrong desyncs the arithmetic decoder, so the check is that every block
3247 /// still decodes to the grey its own level asks for.
3248 #[test]
3249 fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {
3250 if !have_ffmpeg() {
3251 eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg");
3252 return;
3253 }
3254 // Read in raster order the two grids put a positive, a negative and a
3255 // cancelling sign context in front of the bottom-right block, and a
3256 // leaning-down one in front of the second grid's right and bottom
3257 // blocks.
3258 for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] {
3259 let planes = decode_level_grid(&levels, 2, 2);
3260 let (luma, chroma) = planes.split_at(128 * 128);
3261 // The blocks are not independent: a DC prediction reads the
3262 // reconstructed neighbours, so each block's grey is its
3263 // neighbours' average plus its own residual.
3264 let mut recon = [0u8; 4];
3265 for (block, level) in levels.iter().enumerate() {
3266 let (br, bc) = (block / 2, block % 2);
3267 let above = (br > 0).then(|| recon[block - 2]);
3268 let left = (bc > 0).then(|| recon[block - 1]);
3269 let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level))
3270 .clamp(0, 255) as u8;
3271 recon[block] = want;
3272 for y in 0..64 {
3273 for x in 0..64 {
3274 let i = (br * 64 + y) * 128 + bc * 64 + x;
3275 assert_eq!(
3276 luma[i], want,
3277 "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}"
3278 );
3279 }
3280 }
3281 }
3282 for (i, &sample) in chroma.iter().enumerate() {
3283 assert_eq!(sample, 128, "chroma sample {i} of {levels:?}");
3284 }
3285 }
3286 }
3287
3288 /// What a DC level adds to a 32x32 block's prediction at `base_q_idx` 100,
3289 /// pinned from the decoder the way [`DECODED_AT_Q100`] is. A 32x32
3290 /// transform spreads its DC over a quarter of the samples a 64x64 one
3291 /// does, so the same level moves the picture further: level 14 is five
3292 /// sample values here against three there.
3293 const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [
3294 (1, 0),
3295 (2, 1),
3296 (3, 1),
3297 (4, 1),
3298 (5, 2),
3299 (6, 2),
3300 (7, 3),
3301 (8, 3),
3302 (9, 3),
3303 (10, 4),
3304 (11, 4),
3305 (12, 4),
3306 (13, 5),
3307 (14, 5),
3308 (-1, 0),
3309 (-2, -1),
3310 (-3, -1),
3311 (-4, -1),
3312 (-5, -2),
3313 (-6, -2),
3314 (-7, -2),
3315 (-8, -3),
3316 (-9, -3),
3317 (-10, -4),
3318 (-11, -4),
3319 (-12, -4),
3320 (-13, -5),
3321 (-14, -5),
3322 ];
3323
3324 fn split_residual(level: i32) -> i32 {
3325 SPLIT_RESIDUAL_AT_Q100
3326 .iter()
3327 .find(|&&(l, _)| l == level)
3328 .map(|&(_, r)| r)
3329 .expect("the level is in the pinned table")
3330 }
3331
3332 /// Splitting a superblock puts three more syntax elements in front of every
3333 /// block — the split partition itself, the 32x32 partition below it and a
3334 /// chroma mode from the wider table CFL-capable blocks read — and moves the
3335 /// coefficients onto the 32x32 CDFs. Getting any of them wrong desyncs the
3336 /// arithmetic decoder, and the check is that all sixteen blocks still land
3337 /// on the grey their own level and their neighbours ask for.
3338 #[test]
3339 fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
3340 if !have_ffmpeg() {
3341 eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
3342 return;
3343 }
3344 // Four by four 32x32 blocks over two by two superblocks, so the walk
3345 // crosses superblock boundaries in both directions, and signs that
3346 // alternate so the DC sign context lands on all three of its values.
3347 let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1];
3348 let planes = decode_split_grid(&levels, 2, 2);
3349 let (luma, chroma) = planes.split_at(128 * 128);
3350
3351 let mut recon = [0i32; 16];
3352 for (block, level) in levels.iter().enumerate() {
3353 let (br, bc) = (block / 4, block % 4);
3354 let above = (br > 0).then(|| recon[block - 4] as u8);
3355 let left = (bc > 0).then(|| recon[block - 1] as u8);
3356 let want =
3357 (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255);
3358 recon[block] = want;
3359 for y in 0..32 {
3360 for x in 0..32 {
3361 let i = (br * 32 + y) * 128 + bc * 32 + x;
3362 assert_eq!(
3363 i32::from(luma[i]),
3364 want,
3365 "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \
3366 column {bc}"
3367 );
3368 }
3369 }
3370 }
3371 for (i, &sample) in chroma.iter().enumerate() {
3372 assert_eq!(sample, 128, "chroma sample {i}");
3373 }
3374 }
3375
3376 /// Encode a grid of 32x32 blocks, each carrying its own DC level.
3377 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
3378 let (w, h) = (64 * sb_cols, 64 * sb_rows);
3379 let (seq, mut header) = frame_of(w, h);
3380 // The DC fixture writers code against the default CDFs and never
3381 // update them, so their frames say so.
3382 header.disable_cdf_update = true;
3383 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
3384 let mut stream = temporal_delimiter();
3385 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3386 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3387 ffmpeg_decode(&stream, w as usize, h as usize)
3388 }
3389
3390 #[test]
3391 fn a_level_grid_that_does_not_cover_the_frame_is_refused() {
3392 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err());
3393 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err());
3394 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());
3395 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());
3396 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());
3397 }
3398
3399 #[test]
3400 fn dc_levels_the_base_syntax_cannot_carry_are_refused() {
3401 assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());
3402 assert!(dc_key_frame_tile(16, 16, 100, 15).is_err());
3403 assert!(dc_key_frame_tile(16, 16, 100, -15).is_err());
3404 }
3405
3406 #[test]
3407 fn partial_superblocks_are_refused() {
3408 assert!(flat_key_frame_tile(16, 20).is_err());
3409 assert!(flat_key_frame_tile(0, 16).is_err());
3410 }
3411
3412 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
3413 /// hands back the luma plane as rows of samples.
3414 fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {
3415 let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect();
3416 let [luma, u, v] = decode_coeff_planes(&blocks);
3417 for (name, plane) in [("U", &u), ("V", &v)] {
3418 for (y, row) in plane.iter().enumerate() {
3419 for (x, &s) in row.iter().enumerate() {
3420 assert_eq!(
3421 s, 128,
3422 "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \
3423 DC prediction with no coded neighbour is mid-grey"
3424 );
3425 }
3426 }
3427 }
3428 luma
3429 }
3430
3431 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
3432 /// hands back its three planes as rows of samples: 64 rows of luma and, at
3433 /// 4:2:0, 32 rows of each chroma plane.
3434 fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] {
3435 let (seq, header) = frame_of(64, 64);
3436 let tile =
3437 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
3438 let mut stream = temporal_delimiter();
3439 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3440 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3441 let planes = ffmpeg_decode(&stream, 64, 64);
3442 let (luma, chroma) = planes.split_at(64 * 64);
3443 let (u, v) = chroma.split_at(32 * 32);
3444 [
3445 luma.chunks_exact(64).map(<[u8]>::to_vec).collect(),
3446 u.chunks_exact(32).map(<[u8]>::to_vec).collect(),
3447 v.chunks_exact(32).map(<[u8]>::to_vec).collect(),
3448 ]
3449 }
3450
3451 /// The top-left 32x32 block of a decoded frame, which is the only one whose
3452 /// prediction has no neighbour to lean on.
3453 fn top_left_block(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
3454 rows[..32].iter().map(|r| r[..32].to_vec()).collect()
3455 }
3456
3457 /// A transform's basis functions all average to zero except the DC's, so a
3458 /// block carrying no DC decodes to samples that average to its prediction —
3459 /// mid-grey for the block with no neighbours. Rounding of the inverse
3460 /// transform moves the average by less than a sample.
3461 fn assert_mean_is_mid_grey(block: &[Vec<u8>]) {
3462 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
3463 let mean = f64::from(sum) / (32.0 * 32.0);
3464 assert!(
3465 (mean - 128.0).abs() <= 1.0,
3466 "a block with no DC coefficient averages to its mid-grey prediction, got {mean}"
3467 );
3468 }
3469
3470 /// A coefficient at row 0, column 1 selects the basis function that is flat
3471 /// down the block and a half-cycle of a cosine across it. Nothing about
3472 /// that shape is pinned here: every row of the block must be the same row,
3473 /// the samples must fall from left to right and actually move, and the
3474 /// block must still average to its prediction. A desync in the scan, the
3475 /// end-of-block position or the level contexts breaks one of those.
3476 #[test]
3477 fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
3478 if !have_ffmpeg() {
3479 eprintln!(
3480 "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg"
3481 );
3482 return;
3483 }
3484 let blocks = vec![
3485 vec![Coeff {
3486 row: 0,
3487 col: 1,
3488 level: 12,
3489 }],
3490 Vec::new(),
3491 Vec::new(),
3492 Vec::new(),
3493 ];
3494 let rows = decode_coeff_quadrants(&blocks);
3495 let block = top_left_block(&rows);
3496
3497 for (y, row) in block.iter().enumerate() {
3498 assert_eq!(row, &block[0], "row {y} of a horizontal basis function");
3499 }
3500 assert!(
3501 block[0][0] > block[0][31],
3502 "a positive coefficient leans the block towards its left edge: {:?}",
3503 block[0]
3504 );
3505 for x in 1..32 {
3506 assert!(
3507 block[0][x] <= block[0][x - 1],
3508 "the half-cycle falls from left to right, broke at column {x}: {:?}",
3509 block[0]
3510 );
3511 }
3512 assert_mean_is_mid_grey(&block);
3513
3514 // The same coefficient transposed selects the basis function that is
3515 // flat across the block and a half-cycle down it.
3516 let blocks = vec![
3517 vec![Coeff {
3518 row: 1,
3519 col: 0,
3520 level: 12,
3521 }],
3522 Vec::new(),
3523 Vec::new(),
3524 Vec::new(),
3525 ];
3526 let rows = decode_coeff_quadrants(&blocks);
3527 let block = top_left_block(&rows);
3528 for (y, row) in block.iter().enumerate() {
3529 for (x, &s) in row.iter().enumerate() {
3530 assert_eq!(s, row[0], "sample ({y},{x}) of a vertical basis function");
3531 }
3532 }
3533 assert!(
3534 block[0][0] > block[31][0],
3535 "a positive coefficient leans the block up"
3536 );
3537 for y in 1..32 {
3538 assert!(
3539 block[y][0] <= block[y - 1][0],
3540 "the half-cycle falls from top to bottom, broke at row {y}"
3541 );
3542 }
3543 assert_mean_is_mid_grey(&block);
3544 }
3545
3546 /// A coefficient late in the scan pushes the end-of-block position into a
3547 /// group that carries an offset — the far corner of a 32x32 transform is
3548 /// the last of the eleven groups, whose offset is nine bits wide, one of
3549 /// them from a CDF and the rest raw. Every coefficient before it is coded
3550 /// too, so this also walks the base and base-range contexts over a block
3551 /// with neighbours that carry levels rather than zeros.
3552 #[test]
3553 fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {
3554 if !have_ffmpeg() {
3555 eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group");
3556 return;
3557 }
3558 let block = vec![
3559 Coeff {
3560 row: 31,
3561 col: 31,
3562 level: 5,
3563 },
3564 Coeff {
3565 row: 5,
3566 col: 7,
3567 level: -9,
3568 },
3569 Coeff {
3570 row: 1,
3571 col: 1,
3572 level: 14,
3573 },
3574 Coeff {
3575 row: 0,
3576 col: 2,
3577 level: -3,
3578 },
3579 Coeff {
3580 row: 2,
3581 col: 0,
3582 level: 2,
3583 },
3584 Coeff {
3585 row: 1,
3586 col: 2,
3587 level: -1,
3588 },
3589 ];
3590 let rows = decode_coeff_quadrants(&[block, Vec::new(), Vec::new(), Vec::new()]);
3591 let block = top_left_block(&rows);
3592 assert_mean_is_mid_grey(&block);
3593 assert!(
3594 block.iter().flatten().any(|&s| s != block[0][0]),
3595 "six coefficients do not decode to a flat block"
3596 );
3597 // The blocks that carry nothing are flat: their prediction is whatever
3598 // their neighbours left, and they add no residual to it.
3599 for (name, ys, xs) in [("top right", 0..32, 32..64), ("bottom left", 32..64, 0..32)] {
3600 let first = rows[ys.start][xs.start];
3601 for y in ys {
3602 for x in xs.clone() {
3603 assert_eq!(rows[y][x], first, "the {name} block carries no coefficient");
3604 }
3605 }
3606 }
3607 }
3608
3609 /// The price the mode search pays for a block's levels has to be the price
3610 /// the writer charges for them, or the search is ranking modes by a
3611 /// fiction. Both halves are asked for the same grids under the same
3612 /// neutral contexts, and the priced bits are compared against the bytes
3613 /// the writer really spends.
3614 #[test]
3615 fn the_priced_coefficient_bits_match_the_bytes_written() {
3616 let scan = default_scan(TX32);
3617 // Three grids that reach different parts of the syntax: a lone DC, a
3618 // sparse spread of small levels with both signs, and levels past the
3619 // base-range alphabet so the Golomb tail runs.
3620 let mut grids = vec![vec![0i32; TX32 * TX32]; 3];
3621 grids[0][0] = -7;
3622 for (i, &pos) in scan.iter().enumerate().take(400) {
3623 if i % 7 == 0 {
3624 grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 };
3625 }
3626 }
3627 grids[2][0] = 40;
3628 for (i, &pos) in scan.iter().enumerate().take(64) {
3629 grids[2][pos as usize] += i as i32 % 23 - 11;
3630 }
3631
3632 // A single block is too short for the coder's own flush to average
3633 // out, so all three go through one encoder and one flush.
3634 let mut enc = SymbolEncoder::new();
3635 let mut priced = 0.0;
3636 for grid in &grids {
3637 write_coeffs(
3638 &mut enc,
3639 &mut Cdfs::new(2).txb(TxbSet::Luma32, 0),
3640 grid,
3641 &scan,
3642 0,
3643 0,
3644 None,
3645 );
3646 priced += luma_32_coeff_bits(grid);
3647 }
3648 let spent = enc.finish().len() as f64 * 8.0;
3649 assert!(
3650 (priced - spent).abs() / spent < 0.02,
3651 "priced {priced} bits, wrote {spent}"
3652 );
3653 }
3654
3655 /// A rate term the search can read as constant is a rate term that ranks
3656 /// nothing, so the price is checked to move the way the levels move: an
3657 /// empty block is the cheapest thing there is, one coefficient costs more
3658 /// than none, and both spreading the coefficients and growing them costs
3659 /// more again.
3660 #[test]
3661 fn the_price_grows_with_the_levels() {
3662 let grid = |f: &dyn Fn(&mut Vec<i32>)| {
3663 let mut g = vec![0i32; TX32 * TX32];
3664 f(&mut g);
3665 luma_32_coeff_bits(&g)
3666 };
3667 let empty = grid(&|_| {});
3668 let one = grid(&|g| g[0] = 1);
3669 let bigger = grid(&|g| g[0] = 30);
3670 let spread = grid(&|g| {
3671 for i in 0..TX32 {
3672 g[i * TX32 + i] = 1;
3673 }
3674 });
3675 assert!(empty < one, "{empty} {one}");
3676 assert!(one < bigger, "{one} {bigger}");
3677 assert!(one < spread, "{one} {spread}");
3678 // An empty block is one symbol -- an expensive one, because a block
3679 // with no coefficients at all is the rarer of the two under the
3680 // neutral context -- and nothing else.
3681 assert!(
3682 empty < 6.0,
3683 "an empty block is one skip symbol, not {empty}"
3684 );
3685 }
3686
3687 /// Neighbouring blocks that each carry coefficients read their DC sign
3688 /// context, their prediction and their own contexts off each other, so a
3689 /// frame whose four blocks all carry mixed-sign coefficients exercises what
3690 /// a single coded block cannot. The check is that it decodes at all — a
3691 /// desync anywhere fails the decode or the frame size — and that the block
3692 /// with no neighbours still averages to mid-grey.
3693 #[test]
3694 fn every_quadrant_carries_its_own_coefficients() {
3695 if !have_ffmpeg() {
3696 eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg");
3697 return;
3698 }
3699 let blocks = vec![
3700 vec![
3701 Coeff {
3702 row: 0,
3703 col: 1,
3704 level: 7,
3705 },
3706 Coeff {
3707 row: 3,
3708 col: 4,
3709 level: -14,
3710 },
3711 ],
3712 vec![
3713 Coeff {
3714 row: 0,
3715 col: 0,
3716 level: -6,
3717 },
3718 Coeff {
3719 row: 2,
3720 col: 2,
3721 level: 9,
3722 },
3723 ],
3724 vec![
3725 Coeff {
3726 row: 0,
3727 col: 0,
3728 level: 6,
3729 },
3730 Coeff {
3731 row: 1,
3732 col: 0,
3733 level: -2,
3734 },
3735 Coeff {
3736 row: 8,
3737 col: 9,
3738 level: 3,
3739 },
3740 ],
3741 vec![
3742 Coeff {
3743 row: 0,
3744 col: 0,
3745 level: 11,
3746 },
3747 Coeff {
3748 row: 16,
3749 col: 1,
3750 level: -4,
3751 },
3752 ],
3753 ];
3754 let rows = decode_coeff_quadrants(&blocks);
3755 assert_mean_is_mid_grey(&top_left_block(&rows));
3756 for (name, ys, xs) in [
3757 ("top right", 0..32, 32..64),
3758 ("bottom left", 32..64, 0..32),
3759 ("bottom right", 32..64, 32..64),
3760 ] {
3761 let block: Vec<Vec<u8>> = rows[ys].iter().map(|r| r[xs.clone()].to_vec()).collect();
3762 assert!(
3763 block.iter().flatten().any(|&s| s != block[0][0]),
3764 "the {name} block carries coefficients, so it is not flat"
3765 );
3766 }
3767 }
3768
3769 /// The top-left 16x16 block of a decoded chroma plane, which is the only
3770 /// one whose prediction has no neighbour to lean on.
3771 fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
3772 rows[..16].iter().map(|r| r[..16].to_vec()).collect()
3773 }
3774
3775 /// The mean of a decoded block, which every basis function but the DC's
3776 /// leaves at the block's prediction.
3777 fn mean(block: &[Vec<u8>]) -> f64 {
3778 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
3779 let count = block.iter().map(Vec::len).sum::<usize>() as f64;
3780 f64::from(sum) / count
3781 }
3782
3783 /// A chroma plane's coefficients ride their own transform, their own CDFs
3784 /// and their own end-of-block alphabet, so a chroma basis function is the
3785 /// gate on all three: U carries the coefficient that is flat down the block
3786 /// and a half-cycle across it, V the one turned a quarter turn, and neither
3787 /// may reach the other plane or luma.
3788 #[test]
3789 fn each_chroma_plane_codes_its_own_basis_function() {
3790 if !have_ffmpeg() {
3791 eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
3792 return;
3793 }
3794 let mut blocks = vec![BlockCoeffs::default(); 4];
3795 blocks[0].u = vec![Coeff {
3796 row: 0,
3797 col: 1,
3798 level: 12,
3799 }];
3800 blocks[0].v = vec![Coeff {
3801 row: 1,
3802 col: 0,
3803 level: 12,
3804 }];
3805 let [luma, u, v] = decode_coeff_planes(&blocks);
3806
3807 for (y, row) in luma.iter().enumerate() {
3808 for (x, &s) in row.iter().enumerate() {
3809 assert_eq!(
3810 s, 128,
3811 "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \
3812 stays at its mid-grey prediction"
3813 );
3814 }
3815 }
3816
3817 let u_block = top_left_chroma(&u);
3818 for (y, row) in u_block.iter().enumerate() {
3819 assert_eq!(
3820 row, &u_block[0],
3821 "row {y} of a horizontal chroma basis function"
3822 );
3823 }
3824 assert!(
3825 u_block[0][0] > u_block[0][15],
3826 "a positive coefficient leans the U block towards its left edge: {:?}",
3827 u_block[0]
3828 );
3829
3830 let v_block = top_left_chroma(&v);
3831 for (x, &top) in v_block[0].iter().enumerate() {
3832 assert_eq!(
3833 top, v_block[0][0],
3834 "column {x} of a vertical chroma basis function"
3835 );
3836 let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect();
3837 assert!(
3838 column[0] > column[15],
3839 "a positive coefficient leans the V column towards its top edge: {column:?}"
3840 );
3841 }
3842
3843 for (name, block) in [("U", &u_block), ("V", &v_block)] {
3844 let mean = mean(block);
3845 assert!(
3846 (mean - 128.0).abs() <= 1.0,
3847 "the {name} block carries no DC, so it averages to its mid-grey prediction, \
3848 got {mean}"
3849 );
3850 }
3851 }
3852
3853 /// Every block coding chroma puts the chroma all-zero flag on the contexts
3854 /// a coded neighbour above and to the left select, and the DC sign on the
3855 /// contexts their signs select. A frame whose four blocks all carry chroma
3856 /// DCs of mixed sign walks those contexts; the picture that comes back must
3857 /// still lean the way each block's own DC asks.
3858 #[test]
3859 fn chroma_dc_signs_read_their_neighbours() {
3860 if !have_ffmpeg() {
3861 eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
3862 return;
3863 }
3864 let dc = |level| {
3865 vec![Coeff {
3866 row: 0,
3867 col: 0,
3868 level,
3869 }]
3870 };
3871 let signs = [8, -8, -8, 8];
3872 let blocks: Vec<BlockCoeffs> = signs
3873 .iter()
3874 .map(|&level| BlockCoeffs {
3875 luma: Vec::new(),
3876 u: dc(level),
3877 v: dc(-level),
3878 ..BlockCoeffs::default()
3879 })
3880 .collect();
3881 let [luma, u, v] = decode_coeff_planes(&blocks);
3882
3883 for (y, row) in luma.iter().enumerate() {
3884 for (x, &s) in row.iter().enumerate() {
3885 assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient");
3886 }
3887 }
3888
3889 // A DC prediction leans on the neighbours a block has, so each block is
3890 // measured against the prediction it was given rather than mid-grey:
3891 // the only block with no neighbour is the first, and the rest are read
3892 // as a step away from the block above them and to their left.
3893 for (i, &level) in signs.iter().enumerate() {
3894 let (r, c) = (i / 2, i % 2);
3895 let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> {
3896 plane[r * 16..r * 16 + 16]
3897 .iter()
3898 .map(|row| row[c * 16..c * 16 + 16].to_vec())
3899 .collect()
3900 };
3901 for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] {
3902 let block = block(plane);
3903 let mean = mean(&block);
3904 for (y, row) in block.iter().enumerate() {
3905 assert_eq!(
3906 row.iter().collect::<std::collections::HashSet<_>>().len(),
3907 1,
3908 "row {y} of a DC-only {name} block is flat"
3909 );
3910 }
3911 if i == 0 {
3912 assert!(
3913 (want > 0) == (mean > 128.0),
3914 "{name} block {i} carries a DC of {want}, so it must lean off its \
3915 mid-grey prediction that way, got {mean}"
3916 );
3917 }
3918 }
3919 }
3920 assert_ne!(u, v, "the two chroma planes carry opposite DCs");
3921 }
3922
3923 /// The coefficient writer refuses what it cannot code rather than writing a
3924 /// stream a decoder walks off the end of.
3925 /// The 32x32 block at the given block row and column of a decoded plane.
3926 fn block_at(rows: &[Vec<u8>], block_row: usize, block_col: usize) -> Vec<Vec<u8>> {
3927 rows[block_row * 32..block_row * 32 + 32]
3928 .iter()
3929 .map(|r| r[block_col * 32..block_col * 32 + 32].to_vec())
3930 .collect()
3931 }
3932
3933 /// Encodes a key frame of the given size, whose 32x32 blocks carry
3934 /// `blocks` in raster order, and hands back its luma plane as rows of
3935 /// The neighbour context a block reads is gathered across every cell it
3936 /// spans, not taken from the first one: a 32x32 block whose left-hand
3937 /// neighbour cells disagree still sees the coded one. Reading a single
3938 /// cell agreed with the decoder only while every block was the same size,
3939 /// and desynchronised the arithmetic decoder the moment a 16x16 one
3940 /// appeared beside a 32x32 one.
3941 #[test]
3942 fn a_block_gathers_the_cells_its_neighbours_cover() {
3943 let mut neighbours = Neighbours::new(4, 4, 64, 64);
3944 let quiet = [
3945 vec![0i32; TX16 * TX16],
3946 vec![0; TX8 * TX8],
3947 vec![0; TX8 * TX8],
3948 ];
3949 let mut loud = quiet.clone();
3950 loud[1][0] = -3;
3951 // Two 16x16 blocks above the right-hand 32x32 block of the row, of
3952 // which only the second codes anything.
3953 neighbours.record((0, 2), SUB, DC_PRED, &quiet);
3954 neighbours.record((0, 3), SUB, DC_PRED, &loud);
3955 let around = neighbours.around((2, 2), BLOCK);
3956 assert!(
3957 around[1].above_coded,
3958 "the coded cell has to reach the block below it"
3959 );
3960 assert_eq!(
3961 dc_sign_ctx(around[1].dc_vote),
3962 1,
3963 "the one negative DC above the block is what it votes"
3964 );
3965 // The same read one cell at a time misses it, which is the bug this
3966 // gate is here for. `above[8]` is the first 4x4 unit the quiet block
3967 // at `(0, 2)` wrote (2 SUB units * 4 4x4-units-per-SUB).
3968 assert!(!neighbours.above[8][1].coded);
3969 }
3970
3971 /// samples.
3972 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
3973 let (seq, header) = frame_of(width as u32, height as u32);
3974 let tile =
3975 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
3976 let mut stream = temporal_delimiter();
3977 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3978 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3979 let planes = ffmpeg_decode(&stream, width, height);
3980 planes[..width * height]
3981 .chunks_exact(width)
3982 .map(<[u8]>::to_vec)
3983 .collect()
3984 }
3985
3986 /// Every row of a block is the same row, and that row falls from left to
3987 /// right — the shape of a coefficient at row 0, column 1.
3988 fn assert_falls_across(block: &[Vec<u8>], name: &str) {
3989 for row in block {
3990 assert_eq!(
3991 row, &block[0],
3992 "{name}: every row of the block is the same row"
3993 );
3994 }
3995 assert!(
3996 block[0][0] > block[0][31],
3997 "{name}: the row falls from left to right, got {} then {}",
3998 block[0][0],
3999 block[0][31]
4000 );
4001 }
4002
4003 /// Every column of a block is constant across it and falls down it — the
4004 /// shape of a coefficient at row 1, column 0.
4005 fn assert_falls_down(block: &[Vec<u8>], name: &str) {
4006 for (y, row) in block.iter().enumerate() {
4007 assert!(
4008 row.iter().all(|&s| s == row[0]),
4009 "{name}: row {y} of the block is one constant"
4010 );
4011 }
4012 assert!(
4013 block[0][0] > block[31][0],
4014 "{name}: the column falls down the block, got {} then {}",
4015 block[0][0],
4016 block[31][0]
4017 );
4018 }
4019
4020 /// The mean sample of a decoded block.
4021 fn mean_of(block: &[Vec<u8>]) -> f64 {
4022 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
4023 f64::from(sum) / (block.len() * block[0].len()) as f64
4024 }
4025
4026 /// The top-left block of a frame whose only coefficient is a luma DC of
4027 /// `level`.
4028 fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> {
4029 let blocks = vec![
4030 vec![Coeff {
4031 row: 0,
4032 col: 0,
4033 level,
4034 }],
4035 Vec::new(),
4036 Vec::new(),
4037 Vec::new(),
4038 ];
4039 top_left_block(&decode_coeff_quadrants(&blocks))
4040 }
4041
4042 /// `read_golomb` (spec 5.11.40), written from the specification's
4043 /// pseudocode, and the level its caller builds from it: a level above the
4044 /// base-range tail is fifteen plus what the tail carries.
4045 fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 {
4046 let mut length = 0;
4047 while dec.literal(1) == 0 {
4048 length += 1;
4049 assert!(
4050 length < 20,
4051 "the tail's length prefix runs past twenty bits"
4052 );
4053 }
4054 let mut x = 1;
4055 for _ in 0..length {
4056 x = (x << 1) | dec.literal(1);
4057 }
4058 (MAX_BR_LEVEL + 1) as u32 + (x - 1)
4059 }
4060
4061 /// The tail says how much of the level the base and base-range syntax could
4062 /// not carry, and the spec's own reader must hand back the level that was
4063 /// asked for — not one either side of it. A tail written a bit long, a bit
4064 /// short, or against the wrong base fails this at the first level it
4065 /// reaches.
4066 #[test]
4067 fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
4068 for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300)
4069 .chain([MAX_LEVEL - 1, MAX_LEVEL])
4070 .map(|l| l as u32)
4071 {
4072 let mut enc = SymbolEncoder::new();
4073 write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32);
4074 // The tail is raw bits, so it needs no padding beyond what the
4075 // encoder's own flush writes.
4076 let data = enc.finish();
4077 let mut dec = crate::msac::tests::SymbolDecoder::new(&data);
4078 assert_eq!(
4079 read_golomb_level(&mut dec),
4080 level,
4081 "the tail of level {level}"
4082 );
4083 }
4084 }
4085
4086 /// The base and base-range syntax reach level fourteen between them;
4087 /// anything above that carries the rest of itself as a Golomb tail, written
4088 /// after its own sign. A DC level moves the whole block off its mid-grey
4089 /// prediction by an amount that grows with the level, so a run of levels
4090 /// either side of the tail's threshold — spaced wide enough that the
4091 /// quantiser separates them — must decode to a run of steadily
4092 /// brighter blocks — and the negatives of the same levels to steadily
4093 /// darker ones. A tail written with the wrong length, in the wrong place in
4094 /// the syntax, or off by one desyncs the decoder outright.
4095 #[test]
4096 fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
4097 if !have_ffmpeg() {
4098 eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
4099 return;
4100 }
4101 let mut brighter = Vec::new();
4102 let mut darker = Vec::new();
4103 for level in [10, 14, 18, 31, 60, 400] {
4104 brighter.push((level, mean_of(&decode_dc_level_block(level))));
4105 darker.push((level, mean_of(&decode_dc_level_block(-level))));
4106 }
4107 for pair in brighter.windows(2) {
4108 let [(low, dim), (high, bright)] = [pair[0], pair[1]];
4109 assert!(
4110 bright > dim,
4111 "level {high} decodes brighter than level {low}, got {bright} against {dim}"
4112 );
4113 }
4114 for pair in darker.windows(2) {
4115 let [(low, bright), (high, dim)] = [pair[0], pair[1]];
4116 assert!(
4117 dim < bright,
4118 "level -{high} decodes darker than level -{low}, got {dim} against {bright}"
4119 );
4120 }
4121 let (_, mid) = brighter[0];
4122 assert!(
4123 mid > 128.0 && darker[0].1 < 128.0,
4124 "a positive level brightens its block and a negative one darkens it, got {mid} and {}",
4125 darker[0].1
4126 );
4127 }
4128
4129 /// A frame need not be a whole number of superblocks. A 96x64 frame is a
4130 /// superblock and a half across: the second superblock has no right-hand
4131 /// half, so its partition is a gathered flag rather than the full symbol,
4132 /// and the two blocks that would sit in that half are never coded at all.
4133 /// Each of the six blocks that do exist carries one of two basis functions,
4134 /// alternating, so a block written into the wrong place or a flag the
4135 /// decoder reads as a different number of bits shows up as a block with the
4136 /// other block's shape — or as a decode failure.
4137 fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8>> {
4138 let (seq, header) = frame_of(width as u32, height as u32);
4139 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap();
4140 let mut stream = temporal_delimiter();
4141 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
4142 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
4143 let planes = ffmpeg_decode(&stream, width, height);
4144 planes[..width * height]
4145 .chunks_exact(width)
4146 .map(<[u8]>::to_vec)
4147 .collect()
4148 }
4149
4150 /// A superblock left whole carries one 64x64 transform, whose lowest
4151 /// horizontal basis function falls across the whole sixty-four samples in
4152 /// one stroke. Were the same superblock split, each half would restart the
4153 /// gradient at its own left edge and the picture would rise again in the
4154 /// middle, so the walk across the row is what tells the two apart — and
4155 /// the split superblock beside it proves the two partitions still agree on
4156 /// where the next one begins.
4157 #[test]
4158 fn a_whole_superblock_covers_all_four_of_its_quadrants() {
4159 if !have_ffmpeg() {
4160 eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg");
4161 return;
4162 }
4163 let across = BlockCoeffs::from(vec![Coeff {
4164 row: 0,
4165 col: 1,
4166 level: 20,
4167 }]);
4168 let down = BlockCoeffs::from(vec![Coeff {
4169 row: 1,
4170 col: 0,
4171 level: 20,
4172 }]);
4173 let sbs = [
4174 Superblock::Whole(across),
4175 Superblock::Split(vec![
4176 Quadrant::Whole(down.clone()),
4177 Quadrant::Whole(down.clone()),
4178 Quadrant::Whole(down.clone()),
4179 Quadrant::Whole(down),
4180 ]),
4181 ];
4182 let rows = decode_luma_sb(128, 64, &sbs);
4183
4184 for (y, row) in rows.iter().enumerate() {
4185 assert_eq!(
4186 &row[..64],
4187 &rows[0][..64],
4188 "row {y} of the whole superblock repeats its first row"
4189 );
4190 }
4191 let first = &rows[0][..64];
4192 assert!(
4193 first.windows(2).all(|w| w[0] >= w[1]),
4194 "the whole superblock falls across its sixty-four samples without \
4195 restarting: {first:?}"
4196 );
4197 assert!(
4198 first[0] > first[63],
4199 "the whole superblock falls from left to right, got {} then {}",
4200 first[0],
4201 first[63]
4202 );
4203 for block_row in 0..2 {
4204 for block_col in 2..4 {
4205 let block = block_at(&rows, block_row, block_col);
4206 assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})"));
4207 }
4208 }
4209 }
4210
4211 /// A quadrant may be split again into four 16x16 blocks, each carrying its
4212 /// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block
4213 /// makes each of the four a flat grey of its own, so the quadrant reads as
4214 /// four squares rather than one — which is what tells the extra split from
4215 /// a 32x32 block that merely carries the same coefficients.
4216 #[test]
4217 fn a_quadrant_splits_into_four_sixteens() {
4218 if !have_ffmpeg() {
4219 eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
4220 return;
4221 }
4222 let dc = |level: i32| {
4223 BlockCoeffs::from(vec![Coeff {
4224 row: 0,
4225 col: 0,
4226 level,
4227 }])
4228 };
4229 let levels = [14, 8, -8, -14];
4230 let flat = BlockCoeffs::from(Vec::new());
4231 let sbs = [Superblock::Split(vec![
4232 Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()),
4233 Quadrant::Whole(flat.clone()),
4234 Quadrant::Whole(flat.clone()),
4235 Quadrant::Whole(flat),
4236 ])];
4237 let rows = decode_luma_sb(64, 64, &sbs);
4238
4239 let mut greys = Vec::new();
4240 for i in 0..levels.len() {
4241 let (y0, x0) = ((i / 2) * 16, (i % 2) * 16);
4242 let grey = rows[y0][x0];
4243 for (y, row) in rows.iter().enumerate().skip(y0).take(16) {
4244 for (x, &sample) in row.iter().enumerate().skip(x0).take(16) {
4245 assert_eq!(
4246 sample, grey,
4247 "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not"
4248 );
4249 }
4250 }
4251 greys.push(grey);
4252 }
4253
4254 // Each block is predicted DC from the blocks the decoder has already
4255 // rebuilt, so what its own level does is move it off that prediction,
4256 // in the level's own direction.
4257 let g = |i: usize| i32::from(greys[i]);
4258 let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2];
4259 for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() {
4260 assert_eq!(
4261 (g(i) - prediction).signum(),
4262 level.signum(),
4263 "the 16x16 block {i} carries level {level}, so it sits on the \
4264 {} side of the {prediction} its neighbours predict, not at {}",
4265 if level > 0 { "bright" } else { "dark" },
4266 g(i)
4267 );
4268 }
4269 assert_eq!(
4270 greys.iter().collect::<std::collections::HashSet<_>>().len(),
4271 4,
4272 "the four blocks are four different greys, not one: {greys:?}"
4273 );
4274 }
4275
4276 /// A superblock half outside the frame has no partition that keeps a block
4277 /// outside it, so it cannot be left whole.
4278 #[test]
4279 fn a_whole_superblock_at_the_frame_edge_is_refused() {
4280 let block = BlockCoeffs::from(vec![Coeff {
4281 row: 0,
4282 col: 0,
4283 level: 4,
4284 }]);
4285 let sbs = [
4286 Superblock::Split(vec![
4287 Quadrant::Whole(block.clone()),
4288 Quadrant::Whole(block.clone()),
4289 Quadrant::Whole(block.clone()),
4290 Quadrant::Whole(block.clone()),
4291 ]),
4292 Superblock::Whole(block.clone()),
4293 ];
4294 // Ninety-six samples across is three 32x32 blocks, so the second
4295 // superblock hangs half outside the frame.
4296 let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err();
4297 assert!(
4298 format!("{err}").contains("half outside the frame"),
4299 "got {err}"
4300 );
4301 }
4302
4303 #[test]
4304 fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
4305 if !have_ffmpeg() {
4306 eprintln!(
4307 "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \
4308 ffmpeg"
4309 );
4310 return;
4311 }
4312 let blocks: Vec<BlockCoeffs> = (0..6)
4313 .map(|i| {
4314 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
4315 BlockCoeffs::from(vec![Coeff {
4316 row,
4317 col,
4318 level: 12,
4319 }])
4320 })
4321 .collect();
4322 let rows = decode_luma_at(96, 64, &blocks);
4323 for block_row in 0..2 {
4324 for block_col in 0..3 {
4325 let name = format!("block ({block_row},{block_col})");
4326 let block = block_at(&rows, block_row, block_col);
4327 if (block_row * 3 + block_col) % 2 == 0 {
4328 assert_falls_across(&block, &name);
4329 } else {
4330 assert_falls_down(&block, &name);
4331 }
4332 }
4333 }
4334 }
4335
4336 /// The transpose of [`a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block`]:
4337 /// an odd number of 32x32 block *rows* (superblock hangs off the
4338 /// *bottom*, `has_cols=true, has_rows=false`) rather than an odd number of
4339 /// columns (hangs off the *right*, `has_cols=false, has_rows=true`) --
4340 /// the two halves of the `(has_cols, has_rows)` match in
4341 /// `sb_coeff_key_frame_tile` gather from different tables
4342 /// (`VERT_ALIKE`/`HORZ_ALIKE`), and only the right-hand-edge direction had
4343 /// a real-decoder test before this one.
4344 #[test]
4345 fn a_frame_that_hangs_off_the_bottom_codes_every_block() {
4346 if !have_ffmpeg() {
4347 eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg");
4348 return;
4349 }
4350 let blocks: Vec<BlockCoeffs> = (0..6)
4351 .map(|i| {
4352 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
4353 BlockCoeffs::from(vec![Coeff {
4354 row,
4355 col,
4356 level: 12,
4357 }])
4358 })
4359 .collect();
4360 let rows = decode_luma_at(64, 96, &blocks);
4361 for block_row in 0..3 {
4362 for block_col in 0..2 {
4363 let name = format!("block ({block_row},{block_col})");
4364 let block = block_at(&rows, block_row, block_col);
4365 if (block_row * 2 + block_col) % 2 == 0 {
4366 assert_falls_across(&block, &name);
4367 } else {
4368 assert_falls_down(&block, &name);
4369 }
4370 }
4371 }
4372 }
4373
4374 /// A frame whose blocks do not tile it is refused rather than written as a
4375 /// stream a decoder walks off the end of.
4376 #[test]
4377 fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() {
4378 let (_, header) = frame_of(80, 64);
4379 let blocks = vec![BlockCoeffs::default(); 4];
4380 let err = split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, &blocks)
4381 .expect_err("80 is not a whole number of 32x32 blocks");
4382 assert!(
4383 format!("{err}").contains("32x32"),
4384 "the refusal names the block size, got {err}"
4385 );
4386 }
4387
4388 /// A directional intra mode says where its prediction comes from, and with
4389 /// no residual of its own a block must be exactly that prediction. The
4390 /// top-left block is given a basis function that is flat across it and
4391 /// falls down it; the block to its right is coded `H_PRED`, so every one of
4392 /// its rows must be the constant its left neighbour's rightmost column
4393 /// hands it, and the block below is coded `V_PRED`, so every one of its
4394 /// columns must be the constant the row above it ends on — a single flat
4395 /// value for the whole block. Nothing here pins the transform's shape or
4396 /// the mode's CDF: a mode written with the wrong context, an angle delta
4397 /// left out or a mode index off by one desyncs the symbol decoder and the
4398 /// two empty blocks stop mirroring their neighbours.
4399 #[test]
4400 fn directional_modes_predict_from_the_neighbours_they_name() {
4401 if !have_ffmpeg() {
4402 eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg");
4403 return;
4404 }
4405 let gradient = BlockCoeffs {
4406 luma: vec![Coeff {
4407 row: 1,
4408 col: 0,
4409 level: 12,
4410 }],
4411 ..BlockCoeffs::default()
4412 };
4413 let blocks = [
4414 gradient,
4415 BlockCoeffs {
4416 mode: H_PRED as u8,
4417 ..BlockCoeffs::default()
4418 },
4419 BlockCoeffs {
4420 mode: V_PRED as u8,
4421 ..BlockCoeffs::default()
4422 },
4423 BlockCoeffs::default(),
4424 ];
4425 let [luma, ..] = decode_coeff_planes(&blocks);
4426
4427 let source = block_at(&luma, 0, 0);
4428 for (r, row) in source.iter().enumerate() {
4429 assert!(
4430 row.iter().all(|&s| s == row[0]),
4431 "the basis function at row 1, column 0 is flat across the block, row {r} is not: {row:?}"
4432 );
4433 }
4434 let profile: Vec<u8> = source.iter().map(|r| r[0]).collect();
4435 assert!(
4436 profile.windows(2).all(|w| w[0] >= w[1]) && profile[0] > profile[31],
4437 "the block must fall from top to bottom, got {profile:?}"
4438 );
4439
4440 let horizontal = block_at(&luma, 0, 1);
4441 for (r, row) in horizontal.iter().enumerate() {
4442 assert!(
4443 row.iter().all(|&s| s == profile[r]),
4444 "an H_PRED block repeats the column to its left, row {r} should be all {} but is {row:?}",
4445 profile[r]
4446 );
4447 }
4448
4449 let vertical = block_at(&luma, 1, 0);
4450 let bottom = profile[31];
4451 assert!(
4452 vertical.iter().flatten().all(|&s| s == bottom),
4453 "a V_PRED block repeats the row above it, which is all {bottom} here, got rows \
4454 {:?} and {:?}",
4455 vertical[0],
4456 vertical[31]
4457 );
4458 }
4459
4460 /// The mode index is checked before anything is written.
4461 #[test]
4462 fn an_intra_mode_outside_the_key_frame_set_is_refused() {
4463 let mut blocks = vec![BlockCoeffs::default(); 4];
4464 blocks[2].mode = INTRA_MODES as u8;
4465 let message = split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks)
4466 .unwrap_err()
4467 .to_string();
4468 assert!(
4469 message.contains("intra mode 13"),
4470 "the refusal must name the mode, got {message}"
4471 );
4472 }
4473
4474 #[test]
4475 fn coefficients_the_writer_cannot_code_are_refused() {
4476 let empty = || vec![BlockCoeffs::default(); 4];
4477 let cases: [(&str, Vec<BlockCoeffs>); 6] = [
4478 ("one set short", vec![BlockCoeffs::default(); 3]),
4479 ("off the transform", {
4480 let mut b = empty();
4481 b[0].luma = vec![Coeff {
4482 row: 32,
4483 col: 0,
4484 level: 1,
4485 }];
4486 b
4487 }),
4488 ("a zero level", {
4489 let mut b = empty();
4490 b[1].luma = vec![Coeff {
4491 row: 0,
4492 col: 0,
4493 level: 0,
4494 }];
4495 b
4496 }),
4497 ("a level past the Golomb tail's reach", {
4498 let mut b = empty();
4499 b[2].luma = vec![Coeff {
4500 row: 0,
4501 col: 0,
4502 level: MAX_LEVEL + 1,
4503 }];
4504 b
4505 }),
4506 ("two coefficients at one position", {
4507 let mut b = empty();
4508 b[3].luma = vec![
4509 Coeff {
4510 row: 4,
4511 col: 4,
4512 level: 1,
4513 },
4514 Coeff {
4515 row: 4,
4516 col: 4,
4517 level: 2,
4518 },
4519 ];
4520 b
4521 }),
4522 ("off the chroma transform", {
4523 let mut b = empty();
4524 b[0].u = vec![Coeff {
4525 row: 0,
4526 col: 16,
4527 level: 1,
4528 }];
4529 b
4530 }),
4531 ];
4532 for (name, blocks) in cases {
4533 assert!(
4534 split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks).is_err(),
4535 "{name} must be refused"
4536 );
4537 }
4538 }
4539
4540 /// The default scan is written as the rule that generates it rather than a
4541 /// thousand pinned numbers, so the rule is checked against what a scan must
4542 /// be: every position exactly once, the origin first, and never a position
4543 /// before one it sits diagonally behind — which is what lets a decoder read
4544 /// a coefficient's context off the coefficients it has already decoded.
4545 #[test]
4546 fn the_default_scan_walks_every_position_outwards() {
4547 for side in [TX16, TX32] {
4548 let area = side * side;
4549 let scan = default_scan(side);
4550 assert_eq!(scan.len(), area);
4551 let mut seen = vec![false; area];
4552 for &pos in &scan {
4553 assert!(
4554 !seen[pos as usize],
4555 "position {pos} is scanned twice in {side}x{side}"
4556 );
4557 seen[pos as usize] = true;
4558 }
4559 assert_eq!(scan[0], 0, "the scan starts at the DC");
4560
4561 let mut order = vec![0usize; area];
4562 for (i, &pos) in scan.iter().enumerate() {
4563 order[pos as usize] = i;
4564 }
4565 for row in 0..side {
4566 for col in 0..side {
4567 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
4568 let (nr, nc) = (row + dr, col + dc);
4569 if nr < side && nc < side {
4570 assert!(
4571 order[nr * side + nc] > order[row * side + col],
4572 "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
4573 be scanned after it"
4574 );
4575 }
4576 }
4577 }
4578 }
4579 }
4580 }
4581
4582 /// The whole point of the inverse transform living in the encoder is that
4583 /// it predicts the decoder without asking one. The residual a DC-only
4584 /// 64x64 transform produces has already been pinned from a real decoder in
4585 /// [`DECODED_AT_Q100`], so that table is the gate: every level in it, both
4586 /// signs, has to come back out of `dequant_and_inverse` exactly.
4587 #[test]
4588 fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() {
4589 for (level, _) in DECODED_AT_Q100 {
4590 let mut levels = vec![0i32; 64 * 64];
4591 levels[0] = level;
4592 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
4593 let want = dc_residual(level);
4594 assert!(
4595 residual.iter().all(|&r| r == want),
4596 "level {level}: want a flat {want}, got {}..{} (first {})",
4597 residual.iter().min().unwrap(),
4598 residual.iter().max().unwrap(),
4599 residual[0]
4600 );
4601 }
4602 }
4603
4604 /// The same gate at the other transform size the encoder codes: a split
4605 /// superblock's 32x32 blocks, whose residuals are pinned in
4606 /// [`SPLIT_RESIDUAL_AT_Q100`]. The two sizes divide the dequantized
4607 /// coefficient by different denominators, so a size-blind dequantizer
4608 /// passes one table and fails the other.
4609 #[test]
4610 fn the_inverse_transform_reproduces_the_pinned_split_residuals() {
4611 for (level, want) in SPLIT_RESIDUAL_AT_Q100 {
4612 let mut levels = vec![0i32; 32 * 32];
4613 levels[0] = level;
4614 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
4615 assert!(
4616 residual.iter().all(|&r| r == want),
4617 "level {level}: want a flat {want}, got {}..{} (first {})",
4618 residual.iter().min().unwrap(),
4619 residual.iter().max().unwrap(),
4620 residual[0]
4621 );
4622 }
4623 }
4624
4625 /// A DC-only transform is flat, which is exactly the case that cannot tell
4626 /// a transposed or mis-permuted butterfly network from a correct one. An AC
4627 /// coefficient in the first row must vary along the row and stay constant
4628 /// down each column, and the one in the first column the other way round;
4629 /// a transposed network swaps the two.
4630 #[test]
4631 fn a_single_ac_coefficient_varies_along_its_own_axis() {
4632 for side in [4, 8, 16, 32, 64] {
4633 let mut horizontal = vec![0i32; side * side];
4634 horizontal[1] = 100;
4635 let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX));
4636 let mut vertical = vec![0i32; side * side];
4637 vertical[side] = 100;
4638 let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX));
4639 for row in 0..side {
4640 for col in 0..side {
4641 assert_eq!(
4642 h[row * side + col],
4643 h[col],
4644 "{side}: a first-row coefficient is constant down column {col}"
4645 );
4646 assert_eq!(
4647 v[row * side + col],
4648 v[row * side],
4649 "{side}: a first-column coefficient is constant along row {row}"
4650 );
4651 }
4652 }
4653 // The two are each other's transpose. Only to within a rounding
4654 // step: the spec rounds halves up rather than away from zero, so a
4655 // basis function and its transpose can land a count apart where
4656 // the row and column passes round opposite ways.
4657 assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies");
4658 for row in 0..side {
4659 for col in 0..side {
4660 let (a, b) = (h[row * side + col], v[col * side + row]);
4661 assert!(
4662 (a - b).abs() <= 1,
4663 "{side}: transpose at ({row},{col}): {a} vs {b}"
4664 );
4665 }
4666 }
4667 }
4668 }
4669
4670 /// Negating every level negates every residual, to within the one count
4671 /// the spec's round-halves-up leaves behind. A dequantizer that rounded a
4672 /// negative coefficient away from zero instead of toward it would shift a
4673 /// whole basis function, not a count of it, so the bound is what makes
4674 /// this a test rather than a restatement.
4675 #[test]
4676 fn negating_the_levels_negates_the_residual() {
4677 for side in [32, 64] {
4678 for level in [1, 2, 3, 5, 9, 14, 40, 100] {
4679 let mut levels = vec![0i32; side * side];
4680 levels[0] = level;
4681 levels[1] = -level;
4682 levels[side + 1] = level * 2;
4683 let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
4684 let negated: Vec<i32> = levels.iter().map(|&l| -l).collect();
4685 let neg =
4686 crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX));
4687 let worst = pos
4688 .iter()
4689 .zip(&neg)
4690 .map(|(&p, &n)| (p + n).abs())
4691 .max()
4692 .expect("the block is not empty");
4693 assert!(worst <= 1, "side {side} level {level}: off by {worst}");
4694 }
4695 }
4696 }
4697
4698 /// The pinned tables above are DC-only, and a flat residual cannot tell a
4699 /// correct butterfly network from one that is merely correct at DC. This
4700 /// is the same claim against a real decoder and with real AC content: the
4701 /// top-left block of a key frame predicts a flat mid-grey with no
4702 /// neighbours to read, so what ffmpeg shows there is exactly 128 plus the
4703 /// residual the encoder's own inverse transform computes. Every sample has
4704 /// to agree, not most of them.
4705 #[test]
4706 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
4707 if !have_ffmpeg() {
4708 eprintln!(
4709 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg"
4710 );
4711 return;
4712 }
4713 // A DC, two low-frequency terms of each orientation, a diagonal and a
4714 // far corner, with both signs among them.
4715 let coeffs = [
4716 (0u8, 0u8, 9i32),
4717 (0, 1, -14),
4718 (1, 0, 7),
4719 (0, 3, 5),
4720 (3, 0, -3),
4721 (2, 2, 11),
4722 (7, 5, -6),
4723 (31, 31, 4),
4724 ];
4725 let block: BlockCoeffs = coeffs
4726 .iter()
4727 .map(|&(row, col, level)| Coeff { row, col, level })
4728 .collect::<Vec<_>>()
4729 .into();
4730 let rows = decode_luma_at(
4731 64,
4732 64,
4733 &[
4734 block,
4735 BlockCoeffs::default(),
4736 BlockCoeffs::default(),
4737 BlockCoeffs::default(),
4738 ],
4739 );
4740
4741 let mut levels = vec![0i32; 32 * 32];
4742 for &(row, col, level) in &coeffs {
4743 levels[usize::from(row) * 32 + usize::from(col)] = level;
4744 }
4745 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
4746 for row in 0..32 {
4747 for col in 0..32 {
4748 let want = (128 + residual[row * 32 + col]).clamp(0, 255);
4749 assert_eq!(
4750 i32::from(rows[row][col]),
4751 want,
4752 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
4753 rows[row][col]
4754 );
4755 }
4756 }
4757 // The block is not flat, so the agreement is about the transform and
4758 // not about a prediction both sides got trivially right.
4759 let (lo, hi) = (
4760 rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(),
4761 rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(),
4762 );
4763 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
4764 }
4765
4766 /// The same against the smallest transform the writer codes, the 16x16 one
4767 /// a split quadrant carries. Its rounding is the one the split path rests
4768 /// on, and nothing else in the crate exercises it against a decoder.
4769 #[test]
4770 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
4771 if !have_ffmpeg() {
4772 eprintln!(
4773 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
4774 );
4775 return;
4776 }
4777 let coeffs = [
4778 (0u8, 0u8, 9i32),
4779 (0, 1, -14),
4780 (1, 0, 7),
4781 (0, 3, 5),
4782 (3, 0, -3),
4783 (2, 2, 11),
4784 (7, 5, -6),
4785 (15, 15, 4),
4786 ];
4787 let block: BlockCoeffs = coeffs
4788 .iter()
4789 .map(|&(row, col, level)| Coeff { row, col, level })
4790 .collect::<Vec<_>>()
4791 .into();
4792 let (seq, header) = frame_of(64, 64);
4793 let quadrants = vec![
4794 Quadrant::Split(vec![
4795 block,
4796 BlockCoeffs::default(),
4797 BlockCoeffs::default(),
4798 BlockCoeffs::default(),
4799 ]),
4800 Quadrant::Whole(BlockCoeffs::default()),
4801 Quadrant::Whole(BlockCoeffs::default()),
4802 Quadrant::Whole(BlockCoeffs::default()),
4803 ];
4804 let tile = sb_coeff_key_frame_tile(
4805 header.mi_cols,
4806 header.mi_rows,
4807 Q_IDX,
4808 &[Superblock::Split(quadrants)],
4809 )
4810 .unwrap();
4811 let mut stream = temporal_delimiter();
4812 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
4813 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
4814 let planes = ffmpeg_decode(&stream, 64, 64);
4815
4816 let mut levels = vec![0i32; TX16 * TX16];
4817 for &(row, col, level) in &coeffs {
4818 levels[usize::from(row) * TX16 + usize::from(col)] = level;
4819 }
4820 let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX));
4821 for row in 0..TX16 {
4822 for col in 0..TX16 {
4823 let want = (128 + residual[row * TX16 + col]).clamp(0, 255);
4824 assert_eq!(
4825 i32::from(planes[row * 64 + col]),
4826 want,
4827 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
4828 planes[row * 64 + col]
4829 );
4830 }
4831 }
4832 }
4833
4834 /// The same against the other transform size, the 64x64 one a whole
4835 /// superblock carries. Only its top-left 32x32 can hold coefficients, and
4836 /// the spec zeroes the rest before the row transform — a 64-point network
4837 /// that read the missing half as anything else would disagree here.
4838 #[test]
4839 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {
4840 if !have_ffmpeg() {
4841 eprintln!(
4842 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg"
4843 );
4844 return;
4845 }
4846 let coeffs = [
4847 (0u8, 0u8, 12i32),
4848 (0, 2, -9),
4849 (2, 0, 6),
4850 (1, 1, -5),
4851 (5, 9, 8),
4852 (31, 0, -4),
4853 (0, 31, 3),
4854 ];
4855 let block: BlockCoeffs = coeffs
4856 .iter()
4857 .map(|&(row, col, level)| Coeff { row, col, level })
4858 .collect::<Vec<_>>()
4859 .into();
4860 let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]);
4861
4862 let mut levels = vec![0i32; 64 * 64];
4863 for &(row, col, level) in &coeffs {
4864 levels[usize::from(row) * 64 + usize::from(col)] = level;
4865 }
4866 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
4867 for row in 0..64 {
4868 for col in 0..64 {
4869 let want = (128 + residual[row * 64 + col]).clamp(0, 255);
4870 assert_eq!(
4871 i32::from(rows[row][col]),
4872 want,
4873 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
4874 rows[row][col]
4875 );
4876 }
4877 }
4878 }
4879
4880 /// The AV1 transforms are normalized so that a quantized level means the
4881 /// same thing at every size: doubling the transform's side halves what a
4882 /// DC level is worth, which is the job the per-size row shift and the
4883 /// dequantizer's denominator split between them. The frame syntax only
4884 /// codes 32x32 and 64x64 transforms, so this is what holds the four
4885 /// smaller sizes' shifts to the spec's table — a shift wrong by one at any
4886 /// size doubles or halves that size's step alone.
4887 #[test]
4888 fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() {
4889 let mut previous: Option<i32> = None;
4890 for side in [4usize, 8, 16, 32, 64] {
4891 let mut levels = vec![0i32; side * side];
4892 levels[0] = 100;
4893 let residual =
4894 crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
4895 let dc = residual[0];
4896 assert!(
4897 residual.iter().all(|&r| r == dc),
4898 "side {side}: a DC coefficient reconstructs flat"
4899 );
4900 if let Some(previous) = previous {
4901 assert!(
4902 (dc * 2 - previous).abs() <= 1,
4903 "side {side}: {dc} is not half of the previous size's {previous}"
4904 );
4905 }
4906 previous = Some(dc);
4907 }
4908 }
4909
4910 /// The encoder's own round trip, through a real bitstream.
4911 ///
4912 /// A picture is chosen, its residual against the DC prediction of 128 is
4913 /// forward-transformed and quantized, the levels are written into a tile,
4914 /// and ffmpeg decodes it. Two things have to hold: what comes back is
4915 /// exactly what the encoder's own inverse said it would be — sample for
4916 /// sample, which is what lets a rate-distortion loop trust its
4917 /// reconstruction — and it is within a quantizer step of the picture that
4918 /// was asked for, which is what makes the forward transform an encoder
4919 /// rather than a scrambler.
4920 #[test]
4921 fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {
4922 if !have_ffmpeg() {
4923 eprintln!(
4924 "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
4925 );
4926 return;
4927 }
4928 // A gradient, a ripple and a corner patch: low frequencies, a mid one
4929 // and an edge, none of them a basis function of the transform.
4930 let mut residual = vec![0i32; 32 * 32];
4931 for row in 0..32usize {
4932 for col in 0..32usize {
4933 let gradient = row as f64 * 2.0 - 32.0;
4934 let ripple = 25.0
4935 * (col as f64 * std::f64::consts::PI / 6.0).sin()
4936 * (row as f64 * std::f64::consts::PI / 11.0).cos();
4937 let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 };
4938 residual[row * 32 + col] = (gradient + ripple + patch).round() as i32;
4939 }
4940 }
4941
4942 let levels =
4943 crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5);
4944 assert!(
4945 levels.iter().any(|&l| l != 0),
4946 "the picture quantized away entirely"
4947 );
4948 let coded: Vec<Coeff> = levels
4949 .iter()
4950 .enumerate()
4951 .filter(|&(_, &level)| level != 0)
4952 .map(|(i, &level)| Coeff {
4953 row: (i / 32) as u8,
4954 col: (i % 32) as u8,
4955 level,
4956 })
4957 .collect();
4958
4959 let rows = decode_luma_at(
4960 64,
4961 64,
4962 &[
4963 coded.into(),
4964 BlockCoeffs::default(),
4965 BlockCoeffs::default(),
4966 BlockCoeffs::default(),
4967 ],
4968 );
4969 let reconstruction =
4970 crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
4971
4972 let mut squared = 0.0f64;
4973 for row in 0..32 {
4974 for col in 0..32 {
4975 let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255);
4976 assert_eq!(
4977 i32::from(rows[row][col]),
4978 want,
4979 "sample ({row},{col}): the decoder and the encoder disagree"
4980 );
4981 let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]);
4982 squared += error * error;
4983 }
4984 }
4985 let rmse = (squared / 1024.0).sqrt();
4986 // A quantizer step is q/8 in residual units. Rounding to nearest
4987 // spreads the error over a step, and a quarter of one is a bound this
4988 // picture clears with room to spare (2.2 of 14 as written) while a
4989 // forward transform that is merely energy-preserving does not: a
4990 // transposed column pass measures 13.3 here.
4991 let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0;
4992 assert!(
4993 rmse < step / 4.0,
4994 "the decoded picture is {rmse} off, a step being {step}"
4995 );
4996 }
4997
4998 /// The inverse of [`write_mv_component`], mirroring [`SymbolDecoder`]
4999 /// against the spec's own `read_mv_component` pseudocode.
5000 fn decode_mv_component(
5001 dec: &mut crate::msac::tests::SymbolDecoder,
5002 c: &mut MvComponentCdfs,
5003 ) -> i32 {
5004 let sign = dec.symbol(&mut c.sign);
5005 let class = dec.symbol(&mut c.class);
5006 let local = if class == 0 {
5007 let bit = dec.symbol(&mut c.class0_bit);
5008 let fr = dec.symbol(&mut c.class0_fr[bit]);
5009 (bit << 3) | (fr << 1) | 1
5010 } else {
5011 let mut d = 0;
5012 for i in 0..class {
5013 d |= dec.symbol(&mut c.bit[i]) << i;
5014 }
5015 let fr = dec.symbol(&mut c.fr);
5016 (d << 3) | (fr << 1) | 1
5017 };
5018 let mag = mv_class_base(class) + local as i32 + 1;
5019 if sign == 1 { -mag } else { mag }
5020 }
5021
5022 /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,
5023 /// mirroring the writer's own context tracking (partition, skip,
5024 /// is_inter, and the MV stack) symbol for symbol against a fresh
5025 /// [`Cdfs`], so a desync between the two shows up as a wrong decoded
5026 /// value rather than a silent pass. Every block here is skipped, so no
5027 /// coefficient symbols are read. `wrong_y_mode` swaps in `KF_Y_MODE`'s
5028 /// (0, 0) row for an intra block's mode read, to show that reading the
5029 /// wrong table decodes the wrong mode rather than the one that was
5030 /// written.
5031 ///
5032 /// One decoded block's `(skip, is_inter, mode, mv)` — `mode` is `None`
5033 /// for an inter block, `mv` is `(0, 0)` for an intra one.
5034 type DecodedBlock = (bool, bool, Option<usize>, (i32, i32));
5035
5036 /// Returns the number of symbols and literals read, and each block's
5037 /// decoded state.
5038 fn decode_inter_sb(
5039 data: &[u8],
5040 mi_cols: u32,
5041 mi_rows: u32,
5042 wrong_y_mode: bool,
5043 ) -> (usize, Vec<DecodedBlock>) {
5044 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
5045 let mut cdfs = Cdfs::new(2);
5046 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
5047 let mut above_skip = [false; 2];
5048 let mut left_skip = [false; 2];
5049 let mut above_inter = [false; 2];
5050 let mut left_inter = [false; 2];
5051 let mut count = 0usize;
5052
5053 count += 1;
5054 dec.symbol(&mut cdfs.partition_w64[0]);
5055
5056 let mut results = Vec::new();
5057 for quadrant in 0..4usize {
5058 let (r32, c32) = (quadrant / 2, quadrant % 2);
5059 count += 1;
5060 dec.symbol(&mut cdfs.partition_w32[0]);
5061
5062 let (has_above, has_left) = (r32 > 0, c32 > 0);
5063 let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]);
5064 count += 1;
5065 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
5066
5067 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]);
5068 count += 1;
5069 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
5070
5071 let (mode, mv) = if is_inter {
5072 let sr_ctx = single_ref_ctx(above_inter[c32] || left_inter[r32]);
5073 count += 3;
5074 assert_eq!(
5075 dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
5076 0,
5077 "single_ref p1"
5078 );
5079 assert_eq!(
5080 dec.symbol(&mut cdfs.single_ref[sr_ctx][2]),
5081 0,
5082 "single_ref p3"
5083 );
5084 assert_eq!(
5085 dec.symbol(&mut cdfs.single_ref[sr_ctx][3]),
5086 0,
5087 "single_ref p4"
5088 );
5089
5090 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
5091 let stack = find_mv_stack(
5092 &grid,
5093 mi_row,
5094 mi_col,
5095 8,
5096 8,
5097 1,
5098 mi_cols as usize,
5099 mi_rows as usize,
5100 );
5101
5102 count += 1;
5103 let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0;
5104 let (mv, is_new_mv) = if new_mv {
5105 if stack.entries.len() > 1 {
5106 count += 1;
5107 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
5108 }
5109 count += 1;
5110 let joint = dec.symbol(&mut cdfs.mv_joint);
5111 let mut diff = (0, 0);
5112 if joint == 2 || joint == 3 {
5113 // sign, class, class0_bit, class0_fr for this test's
5114 // small (class 0) components.
5115 count += 4;
5116 diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]);
5117 }
5118 if joint == 1 || joint == 3 {
5119 count += 4;
5120 diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]);
5121 }
5122 ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true)
5123 } else {
5124 count += 2;
5125 assert_eq!(
5126 dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]),
5127 1,
5128 "zero_mv"
5129 );
5130 assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv");
5131 (stack.nearest_mv, false)
5132 };
5133 for dr in 0..8 {
5134 for dc in 0..8 {
5135 grid.set(
5136 mi_row + dr,
5137 mi_col + dc,
5138 MiInfo {
5139 is_inter: true,
5140 ref_frame: 1,
5141 ref_frame1: None,
5142 mv1: None,
5143 mv,
5144 is_new_mv,
5145 size: 8,
5146 size_h: 8,
5147 is_global_mv0: false,
5148 is_global_mv1: false,
5149 },
5150 );
5151 }
5152 }
5153 (None, mv)
5154 } else {
5155 count += 1;
5156 let m = if wrong_y_mode {
5157 dec.symbol(&mut cdfs.kf_y_mode[0][0])
5158 } else {
5159 dec.symbol(&mut cdfs.y_mode[3])
5160 };
5161 if (V_PRED..=D67_PRED).contains(&m) {
5162 count += 1;
5163 dec.symbol(&mut cdfs.angle_delta[m - V_PRED]);
5164 }
5165 count += 1;
5166 dec.symbol(&mut cdfs.uv_mode_cfl[m]);
5167 (Some(m), (0, 0))
5168 };
5169
5170 above_skip[c32] = skip;
5171 left_skip[r32] = skip;
5172 above_inter[c32] = is_inter;
5173 left_inter[r32] = is_inter;
5174 results.push((skip, is_inter, mode, mv));
5175 }
5176 (count, results)
5177 }
5178
5179 /// Every superblock here skips: no residual, so the only symbols are the
5180 /// mode chain, and the byte count and the symbol count both come out
5181 /// small enough to hand-check.
5182 #[test]
5183 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
5184 let block = BlockCoeffs {
5185 inter: Some(InterInfo {
5186 mode: InterMode::NearestMv,
5187 mv: (0, 0),
5188 }),
5189 skip: true,
5190 ..BlockCoeffs::default()
5191 };
5192 let blocks = vec![
5193 Quadrant::Whole(block.clone()),
5194 Quadrant::Whole(block.clone()),
5195 Quadrant::Whole(block.clone()),
5196 Quadrant::Whole(block),
5197 ];
5198 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
5199 // Hand count: one partition_w64, then per block partition_w32 + skip +
5200 // is_inter + 3 single_ref + new_mv + zero_mv + ref_mv = 9, times four.
5201 assert!(
5202 data.len() <= 16,
5203 "an all-skip NEARESTMV superblock took {} bytes",
5204 data.len()
5205 );
5206
5207 let (count, results) = decode_inter_sb(&data, 16, 16, false);
5208 assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count");
5209 for (skip, is_inter, mode, mv) in results {
5210 assert!(skip);
5211 assert!(is_inter);
5212 assert_eq!(mode, None);
5213 // Every block's only inter neighbours carry (0, 0), so the stack's
5214 // nearest candidate is (0, 0) throughout.
5215 assert_eq!(mv, (0, 0));
5216 }
5217 }
5218
5219 /// The fourth block codes NEWMV against a (0, 0) predictor with a coded
5220 /// column component: the symbol sequence a decoder reads back has to be
5221 /// exactly what [`write_mv`] wrote, not a residual that merely decodes
5222 /// to *some* valid vector.
5223 #[test]
5224 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
5225 let nearest = BlockCoeffs {
5226 inter: Some(InterInfo {
5227 mode: InterMode::NearestMv,
5228 mv: (0, 0),
5229 }),
5230 skip: true,
5231 ..BlockCoeffs::default()
5232 };
5233 let newmv = BlockCoeffs {
5234 inter: Some(InterInfo {
5235 mode: InterMode::NewMv,
5236 mv: (0, 2),
5237 }),
5238 skip: true,
5239 ..BlockCoeffs::default()
5240 };
5241 let blocks = vec![
5242 Quadrant::Whole(nearest.clone()),
5243 Quadrant::Whole(nearest.clone()),
5244 Quadrant::Whole(nearest),
5245 Quadrant::Whole(newmv),
5246 ];
5247 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
5248
5249 let (count, results) = decode_inter_sb(&data, 16, 16, false);
5250 // Three NEARESTMV blocks at 9 symbols each, one NEWMV block at
5251 // partition + skip + is_inter + 3 single_ref + new_mv + mv_joint +
5252 // (sign, class, class0_bit, class0_fr for the one nonzero component)
5253 // = 12, plus the superblock's partition_w64.
5254 assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count");
5255 let (skip, is_inter, mode, mv) = results[3];
5256 assert!(skip);
5257 assert!(is_inter);
5258 assert_eq!(mode, None);
5259 assert_eq!(
5260 mv,
5261 (0, 2),
5262 "the decoded motion vector must be exactly what was written"
5263 );
5264 }
5265
5266 /// Decodes only the first 32x32 block's mode symbol of a superblock: the
5267 /// tile's own first block always reads partition, skip and is_inter at
5268 /// context zero, so this needs none of [`decode_inter_sb`]'s neighbour
5269 /// bookkeeping — which matters here because the mutation this feeds
5270 /// desyncs everything after the one symbol it is testing, and a decoder
5271 /// that kept reading past it would be asserting on garbage.
5272 fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize {
5273 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
5274 let mut cdfs = Cdfs::new(2);
5275 dec.symbol(&mut cdfs.partition_w64[0]);
5276 dec.symbol(&mut cdfs.partition_w32[0]);
5277 dec.symbol(&mut cdfs.skip[0]);
5278 dec.symbol(&mut cdfs.intra_inter[0]);
5279 if wrong_y_mode {
5280 dec.symbol(&mut cdfs.kf_y_mode[0][0])
5281 } else {
5282 dec.symbol(&mut cdfs.y_mode[3])
5283 }
5284 }
5285
5286 /// An inter frame's intra block reads its mode against `Y_MODE`'s size
5287 /// group, not `KF_Y_MODE`'s neighbour-context table a key frame's block
5288 /// reads. Reading the wrong table back — `KF_Y_MODE`'s `(0, 0)` row —
5289 /// decodes a different mode than the one [`sb_coeff_inter_frame_tile`]
5290 /// wrote, because the two tables carry different default probabilities
5291 /// even though a row of each is the same fourteen-entry width. (The swap
5292 /// this test's name warns of does not typecheck as a one-line
5293 /// substitution at the write site either — `cdfs.kf_y_mode[3]` is a
5294 /// `[[u16; 14]; 5]` row, not the single `[u16; 14]` `Y_MODE` indexing
5295 /// needs — so a mutation that got the *outer* shape wrong would be
5296 /// caught by `cargo check` before it ever reached a test; this test is
5297 /// what catches getting the *right* leaf shape from the *wrong* table.)
5298 #[test]
5299 fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() {
5300 let block = BlockCoeffs {
5301 mode: H_PRED as u8,
5302 skip: true,
5303 ..BlockCoeffs::default()
5304 };
5305 let blocks = vec![Quadrant::Whole(block); 4];
5306 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
5307
5308 assert_eq!(
5309 decode_first_block_mode(&data, false),
5310 H_PRED,
5311 "the right table reads the mode back exactly"
5312 );
5313 assert_ne!(
5314 decode_first_block_mode(&data, true),
5315 H_PRED,
5316 "KF_Y_MODE's different probabilities must decode a different mode"
5317 );
5318 }
5319}