forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

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