forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiBa5441e8Tahinli3 months ago1014 commits

tile.rs5298 lines, 216.3 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 fn have_ffmpeg() -> bool {
2987 Command::new("ffmpeg")
2988 .arg("-version")
2989 .stdout(Stdio::null())
2990 .stderr(Stdio::null())
2991 .status()
2992 .is_ok_and(|s| s.success())
2993 }
2994
2995 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
2996 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
2997 let mut child = Command::new("ffmpeg")
2998 .args([
2999 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3000 ])
3001 .stdin(Stdio::piped())
3002 .stdout(Stdio::piped())
3003 .stderr(Stdio::piped())
3004 .spawn()
3005 .expect("ffmpeg failed to start");
3006 child
3007 .stdin
3008 .take()
3009 .expect("ffmpeg stdin")
3010 .write_all(stream)
3011 .expect("writing the stream to ffmpeg");
3012 let out = child.wait_with_output().expect("ffmpeg failed to run");
3013 assert!(
3014 out.status.success(),
3015 "ffmpeg refused the stream: {}",
3016 String::from_utf8_lossy(&out.stderr)
3017 );
3018 assert_eq!(
3019 out.stdout.len(),
3020 w * h * 3 / 2,
3021 "expected one 4:2:0 frame, ffmpeg said: {}",
3022 String::from_utf8_lossy(&out.stderr)
3023 );
3024 out.stdout
3025 }
3026
3027 #[test]
3028 fn flat_key_frame_decodes_to_mid_grey() {
3029 if !have_ffmpeg() {
3030 eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH");
3031 return;
3032 }
3033 let seq = sequence_64();
3034 let header = flat_key_frame();
3035 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();
3036
3037 let mut stream = temporal_delimiter();
3038 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3039 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3040
3041 let planes = ffmpeg_decode(&stream, 64, 64);
3042 // A DC prediction with no neighbour to average is the middle of the
3043 // range, and a skipped block adds no residual, so every sample of every
3044 // plane is 128 — one wrong symbol anywhere in the tile shows up here.
3045 for (i, &s) in planes.iter().enumerate() {
3046 assert_eq!(s, 128, "sample {i} of the decoded frame");
3047 }
3048 }
3049
3050 /// The one q-context whose CDFs this crate carries; the decoded table
3051 /// below is pinned at this quantiser and nowhere else.
3052 const Q_IDX: u8 = 100;
3053
3054 /// Encode a 64x64 key frame carrying `dc_level` and hand back its planes.
3055 fn decode_dc_frame(dc_level: i32) -> Vec<u8> {
3056 let seq = sequence_64();
3057 let mut header = flat_key_frame();
3058 header.quantization.base_q_idx = Q_IDX;
3059 let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap();
3060 let mut stream = temporal_delimiter();
3061 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3062 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3063 ffmpeg_decode(&stream, 64, 64)
3064 }
3065
3066 /// What a reference decoder makes of each DC level at `base_q_idx` 100:
3067 /// the level times the DC quantiser, inverse-transformed over a whole
3068 /// 64x64 block — which spreads one coefficient over 4096 samples, so a
3069 /// level moves the picture by a sample or two, not by tens. These numbers
3070 /// are pinned from the decoder rather than derived: this crate has no
3071 /// inverse transform of its own yet to derive them with. What the test
3072 /// asserts around them — flat planes, untouched chroma, monotone in the
3073 /// level, and the sign going the right way — is derived, and it is what a
3074 /// desync in the coefficient syntax breaks first.
3075 const DECODED_AT_Q100: [(i32, u8); 28] = [
3076 (1, 128),
3077 (2, 128),
3078 (3, 129),
3079 (4, 129),
3080 (5, 129),
3081 (6, 129),
3082 (7, 129),
3083 (8, 129),
3084 (9, 130),
3085 (10, 130),
3086 (11, 130),
3087 (12, 130),
3088 (13, 130),
3089 (14, 131),
3090 (-1, 128),
3091 (-2, 128),
3092 (-3, 128),
3093 (-4, 127),
3094 (-5, 127),
3095 (-6, 127),
3096 (-7, 127),
3097 (-8, 127),
3098 (-9, 126),
3099 (-10, 126),
3100 (-11, 126),
3101 (-12, 126),
3102 (-13, 126),
3103 (-14, 126),
3104 ];
3105
3106 #[test]
3107 fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
3108 if !have_ffmpeg() {
3109 eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
3110 return;
3111 }
3112 let mut seen = Vec::new();
3113 for (level, want) in DECODED_AT_Q100 {
3114 let planes = decode_dc_frame(level);
3115 let (luma, chroma) = planes.split_at(64 * 64);
3116 for (i, &sample) in luma.iter().enumerate() {
3117 assert_eq!(sample, want, "luma sample {i} at dc level {level}");
3118 }
3119 // The chroma transform blocks are all-zero, so both planes stay at
3120 // the prediction. A desync in the luma coefficient syntax lands
3121 // here first: the chroma flags are the next symbols after it.
3122 for (i, &sample) in chroma.iter().enumerate() {
3123 assert_eq!(sample, 128, "chroma sample {i} at dc level {level}");
3124 }
3125 seen.push((level, want));
3126 }
3127 // The picture moves off mid-grey the way the level says: up for a
3128 // positive level, down for a negative one, and never back towards it
3129 // as the level grows.
3130 for w in seen.windows(2) {
3131 let ((prev_level, prev), (level, value)) = (w[0], w[1]);
3132 if prev_level.signum() != level.signum() {
3133 continue;
3134 }
3135 if level > 0 {
3136 assert!(
3137 value >= prev,
3138 "level {level} decoded below level {prev_level}"
3139 );
3140 assert!(value >= 128, "a positive level darkened the picture");
3141 } else {
3142 assert!(
3143 value <= prev,
3144 "level {level} decoded above level {prev_level}"
3145 );
3146 assert!(value <= 128, "a negative level brightened the picture");
3147 }
3148 }
3149 assert!(
3150 DECODED_AT_Q100.iter().any(|&(_, v)| v > 128)
3151 && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128),
3152 "the pinned table has to move the picture both ways"
3153 );
3154 }
3155
3156 /// Encode a grid of 64x64 superblocks, each carrying its own DC level, and
3157 /// hand back the decoded planes.
3158 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
3159 let (w, h) = (64 * sb_cols, 64 * sb_rows);
3160 let (seq, mut header) = frame_of(w, h);
3161 // The DC fixture writers code against the default CDFs and never
3162 // update them, so their frames say so.
3163 header.disable_cdf_update = true;
3164 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
3165 let mut stream = temporal_delimiter();
3166 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3167 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3168 ffmpeg_decode(&stream, w as usize, h as usize)
3169 }
3170
3171 /// A sequence and key frame header for a `w` by `h` frame of whole
3172 /// superblocks.
3173 fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) {
3174 let mut seq = sequence_64();
3175 seq.max_frame_width = w;
3176 seq.max_frame_height = h;
3177 let mut header = flat_key_frame();
3178 // Every tile these headers carry is written by the adapting writer.
3179 header.disable_cdf_update = false;
3180 header.frame_width = w;
3181 header.frame_height = h;
3182 header.upscaled_width = w;
3183 header.render_width = w;
3184 header.render_height = h;
3185 header.mi_cols = w / 4;
3186 header.mi_rows = h / 4;
3187 header.tile_info.mi_col_starts = vec![0, header.mi_cols];
3188 header.tile_info.mi_row_starts = vec![0, header.mi_rows];
3189 header.quantization.base_q_idx = Q_IDX;
3190 (seq, header)
3191 }
3192
3193 fn decoded_value(level: i32) -> u8 {
3194 DECODED_AT_Q100
3195 .iter()
3196 .find(|&&(l, _)| l == level)
3197 .map(|&(_, v)| v)
3198 .expect("the level is in the pinned table")
3199 }
3200
3201 /// `dc_predict` (spec 7.11.2) for the flat case: a block whose neighbours
3202 /// are themselves flat predicts their average, and predicts mid-grey with
3203 /// no neighbour at all. Every block here is a whole 64x64 superblock, so
3204 /// the above row and the left column weigh the same.
3205 fn dc_prediction(above: Option<u8>, left: Option<u8>) -> u8 {
3206 match (above, left) {
3207 (None, None) => 128,
3208 (Some(a), None) => a,
3209 (None, Some(l)) => l,
3210 (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8,
3211 }
3212 }
3213
3214 /// What a DC level adds to the prediction: the pinned table is that sum
3215 /// against a mid-grey prediction, and the residual does not depend on what
3216 /// it is added to.
3217 fn dc_residual(level: i32) -> i32 {
3218 i32::from(decoded_value(level)) - 128
3219 }
3220
3221 /// Every block reads its DC sign context off the coded blocks above and to
3222 /// its left, and the three ways that can land — no coded neighbour, the
3223 /// neighbours leaning one way, the neighbours cancelling — are only
3224 /// reachable in a frame whose levels differ in sign. Getting the context
3225 /// wrong desyncs the arithmetic decoder, so the check is that every block
3226 /// still decodes to the grey its own level asks for.
3227 #[test]
3228 fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {
3229 if !have_ffmpeg() {
3230 eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg");
3231 return;
3232 }
3233 // Read in raster order the two grids put a positive, a negative and a
3234 // cancelling sign context in front of the bottom-right block, and a
3235 // leaning-down one in front of the second grid's right and bottom
3236 // blocks.
3237 for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] {
3238 let planes = decode_level_grid(&levels, 2, 2);
3239 let (luma, chroma) = planes.split_at(128 * 128);
3240 // The blocks are not independent: a DC prediction reads the
3241 // reconstructed neighbours, so each block's grey is its
3242 // neighbours' average plus its own residual.
3243 let mut recon = [0u8; 4];
3244 for (block, level) in levels.iter().enumerate() {
3245 let (br, bc) = (block / 2, block % 2);
3246 let above = (br > 0).then(|| recon[block - 2]);
3247 let left = (bc > 0).then(|| recon[block - 1]);
3248 let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level))
3249 .clamp(0, 255) as u8;
3250 recon[block] = want;
3251 for y in 0..64 {
3252 for x in 0..64 {
3253 let i = (br * 64 + y) * 128 + bc * 64 + x;
3254 assert_eq!(
3255 luma[i], want,
3256 "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}"
3257 );
3258 }
3259 }
3260 }
3261 for (i, &sample) in chroma.iter().enumerate() {
3262 assert_eq!(sample, 128, "chroma sample {i} of {levels:?}");
3263 }
3264 }
3265 }
3266
3267 /// What a DC level adds to a 32x32 block's prediction at `base_q_idx` 100,
3268 /// pinned from the decoder the way [`DECODED_AT_Q100`] is. A 32x32
3269 /// transform spreads its DC over a quarter of the samples a 64x64 one
3270 /// does, so the same level moves the picture further: level 14 is five
3271 /// sample values here against three there.
3272 const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [
3273 (1, 0),
3274 (2, 1),
3275 (3, 1),
3276 (4, 1),
3277 (5, 2),
3278 (6, 2),
3279 (7, 3),
3280 (8, 3),
3281 (9, 3),
3282 (10, 4),
3283 (11, 4),
3284 (12, 4),
3285 (13, 5),
3286 (14, 5),
3287 (-1, 0),
3288 (-2, -1),
3289 (-3, -1),
3290 (-4, -1),
3291 (-5, -2),
3292 (-6, -2),
3293 (-7, -2),
3294 (-8, -3),
3295 (-9, -3),
3296 (-10, -4),
3297 (-11, -4),
3298 (-12, -4),
3299 (-13, -5),
3300 (-14, -5),
3301 ];
3302
3303 fn split_residual(level: i32) -> i32 {
3304 SPLIT_RESIDUAL_AT_Q100
3305 .iter()
3306 .find(|&&(l, _)| l == level)
3307 .map(|&(_, r)| r)
3308 .expect("the level is in the pinned table")
3309 }
3310
3311 /// Splitting a superblock puts three more syntax elements in front of every
3312 /// block — the split partition itself, the 32x32 partition below it and a
3313 /// chroma mode from the wider table CFL-capable blocks read — and moves the
3314 /// coefficients onto the 32x32 CDFs. Getting any of them wrong desyncs the
3315 /// arithmetic decoder, and the check is that all sixteen blocks still land
3316 /// on the grey their own level and their neighbours ask for.
3317 #[test]
3318 fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
3319 if !have_ffmpeg() {
3320 eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
3321 return;
3322 }
3323 // Four by four 32x32 blocks over two by two superblocks, so the walk
3324 // crosses superblock boundaries in both directions, and signs that
3325 // alternate so the DC sign context lands on all three of its values.
3326 let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1];
3327 let planes = decode_split_grid(&levels, 2, 2);
3328 let (luma, chroma) = planes.split_at(128 * 128);
3329
3330 let mut recon = [0i32; 16];
3331 for (block, level) in levels.iter().enumerate() {
3332 let (br, bc) = (block / 4, block % 4);
3333 let above = (br > 0).then(|| recon[block - 4] as u8);
3334 let left = (bc > 0).then(|| recon[block - 1] as u8);
3335 let want =
3336 (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255);
3337 recon[block] = want;
3338 for y in 0..32 {
3339 for x in 0..32 {
3340 let i = (br * 32 + y) * 128 + bc * 32 + x;
3341 assert_eq!(
3342 i32::from(luma[i]),
3343 want,
3344 "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \
3345 column {bc}"
3346 );
3347 }
3348 }
3349 }
3350 for (i, &sample) in chroma.iter().enumerate() {
3351 assert_eq!(sample, 128, "chroma sample {i}");
3352 }
3353 }
3354
3355 /// Encode a grid of 32x32 blocks, each carrying its own DC level.
3356 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
3357 let (w, h) = (64 * sb_cols, 64 * sb_rows);
3358 let (seq, mut header) = frame_of(w, h);
3359 // The DC fixture writers code against the default CDFs and never
3360 // update them, so their frames say so.
3361 header.disable_cdf_update = true;
3362 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
3363 let mut stream = temporal_delimiter();
3364 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3365 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3366 ffmpeg_decode(&stream, w as usize, h as usize)
3367 }
3368
3369 #[test]
3370 fn a_level_grid_that_does_not_cover_the_frame_is_refused() {
3371 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err());
3372 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err());
3373 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());
3374 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());
3375 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());
3376 }
3377
3378 #[test]
3379 fn dc_levels_the_base_syntax_cannot_carry_are_refused() {
3380 assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());
3381 assert!(dc_key_frame_tile(16, 16, 100, 15).is_err());
3382 assert!(dc_key_frame_tile(16, 16, 100, -15).is_err());
3383 }
3384
3385 #[test]
3386 fn partial_superblocks_are_refused() {
3387 assert!(flat_key_frame_tile(16, 20).is_err());
3388 assert!(flat_key_frame_tile(0, 16).is_err());
3389 }
3390
3391 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
3392 /// hands back the luma plane as rows of samples.
3393 fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {
3394 let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect();
3395 let [luma, u, v] = decode_coeff_planes(&blocks);
3396 for (name, plane) in [("U", &u), ("V", &v)] {
3397 for (y, row) in plane.iter().enumerate() {
3398 for (x, &s) in row.iter().enumerate() {
3399 assert_eq!(
3400 s, 128,
3401 "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \
3402 DC prediction with no coded neighbour is mid-grey"
3403 );
3404 }
3405 }
3406 }
3407 luma
3408 }
3409
3410 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
3411 /// hands back its three planes as rows of samples: 64 rows of luma and, at
3412 /// 4:2:0, 32 rows of each chroma plane.
3413 fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] {
3414 let (seq, header) = frame_of(64, 64);
3415 let tile =
3416 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
3417 let mut stream = temporal_delimiter();
3418 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3419 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3420 let planes = ffmpeg_decode(&stream, 64, 64);
3421 let (luma, chroma) = planes.split_at(64 * 64);
3422 let (u, v) = chroma.split_at(32 * 32);
3423 [
3424 luma.chunks_exact(64).map(<[u8]>::to_vec).collect(),
3425 u.chunks_exact(32).map(<[u8]>::to_vec).collect(),
3426 v.chunks_exact(32).map(<[u8]>::to_vec).collect(),
3427 ]
3428 }
3429
3430 /// The top-left 32x32 block of a decoded frame, which is the only one whose
3431 /// prediction has no neighbour to lean on.
3432 fn top_left_block(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
3433 rows[..32].iter().map(|r| r[..32].to_vec()).collect()
3434 }
3435
3436 /// A transform's basis functions all average to zero except the DC's, so a
3437 /// block carrying no DC decodes to samples that average to its prediction —
3438 /// mid-grey for the block with no neighbours. Rounding of the inverse
3439 /// transform moves the average by less than a sample.
3440 fn assert_mean_is_mid_grey(block: &[Vec<u8>]) {
3441 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
3442 let mean = f64::from(sum) / (32.0 * 32.0);
3443 assert!(
3444 (mean - 128.0).abs() <= 1.0,
3445 "a block with no DC coefficient averages to its mid-grey prediction, got {mean}"
3446 );
3447 }
3448
3449 /// A coefficient at row 0, column 1 selects the basis function that is flat
3450 /// down the block and a half-cycle of a cosine across it. Nothing about
3451 /// that shape is pinned here: every row of the block must be the same row,
3452 /// the samples must fall from left to right and actually move, and the
3453 /// block must still average to its prediction. A desync in the scan, the
3454 /// end-of-block position or the level contexts breaks one of those.
3455 #[test]
3456 fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
3457 if !have_ffmpeg() {
3458 eprintln!(
3459 "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg"
3460 );
3461 return;
3462 }
3463 let blocks = vec![
3464 vec![Coeff {
3465 row: 0,
3466 col: 1,
3467 level: 12,
3468 }],
3469 Vec::new(),
3470 Vec::new(),
3471 Vec::new(),
3472 ];
3473 let rows = decode_coeff_quadrants(&blocks);
3474 let block = top_left_block(&rows);
3475
3476 for (y, row) in block.iter().enumerate() {
3477 assert_eq!(row, &block[0], "row {y} of a horizontal basis function");
3478 }
3479 assert!(
3480 block[0][0] > block[0][31],
3481 "a positive coefficient leans the block towards its left edge: {:?}",
3482 block[0]
3483 );
3484 for x in 1..32 {
3485 assert!(
3486 block[0][x] <= block[0][x - 1],
3487 "the half-cycle falls from left to right, broke at column {x}: {:?}",
3488 block[0]
3489 );
3490 }
3491 assert_mean_is_mid_grey(&block);
3492
3493 // The same coefficient transposed selects the basis function that is
3494 // flat across the block and a half-cycle down it.
3495 let blocks = vec![
3496 vec![Coeff {
3497 row: 1,
3498 col: 0,
3499 level: 12,
3500 }],
3501 Vec::new(),
3502 Vec::new(),
3503 Vec::new(),
3504 ];
3505 let rows = decode_coeff_quadrants(&blocks);
3506 let block = top_left_block(&rows);
3507 for (y, row) in block.iter().enumerate() {
3508 for (x, &s) in row.iter().enumerate() {
3509 assert_eq!(s, row[0], "sample ({y},{x}) of a vertical basis function");
3510 }
3511 }
3512 assert!(
3513 block[0][0] > block[31][0],
3514 "a positive coefficient leans the block up"
3515 );
3516 for y in 1..32 {
3517 assert!(
3518 block[y][0] <= block[y - 1][0],
3519 "the half-cycle falls from top to bottom, broke at row {y}"
3520 );
3521 }
3522 assert_mean_is_mid_grey(&block);
3523 }
3524
3525 /// A coefficient late in the scan pushes the end-of-block position into a
3526 /// group that carries an offset — the far corner of a 32x32 transform is
3527 /// the last of the eleven groups, whose offset is nine bits wide, one of
3528 /// them from a CDF and the rest raw. Every coefficient before it is coded
3529 /// too, so this also walks the base and base-range contexts over a block
3530 /// with neighbours that carry levels rather than zeros.
3531 #[test]
3532 fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {
3533 if !have_ffmpeg() {
3534 eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group");
3535 return;
3536 }
3537 let block = vec![
3538 Coeff {
3539 row: 31,
3540 col: 31,
3541 level: 5,
3542 },
3543 Coeff {
3544 row: 5,
3545 col: 7,
3546 level: -9,
3547 },
3548 Coeff {
3549 row: 1,
3550 col: 1,
3551 level: 14,
3552 },
3553 Coeff {
3554 row: 0,
3555 col: 2,
3556 level: -3,
3557 },
3558 Coeff {
3559 row: 2,
3560 col: 0,
3561 level: 2,
3562 },
3563 Coeff {
3564 row: 1,
3565 col: 2,
3566 level: -1,
3567 },
3568 ];
3569 let rows = decode_coeff_quadrants(&[block, Vec::new(), Vec::new(), Vec::new()]);
3570 let block = top_left_block(&rows);
3571 assert_mean_is_mid_grey(&block);
3572 assert!(
3573 block.iter().flatten().any(|&s| s != block[0][0]),
3574 "six coefficients do not decode to a flat block"
3575 );
3576 // The blocks that carry nothing are flat: their prediction is whatever
3577 // their neighbours left, and they add no residual to it.
3578 for (name, ys, xs) in [("top right", 0..32, 32..64), ("bottom left", 32..64, 0..32)] {
3579 let first = rows[ys.start][xs.start];
3580 for y in ys {
3581 for x in xs.clone() {
3582 assert_eq!(rows[y][x], first, "the {name} block carries no coefficient");
3583 }
3584 }
3585 }
3586 }
3587
3588 /// The price the mode search pays for a block's levels has to be the price
3589 /// the writer charges for them, or the search is ranking modes by a
3590 /// fiction. Both halves are asked for the same grids under the same
3591 /// neutral contexts, and the priced bits are compared against the bytes
3592 /// the writer really spends.
3593 #[test]
3594 fn the_priced_coefficient_bits_match_the_bytes_written() {
3595 let scan = default_scan(TX32);
3596 // Three grids that reach different parts of the syntax: a lone DC, a
3597 // sparse spread of small levels with both signs, and levels past the
3598 // base-range alphabet so the Golomb tail runs.
3599 let mut grids = vec![vec![0i32; TX32 * TX32]; 3];
3600 grids[0][0] = -7;
3601 for (i, &pos) in scan.iter().enumerate().take(400) {
3602 if i % 7 == 0 {
3603 grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 };
3604 }
3605 }
3606 grids[2][0] = 40;
3607 for (i, &pos) in scan.iter().enumerate().take(64) {
3608 grids[2][pos as usize] += i as i32 % 23 - 11;
3609 }
3610
3611 // A single block is too short for the coder's own flush to average
3612 // out, so all three go through one encoder and one flush.
3613 let mut enc = SymbolEncoder::new();
3614 let mut priced = 0.0;
3615 for grid in &grids {
3616 write_coeffs(
3617 &mut enc,
3618 &mut Cdfs::new(2).txb(TxbSet::Luma32, 0),
3619 grid,
3620 &scan,
3621 0,
3622 0,
3623 None,
3624 );
3625 priced += luma_32_coeff_bits(grid);
3626 }
3627 let spent = enc.finish().len() as f64 * 8.0;
3628 assert!(
3629 (priced - spent).abs() / spent < 0.02,
3630 "priced {priced} bits, wrote {spent}"
3631 );
3632 }
3633
3634 /// A rate term the search can read as constant is a rate term that ranks
3635 /// nothing, so the price is checked to move the way the levels move: an
3636 /// empty block is the cheapest thing there is, one coefficient costs more
3637 /// than none, and both spreading the coefficients and growing them costs
3638 /// more again.
3639 #[test]
3640 fn the_price_grows_with_the_levels() {
3641 let grid = |f: &dyn Fn(&mut Vec<i32>)| {
3642 let mut g = vec![0i32; TX32 * TX32];
3643 f(&mut g);
3644 luma_32_coeff_bits(&g)
3645 };
3646 let empty = grid(&|_| {});
3647 let one = grid(&|g| g[0] = 1);
3648 let bigger = grid(&|g| g[0] = 30);
3649 let spread = grid(&|g| {
3650 for i in 0..TX32 {
3651 g[i * TX32 + i] = 1;
3652 }
3653 });
3654 assert!(empty < one, "{empty} {one}");
3655 assert!(one < bigger, "{one} {bigger}");
3656 assert!(one < spread, "{one} {spread}");
3657 // An empty block is one symbol -- an expensive one, because a block
3658 // with no coefficients at all is the rarer of the two under the
3659 // neutral context -- and nothing else.
3660 assert!(
3661 empty < 6.0,
3662 "an empty block is one skip symbol, not {empty}"
3663 );
3664 }
3665
3666 /// Neighbouring blocks that each carry coefficients read their DC sign
3667 /// context, their prediction and their own contexts off each other, so a
3668 /// frame whose four blocks all carry mixed-sign coefficients exercises what
3669 /// a single coded block cannot. The check is that it decodes at all — a
3670 /// desync anywhere fails the decode or the frame size — and that the block
3671 /// with no neighbours still averages to mid-grey.
3672 #[test]
3673 fn every_quadrant_carries_its_own_coefficients() {
3674 if !have_ffmpeg() {
3675 eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg");
3676 return;
3677 }
3678 let blocks = vec![
3679 vec![
3680 Coeff {
3681 row: 0,
3682 col: 1,
3683 level: 7,
3684 },
3685 Coeff {
3686 row: 3,
3687 col: 4,
3688 level: -14,
3689 },
3690 ],
3691 vec![
3692 Coeff {
3693 row: 0,
3694 col: 0,
3695 level: -6,
3696 },
3697 Coeff {
3698 row: 2,
3699 col: 2,
3700 level: 9,
3701 },
3702 ],
3703 vec![
3704 Coeff {
3705 row: 0,
3706 col: 0,
3707 level: 6,
3708 },
3709 Coeff {
3710 row: 1,
3711 col: 0,
3712 level: -2,
3713 },
3714 Coeff {
3715 row: 8,
3716 col: 9,
3717 level: 3,
3718 },
3719 ],
3720 vec![
3721 Coeff {
3722 row: 0,
3723 col: 0,
3724 level: 11,
3725 },
3726 Coeff {
3727 row: 16,
3728 col: 1,
3729 level: -4,
3730 },
3731 ],
3732 ];
3733 let rows = decode_coeff_quadrants(&blocks);
3734 assert_mean_is_mid_grey(&top_left_block(&rows));
3735 for (name, ys, xs) in [
3736 ("top right", 0..32, 32..64),
3737 ("bottom left", 32..64, 0..32),
3738 ("bottom right", 32..64, 32..64),
3739 ] {
3740 let block: Vec<Vec<u8>> = rows[ys].iter().map(|r| r[xs.clone()].to_vec()).collect();
3741 assert!(
3742 block.iter().flatten().any(|&s| s != block[0][0]),
3743 "the {name} block carries coefficients, so it is not flat"
3744 );
3745 }
3746 }
3747
3748 /// The top-left 16x16 block of a decoded chroma plane, which is the only
3749 /// one whose prediction has no neighbour to lean on.
3750 fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
3751 rows[..16].iter().map(|r| r[..16].to_vec()).collect()
3752 }
3753
3754 /// The mean of a decoded block, which every basis function but the DC's
3755 /// leaves at the block's prediction.
3756 fn mean(block: &[Vec<u8>]) -> f64 {
3757 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
3758 let count = block.iter().map(Vec::len).sum::<usize>() as f64;
3759 f64::from(sum) / count
3760 }
3761
3762 /// A chroma plane's coefficients ride their own transform, their own CDFs
3763 /// and their own end-of-block alphabet, so a chroma basis function is the
3764 /// gate on all three: U carries the coefficient that is flat down the block
3765 /// and a half-cycle across it, V the one turned a quarter turn, and neither
3766 /// may reach the other plane or luma.
3767 #[test]
3768 fn each_chroma_plane_codes_its_own_basis_function() {
3769 if !have_ffmpeg() {
3770 eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
3771 return;
3772 }
3773 let mut blocks = vec![BlockCoeffs::default(); 4];
3774 blocks[0].u = vec![Coeff {
3775 row: 0,
3776 col: 1,
3777 level: 12,
3778 }];
3779 blocks[0].v = vec![Coeff {
3780 row: 1,
3781 col: 0,
3782 level: 12,
3783 }];
3784 let [luma, u, v] = decode_coeff_planes(&blocks);
3785
3786 for (y, row) in luma.iter().enumerate() {
3787 for (x, &s) in row.iter().enumerate() {
3788 assert_eq!(
3789 s, 128,
3790 "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \
3791 stays at its mid-grey prediction"
3792 );
3793 }
3794 }
3795
3796 let u_block = top_left_chroma(&u);
3797 for (y, row) in u_block.iter().enumerate() {
3798 assert_eq!(
3799 row, &u_block[0],
3800 "row {y} of a horizontal chroma basis function"
3801 );
3802 }
3803 assert!(
3804 u_block[0][0] > u_block[0][15],
3805 "a positive coefficient leans the U block towards its left edge: {:?}",
3806 u_block[0]
3807 );
3808
3809 let v_block = top_left_chroma(&v);
3810 for (x, &top) in v_block[0].iter().enumerate() {
3811 assert_eq!(
3812 top, v_block[0][0],
3813 "column {x} of a vertical chroma basis function"
3814 );
3815 let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect();
3816 assert!(
3817 column[0] > column[15],
3818 "a positive coefficient leans the V column towards its top edge: {column:?}"
3819 );
3820 }
3821
3822 for (name, block) in [("U", &u_block), ("V", &v_block)] {
3823 let mean = mean(block);
3824 assert!(
3825 (mean - 128.0).abs() <= 1.0,
3826 "the {name} block carries no DC, so it averages to its mid-grey prediction, \
3827 got {mean}"
3828 );
3829 }
3830 }
3831
3832 /// Every block coding chroma puts the chroma all-zero flag on the contexts
3833 /// a coded neighbour above and to the left select, and the DC sign on the
3834 /// contexts their signs select. A frame whose four blocks all carry chroma
3835 /// DCs of mixed sign walks those contexts; the picture that comes back must
3836 /// still lean the way each block's own DC asks.
3837 #[test]
3838 fn chroma_dc_signs_read_their_neighbours() {
3839 if !have_ffmpeg() {
3840 eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
3841 return;
3842 }
3843 let dc = |level| {
3844 vec![Coeff {
3845 row: 0,
3846 col: 0,
3847 level,
3848 }]
3849 };
3850 let signs = [8, -8, -8, 8];
3851 let blocks: Vec<BlockCoeffs> = signs
3852 .iter()
3853 .map(|&level| BlockCoeffs {
3854 luma: Vec::new(),
3855 u: dc(level),
3856 v: dc(-level),
3857 ..BlockCoeffs::default()
3858 })
3859 .collect();
3860 let [luma, u, v] = decode_coeff_planes(&blocks);
3861
3862 for (y, row) in luma.iter().enumerate() {
3863 for (x, &s) in row.iter().enumerate() {
3864 assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient");
3865 }
3866 }
3867
3868 // A DC prediction leans on the neighbours a block has, so each block is
3869 // measured against the prediction it was given rather than mid-grey:
3870 // the only block with no neighbour is the first, and the rest are read
3871 // as a step away from the block above them and to their left.
3872 for (i, &level) in signs.iter().enumerate() {
3873 let (r, c) = (i / 2, i % 2);
3874 let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> {
3875 plane[r * 16..r * 16 + 16]
3876 .iter()
3877 .map(|row| row[c * 16..c * 16 + 16].to_vec())
3878 .collect()
3879 };
3880 for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] {
3881 let block = block(plane);
3882 let mean = mean(&block);
3883 for (y, row) in block.iter().enumerate() {
3884 assert_eq!(
3885 row.iter().collect::<std::collections::HashSet<_>>().len(),
3886 1,
3887 "row {y} of a DC-only {name} block is flat"
3888 );
3889 }
3890 if i == 0 {
3891 assert!(
3892 (want > 0) == (mean > 128.0),
3893 "{name} block {i} carries a DC of {want}, so it must lean off its \
3894 mid-grey prediction that way, got {mean}"
3895 );
3896 }
3897 }
3898 }
3899 assert_ne!(u, v, "the two chroma planes carry opposite DCs");
3900 }
3901
3902 /// The coefficient writer refuses what it cannot code rather than writing a
3903 /// stream a decoder walks off the end of.
3904 /// The 32x32 block at the given block row and column of a decoded plane.
3905 fn block_at(rows: &[Vec<u8>], block_row: usize, block_col: usize) -> Vec<Vec<u8>> {
3906 rows[block_row * 32..block_row * 32 + 32]
3907 .iter()
3908 .map(|r| r[block_col * 32..block_col * 32 + 32].to_vec())
3909 .collect()
3910 }
3911
3912 /// Encodes a key frame of the given size, whose 32x32 blocks carry
3913 /// `blocks` in raster order, and hands back its luma plane as rows of
3914 /// The neighbour context a block reads is gathered across every cell it
3915 /// spans, not taken from the first one: a 32x32 block whose left-hand
3916 /// neighbour cells disagree still sees the coded one. Reading a single
3917 /// cell agreed with the decoder only while every block was the same size,
3918 /// and desynchronised the arithmetic decoder the moment a 16x16 one
3919 /// appeared beside a 32x32 one.
3920 #[test]
3921 fn a_block_gathers_the_cells_its_neighbours_cover() {
3922 let mut neighbours = Neighbours::new(4, 4, 64, 64);
3923 let quiet = [
3924 vec![0i32; TX16 * TX16],
3925 vec![0; TX8 * TX8],
3926 vec![0; TX8 * TX8],
3927 ];
3928 let mut loud = quiet.clone();
3929 loud[1][0] = -3;
3930 // Two 16x16 blocks above the right-hand 32x32 block of the row, of
3931 // which only the second codes anything.
3932 neighbours.record((0, 2), SUB, DC_PRED, &quiet);
3933 neighbours.record((0, 3), SUB, DC_PRED, &loud);
3934 let around = neighbours.around((2, 2), BLOCK);
3935 assert!(
3936 around[1].above_coded,
3937 "the coded cell has to reach the block below it"
3938 );
3939 assert_eq!(
3940 dc_sign_ctx(around[1].dc_vote),
3941 1,
3942 "the one negative DC above the block is what it votes"
3943 );
3944 // The same read one cell at a time misses it, which is the bug this
3945 // gate is here for. `above[8]` is the first 4x4 unit the quiet block
3946 // at `(0, 2)` wrote (2 SUB units * 4 4x4-units-per-SUB).
3947 assert!(!neighbours.above[8][1].coded);
3948 }
3949
3950 /// samples.
3951 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
3952 let (seq, header) = frame_of(width as u32, height as u32);
3953 let tile =
3954 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
3955 let mut stream = temporal_delimiter();
3956 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3957 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3958 let planes = ffmpeg_decode(&stream, width, height);
3959 planes[..width * height]
3960 .chunks_exact(width)
3961 .map(<[u8]>::to_vec)
3962 .collect()
3963 }
3964
3965 /// Every row of a block is the same row, and that row falls from left to
3966 /// right — the shape of a coefficient at row 0, column 1.
3967 fn assert_falls_across(block: &[Vec<u8>], name: &str) {
3968 for row in block {
3969 assert_eq!(
3970 row, &block[0],
3971 "{name}: every row of the block is the same row"
3972 );
3973 }
3974 assert!(
3975 block[0][0] > block[0][31],
3976 "{name}: the row falls from left to right, got {} then {}",
3977 block[0][0],
3978 block[0][31]
3979 );
3980 }
3981
3982 /// Every column of a block is constant across it and falls down it — the
3983 /// shape of a coefficient at row 1, column 0.
3984 fn assert_falls_down(block: &[Vec<u8>], name: &str) {
3985 for (y, row) in block.iter().enumerate() {
3986 assert!(
3987 row.iter().all(|&s| s == row[0]),
3988 "{name}: row {y} of the block is one constant"
3989 );
3990 }
3991 assert!(
3992 block[0][0] > block[31][0],
3993 "{name}: the column falls down the block, got {} then {}",
3994 block[0][0],
3995 block[31][0]
3996 );
3997 }
3998
3999 /// The mean sample of a decoded block.
4000 fn mean_of(block: &[Vec<u8>]) -> f64 {
4001 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
4002 f64::from(sum) / (block.len() * block[0].len()) as f64
4003 }
4004
4005 /// The top-left block of a frame whose only coefficient is a luma DC of
4006 /// `level`.
4007 fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> {
4008 let blocks = vec![
4009 vec![Coeff {
4010 row: 0,
4011 col: 0,
4012 level,
4013 }],
4014 Vec::new(),
4015 Vec::new(),
4016 Vec::new(),
4017 ];
4018 top_left_block(&decode_coeff_quadrants(&blocks))
4019 }
4020
4021 /// `read_golomb` (spec 5.11.40), written from the specification's
4022 /// pseudocode, and the level its caller builds from it: a level above the
4023 /// base-range tail is fifteen plus what the tail carries.
4024 fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 {
4025 let mut length = 0;
4026 while dec.literal(1) == 0 {
4027 length += 1;
4028 assert!(
4029 length < 20,
4030 "the tail's length prefix runs past twenty bits"
4031 );
4032 }
4033 let mut x = 1;
4034 for _ in 0..length {
4035 x = (x << 1) | dec.literal(1);
4036 }
4037 (MAX_BR_LEVEL + 1) as u32 + (x - 1)
4038 }
4039
4040 /// The tail says how much of the level the base and base-range syntax could
4041 /// not carry, and the spec's own reader must hand back the level that was
4042 /// asked for — not one either side of it. A tail written a bit long, a bit
4043 /// short, or against the wrong base fails this at the first level it
4044 /// reaches.
4045 #[test]
4046 fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
4047 for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300)
4048 .chain([MAX_LEVEL - 1, MAX_LEVEL])
4049 .map(|l| l as u32)
4050 {
4051 let mut enc = SymbolEncoder::new();
4052 write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32);
4053 // The tail is raw bits, so it needs no padding beyond what the
4054 // encoder's own flush writes.
4055 let data = enc.finish();
4056 let mut dec = crate::msac::tests::SymbolDecoder::new(&data);
4057 assert_eq!(
4058 read_golomb_level(&mut dec),
4059 level,
4060 "the tail of level {level}"
4061 );
4062 }
4063 }
4064
4065 /// The base and base-range syntax reach level fourteen between them;
4066 /// anything above that carries the rest of itself as a Golomb tail, written
4067 /// after its own sign. A DC level moves the whole block off its mid-grey
4068 /// prediction by an amount that grows with the level, so a run of levels
4069 /// either side of the tail's threshold — spaced wide enough that the
4070 /// quantiser separates them — must decode to a run of steadily
4071 /// brighter blocks — and the negatives of the same levels to steadily
4072 /// darker ones. A tail written with the wrong length, in the wrong place in
4073 /// the syntax, or off by one desyncs the decoder outright.
4074 #[test]
4075 fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
4076 if !have_ffmpeg() {
4077 eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
4078 return;
4079 }
4080 let mut brighter = Vec::new();
4081 let mut darker = Vec::new();
4082 for level in [10, 14, 18, 31, 60, 400] {
4083 brighter.push((level, mean_of(&decode_dc_level_block(level))));
4084 darker.push((level, mean_of(&decode_dc_level_block(-level))));
4085 }
4086 for pair in brighter.windows(2) {
4087 let [(low, dim), (high, bright)] = [pair[0], pair[1]];
4088 assert!(
4089 bright > dim,
4090 "level {high} decodes brighter than level {low}, got {bright} against {dim}"
4091 );
4092 }
4093 for pair in darker.windows(2) {
4094 let [(low, bright), (high, dim)] = [pair[0], pair[1]];
4095 assert!(
4096 dim < bright,
4097 "level -{high} decodes darker than level -{low}, got {dim} against {bright}"
4098 );
4099 }
4100 let (_, mid) = brighter[0];
4101 assert!(
4102 mid > 128.0 && darker[0].1 < 128.0,
4103 "a positive level brightens its block and a negative one darkens it, got {mid} and {}",
4104 darker[0].1
4105 );
4106 }
4107
4108 /// A frame need not be a whole number of superblocks. A 96x64 frame is a
4109 /// superblock and a half across: the second superblock has no right-hand
4110 /// half, so its partition is a gathered flag rather than the full symbol,
4111 /// and the two blocks that would sit in that half are never coded at all.
4112 /// Each of the six blocks that do exist carries one of two basis functions,
4113 /// alternating, so a block written into the wrong place or a flag the
4114 /// decoder reads as a different number of bits shows up as a block with the
4115 /// other block's shape — or as a decode failure.
4116 fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8>> {
4117 let (seq, header) = frame_of(width as u32, height as u32);
4118 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap();
4119 let mut stream = temporal_delimiter();
4120 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
4121 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
4122 let planes = ffmpeg_decode(&stream, width, height);
4123 planes[..width * height]
4124 .chunks_exact(width)
4125 .map(<[u8]>::to_vec)
4126 .collect()
4127 }
4128
4129 /// A superblock left whole carries one 64x64 transform, whose lowest
4130 /// horizontal basis function falls across the whole sixty-four samples in
4131 /// one stroke. Were the same superblock split, each half would restart the
4132 /// gradient at its own left edge and the picture would rise again in the
4133 /// middle, so the walk across the row is what tells the two apart — and
4134 /// the split superblock beside it proves the two partitions still agree on
4135 /// where the next one begins.
4136 #[test]
4137 fn a_whole_superblock_covers_all_four_of_its_quadrants() {
4138 if !have_ffmpeg() {
4139 eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg");
4140 return;
4141 }
4142 let across = BlockCoeffs::from(vec![Coeff {
4143 row: 0,
4144 col: 1,
4145 level: 20,
4146 }]);
4147 let down = BlockCoeffs::from(vec![Coeff {
4148 row: 1,
4149 col: 0,
4150 level: 20,
4151 }]);
4152 let sbs = [
4153 Superblock::Whole(across),
4154 Superblock::Split(vec![
4155 Quadrant::Whole(down.clone()),
4156 Quadrant::Whole(down.clone()),
4157 Quadrant::Whole(down.clone()),
4158 Quadrant::Whole(down),
4159 ]),
4160 ];
4161 let rows = decode_luma_sb(128, 64, &sbs);
4162
4163 for (y, row) in rows.iter().enumerate() {
4164 assert_eq!(
4165 &row[..64],
4166 &rows[0][..64],
4167 "row {y} of the whole superblock repeats its first row"
4168 );
4169 }
4170 let first = &rows[0][..64];
4171 assert!(
4172 first.windows(2).all(|w| w[0] >= w[1]),
4173 "the whole superblock falls across its sixty-four samples without \
4174 restarting: {first:?}"
4175 );
4176 assert!(
4177 first[0] > first[63],
4178 "the whole superblock falls from left to right, got {} then {}",
4179 first[0],
4180 first[63]
4181 );
4182 for block_row in 0..2 {
4183 for block_col in 2..4 {
4184 let block = block_at(&rows, block_row, block_col);
4185 assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})"));
4186 }
4187 }
4188 }
4189
4190 /// A quadrant may be split again into four 16x16 blocks, each carrying its
4191 /// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block
4192 /// makes each of the four a flat grey of its own, so the quadrant reads as
4193 /// four squares rather than one — which is what tells the extra split from
4194 /// a 32x32 block that merely carries the same coefficients.
4195 #[test]
4196 fn a_quadrant_splits_into_four_sixteens() {
4197 if !have_ffmpeg() {
4198 eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
4199 return;
4200 }
4201 let dc = |level: i32| {
4202 BlockCoeffs::from(vec![Coeff {
4203 row: 0,
4204 col: 0,
4205 level,
4206 }])
4207 };
4208 let levels = [14, 8, -8, -14];
4209 let flat = BlockCoeffs::from(Vec::new());
4210 let sbs = [Superblock::Split(vec![
4211 Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()),
4212 Quadrant::Whole(flat.clone()),
4213 Quadrant::Whole(flat.clone()),
4214 Quadrant::Whole(flat),
4215 ])];
4216 let rows = decode_luma_sb(64, 64, &sbs);
4217
4218 let mut greys = Vec::new();
4219 for i in 0..levels.len() {
4220 let (y0, x0) = ((i / 2) * 16, (i % 2) * 16);
4221 let grey = rows[y0][x0];
4222 for (y, row) in rows.iter().enumerate().skip(y0).take(16) {
4223 for (x, &sample) in row.iter().enumerate().skip(x0).take(16) {
4224 assert_eq!(
4225 sample, grey,
4226 "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not"
4227 );
4228 }
4229 }
4230 greys.push(grey);
4231 }
4232
4233 // Each block is predicted DC from the blocks the decoder has already
4234 // rebuilt, so what its own level does is move it off that prediction,
4235 // in the level's own direction.
4236 let g = |i: usize| i32::from(greys[i]);
4237 let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2];
4238 for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() {
4239 assert_eq!(
4240 (g(i) - prediction).signum(),
4241 level.signum(),
4242 "the 16x16 block {i} carries level {level}, so it sits on the \
4243 {} side of the {prediction} its neighbours predict, not at {}",
4244 if level > 0 { "bright" } else { "dark" },
4245 g(i)
4246 );
4247 }
4248 assert_eq!(
4249 greys.iter().collect::<std::collections::HashSet<_>>().len(),
4250 4,
4251 "the four blocks are four different greys, not one: {greys:?}"
4252 );
4253 }
4254
4255 /// A superblock half outside the frame has no partition that keeps a block
4256 /// outside it, so it cannot be left whole.
4257 #[test]
4258 fn a_whole_superblock_at_the_frame_edge_is_refused() {
4259 let block = BlockCoeffs::from(vec![Coeff {
4260 row: 0,
4261 col: 0,
4262 level: 4,
4263 }]);
4264 let sbs = [
4265 Superblock::Split(vec![
4266 Quadrant::Whole(block.clone()),
4267 Quadrant::Whole(block.clone()),
4268 Quadrant::Whole(block.clone()),
4269 Quadrant::Whole(block.clone()),
4270 ]),
4271 Superblock::Whole(block.clone()),
4272 ];
4273 // Ninety-six samples across is three 32x32 blocks, so the second
4274 // superblock hangs half outside the frame.
4275 let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err();
4276 assert!(
4277 format!("{err}").contains("half outside the frame"),
4278 "got {err}"
4279 );
4280 }
4281
4282 #[test]
4283 fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
4284 if !have_ffmpeg() {
4285 eprintln!(
4286 "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \
4287 ffmpeg"
4288 );
4289 return;
4290 }
4291 let blocks: Vec<BlockCoeffs> = (0..6)
4292 .map(|i| {
4293 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
4294 BlockCoeffs::from(vec![Coeff {
4295 row,
4296 col,
4297 level: 12,
4298 }])
4299 })
4300 .collect();
4301 let rows = decode_luma_at(96, 64, &blocks);
4302 for block_row in 0..2 {
4303 for block_col in 0..3 {
4304 let name = format!("block ({block_row},{block_col})");
4305 let block = block_at(&rows, block_row, block_col);
4306 if (block_row * 3 + block_col) % 2 == 0 {
4307 assert_falls_across(&block, &name);
4308 } else {
4309 assert_falls_down(&block, &name);
4310 }
4311 }
4312 }
4313 }
4314
4315 /// The transpose of [`a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block`]:
4316 /// an odd number of 32x32 block *rows* (superblock hangs off the
4317 /// *bottom*, `has_cols=true, has_rows=false`) rather than an odd number of
4318 /// columns (hangs off the *right*, `has_cols=false, has_rows=true`) --
4319 /// the two halves of the `(has_cols, has_rows)` match in
4320 /// `sb_coeff_key_frame_tile` gather from different tables
4321 /// (`VERT_ALIKE`/`HORZ_ALIKE`), and only the right-hand-edge direction had
4322 /// a real-decoder test before this one.
4323 #[test]
4324 fn a_frame_that_hangs_off_the_bottom_codes_every_block() {
4325 if !have_ffmpeg() {
4326 eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg");
4327 return;
4328 }
4329 let blocks: Vec<BlockCoeffs> = (0..6)
4330 .map(|i| {
4331 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
4332 BlockCoeffs::from(vec![Coeff {
4333 row,
4334 col,
4335 level: 12,
4336 }])
4337 })
4338 .collect();
4339 let rows = decode_luma_at(64, 96, &blocks);
4340 for block_row in 0..3 {
4341 for block_col in 0..2 {
4342 let name = format!("block ({block_row},{block_col})");
4343 let block = block_at(&rows, block_row, block_col);
4344 if (block_row * 2 + block_col) % 2 == 0 {
4345 assert_falls_across(&block, &name);
4346 } else {
4347 assert_falls_down(&block, &name);
4348 }
4349 }
4350 }
4351 }
4352
4353 /// A frame whose blocks do not tile it is refused rather than written as a
4354 /// stream a decoder walks off the end of.
4355 #[test]
4356 fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() {
4357 let (_, header) = frame_of(80, 64);
4358 let blocks = vec![BlockCoeffs::default(); 4];
4359 let err = split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, &blocks)
4360 .expect_err("80 is not a whole number of 32x32 blocks");
4361 assert!(
4362 format!("{err}").contains("32x32"),
4363 "the refusal names the block size, got {err}"
4364 );
4365 }
4366
4367 /// A directional intra mode says where its prediction comes from, and with
4368 /// no residual of its own a block must be exactly that prediction. The
4369 /// top-left block is given a basis function that is flat across it and
4370 /// falls down it; the block to its right is coded `H_PRED`, so every one of
4371 /// its rows must be the constant its left neighbour's rightmost column
4372 /// hands it, and the block below is coded `V_PRED`, so every one of its
4373 /// columns must be the constant the row above it ends on — a single flat
4374 /// value for the whole block. Nothing here pins the transform's shape or
4375 /// the mode's CDF: a mode written with the wrong context, an angle delta
4376 /// left out or a mode index off by one desyncs the symbol decoder and the
4377 /// two empty blocks stop mirroring their neighbours.
4378 #[test]
4379 fn directional_modes_predict_from_the_neighbours_they_name() {
4380 if !have_ffmpeg() {
4381 eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg");
4382 return;
4383 }
4384 let gradient = BlockCoeffs {
4385 luma: vec![Coeff {
4386 row: 1,
4387 col: 0,
4388 level: 12,
4389 }],
4390 ..BlockCoeffs::default()
4391 };
4392 let blocks = [
4393 gradient,
4394 BlockCoeffs {
4395 mode: H_PRED as u8,
4396 ..BlockCoeffs::default()
4397 },
4398 BlockCoeffs {
4399 mode: V_PRED as u8,
4400 ..BlockCoeffs::default()
4401 },
4402 BlockCoeffs::default(),
4403 ];
4404 let [luma, ..] = decode_coeff_planes(&blocks);
4405
4406 let source = block_at(&luma, 0, 0);
4407 for (r, row) in source.iter().enumerate() {
4408 assert!(
4409 row.iter().all(|&s| s == row[0]),
4410 "the basis function at row 1, column 0 is flat across the block, row {r} is not: {row:?}"
4411 );
4412 }
4413 let profile: Vec<u8> = source.iter().map(|r| r[0]).collect();
4414 assert!(
4415 profile.windows(2).all(|w| w[0] >= w[1]) && profile[0] > profile[31],
4416 "the block must fall from top to bottom, got {profile:?}"
4417 );
4418
4419 let horizontal = block_at(&luma, 0, 1);
4420 for (r, row) in horizontal.iter().enumerate() {
4421 assert!(
4422 row.iter().all(|&s| s == profile[r]),
4423 "an H_PRED block repeats the column to its left, row {r} should be all {} but is {row:?}",
4424 profile[r]
4425 );
4426 }
4427
4428 let vertical = block_at(&luma, 1, 0);
4429 let bottom = profile[31];
4430 assert!(
4431 vertical.iter().flatten().all(|&s| s == bottom),
4432 "a V_PRED block repeats the row above it, which is all {bottom} here, got rows \
4433 {:?} and {:?}",
4434 vertical[0],
4435 vertical[31]
4436 );
4437 }
4438
4439 /// The mode index is checked before anything is written.
4440 #[test]
4441 fn an_intra_mode_outside_the_key_frame_set_is_refused() {
4442 let mut blocks = vec![BlockCoeffs::default(); 4];
4443 blocks[2].mode = INTRA_MODES as u8;
4444 let message = split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks)
4445 .unwrap_err()
4446 .to_string();
4447 assert!(
4448 message.contains("intra mode 13"),
4449 "the refusal must name the mode, got {message}"
4450 );
4451 }
4452
4453 #[test]
4454 fn coefficients_the_writer_cannot_code_are_refused() {
4455 let empty = || vec![BlockCoeffs::default(); 4];
4456 let cases: [(&str, Vec<BlockCoeffs>); 6] = [
4457 ("one set short", vec![BlockCoeffs::default(); 3]),
4458 ("off the transform", {
4459 let mut b = empty();
4460 b[0].luma = vec![Coeff {
4461 row: 32,
4462 col: 0,
4463 level: 1,
4464 }];
4465 b
4466 }),
4467 ("a zero level", {
4468 let mut b = empty();
4469 b[1].luma = vec![Coeff {
4470 row: 0,
4471 col: 0,
4472 level: 0,
4473 }];
4474 b
4475 }),
4476 ("a level past the Golomb tail's reach", {
4477 let mut b = empty();
4478 b[2].luma = vec![Coeff {
4479 row: 0,
4480 col: 0,
4481 level: MAX_LEVEL + 1,
4482 }];
4483 b
4484 }),
4485 ("two coefficients at one position", {
4486 let mut b = empty();
4487 b[3].luma = vec![
4488 Coeff {
4489 row: 4,
4490 col: 4,
4491 level: 1,
4492 },
4493 Coeff {
4494 row: 4,
4495 col: 4,
4496 level: 2,
4497 },
4498 ];
4499 b
4500 }),
4501 ("off the chroma transform", {
4502 let mut b = empty();
4503 b[0].u = vec![Coeff {
4504 row: 0,
4505 col: 16,
4506 level: 1,
4507 }];
4508 b
4509 }),
4510 ];
4511 for (name, blocks) in cases {
4512 assert!(
4513 split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks).is_err(),
4514 "{name} must be refused"
4515 );
4516 }
4517 }
4518
4519 /// The default scan is written as the rule that generates it rather than a
4520 /// thousand pinned numbers, so the rule is checked against what a scan must
4521 /// be: every position exactly once, the origin first, and never a position
4522 /// before one it sits diagonally behind — which is what lets a decoder read
4523 /// a coefficient's context off the coefficients it has already decoded.
4524 #[test]
4525 fn the_default_scan_walks_every_position_outwards() {
4526 for side in [TX16, TX32] {
4527 let area = side * side;
4528 let scan = default_scan(side);
4529 assert_eq!(scan.len(), area);
4530 let mut seen = vec![false; area];
4531 for &pos in &scan {
4532 assert!(
4533 !seen[pos as usize],
4534 "position {pos} is scanned twice in {side}x{side}"
4535 );
4536 seen[pos as usize] = true;
4537 }
4538 assert_eq!(scan[0], 0, "the scan starts at the DC");
4539
4540 let mut order = vec![0usize; area];
4541 for (i, &pos) in scan.iter().enumerate() {
4542 order[pos as usize] = i;
4543 }
4544 for row in 0..side {
4545 for col in 0..side {
4546 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
4547 let (nr, nc) = (row + dr, col + dc);
4548 if nr < side && nc < side {
4549 assert!(
4550 order[nr * side + nc] > order[row * side + col],
4551 "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
4552 be scanned after it"
4553 );
4554 }
4555 }
4556 }
4557 }
4558 }
4559 }
4560
4561 /// The whole point of the inverse transform living in the encoder is that
4562 /// it predicts the decoder without asking one. The residual a DC-only
4563 /// 64x64 transform produces has already been pinned from a real decoder in
4564 /// [`DECODED_AT_Q100`], so that table is the gate: every level in it, both
4565 /// signs, has to come back out of `dequant_and_inverse` exactly.
4566 #[test]
4567 fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() {
4568 for (level, _) in DECODED_AT_Q100 {
4569 let mut levels = vec![0i32; 64 * 64];
4570 levels[0] = level;
4571 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
4572 let want = dc_residual(level);
4573 assert!(
4574 residual.iter().all(|&r| r == want),
4575 "level {level}: want a flat {want}, got {}..{} (first {})",
4576 residual.iter().min().unwrap(),
4577 residual.iter().max().unwrap(),
4578 residual[0]
4579 );
4580 }
4581 }
4582
4583 /// The same gate at the other transform size the encoder codes: a split
4584 /// superblock's 32x32 blocks, whose residuals are pinned in
4585 /// [`SPLIT_RESIDUAL_AT_Q100`]. The two sizes divide the dequantized
4586 /// coefficient by different denominators, so a size-blind dequantizer
4587 /// passes one table and fails the other.
4588 #[test]
4589 fn the_inverse_transform_reproduces_the_pinned_split_residuals() {
4590 for (level, want) in SPLIT_RESIDUAL_AT_Q100 {
4591 let mut levels = vec![0i32; 32 * 32];
4592 levels[0] = level;
4593 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
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 /// A DC-only transform is flat, which is exactly the case that cannot tell
4605 /// a transposed or mis-permuted butterfly network from a correct one. An AC
4606 /// coefficient in the first row must vary along the row and stay constant
4607 /// down each column, and the one in the first column the other way round;
4608 /// a transposed network swaps the two.
4609 #[test]
4610 fn a_single_ac_coefficient_varies_along_its_own_axis() {
4611 for side in [4, 8, 16, 32, 64] {
4612 let mut horizontal = vec![0i32; side * side];
4613 horizontal[1] = 100;
4614 let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX));
4615 let mut vertical = vec![0i32; side * side];
4616 vertical[side] = 100;
4617 let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX));
4618 for row in 0..side {
4619 for col in 0..side {
4620 assert_eq!(
4621 h[row * side + col],
4622 h[col],
4623 "{side}: a first-row coefficient is constant down column {col}"
4624 );
4625 assert_eq!(
4626 v[row * side + col],
4627 v[row * side],
4628 "{side}: a first-column coefficient is constant along row {row}"
4629 );
4630 }
4631 }
4632 // The two are each other's transpose. Only to within a rounding
4633 // step: the spec rounds halves up rather than away from zero, so a
4634 // basis function and its transpose can land a count apart where
4635 // the row and column passes round opposite ways.
4636 assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies");
4637 for row in 0..side {
4638 for col in 0..side {
4639 let (a, b) = (h[row * side + col], v[col * side + row]);
4640 assert!(
4641 (a - b).abs() <= 1,
4642 "{side}: transpose at ({row},{col}): {a} vs {b}"
4643 );
4644 }
4645 }
4646 }
4647 }
4648
4649 /// Negating every level negates every residual, to within the one count
4650 /// the spec's round-halves-up leaves behind. A dequantizer that rounded a
4651 /// negative coefficient away from zero instead of toward it would shift a
4652 /// whole basis function, not a count of it, so the bound is what makes
4653 /// this a test rather than a restatement.
4654 #[test]
4655 fn negating_the_levels_negates_the_residual() {
4656 for side in [32, 64] {
4657 for level in [1, 2, 3, 5, 9, 14, 40, 100] {
4658 let mut levels = vec![0i32; side * side];
4659 levels[0] = level;
4660 levels[1] = -level;
4661 levels[side + 1] = level * 2;
4662 let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
4663 let negated: Vec<i32> = levels.iter().map(|&l| -l).collect();
4664 let neg =
4665 crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX));
4666 let worst = pos
4667 .iter()
4668 .zip(&neg)
4669 .map(|(&p, &n)| (p + n).abs())
4670 .max()
4671 .expect("the block is not empty");
4672 assert!(worst <= 1, "side {side} level {level}: off by {worst}");
4673 }
4674 }
4675 }
4676
4677 /// The pinned tables above are DC-only, and a flat residual cannot tell a
4678 /// correct butterfly network from one that is merely correct at DC. This
4679 /// is the same claim against a real decoder and with real AC content: the
4680 /// top-left block of a key frame predicts a flat mid-grey with no
4681 /// neighbours to read, so what ffmpeg shows there is exactly 128 plus the
4682 /// residual the encoder's own inverse transform computes. Every sample has
4683 /// to agree, not most of them.
4684 #[test]
4685 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
4686 if !have_ffmpeg() {
4687 eprintln!(
4688 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg"
4689 );
4690 return;
4691 }
4692 // A DC, two low-frequency terms of each orientation, a diagonal and a
4693 // far corner, with both signs among them.
4694 let coeffs = [
4695 (0u8, 0u8, 9i32),
4696 (0, 1, -14),
4697 (1, 0, 7),
4698 (0, 3, 5),
4699 (3, 0, -3),
4700 (2, 2, 11),
4701 (7, 5, -6),
4702 (31, 31, 4),
4703 ];
4704 let block: BlockCoeffs = coeffs
4705 .iter()
4706 .map(|&(row, col, level)| Coeff { row, col, level })
4707 .collect::<Vec<_>>()
4708 .into();
4709 let rows = decode_luma_at(
4710 64,
4711 64,
4712 &[
4713 block,
4714 BlockCoeffs::default(),
4715 BlockCoeffs::default(),
4716 BlockCoeffs::default(),
4717 ],
4718 );
4719
4720 let mut levels = vec![0i32; 32 * 32];
4721 for &(row, col, level) in &coeffs {
4722 levels[usize::from(row) * 32 + usize::from(col)] = level;
4723 }
4724 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
4725 for row in 0..32 {
4726 for col in 0..32 {
4727 let want = (128 + residual[row * 32 + col]).clamp(0, 255);
4728 assert_eq!(
4729 i32::from(rows[row][col]),
4730 want,
4731 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
4732 rows[row][col]
4733 );
4734 }
4735 }
4736 // The block is not flat, so the agreement is about the transform and
4737 // not about a prediction both sides got trivially right.
4738 let (lo, hi) = (
4739 rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(),
4740 rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(),
4741 );
4742 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
4743 }
4744
4745 /// The same against the smallest transform the writer codes, the 16x16 one
4746 /// a split quadrant carries. Its rounding is the one the split path rests
4747 /// on, and nothing else in the crate exercises it against a decoder.
4748 #[test]
4749 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
4750 if !have_ffmpeg() {
4751 eprintln!(
4752 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
4753 );
4754 return;
4755 }
4756 let coeffs = [
4757 (0u8, 0u8, 9i32),
4758 (0, 1, -14),
4759 (1, 0, 7),
4760 (0, 3, 5),
4761 (3, 0, -3),
4762 (2, 2, 11),
4763 (7, 5, -6),
4764 (15, 15, 4),
4765 ];
4766 let block: BlockCoeffs = coeffs
4767 .iter()
4768 .map(|&(row, col, level)| Coeff { row, col, level })
4769 .collect::<Vec<_>>()
4770 .into();
4771 let (seq, header) = frame_of(64, 64);
4772 let quadrants = vec![
4773 Quadrant::Split(vec![
4774 block,
4775 BlockCoeffs::default(),
4776 BlockCoeffs::default(),
4777 BlockCoeffs::default(),
4778 ]),
4779 Quadrant::Whole(BlockCoeffs::default()),
4780 Quadrant::Whole(BlockCoeffs::default()),
4781 Quadrant::Whole(BlockCoeffs::default()),
4782 ];
4783 let tile = sb_coeff_key_frame_tile(
4784 header.mi_cols,
4785 header.mi_rows,
4786 Q_IDX,
4787 &[Superblock::Split(quadrants)],
4788 )
4789 .unwrap();
4790 let mut stream = temporal_delimiter();
4791 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
4792 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
4793 let planes = ffmpeg_decode(&stream, 64, 64);
4794
4795 let mut levels = vec![0i32; TX16 * TX16];
4796 for &(row, col, level) in &coeffs {
4797 levels[usize::from(row) * TX16 + usize::from(col)] = level;
4798 }
4799 let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX));
4800 for row in 0..TX16 {
4801 for col in 0..TX16 {
4802 let want = (128 + residual[row * TX16 + col]).clamp(0, 255);
4803 assert_eq!(
4804 i32::from(planes[row * 64 + col]),
4805 want,
4806 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
4807 planes[row * 64 + col]
4808 );
4809 }
4810 }
4811 }
4812
4813 /// The same against the other transform size, the 64x64 one a whole
4814 /// superblock carries. Only its top-left 32x32 can hold coefficients, and
4815 /// the spec zeroes the rest before the row transform — a 64-point network
4816 /// that read the missing half as anything else would disagree here.
4817 #[test]
4818 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {
4819 if !have_ffmpeg() {
4820 eprintln!(
4821 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg"
4822 );
4823 return;
4824 }
4825 let coeffs = [
4826 (0u8, 0u8, 12i32),
4827 (0, 2, -9),
4828 (2, 0, 6),
4829 (1, 1, -5),
4830 (5, 9, 8),
4831 (31, 0, -4),
4832 (0, 31, 3),
4833 ];
4834 let block: BlockCoeffs = coeffs
4835 .iter()
4836 .map(|&(row, col, level)| Coeff { row, col, level })
4837 .collect::<Vec<_>>()
4838 .into();
4839 let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]);
4840
4841 let mut levels = vec![0i32; 64 * 64];
4842 for &(row, col, level) in &coeffs {
4843 levels[usize::from(row) * 64 + usize::from(col)] = level;
4844 }
4845 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
4846 for row in 0..64 {
4847 for col in 0..64 {
4848 let want = (128 + residual[row * 64 + col]).clamp(0, 255);
4849 assert_eq!(
4850 i32::from(rows[row][col]),
4851 want,
4852 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
4853 rows[row][col]
4854 );
4855 }
4856 }
4857 }
4858
4859 /// The AV1 transforms are normalized so that a quantized level means the
4860 /// same thing at every size: doubling the transform's side halves what a
4861 /// DC level is worth, which is the job the per-size row shift and the
4862 /// dequantizer's denominator split between them. The frame syntax only
4863 /// codes 32x32 and 64x64 transforms, so this is what holds the four
4864 /// smaller sizes' shifts to the spec's table — a shift wrong by one at any
4865 /// size doubles or halves that size's step alone.
4866 #[test]
4867 fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() {
4868 let mut previous: Option<i32> = None;
4869 for side in [4usize, 8, 16, 32, 64] {
4870 let mut levels = vec![0i32; side * side];
4871 levels[0] = 100;
4872 let residual =
4873 crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
4874 let dc = residual[0];
4875 assert!(
4876 residual.iter().all(|&r| r == dc),
4877 "side {side}: a DC coefficient reconstructs flat"
4878 );
4879 if let Some(previous) = previous {
4880 assert!(
4881 (dc * 2 - previous).abs() <= 1,
4882 "side {side}: {dc} is not half of the previous size's {previous}"
4883 );
4884 }
4885 previous = Some(dc);
4886 }
4887 }
4888
4889 /// The encoder's own round trip, through a real bitstream.
4890 ///
4891 /// A picture is chosen, its residual against the DC prediction of 128 is
4892 /// forward-transformed and quantized, the levels are written into a tile,
4893 /// and ffmpeg decodes it. Two things have to hold: what comes back is
4894 /// exactly what the encoder's own inverse said it would be — sample for
4895 /// sample, which is what lets a rate-distortion loop trust its
4896 /// reconstruction — and it is within a quantizer step of the picture that
4897 /// was asked for, which is what makes the forward transform an encoder
4898 /// rather than a scrambler.
4899 #[test]
4900 fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {
4901 if !have_ffmpeg() {
4902 eprintln!(
4903 "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
4904 );
4905 return;
4906 }
4907 // A gradient, a ripple and a corner patch: low frequencies, a mid one
4908 // and an edge, none of them a basis function of the transform.
4909 let mut residual = vec![0i32; 32 * 32];
4910 for row in 0..32usize {
4911 for col in 0..32usize {
4912 let gradient = row as f64 * 2.0 - 32.0;
4913 let ripple = 25.0
4914 * (col as f64 * std::f64::consts::PI / 6.0).sin()
4915 * (row as f64 * std::f64::consts::PI / 11.0).cos();
4916 let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 };
4917 residual[row * 32 + col] = (gradient + ripple + patch).round() as i32;
4918 }
4919 }
4920
4921 let levels =
4922 crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5);
4923 assert!(
4924 levels.iter().any(|&l| l != 0),
4925 "the picture quantized away entirely"
4926 );
4927 let coded: Vec<Coeff> = levels
4928 .iter()
4929 .enumerate()
4930 .filter(|&(_, &level)| level != 0)
4931 .map(|(i, &level)| Coeff {
4932 row: (i / 32) as u8,
4933 col: (i % 32) as u8,
4934 level,
4935 })
4936 .collect();
4937
4938 let rows = decode_luma_at(
4939 64,
4940 64,
4941 &[
4942 coded.into(),
4943 BlockCoeffs::default(),
4944 BlockCoeffs::default(),
4945 BlockCoeffs::default(),
4946 ],
4947 );
4948 let reconstruction =
4949 crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
4950
4951 let mut squared = 0.0f64;
4952 for row in 0..32 {
4953 for col in 0..32 {
4954 let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255);
4955 assert_eq!(
4956 i32::from(rows[row][col]),
4957 want,
4958 "sample ({row},{col}): the decoder and the encoder disagree"
4959 );
4960 let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]);
4961 squared += error * error;
4962 }
4963 }
4964 let rmse = (squared / 1024.0).sqrt();
4965 // A quantizer step is q/8 in residual units. Rounding to nearest
4966 // spreads the error over a step, and a quarter of one is a bound this
4967 // picture clears with room to spare (2.2 of 14 as written) while a
4968 // forward transform that is merely energy-preserving does not: a
4969 // transposed column pass measures 13.3 here.
4970 let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0;
4971 assert!(
4972 rmse < step / 4.0,
4973 "the decoded picture is {rmse} off, a step being {step}"
4974 );
4975 }
4976
4977 /// The inverse of [`write_mv_component`], mirroring [`SymbolDecoder`]
4978 /// against the spec's own `read_mv_component` pseudocode.
4979 fn decode_mv_component(
4980 dec: &mut crate::msac::tests::SymbolDecoder,
4981 c: &mut MvComponentCdfs,
4982 ) -> i32 {
4983 let sign = dec.symbol(&mut c.sign);
4984 let class = dec.symbol(&mut c.class);
4985 let local = if class == 0 {
4986 let bit = dec.symbol(&mut c.class0_bit);
4987 let fr = dec.symbol(&mut c.class0_fr[bit]);
4988 (bit << 3) | (fr << 1) | 1
4989 } else {
4990 let mut d = 0;
4991 for i in 0..class {
4992 d |= dec.symbol(&mut c.bit[i]) << i;
4993 }
4994 let fr = dec.symbol(&mut c.fr);
4995 (d << 3) | (fr << 1) | 1
4996 };
4997 let mag = mv_class_base(class) + local as i32 + 1;
4998 if sign == 1 { -mag } else { mag }
4999 }
5000
5001 /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,
5002 /// mirroring the writer's own context tracking (partition, skip,
5003 /// is_inter, and the MV stack) symbol for symbol against a fresh
5004 /// [`Cdfs`], so a desync between the two shows up as a wrong decoded
5005 /// value rather than a silent pass. Every block here is skipped, so no
5006 /// coefficient symbols are read. `wrong_y_mode` swaps in `KF_Y_MODE`'s
5007 /// (0, 0) row for an intra block's mode read, to show that reading the
5008 /// wrong table decodes the wrong mode rather than the one that was
5009 /// written.
5010 ///
5011 /// One decoded block's `(skip, is_inter, mode, mv)` — `mode` is `None`
5012 /// for an inter block, `mv` is `(0, 0)` for an intra one.
5013 type DecodedBlock = (bool, bool, Option<usize>, (i32, i32));
5014
5015 /// Returns the number of symbols and literals read, and each block's
5016 /// decoded state.
5017 fn decode_inter_sb(
5018 data: &[u8],
5019 mi_cols: u32,
5020 mi_rows: u32,
5021 wrong_y_mode: bool,
5022 ) -> (usize, Vec<DecodedBlock>) {
5023 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
5024 let mut cdfs = Cdfs::new(2);
5025 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
5026 let mut above_skip = [false; 2];
5027 let mut left_skip = [false; 2];
5028 let mut above_inter = [false; 2];
5029 let mut left_inter = [false; 2];
5030 let mut count = 0usize;
5031
5032 count += 1;
5033 dec.symbol(&mut cdfs.partition_w64[0]);
5034
5035 let mut results = Vec::new();
5036 for quadrant in 0..4usize {
5037 let (r32, c32) = (quadrant / 2, quadrant % 2);
5038 count += 1;
5039 dec.symbol(&mut cdfs.partition_w32[0]);
5040
5041 let (has_above, has_left) = (r32 > 0, c32 > 0);
5042 let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]);
5043 count += 1;
5044 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
5045
5046 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]);
5047 count += 1;
5048 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
5049
5050 let (mode, mv) = if is_inter {
5051 let sr_ctx = single_ref_ctx(above_inter[c32] || left_inter[r32]);
5052 count += 3;
5053 assert_eq!(
5054 dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
5055 0,
5056 "single_ref p1"
5057 );
5058 assert_eq!(
5059 dec.symbol(&mut cdfs.single_ref[sr_ctx][2]),
5060 0,
5061 "single_ref p3"
5062 );
5063 assert_eq!(
5064 dec.symbol(&mut cdfs.single_ref[sr_ctx][3]),
5065 0,
5066 "single_ref p4"
5067 );
5068
5069 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
5070 let stack = find_mv_stack(
5071 &grid,
5072 mi_row,
5073 mi_col,
5074 8,
5075 8,
5076 1,
5077 mi_cols as usize,
5078 mi_rows as usize,
5079 );
5080
5081 count += 1;
5082 let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0;
5083 let (mv, is_new_mv) = if new_mv {
5084 if stack.entries.len() > 1 {
5085 count += 1;
5086 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
5087 }
5088 count += 1;
5089 let joint = dec.symbol(&mut cdfs.mv_joint);
5090 let mut diff = (0, 0);
5091 if joint == 2 || joint == 3 {
5092 // sign, class, class0_bit, class0_fr for this test's
5093 // small (class 0) components.
5094 count += 4;
5095 diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]);
5096 }
5097 if joint == 1 || joint == 3 {
5098 count += 4;
5099 diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]);
5100 }
5101 ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true)
5102 } else {
5103 count += 2;
5104 assert_eq!(
5105 dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]),
5106 1,
5107 "zero_mv"
5108 );
5109 assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv");
5110 (stack.nearest_mv, false)
5111 };
5112 for dr in 0..8 {
5113 for dc in 0..8 {
5114 grid.set(
5115 mi_row + dr,
5116 mi_col + dc,
5117 MiInfo {
5118 is_inter: true,
5119 ref_frame: 1,
5120 ref_frame1: None,
5121 mv1: None,
5122 mv,
5123 is_new_mv,
5124 size: 8,
5125 size_h: 8,
5126 is_global_mv0: false,
5127 is_global_mv1: false,
5128 },
5129 );
5130 }
5131 }
5132 (None, mv)
5133 } else {
5134 count += 1;
5135 let m = if wrong_y_mode {
5136 dec.symbol(&mut cdfs.kf_y_mode[0][0])
5137 } else {
5138 dec.symbol(&mut cdfs.y_mode[3])
5139 };
5140 if (V_PRED..=D67_PRED).contains(&m) {
5141 count += 1;
5142 dec.symbol(&mut cdfs.angle_delta[m - V_PRED]);
5143 }
5144 count += 1;
5145 dec.symbol(&mut cdfs.uv_mode_cfl[m]);
5146 (Some(m), (0, 0))
5147 };
5148
5149 above_skip[c32] = skip;
5150 left_skip[r32] = skip;
5151 above_inter[c32] = is_inter;
5152 left_inter[r32] = is_inter;
5153 results.push((skip, is_inter, mode, mv));
5154 }
5155 (count, results)
5156 }
5157
5158 /// Every superblock here skips: no residual, so the only symbols are the
5159 /// mode chain, and the byte count and the symbol count both come out
5160 /// small enough to hand-check.
5161 #[test]
5162 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
5163 let block = BlockCoeffs {
5164 inter: Some(InterInfo {
5165 mode: InterMode::NearestMv,
5166 mv: (0, 0),
5167 }),
5168 skip: true,
5169 ..BlockCoeffs::default()
5170 };
5171 let blocks = vec![
5172 Quadrant::Whole(block.clone()),
5173 Quadrant::Whole(block.clone()),
5174 Quadrant::Whole(block.clone()),
5175 Quadrant::Whole(block),
5176 ];
5177 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
5178 // Hand count: one partition_w64, then per block partition_w32 + skip +
5179 // is_inter + 3 single_ref + new_mv + zero_mv + ref_mv = 9, times four.
5180 assert!(
5181 data.len() <= 16,
5182 "an all-skip NEARESTMV superblock took {} bytes",
5183 data.len()
5184 );
5185
5186 let (count, results) = decode_inter_sb(&data, 16, 16, false);
5187 assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count");
5188 for (skip, is_inter, mode, mv) in results {
5189 assert!(skip);
5190 assert!(is_inter);
5191 assert_eq!(mode, None);
5192 // Every block's only inter neighbours carry (0, 0), so the stack's
5193 // nearest candidate is (0, 0) throughout.
5194 assert_eq!(mv, (0, 0));
5195 }
5196 }
5197
5198 /// The fourth block codes NEWMV against a (0, 0) predictor with a coded
5199 /// column component: the symbol sequence a decoder reads back has to be
5200 /// exactly what [`write_mv`] wrote, not a residual that merely decodes
5201 /// to *some* valid vector.
5202 #[test]
5203 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
5204 let nearest = BlockCoeffs {
5205 inter: Some(InterInfo {
5206 mode: InterMode::NearestMv,
5207 mv: (0, 0),
5208 }),
5209 skip: true,
5210 ..BlockCoeffs::default()
5211 };
5212 let newmv = BlockCoeffs {
5213 inter: Some(InterInfo {
5214 mode: InterMode::NewMv,
5215 mv: (0, 2),
5216 }),
5217 skip: true,
5218 ..BlockCoeffs::default()
5219 };
5220 let blocks = vec![
5221 Quadrant::Whole(nearest.clone()),
5222 Quadrant::Whole(nearest.clone()),
5223 Quadrant::Whole(nearest),
5224 Quadrant::Whole(newmv),
5225 ];
5226 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
5227
5228 let (count, results) = decode_inter_sb(&data, 16, 16, false);
5229 // Three NEARESTMV blocks at 9 symbols each, one NEWMV block at
5230 // partition + skip + is_inter + 3 single_ref + new_mv + mv_joint +
5231 // (sign, class, class0_bit, class0_fr for the one nonzero component)
5232 // = 12, plus the superblock's partition_w64.
5233 assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count");
5234 let (skip, is_inter, mode, mv) = results[3];
5235 assert!(skip);
5236 assert!(is_inter);
5237 assert_eq!(mode, None);
5238 assert_eq!(
5239 mv,
5240 (0, 2),
5241 "the decoded motion vector must be exactly what was written"
5242 );
5243 }
5244
5245 /// Decodes only the first 32x32 block's mode symbol of a superblock: the
5246 /// tile's own first block always reads partition, skip and is_inter at
5247 /// context zero, so this needs none of [`decode_inter_sb`]'s neighbour
5248 /// bookkeeping — which matters here because the mutation this feeds
5249 /// desyncs everything after the one symbol it is testing, and a decoder
5250 /// that kept reading past it would be asserting on garbage.
5251 fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize {
5252 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
5253 let mut cdfs = Cdfs::new(2);
5254 dec.symbol(&mut cdfs.partition_w64[0]);
5255 dec.symbol(&mut cdfs.partition_w32[0]);
5256 dec.symbol(&mut cdfs.skip[0]);
5257 dec.symbol(&mut cdfs.intra_inter[0]);
5258 if wrong_y_mode {
5259 dec.symbol(&mut cdfs.kf_y_mode[0][0])
5260 } else {
5261 dec.symbol(&mut cdfs.y_mode[3])
5262 }
5263 }
5264
5265 /// An inter frame's intra block reads its mode against `Y_MODE`'s size
5266 /// group, not `KF_Y_MODE`'s neighbour-context table a key frame's block
5267 /// reads. Reading the wrong table back — `KF_Y_MODE`'s `(0, 0)` row —
5268 /// decodes a different mode than the one [`sb_coeff_inter_frame_tile`]
5269 /// wrote, because the two tables carry different default probabilities
5270 /// even though a row of each is the same fourteen-entry width. (The swap
5271 /// this test's name warns of does not typecheck as a one-line
5272 /// substitution at the write site either — `cdfs.kf_y_mode[3]` is a
5273 /// `[[u16; 14]; 5]` row, not the single `[u16; 14]` `Y_MODE` indexing
5274 /// needs — so a mutation that got the *outer* shape wrong would be
5275 /// caught by `cargo check` before it ever reached a test; this test is
5276 /// what catches getting the *right* leaf shape from the *wrong* table.)
5277 #[test]
5278 fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() {
5279 let block = BlockCoeffs {
5280 mode: H_PRED as u8,
5281 skip: true,
5282 ..BlockCoeffs::default()
5283 };
5284 let blocks = vec![Quadrant::Whole(block); 4];
5285 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
5286
5287 assert_eq!(
5288 decode_first_block_mode(&data, false),
5289 H_PRED,
5290 "the right table reads the mode back exactly"
5291 );
5292 assert_ne!(
5293 decode_first_block_mode(&data, true),
5294 H_PRED,
5295 "KF_Y_MODE's different probabilities must decode a different mode"
5296 );
5297 }
5298}