forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

tile.rs11519 lines, 473.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::cell::RefCell;
13#[cfg(test)]
14use std::collections::BTreeMap;
15use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
16use std::sync::LazyLock;
17
18use ec_core::{Error, Result};
19
20use crate::cdf;
21use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
22use crate::decode::{txfm_partition_ctx_rect, TXFM_CTX_INIT};
23use crate::msac::SymbolEncoder;
24use crate::mvstack::{find_mv_stack, mv16, MiGrid, MiInfo, NO_REF1};
25use crate::transform::TxType;
26
27// ---------------------------------------------------------------------------
28// lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder
29// reads ONE `cdef_idx` literal per 64x64 superblock, at that superblock's
30// first non-skip block, and only when the frame header's `cdef_bits > 0`
31// (`crate::decode::maybe_read_cdef_idx`). The writers below mirror that from
32// a plan the filter search hands over, kept in a thread-local rather than
33// threaded through every `write_*` signature -- the same shape the decoder's
34// own `FrameCtx::cdef_transmitted` uses, and the encoder codes one tile at a
35// time on one thread. The plan is CONSUMED by the tile writer that runs next
36// ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame
37// that arms nothing writes no literals.
38
39// ---------------------------------------------------------------------------
40// lane-av1lr: per-restoration-unit loop restoration syntax (spec 5.11.57,
41// `read_lr`), armed by the encoder's restoration search the same way
42// [`arm_cdef_idx`] arms the CDEF indices. LUMA ONLY and Wiener only: the
43// frame header this encoder writes sets `FrameRestorationType[0] = WIENER`
44// and leaves both chroma planes at `RESTORE_NONE`, so a unit codes one
45// `restore_wiener` symbol and, when it takes the filter, its two directions
46// against the running per-tile reference (`crate::restoration::
47// write_wiener_filter`, the exact inverse of the reader's own
48// `read_wiener_filter`).
49
50/// One frame's per-unit restoration plan (see [`arm_lr`]).
51struct LrPlan {
52 /// `LoopRestorationSize[0]`, in luma samples.
53 unit_size: u32,
54 /// `horz_units`/`vert_units` for the luma plane.
55 horz_units: u32,
56 vert_units: u32,
57 /// One entry per unit, `rcol + rrow * horz_units`: the filter it takes,
58 /// or `None` for `RESTORE_NONE`.
59 units: Vec<Option<crate::restoration::WienerInfo>>,
60 /// `ref_wiener_info`: the running reference the taps are coded against,
61 /// reset to the midpoint filter at the start of each tile (this writer
62 /// codes one tile per frame).
63 reference: crate::restoration::WienerInfo,
64}
65
66thread_local! {
67 static LR_PLAN: std::cell::RefCell<Option<LrPlan>> = const { std::cell::RefCell::new(None) };
68}
69
70/// Arms the next tile write with one Wiener decision per luma restoration
71/// unit. An empty `units` disarms (the frame codes no restoration at all).
72pub(crate) fn arm_lr(
73 unit_size: u32,
74 horz_units: u32,
75 vert_units: u32,
76 units: Vec<Option<crate::restoration::WienerInfo>>,
77) {
78 LR_PLAN.with(|c| {
79 *c.borrow_mut() = (!units.is_empty()).then(|| LrPlan {
80 unit_size,
81 horz_units,
82 vert_units,
83 units,
84 reference: crate::restoration::WienerInfo::default(),
85 });
86 });
87}
88
89// ---------------------------------------------------------------------------
90// lane-sb128: the sequence's `use_128x128_superblock`. Armed per tile write
91// like [`arm_lr`] (the encoder codes one tile at a time per thread) rather
92// than threaded through every writer signature. When set, the two tile
93// writers walk 128x128 superblocks -- loop restoration and one
94// `partition_w128` symbol at the 128 root, then the four 64x64 quadrants in
95// libaom `decode_partition`'s own TL, TR, BL, BR order -- which is exactly
96// what `crate::decode::read_sb128_root` reads.
97
98thread_local! {
99 static SB128: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
100}
101
102/// Arms the next tile write with the sequence's 128x128 superblock size.
103pub(crate) fn arm_sb128(on: bool) {
104 SB128.with(|c| c.set(on));
105}
106
107/// How many 128x128 superblock roots the writers have coded since the last
108/// [`take_sb128_root_hits`] -- a gate reports how often the root fires rather
109/// than assuming it does (class `gate-blind-to-feature`). Process-global
110/// rather than thread-local because the tiles of one frame are written on
111/// worker threads.
112static SB128_ROOT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
113
114/// The 128x128-root count since the last call, and zero it.
115pub fn take_sb128_root_hits() -> usize {
116 SB128_ROOT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
117}
118
119/// Whether the next tile write codes 128x128 superblocks ([`arm_sb128`]).
120fn sb128_armed() -> bool {
121 SB128.with(std::cell::Cell::get)
122}
123
124/// The order a tile's 64x64 superblock cells are written in, mirroring
125/// `crate::decode::sb_visit_order` exactly: plain raster at a 64 superblock,
126/// and TL/TR/BL/BR inside each 128x128 superblock (in raster order over the
127/// 128 grid) at a 128 one. The two flags mark the first cell of a superblock
128/// ROW (where the left neighbour context resets) and the first cell of a
129/// superblock (where the 128 root's own restoration units and partition
130/// symbol are written).
131fn sb_write_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
132 let mut out = Vec::new();
133 if !sb128 {
134 for r in r0..r1 {
135 for c in c0..c1 {
136 out.push((r, c, c == c0, true));
137 }
138 }
139 return out;
140 }
141 let mut r = r0;
142 while r < r1 {
143 let mut first_in_row = true;
144 let mut c = c0;
145 while c < c1 {
146 let mut first_in_sb = true;
147 for qr in 0..2 {
148 for qc in 0..2 {
149 let (rr, cc) = (r + qr, c + qc);
150 if rr >= r1 || cc >= c1 {
151 continue;
152 }
153 out.push((rr, cc, first_in_row, first_in_sb));
154 first_in_row = false;
155 first_in_sb = false;
156 }
157 }
158 c += 2;
159 }
160 r += 2;
161 }
162 out
163}
164
165/// The 128x128 superblock root ([`sb_write_order`]'s `sb_start` cells): the
166/// units its own 128-sample span covers, then the partition symbol. Only
167/// `PARTITION_SPLIT` is written -- the four 64x64 quadrants below are today's
168/// superblocks -- and at a root the true frame edge cuts, the DECIDING
169/// gathered bit the decoder reads instead (`read_sb128_root`).
170fn write_sb128_root(
171 enc: &mut SymbolEncoder,
172 cdfs: &mut Cdfs,
173 neighbours: &Neighbours,
174 sb_r: u32,
175 sb_c: u32,
176 mi_cols: u32,
177 mi_rows: u32,
178 // lane-b128: the partition the root's own search chose --
179 // `PARTITION_SPLIT` (the four 64x64 quadrants below, which is every root
180 // this writer coded before) or `PARTITION_NONE` (one 128x128 block,
181 // written by the caller right after this). Only offered at a root wholly
182 // inside the frame, so the gathered edge arms below still code SPLIT.
183 part: usize,
184) {
185 SB128_ROOT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
186 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
187 write_lr(enc, cdfs, mi_r128, mi_c128, SB_MI * 2);
188 let at128 = ((mi_r128 / 4) as usize, (mi_c128 / 4) as usize);
189 let ctx128 = neighbours.partition_ctx(at128, 128);
190 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
191 if crate::envflags::env_flag!("EC_AV1_TRACE") {
192 eprintln!("WTRACE partition_w128 ctx={ctx128} cols={has_cols128} rows={has_rows128}");
193 }
194 match (has_cols128, has_rows128) {
195 (true, true) => enc.symbol(part, &mut cdfs.partition_w128[ctx128]),
196 // As at the 64 root: the gathered CDF is built for the read and
197 // thrown away, so nothing adapts here. Value 1 is SPLIT.
198 (true, false) => enc.symbol_fixed(
199 1,
200 &crate::decode::gather_of(&cdfs.partition_w128[ctx128], &crate::decode::VERT_ALIKE128),
201 ),
202 (false, true) => enc.symbol_fixed(
203 1,
204 &crate::decode::gather_of(&cdfs.partition_w128[ctx128], &crate::decode::HORZ_ALIKE128),
205 ),
206 // Both halves outside: the split is the only partition left and the
207 // decoder reads nothing.
208 (false, false) => {}
209 }
210}
211
212/// lane-b128: one 128x128 inter block at a `PARTITION_NONE` 128 superblock
213/// root -- the syntax `decode_inter_block` reads for `sb128_none` (decode.rs
214/// ~35110): `skip`, `is_inter`, the reference/mode chain at the block's own
215/// 32x32-mi window, the motion mode, and the transform syntax, with the mi
216/// grid and every neighbour band published over all thirty-two mi cells.
217///
218/// lane-b128r: a block that carries a RESIDUAL codes it as the four 64x64 mu
219/// chunks libaom's `decode_token_recon_block` walks -- per chunk one
220/// TX_64X64 luma unit (its coded 32x32 corner, `TxbSet::Luma64`, DCT-only at
221/// this size) then one TX_32X32 unit per chroma plane on the offset-10
222/// `txb_skip` rows, each publishing its own coefficient context before the
223/// next unit reads it. Its transform syntax is the var-tx tree's four
224/// depth-0 `txfm_partition` symbols, one per chunk. The levels arrive packed
225/// per plane into a 64-wide grid, chunk (cr, cc) at (cr * 32, cc * 32)
226/// ([`crate::encode::search_root_128`]). A skipped block writes no
227/// `cdef_idx` and no `delta_q`, exactly as the 64 root's skip arm does.
228///
229/// # Errors
230/// A block that is intra, that is compound with a residual, or whose var-tx
231/// depth is not 0, at this size.
232#[allow(clippy::too_many_arguments)]
233fn write_inter_block_128(
234 enc: &mut SymbolEncoder,
235 cdfs: &mut Cdfs,
236 neighbours: &mut Neighbours,
237 grid: &mut MiGrid,
238 // The root's top-left position in [`SUB`] (16x16) units.
239 sb_at: (usize, usize),
240 block: &BlockCoeffs,
241 mi_cols: u32,
242 mi_rows: u32,
243 tx_select: bool,
244) -> Result<()> {
245 /// The block's side in samples and in 4x4 mode-info units.
246 const SIDE: usize = 128;
247 const SIDE_MI: usize = SIDE / MI;
248 /// The four 64x64 "mu" chunks, in the order libaom's
249 /// `decode_token_recon_block` walks them (raster).
250 const CHUNKS: [(usize, usize); 4] = [(0, 0), (0, 1), (1, 0), (1, 1)];
251 let info = block.inter.ok_or_else(|| {
252 Error::unsupported("AV1 tile", "a 128x128 superblock root block is coded inter")
253 })?;
254 if !block.skip && block.tx_depth != 0 {
255 return Err(Error::unsupported(
256 "AV1 tile",
257 "a 128x128 superblock root block splits its var-tx tree below TX_64X64",
258 ));
259 }
260 let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
261 let has_above = neighbours.has_above(mi_r);
262 let has_left = neighbours.has_left(mi_c);
263 let skip_ctx =
264 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
265 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
266 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
267 write_delta_q(enc, cdfs, (mi_r, mi_c), true, block.skip);
268 let ii_ctx = intra_inter_ctx(
269 has_above,
270 has_left,
271 neighbours.above_inter[mi_c],
272 neighbours.left_inter[mi_r],
273 );
274 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
275 write_comp_mode(
276 enc,
277 cdfs,
278 neighbours,
279 (mi_r, mi_c),
280 (has_above, has_left),
281 info.ref1.is_some(),
282 );
283 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
284 write_compound_block(
285 enc,
286 cdfs,
287 neighbours,
288 grid,
289 (mi_r, mi_c),
290 (SIDE_MI, SIDE_MI),
291 (has_above, has_left),
292 info,
293 (mi_cols as usize, mi_rows as usize),
294 )?
295 } else {
296 write_single_ref(
297 enc,
298 cdfs,
299 info.ref_frame,
300 neighbours.above_ref[mi_c],
301 neighbours.above_ref1[mi_c],
302 neighbours.left_ref[mi_r],
303 neighbours.left_ref1[mi_r],
304 );
305 let stack = find_mv_stack(
306 grid,
307 mi_r,
308 mi_c,
309 SIDE_MI,
310 SIDE_MI,
311 info.ref_frame,
312 mi_cols as usize,
313 mi_rows as usize,
314 );
315 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
316 (mv, (0, 0), is_new_mv)
317 };
318 for dr in 0..SIDE_MI {
319 for dc in 0..SIDE_MI {
320 grid.set(
321 mi_r + dr,
322 mi_c + dc,
323 MiInfo {
324 is_inter: true,
325 ref_frame: info.ref_frame,
326 ref_frame1: info.ref1.unwrap_or(NO_REF1),
327 mv1: mv16(mv1),
328 mv: mv16(mv),
329 is_new_mv,
330 size: SIDE_MI as u8,
331 size_h: SIDE_MI as u8,
332 is_global_mv0: false,
333 is_global_mv1: false,
334 },
335 );
336 }
337 }
338 if info.ref1.is_none() {
339 write_motion_mode(
340 enc,
341 cdfs,
342 grid,
343 (mi_r, mi_c),
344 (SIDE_MI, SIDE_MI),
345 (SIDE, SIDE),
346 (mi_cols as usize, mi_rows as usize),
347 info.ref_frame,
348 block.motion_mode,
349 )?;
350 }
351 if tx_select {
352 if block.skip {
353 write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SIDE, true, true, 0);
354 } else {
355 // The var-tx tree of a 128x128 block enters at TX_64X64 once per
356 // mu chunk (`read_block_tx_size`'s `max_tx = side.min(64)` loop),
357 // so it is four depth-0 `txfm_split` flags of zero, each read
358 // against the bands the chunks before it published.
359 for (cr, cc) in CHUNKS {
360 let unit = (mi_r + cr * 16, mi_c + cc * 16);
361 let ctx = txfm_partition_ctx_rect(
362 neighbours.above_txfm[unit.1],
363 neighbours.left_txfm[unit.0],
364 SIDE,
365 64,
366 64,
367 );
368 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
369 neighbours.record_txfm(unit, 64, 64, 64);
370 }
371 }
372 }
373 let zero_grids = [
374 vec![0i32; TX32 * TX32],
375 vec![0i32; TX32 * TX32],
376 vec![0i32; TX32 * TX32],
377 ];
378 if !block.skip {
379 // The packed 64-wide level grids the search hands over, one plane
380 // each (see this function's doc).
381 let packed = [
382 level_grid(&block.luma, 64)?,
383 level_grid(&block.u, 64)?,
384 level_grid(&block.v, 64)?,
385 ];
386 let scan32 = default_scan(TX32);
387 let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec<i32> {
388 (0..32)
389 .flat_map(|row| packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec())
390 .collect()
391 };
392 let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
393 for (cr, cc) in CHUNKS {
394 let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
395 // The luma unit: its own `txb_skip_ctx` is the neighbour
396 // magnitude table (the unit is smaller than its block), and it
397 // publishes its context before the next chunk reads it.
398 let luma = unit_of(0, cr, cc);
399 let skip_ctx = neighbours.luma_skip_ctx(unit_mi, 64 / MI);
400 let around = neighbours.around_mi(unit_mi, 64);
401 write_coeffs(
402 enc,
403 &mut cdfs.txb(TxbSet::Luma64, 0),
404 &luma,
405 &scan32,
406 skip_ctx,
407 dc_sign_ctx(around[0].dc_vote),
408 Some(0),
409 TxType::DctDct,
410 );
411 neighbours.record_mi_luma(unit_mi, 64, &luma);
412 // Then this chunk's chroma pair, before the next chunk's luma:
413 // libaom codes every plane of a mu chunk before moving on. The
414 // chroma `txb_skip_ctx` takes `get_txb_ctx`'s offset-10 rows
415 // (+3 here) because the uv plane block is bigger than the unit.
416 // lane-av1-128rectspan: SQUARE per-axis geometry -- one TX_32X32
417 // per 64x64 mu chunk, stamped at span 64 on BOTH axes. That is
418 // 4:2:0/4:4:4 only: at 4:2:2 the chunk's chroma plane block is
419 // 32x64 (two stacked units) with a (64, 32) luma footprint per
420 // unit, so `unit_mi`, the `64`-spans and the whole `CHUNKS`
421 // raster need the same per-axis treatment before 4:2:2 could be
422 // written here. Refused by name at the sequence header today, so
423 // this is a PORT note, not a live defect.
424 let mut pair = [Vec::new(), Vec::new()];
425 for plane in 1..3usize {
426 let grid = unit_of(plane, cr, cc);
427 let around = neighbours.around_mi(unit_mi, 64)[plane];
428 write_coeffs(
429 enc,
430 &mut cdfs.txb(TxbSet::Chroma32, 0),
431 &grid,
432 &scan32,
433 usize::from(around.above_coded) + usize::from(around.left_coded) + 3,
434 dc_sign_ctx(around.dc_vote),
435 Some(plane),
436 TxType::DctDct,
437 );
438 neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
439 pair[plane - 1] = grid;
440 }
441 chroma_units.push((unit_mi, pair));
442 }
443 // decode.rs' own tail (`record_split_luma_rect_mi` then the
444 // `mu_chroma_units` re-stamp): the block-level write off the WHOLE
445 // assembled chroma plane grid, luma kept because each unit already
446 // published its own, and then the per-unit chroma writes replayed
447 // over it -- last writer wins, so the next block reads the units.
448 let block_grids = [
449 vec![0i32; TX32 * TX32],
450 packed[1].clone(),
451 packed[2].clone(),
452 ];
453 neighbours.record_planes(sb_at, SIDE, 0, &block_grids, false);
454 for (unit_mi, pair) in &chroma_units {
455 neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
456 neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
457 }
458 } else {
459 neighbours.record(sb_at, SIDE, 0, &zero_grids);
460 }
461 neighbours.record_inter(sb_at, SIDE, block.skip, true, block_ref(block));
462 record_block_compound(neighbours, (mi_r, mi_c), SIDE, block);
463 SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
464 if !block.skip {
465 SB128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
466 }
467 if info.ref1.is_some() {
468 SB128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
469 }
470 Ok(())
471}
472
473/// lane-b128hv: one 128x64 (HORZ) or 64x128 (VERT) inter block, the two
474/// halves a `PARTITION_HORZ`/`PARTITION_VERT` 128 superblock root carries --
475/// the syntax `decode_inter_block` reads for `sb128_rect` (decode.rs ~35343):
476/// the same chain [`write_inter_block_128`] writes, at the block's own
477/// rectangular window. Every CDF/context decision is taken at the enclosing
478/// square `side` of 128 (what the decoder's `inter_piece!` passes), and the
479/// block's true footprint governs only its mv-stack window, its mi/grid stamp
480/// and its neighbour bands (decode.rs' own `write_w`/`write_h` split).
481///
482/// lane-ab128: also the two 64x64 squares an AB shape codes (the `w == h`
483/// arm below) and its 128x64 / 64x128 half.
484///
485/// lane-rectres: a piece may CARRY A RESIDUAL -- the search only ever hands
486/// one over under `EC_AV1_RECTRES` ([`crate::encode::rectres`]), and then it
487/// is coded here exactly as `decode_inter_block` reads it: one TX_64X64 luma
488/// unit plus a TX_32X32 chroma pair per 64x64 mu chunk (two chunks for a
489/// half, one for a square), each depth-0 in the var-tx tree (a half codes
490/// two `txfm_partition` flags under `TxMode::Select`, a square one).
491///
492/// # Errors
493/// A block that is intra.
494#[allow(clippy::too_many_arguments)]
495fn write_inter_block_128_rect(
496 enc: &mut SymbolEncoder,
497 cdfs: &mut Cdfs,
498 neighbours: &mut Neighbours,
499 grid: &mut MiGrid,
500 // The half's own top-left position in mode-info (4x4) units.
501 at_mi: (usize, usize),
502 // Its true footprint in samples: (128, 64) at HORZ, (64, 128) at VERT.
503 (w, h): (usize, usize),
504 block: &BlockCoeffs,
505 mi_cols: u32,
506 mi_rows: u32,
507 tx_select: bool,
508) -> Result<()> {
509 let info = block.inter.ok_or_else(|| {
510 Error::unsupported("AV1 tile", "a 128-root rectangular half is coded inter")
511 })?;
512 let (mi_r, mi_c) = at_mi;
513 let (w_mi, h_mi) = (w / MI, h / MI);
514 let has_above = neighbours.has_above(mi_r);
515 let has_left = neighbours.has_left(mi_c);
516 let skip_ctx =
517 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
518 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
519 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
520 // NOT a whole superblock: decode.rs' `whole_sb` is `write_w == write_h ==
521 // sb_px`, so a rect half reads its `delta_q` group even when skipped.
522 write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
523 let ii_ctx = intra_inter_ctx(
524 has_above,
525 has_left,
526 neighbours.above_inter[mi_c],
527 neighbours.left_inter[mi_r],
528 );
529 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
530 write_comp_mode(
531 enc,
532 cdfs,
533 neighbours,
534 (mi_r, mi_c),
535 (has_above, has_left),
536 info.ref1.is_some(),
537 );
538 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
539 write_compound_block(
540 enc,
541 cdfs,
542 neighbours,
543 grid,
544 (mi_r, mi_c),
545 (w_mi, h_mi),
546 (has_above, has_left),
547 info,
548 (mi_cols as usize, mi_rows as usize),
549 )?
550 } else {
551 write_single_ref(
552 enc,
553 cdfs,
554 info.ref_frame,
555 neighbours.above_ref[mi_c],
556 neighbours.above_ref1[mi_c],
557 neighbours.left_ref[mi_r],
558 neighbours.left_ref1[mi_r],
559 );
560 let stack = find_mv_stack(
561 grid,
562 mi_r,
563 mi_c,
564 w_mi,
565 h_mi,
566 info.ref_frame,
567 mi_cols as usize,
568 mi_rows as usize,
569 );
570 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
571 (mv, (0, 0), is_new_mv)
572 };
573 for dr in 0..h_mi {
574 for dc in 0..w_mi {
575 grid.set(
576 mi_r + dr,
577 mi_c + dc,
578 MiInfo {
579 is_inter: true,
580 ref_frame: info.ref_frame,
581 ref_frame1: info.ref1.unwrap_or(NO_REF1),
582 mv1: mv16(mv1),
583 mv: mv16(mv),
584 is_new_mv,
585 size: w_mi as u8,
586 size_h: h_mi as u8,
587 is_global_mv0: false,
588 is_global_mv1: false,
589 },
590 );
591 }
592 }
593 if info.ref1.is_none() {
594 write_motion_mode(
595 enc,
596 cdfs,
597 grid,
598 (mi_r, mi_c),
599 (w_mi, h_mi),
600 (w, h),
601 (mi_cols as usize, mi_rows as usize),
602 info.ref_frame,
603 block.motion_mode,
604 )?;
605 }
606 // The 64x64 mu chunks the residual is coded in, raster order -- the
607 // decoder's own walk: two for a half, one for a square piece.
608 let chunks: &[(usize, usize)] = match (w, h) {
609 (128, 64) => &[(0, 0), (0, 1)],
610 (64, 128) => &[(0, 0), (1, 0)],
611 _ => &[(0, 0)],
612 };
613 // A half's uv plane block (64x32 / 32x64) is wider or taller than its
614 // 32x32 unit, so the unit's `txb_skip_ctx` takes `get_txb_ctx`'s
615 // offset-10 rows (+3 here); a 64x64 piece's uv block IS the unit and
616 // takes none. The half is also the only shape whose chroma is re-stamped
617 // per mu chunk at the end (decode.rs' `mu_chroma`).
618 let is_half = w.max(h) > 64;
619 if tx_select {
620 if block.skip {
621 // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect`
622 // with the BLOCK's own size in both bands, no symbol.
623 neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h));
624 } else if is_half {
625 // The var-tx tree of a 128x64 / 64x128 block enters at TX_64X64
626 // once per mu chunk (`read_block_tx_size_rect`'s `max_tx = 64`
627 // loop), so it is two depth-0 `txfm_split` flags of zero, each
628 // read against the bands the chunks before it published.
629 for &(cr, cc) in chunks {
630 let unit = (mi_r + cr * 16, mi_c + cc * 16);
631 let ctx = txfm_partition_ctx_rect(
632 neighbours.above_txfm[unit.1],
633 neighbours.left_txfm[unit.0],
634 w.max(h),
635 64,
636 64,
637 );
638 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
639 neighbours.record_txfm(unit, 64, 64, 64);
640 }
641 } else {
642 // A 64x64 piece is one whole TX_64X64: the single depth-0 flag
643 // the 64 root's own writer codes (`write_tx_syntax_inter`).
644 write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SB, true, false, 0);
645 }
646 }
647 let zero_grids = [
648 vec![0i32; TX32 * TX32],
649 vec![0i32; TX32 * TX32],
650 vec![0i32; TX32 * TX32],
651 ];
652 // A 128 root's half is always SUB (16 px) aligned, so the coarse mode /
653 // side bands are named by the same SUB-grid origin every square block
654 // uses.
655 let at_sub = (mi_r / (SUB / MI), mi_c / (SUB / MI));
656 if !block.skip {
657 // lane-rectres: the packed 64-wide level grids the search hands over,
658 // one plane each (the same layout `write_inter_block_128` slices for
659 // the whole block, here with the piece's own chunk list).
660 let packed = [
661 level_grid(&block.luma, 64)?,
662 level_grid(&block.u, 64)?,
663 level_grid(&block.v, 64)?,
664 ];
665 let scan32 = default_scan(TX32);
666 let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec<i32> {
667 (0..32)
668 .flat_map(|row| packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec())
669 .collect()
670 };
671 let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
672 for &(cr, cc) in chunks {
673 let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
674 // The luma unit, and the context its all-zero flag reads: a
675 // HALF's unit is smaller than its block (neighbour magnitude
676 // table), a square's IS the whole plane block (fixed zero --
677 // `read_inter_plane`'s `luma_skip_ctx.unwrap_or(0)`, the 64
678 // root's own writer rule). It publishes its context before the
679 // next chunk reads it.
680 let luma = unit_of(0, cr, cc);
681 let skip_ctx = if is_half {
682 neighbours.luma_skip_ctx(unit_mi, 64 / MI)
683 } else {
684 0
685 };
686 let around = neighbours.around_mi(unit_mi, 64);
687 write_coeffs(
688 enc,
689 &mut cdfs.txb(TxbSet::Luma64, 0),
690 &luma,
691 &scan32,
692 skip_ctx,
693 dc_sign_ctx(around[0].dc_vote),
694 Some(0),
695 TxType::DctDct,
696 );
697 neighbours.record_mi_luma(unit_mi, 64, &luma);
698 // Then this chunk's chroma pair, before the next chunk's luma:
699 // libaom codes every plane of a mu chunk before moving on.
700 let mut pair = [Vec::new(), Vec::new()];
701 for plane in 1..3usize {
702 let grid = unit_of(plane, cr, cc);
703 let around = neighbours.around_mi(unit_mi, 64)[plane];
704 write_coeffs(
705 enc,
706 &mut cdfs.txb(TxbSet::Chroma32, 0),
707 &grid,
708 &scan32,
709 usize::from(around.above_coded)
710 + usize::from(around.left_coded)
711 + 3 * usize::from(is_half),
712 dc_sign_ctx(around.dc_vote),
713 Some(plane),
714 TxType::DctDct,
715 );
716 neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
717 pair[plane - 1] = grid;
718 }
719 chroma_units.push((unit_mi, pair));
720 }
721 // decode.rs' own tail (`record_split_luma_rect_mi` then, on a half,
722 // the per-chunk chroma re-stamp): the block-level write off the
723 // whole assembled chroma plane grid, luma kept because each unit
724 // already published its own, and then the per-unit chroma writes
725 // replayed over it -- last writer wins, so the next block reads the
726 // units.
727 let block_grids = [
728 vec![0i32; TX32 * TX32],
729 packed[1].clone(),
730 packed[2].clone(),
731 ];
732 neighbours.record_planes_rect(at_sub, (w, h), 0, &block_grids, false);
733 if is_half {
734 for (unit_mi, pair) in &chroma_units {
735 neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
736 neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
737 }
738 }
739 SB128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
740 } else {
741 neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
742 }
743 neighbours.record_inter_rect_mi((mi_r, mi_c), (w, h), block.skip, true, block_ref(block));
744 if let Some(r1) = info.ref1 {
745 neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1);
746 }
747 // lane-ab128: an AB shape codes its two 64x64 pieces through this same
748 // function, and they are neither a 128x64 nor a 64x128 half -- the
749 // witness reads these two counters for the HORZ/VERT shape alone.
750 if w > h {
751 SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
752 } else if h > w {
753 SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
754 }
755 Ok(())
756}
757
758/// lane-b128hv: how many 128x64 / 64x128 halves the inter writer has coded
759/// since the last [`take_sb128_horz_hits`] / [`take_sb128_vert_hits`] (class
760/// `gate-blind-to-feature`).
761static SB128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
762/// The VERT twin of [`SB128_HORZ_HITS`].
763static SB128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
764
765/// The 128x64-half count since the last call, and zero it.
766pub fn take_sb128_horz_hits() -> usize {
767 SB128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
768}
769
770/// The 64x128-half count since the last call, and zero it.
771pub fn take_sb128_vert_hits() -> usize {
772 SB128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
773}
774
775/// lane-ab128: how many AB-shape roots the inter writer has coded since the
776/// last [`take_sb128_ab_hits`], in `PARTITION_HORZ_A` .. `_VERT_B` order
777/// (class `gate-blind-to-feature`).
778static SB128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
779 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
780
781/// The four per-shape AB-root counts since the last call, and zero them.
782pub fn take_sb128_ab_hits() -> [usize; 4] {
783 std::array::from_fn(|i| SB128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
784}
785
786/// lane-b128r: how many of those blocks carried a REAL residual (four
787/// TX_64X64 luma units plus their per-chunk chroma pair) rather than being
788/// skipped, since the last [`take_sb128_residual_hits`].
789static SB128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
790
791/// The 128x128-with-residual count since the last call, and zero it.
792pub fn take_sb128_residual_hits() -> usize {
793 SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
794}
795/// lane-rectres: how many RECT/AB pieces (the halves and 64x64 squares
796/// [`write_inter_block_128_rect`] codes) carried a REAL residual rather than
797/// being skipped, since the last [`take_sb128_rectres_hits`] -- the writer
798/// side of [`crate::encode::take_b128_rectres_hits`]'s search count.
799static SB128_RECTRES_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
800
801/// The rect/AB-piece-with-residual count since the last call, and zero it.
802pub fn take_sb128_rectres_hits() -> usize {
803 SB128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
804}
805
806/// lane-b128r: how many of those blocks named a SECOND reference (the
807/// compound arm at the 128 root), since the last
808/// [`take_sb128_compound_hits`].
809static SB128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
810
811/// The compound-128 count since the last call, and zero it.
812pub fn take_sb128_compound_hits() -> usize {
813 SB128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
814}
815
816/// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since
817/// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).
818static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
819
820/// The 128x128-block count since the last call, and zero it.
821pub fn take_sb128_none_hits() -> usize {
822 SB128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
823}
824
825/// `read_lr`'s write side, called once at the top of every superblock,
826/// before its partition symbol: writes the units this superblock's own
827/// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
828/// column scaling is the plain mi one).
829fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32, span: u32) {
830 LR_PLAN.with(|c| {
831 let mut plan = c.borrow_mut();
832 let Some(plan) = plan.as_mut() else { return };
833 let unit = plan.unit_size;
834 let rcol0 = (mi_col * 4).div_ceil(unit);
835 let rcol1 = ((mi_col + span) * 4).div_ceil(unit).min(plan.horz_units);
836 let rrow0 = (mi_row * 4).div_ceil(unit);
837 let rrow1 = ((mi_row + span) * 4).div_ceil(unit).min(plan.vert_units);
838 for rrow in rrow0..rrow1 {
839 for rcol in rcol0..rcol1 {
840 let info = plan.units[(rcol + rrow * plan.horz_units) as usize];
841 enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener);
842 if let Some(info) = info {
843 crate::restoration::write_wiener_filter(enc, false, &mut plan.reference, &info);
844 }
845 }
846 }
847 });
848}
849
850/// A 64x64 superblock's width in 4x4 mode-info units (`SB_MI` in
851/// `crate::decode`), the span [`write_lr`] resolves its units over.
852const SB_MI_W: u32 = 16;
853
854/// One tile's own superblock and mode-info span (spec 5.11.1's tile loop
855/// bounds): `MiColStarts[i]..MiColStarts[i+1]` and the same down the rows,
856/// with the superblock indices those mi bounds fall on. The writers walk
857/// exactly this rect, and everything a block reads outside it -- the
858/// neighbour bands, the MV grid -- is left at the "unavailable" state a
859/// tile's own first row and column see, which is how the decoder clips them
860/// (`MiGrid::set_tile_bounds`, `PlaneBuf::set_tile_origin`).
861#[derive(Clone, Copy, Debug, PartialEq, Eq)]
862pub(crate) struct TileRect {
863 pub(crate) sb_col0: u32,
864 pub(crate) sb_col1: u32,
865 pub(crate) sb_row0: u32,
866 pub(crate) sb_row1: u32,
867 pub(crate) mi_col0: u32,
868 pub(crate) mi_col1: u32,
869 pub(crate) mi_row0: u32,
870 pub(crate) mi_row1: u32,
871}
872
873impl TileRect {
874 /// The whole frame as one tile -- what every single-tile caller writes.
875 pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self {
876 let (cols, rows) = block_grid(mi_cols, mi_rows);
877 Self {
878 sb_col0: 0,
879 sb_col1: cols.div_ceil(2),
880 sb_row0: 0,
881 sb_row1: rows.div_ceil(2),
882 mi_col0: 0,
883 mi_col1: mi_cols,
884 mi_row0: 0,
885 mi_row1: mi_rows,
886 }
887 }
888}
889
890/// A frame's uniform tile grid (spec 5.9.15's `uniform_tile_spacing_flag`
891/// arm, mirrored from `ec_av1_syntax::frame::read_tile_info` so that what
892/// this encoder writes and what a decoder derives from the same two log2
893/// fields are the same rects). 64x64 superblocks only, which is the only
894/// size this encoder's sequence header signals.
895#[derive(Clone, Debug)]
896pub(crate) struct TileLayout {
897 pub(crate) cols_log2: u32,
898 pub(crate) rows_log2: u32,
899 /// Tile column starts in superblocks, `cols + 1` entries.
900 col_starts_sb: Vec<u32>,
901 /// Tile row starts in superblocks, `rows + 1` entries.
902 row_starts_sb: Vec<u32>,
903 mi_cols: u32,
904 mi_rows: u32,
905}
906
907impl TileLayout {
908 /// The layout `cols_log2`/`rows_log2` name for this frame's mi grid.
909 pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self {
910 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
911 let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2));
912 // lane-sb128: a tile boundary is a SUPERBLOCK boundary, so under a
913 // 128 superblock the starts are laid out on the 128 grid and then
914 // doubled back into the 64-cell units the writers walk.
915 let unit = u32::from(crate::encode::sb128_on()) + 1;
916 let starts = |total: u32, log2: u32| {
917 let total128 = total.div_ceil(unit);
918 let step = total128.div_ceil(1 << log2).max(1);
919 let mut v: Vec<u32> = (0..total128)
920 .step_by(step as usize)
921 .map(|s| s * unit)
922 .collect();
923 v.push(total);
924 v
925 };
926 Self {
927 cols_log2,
928 rows_log2,
929 col_starts_sb: starts(sb_cols, cols_log2),
930 row_starts_sb: starts(sb_rows, rows_log2),
931 mi_cols,
932 mi_rows,
933 }
934 }
935
936 pub(crate) fn cols(&self) -> u32 {
937 self.col_starts_sb.len() as u32 - 1
938 }
939
940 pub(crate) fn rows(&self) -> u32 {
941 self.row_starts_sb.len() as u32 - 1
942 }
943
944 pub(crate) fn count(&self) -> usize {
945 (self.cols() * self.rows()) as usize
946 }
947
948 /// `MiColStarts`/`MiRowStarts` as the frame header carries them.
949 pub(crate) fn mi_col_starts(&self) -> Vec<u32> {
950 let mut v: Vec<u32> = self.col_starts_sb[..self.cols() as usize]
951 .iter()
952 .map(|sb| sb * SB_MI_W)
953 .collect();
954 v.push(self.mi_cols);
955 v
956 }
957
958 pub(crate) fn mi_row_starts(&self) -> Vec<u32> {
959 let mut v: Vec<u32> = self.row_starts_sb[..self.rows() as usize]
960 .iter()
961 .map(|sb| sb * SB_MI_W)
962 .collect();
963 v.push(self.mi_rows);
964 v
965 }
966
967 /// Tile `index` (row major, `TileNum`) as a rect.
968 pub(crate) fn rect(&self, index: usize) -> TileRect {
969 let (r, c) = (index / self.cols() as usize, index % self.cols() as usize);
970 let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]);
971 let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]);
972 TileRect {
973 sb_col0,
974 sb_col1,
975 sb_row0,
976 sb_row1,
977 mi_col0: sb_col0 * SB_MI_W,
978 mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols),
979 mi_row0: sb_row0 * SB_MI_W,
980 mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows),
981 }
982 }
983
984 /// The largest tile by mi area, `context_update_tile_id`'s own rule
985 /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both
986 /// name the biggest tile, whose end-of-tile tables the frame stores).
987 pub(crate) fn largest_tile(&self) -> usize {
988 (0..self.count())
989 .max_by_key(|&i| {
990 let t = self.rect(i);
991 ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64)
992 })
993 .unwrap_or(0)
994 }
995}
996
997/// lane-edge128: which 64x64 CDEF unit's `cdef_idx` literal covers each unit
998/// of this frame, in the same raster order [`arm_cdef_idx`]'s grid is in.
999///
1000/// `read_cdef` (spec 5.11.56) codes ONE literal for the block that first
1001/// reaches a unit and copies it over every unit that block SPANS, so a whole
1002/// 128x128 root block puts one literal in the stream for all four of its
1003/// units -- the encoder's CDEF search, which prices a preset per unit, may
1004/// not hand those four units different presets: only the first would be
1005/// coded, and every decoder (ours and ffmpeg's alike) would apply it to all
1006/// four while the encoder's own filter replay applied four different ones.
1007/// That is the shape this map exists to collapse
1008/// ([`crate::filter_search::pick_filters`]).
1009///
1010/// lane-rectres: the same holds for a Rect128 half or an Ab128 half that
1011/// carries a residual (`EC_AV1_RECTRES`) -- it codes one literal at its own
1012/// origin and the decoder stamps BOTH units it spans with it, so its pair is
1013/// collapsed onto the origin unit too. Its 64x64 squares cover exactly one
1014/// unit each, and a SKIP-ONLY rect/AB piece codes no literal at all (the
1015/// decoder's per-piece `cdef_transmitted` reset never fires), so neither
1016/// touches this map -- only pieces the writer really codes a residual for.
1017pub(crate) fn cdef_unit_owner(blocks: &[Quadrant], mi_cols: u32, mi_rows: u32) -> Vec<u32> {
1018 let (cols, rows) = block_grid(mi_cols, mi_rows);
1019 let (sb_cols, sb_rows) = (cols.div_ceil(2) as usize, rows.div_ceil(2) as usize);
1020 let mut owner: Vec<u32> = (0..(sb_cols * sb_rows) as u32).collect();
1021 // Collapses every 64x64 unit `(ur, uc) ..` a residual piece at unit
1022 // `(ur, uc)` with footprint `(w, h)` spans onto the piece's origin --
1023 // [`crate::encode::write_inter_block_128_rect`]'s one `write_cdef_idx`
1024 // is what the decoder copies over all of them.
1025 let collapse = |owner: &mut Vec<u32>, (ur, uc): (usize, usize), (w, h): (usize, usize)| {
1026 let origin = (ur * sb_cols + uc) as u32;
1027 for r in ur..(ur + (h / 64).max(1)).min(sb_rows) {
1028 for c in uc..(uc + (w / 64).max(1)).min(sb_cols) {
1029 owner[r * sb_cols + c] = origin;
1030 }
1031 }
1032 };
1033 for sb_r in (0..sb_rows).step_by(2) {
1034 for sb_c in (0..sb_cols).step_by(2) {
1035 let Some(root) = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize)
1036 .then(|| &blocks[(sb_r * 2) * cols as usize + sb_c * 2])
1037 else {
1038 continue;
1039 };
1040 match root {
1041 Quadrant::Whole128(_) => {
1042 let origin = (sb_r * sb_cols + sb_c) as u32;
1043 for r in sb_r..(sb_r + 2).min(sb_rows) {
1044 for c in sb_c..(sb_c + 2).min(sb_cols) {
1045 owner[r * sb_cols + c] = origin;
1046 }
1047 }
1048 }
1049 // lane-rectres: the two halves of a HORZ/VERT root sit in
1050 // different unit rows (HORZ) / columns (VERT); each
1051 // non-skip half collapses its own pair.
1052 Quadrant::Rect128(horz, halves) => {
1053 for (i, half) in halves.iter().enumerate() {
1054 if half.skip {
1055 continue;
1056 }
1057 let (ur, uc) = if *horz {
1058 (sb_r + i, sb_c)
1059 } else {
1060 (sb_r, sb_c + i)
1061 };
1062 let (w, h) = if *horz { (128, 64) } else { (64, 128) };
1063 collapse(&mut owner, (ur, uc), (w, h));
1064 }
1065 }
1066 // lane-rectres: the AB half is the only multi-unit piece
1067 // (its two squares are one unit each); only a non-skip one
1068 // codes a literal, so only it fires.
1069 Quadrant::Ab128(symbol, pieces) => {
1070 for (piece, ((mi_r, mi_c), (w, h))) in pieces
1071 .iter()
1072 .zip(crate::encode::ab128_pieces(usize::from(*symbol), (0, 0)))
1073 {
1074 if piece.skip {
1075 continue;
1076 }
1077 let (ur, uc) = (sb_r + mi_r / 16, sb_c + mi_c / 16);
1078 collapse(&mut owner, (ur, uc), (w, h));
1079 }
1080 }
1081 _ => {}
1082 }
1083 }
1084 }
1085 owner
1086}
1087
1088/// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
1089struct CdefIdxPlan {
1090 /// The header's `cdef_bits`; never 0 while armed.
1091 bits: u8,
1092 /// Superblocks per row, the stride of `grid`.
1093 sb_cols: usize,
1094 /// One index per 64x64 superblock, in raster order.
1095 grid: Vec<u8>,
1096 /// The superblock whose literal was already written -- the decoder's
1097 /// `cdef_transmitted`, which resets at every superblock and which coding
1098 /// order (each superblock's blocks are contiguous) makes a single slot.
1099 last: Option<usize>,
1100}
1101
1102thread_local! {
1103 static CDEF_IDX: std::cell::RefCell<Option<CdefIdxPlan>> =
1104 const { std::cell::RefCell::new(None) };
1105}
1106
1107/// Arms the next tile write with one `cdef_idx` per 64x64 superblock.
1108/// `bits == 0` disarms (the header codes a single strength pair, so the tile
1109/// carries no literal at all).
1110pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
1111 CDEF_IDX.with(|c| {
1112 *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan {
1113 bits,
1114 sb_cols,
1115 grid,
1116 last: None,
1117 });
1118 });
1119}
1120
1121/// One frame's per-superblock quantizer plan (lane-deltaq, see
1122/// [`arm_delta_q`]): the writer side of decode.rs `maybe_read_delta_q`.
1123struct DeltaQPlan {
1124 /// `1 << delta_q_res`, the multiplier the coded symbol is scaled by --
1125 /// every `grid` entry is congruent to `base` modulo it, so the delta the
1126 /// writer codes is always a whole number of steps.
1127 res: i32,
1128 /// Superblocks per row, the stride of `grid`.
1129 sb_cols: usize,
1130 /// The absolute `qindex` each 64x64 superblock is coded at, raster order.
1131 grid: Vec<u8>,
1132 /// The spec's `CurrentQIndex`, carried across the superblocks of THIS
1133 /// tile -- armed at the frame's `base_q_idx` because a tile writer is
1134 /// armed once per tile (`encode_inter_frame`'s `code_tiles`), which is
1135 /// exactly the spec's own per-tile reset.
1136 cur: i32,
1137}
1138
1139thread_local! {
1140 static DELTA_Q: std::cell::RefCell<Option<DeltaQPlan>> =
1141 const { std::cell::RefCell::new(None) };
1142}
1143
1144/// Arms the next tile write with one absolute `qindex` per 64x64 superblock.
1145/// Disarmed (a plain no-op writer, byte for byte what this crate wrote before
1146/// lane-deltaq) when `res == 0`.
1147pub(crate) fn arm_delta_q(res: i32, sb_cols: usize, grid: Vec<u8>, base: u8) {
1148 DELTA_Q.with(|c| {
1149 *c.borrow_mut() = (res > 0).then(|| DeltaQPlan {
1150 res,
1151 sb_cols,
1152 grid,
1153 cur: i32::from(base),
1154 });
1155 });
1156}
1157
1158thread_local! {
1159 static SIGN_BIAS: std::cell::Cell<crate::mvstack::SignBiasTable> =
1160 const { std::cell::Cell::new(crate::mvstack::NO_SIGN_BIAS) };
1161}
1162
1163/// Arms the next tile write with this frame's `ref_frame_sign_bias` (spec
1164/// 5.9.2), the table its MV-stack scans run under. Armed the same way
1165/// [`arm_cdef_idx`]/[`arm_lr`] are -- and disarmed by the same guard -- so
1166/// that a frame with a backward reference needs no new parameter on the four
1167/// nested writer helpers between here and `find_mv_stack`. A frame that never
1168/// names a future reference leaves this alone: all-`false` is what every
1169/// stream this crate wrote before pyramids existed codes under.
1170pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
1171 SIGN_BIAS.with(|c| c.set(sign_bias));
1172}
1173
1174thread_local! {
1175 static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1176}
1177
1178/// Arms the next tile write with this frame's `allow_screen_content_tools`
1179/// (spec 5.9.2), which is what makes every intra block carry the
1180/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46
1181/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/
1182/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that
1183/// never detected screen content writes exactly the stream it wrote before
1184/// this lane.
1185pub(crate) fn arm_screen(on: bool) {
1186 SCREEN.with(|c| c.set(on));
1187}
1188
1189thread_local! {
1190 /// This frame's `(mi_rows, mi_cols)` (spec `compute_image_size`), armed
1191 /// beside [`SCREEN`] by both frame encoders: a palette block cut by the
1192 /// frame's right/bottom mi edge codes its colour-index map over the
1193 /// ON-SCREEN part only, so the writer needs the same dims the decoder's
1194 /// `palette_onscreen` reads off its `FrameCtx` (lane-palw). `(0, 0)`
1195 /// -- an unarmed writer, i.e. a unit test coding one block -- clamps
1196 /// nothing, which is what every stream without a cut palette block codes.
1197 static FRAME_MI_DIMS: std::cell::Cell<(usize, usize)> =
1198 const { std::cell::Cell::new((0, 0)) };
1199}
1200
1201/// Arms the next tile write with this frame's `(mi_rows, mi_cols)`.
1202pub(crate) fn arm_frame_mi_dims(dims: (usize, usize)) {
1203 FRAME_MI_DIMS.with(|c| c.set(dims));
1204}
1205
1206/// The armed `(mi_rows, mi_cols)`, or a grid big enough to clamp nothing.
1207fn frame_mi_dims() -> (usize, usize) {
1208 match FRAME_MI_DIMS.with(std::cell::Cell::get) {
1209 (0, 0) => (usize::MAX / 8, usize::MAX / 8),
1210 dims => dims,
1211 }
1212}
1213
1214fn screen_armed() -> bool {
1215 SCREEN.with(std::cell::Cell::get)
1216}
1217
1218thread_local! {
1219 /// This frame header's `allow_intrabc` (spec 5.9.2), armed exactly like
1220 /// [`SCREEN`]: with it every intra block of the tile carries a
1221 /// `use_intrabc` symbol right after `skip`/`cdef`/`delta_q` (decode.rs
1222 /// `read_intra_mode`), so a tile written without it and read with it
1223 /// desyncs at the first block.
1224 static INTRABC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1225 /// The mi grid the DV predictor is built off (decode.rs
1226 /// `INTRABC_MI_GRID`/`record_intrabc_mi`): every coded block publishes
1227 /// its own footprint into it, an intrabc one also its DV as an
1228 /// `INTRA_FRAME` candidate. `Some` only while an `allow_intrabc` tile is
1229 /// being written.
1230 static INTRABC_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1231 const { std::cell::RefCell::new(None) };
1232}
1233
1234/// Arms the frame's `allow_intrabc` bit for the next tile written on this
1235/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
1236pub(crate) fn arm_intrabc(on: bool) {
1237 INTRABC.with(|c| c.set(on));
1238}
1239
1240fn intrabc_armed() -> bool {
1241 INTRABC.with(std::cell::Cell::get)
1242}
1243
1244thread_local! {
1245 /// This SEQUENCE header's `enable_filter_intra` (spec 5.5.2), armed
1246 /// exactly like [`SCREEN`]: with it every DC_PRED intra block of at most
1247 /// 32x32 that took no luma palette carries a `use_filter_intra` symbol
1248 /// after the palette colours and before the colour-index maps (decode.rs
1249 /// `read_intra_mode`), so a tile written without it and read with it
1250 /// desyncs at the first such block.
1251 static FILTER_INTRA: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1252}
1253
1254/// Arms the sequence's `enable_filter_intra` bit for the next tile written on
1255/// this thread; cleared by [`CdefIdxGuard`] when that writer returns.
1256pub(crate) fn arm_filter_intra(on: bool) {
1257 FILTER_INTRA.with(|c| c.set(on));
1258}
1259
1260fn filter_intra_armed() -> bool {
1261 FILTER_INTRA.with(std::cell::Cell::get)
1262}
1263
1264/// How many blocks this writer coded `use_filter_intra == 1`, and the
1265/// histogram of the five `filter_intra_mode`s (index 1..=5) -- the fire count
1266/// a gate prints so that "filter intra is on" is a measurement rather than a
1267/// claim (class `gate-blind-to-feature`). Index 0 is the block count.
1268static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] =
1269 [const { std::sync::atomic::AtomicUsize::new(0) }; 6];
1270
1271/// Reads [`FILTER_INTRA_HITS`] and zeroes it, so a gate can attribute the
1272/// counts to its own encode.
1273#[cfg(test)]
1274pub(crate) fn take_filter_intra_hits() -> [usize; 6] {
1275 std::array::from_fn(|i| FILTER_INTRA_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1276}
1277
1278/// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for
1279/// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every
1280/// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <=
1281/// 32, [`crate::decode::filter_intra_size_class`]) and that took no luma
1282/// palette (`av1_filter_intra_allowed`, reconintra.h:77), then the chosen mode
1283/// of five. Sits between the palette COLOUR lists and the colour-index maps,
1284/// where libaom reads it (`av1_visit_palette` runs after
1285/// `read_filter_intra_mode_info`).
1286fn write_filter_intra(
1287 enc: &mut SymbolEncoder,
1288 cdfs: &mut Cdfs,
1289 mode: usize,
1290 side: usize,
1291 has_palette_y: bool,
1292 filter_intra: Option<u8>,
1293) {
1294 if !filter_intra_armed() || mode != DC_PRED || has_palette_y {
1295 debug_assert!(
1296 filter_intra.is_none(),
1297 "no `use_filter_intra` symbol exists here"
1298 );
1299 return;
1300 }
1301 let Some(class) = crate::decode::filter_intra_size_class(side) else {
1302 debug_assert!(
1303 filter_intra.is_none(),
1304 "past av1_filter_intra_allowed_bsize"
1305 );
1306 return;
1307 };
1308 enc.symbol(
1309 usize::from(filter_intra.is_some()),
1310 &mut cdfs.filter_intra[class],
1311 );
1312 if let Some(fi) = filter_intra {
1313 enc.symbol(usize::from(fi), &mut cdfs.filter_intra_mode);
1314 FILTER_INTRA_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1315 FILTER_INTRA_HITS[usize::from(fi) + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1316 }
1317}
1318
1319/// The coefficient-table row a block's luma transform types are coded from:
1320/// `fimode_to_intradir[filter_intra_mode]` for a filter-intra block, its own
1321/// luma mode otherwise (class `filter-intra tx_type row`, decode.rs
1322/// [`crate::decode::fi_tx_row`]). The block still PUBLISHES `DC_PRED` as its
1323/// neighbour mode -- libaom's `mbmi->mode` is unchanged by filter intra.
1324fn tx_row(mode: usize, filter_intra: Option<u8>) -> usize {
1325 crate::decode::fi_tx_row(mode, filter_intra.map(usize::from))
1326}
1327
1328/// How many blocks this writer coded `use_intrabc == 1`, and the histogram of
1329/// their DV magnitudes in full pels (index 1..=6 = 1, 2, 4, 8, 16, 32 pels
1330/// and up, by the larger component) -- the fire count a gate prints so that
1331/// "intrabc is on" is a measurement rather than a claim (class
1332/// `gate-blind-to-feature`). Index 0 is the block count.
1333static INTRABC_HITS: [std::sync::atomic::AtomicUsize; 7] =
1334 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1335
1336fn note_intrabc(dv: (i32, i32)) {
1337 INTRABC_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1338 let px = (dv.0.abs() / 8).max(dv.1.abs() / 8).max(1) as usize;
1339 let bucket = (usize::BITS - px.leading_zeros()) as usize;
1340 INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1341}
1342
1343/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts
1344/// to its own encode.
1345#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1346pub(crate) fn take_intrabc_hits() -> [usize; 7] {
1347 std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1348}
1349
1350thread_local! {
1351 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
1352 /// the same way `arm_sign_bias` arms the sign-bias table rather than
1353 /// threaded through the five nested writer helpers between here and the
1354 /// per-block mode syntax. `true` makes every inter block of size at least
1355 /// 8x8 code a `comp_mode` symbol, exactly where decode.rs `read_comp_mode`
1356 /// reads one.
1357 static REFERENCE_SELECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1358}
1359
1360/// Arms the frame's `reference_select` bit for the next tile written on this
1361/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
1362pub(crate) fn arm_reference_select(on: bool) {
1363 REFERENCE_SELECT.with(|c| c.set(on));
1364}
1365
1366thread_local! {
1367 /// This frame header's own `is_motion_mode_switchable` bit (spec 5.9.2),
1368 /// armed exactly like [`REFERENCE_SELECT`]. `true` makes every
1369 /// single-reference inter block that libaom's `motion_mode_allowed`
1370 /// accepts carry a `motion_mode`/`obmc` symbol right after its MV syntax,
1371 /// exactly where decode.rs' `read_motion_mode` reads one.
1372 static MOTION_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1373}
1374
1375thread_local! {
1376 /// This frame header's own `allow_warped_motion` bit (spec 5.9.2): with
1377 /// it set, every block libaom's `motion_mode_allowed` accepts AND that
1378 /// has at least one warp sample (`num_proj_ref >= 1`) reads the 3-symbol
1379 /// `motion_mode_cdf` alphabet instead of the 2-symbol `obmc_cdf` one.
1380 /// lane-av1obmc2.
1381 static WARPED_MOTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1382 /// The frame geometry the warp-sample walk needs (`num_proj_ref` ->
1383 /// `has_top_right`), which is only ever this writer's own superblock
1384 /// size. Every stream this crate writes uses a 64 superblock, which is
1385 /// `FrameCtx::new`'s default.
1386 /// corner-cut: ceiling is a 128-superblock WRITER -- it must arm the real
1387 /// frame context here (or take one as a parameter) or the warp-sample
1388 /// walk reads the wrong `has_top_right` geometry.
1389 static WRITER_FCTX: crate::decode::FrameCtx = crate::decode::FrameCtx::new();
1390}
1391
1392/// Arms [`WARPED_MOTION`] for the next tile written on this thread.
1393pub(crate) fn arm_warped_motion(on: bool) {
1394 WARPED_MOTION.with(|c| c.set(on));
1395}
1396
1397/// Arms the frame's `is_motion_mode_switchable` bit for the next tile written
1398/// on this thread; cleared by [`CdefIdxGuard`] when that writer returns.
1399pub(crate) fn arm_motion_mode(on: bool) {
1400 MOTION_MODE.with(|c| c.set(on));
1401}
1402
1403/// How many single-reference inter blocks this writer coded a `motion_mode`
1404/// symbol for, split by the value it coded and by the block's own footprint
1405/// -- the histogram a gate prints so that "OBMC is on" is a measurement, not
1406/// a claim (class `gate-blind-to-feature`). Index: `0 + 2 * bucket` for
1407/// SIMPLE, `1 + 2 * bucket` for OBMC, bucket 0/1/2 = 32x32/16x16/8x8.
1408static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] =
1409 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
1410
1411/// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the
1412/// counts to its own encode.
1413#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1414pub(crate) fn take_motion_mode_hits() -> [usize; 9] {
1415 std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1416}
1417
1418/// What the 3-symbol `motion_mode` symbol costs, in bits, against the same
1419/// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off --
1420/// which alphabet a block reads is `motion_mode_allowed`'s own choice
1421/// ([`write_motion_mode`]).
1422pub(crate) fn motion_mode_symbol_bits(row: usize, motion: u8) -> f64 {
1423 PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
1424 Some(s) => crate::encode::symbol_bits(&s.0.motion_mode[row], usize::from(motion)),
1425 None => crate::encode::symbol_bits(&crate::cdf::MOTION_MODE[row], usize::from(motion)),
1426 })
1427}
1428
1429/// What the `motion_mode`/`obmc` symbol costs, in bits, against the tables
1430/// this frame's writer really starts from ([`arm_pricing_cdfs`]) -- the same
1431/// tables the coefficients are priced off since lane-av1price2, rather than
1432/// the static defaults the symbol used to be estimated with. Falls back to
1433/// the default table whenever the search is armed with the defaults (a key
1434/// frame, or a screen frame the gate turned off).
1435pub(crate) fn obmc_symbol_bits(row: usize, obmc: bool) -> f64 {
1436 PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
1437 Some(s) => crate::encode::symbol_bits(&s.0.obmc[row], usize::from(obmc)),
1438 None => crate::encode::symbol_bits(&crate::cdf::OBMC[row], usize::from(obmc)),
1439 })
1440}
1441
1442/// `read_motion_mode`'s write side (spec 5.11.24), called on a
1443/// single-reference inter block right after its MV syntax and before the
1444/// (never switchable here) interpolation filter -- libaom's own sequential
1445/// order in `read_inter_block_mode_info`.
1446///
1447/// Eligibility is decode.rs' own `motion_mode_eligible`, term for term, with
1448/// the terms this writer settles statically dropped: no block it codes is
1449/// `skip_mode`, interintra or a non-IDENTITY-global `GLOBALMV` one, so what
1450/// is left is the footprint floor and the overlappable-neighbour walk
1451/// ([`crate::decode::has_overlappable_neighbour`], shared with the decoder so
1452/// the two cannot drift). The frame header keeps `allow_warped_motion == 0`,
1453/// so the alphabet is always the 2-symbol `obmc_cdf`, never the 3-symbol
1454/// `motion_mode_cdf`.
1455fn write_motion_mode(
1456 enc: &mut SymbolEncoder,
1457 cdfs: &mut Cdfs,
1458 grid: &MiGrid,
1459 (mi_row, mi_col): (usize, usize),
1460 (bw4, bh4): (usize, usize),
1461 (write_w, write_h): (usize, usize),
1462 (mi_cols, mi_rows): (usize, usize),
1463 // This block's own reference, for the warp-sample walk that picks the
1464 // alphabet (`num_proj_ref`).
1465 ref_frame: i8,
1466 // 0 SIMPLE_TRANSLATION, 1 OBMC_CAUSAL, 2 WARPED_CAUSAL -- what the
1467 // encoder's search committed for this block.
1468 motion: u8,
1469) -> Result<()> {
1470 let eligible = MOTION_MODE.with(std::cell::Cell::get)
1471 && write_w.min(write_h) >= 8
1472 && crate::decode::has_overlappable_neighbour(
1473 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows,
1474 );
1475 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
1476 let proj = WRITER_FCTX.with(|fctx| {
1477 crate::decode::num_proj_ref(
1478 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1479 )
1480 });
1481 eprintln!(
1482 "EC_MMW mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} proj={proj} warp_armed={} motion={motion}",
1483 eligible as u8,
1484 WARPED_MOTION.with(std::cell::Cell::get) as u8,
1485 );
1486 }
1487 if !eligible {
1488 // The encoder trialled an OBMC prediction for a block this writer
1489 // codes as SIMPLE_TRANSLATION: its reconstruction is not the
1490 // decoder's (class encoder-grid-drift), which is exactly what the
1491 // `EC_COMP_MISMATCH` rung exists to catch.
1492 if motion != 0 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
1493 eprintln!(
1494 "EC_COMP_MISMATCH motion_mode enc=OBMC wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
1495 );
1496 }
1497 return Ok(());
1498 }
1499 let row = crate::decode::motion_mode_cdf_row(write_w, write_h).ok_or_else(|| {
1500 Error::unsupported(
1501 "AV1 tile",
1502 format!("a {write_w}x{write_h} block has no motion_mode CDF row"),
1503 )
1504 })?;
1505 // libaom `motion_mode_allowed`: the 3-symbol `motion_mode_cdf` alphabet
1506 // exactly when `allow_warped_motion` is on and the block has at least one
1507 // warp sample. The other two vetoes libaom applies there cannot fire for
1508 // a stream this encoder writes -- it codes no scaled reference and no
1509 // inter frame with `force_integer_mv` -- and the decoder checks all three
1510 // (`decode.rs`'s `warp_eligible`), so the two sides agree term for term.
1511 let warp_alphabet = WARPED_MOTION.with(std::cell::Cell::get)
1512 && WRITER_FCTX.with(|fctx| {
1513 crate::decode::num_proj_ref(
1514 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1515 )
1516 }) >= 1;
1517 if warp_alphabet {
1518 enc.symbol(usize::from(motion), &mut cdfs.motion_mode[row]);
1519 } else {
1520 // A warp winner whose block the writer resolves to the 2-symbol
1521 // alphabet would reconstruct as SIMPLE at the decoder: the same
1522 // encoder-grid-drift rung the OBMC case above prints.
1523 if motion == 2 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
1524 eprintln!(
1525 "EC_COMP_MISMATCH motion_mode enc=WARP wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
1526 );
1527 }
1528 enc.symbol(usize::from(motion == 1), &mut cdfs.obmc[row]);
1529 }
1530 let bucket = match write_w.min(write_h) {
1531 32.. => 0,
1532 16 => 1,
1533 _ => 2,
1534 };
1535 MOTION_MODE_HITS[usize::from(motion.min(2)) + 3 * bucket]
1536 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1537 Ok(())
1538}
1539
1540/// The compound half of a block's end-of-block neighbour record: nothing for
1541/// a single-reference or intra block, and `record_compound_mi`'s overwrite of
1542/// the ALTREF default for a compound one (this writer only codes
1543/// `comp_group_idx == 0`, `compound_idx == 1`).
1544fn record_block_compound(
1545 neighbours: &mut Neighbours,
1546 at_mi: (usize, usize),
1547 side: usize,
1548 block: &BlockCoeffs,
1549) {
1550 if let Some(r1) = block.inter.and_then(|i| i.ref1) {
1551 neighbours.record_compound_mi(at_mi, side, r1, 0, 1);
1552 }
1553}
1554
1555/// decode.rs' own `is_uni_comp_ref`: a pair is `UNIDIR_COMP_REFERENCE`
1556/// exactly when both references sit on the same temporal side.
1557use crate::mvstack::is_uni_comp_ref;
1558
1559thread_local! {
1560 /// `(order_hint_bits, this frame's order hint, each reference's order
1561 /// hint)` -- what `get_comp_index_context` (decode.rs) needs to context
1562 /// the `compound_idx` symbol, armed the same way the sign-bias table is.
1563 static ORDER_HINTS: std::cell::Cell<(u32, u32, [u32; 7])> =
1564 const { std::cell::Cell::new((7, 0, [0; 7])) };
1565}
1566
1567/// Arms this frame's order hints for the next tile written on this thread.
1568pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) {
1569 ORDER_HINTS.with(|c| c.set((bits, order_hint, hints)));
1570}
1571
1572/// What [`arm_order_hints`] last armed: `(order_hint_bits, order_hint,
1573/// ref_order_hints)`, for the encoder's own per-reference distance.
1574pub(crate) fn order_hints() -> (u32, u32, [u32; 7]) {
1575 ORDER_HINTS.with(std::cell::Cell::get)
1576}
1577
1578thread_local! {
1579 /// lane-hpmv: this frame's `allow_high_precision_mv`, armed per worker
1580 /// beside [`arm_order_hints`] -- the writer's eighth-pel symbol, the
1581 /// pricer's mv bits and the motion search's finest step all read it.
1582 static HIGH_PRECISION_MV: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1583}
1584
1585/// Arms this frame's `allow_high_precision_mv` for the next tile written --
1586/// or searched -- on this thread.
1587pub(crate) fn arm_high_precision_mv(on: bool) {
1588 HIGH_PRECISION_MV.with(|c| c.set(on));
1589}
1590
1591/// What [`arm_high_precision_mv`] last armed on this thread.
1592pub(crate) fn high_precision_mv() -> bool {
1593 HIGH_PRECISION_MV.with(std::cell::Cell::get)
1594}
1595
1596/// lane-hpmv's witness counters: `[0]` counts every `mv_hp`/`mv_class0_hp`
1597/// symbol this process's writers coded (zero without
1598/// `allow_high_precision_mv`, one per non-zero mv component with it), `[1]`
1599/// counts the ones that came out ZERO -- an eighth-pel vector, i.e. one a
1600/// frame without the flag cannot name at all.
1601static HP_SYMBOLS: [std::sync::atomic::AtomicU64; 2] = [
1602 std::sync::atomic::AtomicU64::new(0),
1603 std::sync::atomic::AtomicU64::new(0),
1604];
1605
1606/// Reads and clears [`HP_SYMBOLS`]: `(hp symbols coded, eighth-pel ones)`.
1607#[allow(dead_code)] // read only from the `#[cfg(test)]` witness
1608pub(crate) fn take_hp_symbols() -> (u64, u64) {
1609 let all = HP_SYMBOLS[0].swap(0, std::sync::atomic::Ordering::Relaxed);
1610 (
1611 all,
1612 HP_SYMBOLS[1].swap(0, std::sync::atomic::Ordering::Relaxed),
1613 )
1614}
1615
1616/// [`take_hp_symbols`] without clearing -- what the NEWMV census prints.
1617pub(crate) fn hp_symbols() -> (u64, u64) {
1618 use std::sync::atomic::Ordering::Relaxed;
1619 (HP_SYMBOLS[0].load(Relaxed), HP_SYMBOLS[1].load(Relaxed))
1620}
1621
1622/// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec
1623/// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref`
1624/// trees), symbol for symbol at the same contexts -- which are, as that
1625/// function's own doc records, `single_ref_p1_ctx`..`single_ref_p6_ctx`/
1626/// `uni_comp_ref_p1_ctx` under libaom's compound names.
1627///
1628/// # Errors
1629/// A pair this writer never forms (its `ref0` is not `LAST_FRAME`).
1630fn write_compound_ref_frames(
1631 enc: &mut SymbolEncoder,
1632 cdfs: &mut Cdfs,
1633 above: Option<crate::mvstack::NeighbourRef>,
1634 left: Option<crate::mvstack::NeighbourRef>,
1635 above_ref: i8,
1636 left_ref: i8,
1637 (ref0, ref1): (i8, i8),
1638) -> Result<()> {
1639 use crate::mvstack::{
1640 comp_reference_type_ctx, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
1641 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
1642 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
1643 LAST_FRAME,
1644 };
1645 let a = (above_ref > 0).then_some(above_ref);
1646 let l = (left_ref > 0).then_some(left_ref);
1647 let a1 = above.and_then(|n| n.ref1);
1648 let l1 = left.and_then(|n| n.ref1);
1649 let unidir = is_uni_comp_ref(ref0, ref1);
1650 enc.symbol(
1651 usize::from(!unidir),
1652 &mut cdfs.comp_ref_type[comp_reference_type_ctx(above, left)],
1653 );
1654 if unidir {
1655 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
1656 enc.symbol(
1657 usize::from(both_backward),
1658 &mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0],
1659 );
1660 if both_backward {
1661 return Ok(());
1662 }
1663 if ref0 != LAST_FRAME {
1664 return Err(Error::unsupported(
1665 "AV1 tile",
1666 "a unidirectional compound pair this writer does not form",
1667 ));
1668 }
1669 let past_last2 = ref1 != LAST2_FRAME;
1670 enc.symbol(
1671 usize::from(past_last2),
1672 &mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
1673 );
1674 if past_last2 {
1675 enc.symbol(
1676 usize::from(ref1 == GOLDEN_FRAME),
1677 &mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
1678 );
1679 }
1680 return Ok(());
1681 }
1682 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
1683 enc.symbol(
1684 usize::from(far),
1685 &mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0],
1686 );
1687 if far {
1688 enc.symbol(
1689 usize::from(ref0 == GOLDEN_FRAME),
1690 &mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
1691 );
1692 } else {
1693 enc.symbol(
1694 usize::from(ref0 == LAST2_FRAME),
1695 &mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1],
1696 );
1697 }
1698 let is_altref = ref1 == ALTREF_FRAME;
1699 enc.symbol(
1700 usize::from(is_altref),
1701 &mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0],
1702 );
1703 if !is_altref {
1704 enc.symbol(
1705 usize::from(ref1 == ALTREF2_FRAME),
1706 &mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1],
1707 );
1708 }
1709 Ok(())
1710}
1711
1712/// Per-mode and per-pair fire counts of [`write_compound_block`], for the
1713/// gate's own census (gate-blind-to-feature): modes indexed by the spec's
1714/// `INTER_COMPOUND_MODES`, pairs by `ref1` (`LAST`..`ALTREF`).
1715static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1716 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1717static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =
1718 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1719
1720/// Takes and clears the compound mode histogram.
1721#[cfg(test)]
1722pub(crate) fn take_compound_mode_hits() -> [usize; 8] {
1723 std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1724}
1725
1726/// Takes and clears the compound pair histogram, indexed by the SECOND
1727/// reference (`LAST` = 0 .. `ALTREF` = 6).
1728#[cfg(test)]
1729pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
1730 std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1731}
1732
1733/// Per-SIZE fire counts of [`write_compound_block`], indexed by
1734/// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
1735/// 32x32-only tool, so the share by size is what says whether the leaf
1736/// candidates fire at all (gate-blind-to-feature).
1737static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
1738 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
1739
1740/// Takes and clears the compound size histogram.
1741#[cfg(test)]
1742pub(crate) fn take_compound_size_hits() -> [usize; 4] {
1743 std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1744}
1745
1746/// The compound mode histogram of the LEAVES alone (`bw4 <= 4`, so 16x16 and
1747/// below). The frame-wide histogram above cannot say whether a mode reaches
1748/// the leaves at all, which is exactly the question every leaf compound step
1749/// asks (gate-blind-to-feature): before lane-av1comp4 gave a leaf its second
1750/// reference search, the two half-new modes were structurally impossible
1751/// there and screen capture's leaf compound was 100% `NEAREST_NEARESTMV`.
1752static COMPOUND_LEAF_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1753 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1754
1755/// Takes and clears the leaf-only compound mode histogram.
1756#[cfg(test)]
1757pub(crate) fn take_compound_leaf_mode_hits() -> [usize; 8] {
1758 std::array::from_fn(|i| {
1759 COMPOUND_LEAF_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)
1760 })
1761}
1762
1763/// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
1764/// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
1765/// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
1766/// order. Returns the two motion vectors the decoder derives (what the MI
1767/// grid must record) and whether the mode was a `NEW*` one.
1768///
1769/// Only the modes [`InterMode::compound_index`] names are written, and
1770/// only the `comp_group_idx == 0`, `compound_idx == 1` blend (spec
1771/// `COMPOUND_AVERAGE`) -- masked compound and the distance-weighted blend are
1772/// not searched.
1773///
1774/// # Errors
1775/// As [`write_mv`], or a pair/mode this writer does not form.
1776#[allow(clippy::too_many_arguments)]
1777fn write_compound_block(
1778 enc: &mut SymbolEncoder,
1779 cdfs: &mut Cdfs,
1780 neighbours: &Neighbours,
1781 grid: &crate::mvstack::MiGrid,
1782 (mi_row, mi_col): (usize, usize),
1783 (bw4, bh4): (usize, usize),
1784 (has_above, has_left): (bool, bool),
1785 info: InterInfo,
1786 (mi_cols, mi_rows): (usize, usize),
1787) -> Result<((i32, i32), (i32, i32), bool)> {
1788 let (Some(ref1), Some(mode)) = (info.ref1, info.mode.compound_index()) else {
1789 return Err(Error::unsupported(
1790 "AV1 tile",
1791 "a compound block needs a second reference and a compound mode",
1792 ));
1793 };
1794 let above = has_above.then(|| neighbours.above_nbr(mi_col));
1795 let left = has_left.then(|| neighbours.left_nbr(mi_row));
1796 write_compound_ref_frames(
1797 enc,
1798 cdfs,
1799 above,
1800 left,
1801 neighbours.above_ref[mi_col],
1802 neighbours.left_ref[mi_row],
1803 (info.ref_frame, ref1),
1804 )?;
1805 let stack = crate::mvstack::find_mv_stack_compound(
1806 grid,
1807 mi_row,
1808 mi_col,
1809 bw4,
1810 bh4,
1811 (info.ref_frame, ref1),
1812 mi_cols,
1813 mi_rows,
1814 grid.sign_bias_table(),
1815 &[(0, 0); 7],
1816 None,
1817 );
1818 let ctx = crate::cdf::COMPOUND_MODE_CTX_MAP[stack.ref_mv_ctx >> 1][stack.new_mv_ctx.min(4)];
1819 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1820 eprintln!(
1821 "EC_WCOMP mi_row={mi_row} mi_col={mi_col} mode={mode} ref0={} ref1={ref1} ctx={ctx} new_mv_ctx={} ref_mv_ctx={} stack={}",
1822 info.ref_frame, stack.new_mv_ctx, stack.ref_mv_ctx, stack.entries.len()
1823 );
1824 }
1825 enc.symbol(mode, &mut cdfs.inter_compound_mode[ctx]);
1826 // `assign_compound_mv`'s own DRL half: `NEW_NEWMV` walks from index 0,
1827 // the two derived modes code no index at all.
1828 let mvs = match info.mode {
1829 InterMode::NearestNearestMv => stack.nearest_mv,
1830 InterMode::GlobalGlobalMv => ((0, 0), (0, 0)),
1831 InterMode::NearNearMv => {
1832 // decode.rs `assign_compound_mv`'s second DRL loop: the index
1833 // starts at 1 and the mode's own `ref_mv_idx` is `idx - 1`, so
1834 // this walk starts at 1 too and reads entry `ref_mv_idx + 1`.
1835 let idx = usize::from(info.ref_mv_idx) + 1;
1836 let mut walk = 1usize;
1837 while walk < 3 && stack.entries.len() > walk + 1 {
1838 let advance = walk < idx;
1839 enc.symbol(
1840 usize::from(advance),
1841 &mut cdfs.drl_mode[stack.drl_ctx[walk]],
1842 );
1843 if !advance {
1844 break;
1845 }
1846 walk += 1;
1847 }
1848 let near = |i: usize| {
1849 stack
1850 .entries
1851 .get(i)
1852 .map_or(stack.near_mv, |e| (e.mv0, e.mv1))
1853 };
1854 if walk != idx && near(walk) != near(idx) {
1855 note_drl_clamp(idx, walk, stack.entries.len());
1856 }
1857 near(walk)
1858 }
1859 InterMode::NearestNewMv | InterMode::NewNearestMv => {
1860 // Neither mode codes a DRL index (the decoder leaves `ref_mv_idx`
1861 // at 0): the NEAREST half is derived, the NEW half codes a
1862 // residual against stack entry 0.
1863 let base = stack
1864 .entries
1865 .first()
1866 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
1867 if matches!(info.mode, InterMode::NearestNewMv) {
1868 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
1869 (stack.nearest_mv.0, info.mv1)
1870 } else {
1871 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
1872 (info.mv, stack.nearest_mv.1)
1873 }
1874 }
1875 _ => {
1876 let idx = usize::from(info.ref_mv_idx);
1877 let mut walk = 0usize;
1878 while walk < 2 && stack.entries.len() > walk + 1 {
1879 let advance = walk < idx;
1880 enc.symbol(
1881 usize::from(advance),
1882 &mut cdfs.drl_mode[stack.drl_ctx[walk]],
1883 );
1884 if !advance {
1885 break;
1886 }
1887 walk += 1;
1888 }
1889 let nearest = |i: usize| {
1890 stack
1891 .entries
1892 .get(i)
1893 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1))
1894 };
1895 if walk != idx && nearest(walk) != nearest(idx) {
1896 note_drl_clamp(idx, walk, stack.entries.len());
1897 }
1898 let base = nearest(walk);
1899 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
1900 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
1901 (info.mv, info.mv1)
1902 }
1903 };
1904 // spec 5.11.25's `comp_group_idx`/`compound_idx` are NOT coded: this
1905 // crate's sequence header carries `enable_masked_compound = false` and
1906 // `enable_jnt_comp = false` (encode.rs), and decode.rs reads neither
1907 // symbol under those bits -- it infers `comp_group_idx = 0`,
1908 // `compound_idx = 1` (the simple average), which is the only blend this
1909 // writer forms anyway. A lane that turns either sequence bit on has to
1910 // write the matching symbol here, at
1911 // `get_comp_group_idx_context`/`get_comp_index_context`'s contexts (which
1912 // is what `Neighbours::above_comp_group_idx`/`above_compound_idx` and the
1913 // armed order hints below are already kept for).
1914 let _ = ORDER_HINTS.with(std::cell::Cell::get);
1915 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1916 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
1917 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1918 COMPOUND_SIZE_HITS[(bw4.max(1).trailing_zeros() as usize).min(3)]
1919 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1920 if bw4 <= 4 {
1921 COMPOUND_LEAF_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1922 }
1923 if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {
1924 eprintln!(
1925 "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",
1926 info.mv, info.mv1, mvs.0, mvs.1
1927 );
1928 }
1929 // decode.rs' own `is_new_mv` for a compound block: modes 2, 3, 4, 5, 7.
1930 Ok((
1931 mvs.0,
1932 mvs.1,
1933 matches!(
1934 info.mode,
1935 InterMode::NewNewMv | InterMode::NearestNewMv | InterMode::NewNearestMv
1936 ),
1937 ))
1938}
1939
1940/// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's
1941/// `comp_mode`): on a `reference_select` frame every inter block whose size
1942/// allows compound (`is_comp_ref_allowed`, always true here -- this writer's
1943/// smallest leaf is 8x8) names SINGLE or COMPOUND, at
1944/// `mvstack::reference_mode_ctx`'s own context off the same two neighbour
1945/// bands decode.rs builds its `NeighbourRef` pair from.
1946fn write_comp_mode(
1947 enc: &mut SymbolEncoder,
1948 cdfs: &mut Cdfs,
1949 neighbours: &Neighbours,
1950 (mi_r, mi_c): (usize, usize),
1951 (has_above, has_left): (bool, bool),
1952 compound: bool,
1953) {
1954 if !REFERENCE_SELECT.with(std::cell::Cell::get) {
1955 return;
1956 }
1957 let above = has_above.then(|| neighbours.above_nbr(mi_c));
1958 let left = has_left.then(|| neighbours.left_nbr(mi_r));
1959 let ctx = crate::mvstack::reference_mode_ctx(above, left);
1960 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1961 eprintln!(
1962 "EC_WCM mi=({mi_r},{mi_c}) ctx={ctx} val={} a={:?} l={:?}",
1963 usize::from(compound),
1964 above.map(|n| (n.is_inter, n.ref0, n.ref1)),
1965 left.map(|n| (n.is_inter, n.ref0, n.ref1))
1966 );
1967 }
1968 enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]);
1969}
1970
1971/// Clears the armed plan when the tile writer that consumed it returns.
1972struct CdefIdxGuard;
1973
1974impl Drop for CdefIdxGuard {
1975 fn drop(&mut self) {
1976 CDEF_IDX.with(|c| *c.borrow_mut() = None);
1977 DELTA_Q.with(|c| *c.borrow_mut() = None);
1978 LR_PLAN.with(|c| *c.borrow_mut() = None);
1979 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
1980 SCREEN.with(|c| c.set(false));
1981 REFERENCE_SELECT.with(|c| c.set(false));
1982 MOTION_MODE.with(|c| c.set(false));
1983 INTRABC.with(|c| c.set(false));
1984 FILTER_INTRA.with(|c| c.set(false));
1985 INTRABC_GRID.with(|c| *c.borrow_mut() = None);
1986 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
1987 }
1988}
1989
1990/// `read_cdef`'s write side, called right after every block's `skip` symbol:
1991/// writes this superblock's `cdef_idx` literal the first time a non-skip
1992/// block of it is coded. `mi` is the block's own position in 4x4 mode-info
1993/// units.
1994fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) {
1995 if skip {
1996 return;
1997 }
1998 CDEF_IDX.with(|c| {
1999 let mut plan = c.borrow_mut();
2000 let Some(plan) = plan.as_mut() else { return };
2001 let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16);
2002 if plan.last == Some(sb) {
2003 return;
2004 }
2005 plan.last = Some(sb);
2006 enc.literal(
2007 u32::from(plan.grid.get(sb).copied().unwrap_or(0)),
2008 u32::from(plan.bits),
2009 );
2010 });
2011}
2012
2013/// `read_delta_qindex`'s write side (spec 5.11.10), called right after every
2014/// block's [`write_cdef_idx`] -- the spec's own `skip -> cdef -> delta_q`
2015/// order, and decode.rs `maybe_read_delta_q` is the reader this mirrors
2016/// symbol for symbol. A no-op unless this block sits at its superblock's own
2017/// top-left mode-info position, and (the one case the reader skips too) when
2018/// that block IS the whole superblock and is skipped, in which case
2019/// `CurrentQIndex` carries over unchanged on both sides.
2020fn write_delta_q(
2021 enc: &mut SymbolEncoder,
2022 cdfs: &mut Cdfs,
2023 mi: (usize, usize),
2024 is_whole_sb: bool,
2025 skip: bool,
2026) {
2027 DELTA_Q.with(|c| {
2028 let mut plan = c.borrow_mut();
2029 let Some(plan) = plan.as_mut() else { return };
2030 // lane-b128m: the delta_q unit is the SUPERBLOCK, so it is 128 wide
2031 // under `EC_AV1_SB128` -- decode.rs `maybe_read_delta_q` gates on
2032 // `sb_mi_cur`, and a writer gating on a hardcoded 64 codes three
2033 // symbol groups per 128 root the reader never reads.
2034 let sb_mi = if sb128_armed() {
2035 SB_MI as usize * 2
2036 } else {
2037 SB_MI as usize
2038 };
2039 if mi.0 % sb_mi != 0 || mi.1 % sb_mi != 0 {
2040 return;
2041 }
2042 if is_whole_sb && skip {
2043 return;
2044 }
2045 let sb = (mi.0 / SB_MI as usize) * plan.sb_cols + (mi.1 / SB_MI as usize);
2046 let target = i32::from(plan.grid.get(sb).copied().unwrap_or(0));
2047 // `reduced` is the spec's `delta_q_abs`/`delta_q_sign_bit` pair: the
2048 // step count, not the qindex difference.
2049 let reduced = (target - plan.cur) / plan.res;
2050 let abs = reduced.unsigned_abs() as usize;
2051 /// spec `DELTA_Q_SMALL`: the largest `delta_q_abs` symbol that is not
2052 /// an escape into the literal pair below.
2053 const DELTA_Q_SMALL: usize = 3;
2054 enc.symbol(abs.min(DELTA_Q_SMALL), &mut cdfs.delta_q);
2055 if abs >= DELTA_Q_SMALL {
2056 // libaom `write_delta_qindex`: `rem_bits = get_msb(abs - 1)`,
2057 // written one less in three bits, and the value offset by the
2058 // threshold `(1 << rem_bits) + 1` the reader adds back.
2059 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
2060 let thr = (1u32 << rem_bits) + 1;
2061 enc.literal(rem_bits - 1, 3);
2062 enc.literal(abs as u32 - thr, rem_bits);
2063 }
2064 if abs != 0 {
2065 enc.literal(u32::from(reduced < 0), 1);
2066 }
2067 plan.cur = (plan.cur + reduced * plan.res).clamp(1, 255);
2068 });
2069}
2070
2071/// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
2072/// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
2073/// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
2074/// same variable, so the two traces line up symbol for symbol. Checked once
2075/// per process, so unset (the default) costs one atomic load per call and no
2076/// allocation. Only the real tile writer below calls this -- the mode/rate
2077/// search's own trial encoders never do -- so the trace does not need the
2078/// throwaway-encoder gating a whole-encoder trace would.
2079fn ec_rng_trace(msg: impl FnOnce() -> String) {
2080 use std::sync::atomic::{AtomicU8, Ordering};
2081 static ON: AtomicU8 = AtomicU8::new(2); // 2 = unknown, 1 = on, 0 = off
2082 let on = match ON.load(Ordering::Relaxed) {
2083 2 => {
2084 let on = u8::from(std::env::var_os("EC_RNG").is_some());
2085 ON.store(on, Ordering::Relaxed);
2086 on
2087 }
2088 v => v,
2089 };
2090 if on == 1 {
2091 eprintln!("{}", msg());
2092 }
2093}
2094
2095/// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
2096const PARTITION_NONE: usize = 0;
2097/// `PARTITION_HORZ` (spec 6.10.4): the block cut into a top and a bottom half.
2098const PARTITION_HORZ: usize = 1;
2099/// `PARTITION_VERT` (spec 6.10.4): the block cut into a left and a right half.
2100const PARTITION_VERT: usize = 2;
2101/// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants.
2102const PARTITION_SPLIT: usize = 3;
2103
2104/// The partition types whose probability mass the split-or-horizontal flag of
2105/// a superblock hanging off the bottom of the frame gathers (spec 9.3,
2106/// `partition_gather_vert_alike`): the flag says split, so everything vertical
2107/// or split lands on it.
2108const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2109
2110/// The same for a superblock hanging off the right-hand edge
2111/// (`partition_gather_horz_alike`).
2112const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2113
2114/// Mode-info units across a 32x32 block.
2115pub(crate) const BLOCK_MI: u32 = SB_MI / 2;
2116
2117/// Mode-info units across a 16x16 block, the smallest this crate's key-frame
2118/// writer codes.
2119pub(crate) const SUB_MI: u32 = BLOCK_MI / 2;
2120
2121/// spec `decode_partition`'s `hasRows`/`hasCols` (5.11.4), recomputed at
2122/// whichever block size is asking: a block of `side_mi` mode-info units at mi
2123/// position `pos` may be coded unsplit (its own `PARTITION_NONE`) only when
2124/// this is true in both directions -- the frame's *true* size can put the
2125/// boundary inside a superblock, a 32x32 quadrant or (since this writer's
2126/// smallest block is 16x16) even a leaf, and each level must ask again with
2127/// its own half, not just once at the superblock.
2128pub(crate) fn has_half(pos: u32, side_mi: u32, bound: u32) -> bool {
2129 pos + side_mi / 2 < bound
2130}
2131
2132/// The number of 32x32 block columns/rows a frame whose *true* (unpadded)
2133/// size gives `mi_cols`/`mi_rows` is coded over: every block whose mi origin
2134/// (`col * BLOCK_MI`) is inside the true bound is coded, so this is a
2135/// ceiling, not the exact division a block-aligned frame would give. Shared
2136/// by the tile writer's own iteration and by [`crate::encode`]'s block/
2137/// superblock generation, which must agree with it exactly.
2138pub(crate) fn block_grid(mi_cols: u32, mi_rows: u32) -> (u32, u32) {
2139 (mi_cols.div_ceil(BLOCK_MI), mi_rows.div_ceil(BLOCK_MI))
2140}
2141/// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode.
2142const DC_PRED: usize = 0;
2143
2144/// `V_PRED` (spec 6.10.2), the first of the eight directional intra modes and
2145/// so the first mode that carries an angle delta.
2146const V_PRED: usize = 1;
2147
2148/// `H_PRED`, which predicts every row from the column to the block's left.
2149#[cfg(test)]
2150const H_PRED: usize = 2;
2151
2152/// The last directional mode, `D67_PRED`.
2153const D67_PRED: usize = 8;
2154
2155/// The number of intra modes a key frame's luma block chooses from,
2156/// `INTRA_MODES` (spec 3).
2157const INTRA_MODES: usize = 13;
2158
2159/// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts
2160/// its neighbours in when they pick the CDF for the next block's mode.
2161pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0];
2162
2163/// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
2164/// +3, so `MAX_ANGLE_DELTA` is the middle of it.
2165pub(crate) const ANGLE_DELTA_ZERO: usize = 3;
2166/// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
2167pub(crate) const SB_MI: u32 = 16;
2168
2169/// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
2170const NUM_BASE_LEVELS: i32 = 2;
2171/// Where DCT_DCT sits in the spec's `Tx_Type_Intra_Inv_Set2`, the set a 16x16
2172/// intra luma transform picks its type from.
2173const TX_TYPE_DCT_DCT_SET2: usize = 1;
2174/// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
2175/// Golomb tail takes over.
2176const COEFF_BASE_RANGE: i32 = 12;
2177/// `BR_CDF_SIZE - 1` (spec 3): the largest increment one base-range symbol
2178/// carries.
2179const BR_STEP: i32 = 3;
2180/// The largest level the base and base-range syntax carry between them.
2181/// Anything above it is written as a Golomb tail on top of this.
2182const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2183/// The largest level this writer codes. The Golomb tail is a length in unary
2184/// followed by that many bits, and the spec's decoder reads at most twenty of
2185/// each, so a level a decoder cannot read back is refused rather than written.
2186const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
2187
2188/// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s
2189/// leading index) a frame's `base_q_idx` picks its default CDFs from.
2190/// [`crate::cdf`] carries all four, one constant set per context.
2191pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
2192 match base_q_idx {
2193 0..=20 => 0,
2194 21..=60 => 1,
2195 61..=120 => 2,
2196 _ => 3,
2197 }
2198}
2199
2200/// Both writers here code whole superblocks only: a partial one forces the
2201/// partition syntax down the block tree, which they do not code yet.
2202/// The probability the CDF gives one symbol on its own.
2203fn element_prob(cdf: &[u16], element: usize) -> u16 {
2204 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2205}
2206
2207/// The two-symbol CDF a partial superblock's partition flag is coded with: the
2208/// mass of the listed partition types becomes the probability of a split, and
2209/// the rest is the one partition the frame edge still allows.
2210fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
2211 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
2212 [32768 - split, 32768, 0]
2213}
2214
2215fn check_superblocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
2216 if mi_cols == 0
2217 || mi_rows == 0
2218 || !mi_cols.is_multiple_of(SB_MI)
2219 || !mi_rows.is_multiple_of(SB_MI)
2220 {
2221 return Err(Error::unsupported(
2222 "AV1 tile",
2223 "a key frame is written only for frames that are a whole number \
2224 of 64x64 superblocks",
2225 ));
2226 }
2227 Ok(())
2228}
2229
2230/// Writes the payload of a one-tile key frame in which every superblock is a
2231/// skipped 64x64 DC-predicted block.
2232///
2233/// `mi_cols` and `mi_rows` are the frame's dimensions in 4x4 mode-info units,
2234/// as the frame header carries them.
2235///
2236/// # Errors
2237/// Returns an error when the frame is not a whole number of 64x64 superblocks:
2238/// a partial superblock forces the partition syntax down the block tree, which
2239/// this writer does not code yet.
2240pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {
2241 check_superblocks(mi_cols, mi_rows)?;
2242 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2243
2244 let mut enc = SymbolEncoder::new();
2245 for r in 0..sb_rows {
2246 for c in 0..sb_cols {
2247 // decode_partition (spec 5.11.4). Every neighbour is a 64x64 block,
2248 // whose stored partition context has a zero bit at this block
2249 // size, so the context is 0 wherever the block sits.
2250 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
2251
2252 // intra_frame_mode_info (spec 5.11.16). Segmentation, delta q,
2253 // delta lf, palette, filter intra and intrabc are all off in the
2254 // frame header, and a skipped block codes no CDEF index, so the
2255 // block is three symbols: the skip flag and the two modes.
2256 let skip_ctx = usize::from(r > 0) + usize::from(c > 0);
2257 enc.symbol_fixed(1, &cdf::SKIP[skip_ctx]);
2258 // Both neighbours are DC-predicted, and an unavailable neighbour
2259 // counts as DC too, so both mode contexts are 0.
2260 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2261 // Chroma from luma is only offered up to 32x32, so the CFL-free
2262 // table is the one a 64x64 block reads.
2263 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
2264
2265 // read_block_tx_size codes nothing while the frame's tx_mode is
2266 // TX_MODE_LARGEST, and a skipped block has no residual, so the
2267 // block ends here.
2268 }
2269 }
2270 Ok(enc.finish())
2271}
2272
2273/// Writes the payload of a one-tile key frame in which every superblock is a
2274/// 64x64 DC-predicted block carrying one luma DC coefficient of `dc_level` and
2275/// no chroma residual.
2276///
2277/// `dc_level` is a quantised level, not a sample value: the decoder multiplies
2278/// it by the frame's DC quantiser and inverse-transforms it over the whole
2279/// block, so the picture it makes is a flat grey some distance either side of
2280/// the mid-grey a zero level gives. `base_q_idx` is the frame header's, and
2281/// picks the coefficient CDFs.
2282///
2283/// # Errors
2284/// As [`dc_key_frame_tile_levels`], which this is the one-level case of.
2285pub fn dc_key_frame_tile(
2286 mi_cols: u32,
2287 mi_rows: u32,
2288 base_q_idx: u8,
2289 dc_level: i32,
2290) -> Result<Vec<u8>> {
2291 check_superblocks(mi_cols, mi_rows)?;
2292 let blocks = ((mi_cols / SB_MI) * (mi_rows / SB_MI)) as usize;
2293 dc_key_frame_tile_levels(mi_cols, mi_rows, base_q_idx, &vec![dc_level; blocks])
2294}
2295
2296/// Writes the payload of a one-tile key frame carrying one luma DC coefficient
2297/// per superblock, `levels` giving them in the raster order the superblocks are
2298/// coded in.
2299///
2300/// Each superblock decodes to a flat block of its own grey, so a frame written
2301/// here is a grid of greys the caller chooses — which is what makes the sign
2302/// context observable: a block's sign context is read off its coded neighbours,
2303/// and a frame whose levels differ in sign exercises the three-way split that a
2304/// single-sign frame cannot reach.
2305///
2306/// # Errors
2307/// Returns an error when the frame is not a whole number of 64x64 superblocks,
2308/// when `levels` does not carry exactly one level per superblock, when a level
2309/// is outside the range the base and base-range syntax carry (`-14..=14`
2310/// without zero).
2311pub fn dc_key_frame_tile_levels(
2312 mi_cols: u32,
2313 mi_rows: u32,
2314 base_q_idx: u8,
2315 levels: &[i32],
2316) -> Result<Vec<u8>> {
2317 check_superblocks(mi_cols, mi_rows)?;
2318 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2319 check_levels(levels, (sb_cols * sb_rows) as usize)?;
2320 let q_ctx = q_ctx_of(base_q_idx);
2321 let txb_skip_luma_64 = crate::cdf_state::pick(
2322 q_ctx,
2323 cdf::TXB_SKIP_LUMA_64_Q0,
2324 cdf::TXB_SKIP_LUMA_64_Q1,
2325 cdf::TXB_SKIP_LUMA_64,
2326 cdf::TXB_SKIP_LUMA_64_Q3,
2327 );
2328 let base_eob_luma_64_dc = crate::cdf_state::pick(
2329 q_ctx,
2330 cdf::COEFF_BASE_EOB_LUMA_64_Q0[0],
2331 cdf::COEFF_BASE_EOB_LUMA_64_Q1[0],
2332 cdf::COEFF_BASE_EOB_LUMA_64[0],
2333 cdf::COEFF_BASE_EOB_LUMA_64_Q3[0],
2334 );
2335 let txb_skip_chroma_32_none = crate::cdf_state::pick(
2336 q_ctx,
2337 cdf::TXB_SKIP_CHROMA_32_Q0[0],
2338 cdf::TXB_SKIP_CHROMA_32_Q1[0],
2339 cdf::TXB_SKIP_CHROMA_32[0],
2340 cdf::TXB_SKIP_CHROMA_32_Q3[0],
2341 );
2342
2343 // The sign of the DC each coded block left behind, for the two neighbours
2344 // the sign context is read from: one row of them above, and the block to
2345 // the left, which is dropped at the start of every superblock row the way a
2346 // decoder clears its left context there.
2347 let mut above: Vec<Option<bool>> = vec![None; sb_cols as usize];
2348 let mut enc = SymbolEncoder::new();
2349 for r in 0..sb_rows {
2350 let mut left: Option<bool> = None;
2351 for c in 0..sb_cols {
2352 let dc_level = levels[(r * sb_cols + c) as usize];
2353 let negative = dc_level < 0;
2354
2355 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
2356
2357 // Nothing is skipped now, so every neighbour's skip flag is 0 and
2358 // the skip context stays 0 across the frame.
2359 enc.symbol_fixed(0, &cdf::SKIP[0]);
2360 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2361 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
2362
2363 write_dc_coeffs(
2364 &mut enc,
2365 dc_level,
2366 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)),
2367 q_ctx,
2368 &txb_skip_luma_64,
2369 &base_eob_luma_64_dc,
2370 );
2371
2372 // Both chroma transform blocks are all-zero. Their planes carry no
2373 // coded coefficient anywhere in the frame, so the neighbour halves
2374 // of their context stay 0 and only the offset for a transform block
2375 // that covers its whole plane block is left: context 7.
2376 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
2377 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
2378
2379 above[c as usize] = Some(negative);
2380 left = Some(negative);
2381 }
2382 }
2383 Ok(enc.finish())
2384}
2385
2386/// Writes the payload of a one-tile key frame in which every superblock is
2387/// split into four 32x32 DC-predicted blocks, each carrying one luma DC
2388/// coefficient and no chroma residual.
2389///
2390/// `levels` gives one level per 32x32 block in raster order across the frame,
2391/// so the grid is twice as wide and twice as tall as the superblock grid. The
2392/// blocks are coded in the z-order a superblock's split walks, but every
2393/// block's neighbours above and to its left are coded before it either way, so
2394/// the picture reads in raster order.
2395///
2396/// # Errors
2397/// As [`dc_key_frame_tile_levels`], with `levels` sized for the 32x32 grid.
2398pub fn split_dc_key_frame_tile(
2399 mi_cols: u32,
2400 mi_rows: u32,
2401 base_q_idx: u8,
2402 levels: &[i32],
2403) -> Result<Vec<u8>> {
2404 check_superblocks(mi_cols, mi_rows)?;
2405 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2406 let (cols, rows) = (sb_cols * 2, sb_rows * 2);
2407 check_levels(levels, (cols * rows) as usize)?;
2408 let q_ctx = q_ctx_of(base_q_idx);
2409 let txb_skip_luma_32 = crate::cdf_state::pick(
2410 q_ctx,
2411 cdf::TXB_SKIP_LUMA_32_Q0,
2412 cdf::TXB_SKIP_LUMA_32_Q1,
2413 cdf::TXB_SKIP_LUMA_32,
2414 cdf::TXB_SKIP_LUMA_32_Q3,
2415 );
2416 let base_eob_luma_32 = crate::cdf_state::pick(
2417 q_ctx,
2418 cdf::COEFF_BASE_EOB_LUMA_32_Q0[0],
2419 cdf::COEFF_BASE_EOB_LUMA_32_Q1[0],
2420 cdf::COEFF_BASE_EOB_LUMA_32[0],
2421 cdf::COEFF_BASE_EOB_LUMA_32_Q3[0],
2422 );
2423 let txb_skip_chroma_16_0 = crate::cdf_state::pick(
2424 q_ctx,
2425 cdf::TXB_SKIP_CHROMA_16_Q0[0],
2426 cdf::TXB_SKIP_CHROMA_16_Q1[0],
2427 cdf::TXB_SKIP_CHROMA_16[0],
2428 cdf::TXB_SKIP_CHROMA_16_Q3[0],
2429 );
2430
2431 let mut above: Vec<Option<bool>> = vec![None; cols as usize];
2432 let mut left: Vec<Option<bool>> = vec![None; rows as usize];
2433
2434 let mut enc = SymbolEncoder::new();
2435 for sb_r in 0..sb_rows {
2436 // A decoder clears its left context at the start of every superblock
2437 // row, and so does the partition context the 64x64 symbol reads.
2438 left.iter_mut().for_each(|l| *l = None);
2439 for sb_c in 0..sb_cols {
2440 // The partition context of a 64x64 block reads the bit its
2441 // neighbours' block size sets at this depth: a 32x32 neighbour sets
2442 // it, and an uncoded one leaves it clear, so the context is just
2443 // which neighbours exist. The 32x32 blocks below read a bit their
2444 // own size leaves clear, so their context is 0 throughout.
2445 // Every superblock here is split, so an existing neighbour always
2446 // sets that bit.
2447 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
2448 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
2449
2450 for quadrant in 0..4 {
2451 let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
2452 let dc_level = levels[(r * cols + c) as usize];
2453 let negative = dc_level < 0;
2454
2455 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
2456 enc.symbol_fixed(0, &cdf::SKIP[0]);
2457 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2458 // Chroma from luma is offered up to 32x32, so the block reads
2459 // the wider table even though it does not take the mode.
2460 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL[DC_PRED]);
2461
2462 write_dc_coeffs(
2463 &mut enc,
2464 dc_level,
2465 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])),
2466 q_ctx,
2467 &txb_skip_luma_32,
2468 &base_eob_luma_32,
2469 );
2470 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
2471 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
2472
2473 above[c as usize] = Some(negative);
2474 left[r as usize] = Some(negative);
2475 }
2476 }
2477 }
2478 Ok(enc.finish())
2479}
2480
2481/// One quantised coefficient of a transform block.
2482///
2483/// `row` and `col` are its position in the transform it belongs to — 32x32 for
2484/// luma, 16x16 for each chroma plane — not in the picture: a coefficient at
2485/// row 0 varies along the picture's width and one at column 0 along its
2486/// height, and the coefficient at the origin is the DC the block's average
2487/// sample value rides on.
2488#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2489pub struct Coeff {
2490 /// The coefficient's row in the transform.
2491 pub row: u8,
2492 /// The coefficient's column in the transform.
2493 pub col: u8,
2494 /// Its quantised level, which the base and base-range syntax carry for
2495 /// magnitudes up to [`MAX_LEVEL`].
2496 pub level: i32,
2497}
2498
2499/// The coefficients of one coded block: a 32x32 luma transform and, at 4:2:0,
2500/// the 16x16 transform each chroma plane covers the same area with.
2501#[derive(Clone, Debug, Default, PartialEq, Eq)]
2502pub struct BlockCoeffs {
2503 /// The luma transform's coefficients.
2504 pub luma: Vec<Coeff>,
2505 /// One transform type per luma transform unit, raster order (lane-txset).
2506 /// Empty is `DCT_DCT` throughout -- what every block coded before the
2507 /// search offered a type, and what an inter block still carries.
2508 pub luma_tx_types: Vec<TxType>,
2509 /// The U plane's.
2510 pub u: Vec<Coeff>,
2511 /// The V plane's.
2512 pub v: Vec<Coeff>,
2513 /// The luma intra mode the block is predicted with, one of the thirteen
2514 /// modes a key frame codes (`DC_PRED` is zero, which is what
2515 /// [`Default`] and a plain coefficient list give).
2516 pub mode: u8,
2517 /// The chroma intra mode both chroma planes are predicted with (spec
2518 /// `uv_mode`, one symbol for the pair). `DC_PRED` is zero, which is what
2519 /// [`Default`] gives; a non-`DC_PRED` mode also changes the transform
2520 /// type the decoder derives for chroma (`Intra_Mode_To_Tx_Type`, spec
2521 /// 9.3), which is never coded as a symbol.
2522 pub uv_mode: u8,
2523 /// Whether the block carries no residual at all (spec `skip`). An intra
2524 /// block may still be skipped; `false` (the [`Default`]) codes whatever
2525 /// `luma`/`u`/`v` carry.
2526 pub skip: bool,
2527 /// The block's inter mode and motion vector, or `None` for an intra
2528 /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key
2529 /// frame writers never read this field.
2530 pub inter: Option<InterInfo>,
2531 /// This (single-reference inter) block's spec `motion_mode`, written by
2532 /// [`write_motion_mode`]: 0 `SIMPLE_TRANSLATION` (the [`Default`], and
2533 /// the only mode this writer coded before lane-av1obmc), 1 `OBMC_CAUSAL`,
2534 /// 2 `WARPED_CAUSAL` (lane-av1obmc2).
2535 pub motion_mode: u8,
2536 /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect),
2537 /// each with its own 8x8 luma transform and 4x4 chroma transforms, in
2538 /// raster order among the leaves that are inside the true frame. `Some`
2539 /// overrides this `BlockCoeffs`'s own `luma`/`u`/`v`/`mode`, which are left
2540 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
2541 /// per-quadrant fields are unused.
2542 pub eight: Option<Vec<BlockCoeffs>>,
2543 /// The luma palette this block is predicted with (spec 5.11.46
2544 /// `palette_mode_info`), or `None` for an ordinary intra block. Only a
2545 /// `DC_PRED` block on a frame whose header set
2546 /// `allow_screen_content_tools` may carry one, and it forces
2547 /// `tx_depth` to zero (the whole block is one transform over the
2548 /// palette's own prediction).
2549 pub palette: Option<PaletteY>,
2550 /// The chroma palette this block's two chroma planes are predicted with
2551 /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a
2552 /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry
2553 /// one; it is independent of [`Self::palette`] (either, both or neither).
2554 pub palette_uv: Option<PaletteUv>,
2555 /// How many times this block's luma transform is halved under
2556 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
2557 /// block). Read only by the writers a `tx_select` frame calls; a
2558 /// `TxMode::Largest` frame codes no symbol and leaves this at zero.
2559 /// `luma` then carries the whole block's levels in BLOCK coordinates,
2560 /// which the writer slices per transform unit.
2561 pub tx_depth: u8,
2562 /// This block's `UV_CFL_PRED` alphas (`alpha_q3` for U and V, spec
2563 /// 5.11.45's `cfl_alpha_signs`/`cfl_alpha_u`/`cfl_alpha_v`), or `None` for
2564 /// any other chroma mode. `Some` iff [`Self::uv_mode`] is
2565 /// [`UV_CFL_PRED`]; at least one of the pair is nonzero, since the joint
2566 /// sign symbol has no (ZERO, ZERO) value.
2567 pub cfl_alphas: Option<(i32, i32)>,
2568 /// This block's `filter_intra_mode` (spec 5.11.14, 0..=4) when it is
2569 /// coded with recursive filter intra, or `None`. `Some` only on a DC_PRED
2570 /// luma block of at most 32x32 with no luma palette, on a sequence whose
2571 /// header set `enable_filter_intra` ([`arm_filter_intra`]); the block's
2572 /// luma transform types are then coded from
2573 /// `fimode_to_intradir[filter_intra_mode]`'s row ([`tx_row`]) while its
2574 /// neighbour mode stays `DC_PRED`.
2575 pub filter_intra: Option<u8>,
2576 /// This block's `angle_delta_y` (spec `read_intra_angle_info`, -3..=3),
2577 /// zero for every non-directional luma mode -- which is what
2578 /// [`Default`] gives, and what every writer coded before lane-av1cfl.
2579 pub angle_delta_y: i8,
2580 /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
2581 /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
2582 /// an ordinary intra block. Only a key frame whose header set
2583 /// `allow_intrabc` ([`arm_intrabc`]) may carry one; the block is then
2584 /// coded `skip` with no residual, no mode, no palette -- exactly what
2585 /// decode.rs `read_intra_mode` reads back and returns early on.
2586 ///
2587 /// lane-av1ibc corner-cut, ceiling named: a residual-carrying intrabc
2588 /// block needs the INTER coefficient tables plus the var-tx tree
2589 /// decode.rs `decode_block`'s `intrabc_vartx` arm reads; the upgrade path
2590 /// is to route the block through [`write_tx_syntax_inter`] instead of
2591 /// returning early here.
2592 pub dv: Option<(i32, i32)>,
2593}
2594
2595/// A block's luma palette: its base colours (ascending, only the first
2596/// `size` entries are real) and the per-pixel colour-index map, `side*side`
2597/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back
2598/// out of the stream.
2599#[derive(Clone, Debug, Default, PartialEq, Eq)]
2600pub struct PaletteY {
2601 /// How many base colours, 2..=8 (spec `PaletteSizeY`).
2602 pub size: u8,
2603 /// The base colours, ascending.
2604 pub colors: [u16; 8],
2605 /// Which colour each pixel takes, row-major over the block's own side.
2606 pub map: Vec<u8>,
2607}
2608
2609/// As [`PaletteY`], for a block's chroma palette -- one colour-index map
2610/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes
2611/// are co-located after 4:2:0 subsampling) plus each plane's own base
2612/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of
2613/// the stream.
2614#[derive(Clone, Debug, Default, PartialEq, Eq)]
2615pub struct PaletteUv {
2616 /// How many base colours, 2..=8 (spec `PaletteSizeUV`).
2617 pub size: u8,
2618 /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv`
2619 /// merges the cached and transmitted lists as two ascending runs, and its
2620 /// delta form only ever steps upwards.
2621 pub u_colors: [u16; 8],
2622 /// V's base colours, in the same cluster order as [`Self::u_colors`] --
2623 /// the shared map indexes both, and V's own coding needs no ordering.
2624 pub v_colors: [u16; 8],
2625 /// Which colour each chroma pixel takes, row-major over the subsampled
2626 /// block's own `(side / 2).max(4)` side.
2627 pub map: Vec<u8>,
2628}
2629
2630/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
2631/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
2632/// [`write_inter_mode`] with the decoder's own contexts.
2633#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2634pub enum InterMode {
2635 /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
2636 NearestMv,
2637 /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names
2638 /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode).
2639 NearMv,
2640 /// `GLOBALMV`: the identity global model's zero vector, two symbols and
2641 /// no MV at all.
2642 GlobalMv,
2643 /// `NEWMV`: codes `mv` as a residual against the stack entry
2644 /// [`InterInfo::ref_mv_idx`] names.
2645 NewMv,
2646 /// `NEAREST_NEARESTMV`: both sides take the compound stack's own nearest
2647 /// pair, no residual, no DRL.
2648 NearestNearestMv,
2649 /// `NEAR_NEARMV`: both sides take compound stack entry
2650 /// [`InterInfo::ref_mv_idx`]` + 1` (decode.rs `assign_compound_mv`'s own
2651 /// `ref_mv_idx + 1`), reached by a DRL walk that starts at index 1.
2652 NearNearMv,
2653 /// `NEAREST_NEWMV`: the first side takes the stack's nearest vector, the
2654 /// second codes a residual against stack entry 0.
2655 NearestNewMv,
2656 /// `NEW_NEARESTMV`: the first side codes a residual against stack entry 0,
2657 /// the second takes the stack's nearest vector.
2658 NewNearestMv,
2659 /// `GLOBAL_GLOBALMV`: both sides take the identity global model's zero
2660 /// vector.
2661 GlobalGlobalMv,
2662 /// `NEW_NEWMV`: both sides code a residual against the compound stack
2663 /// entry [`InterInfo::ref_mv_idx`] names.
2664 NewNewMv,
2665}
2666
2667impl InterMode {
2668 /// The spec's `INTER_COMPOUND_MODES` index (libaom `enums.h` order,
2669 /// `NEAREST_NEARESTMV = 0`..`NEW_NEWMV = 7`) for a compound mode, `None`
2670 /// for a single-reference one.
2671 fn compound_index(self) -> Option<usize> {
2672 match self {
2673 InterMode::NearestNearestMv => Some(0),
2674 InterMode::NearNearMv => Some(1),
2675 InterMode::NearestNewMv => Some(2),
2676 InterMode::NewNearestMv => Some(3),
2677 InterMode::GlobalGlobalMv => Some(6),
2678 InterMode::NewNewMv => Some(7),
2679 _ => None,
2680 }
2681 }
2682}
2683
2684/// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
2685/// `(row, col)` units. For [`InterMode::NearestMv`] this writer ignores `mv`
2686/// and codes the stack's own candidate instead — the decoder derives it, so
2687/// nothing here can disagree with it.
2688#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2689pub struct InterInfo {
2690 /// The mode this block is coded with.
2691 pub mode: InterMode,
2692 /// The motion vector a [`InterMode::NewMv`] block's residual targets.
2693 pub mv: (i32, i32),
2694 /// The reference this block predicts from (`LAST_FRAME`..=`ALTREF_FRAME`,
2695 /// spec 6.10.24's alphabet), written by [`write_single_ref`].
2696 pub ref_frame: i8,
2697 /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which
2698 /// `MvStack::entries` slot `NEWMV` codes its residual against, or
2699 /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
2700 /// index (`NEARESTMV`, `GLOBALMV`).
2701 pub ref_mv_idx: u8,
2702 /// The block's second reference (spec `RefFrames[1]`), `None` for a
2703 /// single-reference block. `Some` only on a `reference_select` frame, and
2704 /// only beside one of [`InterMode`]'s compound modes.
2705 pub ref1: Option<i8>,
2706 /// The motion vector into `ref1`, for the compound modes that code one
2707 /// (`NEW_NEWMV`); the other two derive both sides.
2708 pub mv1: (i32, i32),
2709}
2710
2711impl From<Vec<Coeff>> for BlockCoeffs {
2712 /// A block that codes luma only.
2713 fn from(luma: Vec<Coeff>) -> Self {
2714 Self {
2715 luma,
2716 ..Self::default()
2717 }
2718 }
2719}
2720
2721/// Side of the luma transform the coefficient writer codes.
2722const TX32: usize = 32;
2723/// Side of the larger of the two blocks a superblock splits into, in samples.
2724const BLOCK: usize = 32;
2725/// Side of the chroma transform beside it at 4:2:0, and of the luma transform
2726/// of a 16x16 block.
2727const TX16: usize = 16;
2728/// Side of the chroma transform of a 16x16 block at 4:2:0, and of the luma
2729/// transform of an 8x8 leaf under a straddling 16x16 (lane-av1-rect).
2730const TX8: usize = 8;
2731/// Side of the chroma transform of an 8x8 leaf at 4:2:0 (lane-av1-rect).
2732const TX4: usize = 4;
2733/// Side of a superblock, in samples, which is the size a block outside the
2734/// tile reads as.
2735const SB: usize = 64;
2736
2737/// The `above_side`/`left_side` value a cell with no coded neighbour holds
2738/// (tile start, superblock-row start) -- the writer's copy of
2739/// `crate::decode::NO_NEIGHBOUR_SIDE`, and 128 for the same reason: at 64 it
2740/// reads identically at every level up to 64x64 but sets the bit at the
2741/// `BLOCK_128X128` root (64 * 2 <= 128), putting that root's partition symbol
2742/// on CDF row 3 where libaom uses row 0.
2743const NO_NEIGHBOUR_SIDE: usize = 128;
2744/// Side of the smallest block the writer codes, in samples, which is the grid
2745/// the neighbour bookkeeping is kept on.
2746const SUB: usize = 16;
2747/// Side of a 4x4 mode-info unit, in samples: the granularity libaom's above
2748/// and left entropy-context arrays are actually kept on (spec
2749/// `get_txb_ctx`/`av1_set_entropy_contexts`), finer than [`SUB`].
2750const MI: usize = 4;
2751
2752/// What one coded block leaves behind for the blocks that read it as a
2753/// neighbour: whether it coded anything at all, and the sign of its DC.
2754#[derive(Clone, Copy, Default)]
2755struct Neighbour {
2756 /// Whether the plane's transform block carried a coefficient.
2757 coded: bool,
2758 /// Its cumulative coefficient level (spec `cul_level`, clamped to 7) --
2759 /// what the *luma* `txb_skip_ctx` of a transform unit smaller than its
2760 /// own block reads (`get_txb_ctx_general`, decode.rs `luma_skip_ctx`),
2761 /// where "coded or not" is not enough.
2762 level: u8,
2763 /// The sign of its DC, absent when the DC itself is zero.
2764 dc: Option<bool>,
2765}
2766
2767/// Rejects a frame with no mode-info grid at all.
2768///
2769/// `mi_cols`/`mi_rows` are the frame's *true* (unpadded) size in 4x4 units
2770/// (spec `compute_image_size`), not necessarily a multiple of the 32x32 block
2771/// grid: a block whose origin sits at or past this bound is not coded (spec's
2772/// `decode_partition` never visits it), and one that straddles the bound is
2773/// coded whole, its samples coming from the padded planes.
2774fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
2775 if mi_cols == 0 || mi_rows == 0 {
2776 return Err(Error::unsupported(
2777 "AV1 tile",
2778 "a coefficient key frame needs a nonzero mode-info grid",
2779 ));
2780 }
2781 Ok(())
2782}
2783
2784/// The coefficients of one superblock: either one 64x64 block covering it, or
2785/// the four 32x32 blocks it is split into.
2786///
2787/// A superblock at the right-hand or bottom edge of the frame may be half
2788/// outside it, and such a superblock cannot be left whole — the spec has no
2789/// partition that keeps a block outside the frame — so it must be
2790/// [`Split`](Superblock::Split), and carries only the quadrants that are
2791/// inside, in raster order among themselves.
2792#[derive(Clone, Debug, PartialEq, Eq)]
2793pub enum Superblock {
2794 /// One 64x64 block, whose luma transform is 64x64 — of which only the
2795 /// top-left 32x32 carries coefficients — and whose chroma transforms are
2796 /// 32x32 each at 4:2:0.
2797 Whole(BlockCoeffs),
2798 /// The 32x32 quadrants the superblock is split into, each either one
2799 /// block or four 16x16 blocks of its own.
2800 Split(Vec<Quadrant>),
2801}
2802
2803/// One 32x32 quadrant of a split superblock.
2804#[derive(Clone, Debug, PartialEq, Eq)]
2805pub enum Quadrant {
2806 /// One 32x32 block, with a 32x32 luma transform and a 16x16 transform per
2807 /// chroma plane.
2808 Whole(BlockCoeffs),
2809 /// The four 16x16 blocks it is split into, in raster order, each with a
2810 /// 16x16 luma transform and an 8x8 transform per chroma plane.
2811 Split(Vec<BlockCoeffs>),
2812 /// lane-b64: not a quadrant at all -- the whole 64x64 superblock this
2813 /// quadrant is the TOP-LEFT of, coded as one block (`PARTITION_NONE` at
2814 /// `BLOCK_64X64`). Only the top-left quadrant of a superblock carries it
2815 /// and the other three carry [`Covered`](Quadrant::Covered), so the
2816 /// per-32x32-entry shape the inter writer takes is unchanged.
2817 ///
2818 /// The block is single-reference; the writer refuses a compound one. It
2819 /// may be skipped or carry a real residual -- one TX_64X64 luma transform
2820 /// whose coded quarter is a 32x32 level grid, and one TX_32X32 per chroma
2821 /// plane (lane-tx64, `crate::encode::b64_residual`).
2822 Whole64(BlockCoeffs),
2823 /// lane-b128: the whole 128x128 SUPERBLOCK ROOT this quadrant is the
2824 /// top-left of, coded as one block (`PARTITION_NONE` at the root's
2825 /// `partition_w128` symbol). Carried by the top-left 32x32 entry of the
2826 /// root's sixteen; the other fifteen carry [`Covered`](Quadrant::Covered).
2827 ///
2828 /// SKIP only: a 128x128 block's residual is four TX_64X64 luma units
2829 /// interleaved with its chroma per 64x64 mu chunk, which this writer has
2830 /// no path for; [`crate::tile::write_inter_block_128`] refuses one.
2831 Whole128(BlockCoeffs),
2832 /// lane-b128hv: the two 128x64 (`true`) or 64x128 (`false`) inter blocks a
2833 /// `PARTITION_HORZ` / `PARTITION_VERT` 128 superblock root carries, in the
2834 /// order the decoder reads them (top then bottom, left then right).
2835 /// Carried by the top-left 32x32 entry of the root's sixteen, exactly as
2836 /// [`Whole128`](Quadrant::Whole128) is.
2837 ///
2838 /// Skip-only by default; a piece carries a real residual under
2839 /// `EC_AV1_RECTRES` (`crate::encode::rectres`), single reference or
2840 /// compound either way.
2841 Rect128(bool, Vec<BlockCoeffs>),
2842 /// lane-ab128: the THREE inter blocks an AB shape at a 128 superblock
2843 /// root carries -- two 64x64 pieces and one 128x64 / 64x128 half -- in
2844 /// the order the decoder reads them
2845 /// ([`crate::encode::ab128_pieces`]). The `u8` is the partition symbol
2846 /// itself (4 `PARTITION_HORZ_A` .. 7 `PARTITION_VERT_B`). Carried by the
2847 /// top-left 32x32 entry of the root's sixteen, exactly as
2848 /// [`Rect128`](Quadrant::Rect128) is.
2849 ///
2850 /// Skip-only by default, same writer; under `EC_AV1_RECTRES` any of the
2851 /// three pieces may carry a real residual.
2852 Ab128(u8, Vec<BlockCoeffs>),
2853 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
2854 /// top-left already coded; it carries no block of its own.
2855 Covered,
2856}
2857
2858impl Quadrant {
2859 /// The blocks it carries, in the order they are coded.
2860 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {
2861 match self {
2862 Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {
2863 std::slice::from_ref(block)
2864 }
2865 Quadrant::Split(blocks) | Quadrant::Rect128(_, blocks) | Quadrant::Ab128(_, blocks) => {
2866 blocks.as_slice()
2867 }
2868 Quadrant::Covered => &[],
2869 }
2870 }
2871}
2872
2873/// What the blocks above and to the left of the one being coded left behind,
2874/// kept on the 16x16 grid the smallest block sits on.
2875struct Neighbours {
2876 /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/
2877 /// `MiColStart`): every "is there a neighbour above/left of me" answer is
2878 /// TILE-relative, not frame-relative -- the decoder's own
2879 /// `Neighbours::start_tile` sets the same pair, and a writer that asked
2880 /// `mi_row > 0` instead coded a tile's own first row against a neighbour
2881 /// the decoder does not have (class: new map ignores tile edge).
2882 tile_row0_mi: usize,
2883 tile_col0_mi: usize,
2884 /// Per plane, whether the neighbour coded anything and the sign of its DC.
2885 above: Vec<[Neighbour; 3]>,
2886 /// The same, down the left edge.
2887 left: Vec<[Neighbour; 3]>,
2888 /// The neighbour's luma intra mode, which picks the CDF the next block's
2889 /// mode is coded with.
2890 above_mode: Vec<usize>,
2891 /// The same, down the left edge.
2892 left_mode: Vec<usize>,
2893 /// The side of the neighbour block, in samples, which is what the
2894 /// partition symbol's context reads.
2895 above_side: Vec<usize>,
2896 /// The same, down the left edge.
2897 left_side: Vec<usize>,
2898 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
2899 /// granularity [`Self::above`]/[`Self::left`] are, rather than [`SUB`]:
2900 /// two 8x8 leaves of one straddling 16x16 block (lane-av1-rect) share a
2901 /// single [`SUB`]-grid cell, so a coarse array cannot tell the second
2902 /// leaf's partition symbol that the first one was coded at 8x8 (finer
2903 /// than the 16x16 it sits in) -- exactly what its `above`/`left` context
2904 /// needs to read (spec 9.3's `AbovePartitionContext`/`LeftPartitionContext`,
2905 /// which libaom keeps per mi unit for this reason).
2906 above_side_mi: Vec<usize>,
2907 /// The same, down the left edge.
2908 left_side_mi: Vec<usize>,
2909 /// Whether the neighbour carried no residual, for [`sb_coeff_inter_frame_tile`]'s
2910 /// skip context. Unused (and left at its default) by the key frame writers.
2911 /// Kept per 4x4 mode-info unit, like [`Self::above_side_mi`] and for the
2912 /// same reason: under a real PARTITION_SPLIT to 8x8 the four leaves of a
2913 /// 16x16 read (and leave) different contexts inside one [`SUB`] slot.
2914 above_skip: Vec<bool>,
2915 /// The same, down the left edge.
2916 left_skip: Vec<bool>,
2917 /// The side, in pixels, of the transform last written in this 4x4
2918 /// mode-info column -- the deblock `tx_grid` a key frame's
2919 /// `get_tx_size_context` reads (decode.rs `tx_size_context_txfm`/`tx_px_at`),
2920 /// which is what picks the CDF row of a `TxMode::Select` block's
2921 /// `tx_depth` symbol.
2922 above_tx: Vec<u8>,
2923 /// The same, down the left edge (the transform's HEIGHT, `tx_h_px_at`;
2924 /// every transform this writer codes is square, so one value serves).
2925 left_tx: Vec<u8>,
2926 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), per
2927 /// 4x4 mode-info unit: what an INTER frame's `txfm_split` and `tx_depth`
2928 /// symbols read their context from (decode.rs `txfm_partition_ctx_rect`/
2929 /// `tx_size_context_txfm_rect`). Initialised to the widest transform, not
2930 /// zero (decode.rs `TXFM_CTX_INIT`).
2931 above_txfm: Vec<u8>,
2932 /// The same, down the left edge (transform HEIGHT).
2933 left_txfm: Vec<u8>,
2934 /// The palette size each 4x4 mode-info column last left behind, and its
2935 /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and
2936 /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's
2937 /// own `above_palette_size`/`above_palette_colors` bands (decode.rs
2938 /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content
2939 /// frame writes them, `0` when it took no palette, so a stale size never
2940 /// survives into the next block's context.
2941 above_palette_size: Vec<u8>,
2942 /// The same, down the left edge.
2943 left_palette_size: Vec<u8>,
2944 /// What the block being written right now will leave in the two palette
2945 /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY
2946 /// block of either frame type passes through, so an inter block (or an
2947 /// intra block that took no palette) clears the bands rather than letting
2948 /// an earlier palette block's size stand (the neighbour-band hazard
2949 /// lane-t900 r23 hit on the decoder side).
2950 pending_palette: Option<(u8, [u16; 8])>,
2951 /// The colours beside [`Self::above_palette_size`].
2952 above_palette_colors: Vec<[u16; 8]>,
2953 /// The chroma (U-channel) halves of the three bands above --
2954 /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the
2955 /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`.
2956 above_palette_uv_size: Vec<u8>,
2957 left_palette_uv_size: Vec<u8>,
2958 above_palette_uv_colors: Vec<[u16; 8]>,
2959 left_palette_uv_colors: Vec<[u16; 8]>,
2960 /// [`Self::pending_palette`] for the chroma palette.
2961 pending_palette_uv: Option<(u8, [u16; 8])>,
2962 /// The same, down the left edge.
2963 left_palette_colors: Vec<[u16; 8]>,
2964 /// Whether the neighbour was coded inter, for the `is_inter` context.
2965 /// Unused by the key frame writers.
2966 above_inter: Vec<bool>,
2967 /// The same, down the left edge.
2968 left_inter: Vec<bool>,
2969 /// The reference each neighbour named, `-1` for an intra or unavailable
2970 /// one -- what the decoder keeps in its own `Neighbours::above_ref`
2971 /// (decode.rs) and feeds `read_single_ref`'s context functions.
2972 above_ref: Vec<i8>,
2973 /// The same, down the left edge.
2974 left_ref: Vec<i8>,
2975 /// Each neighbour's SECOND reference, `None` for a single-reference or
2976 /// intra one -- decode.rs `Neighbours::above_ref1`, read by every compound
2977 /// context function (`reference_mode_ctx`, `comp_reference_type_ctx`, the
2978 /// `comp_ref`/`comp_bwdref` votes).
2979 above_ref1: Vec<Option<i8>>,
2980 /// The same, down the left edge.
2981 left_ref1: Vec<Option<i8>>,
2982 /// What decode.rs `Neighbours::above_comp_group_idx` holds: a compound
2983 /// neighbour's own `comp_group_idx`, or libaom's single-reference special
2984 /// case (`3` for an ALTREF block, `0` otherwise).
2985 above_comp_group_idx: Vec<u8>,
2986 /// The same, down the left edge.
2987 left_comp_group_idx: Vec<u8>,
2988 /// The same for `compound_idx` (`1` for a single-ref ALTREF block).
2989 above_compound_idx: Vec<u8>,
2990 /// The same, down the left edge.
2991 left_compound_idx: Vec<u8>,
2992 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
2993 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
2994 /// `av1_set_entropy_contexts`): a block whose row or column run spills
2995 /// past this bound leaves its trailing 4x4 units at their default,
2996 /// mid-cell if need be.
2997 mi_cols: usize,
2998 mi_rows: usize,
2999}
3000
3001/// What one plane's neighbours leave for a block, gathered across every cell
3002/// the block spans -- which is what the decoder's own derivation reads
3003/// (spec 5.11.39), and what a single cell only stands in for while every block
3004/// is the same size.
3005#[derive(Clone, Copy, Default)]
3006struct Around {
3007 /// Whether any transform block above this one carried a coefficient.
3008 above_coded: bool,
3009 /// The same, to the left.
3010 left_coded: bool,
3011 /// The running vote of the neighbours' DC signs: negative DCs count down,
3012 /// positive ones up, and a neighbour with no DC does not count.
3013 dc_vote: i32,
3014}
3015
3016impl Neighbours {
3017 /// The state a tile starts from: a block outside it reads as `DC_PRED`,
3018 /// as having coded nothing, and as unsplit. `cols`/`rows` are in [`SUB`]
3019 /// units; `mi_cols`/`mi_rows` are the frame's true (unpadded) size in 4x4
3020 /// mode-info units.
3021 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
3022 Self {
3023 tile_row0_mi: 0,
3024 tile_col0_mi: 0,
3025 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
3026 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
3027 above_mode: vec![DC_PRED; cols],
3028 left_mode: vec![DC_PRED; rows],
3029 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
3030 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
3031 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
3032 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
3033 above_skip: vec![false; cols * (SUB / MI)],
3034 left_skip: vec![false; rows * (SUB / MI)],
3035 above_inter: vec![false; cols * (SUB / MI)],
3036 left_inter: vec![false; rows * (SUB / MI)],
3037 above_ref: vec![-1; cols * (SUB / MI)],
3038 left_ref: vec![-1; rows * (SUB / MI)],
3039 above_ref1: vec![None; cols * (SUB / MI)],
3040 left_ref1: vec![None; rows * (SUB / MI)],
3041 above_comp_group_idx: vec![0; cols * (SUB / MI)],
3042 left_comp_group_idx: vec![0; rows * (SUB / MI)],
3043 above_compound_idx: vec![0; cols * (SUB / MI)],
3044 left_compound_idx: vec![0; rows * (SUB / MI)],
3045 above_tx: vec![0; cols * (SUB / MI)],
3046 left_tx: vec![0; rows * (SUB / MI)],
3047 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
3048 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
3049 above_palette_size: vec![0; cols * (SUB / MI)],
3050 left_palette_size: vec![0; rows * (SUB / MI)],
3051 pending_palette: None,
3052 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
3053 above_palette_uv_size: vec![0; cols * (SUB / MI)],
3054 left_palette_uv_size: vec![0; rows * (SUB / MI)],
3055 above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)],
3056 left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)],
3057 pending_palette_uv: None,
3058 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
3059 mi_cols,
3060 mi_rows,
3061 }
3062 }
3063
3064 /// Clears the left edge, which a tile starts every superblock row with.
3065 /// Points this writer's availability answers at one tile
3066 /// ([`Self::tile_row0_mi`]).
3067 fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) {
3068 self.tile_row0_mi = row0_mi;
3069 self.tile_col0_mi = col0_mi;
3070 }
3071
3072 /// Whether the block at mode-info row `mi_r` has a neighbour above it
3073 /// INSIDE its own tile, and the same to the left.
3074 fn has_above(&self, mi_r: usize) -> bool {
3075 mi_r > self.tile_row0_mi
3076 }
3077
3078 fn has_left(&self, mi_c: usize) -> bool {
3079 mi_c > self.tile_col0_mi
3080 }
3081
3082 fn start_row(&mut self) {
3083 self.left.iter_mut().for_each(|l| *l = Default::default());
3084 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3085 self.left_side
3086 .iter_mut()
3087 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3088 self.left_side_mi
3089 .iter_mut()
3090 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3091 self.left_skip.iter_mut().for_each(|s| *s = false);
3092 self.left_inter.iter_mut().for_each(|i| *i = false);
3093 self.left_ref.iter_mut().for_each(|r| *r = -1);
3094 self.left_ref1.iter_mut().for_each(|r| *r = None);
3095 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
3096 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
3097 self.left_tx.iter_mut().for_each(|t| *t = 0);
3098 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
3099 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
3100 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
3101 self.left_palette_uv_colors
3102 .iter_mut()
3103 .for_each(|c| *c = [0u16; 8]);
3104 }
3105
3106 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
3107 /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the
3108 /// `palette_y_mode` context (how many of the two neighbours took a
3109 /// palette) and the ascending, deduplicated colour cache the neighbours
3110 /// offer. `mi` is the block's own position in 4x4 units; this writer
3111 /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0`
3112 /// availability terms read against.
3113 fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) {
3114 // `av1_get_palette_cache` drops the above neighbour on a 64-px
3115 // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does
3116 // not, which is why the two terms below are asked separately.
3117 let above_ok = r % 16 != 0;
3118 let above_is_palette = r > 0 && self.above_palette_size[c] > 0;
3119 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3120 (
3121 usize::from(self.above_palette_size[c]),
3122 self.above_palette_colors[c],
3123 )
3124 } else {
3125 (0, [0u16; 8])
3126 };
3127 let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 {
3128 (
3129 usize::from(self.left_palette_size[r]),
3130 self.left_palette_colors[r],
3131 )
3132 } else {
3133 (0, [0u16; 8])
3134 };
3135 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
3136 let mut cache = Vec::with_capacity(16);
3137 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3138 if cache.last() != Some(&v) {
3139 cache.push(v);
3140 }
3141 };
3142 let (mut ai, mut li) = (0usize, 0usize);
3143 while ai < above_n && li < left_n {
3144 let (va, vl) = (above_colors[ai], left_colors[li]);
3145 if vl < va {
3146 push_dedup(&mut cache, vl);
3147 li += 1;
3148 } else {
3149 push_dedup(&mut cache, va);
3150 ai += 1;
3151 if vl == va {
3152 li += 1;
3153 }
3154 }
3155 }
3156 while ai < above_n {
3157 push_dedup(&mut cache, above_colors[ai]);
3158 ai += 1;
3159 }
3160 while li < left_n {
3161 push_dedup(&mut cache, left_colors[li]);
3162 li += 1;
3163 }
3164 (ctx, cache)
3165 }
3166
3167 /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel
3168 /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's
3169 /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no
3170 /// neighbour lookup at all (it is this block's own just-decided Y palette
3171 /// use), so only the cache is wanted here.
3172 fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> {
3173 let above_ok = r % 16 != 0;
3174 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
3175 (
3176 usize::from(self.above_palette_uv_size[c]),
3177 self.above_palette_uv_colors[c],
3178 )
3179 } else {
3180 (0, [0u16; 8])
3181 };
3182 let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 {
3183 (
3184 usize::from(self.left_palette_uv_size[r]),
3185 self.left_palette_uv_colors[r],
3186 )
3187 } else {
3188 (0, [0u16; 8])
3189 };
3190 let mut cache = Vec::with_capacity(16);
3191 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3192 if cache.last() != Some(&v) {
3193 cache.push(v);
3194 }
3195 };
3196 let (mut ai, mut li) = (0usize, 0usize);
3197 while ai < above_n && li < left_n {
3198 let (va, vl) = (above_colors[ai], left_colors[li]);
3199 if vl < va {
3200 push_dedup(&mut cache, vl);
3201 li += 1;
3202 } else {
3203 push_dedup(&mut cache, va);
3204 ai += 1;
3205 if vl == va {
3206 li += 1;
3207 }
3208 }
3209 }
3210 while ai < above_n {
3211 push_dedup(&mut cache, above_colors[ai]);
3212 ai += 1;
3213 }
3214 while li < left_n {
3215 push_dedup(&mut cache, left_colors[li]);
3216 li += 1;
3217 }
3218 cache
3219 }
3220
3221 /// [`Self::record_palette_y`] for the chroma bands (decode.rs
3222 /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same
3223 /// way, and the span is in LUMA pixels for both planes' bands alike.
3224 fn record_palette_uv(
3225 &mut self,
3226 (r, c): (usize, usize),
3227 (w, h): (usize, usize),
3228 size: u8,
3229 colors: [u16; 8],
3230 ) {
3231 // lane-b128hv: the above band spans the block's WIDTH and the left
3232 // band its HEIGHT; identical to the one loop this replaces at w == h.
3233 for cell in 0..(w / MI).max(1) {
3234 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
3235 *e = size;
3236 if size > 0 {
3237 self.above_palette_uv_colors[c + cell] = colors;
3238 }
3239 }
3240 }
3241 for cell in 0..(h / MI).max(1) {
3242 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
3243 *e = size;
3244 if size > 0 {
3245 self.left_palette_uv_colors[r + cell] = colors;
3246 }
3247 }
3248 }
3249 }
3250
3251 /// What a just-written block leaves in the palette bands (decode.rs
3252 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
3253 /// spans, `0` for a block that took no palette.
3254 fn record_palette_y(
3255 &mut self,
3256 (r, c): (usize, usize),
3257 (w, h): (usize, usize),
3258 size: u8,
3259 colors: [u16; 8],
3260 ) {
3261 // lane-b128hv: the above band spans the block's WIDTH and the left
3262 // band its HEIGHT; identical to the one loop this replaces at w == h.
3263 for cell in 0..(w / MI).max(1) {
3264 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
3265 *e = size;
3266 if size > 0 {
3267 self.above_palette_colors[c + cell] = colors;
3268 }
3269 }
3270 }
3271 for cell in 0..(h / MI).max(1) {
3272 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
3273 *e = size;
3274 if size > 0 {
3275 self.left_palette_colors[r + cell] = colors;
3276 }
3277 }
3278 }
3279 }
3280
3281 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block
3282 /// of an INTER frame leaves in the two `TXFM_CONTEXT` bands -- its
3283 /// resolved transform size over the span `(w_px, h_px)`, which for a
3284 /// SKIPPED inter block is its own block size instead.
3285 fn record_txfm(
3286 &mut self,
3287 (mi_r, mi_c): (usize, usize),
3288 tx_px: usize,
3289 w_px: usize,
3290 h_px: usize,
3291 ) {
3292 for i in 0..h_px / MI {
3293 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
3294 *cell = tx_px as u8;
3295 }
3296 }
3297 for i in 0..w_px / MI {
3298 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
3299 *cell = tx_px as u8;
3300 }
3301 }
3302 }
3303
3304 /// lane-b128hv: decode.rs `txfm_partition_update_rect` -- the two bands
3305 /// take the transform's own HEIGHT (left) and WIDTH (above), over the
3306 /// txb's own rect span. [`Self::record_txfm`] is this at `tx_w == tx_h`.
3307 fn record_txfm_rect(
3308 &mut self,
3309 (mi_r, mi_c): (usize, usize),
3310 (tx_w, tx_h): (usize, usize),
3311 (txb_w, txb_h): (usize, usize),
3312 ) {
3313 for i in 0..txb_h / MI {
3314 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
3315 *cell = tx_h as u8;
3316 }
3317 }
3318 for i in 0..txb_w / MI {
3319 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
3320 *cell = tx_w as u8;
3321 }
3322 }
3323 }
3324
3325 /// `get_tx_size_context` as libaom writes it for a block inside an INTER
3326 /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT`
3327 /// bands, except that an *inter* neighbour contributes its own BLOCK size.
3328 ///
3329 /// lane-av1tx2 r1: a neighbour OUTSIDE the tile contributes nothing at all
3330 /// -- the decoder's `tx_size_context_txfm` drops the whole term when
3331 /// `has_above`/`has_left` is false, where this counted the band's
3332 /// [`TXFM_CTX_INIT`] (64, the widest transform) as a real neighbour. Every
3333 /// intra block on a tile's top row or left column then took its `tx_depth`
3334 /// off a CDF row one higher than the decoder's, which is the first
3335 /// divergence of the inter `TxMode::Select` stream.
3336 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
3337 let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c));
3338 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
3339 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
3340 if has_above && self.above_inter[mi_c] {
3341 above = self.above_side_mi[mi_c] >= own_side;
3342 }
3343 if has_left && self.left_inter[mi_r] {
3344 left = self.left_side_mi[mi_r] >= own_side;
3345 }
3346 usize::from(has_above && above) + usize::from(has_left && left)
3347 }
3348
3349 /// `get_tx_size_context` (decode.rs [`crate::decode::tx_size_context_txfm`]):
3350 /// whether the transform above is at least as wide as this block's own
3351 /// largest transform, plus whether the one to the left is at least as
3352 /// tall. A neighbour outside the tile contributes nothing.
3353 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
3354 usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
3355 + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
3356 }
3357
3358 /// Publishes one block's resolved transform side over every 4x4 unit it
3359 /// covers, the way the decoder's `fill_lf_grid` does at the end of every
3360 /// block.
3361 fn record_tx(&mut self, (mi_r, mi_c): (usize, usize), side: usize, tx_px: usize) {
3362 for cell in 0..side / MI {
3363 if mi_r + cell < self.left_tx.len() {
3364 self.left_tx[mi_r + cell] = tx_px as u8;
3365 }
3366 if mi_c + cell < self.above_tx.len() {
3367 self.above_tx[mi_c + cell] = tx_px as u8;
3368 }
3369 }
3370 }
3371
3372 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
3373 /// (decode.rs `Neighbours::luma_skip_ctx`): the above and left magnitude
3374 /// tiers, each ORed over the unit's own span and clamped to 4.
3375 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
3376 let mut top = 0u8;
3377 let mut left = 0u8;
3378 for cell in 0..side_mi {
3379 top |= self.above[mi_c + cell][0].level;
3380 left |= self.left[mi_r + cell][0].level;
3381 }
3382 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3383 }
3384
3385 /// Publishes ONE luma transform unit's coefficient context, the way the
3386 /// decoder's `record_mi_luma` does between the units of a split block.
3387 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
3388 let state = neighbour_state(grid);
3389 for cell in 0..tx_px / MI {
3390 if mi_r + cell < self.mi_rows {
3391 self.left[mi_r + cell][0] = state;
3392 }
3393 if mi_c + cell < self.mi_cols {
3394 self.above[mi_c + cell][0] = state;
3395 }
3396 }
3397 }
3398
3399 /// lane-b128r: publishes ONE chroma transform unit's coefficient context,
3400 /// the decoder's own `record_mi_chroma` -- a 128x128 block's chroma is one
3401 /// TX_32X32 unit per plane per 64x64 mu chunk, and the next chunk reads
3402 /// the previous one's state (its `txb_skip_ctx` base 1 from the left
3403 /// neighbour). `span_px` is the unit's LUMA span, which is what the
3404 /// luma-mi-indexed bands are addressed in.
3405 fn record_mi_chroma(
3406 &mut self,
3407 (mi_r, mi_c): (usize, usize),
3408 span_px: usize,
3409 plane: usize,
3410 grid: &[i32],
3411 ) {
3412 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3413 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
3414 let state = neighbour_state(grid);
3415 for cell in 0..(span_px / MI).min(bound_h.saturating_sub(mi_r)) {
3416 self.left[mi_r + cell][plane] = state;
3417 }
3418 for cell in 0..(span_px / MI).min(bound_w.saturating_sub(mi_c)) {
3419 self.above[mi_c + cell][plane] = state;
3420 }
3421 }
3422
3423 /// Writes one coded block into every 16x16 column and row it covers, and,
3424 /// on the finer 4x4 grid libaom's entropy context arrays are actually
3425 /// kept on, into every unit up to the true frame edge -- the units past
3426 /// it are left at their default (uncoded), even mid-16x16-cell (spec
3427 /// `av1_set_entropy_contexts`, which clamps to `blocks_wide`/`blocks_high`
3428 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own
3429 /// side).
3430 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
3431 self.record_planes(at, side, mode, grids, true);
3432 }
3433
3434 /// [`Self::record`] with a switch for plane 0: a block whose luma was
3435 /// written as several transform units published each unit's own context
3436 /// as it went ([`Self::record_mi_luma`]), so the whole-block write here
3437 /// would clobber what the next block reads (decode.rs
3438 /// `record_split_luma`).
3439 fn record_planes(
3440 &mut self,
3441 at: (usize, usize),
3442 side: usize,
3443 mode: usize,
3444 grids: &[Vec<i32>; 3],
3445 luma: bool,
3446 ) {
3447 self.record_planes_rect(at, (side, side), mode, grids, luma);
3448 }
3449
3450 /// lane-b128hv: [`Self::record_planes`] with independent above (width) /
3451 /// left (height) extents, decode.rs `record_rect_mi`'s own split -- the
3452 /// 128 root's HORZ/VERT halves are the writer's first rect blocks.
3453 fn record_planes_rect(
3454 &mut self,
3455 at: (usize, usize),
3456 (w, h): (usize, usize),
3457 mode: usize,
3458 grids: &[Vec<i32>; 3],
3459 luma: bool,
3460 ) {
3461 let (r, c) = at;
3462 for cell in 0..w / SUB {
3463 self.above_mode[c + cell] = mode;
3464 self.above_side[c + cell] = w;
3465 }
3466 for cell in 0..h / SUB {
3467 self.left_mode[r + cell] = mode;
3468 self.left_side[r + cell] = h;
3469 }
3470 self.record_mi_planes_rect((r * (SUB / MI), c * (SUB / MI)), (w, h), grids, luma);
3471 }
3472
3473 /// The coefficient-context half of [`Self::record`], taking the block's
3474 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
3475 /// (r, c): an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at a
3476 /// mi offset [`Self::record`]'s SUB-unit `at` cannot name, but the
3477 /// `above`/`left` arrays it writes into are already sized to the full mi
3478 /// grid, so no resizing is needed to write into them at this
3479 /// finer-than-SUB granularity.
3480 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
3481 self.record_mi_planes(at_mi, side, grids, true);
3482 }
3483
3484 /// [`Self::record_mi`] with [`Self::record_planes`]'s plane-0 switch.
3485 fn record_mi_planes(
3486 &mut self,
3487 at_mi: (usize, usize),
3488 side: usize,
3489 grids: &[Vec<i32>; 3],
3490 luma: bool,
3491 ) {
3492 self.record_mi_planes_rect(at_mi, (side, side), grids, luma);
3493 }
3494
3495 /// [`Self::record_mi_planes`] with independent above (width) / left
3496 /// (height) extents (lane-b128hv, decode.rs `record_mi_rect`).
3497 fn record_mi_planes_rect(
3498 &mut self,
3499 at_mi: (usize, usize),
3500 (w, h): (usize, usize),
3501 grids: &[Vec<i32>; 3],
3502 luma: bool,
3503 ) {
3504 let (mi_r, mi_c) = at_mi;
3505 if screen_armed() {
3506 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
3507 self.record_palette_y(at_mi, (w, h), size, colors);
3508 let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8]));
3509 self.record_palette_uv(at_mi, (w, h), uv_size, uv_colors);
3510 }
3511 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
3512 let (w_mi, h_mi) = (w / MI, h / MI);
3513 for cell in 0..h_mi {
3514 self.left_side_mi[mi_r + cell] = h;
3515 }
3516 for cell in 0..w_mi {
3517 self.above_side_mi[mi_c + cell] = w;
3518 }
3519 // libaom rounds the luma edge up to the plane's own 4x4 unit before
3520 // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high,
3521 // subsampling_y)` in av1_write_intra_coeffs_mb, encodetxb.c:456-459):
3522 // a chroma 4x4 unit straddling the true luma edge is still whole in
3523 // chroma's own halved grid, so it stays valid one luma-mi row/col
3524 // past where luma's own edge falls when that edge is odd.
3525 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3526 let bound_h = [
3527 self.mi_rows,
3528 round_up_even(self.mi_rows),
3529 round_up_even(self.mi_rows),
3530 ];
3531 let bound_w = [
3532 self.mi_cols,
3533 round_up_even(self.mi_cols),
3534 round_up_even(self.mi_cols),
3535 ];
3536 for cell in 0..h_mi {
3537 let keep_left = self.left[mi_r + cell][0];
3538 self.left[mi_r + cell] = std::array::from_fn(|plane| {
3539 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
3540 states[plane]
3541 } else {
3542 Default::default()
3543 }
3544 });
3545 if !luma {
3546 self.left[mi_r + cell][0] = keep_left;
3547 }
3548 }
3549 for cell in 0..w_mi {
3550 let keep_above = self.above[mi_c + cell][0];
3551 self.above[mi_c + cell] = std::array::from_fn(|plane| {
3552 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
3553 states[plane]
3554 } else {
3555 Default::default()
3556 }
3557 });
3558 if !luma {
3559 self.above[mi_c + cell][0] = keep_above;
3560 }
3561 }
3562 }
3563
3564 /// Writes one inter-frame block's skip flag and inter/intra state into
3565 /// every 16x16 column and row it covers, the same span [`Self::record`]
3566 /// fills for the coefficient and mode state.
3567 fn record_inter(
3568 &mut self,
3569 at: (usize, usize),
3570 side: usize,
3571 skip: bool,
3572 is_inter: bool,
3573 ref_frame: i8,
3574 ) {
3575 let (r, c) = at;
3576 self.record_inter_mi(
3577 (r * (SUB / MI), c * (SUB / MI)),
3578 side,
3579 skip,
3580 is_inter,
3581 ref_frame,
3582 );
3583 }
3584
3585 /// lane-b128hv: [`Self::record_inter_mi`] with independent above (width)
3586 /// / left (height) spans, decode.rs `record_inter_rect_mi`'s own split.
3587 fn record_inter_rect_mi(
3588 &mut self,
3589 (mi_r, mi_c): (usize, usize),
3590 (w, h): (usize, usize),
3591 skip: bool,
3592 is_inter: bool,
3593 ref_frame: i8,
3594 ) {
3595 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3596 for cell in 0..h / MI {
3597 self.left_skip[mi_r + cell] = skip;
3598 self.left_inter[mi_r + cell] = is_inter;
3599 self.left_ref[mi_r + cell] = ref_frame;
3600 self.left_ref1[mi_r + cell] = None;
3601 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
3602 self.left_compound_idx[mi_r + cell] = u8::from(altref);
3603 }
3604 for cell in 0..w / MI {
3605 self.above_skip[mi_c + cell] = skip;
3606 self.above_inter[mi_c + cell] = is_inter;
3607 self.above_ref[mi_c + cell] = ref_frame;
3608 self.above_ref1[mi_c + cell] = None;
3609 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
3610 self.above_compound_idx[mi_c + cell] = u8::from(altref);
3611 }
3612 }
3613
3614 /// [`Self::record_compound_mi`] over a rect block's own two spans.
3615 fn record_compound_rect_mi(
3616 &mut self,
3617 (mi_r, mi_c): (usize, usize),
3618 (w, h): (usize, usize),
3619 ref1: i8,
3620 comp_group_idx: u8,
3621 compound_idx: u8,
3622 ) {
3623 for cell in 0..h / MI {
3624 self.left_ref1[mi_r + cell] = Some(ref1);
3625 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
3626 self.left_compound_idx[mi_r + cell] = compound_idx;
3627 }
3628 for cell in 0..w / MI {
3629 self.above_ref1[mi_c + cell] = Some(ref1);
3630 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
3631 self.above_compound_idx[mi_c + cell] = compound_idx;
3632 }
3633 }
3634
3635 /// [`Self::record_inter_mi`]'s compound half (decode.rs
3636 /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF
3637 /// single-reference default with a real compound block's own second
3638 /// reference and `comp_group_idx`/`compound_idx` bits, called right after
3639 /// it for every compound-coded block.
3640 fn record_compound_mi(
3641 &mut self,
3642 (mi_r, mi_c): (usize, usize),
3643 side: usize,
3644 ref1: i8,
3645 comp_group_idx: u8,
3646 compound_idx: u8,
3647 ) {
3648 for cell in 0..side / MI {
3649 self.above_ref1[mi_c + cell] = Some(ref1);
3650 self.left_ref1[mi_r + cell] = Some(ref1);
3651 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
3652 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
3653 self.above_compound_idx[mi_c + cell] = compound_idx;
3654 self.left_compound_idx[mi_r + cell] = compound_idx;
3655 }
3656 }
3657
3658 /// [`Self::record_inter`] taking the block's position directly in 4x4
3659 /// mode-info units, for a block finer than one [`SUB`] slot.
3660 fn record_inter_mi(
3661 &mut self,
3662 (mi_r, mi_c): (usize, usize),
3663 side: usize,
3664 skip: bool,
3665 is_inter: bool,
3666 ref_frame: i8,
3667 ) {
3668 for cell in 0..side / MI {
3669 self.above_skip[mi_c + cell] = skip;
3670 self.left_skip[mi_r + cell] = skip;
3671 self.above_inter[mi_c + cell] = is_inter;
3672 self.left_inter[mi_r + cell] = is_inter;
3673 self.above_ref[mi_c + cell] = ref_frame;
3674 self.left_ref[mi_r + cell] = ref_frame;
3675 // decode.rs `record_inter`'s single-reference default: no second
3676 // reference, and libaom's ALTREF special case in the two compound
3677 // context bands. `record_compound_mi` overwrites both for a real
3678 // compound block.
3679 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3680 self.above_ref1[mi_c + cell] = None;
3681 self.left_ref1[mi_r + cell] = None;
3682 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
3683 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
3684 self.above_compound_idx[mi_c + cell] = u8::from(altref);
3685 self.left_compound_idx[mi_r + cell] = u8::from(altref);
3686 }
3687 }
3688
3689 /// The above neighbour as decode.rs' own `NeighbourRef`, for every
3690 /// compound context function (`reference_mode_ctx`,
3691 /// `comp_reference_type_ctx`, the `comp_ref`/`comp_bwdref` votes).
3692 fn above_nbr(&self, mi_c: usize) -> crate::mvstack::NeighbourRef {
3693 let is_inter = self.above_inter[mi_c];
3694 let ref0 = if is_inter { self.above_ref[mi_c] } else { 0 };
3695 let ref1 = self.above_ref1[mi_c];
3696 crate::mvstack::NeighbourRef {
3697 is_inter,
3698 ref0,
3699 ref1,
3700 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
3701 }
3702 }
3703
3704 /// [`Self::above_nbr`], down the left edge.
3705 fn left_nbr(&self, mi_r: usize) -> crate::mvstack::NeighbourRef {
3706 let is_inter = self.left_inter[mi_r];
3707 let ref0 = if is_inter { self.left_ref[mi_r] } else { 0 };
3708 let ref1 = self.left_ref1[mi_r];
3709 crate::mvstack::NeighbourRef {
3710 is_inter,
3711 ref0,
3712 ref1,
3713 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
3714 }
3715 }
3716
3717 /// The context of a block's partition symbol (spec 9.3): whether the
3718 /// blocks above it and to its left were split finer than it is.
3719 /// The gathered state of the blocks above and to the left of one block,
3720 /// per plane.
3721 fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] {
3722 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
3723 }
3724
3725 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
3726 /// units, for the same reason [`Self::record_mi`] does.
3727 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [Around; 3] {
3728 let side_mi = side / MI;
3729 std::array::from_fn(|plane| {
3730 let mut around = Around::default();
3731 for cell in 0..side_mi {
3732 let (above, left) = (
3733 &self.above[mi_c + cell][plane],
3734 &self.left[mi_r + cell][plane],
3735 );
3736 around.above_coded |= above.coded;
3737 around.left_coded |= left.coded;
3738 around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc);
3739 }
3740 around
3741 })
3742 }
3743
3744 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
3745 // Delegates to the mi-precise reader (same pattern as `around` /
3746 // `around_mi`): `above_side`/`left_side` are only ever advanced in
3747 // whole-[`SUB`] steps by [`Self::record`], so a leaf8's `record_mi`
3748 // (lane-av1-rect) -- which only touches the finer mi arrays -- leaves
3749 // them stale for the *next* sibling's own partition symbol, reading a
3750 // 16x16-slot side that already split into 8x8s underneath it.
3751 let (r, c) = at;
3752 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
3753 }
3754
3755 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
3756 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
3757 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
3758 /// than the enclosing 16x16 slot's stale, shared state.
3759 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
3760 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
3761 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
3762 }
3763}
3764
3765/// Writes the payload of a one-tile key frame built from `superblocks`, each
3766/// either one 64x64 block or the 32x32 blocks it splits into.
3767///
3768/// `superblocks` gives one entry per superblock in raster order across the
3769/// frame. Every block is DC-predicted unless its [`BlockCoeffs::mode`] says
3770/// otherwise, and carries the coefficients its lists give; the coefficients
3771/// may sit anywhere in their transform, so a block is a picture rather than a
3772/// flat grey.
3773///
3774/// # Errors
3775/// Returns an error when the frame is not a whole number of 32x32 blocks, when
3776/// `superblocks` does not carry exactly one entry per superblock or an entry
3777/// does not carry one block per quadrant inside the frame, when a superblock
3778/// that is half outside the frame is left whole, when a block names an intra
3779/// mode a key frame does not code, when a coefficient sits outside its
3780/// transform, repeats a position, carries a zero level or one wider than the
3781/// Golomb tail reaches.
3782pub fn sb_coeff_key_frame_tile(
3783 mi_cols: u32,
3784 mi_rows: u32,
3785 base_q_idx: u8,
3786 superblocks: &[Superblock],
3787) -> Result<Vec<u8>> {
3788 sb_coeff_key_frame_tile_tx(mi_cols, mi_rows, base_q_idx, superblocks, false)
3789}
3790
3791/// [`sb_coeff_key_frame_tile`] for a frame header carrying
3792/// `tx_mode == TxMode::Select` (`tx_select`): every block then codes a
3793/// `tx_depth` symbol and, where that depth is nonzero, its luma residual as
3794/// several transform units ([`write_luma_select`]). With `tx_select` false
3795/// this writes exactly the stream it always did.
3796///
3797/// # Errors
3798/// As [`sb_coeff_key_frame_tile`], plus a 64x64 block whose `tx_depth` is
3799/// nonzero (not written yet).
3800pub fn sb_coeff_key_frame_tile_tx(
3801 mi_cols: u32,
3802 mi_rows: u32,
3803 base_q_idx: u8,
3804 superblocks: &[Superblock],
3805 tx_select: bool,
3806) -> Result<Vec<u8>> {
3807 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3808 sb_coeff_key_frame_tile_cdfs(
3809 mi_cols,
3810 mi_rows,
3811 base_q_idx,
3812 superblocks,
3813 tx_select,
3814 &mut cdfs,
3815 TileRect::whole(mi_cols, mi_rows),
3816 )
3817}
3818
3819/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
3820/// caller's own CDF state, which is what a frame whose
3821/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must
3822/// start where this tile ended (spec 7.20, mirrored by
3823/// `crate::stream::stored_cdfs_for`).
3824///
3825/// # Errors
3826/// As [`sb_coeff_key_frame_tile_tx`].
3827pub(crate) fn sb_coeff_key_frame_tile_cdfs(
3828 mi_cols: u32,
3829 mi_rows: u32,
3830 _base_q_idx: u8,
3831 superblocks: &[Superblock],
3832 tx_select: bool,
3833 cdfs: &mut Cdfs,
3834 // This tile's own span (spec 5.11.1): the writer walks only these
3835 // superblocks, and its neighbour bands start blank, so everything
3836 // outside reads as unavailable exactly as the decoder's own per-tile
3837 // reset makes it.
3838 tile: TileRect,
3839) -> Result<Vec<u8>> {
3840 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3841 let _cdef_idx = CdefIdxGuard;
3842 check_blocks(mi_cols, mi_rows)?;
3843 // The DV predictor's own mi grid, per tile exactly as decode.rs builds it
3844 // per frame (`decode_key_frame_tile_lr`'s `intrabc_mi_grid`): a tile that
3845 // allows no intrabc arms none and every `record_intrabc_mi` below is a
3846 // no-op.
3847 if intrabc_armed() {
3848 // No `set_tile_bounds`: decode.rs builds this grid for the WHOLE
3849 // frame with the default (whole-grid) bounds, so the writer must
3850 // too. `encode_key_frame_inner` only allows intrabc on a
3851 // single-tile frame, where the two grids are the same grid.
3852 let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize);
3853 INTRABC_GRID.with(|g| {
3854 *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize));
3855 });
3856 }
3857 let (cols, rows) = block_grid(mi_cols, mi_rows);
3858 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3859 if superblocks.len() != (sb_cols * sb_rows) as usize {
3860 return Err(Error::unsupported(
3861 "AV1 tile",
3862 "a coefficient key frame needs one entry per superblock",
3863 ));
3864 }
3865 let mut coded: Vec<&BlockCoeffs> = Vec::new();
3866 for superblock in superblocks {
3867 match superblock {
3868 Superblock::Whole(block) => coded.push(block),
3869 Superblock::Split(quadrants) => {
3870 for block in quadrants.iter().flat_map(Quadrant::blocks) {
3871 match &block.eight {
3872 Some(leaves) => coded.extend(leaves.iter()),
3873 None => coded.push(block),
3874 }
3875 }
3876 }
3877 }
3878 }
3879 if let Some(bad) = coded
3880 .into_iter()
3881 .find(|b| usize::from(b.mode) >= INTRA_MODES)
3882 {
3883 return Err(Error::unsupported(
3884 "AV1 tile",
3885 format!(
3886 "intra mode {} is not one of the thirteen a key frame codes",
3887 bad.mode
3888 ),
3889 ));
3890 }
3891
3892 let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8];
3893 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
3894 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
3895 let scans = [
3896 default_scan(TX32),
3897 default_scan(TX16),
3898 default_scan(TX8),
3899 default_scan(TX4),
3900 ];
3901 // The blocks above and to the left, on the 16x16 grid. The left edge is
3902 // reset at every superblock row because a tile starts each row with no
3903 // left neighbour.
3904 let mut neighbours = Neighbours::new(
3905 cols as usize * 2,
3906 rows as usize * 2,
3907 mi_cols as usize,
3908 mi_rows as usize,
3909 );
3910 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
3911
3912 // The tile adapts every non-literal CDF it writes, exactly as the decoder
3913 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
3914 // off.
3915 let mut cdfs = cdfs;
3916 let mut enc = SymbolEncoder::new();
3917 let sb128 = sb128_armed();
3918 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
3919 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
3920 // and partition symbol first; at a 64 one this is plain raster and every
3921 // cell is its own superblock, i.e. byte-identical to the loop before.
3922 for (sb_r, sb_c, row_start, sb_start) in sb_write_order(
3923 tile.sb_row0,
3924 tile.sb_row1.min(sb_rows),
3925 tile.sb_col0,
3926 tile.sb_col1.min(sb_cols),
3927 sb128,
3928 ) {
3929 if row_start {
3930 neighbours.start_row();
3931 }
3932 if sb128 && sb_start {
3933 write_sb128_root(
3934 &mut enc,
3935 &mut cdfs,
3936 &neighbours,
3937 sb_r,
3938 sb_c,
3939 mi_cols,
3940 mi_rows,
3941 PARTITION_SPLIT,
3942 );
3943 }
3944 {
3945 if !sb128 {
3946 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W);
3947 }
3948 let at = (sb_r as usize * 4, sb_c as usize * 4);
3949 let ctx = neighbours.partition_ctx(at, SB);
3950 ec_rng_trace(|| {
3951 format!(
3952 "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={}",
3953 at.0 * 4,
3954 at.1 * 4,
3955 ctx,
3956 enc.tell()
3957 )
3958 });
3959 // A superblock whose bottom or right half is outside the frame
3960 // cannot be left unsplit, so the decoder reads a flag instead of
3961 // the partition symbol — and reads nothing at all when both halves
3962 // are outside, where the split is the only partition left.
3963 let (has_cols, has_rows) = (
3964 sb_c * SB_MI + SB_MI / 2 < mi_cols,
3965 sb_r * SB_MI + SB_MI / 2 < mi_rows,
3966 );
3967 // The quadrants of this superblock that are inside the frame, as
3968 // positions in the 32x32 block grid.
3969 let quadrant_positions: Vec<(usize, usize)> = (0..4)
3970 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
3971 .filter(|&(r, c)| r < rows && c < cols)
3972 .map(|(r, c)| (r as usize, c as usize))
3973 .collect();
3974
3975 match &superblocks[(sb_r * sb_cols + sb_c) as usize] {
3976 Superblock::Whole(block) => {
3977 if !has_cols || !has_rows {
3978 return Err(Error::unsupported(
3979 "AV1 tile",
3980 "a superblock that is half outside the frame cannot be left whole",
3981 ));
3982 }
3983 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
3984 let grids = [
3985 level_grid(&block.luma, TX32)?,
3986 level_grid(&block.u, TX32)?,
3987 level_grid(&block.v, TX32)?,
3988 ];
3989 write_block(
3990 &mut enc,
3991 &mut cdfs,
3992 &mut neighbours,
3993 block,
3994 at,
3995 SB,
3996 &whole_planes,
3997 &grids,
3998 [&scans[0], &scans[0], &scans[0]],
3999 // A 64x64 block is too big to be offered chroma from
4000 // luma, so its chroma mode reads the table without it.
4001 false,
4002 tx_select,
4003 &scans,
4004 )?;
4005 ec_rng_trace(|| {
4006 format!(
4007 "EC_TOK mi_row={} mi_col={} tell={}",
4008 at.0 * 4,
4009 at.1 * 4,
4010 enc.tell()
4011 )
4012 });
4013 }
4014 Superblock::Split(quadrants) => {
4015 match (has_cols, has_rows) {
4016 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
4017 // The gathered CDF an edge superblock reads is built
4018 // for the read and thrown away: the decoder never
4019 // stores it back, so nothing adapts here.
4020 (true, false) => {
4021 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
4022 }
4023 (false, true) => {
4024 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
4025 }
4026 (false, false) => {}
4027 }
4028 if quadrants.len() != quadrant_positions.len() {
4029 return Err(Error::unsupported(
4030 "AV1 tile",
4031 "a split superblock needs one block per quadrant inside the frame",
4032 ));
4033 }
4034 for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) {
4035 let at = (r * 2, c * 2);
4036 let ctx = neighbours.partition_ctx(at, BLOCK);
4037 // Recomputed at this 32x32 block's own half (spec
4038 // `decode_partition`, called again at every size, not
4039 // just once for the superblock): the true frame edge
4040 // can fall inside this quadrant even when the
4041 // superblock it sits in was itself whole or safely
4042 // split above.
4043 let (has_cols32, has_rows32) = (
4044 has_half(c as u32 * BLOCK_MI, BLOCK_MI, mi_cols),
4045 has_half(r as u32 * BLOCK_MI, BLOCK_MI, mi_rows),
4046 );
4047 ec_rng_trace(|| {
4048 format!(
4049 "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={}",
4050 at.0 * 4,
4051 at.1 * 4,
4052 ctx,
4053 enc.tell()
4054 )
4055 });
4056 match quadrant {
4057 // A 64x64 root is an INTER-frame partition; a
4058 // key frame codes one as `Superblock::Whole`.
4059 Quadrant::Whole64(_)
4060 | Quadrant::Whole128(_)
4061 | Quadrant::Rect128(..)
4062 | Quadrant::Ab128(..)
4063 | Quadrant::Covered => {
4064 return Err(Error::unsupported(
4065 "AV1 tile",
4066 "a key frame codes a 64x64 block as `Superblock::Whole`",
4067 ));
4068 }
4069 Quadrant::Whole(block) => {
4070 if !has_cols32 || !has_rows32 {
4071 return Err(Error::unsupported(
4072 "AV1 tile",
4073 "a 32x32 block that is half outside the true frame \
4074 cannot be left whole",
4075 ));
4076 }
4077 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]);
4078 let grids = [
4079 level_grid(&block.luma, TX32)?,
4080 level_grid(&block.u, TX16)?,
4081 level_grid(&block.v, TX16)?,
4082 ];
4083 write_block(
4084 &mut enc,
4085 &mut cdfs,
4086 &mut neighbours,
4087 block,
4088 at,
4089 BLOCK,
4090 &split_planes,
4091 &grids,
4092 [&scans[0], &scans[1], &scans[1]],
4093 true,
4094 tx_select,
4095 &scans,
4096 )?;
4097 ec_rng_trace(|| {
4098 format!(
4099 "EC_TOK mi_row={} mi_col={} tell={}",
4100 at.0 * 4,
4101 at.1 * 4,
4102 enc.tell()
4103 )
4104 });
4105 }
4106 Quadrant::Split(blocks) => {
4107 // The 16x16 sub-blocks this quadrant's split
4108 // carries: only those whose own mi origin is
4109 // inside the true frame (spec `decode_partition`'s
4110 // `r >= MiRows || c >= MiCols` early return),
4111 // which need not be all four when the true
4112 // edge falls inside this quadrant.
4113 let sub_positions: Vec<(usize, usize)> = (0..4)
4114 .map(|i| (r * 2 + i / 2, c * 2 + i % 2))
4115 .filter(|&(sr, sc)| {
4116 (sr as u32) * SUB_MI < mi_rows
4117 && (sc as u32) * SUB_MI < mi_cols
4118 })
4119 .collect();
4120 if blocks.len() != sub_positions.len() {
4121 return Err(Error::unsupported(
4122 "AV1 tile",
4123 "a split 32x32 block needs one 16x16 entry per \
4124 sub-block inside the true frame",
4125 ));
4126 }
4127 // Same three-way spec signaling as the
4128 // superblock level above, recomputed at this
4129 // block's own half: a full alphabet symbol
4130 // only when both halves are inside, a single
4131 // gathered bit when just one is, and nothing
4132 // at all (SPLIT is inferred) when neither is.
4133 match (has_cols32, has_rows32) {
4134 (true, true) => {
4135 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]);
4136 }
4137 (true, false) => {
4138 enc.symbol_fixed(
4139 1,
4140 &gather(&cdfs.partition_w32[ctx], VERT_ALIKE),
4141 );
4142 }
4143 (false, true) => {
4144 enc.symbol_fixed(
4145 1,
4146 &gather(&cdfs.partition_w32[ctx], HORZ_ALIKE),
4147 );
4148 }
4149 (false, false) => {}
4150 }
4151 for (block, (sr, sc)) in blocks.iter().zip(sub_positions) {
4152 // A 16x16 leaf's own hasRows/hasCols,
4153 // recomputed at this leaf's own half
4154 // (same three-way signaling as the 32x32
4155 // and 64x64 levels above).
4156 let (has_cols16, has_rows16) = (
4157 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
4158 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
4159 );
4160 let at = (sr, sc);
4161 let ctx = neighbours.partition_ctx(at, SUB);
4162 ec_rng_trace(|| {
4163 format!(
4164 "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={}",
4165 at.0 * 4,
4166 at.1 * 4,
4167 ctx,
4168 enc.tell()
4169 )
4170 });
4171 if has_cols16 && has_rows16 {
4172 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]);
4173 let grids = [
4174 level_grid(&block.luma, TX16)?,
4175 level_grid(&block.u, TX8)?,
4176 level_grid(&block.v, TX8)?,
4177 ];
4178 write_block(
4179 &mut enc,
4180 &mut cdfs,
4181 &mut neighbours,
4182 block,
4183 at,
4184 SUB,
4185 &sub_planes,
4186 &grids,
4187 [&scans[1], &scans[2], &scans[2]],
4188 true,
4189 tx_select,
4190 &scans,
4191 )?;
4192 ec_rng_trace(|| {
4193 format!(
4194 "EC_TOK mi_row={} mi_col={} tell={}",
4195 at.0 * 4,
4196 at.1 * 4,
4197 enc.tell()
4198 )
4199 });
4200 continue;
4201 }
4202 // The true edge falls inside this 16x16
4203 // leaf itself: the block splits into the
4204 // 8x8s that are inside, each its own
4205 // leaf. Same three-way spec signaling as
4206 // every level above -- a single gathered
4207 // bit when one half is outside, and
4208 // nothing at all when BOTH are, where
4209 // `decode_partition` infers the split
4210 // (lane-av1rect: no rectangular
4211 // transform is needed for this, the
4212 // earlier refusal here misread 5.11.4).
4213 match (has_cols16, has_rows16) {
4214 (true, false) => enc.symbol_fixed(
4215 1,
4216 &gather(&cdfs.partition_w16[ctx], VERT_ALIKE),
4217 ),
4218 (false, true) => enc.symbol_fixed(
4219 1,
4220 &gather(&cdfs.partition_w16[ctx], HORZ_ALIKE),
4221 ),
4222 _ => {}
4223 }
4224 let leaves = block.eight.as_ref().ok_or_else(|| {
4225 Error::unsupported(
4226 "AV1 tile",
4227 "a 16x16 block the true frame edge cuts through \
4228 needs its `eight` leaves populated",
4229 )
4230 })?;
4231 let (mi_row0, mi_col0) =
4232 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
4233 let leaf_positions: Vec<(u32, u32)> = (0..4)
4234 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
4235 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
4236 .collect();
4237 if leaves.len() != leaf_positions.len() {
4238 return Err(Error::unsupported(
4239 "AV1 tile",
4240 "a straddling 16x16 block needs one `eight` entry \
4241 per 8x8 leaf inside the true frame",
4242 ));
4243 }
4244 // r11: the enclosing 16x16 slot's
4245 // above_mode/left_mode arrays are too
4246 // coarse for a second leaf whose true
4247 // above (or left) neighbour is the FIRST
4248 // leaf -- track it here and hand it to
4249 // write_leaf8 as a context override.
4250 let mut prev_leaf: Option<((usize, usize), usize)> = None;
4251 for (leaf, (mr, mc)) in leaves.iter().zip(leaf_positions) {
4252 let leaf_mi = (mr as usize, mc as usize);
4253 // r8: read at mi granularity, not the
4254 // enclosing 16x16 slot -- the first
4255 // leaf's `record_mi` call below
4256 // updates `above_side_mi`/
4257 // `left_side_mi` at this leaf's own
4258 // mi position, which the second
4259 // leaf's ctx lookup then sees.
4260 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
4261 ec_rng_trace(|| {
4262 format!(
4263 "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={}",
4264 leaf_mi.0,
4265 leaf_mi.1,
4266 leaf_ctx,
4267 enc.tell()
4268 )
4269 });
4270 enc.symbol(
4271 PARTITION_NONE,
4272 &mut cdfs.partition_w8[leaf_ctx],
4273 );
4274 let grids = [
4275 level_grid(&leaf.luma, TX8)?,
4276 level_grid(&leaf.u, TX4)?,
4277 level_grid(&leaf.v, TX4)?,
4278 ];
4279 let leaf_mode = write_leaf8(
4280 &mut enc,
4281 &mut cdfs,
4282 &mut neighbours,
4283 leaf,
4284 at,
4285 leaf_mi,
4286 &grids,
4287 [&scans[2], &scans[3], &scans[3]],
4288 prev_leaf,
4289 tx_select,
4290 &scans,
4291 )?;
4292 prev_leaf = Some((leaf_mi, leaf_mode));
4293 ec_rng_trace(|| {
4294 format!(
4295 "EC_TOK mi_row={} mi_col={} tell={}",
4296 leaf_mi.0,
4297 leaf_mi.1,
4298 enc.tell()
4299 )
4300 });
4301 }
4302 // `record()`'s `above_mode`/`left_mode`
4303 // write is a no-op at an 8x8 leaf's own
4304 // side (`side / SUB == 0`), so the next
4305 // 16x16 quadrant beyond this straddling
4306 // one would otherwise see whatever stale
4307 // mode sat here before it: force the
4308 // write once the whole quadrant's leaves
4309 // are done, from the last (bottom/right-
4310 // most) leaf -- lane-av1-rect r15: doing
4311 // this *inside* `write_leaf8`, once per
4312 // leaf, let the first leaf's write
4313 // clobber the true external neighbour a
4314 // second leaf of the *same* quadrant
4315 // still needed to read on its
4316 // non-adjacency axis.
4317 if let Some((_, mode)) = prev_leaf {
4318 neighbours.above_mode[at.1] = mode;
4319 neighbours.left_mode[at.0] = mode;
4320 }
4321 }
4322 }
4323 }
4324 }
4325 }
4326 }
4327 }
4328 }
4329 Ok(enc.finish())
4330}
4331
4332/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`,
4333/// which the palette colour-index map's first (context-free) symbol is coded
4334/// with.
4335fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) {
4336 let l = crate::decode::ceil_log2(n as u32);
4337 let m = (1usize << l) - n;
4338 if value < m {
4339 enc.literal(value as u32, l - 1);
4340 } else {
4341 enc.literal(((value + m) >> 1) as u32, l - 1);
4342 enc.literal(((value + m) & 1) as u32, 1);
4343 }
4344}
4345
4346/// `write_palette_colors_y` (bitstream.c:1178), the write side of
4347/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache
4348/// entry (taken when this palette holds that colour, in cache order, stopping
4349/// once `n` are cached), then the colours the cache did not supply -- the
4350/// first raw, the rest as deltas off a bit width that shrinks with the range
4351/// left. `colors` is ascending and distinct, so the decoder's `merge_colors`
4352/// of the two ascending lists puts it back exactly.
4353fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) {
4354 let n = colors.len();
4355 let mut cached: Vec<u16> = Vec::with_capacity(n);
4356 for &c in cache {
4357 if cached.len() >= n {
4358 break;
4359 }
4360 let take = colors.contains(&c);
4361 enc.literal(u32::from(take), 1);
4362 if take {
4363 cached.push(c);
4364 }
4365 }
4366 let transmitted: Vec<u16> = colors
4367 .iter()
4368 .copied()
4369 .filter(|c| !cached.contains(c))
4370 .collect();
4371 if transmitted.is_empty() {
4372 return;
4373 }
4374 enc.literal(u32::from(transmitted[0]), 8);
4375 if transmitted.len() == 1 {
4376 return;
4377 }
4378 // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one
4379 // under which every delta still fits its (shrinking) width. `extra == 3`
4380 // always works -- a delta can never exceed the range left -- so the
4381 // search below always finds one.
4382 let fits = |extra: u32| -> bool {
4383 let mut bits = 5 + extra;
4384 let mut range = 255i32 - i32::from(transmitted[0]);
4385 for w in transmitted.windows(2) {
4386 let delta = i32::from(w[1]) - i32::from(w[0]);
4387 if delta - 1 >= (1i32 << bits) {
4388 return false;
4389 }
4390 range -= delta;
4391 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4392 }
4393 true
4394 };
4395 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
4396 enc.literal(extra, 2);
4397 let mut bits = 5 + extra;
4398 let mut range = 255i32 - i32::from(transmitted[0]);
4399 for w in transmitted.windows(2) {
4400 let delta = i32::from(w[1]) - i32::from(w[0]);
4401 enc.literal((delta - 1) as u32, bits);
4402 range -= delta;
4403 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4404 }
4405}
4406
4407/// `write_palette_colors_uv` (bitstream.c:1236), the write side of
4408/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is
4409/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two
4410/// documented differences -- the shrinking range starts at `256 - first`
4411/// (not `255 - first`) and each delta is written unbiased (no `-1`).
4412///
4413/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n`
4414/// 8-bit literals) rather than its first-value-plus-signed-deltas form.
4415/// Ceiling: about `n` bits per chroma-palette block more than the delta form
4416/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer
4417/// below sees, so it only ever makes the encoder take FEWER chroma palettes
4418/// than it should -- never a wrong stream. Upgrade path: price both forms
4419/// here and write the cheaper one under its own leading bit.
4420fn write_palette_colors_uv(
4421 enc: &mut SymbolEncoder,
4422 u_colors: &[u16],
4423 v_colors: &[u16],
4424 cache: &[u16],
4425) {
4426 let n = u_colors.len();
4427 let mut cached: Vec<u16> = Vec::with_capacity(n);
4428 for &c in cache {
4429 if cached.len() >= n {
4430 break;
4431 }
4432 let take = u_colors.contains(&c);
4433 enc.literal(u32::from(take), 1);
4434 if take {
4435 PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4436 cached.push(c);
4437 }
4438 }
4439 let transmitted: Vec<u16> = u_colors
4440 .iter()
4441 .copied()
4442 .filter(|c| !cached.contains(c))
4443 .collect();
4444 if !transmitted.is_empty() {
4445 enc.literal(u32::from(transmitted[0]), 8);
4446 if transmitted.len() > 1 {
4447 let fits = |extra: u32| -> bool {
4448 let mut bits = 5 + extra;
4449 let mut range = 256i32 - i32::from(transmitted[0]);
4450 for w in transmitted.windows(2) {
4451 let delta = i32::from(w[1]) - i32::from(w[0]);
4452 if delta >= (1i32 << bits) {
4453 return false;
4454 }
4455 range -= delta;
4456 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4457 }
4458 true
4459 };
4460 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
4461 enc.literal(extra, 2);
4462 let mut bits = 5 + extra;
4463 let mut range = 256i32 - i32::from(transmitted[0]);
4464 for w in transmitted.windows(2) {
4465 let delta = i32::from(w[1]) - i32::from(w[0]);
4466 enc.literal(delta as u32, bits);
4467 range -= delta;
4468 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4469 }
4470 }
4471 }
4472 enc.literal(0, 1);
4473 for &v in v_colors {
4474 enc.literal(u32::from(v), 8);
4475 }
4476}
4477
4478/// `write_palette_color_map` (bitstream.c), the write side of
4479/// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
4480/// each symbol written as the position its colour takes in the neighbour
4481/// ordering `av1_get_palette_color_index_context` hands back.
4482fn write_color_index_map(
4483 enc: &mut SymbolEncoder,
4484 idx_cdfs: &mut [[u16; 9]; 5],
4485 map: &[u8],
4486 side: usize,
4487 n: usize,
4488 // spec 5.11.50 `onscreenWidth`/`onscreenHeight` in this map's own units:
4489 // a block cut by the frame's right/bottom mi edge codes ONLY this corner
4490 // and the decoder replicates it outward (`decode::palette_replicate`).
4491 // Writing the full grid spent symbols a conformant decoder never reads,
4492 // desyncing the rest of the tile (lane-palw, class
4493 // writer-phantom-units-past-edge).
4494 on: (usize, usize),
4495) {
4496 let (on_w, on_h) = (on.0.clamp(1, side), on.1.clamp(1, side));
4497 write_uniform(enc, usize::from(map[0]), n);
4498 for i in 1..(on_w + on_h - 1) {
4499 for j in (i.saturating_sub(on_h - 1)..=i.min(on_w - 1)).rev() {
4500 let (row, col) = (i - j, j);
4501 let (ctx, color_order) =
4502 crate::decode::palette_color_index_context(map, side, row, col, n);
4503 let want = map[row * side + col];
4504 let symbol = color_order[..n]
4505 .iter()
4506 .position(|&c| c == want)
4507 .expect("every colour index is in the block\'s own palette");
4508 enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]);
4509 }
4510 }
4511}
4512
4513/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag,
4514/// the size symbol, the colours and the whole colour-index map, priced
4515/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the
4516/// search reads the rate the tile will really spend, not an estimate of it.
4517/// The neighbour cache is taken as empty (the search runs before the tile
4518/// knows what its neighbours will be), which only ever over-prices.
4519pub(crate) fn palette_bits(pal: &PaletteY, side: usize, on: (usize, usize)) -> f64 {
4520 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
4521 return f64::INFINITY;
4522 };
4523 let n = usize::from(pal.size);
4524 let mut enc = SymbolEncoder::pricer();
4525 let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0];
4526 enc.symbol(1, &mut mode_cdf);
4527 let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx];
4528 enc.symbol(n - 2, &mut size_cdf);
4529 write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
4530 let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];
4531 write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n, on);
4532 enc.bits()
4533}
4534
4535/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
4536/// size symbol, both colour lists and the shared colour-index map, priced
4537/// through the very writers above (empty cache, which only over-prices).
4538pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize, on: (usize, usize)) -> f64 {
4539 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
4540 return f64::INFINITY;
4541 };
4542 let n = usize::from(pal.size);
4543 let mut enc = SymbolEncoder::pricer();
4544 let mut mode_cdf = cdf::PALETTE_UV_MODE[0];
4545 enc.symbol(1, &mut mode_cdf);
4546 let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx];
4547 enc.symbol(n - 2, &mut size_cdf);
4548 write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
4549 let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];
4550 write_color_index_map(
4551 &mut enc,
4552 &mut idx_cdfs,
4553 &pal.map,
4554 palette_uv_side(side),
4555 n,
4556 on,
4557 );
4558 enc.bits()
4559}
4560
4561/// Writes everything a key frame's block carries before its coefficients: the
4562/// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
4563/// the angle a directional mode is steered by, and its chroma mode. Hands back
4564/// the luma mode, which is what the blocks beside it read.
4565/// The DV predictor decode.rs `read_intrabc_dv` derives, mirrored line for
4566/// line off the writer's own copy of the intrabc mi grid: the `INTRA_FRAME`
4567/// stack's `nearest_mv` (or `near_mv` when that is zero), or -- when both are
4568/// -- `av1_find_ref_dv`'s fallback one superblock up, or 256 pixels plus one
4569/// superblock to the left on the tile's first superblock row, then floored to
4570/// full pel. Returns `(0, 0)` when no grid is armed, which no `allow_intrabc`
4571/// tile ever reaches.
4572fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) {
4573 const INTRABC_DELAY_PIXELS: i32 = 256;
4574 let n4 = side / MI;
4575 let stack_pred = INTRABC_GRID.with(|g| {
4576 let g = g.borrow();
4577 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
4578 let stack = crate::mvstack::find_mv_stack(
4579 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
4580 *mi_cols, *mi_rows,
4581 );
4582 if stack.nearest_mv == (0, 0) {
4583 stack.near_mv
4584 } else {
4585 stack.nearest_mv
4586 }
4587 })
4588 });
4589 let mut pred = stack_pred.unwrap_or((0, 0));
4590 if pred == (0, 0) {
4591 // `av1_find_ref_dv` takes `mib_size`, the SEQUENCE's superblock size
4592 // in mi units (lane-b128m: hardcoding 16 here made the writer's DV
4593 // predictor one 64 superblock up while decode.rs `read_intrabc_dv`
4594 // took 128 -- identical symbols, different reconstructed DV). The
4595 // tile row start is 0, exactly as the reader takes it -- both are
4596 // written for the single-tile-row streams this encoder produces.
4597 let sb_mi = if sb128_armed() { 32i32 } else { 16i32 };
4598 let sb_px = sb_mi * MI as i32;
4599 pred = if (mi_r as i32) < sb_mi {
4600 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
4601 } else {
4602 (-sb_px * 8, 0)
4603 };
4604 }
4605 ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8)
4606}
4607
4608/// Publishes one coded block into [`INTRABC_GRID`], mirroring decode.rs
4609/// `record_intrabc_mi`: every block contributes its size, an intrabc one also
4610/// its DV as an `INTRA_FRAME` candidate.
4611fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
4612 INTRABC_GRID.with(|g| {
4613 let mut g = g.borrow_mut();
4614 let Some((grid, _, _)) = g.as_mut() else {
4615 return;
4616 };
4617 let info = crate::mvstack::MiInfo {
4618 is_inter: dv.is_some(),
4619 ref_frame: 0,
4620 ref_frame1: crate::mvstack::NO_REF1,
4621 mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))),
4622 mv1: (0, 0),
4623 is_new_mv: dv.is_some(),
4624 is_global_mv0: false,
4625 is_global_mv1: false,
4626 size: n4 as u8,
4627 size_h: n4 as u8,
4628 };
4629 for r in mi_r..mi_r + n4 {
4630 for c in mi_c..mi_c + n4 {
4631 grid.set(r, c, info);
4632 }
4633 }
4634 });
4635}
4636
4637/// One full-pel block-vector component, [`write_mv_component`]'s
4638/// `force_integer_mv` twin: decode.rs `read_mv_component` infers `mv_fr`/
4639/// `mv_class0_fr` as 3 and the high-precision bit as 1 under
4640/// `force_integer_mv`, so neither symbol is written here -- writing them
4641/// would leave the decoder two symbols behind from this block on.
4642fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
4643 let mag = diff.unsigned_abs() as i32;
4644 if mag % 8 != 0 {
4645 return Err(Error::unsupported(
4646 "AV1 tile",
4647 "a block vector is coded at full-pel precision only",
4648 ));
4649 }
4650 enc.symbol(usize::from(diff < 0), &mut c.sign);
4651 let z = mag - 1;
4652 let class = mv_class_of(z);
4653 enc.symbol(class, &mut c.class);
4654 let local = z - mv_class_base(class);
4655 if class == 0 {
4656 enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit);
4657 } else {
4658 let d = local >> 3;
4659 for i in 0..class {
4660 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
4661 }
4662 }
4663 Ok(())
4664}
4665
4666/// One intrabc block's DV as a residual against [`intrabc_dv_pred`], off the
4667/// `dv` nmv context (decode.rs `read_intrabc_dv` -> `read_mv`).
4668fn write_dv(
4669 enc: &mut SymbolEncoder,
4670 cdfs: &mut Cdfs,
4671 dv: (i32, i32),
4672 pred: (i32, i32),
4673) -> Result<()> {
4674 let diff = (dv.0 - pred.0, dv.1 - pred.1);
4675 let joint = match (diff.0 != 0, diff.1 != 0) {
4676 (false, false) => 0,
4677 (false, true) => 1,
4678 (true, false) => 2,
4679 (true, true) => 3,
4680 };
4681 enc.symbol(joint, &mut cdfs.dv_joint);
4682 if diff.0 != 0 {
4683 write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?;
4684 }
4685 if diff.1 != 0 {
4686 write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?;
4687 }
4688 Ok(())
4689}
4690
4691/// The mode-info half of an intrabc block (decode.rs `read_intra_mode`'s
4692/// early return): `skip`, `cdef_idx`, `use_intrabc` and the DV, then nothing
4693/// -- no y/uv mode, no angle delta, no palette, and (because it is skipped)
4694/// no transform size and no residual. Publishes the block into every
4695/// neighbour band an ordinary block leaves behind, at the DC_PRED/uncoded/
4696/// skipped state a decoder reads back for it.
4697fn write_intrabc_block(
4698 enc: &mut SymbolEncoder,
4699 cdfs: &mut Cdfs,
4700 neighbours: &mut Neighbours,
4701 dv: (i32, i32),
4702 mi: (usize, usize),
4703 side: usize,
4704) -> Result<()> {
4705 let skip_ctx =
4706 usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
4707 enc.symbol(1, &mut cdfs.skip[skip_ctx]);
4708 write_cdef_idx(enc, mi, true);
4709 enc.symbol(1, &mut cdfs.intrabc);
4710 write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?;
4711 note_intrabc(dv);
4712 // The bands: DC_PRED mode (what the decoder forces), no coefficients
4713 // anywhere (skip), the block's own side for the partition context, the
4714 // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm)
4715 // for the deblock grid, and `skip` itself for the next block's skip
4716 // context.
4717 // One zero level per plane: `neighbour_state` reads `grid[0]` for the DC
4718 // sign vote, and a skipped block leaves every context cleared.
4719 let empty: [Vec<i32>; 3] = [vec![0], vec![0], vec![0]];
4720 for cell in 0..(side / SUB).max(1) {
4721 let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI));
4722 neighbours.above_mode[c + cell] = DC_PRED;
4723 neighbours.left_mode[r + cell] = DC_PRED;
4724 neighbours.above_side[c + cell] = side;
4725 neighbours.left_side[r + cell] = side;
4726 }
4727 neighbours.record_mi_planes(mi, side, &empty, true);
4728 neighbours.record_tx(mi, side, side.min(64));
4729 for cell in 0..side / MI {
4730 neighbours.above_skip[mi.1 + cell] = true;
4731 neighbours.left_skip[mi.0 + cell] = true;
4732 }
4733 Ok(())
4734}
4735
4736/// `UV_CFL_PRED` (spec 6.10.19's chroma mode enum), the fourteenth entry of
4737/// [`crate::cdf::UV_MODE_CFL`] -- the writer's twin of the decoder's own
4738/// constant.
4739pub(crate) const UV_CFL_PRED: usize = 13;
4740
4741/// The `cfl_alpha_signs` joint value (0..8) that codes this signed alpha pair,
4742/// inverting the decoder's own `read_cfl_alphas` split (`sign_u =
4743/// ((joint+1)*11)>>5`, `sign_v = (joint+1) - 3*sign_u`, with 0 ZERO, 1 NEG,
4744/// 2 POS). There is no (ZERO, ZERO) joint value, so at least one alpha of a
4745/// CfL block is nonzero by construction.
4746pub(crate) fn cfl_joint_sign(alpha_u: i32, alpha_v: i32) -> usize {
4747 let sign = |a: i32| match a.signum() {
4748 0 => 0,
4749 -1 => 1,
4750 _ => 2,
4751 };
4752 let (want_u, want_v) = (sign(alpha_u), sign(alpha_v));
4753 (0..8)
4754 .find(|&j| {
4755 let su = ((j + 1) * 11) >> 5;
4756 (su, (j + 1) - 3 * su) == (want_u, want_v)
4757 })
4758 .expect("cfl_alpha_signs covers every pair but (ZERO, ZERO)") as usize
4759}
4760
4761/// The `cfl_alpha_u`/`cfl_alpha_v` magnitude CDF row for one plane, by the
4762/// same `CFL_CONTEXT_U`/`CFL_CONTEXT_V` derivation the decoder reads with
4763/// (libaom cfl.h). `joint` is [`cfl_joint_sign`]'s value.
4764fn cfl_alpha_ctx(joint: usize, plane: usize) -> usize {
4765 let joint = joint as i32;
4766 let su = ((joint + 1) * 11) >> 5;
4767 let sv = (joint + 1) - 3 * su;
4768 if plane == 0 {
4769 (joint + 1 - 3) as usize
4770 } else {
4771 (sv * 3 + su - 3) as usize
4772 }
4773}
4774
4775/// What [`write_cfl_alphas`] will spend on this alpha pair, through the same
4776/// tables -- the encoder's RD price for the CfL arm.
4777pub(crate) fn cfl_alpha_bits(alpha_u: i32, alpha_v: i32) -> f64 {
4778 use crate::encode::symbol_bits;
4779 let joint = cfl_joint_sign(alpha_u, alpha_v);
4780 let mut bits = symbol_bits(&crate::cdf::CFL_SIGN, joint);
4781 for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
4782 if alpha != 0 {
4783 bits += symbol_bits(
4784 &crate::cdf::CFL_ALPHA[cfl_alpha_ctx(joint, plane)],
4785 (alpha.unsigned_abs() - 1) as usize,
4786 );
4787 }
4788 }
4789 bits
4790}
4791
4792/// `read_cfl_alphas` (spec 5.11.45) written: the joint sign, then each
4793/// plane's magnitude where its sign is nonzero.
4794fn write_cfl_alphas(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, (alpha_u, alpha_v): (i32, i32)) {
4795 let joint = cfl_joint_sign(alpha_u, alpha_v);
4796 enc.symbol(joint, &mut cdfs.cfl_sign);
4797 for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
4798 if alpha != 0 {
4799 enc.symbol(
4800 (alpha.unsigned_abs() - 1) as usize,
4801 &mut cdfs.cfl_alpha[cfl_alpha_ctx(joint, plane)],
4802 );
4803 }
4804 }
4805}
4806
4807fn write_intra_mode(
4808 enc: &mut SymbolEncoder,
4809 cdfs: &mut Cdfs,
4810 neighbours: &mut Neighbours,
4811 block: &BlockCoeffs,
4812 above_mode: usize,
4813 left_mode: usize,
4814 cfl: bool,
4815 // This block's own position in 4x4 mode-info units, for the `cdef_idx`
4816 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
4817 mi: (usize, usize),
4818 // The block's side in samples, which gates the palette syntax below
4819 // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]).
4820 side: usize,
4821) -> usize {
4822 let mode = usize::from(block.mode);
4823 // `av1_get_skip_txfm_context` (decode.rs `Neighbours::skip_txfm_ctx`):
4824 // above + left. Every block this writer codes outside an `allow_intrabc`
4825 // frame is unskipped, so both bands stay false and this stays 0 -- the
4826 // literal every stream before this lane was written with.
4827 let skip_ctx =
4828 usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
4829 enc.symbol(0, &mut cdfs.skip[skip_ctx]);
4830 write_cdef_idx(enc, mi, false);
4831 // `read_intrabc_info` (spec 5.11.13): the flag is read for EVERY intra
4832 // block of an `allow_intrabc` frame, not only the ones that use it.
4833 if intrabc_armed() {
4834 enc.symbol(0, &mut cdfs.intrabc);
4835 }
4836 enc.symbol(
4837 mode,
4838 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
4839 );
4840 ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng()));
4841 if (V_PRED..=D67_PRED).contains(&mode) {
4842 enc.symbol(
4843 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
4844 &mut cdfs.angle_delta[mode - V_PRED],
4845 );
4846 }
4847 // A block small enough to be offered chroma from luma reads the wider
4848 // table even when it does not take the mode.
4849 let uv_mode = usize::from(block.uv_mode);
4850 if cfl {
4851 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
4852 } else {
4853 debug_assert_ne!(uv_mode, UV_CFL_PRED, "is_cfl_allowed excludes this block");
4854 enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);
4855 }
4856 if uv_mode == UV_CFL_PRED {
4857 write_cfl_alphas(
4858 enc,
4859 cdfs,
4860 block
4861 .cfl_alphas
4862 .expect("a UV_CFL_PRED block carries its alphas"),
4863 );
4864 }
4865 // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array
4866 // the luma delta reads, indexed by the chroma mode.
4867 if (V_PRED..=D67_PRED).contains(&uv_mode) {
4868 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
4869 }
4870 // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from
4871 // the decoder's own read in `read_intra_mode`: on a frame whose header set
4872 // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED`
4873 // chroma pair each carry a use-palette flag. Both contexts are 0 here --
4874 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
4875 // codes none -- exactly the ctx-0 read the decoder does under the same
4876 // condition.
4877 write_palette_syntax(
4878 enc,
4879 cdfs,
4880 neighbours,
4881 block.palette.as_ref(),
4882 block.palette_uv.as_ref(),
4883 block.filter_intra,
4884 mode,
4885 uv_mode,
4886 mi,
4887 side,
4888 );
4889 mode
4890}
4891
4892/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for
4893/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose
4894/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a
4895/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette
4896/// then codes its size, its colours (against the neighbour colour cache) and
4897/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs
4898/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and
4899/// by the three intra arms of the inter-frame writers, which read the same
4900/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`.
4901///
4902/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the
4903/// one point every block passes through), so a block that takes no palette
4904/// still clears what the column held.
4905#[allow(clippy::too_many_arguments)]
4906fn write_palette_syntax(
4907 enc: &mut SymbolEncoder,
4908 cdfs: &mut Cdfs,
4909 neighbours: &mut Neighbours,
4910 palette: Option<&PaletteY>,
4911 palette_uv: Option<&PaletteUv>,
4912 // lane-fintra: this block's chosen `filter_intra_mode`, or `None`. Written
4913 // here rather than by the caller because its symbol sits BETWEEN the
4914 // palette colour lists and the colour-index maps (decode.rs
4915 // `read_intra_mode`), which is inside this function.
4916 filter_intra: Option<u8>,
4917 mode: usize,
4918 uv_mode: usize,
4919 mi: (usize, usize),
4920 side: usize,
4921) {
4922 if !screen_armed() {
4923 write_filter_intra(enc, cdfs, mode, side, false, filter_intra);
4924 return;
4925 }
4926 let palette = palette.filter(|_| mode == DC_PRED);
4927 let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
4928 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
4929 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
4930 let uv_cache = neighbours.palette_uv_cache(mi);
4931 if mode == DC_PRED {
4932 enc.symbol(
4933 usize::from(palette.is_some()),
4934 &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],
4935 );
4936 }
4937 if let Some(pal) = palette {
4938 let n = usize::from(pal.size);
4939 enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);
4940 write_palette_colors_y(enc, &pal.colors[..n], &cache);
4941 }
4942 if uv_mode == DC_PRED {
4943 enc.symbol(
4944 usize::from(palette_uv.is_some()),
4945 &mut cdfs.palette_uv_mode[usize::from(palette.is_some())],
4946 );
4947 }
4948 if let Some(pal) = palette_uv {
4949 let n = usize::from(pal.size);
4950 enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]);
4951 write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache);
4952 }
4953 write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra);
4954 // Both colour-index maps come after BOTH colour lists, in plane order
4955 // (`av1_visit_palette` runs from the caller, past `filter_intra`).
4956 // The on-screen extent of THIS block, from the frame mi dims armed
4957 // for this tile write -- the decoder's `palette_onscreen` half.
4958 let on = crate::decode::palette_onscreen_dims(mi.0, mi.1, side, side, frame_mi_dims());
4959 if (on.0 < side || on.1 < side) && (palette.is_some() || palette_uv.is_some()) {
4960 PALETTE_CUT_MAPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4961 }
4962 if let Some(pal) = palette {
4963 let n = usize::from(pal.size);
4964 write_color_index_map(
4965 enc,
4966 &mut cdfs.palette_y_color_index[n - 2],
4967 &pal.map,
4968 side,
4969 n,
4970 on,
4971 );
4972 note_palette(n);
4973 }
4974 if let Some(pal) = palette_uv {
4975 let n = usize::from(pal.size);
4976 let uv_side = palette_uv_side(side);
4977 write_color_index_map(
4978 enc,
4979 &mut cdfs.palette_uv_color_index[n - 2],
4980 &pal.map,
4981 uv_side,
4982 n,
4983 // The encoder writes 4:2:0 only (`palette_uv_side` above).
4984 crate::decode::palette_onscreen_uv((side, side), on, (uv_side, uv_side), (1, 1)),
4985 );
4986 note_palette_uv(n);
4987 }
4988 } else {
4989 // Below `av1_allow_palette`'s size bound there is no palette syntax at
4990 // all, but `av1_filter_intra_allowed_bsize` still admits the block.
4991 write_filter_intra(enc, cdfs, mode, side, false, filter_intra);
4992 }
4993 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
4994 neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors));
4995}
4996
4997/// The side of a chroma palette's shared colour-index map for a square luma
4998/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at
4999/// the 4-px transform, NOT a plain halving (decode.rs reads the map at
5000/// exactly this size).
5001pub(crate) fn palette_uv_side(side: usize) -> usize {
5002 (side / 2).max(4)
5003}
5004
5005/// How many blocks took a palette, and of what size -- the fire count a gate
5006/// prints so that "palette is on" is a measurement rather than a claim
5007/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the
5008/// per-size histogram.
5009static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
5010 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
5011
5012/// lane-palw: colour-index maps written over the ON-SCREEN corner only,
5013/// i.e. palette blocks this writer cut at the frame's right/bottom mi edge.
5014/// A gate asserts it non-zero so it cannot pass on a stream that never cuts
5015/// one (class `gate-blind-to-feature`).
5016static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
5017
5018/// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps).
5019pub fn palette_cut_maps_written() -> usize {
5020 PALETTE_CUT_MAPS.load(std::sync::atomic::Ordering::Relaxed)
5021}
5022
5023/// Zeroes [`PALETTE_CUT_MAPS`] before a gate's own encode.
5024pub fn reset_palette_cut_maps_written() {
5025 PALETTE_CUT_MAPS.store(0, std::sync::atomic::Ordering::Relaxed);
5026}
5027
5028fn note_palette(n: usize) {
5029 PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5030 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5031}
5032
5033/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can
5034/// print the share of each plane's palette separately.
5035static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] =
5036 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
5037
5038fn note_palette_uv(n: usize) {
5039 PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5040 PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5041}
5042
5043/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than
5044/// the stream -- the half of `write_palette_colors_uv` a test cannot see from
5045/// the block counts alone, and the one that desyncs the tile if this writer's
5046/// cache ever disagrees with the decoder's (`gate-blind-to-feature`).
5047static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize =
5048 std::sync::atomic::AtomicUsize::new(0);
5049
5050/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it.
5051#[cfg(test)]
5052pub(crate) fn take_palette_uv_cache_hits() -> usize {
5053 PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
5054}
5055
5056/// [`take_palette_hits`] for the chroma palette.
5057#[cfg(test)]
5058pub(crate) fn take_palette_uv_hits() -> [usize; 9] {
5059 std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5060}
5061
5062/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
5063/// its own encode.
5064#[cfg(test)]
5065pub(crate) fn take_palette_hits() -> [usize; 9] {
5066 std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5067}
5068
5069/// Writes one coded block: its mode, its three transform blocks, and what it
5070/// leaves behind for the blocks beside it. Its partition symbol is already
5071/// written, because only the caller knows what tree led here.
5072#[allow(clippy::too_many_arguments)]
5073fn write_block(
5074 enc: &mut SymbolEncoder,
5075 cdfs: &mut Cdfs,
5076 neighbours: &mut Neighbours,
5077 block: &BlockCoeffs,
5078 at: (usize, usize),
5079 side: usize,
5080 planes: &[TxbSet; 3],
5081 grids: &[Vec<i32>; 3],
5082 scans: [&Vec<u16>; 3],
5083 cfl: bool,
5084 // The frame's `tx_mode == TxMode::Select`, and the block's own chosen
5085 // depth: with it the luma residual goes through [`write_luma_select`]
5086 // (one `tx_depth` symbol, then one transform unit per tile of the block)
5087 // instead of the single whole-block transform below.
5088 tx_select: bool,
5089 all_scans: &[Vec<u16>; 4],
5090) -> Result<()> {
5091 let (r, c) = at;
5092 let at_mi = (r * (SUB / MI), c * (SUB / MI));
5093 if let Some(dv) = block.dv {
5094 write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?;
5095 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv));
5096 return Ok(());
5097 }
5098 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
5099 let mode = write_intra_mode(
5100 enc, cdfs, neighbours, block, above_mode, left_mode, cfl, at_mi, side,
5101 );
5102 // The coefficient tables read `fimode_to_intradir[filter_intra_mode]`'s
5103 // row on a filter-intra block; the neighbour publication below still gets
5104 // the block's own `DC_PRED` ([`tx_row`]).
5105 let tx_mode = tx_row(mode, block.filter_intra);
5106 let split = if tx_select {
5107 let tx = write_luma_select(
5108 enc,
5109 cdfs,
5110 neighbours,
5111 at_mi,
5112 side,
5113 usize::from(block.tx_depth),
5114 &grids[0],
5115 tx_mode,
5116 all_scans,
5117 &block.luma_tx_types,
5118 )?;
5119 tx < side
5120 } else {
5121 false
5122 };
5123 write_block_planes(
5124 enc,
5125 cdfs,
5126 planes,
5127 grids,
5128 &scans,
5129 &neighbours.around(at, side),
5130 tx_mode,
5131 tx_select,
5132 block_tx_type(block),
5133 false,
5134 );
5135 neighbours.record_planes(at, side, mode, grids, !split);
5136 clear_skip_band(neighbours, at_mi, side);
5137 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None);
5138 Ok(())
5139}
5140
5141/// An unskipped block's own `skip` publication: only an `allow_intrabc`
5142/// frame ever sets these bands, so a frame without one leaves them exactly
5143/// as they were before this lane (all false).
5144fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) {
5145 if !intrabc_armed() {
5146 return;
5147 }
5148 for cell in 0..side / MI {
5149 neighbours.above_skip[mi.1 + cell] = false;
5150 neighbours.left_skip[mi.0 + cell] = false;
5151 }
5152}
5153
5154/// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
5155/// luma transform and 4x4 chroma transforms, coded exactly like
5156/// [`write_block`] but reading its intra-mode context from the *enclosing*
5157/// 16x16 slot -- `outer_at`, in [`SUB`]-grid units -- rather than from its own
5158/// finer position, since [`Neighbours`]'s `above_mode`/`left_mode` arrays stay
5159/// at [`SUB`] (16-sample) granularity. `leaf_mi` is this leaf's own position
5160/// in 4x4 mode-info units, which is what its coefficient context (finer than
5161/// [`SUB`]) is kept and read at.
5162#[allow(clippy::too_many_arguments)]
5163fn write_leaf8(
5164 enc: &mut SymbolEncoder,
5165 cdfs: &mut Cdfs,
5166 neighbours: &mut Neighbours,
5167 block: &BlockCoeffs,
5168 outer_at: (usize, usize),
5169 leaf_mi: (usize, usize),
5170 grids: &[Vec<i32>; 3],
5171 scans: [&Vec<u16>; 3],
5172 prev_leaf: Option<((usize, usize), usize)>,
5173 tx_select: bool,
5174 all_scans: &[Vec<u16>; 4],
5175) -> Result<usize> {
5176 let (r, c) = outer_at;
5177 if let Some(dv) = block.dv {
5178 write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?;
5179 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv));
5180 return Ok(DC_PRED);
5181 }
5182 let mut above_mode = neighbours.above_mode[c];
5183 let mut left_mode = neighbours.left_mode[r];
5184 // The previous leaf sits directly above (same column, two mi rows up)
5185 // or directly to the left (same row, two mi cols over) of this one --
5186 // in either case its just-written mode, not the enclosing 16x16 slot's
5187 // stale neighbour, is what a decoder reads as this leaf's context.
5188 if let Some(((pr, pc), pmode)) = prev_leaf {
5189 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
5190 above_mode = pmode;
5191 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
5192 left_mode = pmode;
5193 }
5194 }
5195 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
5196 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF -- like every
5197 // other `write_block` caller at 16x16 and up -- not the narrower
5198 // no-CFL one: r12 lane-av1-rect, this leaf's own `cfl: false` was the
5199 // true first divergence (a differently-sized alphabet under the same
5200 // DC_PRED decision desyncs the coder even though the decoded mode is
5201 // unchanged).
5202 let mode = write_intra_mode(
5203 enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8,
5204 );
5205 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
5206 // As [`write_block`]: the coefficient row follows the filter-intra mode,
5207 // the mode this leaf publishes (and returns to the next leaf) does not.
5208 let tx_mode = tx_row(mode, block.filter_intra);
5209 let split = if tx_select {
5210 let tx = write_luma_select(
5211 enc,
5212 cdfs,
5213 neighbours,
5214 leaf_mi,
5215 8,
5216 usize::from(block.tx_depth),
5217 &grids[0],
5218 tx_mode,
5219 all_scans,
5220 &block.luma_tx_types,
5221 )?;
5222 tx < 8
5223 } else {
5224 false
5225 };
5226 write_block_planes(
5227 enc,
5228 cdfs,
5229 &planes,
5230 grids,
5231 &scans,
5232 &neighbours.around_mi(leaf_mi, 8),
5233 tx_mode,
5234 tx_select,
5235 block_tx_type(block),
5236 false,
5237 );
5238 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
5239 clear_skip_band(neighbours, leaf_mi, 8);
5240 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None);
5241 Ok(mode)
5242}
5243
5244/// Writes the three transform blocks of one coded block, in the order a
5245/// decoder reads them.
5246#[allow(clippy::too_many_arguments)]
5247fn write_block_planes(
5248 enc: &mut SymbolEncoder,
5249 cdfs: &mut Cdfs,
5250 planes: &[TxbSet; 3],
5251 grids: &[Vec<i32>; 3],
5252 scans: &[&Vec<u16>; 3],
5253 around: &[Around; 3],
5254 mode: usize,
5255 // A block whose luma was already written as several transform units
5256 // ([`write_luma_select`]) has only its chroma planes left here.
5257 skip_luma: bool,
5258 // This block's single luma transform type (lane-txset); chroma's is
5259 // derived from its mode by the decoder and codes no symbol.
5260 luma_tx_type: TxType,
5261 // lane-intertx: an INTER block's chroma transforms INHERIT the luma
5262 // type (reduced to the chroma set against this frame's own
5263 // `reduced_tx_set` bit); an intra block's comes off its UV mode and
5264 // rides `DCT_DCT`'s 2D class exactly as before.
5265 inter: bool,
5266) {
5267 // lane-intertx, desync (b): the writer used to code every chroma plane
5268 // `DCT_DCT`. Chroma codes no `tx_type` symbol, but the type names the
5269 // transform class, and the class picks the scan, the `eob_pt` row and
5270 // the context offsets (the lane-txw note in `write_coeffs`) -- so an
5271 // inherited 1-D luma type desynced the chroma exactly as luma itself
5272 // once did. The reduced bit read here is the frame's own header bit,
5273 // the ONE the writer's `Cdfs` is armed with (`Cdfs::reduced_tx_set`).
5274 let reduced = cdfs.reduced_tx_set;
5275 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
5276 if plane == 0 && skip_luma {
5277 continue;
5278 }
5279 // Luma's transform covers its whole block, which fixes the all-zero
5280 // flag's context at zero; a chroma transform reads whether its
5281 // neighbours coded anything, on top of the offset the chroma tables
5282 // start at.
5283 let skip_ctx = if plane == 0 {
5284 0
5285 } else {
5286 usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
5287 };
5288 #[cfg(test)]
5289 let before = enc.tell();
5290 #[cfg(test)]
5291 let q_ctx = cdfs.q_ctx;
5292 let mut coding = cdfs.txb(planes[plane], mode);
5293 let tx_type = if plane == 0 {
5294 luma_tx_type
5295 } else if inter {
5296 crate::decode::reduce_inherited_chroma_tx_type_flagged(
5297 luma_tx_type,
5298 coding.side.min(32),
5299 coding.side.min(32),
5300 reduced,
5301 )
5302 } else {
5303 TxType::DctDct
5304 };
5305 write_coeffs(
5306 enc,
5307 &mut coding,
5308 grid,
5309 scan,
5310 skip_ctx,
5311 dc_sign_ctx(around[plane].dc_vote),
5312 Some(plane),
5313 tx_type,
5314 );
5315 #[cfg(test)]
5316 census_record(
5317 planes[plane],
5318 q_ctx,
5319 grid,
5320 f64::from(enc.tell() - before),
5321 skip_ctx,
5322 dc_sign_ctx(around[plane].dc_vote),
5323 );
5324 ec_rng_trace(|| {
5325 format!(
5326 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
5327 grid.iter().filter(|&&l| l != 0).count(),
5328 enc.tell()
5329 )
5330 });
5331 }
5332}
5333
5334/// The single luma transform type a block carries, `DCT_DCT` for one that
5335/// never searched one (lane-txset).
5336fn block_tx_type(block: &BlockCoeffs) -> TxType {
5337 block
5338 .luma_tx_types
5339 .first()
5340 .copied()
5341 .unwrap_or(TxType::DctDct)
5342}
5343
5344/// The `(side / tx)^2` transform units of one block's luma residual, raster
5345/// order, each with its own coefficient context and each published before the
5346/// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch).
5347/// `grid` is the block's levels in BLOCK coordinates when the transform
5348/// splits, and the single transform's own coefficient grid when it does not.
5349#[allow(clippy::too_many_arguments)]
5350fn write_luma_tus(
5351 enc: &mut SymbolEncoder,
5352 cdfs: &mut Cdfs,
5353 neighbours: &mut Neighbours,
5354 at_mi: (usize, usize),
5355 side: usize,
5356 tx: usize,
5357 grid: &[i32],
5358 mode: usize,
5359 scans: &[Vec<u16>; 4],
5360 // lane-av1tx2 r2: an INTER block's split units read the inter coefficient
5361 // tables, not the intra ones (`TxbSet::Luma*Inter`).
5362 inter: bool,
5363 // One transform type per unit in this same raster order (lane-txset).
5364 // Empty -- what every caller that never searched a type passes -- is
5365 // `DCT_DCT` throughout, the one type this writer used to code.
5366 tx_types: &[TxType],
5367) -> Result<()> {
5368 if tx < side && side > 32 && tx < 32 {
5369 // A 64x64 block's own levels reach the writer as the 32x32 corner a
5370 // 64-point transform codes unless the whole block was SPLIT into
5371 // TX_32X32 units (lane-b64b), so any finer split has nothing to slice.
5372 return Err(Error::unsupported(
5373 "AV1 tile",
5374 "a 64x64 block's luma transform splits no finer than TX_32X32",
5375 ));
5376 }
5377 let coeff_side = tx.min(32);
5378 let n = side / tx;
5379 let set = match (tx, inter) {
5380 (32, false) => TxbSet::Luma32,
5381 (16, false) => TxbSet::Luma16,
5382 (8, false) => TxbSet::Luma8,
5383 (4, false) => TxbSet::Luma4,
5384 (32, true) => TxbSet::Luma32Inter,
5385 (16, true) => TxbSet::Luma16Inter,
5386 (8, true) => TxbSet::Luma8Inter,
5387 (4, true) => TxbSet::Luma4Inter,
5388 _ => TxbSet::Luma64,
5389 };
5390 let scan = match coeff_side {
5391 32 => &scans[0],
5392 16 => &scans[1],
5393 8 => &scans[2],
5394 _ => &scans[3],
5395 };
5396 let (mi_r, mi_c) = at_mi;
5397 for tu_row in 0..n {
5398 for tu_col in 0..n {
5399 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
5400 // lane-av1straddle: libaom clips the transform loop to
5401 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
5402 // off the frame's true `mi_cols`/`mi_rows`), and decode.rs does
5403 // the same (`tu_px >= y.true_width` there): a unit whose TOP-LEFT
5404 // sample is outside the frame is NEVER coded. Writing one -- as
5405 // this loop did for the phantom right-hand column of a 32x32 at
5406 // x=192 in a 216-wide frame -- desyncs the tile at the very next
5407 // symbol, which is what made an odd-size GOP's last block
5408 // reconstruct differently and both ffmpeg decoders (libdav1d and
5409 // libaom) refuse the whole key frame.
5410 if tu_mi.0 >= neighbours.mi_rows || tu_mi.1 >= neighbours.mi_cols {
5411 continue;
5412 }
5413 let unit = if n == 1 {
5414 grid.to_vec()
5415 } else {
5416 (0..tx)
5417 .flat_map(|row| grid[(tu_row * tx + row) * side + tu_col * tx..][..tx].to_vec())
5418 .collect()
5419 };
5420 // spec `get_txb_ctx_general`: a lone transform unit covering its
5421 // whole block reads context 0, a smaller one the neighbour
5422 // magnitude table.
5423 let skip_ctx = if n == 1 {
5424 0
5425 } else {
5426 neighbours.luma_skip_ctx(tu_mi, tx / MI)
5427 };
5428 let around = neighbours.around_mi(tu_mi, tx)[0];
5429 #[cfg(test)]
5430 let before = enc.tell();
5431 #[cfg(test)]
5432 let q_ctx = cdfs.q_ctx;
5433 write_coeffs(
5434 enc,
5435 &mut cdfs.txb(set, mode),
5436 &unit,
5437 scan,
5438 skip_ctx,
5439 dc_sign_ctx(around.dc_vote),
5440 Some(0),
5441 tx_types
5442 .get(tu_row * n + tu_col)
5443 .copied()
5444 .unwrap_or(TxType::DctDct),
5445 );
5446 #[cfg(test)]
5447 census_record(
5448 set,
5449 q_ctx,
5450 &unit,
5451 f64::from(enc.tell() - before),
5452 skip_ctx,
5453 dc_sign_ctx(around.dc_vote),
5454 );
5455 if n > 1 {
5456 neighbours.record_mi_luma(tu_mi, tx, &unit);
5457 }
5458 }
5459 }
5460 Ok(())
5461}
5462
5463/// Writes one intra block's luma residual under `TxMode::Select`: the
5464/// `tx_depth` symbol (spec 5.11.16 `read_selected_tx_size`, off the size
5465/// category's own CDF at [`Neighbours::tx_size_ctx`]'s row), then the
5466/// `(side / tx)^2` transform units in raster order -- each predicted and
5467/// coded against what the units before it already left behind, which is why
5468/// every unit publishes its own coefficient context before the next one reads
5469/// it (decode.rs `decode_block`'s multi-transform-unit branch).
5470///
5471/// `grid` is the block's levels in BLOCK coordinates (`side` by `side`) when
5472/// the transform splits, and the single transform's own coefficient grid when
5473/// it does not. Hands back the resolved transform side in pixels.
5474#[allow(clippy::too_many_arguments)]
5475fn write_luma_select(
5476 enc: &mut SymbolEncoder,
5477 cdfs: &mut Cdfs,
5478 neighbours: &mut Neighbours,
5479 at_mi: (usize, usize),
5480 side: usize,
5481 depth: usize,
5482 grid: &[i32],
5483 mode: usize,
5484 scans: &[Vec<u16>; 4],
5485 tx_types: &[TxType],
5486) -> Result<usize> {
5487 let max_tx = side.min(64);
5488 let ctx = neighbours.tx_size_ctx(at_mi, max_tx);
5489 match max_tx {
5490 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
5491 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
5492 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
5493 64 => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
5494 _ => {
5495 return Err(Error::unsupported(
5496 "AV1 tile",
5497 "a tx_depth symbol is only coded at 8/16/32/64",
5498 ));
5499 }
5500 }
5501 let tx = max_tx >> depth;
5502 write_luma_tus(
5503 enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false, tx_types,
5504 )?;
5505 neighbours.record_tx(at_mi, side, tx);
5506 Ok(tx)
5507}
5508
5509/// The transform syntax one block of an INTER frame coded with
5510/// `tx_mode == TxMode::Select` carries, in the place spec 5.11.16's
5511/// `read_block_tx_size` reads it -- after the modes and the motion vector,
5512/// before the residual:
5513/// * an inter block that codes a residual walks a var-tx tree; this writer
5514/// keeps it at its own largest transform, so that is one `txfm_split` flag
5515/// of zero, off `txfm_partition_ctx_rect`'s row, publishing the bands per
5516/// unit the way `read_var_tx_size` does.
5517/// * a skipped inter block codes nothing and records its own BLOCK size
5518/// (`set_txfm_ctxs`'s `skip_inter` term).
5519/// * an intra block codes `tx_depth` like a key frame's, but off the
5520/// `TXFM_CONTEXT` bands rather than the deblock grid.
5521///
5522/// Hands back the block's resolved luma transform side.
5523#[allow(clippy::too_many_arguments)]
5524fn write_tx_syntax_inter(
5525 enc: &mut SymbolEncoder,
5526 cdfs: &mut Cdfs,
5527 neighbours: &mut Neighbours,
5528 at_mi: (usize, usize),
5529 side: usize,
5530 is_inter: bool,
5531 skip: bool,
5532 depth: usize,
5533) -> usize {
5534 let max_tx = side.min(64);
5535 let (mi_r, mi_c) = at_mi;
5536 if is_inter {
5537 if !skip {
5538 let ctx = txfm_partition_ctx_rect(
5539 neighbours.above_txfm[mi_c],
5540 neighbours.left_txfm[mi_r],
5541 side,
5542 max_tx,
5543 max_tx,
5544 );
5545 enc.symbol(usize::from(depth != 0), &mut cdfs.txfm_partition[ctx]);
5546 if depth == 0 {
5547 neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx);
5548 return max_tx;
5549 }
5550 // lane-av1tx2 r2: one halving of the var-tx tree. Each child of a
5551 // split root codes its own `txfm_split` (decode.rs
5552 // `read_var_tx_size` only stops symbol-free at `MAX_VARTX_DEPTH`
5553 // or at a 4x4 sub-size), off the bands the children before it
5554 // published -- so the context read and the update interleave per
5555 // unit, exactly as the reader's recursion does.
5556 let tx = max_tx / 2;
5557 for row in (0..max_tx / MI).step_by(tx / MI) {
5558 for col in (0..max_tx / MI).step_by(tx / MI) {
5559 let unit = (mi_r + row, mi_c + col);
5560 // The encoder only picks depth 1 for a block wholly
5561 // inside the frame; the reader skips a unit past the true
5562 // edge, which would leave the residual units unpaired.
5563 debug_assert!(
5564 unit.0 < neighbours.mi_rows && unit.1 < neighbours.mi_cols,
5565 "a split inter transform unit past the frame edge"
5566 );
5567 let ctx = txfm_partition_ctx_rect(
5568 neighbours.above_txfm[unit.1],
5569 neighbours.left_txfm[unit.0],
5570 side,
5571 tx,
5572 tx,
5573 );
5574 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
5575 neighbours.record_txfm(unit, tx, tx, tx);
5576 }
5577 }
5578 return tx;
5579 }
5580 neighbours.record_txfm(at_mi, side, side, side);
5581 return max_tx;
5582 }
5583 let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx);
5584 match max_tx {
5585 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
5586 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
5587 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
5588 _ => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
5589 }
5590 let tx = max_tx >> depth;
5591 neighbours.record_txfm(at_mi, tx, side, side);
5592 tx
5593}
5594
5595/// What a coded transform block leaves behind for the blocks that read it as a
5596/// neighbour.
5597fn neighbour_state(grid: &[i32]) -> Neighbour {
5598 Neighbour {
5599 coded: grid.iter().any(|&l| l != 0),
5600 level: grid.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8,
5601 dc: (grid[0] != 0).then_some(grid[0] < 0),
5602 }
5603}
5604
5605/// Writes the payload of a one-tile key frame in which every superblock is
5606/// split into 32x32 blocks, each carrying the coefficients `blocks` gives it.
5607///
5608/// `blocks` gives one coefficient set per 32x32 block in raster order across
5609/// the frame. This is [`sb_coeff_key_frame_tile`] with every superblock split.
5610///
5611/// # Errors
5612/// As [`sb_coeff_key_frame_tile`], with `blocks` sized for the 32x32 grid.
5613pub fn split_coeff_key_frame_tile(
5614 mi_cols: u32,
5615 mi_rows: u32,
5616 base_q_idx: u8,
5617 blocks: &[BlockCoeffs],
5618) -> Result<Vec<u8>> {
5619 check_blocks(mi_cols, mi_rows)?;
5620 let (cols, rows) = block_grid(mi_cols, mi_rows);
5621 if blocks.len() != (cols * rows) as usize {
5622 return Err(Error::unsupported(
5623 "AV1 tile",
5624 "a coefficient key frame needs one coefficient set per 32x32 block",
5625 ));
5626 }
5627 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
5628 let superblocks: Vec<Superblock> = (0..sb_rows)
5629 .flat_map(|sb_r| (0..sb_cols).map(move |sb_c| (sb_r, sb_c)))
5630 .map(|(sb_r, sb_c)| {
5631 Superblock::Split(
5632 (0..4)
5633 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
5634 .filter(|&(r, c)| r < rows && c < cols)
5635 .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone()))
5636 .collect(),
5637 )
5638 })
5639 .collect();
5640 sb_coeff_key_frame_tile(mi_cols, mi_rows, base_q_idx, &superblocks)
5641}
5642
5643/// Lays one plane's coefficient list out over its transform, rejecting the
5644/// positions and levels the writer does not code.
5645fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
5646 let mut grid = vec![0i32; side * side];
5647 for coeff in coeffs {
5648 if usize::from(coeff.row) >= side || usize::from(coeff.col) >= side {
5649 return Err(Error::unsupported(
5650 "AV1 tile",
5651 "a coefficient sits outside the transform of its plane",
5652 ));
5653 }
5654 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
5655 return Err(Error::unsupported(
5656 "AV1 tile",
5657 format!(
5658 "coefficients are written for levels -{MAX_LEVEL}..={MAX_LEVEL} without zero"
5659 ),
5660 ));
5661 }
5662 let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
5663 if grid[pos] != 0 {
5664 return Err(Error::unsupported(
5665 "AV1 tile",
5666 "two coefficients of one block share a position",
5667 ));
5668 }
5669 grid[pos] = coeff.level;
5670 }
5671 Ok(grid)
5672}
5673
5674/// The default scan of a square transform (spec 8.4.2's `Default_Scan_NxN`),
5675/// as raster positions in the order they are coded.
5676///
5677/// The table is a rule rather than hundreds of pinned numbers: the scan walks
5678/// the anti-diagonals of the transform outwards from the origin, each diagonal
5679/// from its top-right end on odd diagonals and from its bottom-left end on
5680/// even ones.
5681fn default_scan(side: usize) -> Vec<u16> {
5682 let mut scan = Vec::with_capacity(side * side);
5683 for d in 0..(2 * side - 1) {
5684 let lo = d.saturating_sub(side - 1);
5685 let hi = d.min(side - 1);
5686 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5687 if d % 2 == 0 {
5688 scan.extend(diagonal.rev());
5689 } else {
5690 scan.extend(diagonal);
5691 }
5692 }
5693 scan
5694}
5695
5696/// What one 32x32 luma transform block's levels cost, in bits, priced through
5697/// the very CDFs [`write_coeffs`] will write them with -- end-of-block
5698/// position, base levels, base range, signs and the Golomb tail all included.
5699///
5700/// The mode search calls this before the block's neighbours exist, so the two
5701/// neighbour-derived contexts (the block-skip context and the DC sign context)
5702/// are taken as zero. Every other context inside the block is exact, because
5703/// those are read from the block's own levels.
5704///
5705/// The encoder codes 32x32 luma only -- every superblock it emits is split --
5706/// so one table is all the search needs; a second block size would need its
5707/// own entry point rather than a size argument, because the table and the scan
5708/// have to agree.
5709/// What the search paid for every coefficient of `blocks`, in bits: the same
5710/// [`coeff_bits`] price the mode search ranked those blocks by, summed over
5711/// the blocks that were actually kept.
5712///
5713/// The instrument behind `predicted_coeff_bits_track_the_tile_the_writer_wrote`
5714/// (lane-av1rd1): the writer codes these levels against a state that has
5715/// adapted away from the defaults `coeff_bits` prices with, and against real
5716/// neighbour contexts instead of the empty ones, so the sum here and the tile
5717/// the writer produced differ by exactly that drift plus the non-coefficient
5718/// syntax (partition/mode/skip/mv symbols) the sum leaves out.
5719#[cfg(test)]
5720fn dense(coeffs: &[Coeff], side: usize) -> Vec<i32> {
5721 let mut grid = vec![0i32; side * side];
5722 for c in coeffs {
5723 grid[usize::from(c.row) * side + usize::from(c.col)] = c.level;
5724 }
5725 grid
5726}
5727
5728#[cfg(test)]
5729pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8) -> f64 {
5730 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
5731 superblocks
5732 .iter()
5733 .map(|sb| match sb {
5734 // A whole 64x64 codes its luma through `TxbSet::Luma64` (only the
5735 // top-left 32x32 carries coefficients) and each chroma plane at
5736 // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here.
5737 Superblock::Whole(block) if !block.skip => {
5738 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
5739 + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5740 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5741 }
5742 Superblock::Whole(_) => 0.0,
5743 Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx),
5744 })
5745 .sum()
5746}
5747
5748#[cfg(test)]
5749pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
5750 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
5751 fn block_bits(block: &BlockCoeffs, side: usize, q_ctx: usize) -> f64 {
5752 if let Some(leaves) = &block.eight {
5753 return leaves.iter().map(|l| block_bits(l, 8, q_ctx)).sum();
5754 }
5755 if block.skip {
5756 return 0.0;
5757 }
5758 let inter = block.inter.is_some();
5759 let (luma, chroma) = match (side, inter) {
5760 (32, false) => (TxbSet::Luma32, TxbSet::Chroma16),
5761 (32, true) => (TxbSet::Luma32Inter, TxbSet::Chroma16),
5762 (16, false) => (TxbSet::Luma16, TxbSet::Chroma8),
5763 (16, true) => (TxbSet::Luma16Inter, TxbSet::Chroma8),
5764 (_, false) => (TxbSet::Luma8, TxbSet::Chroma4),
5765 (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4),
5766 };
5767 coeff_bits(&dense(&block.luma, side), luma, q_ctx, 0, 0)
5768 + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx, 0, 0)
5769 + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx, 0, 0)
5770 }
5771 blocks
5772 .iter()
5773 .map(|q| {
5774 let side = match q {
5775 // lane-b128: a 128x128 root is SKIP by construction (the
5776 // writer refuses a residual at that size), so it names no
5777 // coefficients on any plane.
5778 Quadrant::Whole128(_) | Quadrant::Rect128(..) | Quadrant::Ab128(..) => {
5779 return 0.0;
5780 }
5781 Quadrant::Whole(_) => 32,
5782 Quadrant::Split(_) => 16,
5783 // lane-tx64: a 64x64 root that codes a residual pays for one
5784 // TX_64X64 luma transform (only the top-left 32x32 carries
5785 // coefficients) and one TX_32X32 per chroma plane -- the same
5786 // three prices `predicted_coeff_bits_sb` takes for a key
5787 // frame's whole superblock, and the same sets the writer's
5788 // `Whole64` arm codes. `block_bits`'s table has no 64 row, so
5789 // it is spelled out here.
5790 Quadrant::Whole64(block) => {
5791 return match block.skip {
5792 true => 0.0,
5793 false => {
5794 // lane-b64b: at `tx_depth = 1` the luma levels are
5795 // the whole 64-sided block, written as four
5796 // TX_32X32 units, so the pricer slices them the
5797 // same way the writer does.
5798 let luma = if block.tx_depth == 1 {
5799 let g = dense(&block.luma, 64);
5800 (0..4)
5801 .map(|tu| {
5802 let (r0, c0) = ((tu / 2) * 32, (tu % 2) * 32);
5803 let unit: Vec<i32> = (0..32)
5804 .flat_map(|row| {
5805 g[(r0 + row) * 64 + c0..][..32].to_vec()
5806 })
5807 .collect();
5808 coeff_bits(&unit, TxbSet::Luma32Inter, q_ctx, 0, 0)
5809 })
5810 .sum::<f64>()
5811 } else {
5812 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
5813 };
5814 luma + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5815 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5816 }
5817 };
5818 }
5819 Quadrant::Covered => return 0.0,
5820 };
5821 q.blocks()
5822 .iter()
5823 .map(|b| block_bits(b, side, q_ctx))
5824 .sum::<f64>()
5825 })
5826 .sum()
5827}
5828
5829#[cfg(test)]
5830pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
5831 coeff_bits(grid, TxbSet::Luma32, 2, 0, 0)
5832}
5833
5834/// What one transform block's levels cost through the CDFs of `set`, in bits.
5835///
5836/// The search runs before the tile is written, so the adapted state the block
5837/// will really be coded against does not exist yet: the price is taken against
5838/// the defaults every tile starts from, at the frame's own coefficient
5839/// q-context (`q_ctx_of(base_q_idx)`, what `Cdfs::new` is given at
5840/// `sb_coeff_*_tile` -- lane-av1rd1: this used to be pinned at 2, so two of
5841/// the four points of the BD ladder were priced against another quantizer's
5842/// tables), and against the contexts a block whose neighbours coded nothing
5843/// reads.
5844///
5845/// lane-av1skipctx CLOSED that row: `skip_ctx`/`sign_ctx` are the caller's
5846/// now, and [`crate::encode::CoefCtxMap`] -- a per-plane, per-4x4-cell map
5847/// committed in coding order and undone with a losing partition trial's
5848/// pixels -- is the per-trial neighbour state the previous lane said the
5849/// search did not have. The census (6 frames of each clip at 640x384, q=100,
5850/// `pricer_error_census_on_clips`) moved:
5851///
5852/// | row | before | after |
5853/// |---|---|---|
5854/// | screen total | +10.3% | +9.5% |
5855/// | screen Chroma8 nz=0 | -73.0% | -1.9% |
5856/// | screen Chroma16 nz=0 | -48% | -23.4% |
5857/// | screen Chroma4 nz=0 | -74% | -6.7% |
5858/// | screen Chroma8 nz=1 / nz=2 | +32.2% / +26.2% | +4.9% / +7.9% |
5859/// | screen Luma4 nz=0 | +464% | +89.5% |
5860/// | film total | +5.3% | +1.5% |
5861///
5862/// What is left in the all-zero rows is table ADAPTATION, not context: the
5863/// price is taken against the frame's starting tables, and a frame whose
5864/// blocks mostly code nothing narrows `txb_skip` far below where it started.
5865/// A whole-block luma transform still reads context 0 -- that is what the
5866/// writer codes (`write_luma_tus`, `n == 1`), not an approximation.
5867/// The default scan of one transform size, built once per size: the search
5868/// prices thirteen modes for every block, and the scan is the same table
5869/// every time.
5870fn scan_of(side: usize) -> &'static Vec<u16> {
5871 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {
5872 [
5873 default_scan(TX4),
5874 default_scan(TX8),
5875 default_scan(TX16),
5876 default_scan(TX32),
5877 ]
5878 });
5879 match side {
5880 TX4 => &SCANS[0],
5881 TX8 => &SCANS[1],
5882 TX16 => &SCANS[2],
5883 _ => &SCANS[3],
5884 }
5885}
5886
5887/// [`scan_of`]'s `TX_CLASS_HORIZ`/`TX_CLASS_VERT` sibling (lane-txw): the
5888/// `Mrow_Scan`/`Mcol_Scan` a `V_DCT`/`H_DCT` unit is coded in, built off the
5889/// DECODER's own table so the two cannot drift, cached per size and class.
5890fn class_scan_of(side: usize, class: crate::decode::TxClass) -> &'static [u16] {
5891 static SCANS: LazyLock<[[Vec<u16>; 2]; 4]> = LazyLock::new(|| {
5892 use crate::decode::{class_scan_table, TxClass};
5893 [TX4, TX8, TX16, TX32].map(|side| {
5894 [
5895 class_scan_table(side, TxClass::Horiz),
5896 class_scan_table(side, TxClass::Vert),
5897 ]
5898 })
5899 });
5900 let size = match side {
5901 TX4 => 0,
5902 TX8 => 1,
5903 TX16 => 2,
5904 _ => 3,
5905 };
5906 let idx = usize::from(class == crate::decode::TxClass::Vert);
5907 &SCANS[size][idx]
5908}
5909
5910/// [`coeff_bits_typed`] at `DCT_DCT`, the only type the test-only pricers
5911/// ([`predicted_coeff_bits`]) model.
5912#[cfg(test)]
5913pub(crate) fn coeff_bits(
5914 grid: &[i32],
5915 set: TxbSet,
5916 q_ctx: usize,
5917 skip_ctx: usize,
5918 sign_ctx: usize,
5919) -> f64 {
5920 coeff_bits_typed(grid, set, q_ctx, skip_ctx, sign_ctx, TxType::DctDct)
5921}
5922
5923/// What levels a named transform type produced cost: the `tx_type`
5924/// symbol is part of what the block spends, so a search comparing types has
5925/// to see each one's own symbol priced (lane-txset).
5926pub(crate) fn coeff_bits_typed(
5927 grid: &[i32],
5928 set: TxbSet,
5929 q_ctx: usize,
5930 // lane-av1skipctx: the two neighbour-derived contexts, mirrored from the
5931 // writer's own (`write_block_planes`/`write_luma_tus`) off the search's
5932 // coding-order-committed map ([`crate::encode::CoefCtxMap`]). `(0, 0)` is
5933 // what every caller passed before the map existed -- exact for a luma
5934 // transform covering its whole block, and the census row that was the
5935 // largest remaining pricer error for every other block.
5936 skip_ctx: usize,
5937 sign_ctx: usize,
5938 tx_type: TxType,
5939) -> f64 {
5940 // `Cdfs::new` builds every table a tile writer adapts -- tens of
5941 // kilobytes -- and this function is called once per priced candidate:
5942 // together with the copy behind it that was 9% of the encoder's profile
5943 // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the
5944 // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per
5945 // q-context per thread beside a pristine one and restore just those from
5946 // it. The state the price is taken against is identical to a fresh
5947 // `Cdfs::new(q_ctx)`, so every price is bit-identical.
5948 // lane-av1txbits: an inter frame's writer does NOT start from the
5949 // defaults -- it starts from the tables the previous frame stored (spec
5950 // 7.20, `start_cdfs` in `encode_inter_frame`) -- so pricing against the
5951 // defaults charged the search for a narrowing the writer no longer pays.
5952 // The census measured that at +31% on the one-coefficient inter blocks
5953 // the search lives on. `arm_pricing_cdfs` puts the frame's own starting
5954 // tables under the price; nothing armed keeps the old default behaviour.
5955 let price = |slot: &mut (Cdfs, Cdfs)| {
5956 let (pristine, scratch) = (&mut slot.0, &mut slot.1);
5957 let src = pristine.txb(set, DC_PRED);
5958 let mut coding = scratch.txb(set, DC_PRED);
5959 coding.txb_skip.copy_from_slice(src.txb_skip);
5960 coding.eob_pt.copy_from_slice(src.eob_pt);
5961 if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) {
5962 dst.copy_from_slice(src);
5963 }
5964 *coding.eob_extra = *src.eob_extra;
5965 *coding.base = *src.base;
5966 *coding.base_eob = *src.base_eob;
5967 *coding.br = *src.br;
5968 *coding.dc_sign = *src.dc_sign;
5969 if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) {
5970 dst.copy_from_slice(src);
5971 }
5972 let scan = scan_of(coding.side);
5973 let mut enc = SymbolEncoder::pricer();
5974 write_coeffs(
5975 &mut enc,
5976 &mut coding,
5977 grid,
5978 scan,
5979 skip_ctx,
5980 sign_ctx,
5981 None,
5982 tx_type,
5983 );
5984 enc.bits()
5985 };
5986 // lane-av1speed2: 60% of the transform units of an inter stream hold no
5987 // coefficient, and for those `write_coeffs` codes ONE symbol -- the
5988 // all-zero flag -- and returns. Restoring the eight tables it might have
5989 // touched (~800 bytes of `copy_from_slice`, the largest `memmove` in the
5990 // encoder's profile) buys nothing there, so price that symbol straight
5991 // off the pristine table on a copy of its own row. Identical bits: the
5992 // scratch's `txb_skip[skip_ctx]` was restored from exactly this row, and
5993 // nothing after the flag runs.
5994 let zero_price = |slot: &mut (Cdfs, Cdfs)| {
5995 let mut row = slot.0.txb(set, DC_PRED).txb_skip[skip_ctx];
5996 let mut enc = SymbolEncoder::pricer();
5997 enc.symbol(1, &mut row);
5998 enc.bits()
5999 };
6000 let all_zero = grid.iter().all(|&level| level == 0);
6001 PRICING_BASE.with_borrow_mut(|base| {
6002 if let Some(slot) = base.as_deref_mut().filter(|s| s.0.q_ctx == q_ctx) {
6003 return if all_zero {
6004 zero_price(slot)
6005 } else {
6006 price(slot)
6007 };
6008 }
6009 PRICING.with_borrow_mut(|slots| {
6010 let slot = slots[q_ctx.min(3)]
6011 .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
6012 if all_zero {
6013 zero_price(slot)
6014 } else {
6015 price(slot)
6016 }
6017 })
6018 })
6019}
6020
6021/// The largest level [`rdoq`] offers a candidate for, and the most prices it
6022/// may spend on one block. `EC_AV1_RDOQ_MAXLEVEL` / `EC_AV1_RDOQ_BUDGET`
6023/// sweep them; see [`rdoq`] for why both exist.
6024const RDOQ_MAX_LEVEL: u32 = 2;
6025const RDOQ_BUDGET: u32 = 24;
6026
6027fn rdoq_max_level() -> u32 {
6028 static ENV: LazyLock<u32> = LazyLock::new(|| {
6029 crate::envflags::var("EC_AV1_RDOQ_MAXLEVEL")
6030 .ok()
6031 .and_then(|v| v.parse().ok())
6032 .unwrap_or(RDOQ_MAX_LEVEL)
6033 });
6034 *ENV
6035}
6036
6037fn rdoq_budget() -> u32 {
6038 static ENV: LazyLock<u32> = LazyLock::new(|| {
6039 crate::envflags::var("EC_AV1_RDOQ_BUDGET")
6040 .ok()
6041 .and_then(|v| v.parse().ok())
6042 .unwrap_or(RDOQ_BUDGET)
6043 });
6044 *ENV
6045}
6046
6047/// Rate-distortion optimised quantisation (lane-rdoq): the pass every
6048/// reference encoder runs after the quantiser and this one did not have.
6049///
6050/// The deadzone quantiser rounds each coefficient on its own, blind to what
6051/// the coded level costs. Every reference decides that per coefficient
6052/// against the entropy coder (libaom `av1_optimize_txb`, rav1e
6053/// `optimize_txb`): a level is lowered toward zero when the bits it gives
6054/// back are worth more than the squared error it adds, which also shortens
6055/// the eob when the tail levels go to zero.
6056///
6057/// Mirroring rav1e's shape without its incremental cost model: the candidate
6058/// set per coefficient is `{level, level - 1, .., 0}` walked one step at a
6059/// time in REVERSE scan order (the tail first, so a dropped tail is retried
6060/// against the shorter eob it leaves), and each candidate is priced by
6061/// re-coding the whole block through [`coeff_bits`] -- the same CDFs, the
6062/// same neighbour contexts and the same writer the search already prices
6063/// with, so no second cost model can drift from the writer (class
6064/// `table-and-reader-move-together`). That costs one `write_coeffs` per
6065/// candidate instead of rav1e's table lookup, which is why this is a preset
6066/// lever (`crate::speed::RDOQ`) and not unconditional.
6067///
6068/// `levels` is the side-strided grid the inverse transform and the writer
6069/// will read, `scaled` the pre-rounding `coeff / q` of each position
6070/// (`crate::transform::forward_and_quantize_scaled`). `lambda` is the rate
6071/// weight in units of ONE SQUARED AC QUANTISER STEP: the search's own
6072/// `sse + lambda * bits` is `step^2 * (sum (scaled - level)^2 + LAMBDA_SCALE
6073/// * bits)` once the pixel-domain error of a level is written through the
6074/// orthonormal transform (`(coeff - level * q) / 8`, `INVERSE_GAIN_RECIPROCAL`),
6075/// so `step^2` divides out of every comparison here and the DC's different
6076/// quantiser is the only per-position weight left.
6077///
6078/// Returns what the block's levels cost after the pass, so the caller prices
6079/// the tile it will actually write and never the pre-RDOQ grid.
6080#[allow(clippy::too_many_arguments)]
6081pub(crate) fn rdoq(
6082 levels: &mut [i32],
6083 scaled: &[f32],
6084 side: usize,
6085 base_q_idx: u8,
6086 set: TxbSet,
6087 skip_ctx: usize,
6088 sign_ctx: usize,
6089 lambda: f64,
6090 tx_type: TxType,
6091) -> f64 {
6092 // A 64-point transform carries its top-left 32x32 alone, and that corner
6093 // is what the writer and the pricer take (`coded_corner`).
6094 let coded = side.min(TX32);
6095 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
6096 let mut dense = if coded == side {
6097 Vec::new()
6098 } else {
6099 vec![0i32; coded * coded]
6100 };
6101 fn price(
6102 levels: &[i32],
6103 dense: &mut [i32],
6104 side: usize,
6105 coded: usize,
6106 set: TxbSet,
6107 q_ctx: usize,
6108 skip_ctx: usize,
6109 sign_ctx: usize,
6110 tx_type: TxType,
6111 ) -> f64 {
6112 if dense.is_empty() {
6113 return coeff_bits_typed(levels, set, q_ctx, skip_ctx, sign_ctx, tx_type);
6114 }
6115 for row in 0..coded {
6116 dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]);
6117 }
6118 coeff_bits_typed(dense, set, q_ctx, skip_ctx, sign_ctx, tx_type)
6119 }
6120 let mut bits = price(
6121 levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type,
6122 );
6123 // The DC has its own quantiser, so its squared error per unit of level is
6124 // `(dc_q / ac_q)^2` of an AC coefficient's.
6125 let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx)));
6126 let ac = f64::from(crate::quant::ac_q(8, i32::from(base_q_idx)));
6127 let dc_weight = (dc / ac) * (dc / ac);
6128 let census = crate::envflags::env_flag!("EC_AV1_RDOQ_CENSUS");
6129 if census {
6130 census_block(levels, scaled, side, coded, bits);
6131 }
6132 // Where the pass may spend its prices. Every candidate here costs a whole
6133 // `write_coeffs`, where rav1e's incremental model costs a table lookup,
6134 // so both bounds exist to keep that affordable -- and both cut where the
6135 // decisions do not pay anyway:
6136 // * a level above [`RDOQ_MAX_LEVEL`] is never a candidate: one step off
6137 // a big level gives back a fraction of a bit for a whole quantiser
6138 // step of squared error. What pays is `1 -> 0` and `2 -> 1`.
6139 // * at most [`RDOQ_BUDGET`] prices per block, spent from the TAIL
6140 // backwards -- the eob end, where dropping a level also shortens the
6141 // eob -- so a fine-quantizer block carrying two hundred coefficients
6142 // cannot cost two hundred re-codings.
6143 let mut budget = rdoq_budget();
6144 let max_level = rdoq_max_level();
6145 // lane-txw: the tail this walks back from is the tail of the unit's OWN
6146 // scan -- a `V_DCT`/`H_DCT` unit is coded in `Mrow_Scan`/`Mcol_Scan`, so
6147 // the 2D zigzag's last positions are not the ones whose removal shortens
6148 // its eob. Every candidate is still priced through the class-aware writer
6149 // ([`write_coeffs`]), so this changes which positions the budget reaches,
6150 // never whether a decision is right.
6151 let class = crate::decode::TxClass::of(tx_type);
6152 let order: &[u16] = if class == crate::decode::TxClass::TwoD {
6153 scan_of(coded)
6154 } else {
6155 class_scan_of(coded, class)
6156 };
6157 for &position in order.iter().rev() {
6158 if budget == 0 {
6159 break;
6160 }
6161 let (row, col) = (usize::from(position) / coded, usize::from(position) % coded);
6162 let i = row * side + col;
6163 if levels[i] == 0 || levels[i].unsigned_abs() > max_level {
6164 continue;
6165 }
6166 let s = f64::from(scaled[i]);
6167 let weight = if i == 0 { dc_weight } else { 1.0 };
6168 while budget > 0 {
6169 let level = levels[i];
6170 let candidate = level - level.signum();
6171 levels[i] = candidate;
6172 budget -= 1;
6173 let after = price(
6174 levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type,
6175 );
6176 let distortion =
6177 weight * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2));
6178 if distortion + lambda * (after - bits) < 0.0 {
6179 bits = after;
6180 if census {
6181 RDOQ_STATS[if candidate == 0 { 4 } else { 5 }].fetch_add(1, Ordering::Relaxed);
6182 }
6183 if candidate == 0 {
6184 break;
6185 }
6186 } else {
6187 levels[i] = level;
6188 break;
6189 }
6190 }
6191 }
6192 if census {
6193 RDOQ_STATS[6].fetch_add((bits * 64.0) as u64, Ordering::Relaxed);
6194 }
6195 bits
6196}
6197
6198/// blocks, coded coefficients, +-1 levels, trailing +-1 levels (a run of them
6199/// at the end of the scan), zeroed coefficients, lowered coefficients, bits
6200/// after the pass * 64, bits before the pass * 64.
6201pub(crate) static RDOQ_STATS: [AtomicU64; 8] = [
6202 AtomicU64::new(0),
6203 AtomicU64::new(0),
6204 AtomicU64::new(0),
6205 AtomicU64::new(0),
6206 AtomicU64::new(0),
6207 AtomicU64::new(0),
6208 AtomicU64::new(0),
6209 AtomicU64::new(0),
6210];
6211
6212/// The pre-pass half of [`RDOQ_STATS`] (`EC_AV1_RDOQ_CENSUS`): what the
6213/// quantiser handed the pass, which is the instrument for how much is at
6214/// stake before any decision is taken.
6215fn census_block(levels: &[i32], _scaled: &[f32], side: usize, coded: usize, bits: f64) {
6216 let scan = scan_of(coded);
6217 let at = |p: u16| levels[usize::from(p) / coded * side + usize::from(p) % coded];
6218 let nonzero = scan.iter().filter(|&&p| at(p) != 0).count();
6219 let ones = scan.iter().filter(|&&p| at(p).abs() == 1).count();
6220 let trailing = scan
6221 .iter()
6222 .rev()
6223 .skip_while(|&&p| at(p) == 0)
6224 .take_while(|&&p| at(p).abs() == 1)
6225 .count();
6226 RDOQ_STATS[0].fetch_add(1, Ordering::Relaxed);
6227 RDOQ_STATS[1].fetch_add(nonzero as u64, Ordering::Relaxed);
6228 RDOQ_STATS[2].fetch_add(ones as u64, Ordering::Relaxed);
6229 RDOQ_STATS[3].fetch_add(trailing as u64, Ordering::Relaxed);
6230 RDOQ_STATS[7].fetch_add((bits * 64.0) as u64, Ordering::Relaxed);
6231}
6232
6233/// Reads and clears [`RDOQ_STATS`].
6234pub fn take_rdoq_stats() -> [u64; 8] {
6235 std::array::from_fn(|i| RDOQ_STATS[i].swap(0, Ordering::Relaxed))
6236}
6237
6238thread_local! {
6239 /// The default tables every price falls back to, one pristine/scratch
6240 /// pair per q-context (see [`coeff_bits`] for why the pair is kept).
6241 static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
6242 const { RefCell::new([None, None, None, None]) };
6243 /// The tables the frame being searched will really be written against,
6244 /// armed per frame by the encoder ([`arm_pricing_cdfs`]) on every thread
6245 /// that prices -- the search jobs re-arm their own worker, exactly like
6246 /// the other tile thread-locals.
6247 static PRICING_BASE: RefCell<Option<Box<(Cdfs, Cdfs)>>> = const { RefCell::new(None) };
6248}
6249
6250/// Arms the tables [`coeff_bits`] prices against on this thread: the state
6251/// this frame's tile writer starts from. `None` goes back to the per-q-context
6252/// defaults (a key frame, whose writer really does start there), and so does
6253/// any frame the screen detector said yes to (`screen`).
6254///
6255/// ON by default for non-screen frames since lane-av1price2;
6256/// `EC_AV1_PRICE_FRAME_CDFS` selects 0 = never (the pre-lane behaviour),
6257/// 1 = always, unset/2 = the screen-gated default.
6258///
6259/// Pricing against the frame's REAL starting tables is the more accurate
6260/// estimate by measurement -- the pricer census
6261/// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every
6262/// transform block, and the one- and two-coefficient inter blocks the search
6263/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy only
6264/// converts into ladder bytes on camera content. Measured on ONE build
6265/// (lane-av1price2, mode 0 vs mode 2), BD-rate vs libaom / vs rav1e:
6266///
6267/// | clip | 640x384 base | 640x384 gated | native base | native gated |
6268/// |---|---|---|---|---|
6269/// | film 1080p | +79.9 / +37.3 | +78.8 / +36.1 | +18.7 / +1.4 | +18.0 / +0.7 |
6270/// | film 2160p | +94.6 / +55.7 | +95.1 / +56.4 | +48.1 / +19.8 | +47.3 / +19.2 |
6271/// | screen | +54.5 / +1.1 | +54.5 / +1.1 | +59.4 / -10.0 | +59.4 / -10.0 |
6272///
6273/// The screen rows are not merely close, they are byte-identical (the ladders
6274/// print 8832/13507/18772/24754 and 39312/52829/70719/92134 in both modes):
6275/// the gate is per frame and the detector fires on 48 of 48 screen frames, so
6276/// no screen frame is ever armed with anything but the defaults. At native
6277/// resolution -- the resolution his library is in -- both films come down
6278/// against both references and the screen capture is flat, which is this
6279/// lane's keep rule. At the downscaled 640x384 gate the 2160p film goes the
6280/// other way (+0.5/+0.7) while the 1080p one comes down further (-1.1/-1.2);
6281/// the downscale is the same recipe that exaggerated the frame pyramid's loss
6282/// sixfold, so the native table decides and the 640x384 2160p regression is
6283/// recorded here rather than argued away.
6284///
6285/// Why the screen capture needs the gate at all is in the census
6286/// (`pricer_error_census_on_clips`, 6 frames of each clip at 640x384, q=100).
6287/// Real tables take the film clip's total pricer error from +7.8% to +5.3%
6288/// and flatten its inter classes outright (Luma8Inter/Luma16Inter/Luma32Inter
6289/// 1-coefficient rows from +11.7%/+17.4%/+24.9% to -0.3%/-5.5%/+8.8%). On the
6290/// screen capture the total only moves +12.8% -> +10.3%, because the classes
6291/// that dominate a screen frame are not the ones the tables fix: its chroma
6292/// stays over-priced (Chroma8 nz=1 +32.2% -> +31.8%, nz=2 +26.2% -> +26.2%,
6293/// unmoved) and its all-zero blocks stay hugely UNDER-priced (Chroma8 nz=0
6294/// -73.0% -> -73.0%, Luma4 nz=0 +464% -> +467% -- both a pricer that assumes
6295/// `skip_ctx` 0, not a table set). So on screen the change makes the inter
6296/// luma price accurate while leaving the bigger chroma and all-zero errors
6297/// exactly where they were, which SKEWS the search's tradeoffs between them
6298/// instead of correcting them -- and the bytes get worse. The fix for that
6299/// row was the neighbour skip context, not another table set, and
6300/// lane-av1skipctx landed it (see [`coeff_bits`]): with the real contexts
6301/// under every price the screen capture comes down +59.4 -> +58.3 vs libaom
6302/// at native, still with every one of its frames armed with the defaults.
6303pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {
6304 static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
6305 let mode = *MODE.get_or_init(
6306 || match std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() {
6307 Ok("0") => 0,
6308 Ok("1") => 1,
6309 _ => 2,
6310 },
6311 );
6312 let on = match mode {
6313 0 => false,
6314 1 => true,
6315 _ => !screen,
6316 };
6317 PRICING_HITS[usize::from(on && base.is_some())].fetch_add(1, Ordering::Relaxed);
6318 PRICING_BASE.with_borrow_mut(|slot| {
6319 *slot = base
6320 .filter(|_| on)
6321 .map(|c| Box::new((c.clone(), c.clone())));
6322 });
6323}
6324
6325/// How many times a frame's search was armed with the DEFAULT tables and how
6326/// many with the frame's REAL starting tables ([`arm_pricing_cdfs`]), so a
6327/// gate can print which side of the screen gate every frame landed on. Counts
6328/// arming calls, not frames: a multi-tile frame arms one worker per tile.
6329pub(crate) static PRICING_HITS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)];
6330
6331/// Reads and clears [`PRICING_HITS`]: (default-table armings, real-table
6332/// armings).
6333#[cfg(test)]
6334pub(crate) fn take_pricing_hits() -> (usize, usize) {
6335 (
6336 PRICING_HITS[0].swap(0, Ordering::Relaxed),
6337 PRICING_HITS[1].swap(0, Ordering::Relaxed),
6338 )
6339}
6340
6341/// The pricer census (`pricer_census_on`): for every transform block the tile
6342/// writer really codes, the bits it spent against the bits [`coeff_bits`]
6343/// prices those very levels at -- the search's rate term measured against the
6344/// rate it is meant to predict. Keyed by (table set, non-zero bucket) so a
6345/// class that is systematically mispriced (all-zero blocks' `txb_skip`, the
6346/// eob of a one-coefficient block, a whole size) shows up on its own row
6347/// rather than inside one average.
6348/// Thread-local, so a census cannot pick up the blocks of another test's
6349/// encode running beside it; a multi-tile, multi-threaded encode would
6350/// therefore only census the tiles this thread wrote, which is every tile of
6351/// the one-tile-one-thread encodes the gates print it from.
6352#[cfg(test)]
6353type CensusRows = BTreeMap<(String, usize), (u64, f64, f64)>;
6354#[cfg(test)]
6355thread_local! {
6356 static CENSUS: RefCell<Option<CensusRows>> = const { RefCell::new(None) };
6357}
6358
6359/// Starts a census on this thread, discarding anything a previous one left.
6360#[cfg(test)]
6361pub(crate) fn pricer_census_on() {
6362 CENSUS.with_borrow_mut(|c| *c = Some(BTreeMap::new()));
6363}
6364
6365/// Stops the census and hands back its rows: (set, non-zero bucket) ->
6366/// (blocks, priced bits, written bits).
6367#[cfg(test)]
6368pub(crate) fn take_pricer_census() -> CensusRows {
6369 CENSUS.with_borrow_mut(|c| c.take()).unwrap_or_default()
6370}
6371
6372/// The label of a non-zero bucket, for the tables the gates print.
6373#[cfg(test)]
6374pub(crate) fn census_bucket_label(bucket: usize) -> &'static str {
6375 ["0", "1", "2", "3-4", "5-8", "9-16", "17+"][bucket]
6376}
6377
6378#[cfg(test)]
6379fn census_record(
6380 set: TxbSet,
6381 q_ctx: usize,
6382 grid: &[i32],
6383 written: f64,
6384 // The writer's own neighbour contexts for this very transform block: the
6385 // census prices the search's estimate the way the search now takes it
6386 // (lane-av1skipctx), so a row's error is the table/adaptation drift that
6387 // is left once the context is right.
6388 skip_ctx: usize,
6389 sign_ctx: usize,
6390) {
6391 if CENSUS.with_borrow(|c| c.is_none()) {
6392 return;
6393 }
6394 let nz = grid.iter().filter(|&&l| l != 0).count();
6395 let bucket = match nz {
6396 0 => 0,
6397 1 => 1,
6398 2 => 2,
6399 3..=4 => 3,
6400 5..=8 => 4,
6401 9..=16 => 5,
6402 _ => 6,
6403 };
6404 let priced = coeff_bits(grid, set, q_ctx, skip_ctx, sign_ctx);
6405 CENSUS.with_borrow_mut(|rows| {
6406 let rows = rows.as_mut().expect("the census is on");
6407 let row = rows.entry((format!("{set:?}"), bucket)).or_default();
6408 row.0 += 1;
6409 row.1 += priced;
6410 row.2 += written;
6411 });
6412}
6413
6414/// What the partition symbol of a block of `side` samples costs, in bits, when
6415/// it says the block is split (or that it is not).
6416///
6417/// The price is taken at context zero — a block whose neighbours are no finer
6418/// than it is — because the search that reads it runs before the tile knows
6419/// what its neighbours will be.
6420pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
6421 // Read-only, and the same tables every call: built once (see
6422 // [`coeff_bits`] for why that matters here).
6423 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
6424 let cdfs = &*CDFS;
6425 let cdf: &[u16] = match side {
6426 // lane-b128: the 128 superblock root's own eight-symbol alphabet.
6427 128 => &cdfs.partition_w128[0],
6428 SB => &cdfs.partition_w64[0],
6429 BLOCK => &cdfs.partition_w32[0],
6430 TX8 => &cdfs.partition_w8[0],
6431 _ => &cdfs.partition_w16[0],
6432 };
6433 let symbol = if split {
6434 PARTITION_SPLIT
6435 } else {
6436 PARTITION_NONE
6437 };
6438 crate::encode::symbol_bits(cdf, symbol)
6439}
6440
6441/// lane-b128hv: [`partition_bits`] for any partition symbol, at the same
6442/// fixed (round-2) tables -- what the 128 root's HORZ/VERT candidate is priced
6443/// with (`PARTITION_HORZ` = 1, `PARTITION_VERT` = 2).
6444pub(crate) fn partition_bits_sym(side: usize, symbol: usize) -> f64 {
6445 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
6446 let cdfs = &*CDFS;
6447 let cdf: &[u16] = match side {
6448 128 => &cdfs.partition_w128[0],
6449 SB => &cdfs.partition_w64[0],
6450 BLOCK => &cdfs.partition_w32[0],
6451 TX8 => &cdfs.partition_w8[0],
6452 _ => &cdfs.partition_w16[0],
6453 };
6454 crate::encode::symbol_bits(cdf, symbol)
6455}
6456
6457/// coeffs() for one plane's transform block of any coefficients the base and
6458/// base-range syntax reach (spec 5.11.39).
6459///
6460/// A 16x16 luma transform codes which transform type it is, because its set
6461/// holds more than one; 32x32 and 64x64 are DCT-only by spec 5.11.40. The
6462/// levels the contexts below are read from are the levels of
6463/// coefficients later in the scan, which a decoder walking the scan backwards
6464/// already has.
6465#[allow(clippy::too_many_arguments)]
6466fn write_coeffs(
6467 enc: &mut SymbolEncoder,
6468 coding: &mut TxbTables,
6469 grid: &[i32],
6470 scan: &[u16],
6471 skip_ctx: usize,
6472 sign_ctx: usize,
6473 plane: Option<usize>,
6474 // Which transform type these levels were produced with (lane-txset).
6475 // Only a luma set whose alphabet holds more than one type codes it;
6476 // chroma never codes a `tx_type` symbol at all.
6477 tx_type: TxType,
6478) {
6479 if let Some(plane) = plane {
6480 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));
6481 }
6482 let side = coding.side;
6483 // lane-txw ROOT CAUSE: this writer used to code every transform unit as
6484 // `TX_CLASS_2D` -- default zigzag scan, the 2D `eob_pt` table and the 2D
6485 // neighbour taps -- while the decoder resolves `V_DCT`/`H_DCT` to
6486 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`decode::TxClass::of`), which read
6487 // their own scan (`class_scan_table`), their own `eob_pt` row
6488 // (`eob_pt_class1`) and their own context offsets. So the first 1-D type
6489 // the search ever offered (the wider `reduced_tx_set == 0` alphabets)
6490 // desynced the tile from its own trial decode. The class is a property of
6491 // the type alone, so it is resolved here, once per unit, exactly as the
6492 // reader does it.
6493 let class = crate::decode::TxClass::of(tx_type);
6494 let scan: &[u16] = if class == crate::decode::TxClass::TwoD {
6495 scan
6496 } else {
6497 class_scan_of(side, class)
6498 };
6499 // The scan-order search reads the grid in scan order, one dependent load
6500 // per position, and an all-zero block makes it walk every one of them --
6501 // which the pricer does for candidate after candidate. A straight-line
6502 // pass settles that case first: it vectorises, and a block that codes
6503 // anything at all almost always codes its DC, so it stops at the first
6504 // element.
6505 let eob = if grid.iter().all(|&level| level == 0) {
6506 0
6507 } else {
6508 scan.iter()
6509 .rposition(|&pos| grid[pos as usize] != 0)
6510 .map_or(0, |i| i + 1)
6511 };
6512 enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]);
6513 if plane.is_some() {
6514 ec_rng_trace(|| {
6515 format!(
6516 "EC_TXBSKIP ctx={skip_ctx} eob0={} tell={} rng={}",
6517 usize::from(eob == 0),
6518 enc.tell(),
6519 enc.rng()
6520 )
6521 });
6522 }
6523 if eob == 0 {
6524 return;
6525 }
6526 // A luma transform whose type set holds more than one type codes which it
6527 // is, right after the all-zero flag (spec 5.11.39). The writer only ever
6528 // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.
6529 if let Some(cdf) = coding.tx_type.as_deref_mut() {
6530 // The symbol comes from the DECODER's own map, keyed by this set's
6531 // alphabet width, so a type this set cannot express is caught here
6532 // rather than desyncing the tile. The search only ever offers types
6533 // the set holds ([`crate::encode::tx_type_candidates`]).
6534 let symbol = crate::decode::tx_type_symbol(cdf.len(), tx_type);
6535 debug_assert!(
6536 symbol.is_some(),
6537 "{tx_type:?} is not in the {}-symbol tx_type set",
6538 cdf.len() - 1
6539 );
6540 enc.symbol(symbol.unwrap_or(TX_TYPE_DCT_DCT_SET2), cdf);
6541 if plane.is_some() {
6542 ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng()));
6543 }
6544 }
6545
6546 write_eob(enc, coding, eob, plane, class);
6547
6548 // lane-av1speed3: `side` is 4, 8, 16 or 32, but it is a runtime value --
6549 // `pos / side` compiles to a real integer division, once per coefficient,
6550 // in the encoder's largest self-time symbol. Same row and column.
6551 debug_assert!(
6552 side.is_power_of_two(),
6553 "the scan splits a position by shifting"
6554 );
6555 let (shift, mask) = (side.trailing_zeros(), side - 1);
6556 for scan_idx in (0..eob).rev() {
6557 let pos = scan[scan_idx] as usize;
6558 let (row, col) = (pos >> shift, pos & mask);
6559 let level = grid[pos].abs();
6560 if scan_idx == eob - 1 {
6561 let ctx = eob_coeff_ctx(scan_idx, side * side);
6562 let sym = (level.min(NUM_BASE_LEVELS + 1) - 1) as usize;
6563 enc.symbol(sym, &mut coding.base_eob[ctx]);
6564 if plane.is_some() {
6565 ec_rng_trace(|| {
6566 format!(
6567 "EC_BASEEOB scan_idx={scan_idx} ctx={ctx} level={} tell={}",
6568 sym + 1,
6569 enc.tell()
6570 )
6571 });
6572 }
6573 } else {
6574 let ctx = base_ctx(grid, side, row, col, class);
6575 let sym = level.min(NUM_BASE_LEVELS + 1) as usize;
6576 enc.symbol(sym, &mut coding.base[ctx]);
6577 if plane.is_some() {
6578 ec_rng_trace(|| {
6579 format!(
6580 "EC_BASE scan_idx={scan_idx} ctx={ctx} level={sym} tell={}",
6581 enc.tell()
6582 )
6583 });
6584 }
6585 }
6586 if level > NUM_BASE_LEVELS {
6587 let ctx = br_ctx(grid, side, row, col, class);
6588 let mut remaining = level - (NUM_BASE_LEVELS + 1);
6589 let mut sent = 0;
6590 while sent < COEFF_BASE_RANGE {
6591 let k = remaining.min(BR_STEP);
6592 enc.symbol(k as usize, &mut coding.br[ctx]);
6593 if plane.is_some() {
6594 ec_rng_trace(|| {
6595 format!(
6596 "EC_BR scan_idx={scan_idx} ctx={ctx} k={k} tell={}",
6597 enc.tell()
6598 )
6599 });
6600 }
6601 if k < BR_STEP {
6602 break;
6603 }
6604 remaining -= k;
6605 sent += BR_STEP;
6606 }
6607 }
6608 }
6609
6610 // The signs come after the levels, in scan order, the DC's from a CDF and
6611 // the rest as raw bits (spec 5.11.39).
6612 for &pos in &scan[..eob] {
6613 let level = grid[pos as usize];
6614 if level == 0 {
6615 continue;
6616 }
6617 if pos == 0 {
6618 enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]);
6619 if plane.is_some() {
6620 ec_rng_trace(|| {
6621 format!(
6622 "EC_DCSIGN ctx={sign_ctx} neg={} tell={}",
6623 usize::from(level < 0),
6624 enc.tell()
6625 )
6626 });
6627 }
6628 } else {
6629 enc.literal(u32::from(level < 0), 1);
6630 }
6631 // A level the base and base-range syntax cannot reach carries the rest
6632 // of itself here, after its own sign (spec 5.11.39).
6633 if level.abs() > MAX_BR_LEVEL {
6634 write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32);
6635 if plane.is_some() {
6636 ec_rng_trace(|| format!("EC_GOLOMB tell={}", enc.tell()));
6637 }
6638 }
6639 }
6640 if let Some(plane) = plane {
6641 ec_rng_trace(|| format!("EC_PLANE plane={plane} eob={eob} tell_after={}", enc.tell()));
6642 }
6643}
6644
6645/// The end-of-block position (spec 5.11.39): which group of scan positions the
6646/// last coded coefficient falls in, then its offset inside that group — the
6647/// offset's top bit from a CDF and the rest as raw bits.
6648fn write_eob(
6649 enc: &mut SymbolEncoder,
6650 coding: &mut TxbTables,
6651 eob: usize,
6652 plane: Option<usize>,
6653 class: crate::decode::TxClass,
6654) {
6655 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
6656 /// end-of-block positions covers, indexed by the group's own number.
6657 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
6658 /// `Eob_Offset_Bits` (spec 5.11.39): how wide each group's offset is.
6659 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
6660
6661 let group = GROUP_START
6662 .iter()
6663 .rposition(|&start| start <= eob)
6664 .expect("the first group starts at zero");
6665 // The groups are numbered from one, and how many of them the transform
6666 // reaches is the size of its own end-of-block alphabet. A
6667 // `TX_CLASS_HORIZ`/`TX_CLASS_VERT` unit adapts a wholly separate row
6668 // (libaom's `eob_multi_ctx`), which is what `decode::read_eob` reads.
6669 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
6670 (crate::decode::TxClass::TwoD, _) | (_, None) => coding.eob_pt,
6671 (_, Some(class1)) => class1,
6672 };
6673 enc.symbol(group - 1, eob_pt);
6674 if let Some(plane) = plane {
6675 ec_rng_trace(|| {
6676 format!(
6677 "EC_EOBPT plane={plane} eob_pt={group} tell={} rng={}",
6678 enc.tell(),
6679 enc.rng()
6680 )
6681 });
6682 }
6683
6684 let bits = OFFSET_BITS[group];
6685 if bits > 0 {
6686 let offset = (eob - GROUP_START[group]) as u32;
6687 let top = (offset >> (bits - 1)) & 1;
6688 enc.symbol(top as usize, &mut coding.eob_extra[group - 3]);
6689 if let Some(plane) = plane {
6690 ec_rng_trace(|| {
6691 format!(
6692 "EC_EOBEXTRA plane={plane} eob_ctx={} top={top} tell={}",
6693 group - 3,
6694 enc.tell()
6695 )
6696 });
6697 }
6698 if bits > 1 {
6699 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
6700 if let Some(plane) = plane {
6701 ec_rng_trace(|| {
6702 format!(
6703 "EC_EOBBITS plane={plane} eob_extra={offset} tell={}",
6704 enc.tell()
6705 )
6706 });
6707 }
6708 }
6709 }
6710}
6711
6712/// Writes the remainder of a level the base and base-range syntax could not
6713/// reach (spec 5.11.40): the value plus one, as its bit length in unary
6714/// followed by the value's own bits, most significant first.
6715pub(crate) fn write_golomb(enc: &mut SymbolEncoder, value: u32) {
6716 let x = value + 1;
6717 let length = 32 - x.leading_zeros();
6718 for _ in 0..length - 1 {
6719 enc.literal(0, 1);
6720 }
6721 for i in (0..length).rev() {
6722 enc.literal((x >> i) & 1, 1);
6723 }
6724}
6725
6726/// The context of the level of the last coded coefficient (spec 8.3.2): how
6727/// far into the scan it sits, in quarters and eighths of the transform.
6728fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
6729 match scan_idx {
6730 0 => 0,
6731 i if i <= area / 8 => 1,
6732 i if i <= area / 4 => 2,
6733 _ => 3,
6734 }
6735}
6736
6737/// The context of a coefficient's level (spec 8.3.2): the magnitudes of the
6738/// five neighbours below and to the right of it — the ones a decoder walking
6739/// the scan backwards already has — plus a term for where in the transform it
6740/// sits. The DC reads context 0 whatever its neighbours carry.
6741fn base_ctx(
6742 grid: &[i32],
6743 side: usize,
6744 row: usize,
6745 col: usize,
6746 class: crate::decode::TxClass,
6747) -> usize {
6748 use crate::decode::TxClass;
6749 // Only `TX_CLASS_2D` short-circuits its DC to context 0
6750 // (`get_nz_map_ctx_from_stats`'s `(tx_class | coeff_idx) == 0`); a 1-D
6751 // class runs the DC through the same neighbour sum as every other
6752 // position.
6753 if class == TxClass::TwoD && row == 0 && col == 0 {
6754 return 0;
6755 }
6756 if class != TxClass::TwoD {
6757 let offsets: [(usize, usize); 5] = if class == TxClass::Horiz {
6758 [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)]
6759 } else {
6760 [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)]
6761 };
6762 let mag: i32 = offsets
6763 .iter()
6764 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
6765 .sum();
6766 let along = if class == TxClass::Horiz { col } else { row };
6767 return (((mag + 1) >> 1).min(4) as usize)
6768 + crate::decode::nz_map_ctx_offset_1d(along.min(31));
6769 }
6770 // A coefficient two rows and two columns clear of the far edges reaches
6771 // all five neighbours, so the gather is five loads off one index with no
6772 // per-neighbour edge test -- which is where this writer spends a third of
6773 // its coefficient loop.
6774 let p = row * side + col;
6775 let mag: i32 = if row + 2 < side && col + 2 < side {
6776 [p + side, p + 1, p + side + 1, p + 2 * side, p + 2]
6777 .iter()
6778 .map(|&i| grid[i].abs().min(3))
6779 .sum()
6780 } else {
6781 [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
6782 .iter()
6783 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
6784 .sum()
6785 };
6786 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
6787 (((mag + 1) >> 1).min(4) as usize) + offset
6788}
6789
6790/// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes
6791/// of its three closest neighbours below and to the right, uncapped, and a
6792/// term separating the DC, the corner of the transform, and the rest.
6793fn br_ctx(
6794 grid: &[i32],
6795 side: usize,
6796 row: usize,
6797 col: usize,
6798 class: crate::decode::TxClass,
6799) -> usize {
6800 use crate::decode::TxClass;
6801 if class != TxClass::TwoD {
6802 let extra = if class == TxClass::Horiz {
6803 neighbour(grid, side, row, col + 2)
6804 } else {
6805 neighbour(grid, side, row + 2, col)
6806 };
6807 let mag = neighbour(grid, side, row + 1, col).abs()
6808 + neighbour(grid, side, row, col + 1).abs()
6809 + extra.abs();
6810 let mag = (((mag + 1) >> 1).min(6)) as usize;
6811 if row == 0 && col == 0 {
6812 return mag;
6813 }
6814 let near_origin = if class == TxClass::Horiz {
6815 col == 0
6816 } else {
6817 row == 0
6818 };
6819 return if near_origin { mag + 7 } else { mag + 14 };
6820 }
6821 let p = row * side + col;
6822 let mag: i32 = if row + 1 < side && col + 1 < side {
6823 grid[p + side].abs() + grid[p + 1].abs() + grid[p + side + 1].abs()
6824 } else {
6825 [(1, 0), (0, 1), (1, 1)]
6826 .iter()
6827 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
6828 .sum()
6829 };
6830 let mag = (((mag + 1) >> 1).min(6)) as usize;
6831 if row == 0 && col == 0 {
6832 mag
6833 } else if row < 2 && col < 2 {
6834 mag + 7
6835 } else {
6836 mag + 14
6837 }
6838}
6839
6840/// A level at a position that may fall off the transform, where the levels a
6841/// context reads are zero.
6842fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
6843 if row >= side || col >= side {
6844 0
6845 } else {
6846 grid[row * side + col]
6847 }
6848}
6849
6850/// Shared by both DC writers: one level per block, none of them zero.
6851fn check_levels(levels: &[i32], blocks: usize) -> Result<()> {
6852 if levels.len() != blocks {
6853 return Err(Error::unsupported(
6854 "AV1 tile",
6855 "a DC-only key frame needs one level per coded block",
6856 ));
6857 }
6858 if levels.iter().any(|&l| l == 0 || l.abs() > MAX_BR_LEVEL) {
6859 return Err(Error::unsupported(
6860 "AV1 tile",
6861 "a DC-only key frame is written for levels -14..=14 without zero; \
6862 wider levels need the Golomb tail",
6863 ));
6864 }
6865 Ok(())
6866}
6867
6868/// coeffs() for a luma transform block whose only coefficient is the DC (spec
6869/// 5.11.39). The block size is the transform size, so the all-zero flag's
6870/// context is 0; an end-of-block of one is token 0 of the position alphabet
6871/// with no extra bits; the transform sizes here are all DCT-only, so no
6872/// transform type is coded; and the DC's own neighbours are zero, so its
6873/// magnitude contexts are 0 throughout.
6874fn write_dc_coeffs(
6875 enc: &mut SymbolEncoder,
6876 dc_level: i32,
6877 sign_ctx: usize,
6878 q_ctx: usize,
6879 txb_skip: &[u16],
6880 base_eob: &[u16],
6881) {
6882 use crate::cdf_state::pick;
6883 let level = dc_level.abs();
6884 let eob_pt = pick(
6885 q_ctx,
6886 cdf::EOB_PT_1024_LUMA_Q0,
6887 cdf::EOB_PT_1024_LUMA_Q1,
6888 cdf::EOB_PT_1024_LUMA,
6889 cdf::EOB_PT_1024_LUMA_Q3,
6890 );
6891 let br = pick(
6892 q_ctx,
6893 cdf::COEFF_BR_LUMA_32_Q0,
6894 cdf::COEFF_BR_LUMA_32_Q1,
6895 cdf::COEFF_BR_LUMA_32,
6896 cdf::COEFF_BR_LUMA_32_Q3,
6897 );
6898 enc.symbol_fixed(0, txb_skip);
6899 enc.symbol_fixed(0, &eob_pt);
6900 enc.symbol_fixed((level.min(NUM_BASE_LEVELS + 1) - 1) as usize, base_eob);
6901 if level > NUM_BASE_LEVELS {
6902 let mut remaining = level - (NUM_BASE_LEVELS + 1);
6903 let mut sent = 0;
6904 while sent < COEFF_BASE_RANGE {
6905 let k = remaining.min(BR_STEP);
6906 enc.symbol_fixed(k as usize, &br[0]);
6907 if k < BR_STEP {
6908 break;
6909 }
6910 remaining -= k;
6911 sent += BR_STEP;
6912 }
6913 }
6914 // The signs come after the levels, DC first (spec 5.11.39).
6915 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
6916}
6917
6918/// One 4x4 unit's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for a
6919/// positive DC, minus one for a negative one, nothing for a unit whose block
6920/// carried no DC or that sits past the frame's true edge (spec
6921/// `av1_set_entropy_contexts`), which is why the vote is gathered per 4x4
6922/// unit and not per coded cell -- a unit past the edge does not vote even
6923/// when the rest of its cell does.
6924fn dc_vote(dc: Option<bool>) -> i32 {
6925 match dc {
6926 None => 0,
6927 Some(true) => -1,
6928 Some(false) => 1,
6929 }
6930}
6931
6932/// Which of the three DC sign contexts a gathered vote picks.
6933fn dc_sign_ctx(vote: i32) -> usize {
6934 match vote.signum() {
6935 0 => 0,
6936 -1 => 1,
6937 _ => 2,
6938 }
6939}
6940
6941/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`,
6942/// `pred_common.c`): both neighbours' intra/inter state when both are
6943/// available, one neighbour's when only one is, and zero at a tile's own
6944/// top-left corner.
6945pub(crate) fn intra_inter_ctx(
6946 has_above: bool,
6947 has_left: bool,
6948 above_inter: bool,
6949 left_inter: bool,
6950) -> usize {
6951 match (has_above, has_left) {
6952 (true, true) => {
6953 let (above_intra, left_intra) = (!above_inter, !left_inter);
6954 if above_intra && left_intra {
6955 3
6956 } else {
6957 usize::from(above_intra || left_intra)
6958 }
6959 }
6960 (true, false) => 2 * usize::from(!above_inter),
6961 (false, true) => 2 * usize::from(!left_inter),
6962 (false, false) => 0,
6963 }
6964}
6965
6966/// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`
6967/// component's own bits start counting from; class zero starts at zero.
6968fn mv_class_base(class: usize) -> i32 {
6969 if class == 0 {
6970 0
6971 } else {
6972 2i32 << (class + 2)
6973 }
6974}
6975
6976/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse
6977/// of `mv_class_base`'s doubling ranges, ported from libaom's
6978/// `av1_get_mv_class` (`mv.h`).
6979fn mv_class_of(z: i32) -> usize {
6980 let mut class = 0;
6981 while class < 10 && mv_class_base(class + 1) <= z {
6982 class += 1;
6983 }
6984 class
6985}
6986
6987/// Writes one motion vector component's non-zero diff (spec 5.11.32
6988/// `read_mv_component`, run backwards): sign, class, then the class's own
6989/// bits, and (lane-hpmv) the eighth-pel bit when the frame armed through
6990/// [`arm_high_precision_mv`] carries `allow_high_precision_mv`. Without that
6991/// flag the eighth-pel bit is inferred as one rather than coded, so only
6992/// diffs whose eighth-pel bit really is one are representable; anything else
6993/// is refused rather than rounded, since rounding would silently code a
6994/// different vector than the caller asked for.
6995///
6996/// # Errors
6997/// Returns an error when `diff` needs eighth-pel precision in a frame coded
6998/// without `allow_high_precision_mv`.
6999fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
7000 debug_assert_ne!(diff, 0);
7001 let hp_frame = high_precision_mv();
7002 let sign = diff < 0;
7003 enc.symbol(usize::from(sign), &mut c.sign);
7004 let mag = diff.unsigned_abs() as i32;
7005 let z = mag - 1;
7006 if !hp_frame && z & 1 == 0 {
7007 return Err(Error::unsupported(
7008 "AV1 tile",
7009 "a motion vector component needs eighth-pel precision, which \
7010 allow_high_precision_mv off does not carry",
7011 ));
7012 }
7013 let class = mv_class_of(z);
7014 enc.symbol(class, &mut c.class);
7015 let local = z - mv_class_base(class);
7016 let hp = (local & 1) as usize;
7017 if class == 0 {
7018 let bit = (local >> 3) & 1;
7019 let fr = (local >> 1) & 3;
7020 enc.symbol(bit as usize, &mut c.class0_bit);
7021 enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]);
7022 // spec 5.11.32: the eighth-pel bit is CODED when the frame allows
7023 // high-precision motion vectors, and inferred as one otherwise ("if
7024 // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
7025 if hp_frame {
7026 enc.symbol(hp, &mut c.class0_hp);
7027 }
7028 } else {
7029 let d = local >> 3;
7030 let fr = (local >> 1) & 3;
7031 for i in 0..class {
7032 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
7033 }
7034 enc.symbol(fr as usize, &mut c.fr);
7035 if hp_frame {
7036 enc.symbol(hp, &mut c.hp);
7037 }
7038 }
7039 if hp_frame {
7040 HP_SYMBOLS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7041 if hp == 0 {
7042 HP_SYMBOLS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7043 }
7044 }
7045 Ok(())
7046}
7047
7048/// Writes a motion vector as a residual against `pred` (spec 5.11.32
7049/// `read_mv`): the joint symbol naming which components differ, then each
7050/// differing component.
7051fn write_mv(
7052 enc: &mut SymbolEncoder,
7053 mv_comp: &mut [MvComponentCdfs; 2],
7054 mv_joint: &mut [u16; 5],
7055 mv: (i32, i32),
7056 pred: (i32, i32),
7057) -> Result<()> {
7058 let diff = (mv.0 - pred.0, mv.1 - pred.1);
7059 let joint = match (diff.0 != 0, diff.1 != 0) {
7060 (false, false) => 0, // MV_JOINT_ZERO
7061 (false, true) => 1, // MV_JOINT_HNZVZ: column only
7062 (true, false) => 2, // MV_JOINT_HZVNZ: row only
7063 (true, true) => 3, // MV_JOINT_HNZVNZ
7064 };
7065 enc.symbol(joint, mv_joint);
7066 if diff.0 != 0 {
7067 write_mv_component(enc, &mut mv_comp[0], diff.0)?;
7068 }
7069 if diff.1 != 0 {
7070 write_mv_component(enc, &mut mv_comp[1], diff.1)?;
7071 }
7072 Ok(())
7073}
7074
7075/// What a block leaves in the neighbour reference bands: its own reference,
7076/// or `-1` when it is intra (decode.rs `Neighbours::above_ref`'s convention).
7077fn block_ref(block: &BlockCoeffs) -> i8 {
7078 block.inter.map_or(-1, |i| i.ref_frame)
7079}
7080
7081/// Writer-side counterpart of decode.rs `read_single_ref` (spec 5.11.25's
7082/// `single_ref_p1`..`p6` tree): codes `ref_frame` bit by bit, each symbol at
7083/// the context its own `single_ref_p*_ctx` derives from the immediate
7084/// above/left neighbours' references -- the same functions the decoder calls,
7085/// with `-1` standing for an intra or unavailable neighbour and no second
7086/// reference (this writer codes no compound block).
7087fn write_single_ref(
7088 enc: &mut SymbolEncoder,
7089 cdfs: &mut Cdfs,
7090 ref_frame: i8,
7091 above_ref: i8,
7092 above_ref1: Option<i8>,
7093 left_ref: i8,
7094 left_ref1: Option<i8>,
7095) {
7096 REF_HITS[(ref_frame.max(1) - 1) as usize % 7]
7097 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7098 use crate::mvstack::{
7099 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
7100 single_ref_p5_ctx, single_ref_p6_ctx, ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME,
7101 GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
7102 };
7103 let above = (above_ref > 0).then_some(above_ref);
7104 let left = (left_ref > 0).then_some(left_ref);
7105 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
7106 // neighbour's references (decode.rs `read_single_ref`'s own
7107 // `above_ref1`/`left_ref1`): dropping the second one reads a different
7108 // context row for every block sitting under a compound neighbour, and so
7109 // decodes a different reference NAME.
7110 let backward = ref_frame >= BWDREF_FRAME;
7111 enc.symbol(
7112 usize::from(backward),
7113 &mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0],
7114 );
7115 if backward {
7116 let is_altref = ref_frame == ALTREF_FRAME;
7117 enc.symbol(
7118 usize::from(is_altref),
7119 &mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1],
7120 );
7121 if !is_altref {
7122 enc.symbol(
7123 usize::from(ref_frame == ALTREF2_FRAME),
7124 &mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5],
7125 );
7126 }
7127 return;
7128 }
7129 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
7130 enc.symbol(
7131 usize::from(far),
7132 &mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2],
7133 );
7134 if far {
7135 enc.symbol(
7136 usize::from(ref_frame == GOLDEN_FRAME),
7137 &mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4],
7138 );
7139 } else {
7140 enc.symbol(
7141 usize::from(ref_frame == LAST2_FRAME),
7142 &mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3],
7143 );
7144 }
7145}
7146
7147/// Per-mode fire counts of [`write_inter_mode`], indexed
7148/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block
7149/// coded (bucket 3 collects any index past 2). Read by the BD gate, which
7150/// is the only thing that proves a newly added mode ever fires
7151/// (gate-blind-to-feature).
7152static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [
7153 std::sync::atomic::AtomicUsize::new(0),
7154 std::sync::atomic::AtomicUsize::new(0),
7155 std::sync::atomic::AtomicUsize::new(0),
7156 std::sync::atomic::AtomicUsize::new(0),
7157];
7158static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [
7159 std::sync::atomic::AtomicUsize::new(0),
7160 std::sync::atomic::AtomicUsize::new(0),
7161 std::sync::atomic::AtomicUsize::new(0),
7162 std::sync::atomic::AtomicUsize::new(0),
7163];
7164
7165/// One counter per reference name (`LAST`..`ALTREF`), for the gate's own
7166/// census of what the encoder actually picks.
7167static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [
7168 std::sync::atomic::AtomicUsize::new(0),
7169 std::sync::atomic::AtomicUsize::new(0),
7170 std::sync::atomic::AtomicUsize::new(0),
7171 std::sync::atomic::AtomicUsize::new(0),
7172 std::sync::atomic::AtomicUsize::new(0),
7173 std::sync::atomic::AtomicUsize::new(0),
7174 std::sync::atomic::AtomicUsize::new(0),
7175];
7176
7177/// Takes and clears the per-reference histogram.
7178#[cfg(test)]
7179pub(crate) fn take_ref_hits() -> [usize; 7] {
7180 std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7181}
7182
7183/// Bumps the two histograms for one coded inter block.
7184/// How many blocks this process wrote whose search-chosen `ref_mv_idx` the
7185/// write-time stack could not carry, so the writer signalled a SMALLER index
7186/// (lane-sb128b). Every one of these used to price its residual against a
7187/// predictor the decoder never derives.
7188static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7189
7190/// Counts one clamped DRL index whose predictor differs from the one the
7191/// search asked for -- the harmful case, and the only one a witness can see.
7192fn note_drl_clamp(target: usize, signalled: usize, entries: usize) {
7193 DRL_CLAMP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7194 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7195 eprintln!("DRL_CLAMP target={target} signalled={signalled} entries={entries}");
7196 }
7197}
7198
7199/// Takes and clears [`DRL_CLAMP_HITS`], for a gate's own before/after delta.
7200#[cfg(test)]
7201pub(crate) fn take_drl_clamp_hits() -> usize {
7202 DRL_CLAMP_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
7203}
7204
7205fn note_inter_mode(mode: usize, drl: usize) {
7206 INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7207 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7208}
7209
7210/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW).
7211#[cfg(test)]
7212pub(crate) fn take_inter_mode_hits() -> [usize; 4] {
7213 [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7214}
7215
7216/// Takes and clears the DRL-index histogram (0, 1, 2, 3+).
7217#[cfg(test)]
7218pub(crate) fn take_drl_hits() -> [usize; 4] {
7219 [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7220}
7221
7222/// Writes the DRL index of one block: the loop the decoder runs (spec
7223/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
7224/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
7225/// stop, at most two bits. `drl_ctx[idx]` is the context between
7226/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses
7227/// between. Returns the index the symbols actually SIGNAL, which is `target`
7228/// clamped by the stack (`min(target, start + 2, entries.len() - 1)`): the
7229/// decoder derives its predictor from THAT index, so every caller must take
7230/// its own base MV from the returned value and not from `target` (lane-sb128b:
7231/// a search-chosen `ref_mv_idx` of 2 against a two-entry write-time stack
7232/// signalled index 1 and priced the residual against `pred_mv`, and the
7233/// decoder's MV silently drifted a whole frame before the drl symbols
7234/// desynced).
7235/// The DRL index [`write_drl_idx`]'s walk can actually SIGNAL against a stack
7236/// of `entries` candidates: at most two `drl_mode` symbols past `start`, and
7237/// each one needs a further entry to advance into (spec 5.11.24's
7238/// `for (idx = 0; idx < 2; idx++) if (NumMvFound > idx + 1)`).
7239///
7240/// A search that offers an index this clamps prices its residual against a
7241/// predictor the decoder never derives (lane-sb128b's silent MV drift); the
7242/// pricer's own offer set is enumerated against this rule by
7243/// `crate::encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`.
7244pub(crate) fn signalled_drl_idx(entries: usize, start: usize, target: usize) -> usize {
7245 target
7246 .min(start + 2)
7247 .min(entries.saturating_sub(1))
7248 .max(start)
7249}
7250
7251fn write_drl_idx(
7252 enc: &mut SymbolEncoder,
7253 cdfs: &mut Cdfs,
7254 stack: &crate::mvstack::MvStack,
7255 start: usize,
7256 target: usize,
7257) -> usize {
7258 debug_assert_eq!(
7259 signalled_drl_idx(stack.entries.len(), start, target),
7260 {
7261 let mut i = start;
7262 while i < start + 2 && stack.entries.len() > i + 1 && i < target {
7263 i += 1;
7264 }
7265 i
7266 },
7267 "the drl clamp rule and the writer's own walk disagree",
7268 );
7269 let mut idx = start;
7270 while idx < start + 2 && stack.entries.len() > idx + 1 {
7271 let advance = idx < target;
7272 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]);
7273 if !advance {
7274 return idx;
7275 }
7276 idx += 1;
7277 }
7278 idx
7279}
7280
7281/// Writer-side counterpart of the decoder's single-reference
7282/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s
7283/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV
7284/// residual against the DRL-selected predictor. Returns the motion vector
7285/// the decoder will derive for the block (what the MI grid must record) and
7286/// whether it is `NEWMV`.
7287///
7288/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global
7289/// motion parameters at all, so every `gm_get_motion_vector` the decoder
7290/// runs is the identity model's zero vector; a lane that starts writing
7291/// real `gm_params` has to feed the same vector in here.
7292///
7293/// # Errors
7294/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision.
7295fn write_inter_mode(
7296 enc: &mut SymbolEncoder,
7297 cdfs: &mut Cdfs,
7298 info: InterInfo,
7299 stack: &crate::mvstack::MvStack,
7300) -> Result<((i32, i32), bool)> {
7301 let idx = usize::from(info.ref_mv_idx);
7302 if info.mode.compound_index().is_some() {
7303 return Err(Error::unsupported(
7304 "AV1 tile",
7305 "a compound mode is written by `write_compound_block`, not here",
7306 ));
7307 }
7308 match info.mode {
7309 InterMode::NewMv => {
7310 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
7311 let signalled = write_drl_idx(enc, cdfs, stack, 0, idx);
7312 let base = stack.entries.get(signalled).map_or(stack.pred_mv, |e| e.mv);
7313 if signalled != idx && base != stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv) {
7314 note_drl_clamp(idx, signalled, stack.entries.len());
7315 }
7316 let idx = signalled;
7317 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?;
7318 note_inter_mode(3, idx);
7319 Ok((info.mv, true))
7320 }
7321 InterMode::GlobalMv => {
7322 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7323 enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV
7324 note_inter_mode(2, 0);
7325 Ok(((0, 0), false))
7326 }
7327 InterMode::NearestMv => {
7328 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7329 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
7330 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
7331 note_inter_mode(0, 0);
7332 Ok((stack.nearest_mv, false))
7333 }
7334 InterMode::NearMv => {
7335 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7336 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
7337 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV
7338 // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24).
7339 let idx = idx.max(1);
7340 let signalled = write_drl_idx(enc, cdfs, stack, 1, idx);
7341 let mv = stack.entries.get(signalled).map_or(stack.near_mv, |e| e.mv);
7342 if signalled != idx && mv != stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) {
7343 note_drl_clamp(idx, signalled, stack.entries.len());
7344 }
7345 let idx = signalled;
7346 note_inter_mode(1, idx);
7347 Ok((mv, false))
7348 }
7349 _ => unreachable!("compound modes are refused above"),
7350 }
7351}
7352
7353/// Writes the payload of a one-tile inter frame built from `blocks`, one
7354/// 32x32 block per entry in raster order across the frame — every superblock
7355/// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
7356/// codes a key frame, because a mixed-size partition tree buys this writer's
7357/// gate nothing a flat grid does not already prove: the CDF state, the
7358/// neighbour contexts and the single-reference/MV-stack machinery below are
7359/// exactly as size-sensitive whether the tree recurses or not, and recursing
7360/// it would be undirected scaffolding — see `sb_coeff_key_frame_tile` for
7361/// where that tree already lives, ready to graft this block's mode reads
7362/// onto once a real partition search needs it.
7363///
7364/// A block whose [`BlockCoeffs::inter`] is `Some` is coded inter: `skip`,
7365/// then `is_inter`, then a single-reference chain that always names `LAST`
7366/// (spec 5.11.25 `single_ref_p1`/`p3`/`p4`, this crate's only reference so
7367/// far), then the two-mode `read_inter_mode` chain (spec 5.11.24) and, for
7368/// [`InterMode::NewMv`], a DRL index (always zero) and a coded motion vector
7369/// residual. A block whose `inter` is `None` codes intra, through the
7370/// *inter*-frame intra path (spec 5.11.16's `intra_frame_mode_info` is the
7371/// key frame writers' path; this is `inter_frame_mode_info`'s intra branch):
7372/// `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour context, since
7373/// an inter frame's intra blocks do not read their neighbours' modes.
7374///
7375/// # Errors
7376/// Returns an error when the frame is not a whole number of 64x64
7377/// superblocks, when `blocks` does not carry exactly one entry per 32x32
7378/// block, when an intra block names a mode a key frame does not code, when a
7379/// coefficient sits outside its transform or is one the writer cannot code,
7380/// when a `NEWMV` block's motion vector needs eighth-pel precision.
7381pub fn sb_coeff_inter_frame_tile(
7382 mi_cols: u32,
7383 mi_rows: u32,
7384 base_q_idx: u8,
7385 blocks: &[Quadrant],
7386) -> Result<Vec<u8>> {
7387 sb_coeff_inter_frame_tile_tx(mi_cols, mi_rows, base_q_idx, blocks, false)
7388}
7389
7390/// [`sb_coeff_inter_frame_tile`] for a frame header carrying
7391/// `tx_mode == TxMode::Select`: every block then codes the transform syntax
7392/// [`write_tx_syntax_inter`] writes -- one `txfm_split` flag on an inter
7393/// block that carries a residual, a `tx_depth` symbol on an intra one -- and
7394/// an intra block whose depth is nonzero codes its luma as several transform
7395/// units. With `tx_select` false this writes exactly the stream it always did.
7396///
7397/// # Errors
7398/// As [`sb_coeff_inter_frame_tile`].
7399pub fn sb_coeff_inter_frame_tile_tx(
7400 mi_cols: u32,
7401 mi_rows: u32,
7402 base_q_idx: u8,
7403 blocks: &[Quadrant],
7404 tx_select: bool,
7405) -> Result<Vec<u8>> {
7406 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
7407 sb_coeff_inter_frame_tile_cdfs(
7408 mi_cols,
7409 mi_rows,
7410 base_q_idx,
7411 blocks,
7412 tx_select,
7413 &mut cdfs,
7414 TileRect::whole(mi_cols, mi_rows),
7415 &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
7416 )
7417}
7418
7419/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
7420/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`].
7421///
7422/// # Errors
7423/// As [`sb_coeff_inter_frame_tile_tx`].
7424pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
7425 mi_cols: u32,
7426 mi_rows: u32,
7427 _base_q_idx: u8,
7428 blocks: &[Quadrant],
7429 tx_select: bool,
7430 cdfs: &mut Cdfs,
7431 // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
7432 tile: TileRect,
7433 // The frame's MV grid, carried across the frame's tiles by the caller
7434 // (see the comment at `set_tile_bounds` below).
7435 grid: &mut MiGrid,
7436) -> Result<Vec<u8>> {
7437 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
7438 let _cdef_idx = CdefIdxGuard;
7439 check_blocks(mi_cols, mi_rows)?;
7440 // `block_grid`'s ceiling, not a plain division: a true frame size that is
7441 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has
7442 // one more block/superblock whose own origin is inside the true frame,
7443 // same as `sb_coeff_key_frame_tile`.
7444 let (cols, rows) = block_grid(mi_cols, mi_rows);
7445 if blocks.len() != (cols * rows) as usize {
7446 return Err(Error::unsupported(
7447 "AV1 tile",
7448 "an inter frame needs one entry per 32x32 block inside the true frame",
7449 ));
7450 }
7451 let coded: Vec<&BlockCoeffs> = blocks.iter().flat_map(Quadrant::blocks).collect();
7452 if let Some(bad) = coded
7453 .into_iter()
7454 .find(|b| b.inter.is_none() && usize::from(b.mode) >= INTRA_MODES)
7455 {
7456 return Err(Error::unsupported(
7457 "AV1 tile",
7458 format!(
7459 "intra mode {} is not one of the thirteen this writer codes",
7460 bad.mode
7461 ),
7462 ));
7463 }
7464
7465 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only
7466 /// size this writer's inter branch codes.
7467 const SIZE_GROUP_32: usize = 3;
7468
7469 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
7470 let mut neighbours = Neighbours::new(
7471 cols as usize * 2,
7472 rows as usize * 2,
7473 mi_cols as usize,
7474 mi_rows as usize,
7475 );
7476 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
7477 // The MV grid spans the FRAME and carries every tile written before this
7478 // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
7479 // keeps one grid for the whole frame and narrows its read window per
7480 // tile): the tile bounds below are what stops a candidate scan reaching
7481 // across the boundary, and a grid that was merely empty out there would
7482 // not read the same as the decoder's wherever a scan reads the array
7483 // without asking `MiGrid::get` first.
7484 let mut grid = &mut *grid;
7485 grid.set_tile_bounds(
7486 tile.mi_row0 as usize,
7487 tile.mi_col0 as usize,
7488 tile.mi_row1 as usize,
7489 tile.mi_col1 as usize,
7490 );
7491 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
7492 let mut cdfs = cdfs;
7493 let mut enc = SymbolEncoder::new();
7494 // An `is_inter` block's 32x32 luma transform reads a different
7495 // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see
7496 // `TxbSet::Luma32Inter`'s doc comment); chroma's transform type is
7497 // derived from luma's, not coded, so it never differs between the two.
7498 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
7499 let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16];
7500 // A 64x64 root's planes (lane-tx64): TX_64X64 luma -- DCT-only at this
7501 // size for an inter block too (spec `av1_get_ext_tx_set_type` returns
7502 // `TX_SET_DCTONLY` for `tx_size_sqr_up == TX_64X64`), so `Luma64` carries
7503 // no `tx_type` symbol and there is no `Luma64Inter` to write -- and one
7504 // TX_32X32 per chroma plane.
7505 let sb64_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
7506 let scan32 = default_scan(TX32);
7507 let scan16 = default_scan(TX16);
7508 let scan8 = default_scan(TX8);
7509 let scan4 = default_scan(TX4);
7510 // The same four tables again as one array, which is what the per-unit
7511 // luma writer indexes by transform side.
7512 let all_scans = [scan32.clone(), scan16.clone(), scan8.clone(), scan4.clone()];
7513 let zero_grids = [
7514 vec![0i32; TX32 * TX32],
7515 vec![0i32; TX16 * TX16],
7516 vec![0i32; TX16 * TX16],
7517 ];
7518
7519 let sb128 = sb128_armed();
7520 // lane-b128: set at a root whose own `PARTITION_NONE` 128x128 block was
7521 // just written, so the root's remaining 64x64 cells code nothing.
7522 let mut sb128_none = false;
7523 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
7524 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
7525 // and partition symbol first; at a 64 one this is plain raster and every
7526 // cell is its own superblock, i.e. byte-identical to the loop before.
7527 for (sb_r, sb_c, row_start, sb_start) in sb_write_order(
7528 tile.sb_row0,
7529 tile.sb_row1.min(sb_rows),
7530 tile.sb_col0,
7531 tile.sb_col1.min(sb_cols),
7532 sb128,
7533 ) {
7534 if row_start {
7535 neighbours.start_row();
7536 }
7537 if sb_start {
7538 sb128_none = false;
7539 }
7540 // lane-b128: the remaining three 64x64 cells of a root the search
7541 // left WHOLE carry no syntax at all -- the same skip the decoder's
7542 // own `sb128_none` runs.
7543 if sb128_none {
7544 continue;
7545 }
7546 if sb128 && sb_start {
7547 // The 128x128 block a `PARTITION_NONE` root carries, held by the
7548 // top-left 32x32 entry of the root's sixteen.
7549 let root_entry = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols)
7550 .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize]);
7551 let root_block = root_entry.and_then(|q| match q {
7552 Quadrant::Whole128(block) => Some(block),
7553 _ => None,
7554 });
7555 // lane-b128hv: the two rectangular halves a HORZ/VERT root carries.
7556 let root_rect = root_entry.and_then(|q| match q {
7557 Quadrant::Rect128(horz, halves) => Some((*horz, halves)),
7558 _ => None,
7559 });
7560 // lane-ab128: the three pieces an AB-shape root carries, and the
7561 // partition symbol it is coded under.
7562 let root_ab = root_entry.and_then(|q| match q {
7563 Quadrant::Ab128(symbol, pieces) => Some((*symbol as usize, pieces)),
7564 _ => None,
7565 });
7566 write_sb128_root(
7567 &mut enc,
7568 &mut cdfs,
7569 &neighbours,
7570 sb_r,
7571 sb_c,
7572 mi_cols,
7573 mi_rows,
7574 match (root_block.is_some(), root_rect, root_ab) {
7575 (true, ..) => PARTITION_NONE,
7576 (_, Some((true, _)), _) => PARTITION_HORZ,
7577 (_, Some((false, _)), _) => PARTITION_VERT,
7578 (_, _, Some((symbol, _))) => symbol,
7579 _ => PARTITION_SPLIT,
7580 },
7581 );
7582 if let Some(block) = root_block {
7583 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
7584 write_inter_block_128(
7585 &mut enc,
7586 &mut cdfs,
7587 &mut neighbours,
7588 &mut grid,
7589 at128,
7590 block,
7591 mi_cols,
7592 mi_rows,
7593 tx_select,
7594 )?;
7595 sb128_none = true;
7596 continue;
7597 }
7598 if let Some((horz, halves)) = root_rect {
7599 // libaom `decode_partition` at BLOCK_128X128: `subsize` at
7600 // (mi_row, mi_col) and a second one at + hbs (16 mi) along the
7601 // cut axis, the second only when it is inside the frame -- the
7602 // search only offers a root wholly inside, so both are.
7603 let base_mi = (
7604 (sb_r & !1) as usize * SB_MI as usize,
7605 (sb_c & !1) as usize * SB_MI as usize,
7606 );
7607 let (w, h) = if horz { (128usize, 64usize) } else { (64, 128) };
7608 for (i, half) in halves.iter().enumerate() {
7609 let at_mi = if horz {
7610 (base_mi.0 + i * 16, base_mi.1)
7611 } else {
7612 (base_mi.0, base_mi.1 + i * 16)
7613 };
7614 write_inter_block_128_rect(
7615 &mut enc,
7616 &mut cdfs,
7617 &mut neighbours,
7618 &mut grid,
7619 at_mi,
7620 (w, h),
7621 half,
7622 mi_cols,
7623 mi_rows,
7624 tx_select,
7625 )?;
7626 }
7627 sb128_none = true;
7628 continue;
7629 }
7630 if let Some((symbol, pieces)) = root_ab {
7631 // libaom `decode_partition` at BLOCK_128X128, AB arm: two
7632 // 64x64 blocks and one 128x64 / 64x128 half, in the order
7633 // decode.rs' `sb128_ab` reads them
7634 // ([`crate::encode::ab128_pieces`]). An AB shape only comes
7635 // from the full alphabet symbol (both halves in frame), so
7636 // there is no edge break to mirror -- the search offers one
7637 // only at a root wholly inside.
7638 let base_mi = (
7639 (sb_r & !1) as usize * SB_MI as usize,
7640 (sb_c & !1) as usize * SB_MI as usize,
7641 );
7642 for (((mi_r, mi_c), (w, h)), piece) in crate::encode::ab128_pieces(symbol, base_mi)
7643 .iter()
7644 .zip(pieces)
7645 {
7646 write_inter_block_128_rect(
7647 &mut enc,
7648 &mut cdfs,
7649 &mut neighbours,
7650 &mut grid,
7651 (*mi_r, *mi_c),
7652 (*w, *h),
7653 piece,
7654 mi_cols,
7655 mi_rows,
7656 tx_select,
7657 )?;
7658 }
7659 SB128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7660 sb128_none = true;
7661 continue;
7662 }
7663 }
7664 {
7665 if !sb128 {
7666 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W);
7667 }
7668 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
7669 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
7670 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
7671 // whose bottom or right half falls outside the true frame cannot
7672 // be left whole, so the only question there is which of the three
7673 // partition symbols the split takes — same three-way signaling as
7674 // `sb_coeff_key_frame_tile`'s superblock level.
7675 let (has_cols, has_rows) = (
7676 sb_c * SB_MI + SB_MI / 2 < mi_cols,
7677 sb_r * SB_MI + SB_MI / 2 < mi_rows,
7678 );
7679 // lane-b64: a superblock the search left WHOLE — one 64x64 block
7680 // at `PARTITION_NONE`, carried by its top-left quadrant's entry
7681 // ([`Quadrant::Whole64`]). Single-reference; skipped, or with a
7682 // real residual through `TxbSet::Luma64` + two `Chroma32`
7683 // (lane-tx64).
7684 let sb64 = ((sb_r * 2) < rows && (sb_c * 2) < cols)
7685 .then(|| &blocks[((sb_r * 2) * cols + sb_c * 2) as usize])
7686 .and_then(|q| match q {
7687 Quadrant::Whole64(block) => Some(block),
7688 _ => None,
7689 });
7690 if let Some(block) = sb64 {
7691 if !has_cols || !has_rows {
7692 return Err(Error::unsupported(
7693 "AV1 tile",
7694 "a superblock that is half outside the true frame cannot be left whole",
7695 ));
7696 }
7697 let info = block.inter.ok_or_else(|| {
7698 Error::unsupported("AV1 tile", "a 64x64 root block is coded inter")
7699 })?;
7700 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[sb_ctx]);
7701 let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
7702 let has_above = neighbours.has_above(mi_r);
7703 let has_left = neighbours.has_left(mi_c);
7704 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
7705 + usize::from(neighbours.left_skip[mi_r]);
7706 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
7707 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
7708 write_delta_q(
7709 &mut enc,
7710 &mut cdfs,
7711 (mi_r, mi_c),
7712 !sb128_armed(),
7713 block.skip,
7714 );
7715 let ii_ctx = intra_inter_ctx(
7716 has_above,
7717 has_left,
7718 neighbours.above_inter[mi_c],
7719 neighbours.left_inter[mi_r],
7720 );
7721 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
7722 write_comp_mode(
7723 &mut enc,
7724 &mut cdfs,
7725 &neighbours,
7726 (mi_r, mi_c),
7727 (has_above, has_left),
7728 info.ref1.is_some(),
7729 );
7730 // lane-b64b: a COMPOUND 64x64 root takes the same mode chain
7731 // every other compound block does, at this superblock's own
7732 // 16x16-mi window.
7733 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
7734 write_compound_block(
7735 &mut enc,
7736 &mut cdfs,
7737 &neighbours,
7738 &grid,
7739 (mi_r, mi_c),
7740 (SB_MI as usize, SB_MI as usize),
7741 (has_above, has_left),
7742 info,
7743 (mi_cols as usize, mi_rows as usize),
7744 )?
7745 } else {
7746 write_single_ref(
7747 &mut enc,
7748 &mut cdfs,
7749 info.ref_frame,
7750 neighbours.above_ref[mi_c],
7751 neighbours.above_ref1[mi_c],
7752 neighbours.left_ref[mi_r],
7753 neighbours.left_ref1[mi_r],
7754 );
7755 let stack = find_mv_stack(
7756 &grid,
7757 mi_r,
7758 mi_c,
7759 SB_MI as usize,
7760 SB_MI as usize,
7761 info.ref_frame,
7762 mi_cols as usize,
7763 mi_rows as usize,
7764 );
7765 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
7766 if crate::msac::symtrace::dir().is_some() {
7767 crate::msac::symtrace::note(&format!(
7768 " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
7769 info.mode, info.ref_mv_idx, info.mv
7770 ));
7771 }
7772 (mv, (0, 0), is_new_mv)
7773 };
7774 for dr in 0..SB_MI as usize {
7775 for dc in 0..SB_MI as usize {
7776 grid.set(
7777 mi_r + dr,
7778 mi_c + dc,
7779 MiInfo {
7780 is_inter: true,
7781 ref_frame: info.ref_frame,
7782 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7783 mv1: mv16(mv1),
7784 mv: mv16(mv),
7785 is_new_mv,
7786 size: SB_MI as u8,
7787 size_h: SB_MI as u8,
7788 is_global_mv0: false,
7789 is_global_mv1: false,
7790 },
7791 );
7792 }
7793 }
7794 if info.ref1.is_none() {
7795 // libaom's `motion_mode_allowed` fails on a compound
7796 // block, so the decoder reads no symbol for one.
7797 write_motion_mode(
7798 &mut enc,
7799 &mut cdfs,
7800 &grid,
7801 (mi_r, mi_c),
7802 (SB_MI as usize, SB_MI as usize),
7803 (SB, SB),
7804 (mi_cols as usize, mi_rows as usize),
7805 info.ref_frame,
7806 block.motion_mode,
7807 )?;
7808 }
7809 if tx_select {
7810 // A skipped inter block writes no `txfm_split` at all --
7811 // that call only publishes the max transform size the
7812 // reader infers for it; an unskipped one writes the
7813 // `txfm_split` flag: 0 when the root's luma is one whole
7814 // TX_64X64, 1 when it is the four TX_32X32 units
7815 // lane-b64b's var-tx arm chose.
7816 write_tx_syntax_inter(
7817 &mut enc,
7818 &mut cdfs,
7819 &mut neighbours,
7820 (mi_r, mi_c),
7821 SB,
7822 true,
7823 block.skip,
7824 usize::from(block.tx_depth),
7825 );
7826 }
7827 if block.skip {
7828 neighbours.record(sb_at, SB, 0, &zero_grids);
7829 } else {
7830 // lane-tx64: the 64x64 root's real residual. Luma is one
7831 // TX_64X64 whose coded quarter is a 32x32 level grid
7832 // (`TxbSet::Luma64`, `TX32`'s own scan -- the same pair
7833 // `sb_coeff_key_frame_tile`'s `Superblock::Whole` writes),
7834 // chroma one whole TX_32X32 per plane, and `split` is
7835 // false because the luma transform covers the block.
7836 // lane-b64b: at `txfm_split = 1` the luma levels arrive in
7837 // 64x64 block coordinates and are written as the four
7838 // TX_32X32 units `write_luma_tus` slices out, each
7839 // publishing its own coefficient context before the next
7840 // one reads it; chroma is one TX_32X32 per plane either
7841 // way.
7842 let split = block.tx_depth == 1;
7843 let grids = [
7844 level_grid(&block.luma, if split { SB } else { TX32 })?,
7845 level_grid(&block.u, TX32)?,
7846 level_grid(&block.v, TX32)?,
7847 ];
7848 if split {
7849 write_luma_tus(
7850 &mut enc,
7851 &mut cdfs,
7852 &mut neighbours,
7853 (mi_r, mi_c),
7854 SB,
7855 TX32,
7856 &grids[0],
7857 0,
7858 &all_scans,
7859 true,
7860 &block.luma_tx_types,
7861 )?;
7862 }
7863 write_block_planes(
7864 &mut enc,
7865 &mut cdfs,
7866 &sb64_planes,
7867 &grids,
7868 &[&scan32, &scan32, &scan32],
7869 &neighbours.around(sb_at, SB),
7870 0,
7871 split,
7872 block_tx_type(block),
7873 true,
7874 );
7875 neighbours.record_planes(sb_at, SB, 0, &grids, !split);
7876 }
7877 neighbours.record_inter(sb_at, SB, block.skip, true, block_ref(block));
7878 record_block_compound(&mut neighbours, (mi_r, mi_c), SB, block);
7879 continue;
7880 }
7881 match (has_cols, has_rows) {
7882 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]),
7883 (true, false) => {
7884 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
7885 }
7886 (false, true) => {
7887 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
7888 }
7889 (false, false) => {}
7890 }
7891
7892 for quadrant in 0..4 {
7893 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
7894 // Only a quadrant whose own mi origin is inside the true
7895 // frame is coded at all (spec `decode_partition`'s
7896 // `r >= MiRows || c >= MiCols` early return), same filter as
7897 // `sb_coeff_key_frame_tile`'s `quadrant_positions`.
7898 if r32 >= rows || c32 >= cols {
7899 continue;
7900 }
7901 let site = &blocks[(r32 * cols + c32) as usize];
7902 let at = (r32 as usize * 2, c32 as usize * 2);
7903 let ctx32 = neighbours.partition_ctx(at, BLOCK);
7904 // spec `decode_partition`'s hasRows/hasCols recomputed at this
7905 // quadrant's own half: a whole 32x32 block cannot be left
7906 // whole once its own half straddles the true edge, mirroring
7907 // `sb_coeff_key_frame_tile`'s "cannot be left whole" refusal.
7908 let (has_cols32, has_rows32) = (
7909 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
7910 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
7911 );
7912 let block = match site {
7913 // Already coded by the `Whole64` above -- but only inside
7914 // a superblock that really carried one.
7915 Quadrant::Whole64(_)
7916 | Quadrant::Whole128(_)
7917 | Quadrant::Rect128(..)
7918 | Quadrant::Ab128(..)
7919 | Quadrant::Covered => {
7920 return Err(Error::unsupported(
7921 "AV1 tile",
7922 "a `Whole64`/`Covered` quadrant needs its superblock's \
7923 top-left entry to be the `Whole64`",
7924 ));
7925 }
7926 Quadrant::Whole(block) => {
7927 if !has_cols32 || !has_rows32 {
7928 return Err(Error::unsupported(
7929 "AV1 tile",
7930 "a 32x32 block that is half outside the true frame \
7931 cannot be left whole",
7932 ));
7933 }
7934 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]);
7935 block
7936 }
7937 Quadrant::Split(sub_blocks) => {
7938 // Same filter as `sb_coeff_key_frame_tile`'s
7939 // `sub_positions`: only the 16x16 leaves whose own mi
7940 // origin is inside the true frame are coded.
7941 let sub_positions: Vec<(usize, usize)> = (0..4)
7942 .map(|i| (r32 as usize * 2 + i / 2, c32 as usize * 2 + i % 2))
7943 .filter(|&(sr, sc)| {
7944 (sr as u32) * SUB_MI < mi_rows && (sc as u32) * SUB_MI < mi_cols
7945 })
7946 .collect();
7947 if sub_blocks.len() != sub_positions.len() {
7948 return Err(Error::unsupported(
7949 "AV1 tile",
7950 "a split 32x32 inter-frame block needs one 16x16 entry \
7951 per sub-block inside the true frame",
7952 ));
7953 }
7954 // Same three-way spec signaling as the superblock
7955 // level above, recomputed at this quadrant's own half.
7956 match (has_cols32, has_rows32) {
7957 (true, true) => {
7958 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx32]);
7959 }
7960 (true, false) => {
7961 enc.symbol_fixed(
7962 1,
7963 &gather(&cdfs.partition_w32[ctx32], VERT_ALIKE),
7964 );
7965 }
7966 (false, true) => {
7967 enc.symbol_fixed(
7968 1,
7969 &gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE),
7970 );
7971 }
7972 (false, false) => {}
7973 }
7974 for (leaf, (sr, sc)) in sub_blocks.iter().zip(sub_positions) {
7975 // A 16x16 leaf whose own half straddles the true
7976 // frame edge splits into the 8x8 leaves that are
7977 // inside it (lane-av1inter8), same split the key
7978 // frame search takes at this geometry -- on both
7979 // axes too, where `decode_partition` infers the
7980 // split and reads no symbol at all
7981 // (lane-av1rect).
7982 let (has_cols16, has_rows16) = (
7983 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
7984 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
7985 );
7986 let at16 = (sr, sc);
7987 if has_cols16 && has_rows16 {
7988 let ctx16 = neighbours.partition_ctx(at16, SUB);
7989 // A 16x16 leaf wholly inside the frame that
7990 // carries `eight` split itself further, on
7991 // cost rather than on geometry (lane-av1rd2):
7992 // spec PARTITION_SPLIT at BLOCK_16X16, then
7993 // the same four 8x8 leaves the straddling
7994 // branch below writes -- all four inside, so
7995 // the partition symbol is a real one rather
7996 // than the edge's gathered flag.
7997 if let Some(leaves) = &leaf.eight {
7998 if leaves.len() != 4 {
7999 return Err(Error::unsupported(
8000 "AV1 tile",
8001 "a 16x16 inter-frame block inside the frame that splits needs all four 8x8 leaves",
8002 ));
8003 }
8004 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w16[ctx16]);
8005 let (mi_row0, mi_col0) =
8006 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
8007 for (i, leaf8) in leaves.iter().enumerate() {
8008 let leaf_mi = (
8009 (mi_row0 + (i as u32 / 2) * 2) as usize,
8010 (mi_col0 + (i as u32 % 2) * 2) as usize,
8011 );
8012 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
8013 enc.symbol(
8014 PARTITION_NONE,
8015 &mut cdfs.partition_w8[leaf_ctx],
8016 );
8017 let (skip, is_inter) = write_inter_frame_leaf8(
8018 &mut enc,
8019 &mut cdfs,
8020 &mut neighbours,
8021 &mut grid,
8022 mi_cols,
8023 mi_rows,
8024 leaf8,
8025 leaf_mi,
8026 &scan8,
8027 &scan4,
8028 tx_select,
8029 &all_scans,
8030 )?;
8031 let _ = (skip, is_inter);
8032 }
8033 continue;
8034 }
8035 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]);
8036 write_inter_frame_leaf(
8037 &mut enc,
8038 &mut cdfs,
8039 &mut neighbours,
8040 &mut grid,
8041 mi_cols,
8042 mi_rows,
8043 leaf,
8044 at16,
8045 &scan16,
8046 &scan8,
8047 tx_select,
8048 &all_scans,
8049 )?;
8050 } else {
8051 let ctx16 = neighbours.partition_ctx(at16, SUB);
8052 match (has_cols16, has_rows16) {
8053 (true, false) => enc.symbol_fixed(
8054 1,
8055 &gather(&cdfs.partition_w16[ctx16], VERT_ALIKE),
8056 ),
8057 (false, true) => enc.symbol_fixed(
8058 1,
8059 &gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE),
8060 ),
8061 // Both halves outside: SPLIT is inferred.
8062 _ => {}
8063 }
8064 let leaves = leaf.eight.as_ref().ok_or_else(|| {
8065 Error::unsupported(
8066 "AV1 tile",
8067 "a 16x16 inter-frame block the true frame edge cuts \
8068 through needs its `eight` leaves populated",
8069 )
8070 })?;
8071 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
8072 let leaf_positions: Vec<(u32, u32)> = (0..4)
8073 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
8074 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
8075 .collect();
8076 if leaves.len() != leaf_positions.len() {
8077 return Err(Error::unsupported(
8078 "AV1 tile",
8079 "a straddling 16x16 inter-frame block needs one \
8080 `eight` entry per 8x8 leaf inside the true frame",
8081 ));
8082 }
8083 for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) {
8084 let leaf_mi = (mr as usize, mc as usize);
8085 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
8086 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w8[leaf_ctx]);
8087 let (skip, is_inter) = write_inter_frame_leaf8(
8088 &mut enc,
8089 &mut cdfs,
8090 &mut neighbours,
8091 &mut grid,
8092 mi_cols,
8093 mi_rows,
8094 leaf8,
8095 leaf_mi,
8096 &scan8,
8097 &scan4,
8098 tx_select,
8099 &all_scans,
8100 )?;
8101 let _ = (skip, is_inter);
8102 }
8103 // Same write-back-once-from-the-last-leaf rule
8104 // as the key frame search's `write_leaf8`
8105 // caller (r15): the SUB-grid skip/inter arrays
8106 // are otherwise left stale for the next
8107 // 16x16 slot.
8108 }
8109 }
8110 continue;
8111 }
8112 };
8113
8114 let (r, c) = at;
8115 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8116 let has_above = neighbours.has_above(mi_r);
8117 let has_left = neighbours.has_left(mi_c);
8118 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
8119 + usize::from(neighbours.left_skip[mi_r]);
8120 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
8121 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
8122 write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), false, block.skip);
8123
8124 let is_inter = block.inter.is_some();
8125 let (above_inter, left_inter) =
8126 (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
8127 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8128 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
8129
8130 let mode_for_tx;
8131 if let Some(info) = block.inter {
8132 write_comp_mode(
8133 &mut enc,
8134 &mut cdfs,
8135 &neighbours,
8136 (mi_r, mi_c),
8137 (has_above, has_left),
8138 info.ref1.is_some(),
8139 );
8140 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
8141 if info.ref1.is_some() {
8142 let (mv, mv1, is_new_mv) = write_compound_block(
8143 &mut enc,
8144 &mut cdfs,
8145 &neighbours,
8146 &grid,
8147 (mi_row, mi_col),
8148 (8, 8),
8149 (has_above, has_left),
8150 info,
8151 (mi_cols as usize, mi_rows as usize),
8152 )?;
8153 for dr in 0..8 {
8154 for dc in 0..8 {
8155 grid.set(
8156 mi_row + dr,
8157 mi_col + dc,
8158 MiInfo {
8159 is_inter: true,
8160 ref_frame: info.ref_frame,
8161 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8162 mv1: mv16(mv1),
8163 mv: mv16(mv),
8164 is_new_mv,
8165 size: 8,
8166 size_h: 8,
8167 is_global_mv0: false,
8168 is_global_mv1: false,
8169 },
8170 );
8171 }
8172 }
8173 mode_for_tx = 0;
8174 } else {
8175 write_single_ref(
8176 &mut enc,
8177 &mut cdfs,
8178 info.ref_frame,
8179 neighbours.above_ref[mi_c],
8180 neighbours.above_ref1[mi_c],
8181 neighbours.left_ref[mi_r],
8182 neighbours.left_ref1[mi_r],
8183 );
8184
8185 let stack = find_mv_stack(
8186 &grid,
8187 mi_row,
8188 mi_col,
8189 8,
8190 8,
8191 info.ref_frame,
8192 mi_cols as usize,
8193 mi_rows as usize,
8194 );
8195
8196 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
8197 if crate::msac::symtrace::dir().is_some() {
8198 crate::msac::symtrace::note(&format!(
8199 " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
8200 info.mode, info.ref_mv_idx, info.mv
8201 ));
8202 }
8203 grid.set(
8204 mi_row,
8205 mi_col,
8206 MiInfo {
8207 is_inter: true,
8208 ref_frame: info.ref_frame,
8209 ref_frame1: NO_REF1,
8210 mv1: (0, 0),
8211 mv: mv16(mv),
8212 is_new_mv,
8213 size: 8,
8214 size_h: 8,
8215 is_global_mv0: false,
8216 is_global_mv1: false,
8217 },
8218 );
8219 for dr in 0..8 {
8220 for dc in 0..8 {
8221 if dr == 0 && dc == 0 {
8222 continue;
8223 }
8224 grid.set(
8225 mi_row + dr,
8226 mi_col + dc,
8227 MiInfo {
8228 is_inter: true,
8229 ref_frame: info.ref_frame,
8230 ref_frame1: NO_REF1,
8231 mv1: (0, 0),
8232 mv: mv16(mv),
8233 is_new_mv,
8234 size: 8,
8235 size_h: 8,
8236 is_global_mv0: false,
8237 is_global_mv1: false,
8238 },
8239 );
8240 }
8241 }
8242 write_motion_mode(
8243 &mut enc,
8244 &mut cdfs,
8245 &grid,
8246 (mi_row, mi_col),
8247 (8, 8),
8248 (BLOCK, BLOCK),
8249 (mi_cols as usize, mi_rows as usize),
8250 info.ref_frame,
8251 block.motion_mode,
8252 )?;
8253 mode_for_tx = 0;
8254 }
8255 } else {
8256 let mode = usize::from(block.mode);
8257 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
8258 if (V_PRED..=D67_PRED).contains(&mode) {
8259 enc.symbol(
8260 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8261 &mut cdfs.angle_delta[mode - V_PRED],
8262 );
8263 }
8264 let uv_mode = usize::from(block.uv_mode);
8265 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8266 if uv_mode == UV_CFL_PRED {
8267 write_cfl_alphas(&mut enc, &mut cdfs, block.cfl_alphas.expect("cfl"));
8268 }
8269 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8270 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8271 }
8272 mode_for_tx = tx_row(mode, block.filter_intra);
8273 // Intra: no vote, but still a coded cell -- mvstack's
8274 // extended-scan coverage must see it (module doc).
8275 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
8276 write_palette_syntax(
8277 &mut enc,
8278 &mut cdfs,
8279 &mut neighbours,
8280 block.palette.as_ref(),
8281 block.palette_uv.as_ref(),
8282 block.filter_intra,
8283 mode,
8284 uv_mode,
8285 (mi_row, mi_col),
8286 BLOCK,
8287 );
8288 for dr in 0..8 {
8289 for dc in 0..8 {
8290 grid.set(
8291 mi_row + dr,
8292 mi_col + dc,
8293 MiInfo {
8294 is_inter: false,
8295 ref_frame: -1,
8296 ref_frame1: NO_REF1,
8297 mv1: (0, 0),
8298 mv: (0, 0),
8299 is_new_mv: false,
8300 size: 8,
8301 size_h: 8,
8302 is_global_mv0: false,
8303 is_global_mv1: false,
8304 },
8305 );
8306 }
8307 }
8308 }
8309
8310 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
8311 let tx = if tx_select {
8312 write_tx_syntax_inter(
8313 &mut enc,
8314 &mut cdfs,
8315 &mut neighbours,
8316 at_mi,
8317 BLOCK,
8318 is_inter,
8319 block.skip,
8320 usize::from(block.tx_depth),
8321 )
8322 } else {
8323 BLOCK
8324 };
8325 let split = tx < BLOCK;
8326 if block.skip {
8327 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
8328 } else {
8329 let grids = [
8330 level_grid(&block.luma, TX32)?,
8331 level_grid(&block.u, TX16)?,
8332 level_grid(&block.v, TX16)?,
8333 ];
8334 if split {
8335 write_luma_tus(
8336 &mut enc,
8337 &mut cdfs,
8338 &mut neighbours,
8339 at_mi,
8340 BLOCK,
8341 tx,
8342 &grids[0],
8343 mode_for_tx,
8344 &all_scans,
8345 is_inter,
8346 &block.luma_tx_types,
8347 )?;
8348 }
8349 write_block_planes(
8350 &mut enc,
8351 &mut cdfs,
8352 if is_inter {
8353 &inter_planes
8354 } else {
8355 &intra_planes
8356 },
8357 &grids,
8358 &[&scan32, &scan16, &scan16],
8359 &neighbours.around(at, BLOCK),
8360 mode_for_tx,
8361 split,
8362 block_tx_type(block),
8363 is_inter,
8364 );
8365 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
8366 }
8367 neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));
8368 record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block);
8369 }
8370 }
8371 }
8372 Ok(enc.finish())
8373}
8374
8375/// Writes one 16x16 leaf a straddling 32x32 quadrant's [`Quadrant::Split`]
8376/// splits into: intra (spec `inter_frame_mode_info`'s intra branch, the only
8377/// one this writer used to code here) or real inter (`is_inter` coded
8378/// `true`), `NEARESTMV` only -- `NEWMV` at this size is this function's
8379/// caller's to never build (`Quadrant::Split`'s `BlockCoeffs.inter`) -- same
8380/// `single_ref`/mv-stack/DRL symbol chain as the whole-32x32 branch above,
8381/// just at this leaf's own 4x4-mi window (`bw4`/`bh4` of 4, not 8) and coded
8382/// through [`TxbSet::Luma16Inter`] rather than [`TxbSet::Luma32Inter`]. Its
8383/// own `PARTITION_NONE` symbol is already written, same contract as
8384/// [`write_block`].
8385#[allow(clippy::too_many_arguments)]
8386fn write_inter_frame_leaf(
8387 enc: &mut SymbolEncoder,
8388 cdfs: &mut Cdfs,
8389 neighbours: &mut Neighbours,
8390 grid: &mut MiGrid,
8391 mi_cols: u32,
8392 mi_rows: u32,
8393 block: &BlockCoeffs,
8394 at: (usize, usize),
8395 scan16: &Vec<u16>,
8396 scan8: &Vec<u16>,
8397 tx_select: bool,
8398 all_scans: &[Vec<u16>; 4],
8399) -> Result<()> {
8400 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
8401 return Err(Error::unsupported(
8402 "AV1 tile",
8403 format!(
8404 "intra mode {} is not one of the thirteen this writer codes",
8405 block.mode
8406 ),
8407 ));
8408 }
8409 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
8410 /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size.
8411 const SIZE_GROUP_16: usize = 2;
8412
8413 let (r, c) = at;
8414 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8415 let skip_ctx =
8416 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
8417 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
8418 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
8419 write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
8420
8421 let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c));
8422 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
8423 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8424 let is_inter = block.inter.is_some();
8425 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
8426
8427 let mode_for_tx;
8428 if let Some(info) = block.inter {
8429 write_comp_mode(
8430 enc,
8431 cdfs,
8432 neighbours,
8433 (mi_r, mi_c),
8434 (has_above, has_left),
8435 info.ref1.is_some(),
8436 );
8437 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8438 if info.ref1.is_some() {
8439 let n = SUB_MI as usize;
8440 let (mv, mv1, is_new_mv) = write_compound_block(
8441 enc,
8442 cdfs,
8443 neighbours,
8444 grid,
8445 (mi_row, mi_col),
8446 (n, n),
8447 (has_above, has_left),
8448 info,
8449 (mi_cols as usize, mi_rows as usize),
8450 )?;
8451 for dr in 0..n {
8452 for dc in 0..n {
8453 grid.set(
8454 mi_row + dr,
8455 mi_col + dc,
8456 MiInfo {
8457 is_inter: true,
8458 ref_frame: info.ref_frame,
8459 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8460 mv1: mv16(mv1),
8461 mv: mv16(mv),
8462 is_new_mv,
8463 size: n as u8,
8464 size_h: n as u8,
8465 is_global_mv0: false,
8466 is_global_mv1: false,
8467 },
8468 );
8469 }
8470 }
8471 mode_for_tx = 0;
8472 } else {
8473 write_single_ref(
8474 enc,
8475 cdfs,
8476 info.ref_frame,
8477 neighbours.above_ref[mi_c],
8478 neighbours.above_ref1[mi_c],
8479 neighbours.left_ref[mi_r],
8480 neighbours.left_ref1[mi_r],
8481 );
8482
8483 let stack = find_mv_stack(
8484 grid,
8485 mi_row,
8486 mi_col,
8487 SUB_MI as usize,
8488 SUB_MI as usize,
8489 info.ref_frame,
8490 mi_cols as usize,
8491 mi_rows as usize,
8492 );
8493
8494 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
8495 for dr in 0..SUB_MI as usize {
8496 for dc in 0..SUB_MI as usize {
8497 grid.set(
8498 mi_row + dr,
8499 mi_col + dc,
8500 MiInfo {
8501 is_inter: true,
8502 ref_frame: info.ref_frame,
8503 ref_frame1: NO_REF1,
8504 mv1: (0, 0),
8505 mv: mv16(mv),
8506 is_new_mv,
8507 size: SUB_MI as usize as u8,
8508 size_h: SUB_MI as usize as u8,
8509 is_global_mv0: false,
8510 is_global_mv1: false,
8511 },
8512 );
8513 }
8514 }
8515 write_motion_mode(
8516 enc,
8517 cdfs,
8518 grid,
8519 (mi_row, mi_col),
8520 (SUB_MI as usize, SUB_MI as usize),
8521 (SUB, SUB),
8522 (mi_cols as usize, mi_rows as usize),
8523 info.ref_frame,
8524 block.motion_mode,
8525 )?;
8526 mode_for_tx = 0;
8527 }
8528 } else {
8529 let mode = usize::from(block.mode);
8530 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);
8531 if (V_PRED..=D67_PRED).contains(&mode) {
8532 enc.symbol(
8533 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8534 &mut cdfs.angle_delta[mode - V_PRED],
8535 );
8536 }
8537 let uv_mode = usize::from(block.uv_mode);
8538 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8539 if uv_mode == UV_CFL_PRED {
8540 write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
8541 }
8542 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8543 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8544 }
8545 mode_for_tx = tx_row(mode, block.filter_intra);
8546 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
8547 // coverage must see it (module doc).
8548 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8549 write_palette_syntax(
8550 enc,
8551 cdfs,
8552 neighbours,
8553 block.palette.as_ref(),
8554 block.palette_uv.as_ref(),
8555 block.filter_intra,
8556 mode,
8557 uv_mode,
8558 (mi_row, mi_col),
8559 SUB,
8560 );
8561 for dr in 0..SUB_MI as usize {
8562 for dc in 0..SUB_MI as usize {
8563 grid.set(
8564 mi_row + dr,
8565 mi_col + dc,
8566 MiInfo {
8567 is_inter: false,
8568 ref_frame: -1,
8569 ref_frame1: NO_REF1,
8570 mv1: (0, 0),
8571 mv: (0, 0),
8572 is_new_mv: false,
8573 size: SUB_MI as usize as u8,
8574 size_h: SUB_MI as usize as u8,
8575 is_global_mv0: false,
8576 is_global_mv1: false,
8577 },
8578 );
8579 }
8580 }
8581 }
8582
8583 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
8584 let tx = if tx_select {
8585 write_tx_syntax_inter(
8586 enc,
8587 cdfs,
8588 neighbours,
8589 at_mi,
8590 SUB,
8591 is_inter,
8592 block.skip,
8593 usize::from(block.tx_depth),
8594 )
8595 } else {
8596 SUB
8597 };
8598 let split = tx < SUB;
8599 if block.skip {
8600 let zero_grids = [
8601 vec![0i32; TX16 * TX16],
8602 vec![0i32; TX8 * TX8],
8603 vec![0i32; TX8 * TX8],
8604 ];
8605 neighbours.record(at, SUB, mode_for_tx, &zero_grids);
8606 } else {
8607 let grids = [
8608 level_grid(&block.luma, TX16)?,
8609 level_grid(&block.u, TX8)?,
8610 level_grid(&block.v, TX8)?,
8611 ];
8612 if split {
8613 write_luma_tus(
8614 enc,
8615 cdfs,
8616 neighbours,
8617 at_mi,
8618 SUB,
8619 tx,
8620 &grids[0],
8621 mode_for_tx,
8622 all_scans,
8623 is_inter,
8624 &block.luma_tx_types,
8625 )?;
8626 }
8627 write_block_planes(
8628 enc,
8629 cdfs,
8630 if is_inter {
8631 &[TxbSet::Luma16Inter, TxbSet::Chroma8, TxbSet::Chroma8]
8632 } else {
8633 &[TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8]
8634 },
8635 &grids,
8636 &[scan16, scan8, scan8],
8637 &neighbours.around(at, SUB),
8638 mode_for_tx,
8639 split,
8640 block_tx_type(block),
8641 is_inter,
8642 );
8643 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
8644 }
8645 neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block));
8646 record_block_compound(neighbours, (mi_r, mi_c), SUB, block);
8647 Ok(())
8648}
8649
8650/// Writes one 8x8 leaf of a straddling 16x16 inter-frame block
8651/// (lane-av1inter8): its own skip flag, intra/inter choice and (when inter)
8652/// `NEARESTMV`/`NEWMV` chain, or (when intra) `Y_MODE`, then its own luma and
8653/// two chroma transform blocks -- coded exactly like
8654/// [`write_inter_frame_leaf`] but through [`TxbSet::Luma8Inter`]/
8655/// [`TxbSet::Chroma4`] and at this leaf's own 2x2-mi mv-stack window, reading
8656/// its skip/intra-inter context from the *enclosing* 16x16 slot's
8657/// [`Neighbours`] arrays (`outer_at`, in [`SUB`]-grid units) unless
8658/// `prev_leaf` names this straddling block's own first leaf as the true
8659/// mi-adjacent neighbour -- the same override [`write_leaf8`] applies to its
8660/// mode context, needed for the same reason: `Neighbours`' above/left arrays
8661/// only resolve to [`SUB`] granularity, too coarse for the second leaf of a
8662/// straddling 16x16 to see the first. `Y_MODE`'s own context (`Size_Group`)
8663/// is not neighbour-dependent, unlike the key frame path's `kf_y_mode`, so no
8664/// override is needed there. Hands back this leaf's own skip flag and
8665/// intra/inter choice, which is what the next leaf (or the caller's final
8666/// write-back, mirroring `write_leaf8`'s caller) reads.
8667#[allow(clippy::too_many_arguments)]
8668fn write_inter_frame_leaf8(
8669 enc: &mut SymbolEncoder,
8670 cdfs: &mut Cdfs,
8671 neighbours: &mut Neighbours,
8672 grid: &mut MiGrid,
8673 mi_cols: u32,
8674 mi_rows: u32,
8675 block: &BlockCoeffs,
8676 leaf_mi: (usize, usize),
8677 scan8: &Vec<u16>,
8678 scan4: &Vec<u16>,
8679 tx_select: bool,
8680 all_scans: &[Vec<u16>; 4],
8681) -> Result<(bool, bool)> {
8682 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
8683 return Err(Error::unsupported(
8684 "AV1 tile",
8685 format!(
8686 "intra mode {} is not one of the thirteen this writer codes",
8687 block.mode
8688 ),
8689 ));
8690 }
8691 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
8692 /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size.
8693 const SIZE_GROUP_8: usize = 1;
8694
8695 // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's:
8696 // under a real PARTITION_SPLIT all four leaves are coded, so the
8697 // bottom-left leaf's true above neighbour is the FIRST leaf and the
8698 // bottom-right's above and left are two DIFFERENT ones (lane-av1rd2 --
8699 // reading the coarse slot desynced the stream, and so did an override
8700 // that remembered only the previous leaf).
8701 let above_skip = neighbours.above_skip[leaf_mi.1];
8702 let left_skip = neighbours.left_skip[leaf_mi.0];
8703 let above_inter = neighbours.above_inter[leaf_mi.1];
8704 let left_inter = neighbours.left_inter[leaf_mi.0];
8705 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
8706 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
8707 write_cdef_idx(enc, leaf_mi, block.skip);
8708 write_delta_q(enc, cdfs, leaf_mi, false, block.skip);
8709
8710 let (has_above, has_left) = (
8711 neighbours.has_above(leaf_mi.0),
8712 neighbours.has_left(leaf_mi.1),
8713 );
8714 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8715 let is_inter = block.inter.is_some();
8716 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
8717
8718 let mode_for_tx;
8719 if let Some(info) = block.inter {
8720 write_comp_mode(
8721 enc,
8722 cdfs,
8723 neighbours,
8724 leaf_mi,
8725 (has_above, has_left),
8726 info.ref1.is_some(),
8727 );
8728 let (mi_row, mi_col) = leaf_mi;
8729 if info.ref1.is_some() {
8730 let (mv, mv1, is_new_mv) = write_compound_block(
8731 enc,
8732 cdfs,
8733 neighbours,
8734 grid,
8735 (mi_row, mi_col),
8736 (2, 2),
8737 (has_above, has_left),
8738 info,
8739 (mi_cols as usize, mi_rows as usize),
8740 )?;
8741 for dr in 0..2 {
8742 for dc in 0..2 {
8743 grid.set(
8744 mi_row + dr,
8745 mi_col + dc,
8746 MiInfo {
8747 is_inter: true,
8748 ref_frame: info.ref_frame,
8749 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8750 mv1: mv16(mv1),
8751 mv: mv16(mv),
8752 is_new_mv,
8753 size: 2,
8754 size_h: 2,
8755 is_global_mv0: false,
8756 is_global_mv1: false,
8757 },
8758 );
8759 }
8760 }
8761 mode_for_tx = 0;
8762 } else {
8763 write_single_ref(
8764 enc,
8765 cdfs,
8766 info.ref_frame,
8767 neighbours.above_ref[leaf_mi.1],
8768 neighbours.above_ref1[leaf_mi.1],
8769 neighbours.left_ref[leaf_mi.0],
8770 neighbours.left_ref1[leaf_mi.0],
8771 );
8772
8773 let stack = find_mv_stack(
8774 grid,
8775 mi_row,
8776 mi_col,
8777 2,
8778 2,
8779 info.ref_frame,
8780 mi_cols as usize,
8781 mi_rows as usize,
8782 );
8783
8784 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
8785 for dr in 0..2 {
8786 for dc in 0..2 {
8787 grid.set(
8788 mi_row + dr,
8789 mi_col + dc,
8790 MiInfo {
8791 is_inter: true,
8792 ref_frame: info.ref_frame,
8793 ref_frame1: NO_REF1,
8794 mv1: (0, 0),
8795 mv: mv16(mv),
8796 is_new_mv,
8797 size: 2,
8798 size_h: 2,
8799 is_global_mv0: false,
8800 is_global_mv1: false,
8801 },
8802 );
8803 }
8804 }
8805 write_motion_mode(
8806 enc,
8807 cdfs,
8808 grid,
8809 (mi_row, mi_col),
8810 (2, 2),
8811 (8, 8),
8812 (mi_cols as usize, mi_rows as usize),
8813 info.ref_frame,
8814 block.motion_mode,
8815 )?;
8816 mode_for_tx = 0;
8817 }
8818 } else {
8819 let mode = usize::from(block.mode);
8820 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);
8821 if (V_PRED..=D67_PRED).contains(&mode) {
8822 enc.symbol(
8823 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8824 &mut cdfs.angle_delta[mode - V_PRED],
8825 );
8826 }
8827 let uv_mode = usize::from(block.uv_mode);
8828 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8829 if uv_mode == UV_CFL_PRED {
8830 write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
8831 }
8832 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8833 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8834 }
8835 mode_for_tx = tx_row(mode, block.filter_intra);
8836 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
8837 // coverage must see it (module doc).
8838 let (mi_row, mi_col) = leaf_mi;
8839 write_palette_syntax(
8840 enc,
8841 cdfs,
8842 neighbours,
8843 block.palette.as_ref(),
8844 block.palette_uv.as_ref(),
8845 block.filter_intra,
8846 mode,
8847 uv_mode,
8848 leaf_mi,
8849 8,
8850 );
8851 for dr in 0..2 {
8852 for dc in 0..2 {
8853 grid.set(
8854 mi_row + dr,
8855 mi_col + dc,
8856 MiInfo {
8857 is_inter: false,
8858 ref_frame: -1,
8859 ref_frame1: NO_REF1,
8860 mv1: (0, 0),
8861 mv: (0, 0),
8862 is_new_mv: false,
8863 size: 2,
8864 size_h: 2,
8865 is_global_mv0: false,
8866 is_global_mv1: false,
8867 },
8868 );
8869 }
8870 }
8871 }
8872
8873 let planes = if is_inter {
8874 [TxbSet::Luma8Inter, TxbSet::Chroma4, TxbSet::Chroma4]
8875 } else {
8876 [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]
8877 };
8878 let tx = if tx_select {
8879 write_tx_syntax_inter(
8880 enc,
8881 cdfs,
8882 neighbours,
8883 leaf_mi,
8884 8,
8885 is_inter,
8886 block.skip,
8887 usize::from(block.tx_depth),
8888 )
8889 } else {
8890 8
8891 };
8892 let split = tx < 8;
8893 if block.skip {
8894 let zero_grids = [
8895 vec![0i32; TX8 * TX8],
8896 vec![0i32; TX4 * TX4],
8897 vec![0i32; TX4 * TX4],
8898 ];
8899 neighbours.record_mi(leaf_mi, 8, &zero_grids);
8900 neighbours.record_inter_mi(
8901 leaf_mi,
8902 8,
8903 block.skip,
8904 block.inter.is_some(),
8905 block_ref(block),
8906 );
8907 record_block_compound(neighbours, leaf_mi, 8, block);
8908 } else {
8909 let grids = [
8910 level_grid(&block.luma, TX8)?,
8911 level_grid(&block.u, TX4)?,
8912 level_grid(&block.v, TX4)?,
8913 ];
8914 if split {
8915 write_luma_tus(
8916 enc,
8917 cdfs,
8918 neighbours,
8919 leaf_mi,
8920 8,
8921 tx,
8922 &grids[0],
8923 mode_for_tx,
8924 all_scans,
8925 is_inter,
8926 &block.luma_tx_types,
8927 )?;
8928 }
8929 write_block_planes(
8930 enc,
8931 cdfs,
8932 &planes,
8933 &grids,
8934 &[scan8, scan4, scan4],
8935 &neighbours.around_mi(leaf_mi, 8),
8936 mode_for_tx,
8937 split,
8938 block_tx_type(block),
8939 is_inter,
8940 );
8941 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
8942 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));
8943 record_block_compound(neighbours, leaf_mi, 8, block);
8944 }
8945 Ok((block.skip, is_inter))
8946}
8947
8948#[cfg(test)]
8949mod tests {
8950 use super::*;
8951 use crate::frame::frame_obu;
8952 use crate::obu::temporal_delimiter;
8953 use crate::probe::run_with_stdin;
8954 use crate::sequence::sequence_header_obu;
8955 use ec_av1_syntax::sequence::SequenceHeader;
8956 use ec_av1_syntax::{
8957 FrameHeader, FrameType, LoopFilterParams, QuantizationParams, TileInfo, TxMode,
8958 PRIMARY_REF_NONE,
8959 };
8960 use std::process::{Command, Stdio};
8961
8962 /// A 64x64 sequence with every tool this writer does not code turned off:
8963 /// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter
8964 /// intra, and no screen content tools (which is what keeps intra block copy
8965 /// and palette out of the block syntax).
8966 fn sequence_64() -> SequenceHeader {
8967 let mut seq = crate::sequence::tests::sample_1080p();
8968 seq.frame_width_bits = 7;
8969 seq.frame_height_bits = 7;
8970 seq.max_frame_width = 64;
8971 seq.max_frame_height = 64;
8972 seq.use_128x128_superblock = false;
8973 seq.enable_filter_intra = false;
8974 seq.enable_cdef = false;
8975 seq.enable_restoration = false;
8976 seq.enable_superres = false;
8977 seq.seq_force_screen_content_tools = 0;
8978 seq.seq_force_integer_mv = 0;
8979 seq
8980 }
8981
8982 /// The key frame the tile above belongs to: one tile, quantised so nothing
8983 /// is lossless, one transform size per block, no in-loop filtering, and no
8984 /// CDF adaptation (the writer codes against the defaults).
8985 fn flat_key_frame() -> FrameHeader {
8986 FrameHeader {
8987 frame_type: FrameType::Key,
8988 frame_is_intra: true,
8989 show_frame: true,
8990 error_resilient_mode: true,
8991 disable_cdf_update: true,
8992 allow_screen_content_tools: false,
8993 force_integer_mv: true,
8994 refresh_frame_flags: 0xFF,
8995 primary_ref_frame: PRIMARY_REF_NONE,
8996 frame_width: 64,
8997 frame_height: 64,
8998 upscaled_width: 64,
8999 render_width: 64,
9000 render_height: 64,
9001 mi_cols: 16,
9002 mi_rows: 16,
9003 tile_info: TileInfo {
9004 uniform_spacing: true,
9005 cols: 1,
9006 rows: 1,
9007 cols_log2: 0,
9008 rows_log2: 0,
9009 mi_col_starts: vec![0, 16],
9010 mi_row_starts: vec![0, 16],
9011 context_update_tile_id: 0,
9012 tile_size_bytes: 1,
9013 },
9014 quantization: QuantizationParams {
9015 base_q_idx: 100,
9016 ..QuantizationParams::default()
9017 },
9018 loop_filter: LoopFilterParams::default(),
9019 tx_mode: TxMode::Largest,
9020 reduced_tx_set: false,
9021 ..FrameHeader::default()
9022 }
9023 }
9024
9025 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
9026 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
9027 /// aomenc gate decodes its stream through ffmpeg and is meaningless
9028 /// without it -- turns it into a hard failure. Without this the require
9029 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
9030 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
9031 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
9032 fn have_ffmpeg() -> bool {
9033 let present = Command::new("ffmpeg")
9034 .arg("-version")
9035 .stdout(Stdio::null())
9036 .stderr(Stdio::null())
9037 .status()
9038 .is_ok_and(|s| s.success());
9039 assert!(
9040 present
9041 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
9042 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
9043 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
9044 );
9045 present
9046 }
9047
9048 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
9049 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
9050 let out = run_with_stdin(
9051 Command::new("ffmpeg").args([
9052 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
9053 ]),
9054 stream,
9055 );
9056 assert!(
9057 out.status.success(),
9058 "ffmpeg refused the stream: {}",
9059 String::from_utf8_lossy(&out.stderr)
9060 );
9061 assert_eq!(
9062 out.stdout.len(),
9063 w * h * 3 / 2,
9064 "expected one 4:2:0 frame, ffmpeg said: {}",
9065 String::from_utf8_lossy(&out.stderr)
9066 );
9067 out.stdout
9068 }
9069
9070 #[test]
9071 fn flat_key_frame_decodes_to_mid_grey() {
9072 if !have_ffmpeg() {
9073 eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH");
9074 return;
9075 }
9076 let seq = sequence_64();
9077 let header = flat_key_frame();
9078 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();
9079
9080 let mut stream = temporal_delimiter();
9081 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9082 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9083
9084 let planes = ffmpeg_decode(&stream, 64, 64);
9085 // A DC prediction with no neighbour to average is the middle of the
9086 // range, and a skipped block adds no residual, so every sample of every
9087 // plane is 128 — one wrong symbol anywhere in the tile shows up here.
9088 for (i, &s) in planes.iter().enumerate() {
9089 assert_eq!(s, 128, "sample {i} of the decoded frame");
9090 }
9091 }
9092
9093 /// The one q-context whose CDFs this crate carries; the decoded table
9094 /// below is pinned at this quantiser and nowhere else.
9095 const Q_IDX: u8 = 100;
9096
9097 /// Encode a 64x64 key frame carrying `dc_level` and hand back its planes.
9098 fn decode_dc_frame(dc_level: i32) -> Vec<u8> {
9099 let seq = sequence_64();
9100 let mut header = flat_key_frame();
9101 header.quantization.base_q_idx = Q_IDX;
9102 let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap();
9103 let mut stream = temporal_delimiter();
9104 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9105 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9106 ffmpeg_decode(&stream, 64, 64)
9107 }
9108
9109 /// What a reference decoder makes of each DC level at `base_q_idx` 100:
9110 /// the level times the DC quantiser, inverse-transformed over a whole
9111 /// 64x64 block — which spreads one coefficient over 4096 samples, so a
9112 /// level moves the picture by a sample or two, not by tens. These numbers
9113 /// are pinned from the decoder rather than derived: this crate has no
9114 /// inverse transform of its own yet to derive them with. What the test
9115 /// asserts around them — flat planes, untouched chroma, monotone in the
9116 /// level, and the sign going the right way — is derived, and it is what a
9117 /// desync in the coefficient syntax breaks first.
9118 const DECODED_AT_Q100: [(i32, u8); 28] = [
9119 (1, 128),
9120 (2, 128),
9121 (3, 129),
9122 (4, 129),
9123 (5, 129),
9124 (6, 129),
9125 (7, 129),
9126 (8, 129),
9127 (9, 130),
9128 (10, 130),
9129 (11, 130),
9130 (12, 130),
9131 (13, 130),
9132 (14, 131),
9133 (-1, 128),
9134 (-2, 128),
9135 (-3, 128),
9136 (-4, 127),
9137 (-5, 127),
9138 (-6, 127),
9139 (-7, 127),
9140 (-8, 127),
9141 (-9, 126),
9142 (-10, 126),
9143 (-11, 126),
9144 (-12, 126),
9145 (-13, 126),
9146 (-14, 126),
9147 ];
9148
9149 #[test]
9150 fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
9151 if !have_ffmpeg() {
9152 eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
9153 return;
9154 }
9155 let mut seen = Vec::new();
9156 for (level, want) in DECODED_AT_Q100 {
9157 let planes = decode_dc_frame(level);
9158 let (luma, chroma) = planes.split_at(64 * 64);
9159 for (i, &sample) in luma.iter().enumerate() {
9160 assert_eq!(sample, want, "luma sample {i} at dc level {level}");
9161 }
9162 // The chroma transform blocks are all-zero, so both planes stay at
9163 // the prediction. A desync in the luma coefficient syntax lands
9164 // here first: the chroma flags are the next symbols after it.
9165 for (i, &sample) in chroma.iter().enumerate() {
9166 assert_eq!(sample, 128, "chroma sample {i} at dc level {level}");
9167 }
9168 seen.push((level, want));
9169 }
9170 // The picture moves off mid-grey the way the level says: up for a
9171 // positive level, down for a negative one, and never back towards it
9172 // as the level grows.
9173 for w in seen.windows(2) {
9174 let ((prev_level, prev), (level, value)) = (w[0], w[1]);
9175 if prev_level.signum() != level.signum() {
9176 continue;
9177 }
9178 if level > 0 {
9179 assert!(
9180 value >= prev,
9181 "level {level} decoded below level {prev_level}"
9182 );
9183 assert!(value >= 128, "a positive level darkened the picture");
9184 } else {
9185 assert!(
9186 value <= prev,
9187 "level {level} decoded above level {prev_level}"
9188 );
9189 assert!(value <= 128, "a negative level brightened the picture");
9190 }
9191 }
9192 assert!(
9193 DECODED_AT_Q100.iter().any(|&(_, v)| v > 128)
9194 && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128),
9195 "the pinned table has to move the picture both ways"
9196 );
9197 }
9198
9199 /// Encode a grid of 64x64 superblocks, each carrying its own DC level, and
9200 /// hand back the decoded planes.
9201 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
9202 let (w, h) = (64 * sb_cols, 64 * sb_rows);
9203 let (seq, mut header) = frame_of(w, h);
9204 // The DC fixture writers code against the default CDFs and never
9205 // update them, so their frames say so.
9206 header.disable_cdf_update = true;
9207 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
9208 let mut stream = temporal_delimiter();
9209 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9210 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9211 ffmpeg_decode(&stream, w as usize, h as usize)
9212 }
9213
9214 /// A sequence and key frame header for a `w` by `h` frame of whole
9215 /// superblocks.
9216 fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) {
9217 let mut seq = sequence_64();
9218 seq.max_frame_width = w;
9219 seq.max_frame_height = h;
9220 let mut header = flat_key_frame();
9221 // Every tile these headers carry is written by the adapting writer.
9222 header.disable_cdf_update = false;
9223 header.frame_width = w;
9224 header.frame_height = h;
9225 header.upscaled_width = w;
9226 header.render_width = w;
9227 header.render_height = h;
9228 header.mi_cols = w / 4;
9229 header.mi_rows = h / 4;
9230 header.tile_info.mi_col_starts = vec![0, header.mi_cols];
9231 header.tile_info.mi_row_starts = vec![0, header.mi_rows];
9232 header.quantization.base_q_idx = Q_IDX;
9233 (seq, header)
9234 }
9235
9236 fn decoded_value(level: i32) -> u8 {
9237 DECODED_AT_Q100
9238 .iter()
9239 .find(|&&(l, _)| l == level)
9240 .map(|&(_, v)| v)
9241 .expect("the level is in the pinned table")
9242 }
9243
9244 /// `dc_predict` (spec 7.11.2) for the flat case: a block whose neighbours
9245 /// are themselves flat predicts their average, and predicts mid-grey with
9246 /// no neighbour at all. Every block here is a whole 64x64 superblock, so
9247 /// the above row and the left column weigh the same.
9248 fn dc_prediction(above: Option<u8>, left: Option<u8>) -> u8 {
9249 match (above, left) {
9250 (None, None) => 128,
9251 (Some(a), None) => a,
9252 (None, Some(l)) => l,
9253 (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8,
9254 }
9255 }
9256
9257 /// What a DC level adds to the prediction: the pinned table is that sum
9258 /// against a mid-grey prediction, and the residual does not depend on what
9259 /// it is added to.
9260 fn dc_residual(level: i32) -> i32 {
9261 i32::from(decoded_value(level)) - 128
9262 }
9263
9264 /// Every block reads its DC sign context off the coded blocks above and to
9265 /// its left, and the three ways that can land — no coded neighbour, the
9266 /// neighbours leaning one way, the neighbours cancelling — are only
9267 /// reachable in a frame whose levels differ in sign. Getting the context
9268 /// wrong desyncs the arithmetic decoder, so the check is that every block
9269 /// still decodes to the grey its own level asks for.
9270 #[test]
9271 fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {
9272 if !have_ffmpeg() {
9273 eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg");
9274 return;
9275 }
9276 // Read in raster order the two grids put a positive, a negative and a
9277 // cancelling sign context in front of the bottom-right block, and a
9278 // leaning-down one in front of the second grid's right and bottom
9279 // blocks.
9280 for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] {
9281 let planes = decode_level_grid(&levels, 2, 2);
9282 let (luma, chroma) = planes.split_at(128 * 128);
9283 // The blocks are not independent: a DC prediction reads the
9284 // reconstructed neighbours, so each block's grey is its
9285 // neighbours' average plus its own residual.
9286 let mut recon = [0u8; 4];
9287 for (block, level) in levels.iter().enumerate() {
9288 let (br, bc) = (block / 2, block % 2);
9289 let above = (br > 0).then(|| recon[block - 2]);
9290 let left = (bc > 0).then(|| recon[block - 1]);
9291 let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level))
9292 .clamp(0, 255) as u8;
9293 recon[block] = want;
9294 for y in 0..64 {
9295 for x in 0..64 {
9296 let i = (br * 64 + y) * 128 + bc * 64 + x;
9297 assert_eq!(
9298 luma[i], want,
9299 "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}"
9300 );
9301 }
9302 }
9303 }
9304 for (i, &sample) in chroma.iter().enumerate() {
9305 assert_eq!(sample, 128, "chroma sample {i} of {levels:?}");
9306 }
9307 }
9308 }
9309
9310 /// What a DC level adds to a 32x32 block's prediction at `base_q_idx` 100,
9311 /// pinned from the decoder the way [`DECODED_AT_Q100`] is. A 32x32
9312 /// transform spreads its DC over a quarter of the samples a 64x64 one
9313 /// does, so the same level moves the picture further: level 14 is five
9314 /// sample values here against three there.
9315 const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [
9316 (1, 0),
9317 (2, 1),
9318 (3, 1),
9319 (4, 1),
9320 (5, 2),
9321 (6, 2),
9322 (7, 3),
9323 (8, 3),
9324 (9, 3),
9325 (10, 4),
9326 (11, 4),
9327 (12, 4),
9328 (13, 5),
9329 (14, 5),
9330 (-1, 0),
9331 (-2, -1),
9332 (-3, -1),
9333 (-4, -1),
9334 (-5, -2),
9335 (-6, -2),
9336 (-7, -2),
9337 (-8, -3),
9338 (-9, -3),
9339 (-10, -4),
9340 (-11, -4),
9341 (-12, -4),
9342 (-13, -5),
9343 (-14, -5),
9344 ];
9345
9346 fn split_residual(level: i32) -> i32 {
9347 SPLIT_RESIDUAL_AT_Q100
9348 .iter()
9349 .find(|&&(l, _)| l == level)
9350 .map(|&(_, r)| r)
9351 .expect("the level is in the pinned table")
9352 }
9353
9354 /// Splitting a superblock puts three more syntax elements in front of every
9355 /// block — the split partition itself, the 32x32 partition below it and a
9356 /// chroma mode from the wider table CFL-capable blocks read — and moves the
9357 /// coefficients onto the 32x32 CDFs. Getting any of them wrong desyncs the
9358 /// arithmetic decoder, and the check is that all sixteen blocks still land
9359 /// on the grey their own level and their neighbours ask for.
9360 #[test]
9361 fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
9362 if !have_ffmpeg() {
9363 eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
9364 return;
9365 }
9366 // Four by four 32x32 blocks over two by two superblocks, so the walk
9367 // crosses superblock boundaries in both directions, and signs that
9368 // alternate so the DC sign context lands on all three of its values.
9369 let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1];
9370 let planes = decode_split_grid(&levels, 2, 2);
9371 let (luma, chroma) = planes.split_at(128 * 128);
9372
9373 let mut recon = [0i32; 16];
9374 for (block, level) in levels.iter().enumerate() {
9375 let (br, bc) = (block / 4, block % 4);
9376 let above = (br > 0).then(|| recon[block - 4] as u8);
9377 let left = (bc > 0).then(|| recon[block - 1] as u8);
9378 let want =
9379 (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255);
9380 recon[block] = want;
9381 for y in 0..32 {
9382 for x in 0..32 {
9383 let i = (br * 32 + y) * 128 + bc * 32 + x;
9384 assert_eq!(
9385 i32::from(luma[i]),
9386 want,
9387 "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \
9388 column {bc}"
9389 );
9390 }
9391 }
9392 }
9393 for (i, &sample) in chroma.iter().enumerate() {
9394 assert_eq!(sample, 128, "chroma sample {i}");
9395 }
9396 }
9397
9398 /// Encode a grid of 32x32 blocks, each carrying its own DC level.
9399 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
9400 let (w, h) = (64 * sb_cols, 64 * sb_rows);
9401 let (seq, mut header) = frame_of(w, h);
9402 // The DC fixture writers code against the default CDFs and never
9403 // update them, so their frames say so.
9404 header.disable_cdf_update = true;
9405 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
9406 let mut stream = temporal_delimiter();
9407 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9408 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9409 ffmpeg_decode(&stream, w as usize, h as usize)
9410 }
9411
9412 #[test]
9413 fn a_level_grid_that_does_not_cover_the_frame_is_refused() {
9414 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err());
9415 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err());
9416 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());
9417 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());
9418 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());
9419 }
9420
9421 #[test]
9422 fn dc_levels_the_base_syntax_cannot_carry_are_refused() {
9423 assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());
9424 assert!(dc_key_frame_tile(16, 16, 100, 15).is_err());
9425 assert!(dc_key_frame_tile(16, 16, 100, -15).is_err());
9426 }
9427
9428 #[test]
9429 fn partial_superblocks_are_refused() {
9430 assert!(flat_key_frame_tile(16, 20).is_err());
9431 assert!(flat_key_frame_tile(0, 16).is_err());
9432 }
9433
9434 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
9435 /// hands back the luma plane as rows of samples.
9436 fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {
9437 let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect();
9438 let [luma, u, v] = decode_coeff_planes(&blocks);
9439 for (name, plane) in [("U", &u), ("V", &v)] {
9440 for (y, row) in plane.iter().enumerate() {
9441 for (x, &s) in row.iter().enumerate() {
9442 assert_eq!(
9443 s, 128,
9444 "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \
9445 DC prediction with no coded neighbour is mid-grey"
9446 );
9447 }
9448 }
9449 }
9450 luma
9451 }
9452
9453 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
9454 /// hands back its three planes as rows of samples: 64 rows of luma and, at
9455 /// 4:2:0, 32 rows of each chroma plane.
9456 fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] {
9457 let (seq, header) = frame_of(64, 64);
9458 let tile =
9459 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
9460 let mut stream = temporal_delimiter();
9461 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9462 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9463 let planes = ffmpeg_decode(&stream, 64, 64);
9464 let (luma, chroma) = planes.split_at(64 * 64);
9465 let (u, v) = chroma.split_at(32 * 32);
9466 [
9467 luma.chunks_exact(64).map(<[u8]>::to_vec).collect(),
9468 u.chunks_exact(32).map(<[u8]>::to_vec).collect(),
9469 v.chunks_exact(32).map(<[u8]>::to_vec).collect(),
9470 ]
9471 }
9472
9473 /// The top-left 32x32 block of a decoded frame, which is the only one whose
9474 /// prediction has no neighbour to lean on.
9475 fn top_left_block(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
9476 rows[..32].iter().map(|r| r[..32].to_vec()).collect()
9477 }
9478
9479 /// A transform's basis functions all average to zero except the DC's, so a
9480 /// block carrying no DC decodes to samples that average to its prediction —
9481 /// mid-grey for the block with no neighbours. Rounding of the inverse
9482 /// transform moves the average by less than a sample.
9483 fn assert_mean_is_mid_grey(block: &[Vec<u8>]) {
9484 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
9485 let mean = f64::from(sum) / (32.0 * 32.0);
9486 assert!(
9487 (mean - 128.0).abs() <= 1.0,
9488 "a block with no DC coefficient averages to its mid-grey prediction, got {mean}"
9489 );
9490 }
9491
9492 /// A coefficient at row 0, column 1 selects the basis function that is flat
9493 /// down the block and a half-cycle of a cosine across it. Nothing about
9494 /// that shape is pinned here: every row of the block must be the same row,
9495 /// the samples must fall from left to right and actually move, and the
9496 /// block must still average to its prediction. A desync in the scan, the
9497 /// end-of-block position or the level contexts breaks one of those.
9498 #[test]
9499 fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
9500 if !have_ffmpeg() {
9501 eprintln!(
9502 "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg"
9503 );
9504 return;
9505 }
9506 let blocks = vec![
9507 vec![Coeff {
9508 row: 0,
9509 col: 1,
9510 level: 12,
9511 }],
9512 Vec::new(),
9513 Vec::new(),
9514 Vec::new(),
9515 ];
9516 let rows = decode_coeff_quadrants(&blocks);
9517 let block = top_left_block(&rows);
9518
9519 for (y, row) in block.iter().enumerate() {
9520 assert_eq!(row, &block[0], "row {y} of a horizontal basis function");
9521 }
9522 assert!(
9523 block[0][0] > block[0][31],
9524 "a positive coefficient leans the block towards its left edge: {:?}",
9525 block[0]
9526 );
9527 for x in 1..32 {
9528 assert!(
9529 block[0][x] <= block[0][x - 1],
9530 "the half-cycle falls from left to right, broke at column {x}: {:?}",
9531 block[0]
9532 );
9533 }
9534 assert_mean_is_mid_grey(&block);
9535
9536 // The same coefficient transposed selects the basis function that is
9537 // flat across the block and a half-cycle down it.
9538 let blocks = vec![
9539 vec![Coeff {
9540 row: 1,
9541 col: 0,
9542 level: 12,
9543 }],
9544 Vec::new(),
9545 Vec::new(),
9546 Vec::new(),
9547 ];
9548 let rows = decode_coeff_quadrants(&blocks);
9549 let block = top_left_block(&rows);
9550 for (y, row) in block.iter().enumerate() {
9551 for (x, &s) in row.iter().enumerate() {
9552 assert_eq!(s, row[0], "sample ({y},{x}) of a vertical basis function");
9553 }
9554 }
9555 assert!(
9556 block[0][0] > block[31][0],
9557 "a positive coefficient leans the block up"
9558 );
9559 for y in 1..32 {
9560 assert!(
9561 block[y][0] <= block[y - 1][0],
9562 "the half-cycle falls from top to bottom, broke at row {y}"
9563 );
9564 }
9565 assert_mean_is_mid_grey(&block);
9566 }
9567
9568 /// A coefficient late in the scan pushes the end-of-block position into a
9569 /// group that carries an offset — the far corner of a 32x32 transform is
9570 /// the last of the eleven groups, whose offset is nine bits wide, one of
9571 /// them from a CDF and the rest raw. Every coefficient before it is coded
9572 /// too, so this also walks the base and base-range contexts over a block
9573 /// with neighbours that carry levels rather than zeros.
9574 #[test]
9575 fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {
9576 if !have_ffmpeg() {
9577 eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group");
9578 return;
9579 }
9580 let block = vec![
9581 Coeff {
9582 row: 31,
9583 col: 31,
9584 level: 5,
9585 },
9586 Coeff {
9587 row: 5,
9588 col: 7,
9589 level: -9,
9590 },
9591 Coeff {
9592 row: 1,
9593 col: 1,
9594 level: 14,
9595 },
9596 Coeff {
9597 row: 0,
9598 col: 2,
9599 level: -3,
9600 },
9601 Coeff {
9602 row: 2,
9603 col: 0,
9604 level: 2,
9605 },
9606 Coeff {
9607 row: 1,
9608 col: 2,
9609 level: -1,
9610 },
9611 ];
9612 let rows = decode_coeff_quadrants(&[block, Vec::new(), Vec::new(), Vec::new()]);
9613 let block = top_left_block(&rows);
9614 assert_mean_is_mid_grey(&block);
9615 assert!(
9616 block.iter().flatten().any(|&s| s != block[0][0]),
9617 "six coefficients do not decode to a flat block"
9618 );
9619 // The blocks that carry nothing are flat: their prediction is whatever
9620 // their neighbours left, and they add no residual to it.
9621 for (name, ys, xs) in [("top right", 0..32, 32..64), ("bottom left", 32..64, 0..32)] {
9622 let first = rows[ys.start][xs.start];
9623 for y in ys {
9624 for x in xs.clone() {
9625 assert_eq!(rows[y][x], first, "the {name} block carries no coefficient");
9626 }
9627 }
9628 }
9629 }
9630
9631 /// The price the mode search pays for a block's levels has to be the price
9632 /// the writer charges for them, or the search is ranking modes by a
9633 /// fiction. Both halves are asked for the same grids under the same
9634 /// neutral contexts, and the priced bits are compared against the bytes
9635 /// the writer really spends.
9636 #[test]
9637 fn the_priced_coefficient_bits_match_the_bytes_written() {
9638 let scan = default_scan(TX32);
9639 // Three grids that reach different parts of the syntax: a lone DC, a
9640 // sparse spread of small levels with both signs, and levels past the
9641 // base-range alphabet so the Golomb tail runs.
9642 let mut grids = vec![vec![0i32; TX32 * TX32]; 3];
9643 grids[0][0] = -7;
9644 for (i, &pos) in scan.iter().enumerate().take(400) {
9645 if i % 7 == 0 {
9646 grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 };
9647 }
9648 }
9649 grids[2][0] = 40;
9650 for (i, &pos) in scan.iter().enumerate().take(64) {
9651 grids[2][pos as usize] += i as i32 % 23 - 11;
9652 }
9653
9654 // A single block is too short for the coder's own flush to average
9655 // out, so all three go through one encoder and one flush.
9656 let mut enc = SymbolEncoder::new();
9657 let mut priced = 0.0;
9658 for grid in &grids {
9659 write_coeffs(
9660 &mut enc,
9661 &mut Cdfs::new(2).txb(TxbSet::Luma32, 0),
9662 grid,
9663 &scan,
9664 0,
9665 0,
9666 None,
9667 TxType::DctDct,
9668 );
9669 priced += luma_32_coeff_bits(grid);
9670 }
9671 let spent = enc.finish().len() as f64 * 8.0;
9672 assert!(
9673 (priced - spent).abs() / spent < 0.02,
9674 "priced {priced} bits, wrote {spent}"
9675 );
9676 }
9677
9678 /// A rate term the search can read as constant is a rate term that ranks
9679 /// nothing, so the price is checked to move the way the levels move: an
9680 /// empty block is the cheapest thing there is, one coefficient costs more
9681 /// than none, and both spreading the coefficients and growing them costs
9682 /// more again.
9683 #[test]
9684 fn the_price_grows_with_the_levels() {
9685 let grid = |f: &dyn Fn(&mut Vec<i32>)| {
9686 let mut g = vec![0i32; TX32 * TX32];
9687 f(&mut g);
9688 luma_32_coeff_bits(&g)
9689 };
9690 let empty = grid(&|_| {});
9691 let one = grid(&|g| g[0] = 1);
9692 let bigger = grid(&|g| g[0] = 30);
9693 let spread = grid(&|g| {
9694 for i in 0..TX32 {
9695 g[i * TX32 + i] = 1;
9696 }
9697 });
9698 assert!(empty < one, "{empty} {one}");
9699 assert!(one < bigger, "{one} {bigger}");
9700 assert!(one < spread, "{one} {spread}");
9701 // An empty block is one symbol -- an expensive one, because a block
9702 // with no coefficients at all is the rarer of the two under the
9703 // neutral context -- and nothing else.
9704 assert!(
9705 empty < 6.0,
9706 "an empty block is one skip symbol, not {empty}"
9707 );
9708 }
9709
9710 /// Neighbouring blocks that each carry coefficients read their DC sign
9711 /// context, their prediction and their own contexts off each other, so a
9712 /// frame whose four blocks all carry mixed-sign coefficients exercises what
9713 /// a single coded block cannot. The check is that it decodes at all — a
9714 /// desync anywhere fails the decode or the frame size — and that the block
9715 /// with no neighbours still averages to mid-grey.
9716 #[test]
9717 fn every_quadrant_carries_its_own_coefficients() {
9718 if !have_ffmpeg() {
9719 eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg");
9720 return;
9721 }
9722 let blocks = vec![
9723 vec![
9724 Coeff {
9725 row: 0,
9726 col: 1,
9727 level: 7,
9728 },
9729 Coeff {
9730 row: 3,
9731 col: 4,
9732 level: -14,
9733 },
9734 ],
9735 vec![
9736 Coeff {
9737 row: 0,
9738 col: 0,
9739 level: -6,
9740 },
9741 Coeff {
9742 row: 2,
9743 col: 2,
9744 level: 9,
9745 },
9746 ],
9747 vec![
9748 Coeff {
9749 row: 0,
9750 col: 0,
9751 level: 6,
9752 },
9753 Coeff {
9754 row: 1,
9755 col: 0,
9756 level: -2,
9757 },
9758 Coeff {
9759 row: 8,
9760 col: 9,
9761 level: 3,
9762 },
9763 ],
9764 vec![
9765 Coeff {
9766 row: 0,
9767 col: 0,
9768 level: 11,
9769 },
9770 Coeff {
9771 row: 16,
9772 col: 1,
9773 level: -4,
9774 },
9775 ],
9776 ];
9777 let rows = decode_coeff_quadrants(&blocks);
9778 assert_mean_is_mid_grey(&top_left_block(&rows));
9779 for (name, ys, xs) in [
9780 ("top right", 0..32, 32..64),
9781 ("bottom left", 32..64, 0..32),
9782 ("bottom right", 32..64, 32..64),
9783 ] {
9784 let block: Vec<Vec<u8>> = rows[ys].iter().map(|r| r[xs.clone()].to_vec()).collect();
9785 assert!(
9786 block.iter().flatten().any(|&s| s != block[0][0]),
9787 "the {name} block carries coefficients, so it is not flat"
9788 );
9789 }
9790 }
9791
9792 /// The top-left 16x16 block of a decoded chroma plane, which is the only
9793 /// one whose prediction has no neighbour to lean on.
9794 fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
9795 rows[..16].iter().map(|r| r[..16].to_vec()).collect()
9796 }
9797
9798 /// The mean of a decoded block, which every basis function but the DC's
9799 /// leaves at the block's prediction.
9800 fn mean(block: &[Vec<u8>]) -> f64 {
9801 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
9802 let count = block.iter().map(Vec::len).sum::<usize>() as f64;
9803 f64::from(sum) / count
9804 }
9805
9806 /// A chroma plane's coefficients ride their own transform, their own CDFs
9807 /// and their own end-of-block alphabet, so a chroma basis function is the
9808 /// gate on all three: U carries the coefficient that is flat down the block
9809 /// and a half-cycle across it, V the one turned a quarter turn, and neither
9810 /// may reach the other plane or luma.
9811 #[test]
9812 fn each_chroma_plane_codes_its_own_basis_function() {
9813 if !have_ffmpeg() {
9814 eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
9815 return;
9816 }
9817 let mut blocks = vec![BlockCoeffs::default(); 4];
9818 blocks[0].u = vec![Coeff {
9819 row: 0,
9820 col: 1,
9821 level: 12,
9822 }];
9823 blocks[0].v = vec![Coeff {
9824 row: 1,
9825 col: 0,
9826 level: 12,
9827 }];
9828 let [luma, u, v] = decode_coeff_planes(&blocks);
9829
9830 for (y, row) in luma.iter().enumerate() {
9831 for (x, &s) in row.iter().enumerate() {
9832 assert_eq!(
9833 s, 128,
9834 "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \
9835 stays at its mid-grey prediction"
9836 );
9837 }
9838 }
9839
9840 let u_block = top_left_chroma(&u);
9841 for (y, row) in u_block.iter().enumerate() {
9842 assert_eq!(
9843 row, &u_block[0],
9844 "row {y} of a horizontal chroma basis function"
9845 );
9846 }
9847 assert!(
9848 u_block[0][0] > u_block[0][15],
9849 "a positive coefficient leans the U block towards its left edge: {:?}",
9850 u_block[0]
9851 );
9852
9853 let v_block = top_left_chroma(&v);
9854 for (x, &top) in v_block[0].iter().enumerate() {
9855 assert_eq!(
9856 top, v_block[0][0],
9857 "column {x} of a vertical chroma basis function"
9858 );
9859 let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect();
9860 assert!(
9861 column[0] > column[15],
9862 "a positive coefficient leans the V column towards its top edge: {column:?}"
9863 );
9864 }
9865
9866 for (name, block) in [("U", &u_block), ("V", &v_block)] {
9867 let mean = mean(block);
9868 assert!(
9869 (mean - 128.0).abs() <= 1.0,
9870 "the {name} block carries no DC, so it averages to its mid-grey prediction, \
9871 got {mean}"
9872 );
9873 }
9874 }
9875
9876 /// Every block coding chroma puts the chroma all-zero flag on the contexts
9877 /// a coded neighbour above and to the left select, and the DC sign on the
9878 /// contexts their signs select. A frame whose four blocks all carry chroma
9879 /// DCs of mixed sign walks those contexts; the picture that comes back must
9880 /// still lean the way each block's own DC asks.
9881 #[test]
9882 fn chroma_dc_signs_read_their_neighbours() {
9883 if !have_ffmpeg() {
9884 eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
9885 return;
9886 }
9887 let dc = |level| {
9888 vec![Coeff {
9889 row: 0,
9890 col: 0,
9891 level,
9892 }]
9893 };
9894 let signs = [8, -8, -8, 8];
9895 let blocks: Vec<BlockCoeffs> = signs
9896 .iter()
9897 .map(|&level| BlockCoeffs {
9898 luma: Vec::new(),
9899 u: dc(level),
9900 v: dc(-level),
9901 ..BlockCoeffs::default()
9902 })
9903 .collect();
9904 let [luma, u, v] = decode_coeff_planes(&blocks);
9905
9906 for (y, row) in luma.iter().enumerate() {
9907 for (x, &s) in row.iter().enumerate() {
9908 assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient");
9909 }
9910 }
9911
9912 // A DC prediction leans on the neighbours a block has, so each block is
9913 // measured against the prediction it was given rather than mid-grey:
9914 // the only block with no neighbour is the first, and the rest are read
9915 // as a step away from the block above them and to their left.
9916 for (i, &level) in signs.iter().enumerate() {
9917 let (r, c) = (i / 2, i % 2);
9918 let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> {
9919 plane[r * 16..r * 16 + 16]
9920 .iter()
9921 .map(|row| row[c * 16..c * 16 + 16].to_vec())
9922 .collect()
9923 };
9924 for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] {
9925 let block = block(plane);
9926 let mean = mean(&block);
9927 for (y, row) in block.iter().enumerate() {
9928 assert_eq!(
9929 row.iter().collect::<std::collections::HashSet<_>>().len(),
9930 1,
9931 "row {y} of a DC-only {name} block is flat"
9932 );
9933 }
9934 if i == 0 {
9935 assert!(
9936 (want > 0) == (mean > 128.0),
9937 "{name} block {i} carries a DC of {want}, so it must lean off its \
9938 mid-grey prediction that way, got {mean}"
9939 );
9940 }
9941 }
9942 }
9943 assert_ne!(u, v, "the two chroma planes carry opposite DCs");
9944 }
9945
9946 /// The coefficient writer refuses what it cannot code rather than writing a
9947 /// stream a decoder walks off the end of.
9948 /// The 32x32 block at the given block row and column of a decoded plane.
9949 fn block_at(rows: &[Vec<u8>], block_row: usize, block_col: usize) -> Vec<Vec<u8>> {
9950 rows[block_row * 32..block_row * 32 + 32]
9951 .iter()
9952 .map(|r| r[block_col * 32..block_col * 32 + 32].to_vec())
9953 .collect()
9954 }
9955
9956 /// Encodes a key frame of the given size, whose 32x32 blocks carry
9957 /// `blocks` in raster order, and hands back its luma plane as rows of
9958 /// The neighbour context a block reads is gathered across every cell it
9959 /// spans, not taken from the first one: a 32x32 block whose left-hand
9960 /// neighbour cells disagree still sees the coded one. Reading a single
9961 /// cell agreed with the decoder only while every block was the same size,
9962 /// and desynchronised the arithmetic decoder the moment a 16x16 one
9963 /// appeared beside a 32x32 one.
9964 #[test]
9965 fn a_block_gathers_the_cells_its_neighbours_cover() {
9966 let mut neighbours = Neighbours::new(4, 4, 64, 64);
9967 let quiet = [
9968 vec![0i32; TX16 * TX16],
9969 vec![0; TX8 * TX8],
9970 vec![0; TX8 * TX8],
9971 ];
9972 let mut loud = quiet.clone();
9973 loud[1][0] = -3;
9974 // Two 16x16 blocks above the right-hand 32x32 block of the row, of
9975 // which only the second codes anything.
9976 neighbours.record((0, 2), SUB, DC_PRED, &quiet);
9977 neighbours.record((0, 3), SUB, DC_PRED, &loud);
9978 let around = neighbours.around((2, 2), BLOCK);
9979 assert!(
9980 around[1].above_coded,
9981 "the coded cell has to reach the block below it"
9982 );
9983 assert_eq!(
9984 dc_sign_ctx(around[1].dc_vote),
9985 1,
9986 "the one negative DC above the block is what it votes"
9987 );
9988 // The same read one cell at a time misses it, which is the bug this
9989 // gate is here for. `above[8]` is the first 4x4 unit the quiet block
9990 // at `(0, 2)` wrote (2 SUB units * 4 4x4-units-per-SUB).
9991 assert!(!neighbours.above[8][1].coded);
9992 }
9993
9994 /// samples.
9995 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
9996 let (seq, header) = frame_of(width as u32, height as u32);
9997 let tile =
9998 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
9999 let mut stream = temporal_delimiter();
10000 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
10001 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
10002 let planes = ffmpeg_decode(&stream, width, height);
10003 planes[..width * height]
10004 .chunks_exact(width)
10005 .map(<[u8]>::to_vec)
10006 .collect()
10007 }
10008
10009 /// Every row of a block is the same row, and that row falls from left to
10010 /// right — the shape of a coefficient at row 0, column 1.
10011 fn assert_falls_across(block: &[Vec<u8>], name: &str) {
10012 for row in block {
10013 assert_eq!(
10014 row, &block[0],
10015 "{name}: every row of the block is the same row"
10016 );
10017 }
10018 assert!(
10019 block[0][0] > block[0][31],
10020 "{name}: the row falls from left to right, got {} then {}",
10021 block[0][0],
10022 block[0][31]
10023 );
10024 }
10025
10026 /// Every column of a block is constant across it and falls down it — the
10027 /// shape of a coefficient at row 1, column 0.
10028 fn assert_falls_down(block: &[Vec<u8>], name: &str) {
10029 for (y, row) in block.iter().enumerate() {
10030 assert!(
10031 row.iter().all(|&s| s == row[0]),
10032 "{name}: row {y} of the block is one constant"
10033 );
10034 }
10035 assert!(
10036 block[0][0] > block[31][0],
10037 "{name}: the column falls down the block, got {} then {}",
10038 block[0][0],
10039 block[31][0]
10040 );
10041 }
10042
10043 /// The mean sample of a decoded block.
10044 fn mean_of(block: &[Vec<u8>]) -> f64 {
10045 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
10046 f64::from(sum) / (block.len() * block[0].len()) as f64
10047 }
10048
10049 /// The top-left block of a frame whose only coefficient is a luma DC of
10050 /// `level`.
10051 fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> {
10052 let blocks = vec![
10053 vec![Coeff {
10054 row: 0,
10055 col: 0,
10056 level,
10057 }],
10058 Vec::new(),
10059 Vec::new(),
10060 Vec::new(),
10061 ];
10062 top_left_block(&decode_coeff_quadrants(&blocks))
10063 }
10064
10065 /// `read_golomb` (spec 5.11.40), written from the specification's
10066 /// pseudocode, and the level its caller builds from it: a level above the
10067 /// base-range tail is fifteen plus what the tail carries.
10068 fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 {
10069 let mut length = 0;
10070 while dec.literal(1) == 0 {
10071 length += 1;
10072 assert!(
10073 length < 20,
10074 "the tail's length prefix runs past twenty bits"
10075 );
10076 }
10077 let mut x = 1;
10078 for _ in 0..length {
10079 x = (x << 1) | dec.literal(1);
10080 }
10081 (MAX_BR_LEVEL + 1) as u32 + (x - 1)
10082 }
10083
10084 /// The tail says how much of the level the base and base-range syntax could
10085 /// not carry, and the spec's own reader must hand back the level that was
10086 /// asked for — not one either side of it. A tail written a bit long, a bit
10087 /// short, or against the wrong base fails this at the first level it
10088 /// reaches.
10089 #[test]
10090 fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
10091 for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300)
10092 .chain([MAX_LEVEL - 1, MAX_LEVEL])
10093 .map(|l| l as u32)
10094 {
10095 let mut enc = SymbolEncoder::new();
10096 write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32);
10097 // The tail is raw bits, so it needs no padding beyond what the
10098 // encoder's own flush writes.
10099 let data = enc.finish();
10100 let mut dec = crate::msac::tests::SymbolDecoder::new(&data);
10101 assert_eq!(
10102 read_golomb_level(&mut dec),
10103 level,
10104 "the tail of level {level}"
10105 );
10106 }
10107 }
10108
10109 /// The base and base-range syntax reach level fourteen between them;
10110 /// anything above that carries the rest of itself as a Golomb tail, written
10111 /// after its own sign. A DC level moves the whole block off its mid-grey
10112 /// prediction by an amount that grows with the level, so a run of levels
10113 /// either side of the tail's threshold — spaced wide enough that the
10114 /// quantiser separates them — must decode to a run of steadily
10115 /// brighter blocks — and the negatives of the same levels to steadily
10116 /// darker ones. A tail written with the wrong length, in the wrong place in
10117 /// the syntax, or off by one desyncs the decoder outright.
10118 #[test]
10119 fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
10120 if !have_ffmpeg() {
10121 eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
10122 return;
10123 }
10124 let mut brighter = Vec::new();
10125 let mut darker = Vec::new();
10126 for level in [10, 14, 18, 31, 60, 400] {
10127 brighter.push((level, mean_of(&decode_dc_level_block(level))));
10128 darker.push((level, mean_of(&decode_dc_level_block(-level))));
10129 }
10130 for pair in brighter.windows(2) {
10131 let [(low, dim), (high, bright)] = [pair[0], pair[1]];
10132 assert!(
10133 bright > dim,
10134 "level {high} decodes brighter than level {low}, got {bright} against {dim}"
10135 );
10136 }
10137 for pair in darker.windows(2) {
10138 let [(low, bright), (high, dim)] = [pair[0], pair[1]];
10139 assert!(
10140 dim < bright,
10141 "level -{high} decodes darker than level -{low}, got {dim} against {bright}"
10142 );
10143 }
10144 let (_, mid) = brighter[0];
10145 assert!(
10146 mid > 128.0 && darker[0].1 < 128.0,
10147 "a positive level brightens its block and a negative one darkens it, got {mid} and {}",
10148 darker[0].1
10149 );
10150 }
10151
10152 /// A frame need not be a whole number of superblocks. A 96x64 frame is a
10153 /// superblock and a half across: the second superblock has no right-hand
10154 /// half, so its partition is a gathered flag rather than the full symbol,
10155 /// and the two blocks that would sit in that half are never coded at all.
10156 /// Each of the six blocks that do exist carries one of two basis functions,
10157 /// alternating, so a block written into the wrong place or a flag the
10158 /// decoder reads as a different number of bits shows up as a block with the
10159 /// other block's shape — or as a decode failure.
10160 fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8>> {
10161 let (seq, header) = frame_of(width as u32, height as u32);
10162 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap();
10163 let mut stream = temporal_delimiter();
10164 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
10165 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
10166 let planes = ffmpeg_decode(&stream, width, height);
10167 planes[..width * height]
10168 .chunks_exact(width)
10169 .map(<[u8]>::to_vec)
10170 .collect()
10171 }
10172
10173 /// A superblock left whole carries one 64x64 transform, whose lowest
10174 /// horizontal basis function falls across the whole sixty-four samples in
10175 /// one stroke. Were the same superblock split, each half would restart the
10176 /// gradient at its own left edge and the picture would rise again in the
10177 /// middle, so the walk across the row is what tells the two apart — and
10178 /// the split superblock beside it proves the two partitions still agree on
10179 /// where the next one begins.
10180 #[test]
10181 fn a_whole_superblock_covers_all_four_of_its_quadrants() {
10182 if !have_ffmpeg() {
10183 eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg");
10184 return;
10185 }
10186 let across = BlockCoeffs::from(vec![Coeff {
10187 row: 0,
10188 col: 1,
10189 level: 20,
10190 }]);
10191 let down = BlockCoeffs::from(vec![Coeff {
10192 row: 1,
10193 col: 0,
10194 level: 20,
10195 }]);
10196 let sbs = [
10197 Superblock::Whole(across),
10198 Superblock::Split(vec![
10199 Quadrant::Whole(down.clone()),
10200 Quadrant::Whole(down.clone()),
10201 Quadrant::Whole(down.clone()),
10202 Quadrant::Whole(down),
10203 ]),
10204 ];
10205 let rows = decode_luma_sb(128, 64, &sbs);
10206
10207 for (y, row) in rows.iter().enumerate() {
10208 assert_eq!(
10209 &row[..64],
10210 &rows[0][..64],
10211 "row {y} of the whole superblock repeats its first row"
10212 );
10213 }
10214 let first = &rows[0][..64];
10215 assert!(
10216 first.windows(2).all(|w| w[0] >= w[1]),
10217 "the whole superblock falls across its sixty-four samples without \
10218 restarting: {first:?}"
10219 );
10220 assert!(
10221 first[0] > first[63],
10222 "the whole superblock falls from left to right, got {} then {}",
10223 first[0],
10224 first[63]
10225 );
10226 for block_row in 0..2 {
10227 for block_col in 2..4 {
10228 let block = block_at(&rows, block_row, block_col);
10229 assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})"));
10230 }
10231 }
10232 }
10233
10234 /// A quadrant may be split again into four 16x16 blocks, each carrying its
10235 /// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block
10236 /// makes each of the four a flat grey of its own, so the quadrant reads as
10237 /// four squares rather than one — which is what tells the extra split from
10238 /// a 32x32 block that merely carries the same coefficients.
10239 #[test]
10240 fn a_quadrant_splits_into_four_sixteens() {
10241 if !have_ffmpeg() {
10242 eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
10243 return;
10244 }
10245 let dc = |level: i32| {
10246 BlockCoeffs::from(vec![Coeff {
10247 row: 0,
10248 col: 0,
10249 level,
10250 }])
10251 };
10252 let levels = [14, 8, -8, -14];
10253 let flat = BlockCoeffs::from(Vec::new());
10254 let sbs = [Superblock::Split(vec![
10255 Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()),
10256 Quadrant::Whole(flat.clone()),
10257 Quadrant::Whole(flat.clone()),
10258 Quadrant::Whole(flat),
10259 ])];
10260 let rows = decode_luma_sb(64, 64, &sbs);
10261
10262 let mut greys = Vec::new();
10263 for i in 0..levels.len() {
10264 let (y0, x0) = ((i / 2) * 16, (i % 2) * 16);
10265 let grey = rows[y0][x0];
10266 for (y, row) in rows.iter().enumerate().skip(y0).take(16) {
10267 for (x, &sample) in row.iter().enumerate().skip(x0).take(16) {
10268 assert_eq!(
10269 sample, grey,
10270 "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not"
10271 );
10272 }
10273 }
10274 greys.push(grey);
10275 }
10276
10277 // Each block is predicted DC from the blocks the decoder has already
10278 // rebuilt, so what its own level does is move it off that prediction,
10279 // in the level's own direction.
10280 let g = |i: usize| i32::from(greys[i]);
10281 let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2];
10282 for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() {
10283 assert_eq!(
10284 (g(i) - prediction).signum(),
10285 level.signum(),
10286 "the 16x16 block {i} carries level {level}, so it sits on the \
10287 {} side of the {prediction} its neighbours predict, not at {}",
10288 if level > 0 { "bright" } else { "dark" },
10289 g(i)
10290 );
10291 }
10292 assert_eq!(
10293 greys.iter().collect::<std::collections::HashSet<_>>().len(),
10294 4,
10295 "the four blocks are four different greys, not one: {greys:?}"
10296 );
10297 }
10298
10299 /// A superblock half outside the frame has no partition that keeps a block
10300 /// outside it, so it cannot be left whole.
10301 #[test]
10302 fn a_whole_superblock_at_the_frame_edge_is_refused() {
10303 let block = BlockCoeffs::from(vec![Coeff {
10304 row: 0,
10305 col: 0,
10306 level: 4,
10307 }]);
10308 let sbs = [
10309 Superblock::Split(vec![
10310 Quadrant::Whole(block.clone()),
10311 Quadrant::Whole(block.clone()),
10312 Quadrant::Whole(block.clone()),
10313 Quadrant::Whole(block.clone()),
10314 ]),
10315 Superblock::Whole(block.clone()),
10316 ];
10317 // Ninety-six samples across is three 32x32 blocks, so the second
10318 // superblock hangs half outside the frame.
10319 let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err();
10320 assert!(
10321 format!("{err}").contains("half outside the frame"),
10322 "got {err}"
10323 );
10324 }
10325
10326 #[test]
10327 fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
10328 if !have_ffmpeg() {
10329 eprintln!(
10330 "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \
10331 ffmpeg"
10332 );
10333 return;
10334 }
10335 let blocks: Vec<BlockCoeffs> = (0..6)
10336 .map(|i| {
10337 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
10338 BlockCoeffs::from(vec![Coeff {
10339 row,
10340 col,
10341 level: 12,
10342 }])
10343 })
10344 .collect();
10345 let rows = decode_luma_at(96, 64, &blocks);
10346 for block_row in 0..2 {
10347 for block_col in 0..3 {
10348 let name = format!("block ({block_row},{block_col})");
10349 let block = block_at(&rows, block_row, block_col);
10350 if (block_row * 3 + block_col) % 2 == 0 {
10351 assert_falls_across(&block, &name);
10352 } else {
10353 assert_falls_down(&block, &name);
10354 }
10355 }
10356 }
10357 }
10358
10359 /// The transpose of [`a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block`]:
10360 /// an odd number of 32x32 block *rows* (superblock hangs off the
10361 /// *bottom*, `has_cols=true, has_rows=false`) rather than an odd number of
10362 /// columns (hangs off the *right*, `has_cols=false, has_rows=true`) --
10363 /// the two halves of the `(has_cols, has_rows)` match in
10364 /// `sb_coeff_key_frame_tile` gather from different tables
10365 /// (`VERT_ALIKE`/`HORZ_ALIKE`), and only the right-hand-edge direction had
10366 /// a real-decoder test before this one.
10367 #[test]
10368 fn a_frame_that_hangs_off_the_bottom_codes_every_block() {
10369 if !have_ffmpeg() {
10370 eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg");
10371 return;
10372 }
10373 let blocks: Vec<BlockCoeffs> = (0..6)
10374 .map(|i| {
10375 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
10376 BlockCoeffs::from(vec![Coeff {
10377 row,
10378 col,
10379 level: 12,
10380 }])
10381 })
10382 .collect();
10383 let rows = decode_luma_at(64, 96, &blocks);
10384 for block_row in 0..3 {
10385 for block_col in 0..2 {
10386 let name = format!("block ({block_row},{block_col})");
10387 let block = block_at(&rows, block_row, block_col);
10388 if (block_row * 2 + block_col) % 2 == 0 {
10389 assert_falls_across(&block, &name);
10390 } else {
10391 assert_falls_down(&block, &name);
10392 }
10393 }
10394 }
10395 }
10396
10397 /// A frame whose blocks do not tile it is refused rather than written as a
10398 /// stream a decoder walks off the end of.
10399 #[test]
10400 fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() {
10401 let (_, header) = frame_of(80, 64);
10402 let blocks = vec![BlockCoeffs::default(); 4];
10403 let err = split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, &blocks)
10404 .expect_err("80 is not a whole number of 32x32 blocks");
10405 assert!(
10406 format!("{err}").contains("32x32"),
10407 "the refusal names the block size, got {err}"
10408 );
10409 }
10410
10411 /// A directional intra mode says where its prediction comes from, and with
10412 /// no residual of its own a block must be exactly that prediction. The
10413 /// top-left block is given a basis function that is flat across it and
10414 /// falls down it; the block to its right is coded `H_PRED`, so every one of
10415 /// its rows must be the constant its left neighbour's rightmost column
10416 /// hands it, and the block below is coded `V_PRED`, so every one of its
10417 /// columns must be the constant the row above it ends on — a single flat
10418 /// value for the whole block. Nothing here pins the transform's shape or
10419 /// the mode's CDF: a mode written with the wrong context, an angle delta
10420 /// left out or a mode index off by one desyncs the symbol decoder and the
10421 /// two empty blocks stop mirroring their neighbours.
10422 #[test]
10423 fn directional_modes_predict_from_the_neighbours_they_name() {
10424 if !have_ffmpeg() {
10425 eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg");
10426 return;
10427 }
10428 let gradient = BlockCoeffs {
10429 luma: vec![Coeff {
10430 row: 1,
10431 col: 0,
10432 level: 12,
10433 }],
10434 ..BlockCoeffs::default()
10435 };
10436 let blocks = [
10437 gradient,
10438 BlockCoeffs {
10439 mode: H_PRED as u8,
10440 ..BlockCoeffs::default()
10441 },
10442 BlockCoeffs {
10443 mode: V_PRED as u8,
10444 ..BlockCoeffs::default()
10445 },
10446 BlockCoeffs::default(),
10447 ];
10448 let [luma, ..] = decode_coeff_planes(&blocks);
10449
10450 let source = block_at(&luma, 0, 0);
10451 for (r, row) in source.iter().enumerate() {
10452 assert!(
10453 row.iter().all(|&s| s == row[0]),
10454 "the basis function at row 1, column 0 is flat across the block, row {r} is not: {row:?}"
10455 );
10456 }
10457 let profile: Vec<u8> = source.iter().map(|r| r[0]).collect();
10458 assert!(
10459 profile.windows(2).all(|w| w[0] >= w[1]) && profile[0] > profile[31],
10460 "the block must fall from top to bottom, got {profile:?}"
10461 );
10462
10463 let horizontal = block_at(&luma, 0, 1);
10464 for (r, row) in horizontal.iter().enumerate() {
10465 assert!(
10466 row.iter().all(|&s| s == profile[r]),
10467 "an H_PRED block repeats the column to its left, row {r} should be all {} but is {row:?}",
10468 profile[r]
10469 );
10470 }
10471
10472 let vertical = block_at(&luma, 1, 0);
10473 let bottom = profile[31];
10474 assert!(
10475 vertical.iter().flatten().all(|&s| s == bottom),
10476 "a V_PRED block repeats the row above it, which is all {bottom} here, got rows \
10477 {:?} and {:?}",
10478 vertical[0],
10479 vertical[31]
10480 );
10481 }
10482
10483 /// The mode index is checked before anything is written.
10484 #[test]
10485 fn an_intra_mode_outside_the_key_frame_set_is_refused() {
10486 let mut blocks = vec![BlockCoeffs::default(); 4];
10487 blocks[2].mode = INTRA_MODES as u8;
10488 let message = split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks)
10489 .unwrap_err()
10490 .to_string();
10491 assert!(
10492 message.contains("intra mode 13"),
10493 "the refusal must name the mode, got {message}"
10494 );
10495 }
10496
10497 #[test]
10498 fn coefficients_the_writer_cannot_code_are_refused() {
10499 let empty = || vec![BlockCoeffs::default(); 4];
10500 let cases: [(&str, Vec<BlockCoeffs>); 6] = [
10501 ("one set short", vec![BlockCoeffs::default(); 3]),
10502 ("off the transform", {
10503 let mut b = empty();
10504 b[0].luma = vec![Coeff {
10505 row: 32,
10506 col: 0,
10507 level: 1,
10508 }];
10509 b
10510 }),
10511 ("a zero level", {
10512 let mut b = empty();
10513 b[1].luma = vec![Coeff {
10514 row: 0,
10515 col: 0,
10516 level: 0,
10517 }];
10518 b
10519 }),
10520 ("a level past the Golomb tail's reach", {
10521 let mut b = empty();
10522 b[2].luma = vec![Coeff {
10523 row: 0,
10524 col: 0,
10525 level: MAX_LEVEL + 1,
10526 }];
10527 b
10528 }),
10529 ("two coefficients at one position", {
10530 let mut b = empty();
10531 b[3].luma = vec![
10532 Coeff {
10533 row: 4,
10534 col: 4,
10535 level: 1,
10536 },
10537 Coeff {
10538 row: 4,
10539 col: 4,
10540 level: 2,
10541 },
10542 ];
10543 b
10544 }),
10545 ("off the chroma transform", {
10546 let mut b = empty();
10547 b[0].u = vec![Coeff {
10548 row: 0,
10549 col: 16,
10550 level: 1,
10551 }];
10552 b
10553 }),
10554 ];
10555 for (name, blocks) in cases {
10556 assert!(
10557 split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks).is_err(),
10558 "{name} must be refused"
10559 );
10560 }
10561 }
10562
10563 /// The default scan is written as the rule that generates it rather than a
10564 /// thousand pinned numbers, so the rule is checked against what a scan must
10565 /// be: every position exactly once, the origin first, and never a position
10566 /// before one it sits diagonally behind — which is what lets a decoder read
10567 /// a coefficient's context off the coefficients it has already decoded.
10568 /// lane-rdoq's two contracts, on a block shaped like the ones the pass
10569 /// exists for (a strong DC, two mid levels and a tail of barely-rounded
10570 /// +-1s): it may only move a block to a LOWER `D + lambda * R`, and the
10571 /// bits it hands back must be the price of the grid it leaves behind --
10572 /// the search takes that number as the block's rate, so a stale one
10573 /// would price a tile nobody writes.
10574 #[test]
10575 fn rdoq_only_lowers_the_cost_and_reports_its_own_grid() {
10576 let (side, set, q, lambda) = (16usize, TxbSet::Luma16, 150u8, 0.0275);
10577 let mut scaled = vec![0f32; side * side];
10578 for (i, v) in [
10579 (0usize, 7.4f32),
10580 (1, 2.6),
10581 (side, -1.55),
10582 // The tail the pass exists for: coefficients the deadzone only
10583 // just rounded up to +-1, which give a whole level back for a
10584 // fraction of one step of squared error.
10585 (2, 0.55),
10586 (2 * side + 1, -0.52),
10587 (3 * side + 3, 0.51),
10588 ] {
10589 scaled[i] = v;
10590 }
10591 // The deadzone quantiser this pass runs after, at the shipped 0.5.
10592 let mut levels: Vec<i32> = scaled
10593 .iter()
10594 .map(|&v| {
10595 let m = f64::from(v).abs() + 0.5;
10596 let l = if m < 1.0 { 0 } else { m.floor() as i32 };
10597 if v < 0.0 {
10598 -l
10599 } else {
10600 l
10601 }
10602 })
10603 .collect();
10604 let before = levels.clone();
10605 let dc = f64::from(crate::quant::dc_q(8, i32::from(q)));
10606 let ac = f64::from(crate::quant::ac_q(8, i32::from(q)));
10607 let dc_weight = (dc / ac) * (dc / ac);
10608 let cost = |grid: &[i32]| -> f64 {
10609 let d: f64 = grid
10610 .iter()
10611 .zip(&scaled)
10612 .enumerate()
10613 .map(|(i, (&l, &s))| {
10614 (if i == 0 { dc_weight } else { 1.0 }) * (f64::from(s) - f64::from(l)).powi(2)
10615 })
10616 .sum();
10617 d + lambda * coeff_bits(grid, set, crate::decode::q_ctx_of(q), 0, 0)
10618 };
10619 let bits = rdoq(
10620 &mut levels,
10621 &scaled,
10622 side,
10623 q,
10624 set,
10625 0,
10626 0,
10627 lambda,
10628 TxType::DctDct,
10629 );
10630 assert_eq!(
10631 bits,
10632 coeff_bits(&levels, set, crate::decode::q_ctx_of(q), 0, 0)
10633 );
10634 assert!(
10635 cost(&levels) <= cost(&before),
10636 "{:?} vs {:?}",
10637 cost(&levels),
10638 cost(&before)
10639 );
10640 // The tail is what it is for: the last coded position moves earlier.
10641 let last = |g: &[i32]| scan_of(side).iter().rposition(|&p| g[usize::from(p)] != 0);
10642 assert!(
10643 last(&levels) < last(&before),
10644 "eob {:?} -> {:?}",
10645 last(&before),
10646 last(&levels)
10647 );
10648 // A 64-point transform is priced on its top-left 32x32 corner, and
10649 // the pass has to hand back THAT price (the dense path).
10650 let (side, set) = (64usize, TxbSet::Luma64);
10651 let mut scaled = vec![0f32; side * side];
10652 for (i, v) in [(0usize, 6.1f32), (1, 0.55), (side + 1, -0.53)] {
10653 scaled[i] = v;
10654 }
10655 let mut levels: Vec<i32> = scaled
10656 .iter()
10657 .map(|&v| {
10658 let m = f64::from(v).abs() + 0.5;
10659 let l = if m < 1.0 { 0 } else { m.floor() as i32 };
10660 if v < 0.0 {
10661 -l
10662 } else {
10663 l
10664 }
10665 })
10666 .collect();
10667 let bits = rdoq(
10668 &mut levels,
10669 &scaled,
10670 side,
10671 q,
10672 set,
10673 0,
10674 0,
10675 lambda,
10676 TxType::DctDct,
10677 );
10678 let corner: Vec<i32> = (0..32)
10679 .flat_map(|row| levels[row * side..][..32].to_vec())
10680 .collect();
10681 assert_eq!(
10682 bits,
10683 coeff_bits(&corner, set, crate::decode::q_ctx_of(q), 0, 0)
10684 );
10685 }
10686
10687 #[test]
10688 fn the_default_scan_walks_every_position_outwards() {
10689 for side in [TX16, TX32] {
10690 let area = side * side;
10691 let scan = default_scan(side);
10692 assert_eq!(scan.len(), area);
10693 let mut seen = vec![false; area];
10694 for &pos in &scan {
10695 assert!(
10696 !seen[pos as usize],
10697 "position {pos} is scanned twice in {side}x{side}"
10698 );
10699 seen[pos as usize] = true;
10700 }
10701 assert_eq!(scan[0], 0, "the scan starts at the DC");
10702
10703 let mut order = vec![0usize; area];
10704 for (i, &pos) in scan.iter().enumerate() {
10705 order[pos as usize] = i;
10706 }
10707 for row in 0..side {
10708 for col in 0..side {
10709 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
10710 let (nr, nc) = (row + dr, col + dc);
10711 if nr < side && nc < side {
10712 assert!(
10713 order[nr * side + nc] > order[row * side + col],
10714 "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
10715 be scanned after it"
10716 );
10717 }
10718 }
10719 }
10720 }
10721 }
10722 }
10723
10724 /// The whole point of the inverse transform living in the encoder is that
10725 /// it predicts the decoder without asking one. The residual a DC-only
10726 /// 64x64 transform produces has already been pinned from a real decoder in
10727 /// [`DECODED_AT_Q100`], so that table is the gate: every level in it, both
10728 /// signs, has to come back out of `dequant_and_inverse` exactly.
10729 #[test]
10730 fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() {
10731 for (level, _) in DECODED_AT_Q100 {
10732 let mut levels = vec![0i32; 64 * 64];
10733 levels[0] = level;
10734 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
10735 let want = dc_residual(level);
10736 assert!(
10737 residual.iter().all(|&r| r == want),
10738 "level {level}: want a flat {want}, got {}..{} (first {})",
10739 residual.iter().min().unwrap(),
10740 residual.iter().max().unwrap(),
10741 residual[0]
10742 );
10743 }
10744 }
10745
10746 /// The same gate at the other transform size the encoder codes: a split
10747 /// superblock's 32x32 blocks, whose residuals are pinned in
10748 /// [`SPLIT_RESIDUAL_AT_Q100`]. The two sizes divide the dequantized
10749 /// coefficient by different denominators, so a size-blind dequantizer
10750 /// passes one table and fails the other.
10751 #[test]
10752 fn the_inverse_transform_reproduces_the_pinned_split_residuals() {
10753 for (level, want) in SPLIT_RESIDUAL_AT_Q100 {
10754 let mut levels = vec![0i32; 32 * 32];
10755 levels[0] = level;
10756 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
10757 assert!(
10758 residual.iter().all(|&r| r == want),
10759 "level {level}: want a flat {want}, got {}..{} (first {})",
10760 residual.iter().min().unwrap(),
10761 residual.iter().max().unwrap(),
10762 residual[0]
10763 );
10764 }
10765 }
10766
10767 /// A DC-only transform is flat, which is exactly the case that cannot tell
10768 /// a transposed or mis-permuted butterfly network from a correct one. An AC
10769 /// coefficient in the first row must vary along the row and stay constant
10770 /// down each column, and the one in the first column the other way round;
10771 /// a transposed network swaps the two.
10772 #[test]
10773 fn a_single_ac_coefficient_varies_along_its_own_axis() {
10774 for side in [4, 8, 16, 32, 64] {
10775 let mut horizontal = vec![0i32; side * side];
10776 horizontal[1] = 100;
10777 let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX));
10778 let mut vertical = vec![0i32; side * side];
10779 vertical[side] = 100;
10780 let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX));
10781 for row in 0..side {
10782 for col in 0..side {
10783 assert_eq!(
10784 h[row * side + col],
10785 h[col],
10786 "{side}: a first-row coefficient is constant down column {col}"
10787 );
10788 assert_eq!(
10789 v[row * side + col],
10790 v[row * side],
10791 "{side}: a first-column coefficient is constant along row {row}"
10792 );
10793 }
10794 }
10795 // The two are each other's transpose. Only to within a rounding
10796 // step: the spec rounds halves up rather than away from zero, so a
10797 // basis function and its transpose can land a count apart where
10798 // the row and column passes round opposite ways.
10799 assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies");
10800 for row in 0..side {
10801 for col in 0..side {
10802 let (a, b) = (h[row * side + col], v[col * side + row]);
10803 assert!(
10804 (a - b).abs() <= 1,
10805 "{side}: transpose at ({row},{col}): {a} vs {b}"
10806 );
10807 }
10808 }
10809 }
10810 }
10811
10812 /// Negating every level negates every residual, to within the one count
10813 /// the spec's round-halves-up leaves behind. A dequantizer that rounded a
10814 /// negative coefficient away from zero instead of toward it would shift a
10815 /// whole basis function, not a count of it, so the bound is what makes
10816 /// this a test rather than a restatement.
10817 #[test]
10818 fn negating_the_levels_negates_the_residual() {
10819 for side in [32, 64] {
10820 for level in [1, 2, 3, 5, 9, 14, 40, 100] {
10821 let mut levels = vec![0i32; side * side];
10822 levels[0] = level;
10823 levels[1] = -level;
10824 levels[side + 1] = level * 2;
10825 let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
10826 let negated: Vec<i32> = levels.iter().map(|&l| -l).collect();
10827 let neg =
10828 crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX));
10829 let worst = pos
10830 .iter()
10831 .zip(&neg)
10832 .map(|(&p, &n)| (p + n).abs())
10833 .max()
10834 .expect("the block is not empty");
10835 assert!(worst <= 1, "side {side} level {level}: off by {worst}");
10836 }
10837 }
10838 }
10839
10840 /// The pinned tables above are DC-only, and a flat residual cannot tell a
10841 /// correct butterfly network from one that is merely correct at DC. This
10842 /// is the same claim against a real decoder and with real AC content: the
10843 /// top-left block of a key frame predicts a flat mid-grey with no
10844 /// neighbours to read, so what ffmpeg shows there is exactly 128 plus the
10845 /// residual the encoder's own inverse transform computes. Every sample has
10846 /// to agree, not most of them.
10847 #[test]
10848 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
10849 if !have_ffmpeg() {
10850 eprintln!(
10851 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg"
10852 );
10853 return;
10854 }
10855 // A DC, two low-frequency terms of each orientation, a diagonal and a
10856 // far corner, with both signs among them.
10857 let coeffs = [
10858 (0u8, 0u8, 9i32),
10859 (0, 1, -14),
10860 (1, 0, 7),
10861 (0, 3, 5),
10862 (3, 0, -3),
10863 (2, 2, 11),
10864 (7, 5, -6),
10865 (31, 31, 4),
10866 ];
10867 let block: BlockCoeffs = coeffs
10868 .iter()
10869 .map(|&(row, col, level)| Coeff { row, col, level })
10870 .collect::<Vec<_>>()
10871 .into();
10872 let rows = decode_luma_at(
10873 64,
10874 64,
10875 &[
10876 block,
10877 BlockCoeffs::default(),
10878 BlockCoeffs::default(),
10879 BlockCoeffs::default(),
10880 ],
10881 );
10882
10883 let mut levels = vec![0i32; 32 * 32];
10884 for &(row, col, level) in &coeffs {
10885 levels[usize::from(row) * 32 + usize::from(col)] = level;
10886 }
10887 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
10888 for row in 0..32 {
10889 for col in 0..32 {
10890 let want = (128 + residual[row * 32 + col]).clamp(0, 255);
10891 assert_eq!(
10892 i32::from(rows[row][col]),
10893 want,
10894 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
10895 rows[row][col]
10896 );
10897 }
10898 }
10899 // The block is not flat, so the agreement is about the transform and
10900 // not about a prediction both sides got trivially right.
10901 let (lo, hi) = (
10902 rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(),
10903 rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(),
10904 );
10905 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
10906 }
10907
10908 /// The same against the smallest transform the writer codes, the 16x16 one
10909 /// a split quadrant carries. Its rounding is the one the split path rests
10910 /// on, and nothing else in the crate exercises it against a decoder.
10911 #[test]
10912 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
10913 if !have_ffmpeg() {
10914 eprintln!(
10915 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
10916 );
10917 return;
10918 }
10919 let coeffs = [
10920 (0u8, 0u8, 9i32),
10921 (0, 1, -14),
10922 (1, 0, 7),
10923 (0, 3, 5),
10924 (3, 0, -3),
10925 (2, 2, 11),
10926 (7, 5, -6),
10927 (15, 15, 4),
10928 ];
10929 let block: BlockCoeffs = coeffs
10930 .iter()
10931 .map(|&(row, col, level)| Coeff { row, col, level })
10932 .collect::<Vec<_>>()
10933 .into();
10934 let (seq, header) = frame_of(64, 64);
10935 let quadrants = vec![
10936 Quadrant::Split(vec![
10937 block,
10938 BlockCoeffs::default(),
10939 BlockCoeffs::default(),
10940 BlockCoeffs::default(),
10941 ]),
10942 Quadrant::Whole(BlockCoeffs::default()),
10943 Quadrant::Whole(BlockCoeffs::default()),
10944 Quadrant::Whole(BlockCoeffs::default()),
10945 ];
10946 let tile = sb_coeff_key_frame_tile(
10947 header.mi_cols,
10948 header.mi_rows,
10949 Q_IDX,
10950 &[Superblock::Split(quadrants)],
10951 )
10952 .unwrap();
10953 let mut stream = temporal_delimiter();
10954 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
10955 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
10956 let planes = ffmpeg_decode(&stream, 64, 64);
10957
10958 let mut levels = vec![0i32; TX16 * TX16];
10959 for &(row, col, level) in &coeffs {
10960 levels[usize::from(row) * TX16 + usize::from(col)] = level;
10961 }
10962 let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX));
10963 for row in 0..TX16 {
10964 for col in 0..TX16 {
10965 let want = (128 + residual[row * TX16 + col]).clamp(0, 255);
10966 assert_eq!(
10967 i32::from(planes[row * 64 + col]),
10968 want,
10969 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
10970 planes[row * 64 + col]
10971 );
10972 }
10973 }
10974 }
10975
10976 /// The same against the other transform size, the 64x64 one a whole
10977 /// superblock carries. Only its top-left 32x32 can hold coefficients, and
10978 /// the spec zeroes the rest before the row transform — a 64-point network
10979 /// that read the missing half as anything else would disagree here.
10980 #[test]
10981 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {
10982 if !have_ffmpeg() {
10983 eprintln!(
10984 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg"
10985 );
10986 return;
10987 }
10988 let coeffs = [
10989 (0u8, 0u8, 12i32),
10990 (0, 2, -9),
10991 (2, 0, 6),
10992 (1, 1, -5),
10993 (5, 9, 8),
10994 (31, 0, -4),
10995 (0, 31, 3),
10996 ];
10997 let block: BlockCoeffs = coeffs
10998 .iter()
10999 .map(|&(row, col, level)| Coeff { row, col, level })
11000 .collect::<Vec<_>>()
11001 .into();
11002 let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]);
11003
11004 let mut levels = vec![0i32; 64 * 64];
11005 for &(row, col, level) in &coeffs {
11006 levels[usize::from(row) * 64 + usize::from(col)] = level;
11007 }
11008 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
11009 for row in 0..64 {
11010 for col in 0..64 {
11011 let want = (128 + residual[row * 64 + col]).clamp(0, 255);
11012 assert_eq!(
11013 i32::from(rows[row][col]),
11014 want,
11015 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
11016 rows[row][col]
11017 );
11018 }
11019 }
11020 }
11021
11022 /// The AV1 transforms are normalized so that a quantized level means the
11023 /// same thing at every size: doubling the transform's side halves what a
11024 /// DC level is worth, which is the job the per-size row shift and the
11025 /// dequantizer's denominator split between them. The frame syntax only
11026 /// codes 32x32 and 64x64 transforms, so this is what holds the four
11027 /// smaller sizes' shifts to the spec's table — a shift wrong by one at any
11028 /// size doubles or halves that size's step alone.
11029 #[test]
11030 fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() {
11031 let mut previous: Option<i32> = None;
11032 for side in [4usize, 8, 16, 32, 64] {
11033 let mut levels = vec![0i32; side * side];
11034 levels[0] = 100;
11035 let residual =
11036 crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
11037 let dc = residual[0];
11038 assert!(
11039 residual.iter().all(|&r| r == dc),
11040 "side {side}: a DC coefficient reconstructs flat"
11041 );
11042 if let Some(previous) = previous {
11043 assert!(
11044 (dc * 2 - previous).abs() <= 1,
11045 "side {side}: {dc} is not half of the previous size's {previous}"
11046 );
11047 }
11048 previous = Some(dc);
11049 }
11050 }
11051
11052 /// The encoder's own round trip, through a real bitstream.
11053 ///
11054 /// A picture is chosen, its residual against the DC prediction of 128 is
11055 /// forward-transformed and quantized, the levels are written into a tile,
11056 /// and ffmpeg decodes it. Two things have to hold: what comes back is
11057 /// exactly what the encoder's own inverse said it would be — sample for
11058 /// sample, which is what lets a rate-distortion loop trust its
11059 /// reconstruction — and it is within a quantizer step of the picture that
11060 /// was asked for, which is what makes the forward transform an encoder
11061 /// rather than a scrambler.
11062 #[test]
11063 fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {
11064 if !have_ffmpeg() {
11065 eprintln!(
11066 "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
11067 );
11068 return;
11069 }
11070 // A gradient, a ripple and a corner patch: low frequencies, a mid one
11071 // and an edge, none of them a basis function of the transform.
11072 let mut residual = vec![0i32; 32 * 32];
11073 for row in 0..32usize {
11074 for col in 0..32usize {
11075 let gradient = row as f64 * 2.0 - 32.0;
11076 let ripple = 25.0
11077 * (col as f64 * std::f64::consts::PI / 6.0).sin()
11078 * (row as f64 * std::f64::consts::PI / 11.0).cos();
11079 let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 };
11080 residual[row * 32 + col] = (gradient + ripple + patch).round() as i32;
11081 }
11082 }
11083
11084 let levels =
11085 crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5);
11086 assert!(
11087 levels.iter().any(|&l| l != 0),
11088 "the picture quantized away entirely"
11089 );
11090 let coded: Vec<Coeff> = levels
11091 .iter()
11092 .enumerate()
11093 .filter(|&(_, &level)| level != 0)
11094 .map(|(i, &level)| Coeff {
11095 row: (i / 32) as u8,
11096 col: (i % 32) as u8,
11097 level,
11098 })
11099 .collect();
11100
11101 let rows = decode_luma_at(
11102 64,
11103 64,
11104 &[
11105 coded.into(),
11106 BlockCoeffs::default(),
11107 BlockCoeffs::default(),
11108 BlockCoeffs::default(),
11109 ],
11110 );
11111 let reconstruction =
11112 crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
11113
11114 let mut squared = 0.0f64;
11115 for row in 0..32 {
11116 for col in 0..32 {
11117 let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255);
11118 assert_eq!(
11119 i32::from(rows[row][col]),
11120 want,
11121 "sample ({row},{col}): the decoder and the encoder disagree"
11122 );
11123 let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]);
11124 squared += error * error;
11125 }
11126 }
11127 let rmse = (squared / 1024.0).sqrt();
11128 // A quantizer step is q/8 in residual units. Rounding to nearest
11129 // spreads the error over a step, and a quarter of one is a bound this
11130 // picture clears with room to spare (2.2 of 14 as written) while a
11131 // forward transform that is merely energy-preserving does not: a
11132 // transposed column pass measures 13.3 here.
11133 let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0;
11134 assert!(
11135 rmse < step / 4.0,
11136 "the decoded picture is {rmse} off, a step being {step}"
11137 );
11138 }
11139
11140 /// The inverse of [`write_mv_component`], mirroring [`SymbolDecoder`]
11141 /// against the spec's own `read_mv_component` pseudocode.
11142 fn decode_mv_component(
11143 dec: &mut crate::msac::tests::SymbolDecoder,
11144 c: &mut MvComponentCdfs,
11145 ) -> i32 {
11146 let sign = dec.symbol(&mut c.sign);
11147 let class = dec.symbol(&mut c.class);
11148 let local = if class == 0 {
11149 let bit = dec.symbol(&mut c.class0_bit);
11150 let fr = dec.symbol(&mut c.class0_fr[bit]);
11151 (bit << 3) | (fr << 1) | 1
11152 } else {
11153 let mut d = 0;
11154 for i in 0..class {
11155 d |= dec.symbol(&mut c.bit[i]) << i;
11156 }
11157 let fr = dec.symbol(&mut c.fr);
11158 (d << 3) | (fr << 1) | 1
11159 };
11160 let mag = mv_class_base(class) + local as i32 + 1;
11161 if sign == 1 {
11162 -mag
11163 } else {
11164 mag
11165 }
11166 }
11167
11168 /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,
11169 /// mirroring the writer's own context tracking (partition, skip,
11170 /// is_inter, and the MV stack) symbol for symbol against a fresh
11171 /// [`Cdfs`], so a desync between the two shows up as a wrong decoded
11172 /// value rather than a silent pass. Every block here is skipped, so no
11173 /// coefficient symbols are read. `wrong_y_mode` swaps in `KF_Y_MODE`'s
11174 /// (0, 0) row for an intra block's mode read, to show that reading the
11175 /// wrong table decodes the wrong mode rather than the one that was
11176 /// written.
11177 ///
11178 /// One decoded block's `(skip, is_inter, mode, mv)` — `mode` is `None`
11179 /// for an inter block, `mv` is `(0, 0)` for an intra one.
11180 type DecodedBlock = (bool, bool, Option<usize>, (i32, i32));
11181
11182 /// Returns the number of symbols and literals read, and each block's
11183 /// decoded state.
11184 fn decode_inter_sb(
11185 data: &[u8],
11186 mi_cols: u32,
11187 mi_rows: u32,
11188 wrong_y_mode: bool,
11189 ) -> (usize, Vec<DecodedBlock>) {
11190 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
11191 let mut cdfs = Cdfs::new(2);
11192 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
11193 let mut above_skip = [false; 2];
11194 let mut left_skip = [false; 2];
11195 let mut above_inter = [false; 2];
11196 let mut left_inter = [false; 2];
11197 let mut count = 0usize;
11198
11199 count += 1;
11200 dec.symbol(&mut cdfs.partition_w64[0]);
11201
11202 let mut results = Vec::new();
11203 for quadrant in 0..4usize {
11204 let (r32, c32) = (quadrant / 2, quadrant % 2);
11205 count += 1;
11206 dec.symbol(&mut cdfs.partition_w32[0]);
11207
11208 let (has_above, has_left) = (r32 > 0, c32 > 0);
11209 let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]);
11210 count += 1;
11211 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
11212
11213 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]);
11214 count += 1;
11215 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
11216
11217 let (mode, mv) = if is_inter {
11218 let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]);
11219 count += 3;
11220 assert_eq!(
11221 dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
11222 0,
11223 "single_ref p1"
11224 );
11225 assert_eq!(
11226 dec.symbol(&mut cdfs.single_ref[sr_ctx][2]),
11227 0,
11228 "single_ref p3"
11229 );
11230 assert_eq!(
11231 dec.symbol(&mut cdfs.single_ref[sr_ctx][3]),
11232 0,
11233 "single_ref p4"
11234 );
11235
11236 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
11237 let stack = find_mv_stack(
11238 &grid,
11239 mi_row,
11240 mi_col,
11241 8,
11242 8,
11243 1,
11244 mi_cols as usize,
11245 mi_rows as usize,
11246 );
11247
11248 count += 1;
11249 let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0;
11250 let (mv, is_new_mv) = if new_mv {
11251 if stack.entries.len() > 1 {
11252 count += 1;
11253 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
11254 }
11255 count += 1;
11256 let joint = dec.symbol(&mut cdfs.mv_joint);
11257 let mut diff = (0, 0);
11258 if joint == 2 || joint == 3 {
11259 // sign, class, class0_bit, class0_fr for this test's
11260 // small (class 0) components.
11261 count += 4;
11262 diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]);
11263 }
11264 if joint == 1 || joint == 3 {
11265 count += 4;
11266 diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]);
11267 }
11268 ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true)
11269 } else {
11270 count += 2;
11271 assert_eq!(
11272 dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]),
11273 1,
11274 "zero_mv"
11275 );
11276 assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv");
11277 (stack.nearest_mv, false)
11278 };
11279 for dr in 0..8 {
11280 for dc in 0..8 {
11281 grid.set(
11282 mi_row + dr,
11283 mi_col + dc,
11284 MiInfo {
11285 is_inter: true,
11286 ref_frame: 1,
11287 ref_frame1: NO_REF1,
11288 mv1: (0, 0),
11289 mv: mv16(mv),
11290 is_new_mv,
11291 size: 8,
11292 size_h: 8,
11293 is_global_mv0: false,
11294 is_global_mv1: false,
11295 },
11296 );
11297 }
11298 }
11299 (None, mv)
11300 } else {
11301 count += 1;
11302 let m = if wrong_y_mode {
11303 dec.symbol(&mut cdfs.kf_y_mode[0][0])
11304 } else {
11305 dec.symbol(&mut cdfs.y_mode[3])
11306 };
11307 if (V_PRED..=D67_PRED).contains(&m) {
11308 count += 1;
11309 dec.symbol(&mut cdfs.angle_delta[m - V_PRED]);
11310 }
11311 count += 1;
11312 dec.symbol(&mut cdfs.uv_mode_cfl[m]);
11313 (Some(m), (0, 0))
11314 };
11315
11316 above_skip[c32] = skip;
11317 left_skip[r32] = skip;
11318 above_inter[c32] = is_inter;
11319 left_inter[r32] = is_inter;
11320 results.push((skip, is_inter, mode, mv));
11321 }
11322 (count, results)
11323 }
11324
11325 /// Every superblock here skips: no residual, so the only symbols are the
11326 /// mode chain, and the byte count and the symbol count both come out
11327 /// small enough to hand-check.
11328 #[test]
11329 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
11330 let block = BlockCoeffs {
11331 inter: Some(InterInfo {
11332 ref1: None,
11333 mv1: (0, 0),
11334 ref_frame: crate::mvstack::LAST_FRAME,
11335 mode: InterMode::NearestMv,
11336 mv: (0, 0),
11337 ref_mv_idx: 0,
11338 }),
11339 skip: true,
11340 ..BlockCoeffs::default()
11341 };
11342 let blocks = vec![
11343 Quadrant::Whole(block.clone()),
11344 Quadrant::Whole(block.clone()),
11345 Quadrant::Whole(block.clone()),
11346 Quadrant::Whole(block),
11347 ];
11348 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11349 // Hand count: one partition_w64, then per block partition_w32 + skip +
11350 // is_inter + 3 single_ref + new_mv + zero_mv + ref_mv = 9, times four.
11351 assert!(
11352 data.len() <= 16,
11353 "an all-skip NEARESTMV superblock took {} bytes",
11354 data.len()
11355 );
11356
11357 let (count, results) = decode_inter_sb(&data, 16, 16, false);
11358 assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count");
11359 for (skip, is_inter, mode, mv) in results {
11360 assert!(skip);
11361 assert!(is_inter);
11362 assert_eq!(mode, None);
11363 // Every block's only inter neighbours carry (0, 0), so the stack's
11364 // nearest candidate is (0, 0) throughout.
11365 assert_eq!(mv, (0, 0));
11366 }
11367 }
11368
11369 /// The fourth block codes NEWMV against a (0, 0) predictor with a coded
11370 /// column component: the symbol sequence a decoder reads back has to be
11371 /// exactly what [`write_mv`] wrote, not a residual that merely decodes
11372 /// to *some* valid vector.
11373 #[test]
11374 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
11375 let nearest = BlockCoeffs {
11376 inter: Some(InterInfo {
11377 ref1: None,
11378 mv1: (0, 0),
11379 ref_frame: crate::mvstack::LAST_FRAME,
11380 mode: InterMode::NearestMv,
11381 mv: (0, 0),
11382 ref_mv_idx: 0,
11383 }),
11384 skip: true,
11385 ..BlockCoeffs::default()
11386 };
11387 let newmv = BlockCoeffs {
11388 inter: Some(InterInfo {
11389 ref1: None,
11390 mv1: (0, 0),
11391 ref_frame: crate::mvstack::LAST_FRAME,
11392 mode: InterMode::NewMv,
11393 mv: (0, 2),
11394 ref_mv_idx: 0,
11395 }),
11396 skip: true,
11397 ..BlockCoeffs::default()
11398 };
11399 let blocks = vec![
11400 Quadrant::Whole(nearest.clone()),
11401 Quadrant::Whole(nearest.clone()),
11402 Quadrant::Whole(nearest),
11403 Quadrant::Whole(newmv),
11404 ];
11405 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11406
11407 let (count, results) = decode_inter_sb(&data, 16, 16, false);
11408 // Three NEARESTMV blocks at 9 symbols each, one NEWMV block at
11409 // partition + skip + is_inter + 3 single_ref + new_mv + mv_joint +
11410 // (sign, class, class0_bit, class0_fr for the one nonzero component)
11411 // = 12, plus the superblock's partition_w64.
11412 assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count");
11413 let (skip, is_inter, mode, mv) = results[3];
11414 assert!(skip);
11415 assert!(is_inter);
11416 assert_eq!(mode, None);
11417 assert_eq!(
11418 mv,
11419 (0, 2),
11420 "the decoded motion vector must be exactly what was written"
11421 );
11422 }
11423
11424 /// Decodes only the first 32x32 block's mode symbol of a superblock: the
11425 /// tile's own first block always reads partition, skip and is_inter at
11426 /// context zero, so this needs none of [`decode_inter_sb`]'s neighbour
11427 /// bookkeeping — which matters here because the mutation this feeds
11428 /// desyncs everything after the one symbol it is testing, and a decoder
11429 /// that kept reading past it would be asserting on garbage.
11430 fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize {
11431 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
11432 let mut cdfs = Cdfs::new(2);
11433 dec.symbol(&mut cdfs.partition_w64[0]);
11434 dec.symbol(&mut cdfs.partition_w32[0]);
11435 dec.symbol(&mut cdfs.skip[0]);
11436 dec.symbol(&mut cdfs.intra_inter[0]);
11437 if wrong_y_mode {
11438 dec.symbol(&mut cdfs.kf_y_mode[0][0])
11439 } else {
11440 dec.symbol(&mut cdfs.y_mode[3])
11441 }
11442 }
11443
11444 /// An inter frame's intra block reads its mode against `Y_MODE`'s size
11445 /// group, not `KF_Y_MODE`'s neighbour-context table a key frame's block
11446 /// reads. Reading the wrong table back — `KF_Y_MODE`'s `(0, 0)` row —
11447 /// decodes a different mode than the one [`sb_coeff_inter_frame_tile`]
11448 /// wrote, because the two tables carry different default probabilities
11449 /// even though a row of each is the same fourteen-entry width. (The swap
11450 /// this test's name warns of does not typecheck as a one-line
11451 /// substitution at the write site either — `cdfs.kf_y_mode[3]` is a
11452 /// `[[u16; 14]; 5]` row, not the single `[u16; 14]` `Y_MODE` indexing
11453 /// needs — so a mutation that got the *outer* shape wrong would be
11454 /// caught by `cargo check` before it ever reached a test; this test is
11455 /// what catches getting the *right* leaf shape from the *wrong* table.)
11456 #[test]
11457 fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() {
11458 let block = BlockCoeffs {
11459 mode: H_PRED as u8,
11460 skip: true,
11461 ..BlockCoeffs::default()
11462 };
11463 let blocks = vec![Quadrant::Whole(block); 4];
11464 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11465
11466 assert_eq!(
11467 decode_first_block_mode(&data, false),
11468 H_PRED,
11469 "the right table reads the mode back exactly"
11470 );
11471 assert_ne!(
11472 decode_first_block_mode(&data, true),
11473 H_PRED,
11474 "KF_Y_MODE's different probabilities must decode a different mode"
11475 );
11476 }
11477
11478 /// lane-rectdq witness: [`crate::encode::delta_q_bits`] prices exactly
11479 /// what [`write_delta_q`] writes, over the whole `delta_q_abs` domain
11480 /// (0..=20 steps, both signs -- the escape literal pair starts at 3 and
11481 /// its `rem_bits` widens at 4, 5, 9 and 17). The writer is run into a
11482 /// PRICING coder whose account (`SymbolEncoder::bits`) is the same
11483 /// arithmetic-coder cost the pricer's `symbol_bits` sums, so the two
11484 /// agree to floating-point noise, not to a tolerance band.
11485 ///
11486 /// Both sides read the DEFAULT `delta_q` row: the writer's `cdfs` is
11487 /// rebuilt per case, exactly as every tile's is armed before its first
11488 /// superblock.
11489 #[test]
11490 fn the_delta_q_pricer_matches_the_writer_over_the_whole_domain() {
11491 const RES: i32 = 4;
11492 const CUR: i32 = 128;
11493 for steps in -20i32..=20 {
11494 let target = CUR + steps * RES;
11495 arm_delta_q(RES, 1, vec![u8::try_from(target).expect("in range")], 128);
11496 let mut cdfs = Cdfs::new(2);
11497 let mut enc = SymbolEncoder::pricer();
11498 enc.reset_bits();
11499 // `is_whole_sb = false`: the rect half / 64-superblock shape,
11500 // the one whose pricer this witnesses.
11501 write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
11502 let written = enc.bits();
11503 let priced = crate::encode::delta_q_bits(target, CUR, RES);
11504 assert!(
11505 (written - priced).abs() < 1e-9,
11506 "steps {steps}: writer {written} bits, pricer {priced}"
11507 );
11508 }
11509 // Disarmed plan: the writer codes nothing and the pricer charges
11510 // nothing.
11511 arm_delta_q(0, 1, Vec::new(), 128);
11512 let mut cdfs = Cdfs::new(2);
11513 let mut enc = SymbolEncoder::pricer();
11514 enc.reset_bits();
11515 write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
11516 assert!(enc.bits().abs() < 1e-9, "a disarmed plan writes no symbol");
11517 assert!((crate::encode::delta_q_bits(200, 128, 0)).abs() < 1e-9);
11518 }
11519}