forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiBdfeffbcTahinli2 months ago3180 commits

tile.rs11511 lines, 472.7 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 let mut pair = [Vec::new(), Vec::new()];
417 for plane in 1..3usize {
418 let grid = unit_of(plane, cr, cc);
419 let around = neighbours.around_mi(unit_mi, 64)[plane];
420 write_coeffs(
421 enc,
422 &mut cdfs.txb(TxbSet::Chroma32, 0),
423 &grid,
424 &scan32,
425 usize::from(around.above_coded) + usize::from(around.left_coded) + 3,
426 dc_sign_ctx(around.dc_vote),
427 Some(plane),
428 TxType::DctDct,
429 );
430 neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
431 pair[plane - 1] = grid;
432 }
433 chroma_units.push((unit_mi, pair));
434 }
435 // decode.rs' own tail (`record_split_luma_rect_mi` then the
436 // `mu_chroma_units` re-stamp): the block-level write off the WHOLE
437 // assembled chroma plane grid, luma kept because each unit already
438 // published its own, and then the per-unit chroma writes replayed
439 // over it -- last writer wins, so the next block reads the units.
440 let block_grids = [
441 vec![0i32; TX32 * TX32],
442 packed[1].clone(),
443 packed[2].clone(),
444 ];
445 neighbours.record_planes(sb_at, SIDE, 0, &block_grids, false);
446 for (unit_mi, pair) in &chroma_units {
447 neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
448 neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
449 }
450 } else {
451 neighbours.record(sb_at, SIDE, 0, &zero_grids);
452 }
453 neighbours.record_inter(sb_at, SIDE, block.skip, true, block_ref(block));
454 record_block_compound(neighbours, (mi_r, mi_c), SIDE, block);
455 SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
456 if !block.skip {
457 SB128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
458 }
459 if info.ref1.is_some() {
460 SB128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
461 }
462 Ok(())
463}
464
465/// lane-b128hv: one 128x64 (HORZ) or 64x128 (VERT) inter block, the two
466/// halves a `PARTITION_HORZ`/`PARTITION_VERT` 128 superblock root carries --
467/// the syntax `decode_inter_block` reads for `sb128_rect` (decode.rs ~35343):
468/// the same chain [`write_inter_block_128`] writes, at the block's own
469/// rectangular window. Every CDF/context decision is taken at the enclosing
470/// square `side` of 128 (what the decoder's `inter_piece!` passes), and the
471/// block's true footprint governs only its mv-stack window, its mi/grid stamp
472/// and its neighbour bands (decode.rs' own `write_w`/`write_h` split).
473///
474/// lane-ab128: also the two 64x64 squares an AB shape codes (the `w == h`
475/// arm below) and its 128x64 / 64x128 half.
476///
477/// lane-rectres: a piece may CARRY A RESIDUAL -- the search only ever hands
478/// one over under `EC_AV1_RECTRES` ([`crate::encode::rectres`]), and then it
479/// is coded here exactly as `decode_inter_block` reads it: one TX_64X64 luma
480/// unit plus a TX_32X32 chroma pair per 64x64 mu chunk (two chunks for a
481/// half, one for a square), each depth-0 in the var-tx tree (a half codes
482/// two `txfm_partition` flags under `TxMode::Select`, a square one).
483///
484/// # Errors
485/// A block that is intra.
486#[allow(clippy::too_many_arguments)]
487fn write_inter_block_128_rect(
488 enc: &mut SymbolEncoder,
489 cdfs: &mut Cdfs,
490 neighbours: &mut Neighbours,
491 grid: &mut MiGrid,
492 // The half's own top-left position in mode-info (4x4) units.
493 at_mi: (usize, usize),
494 // Its true footprint in samples: (128, 64) at HORZ, (64, 128) at VERT.
495 (w, h): (usize, usize),
496 block: &BlockCoeffs,
497 mi_cols: u32,
498 mi_rows: u32,
499 tx_select: bool,
500) -> Result<()> {
501 let info = block.inter.ok_or_else(|| {
502 Error::unsupported("AV1 tile", "a 128-root rectangular half is coded inter")
503 })?;
504 let (mi_r, mi_c) = at_mi;
505 let (w_mi, h_mi) = (w / MI, h / MI);
506 let has_above = neighbours.has_above(mi_r);
507 let has_left = neighbours.has_left(mi_c);
508 let skip_ctx =
509 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
510 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
511 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
512 // NOT a whole superblock: decode.rs' `whole_sb` is `write_w == write_h ==
513 // sb_px`, so a rect half reads its `delta_q` group even when skipped.
514 write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
515 let ii_ctx = intra_inter_ctx(
516 has_above,
517 has_left,
518 neighbours.above_inter[mi_c],
519 neighbours.left_inter[mi_r],
520 );
521 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
522 write_comp_mode(
523 enc,
524 cdfs,
525 neighbours,
526 (mi_r, mi_c),
527 (has_above, has_left),
528 info.ref1.is_some(),
529 );
530 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
531 write_compound_block(
532 enc,
533 cdfs,
534 neighbours,
535 grid,
536 (mi_r, mi_c),
537 (w_mi, h_mi),
538 (has_above, has_left),
539 info,
540 (mi_cols as usize, mi_rows as usize),
541 )?
542 } else {
543 write_single_ref(
544 enc,
545 cdfs,
546 info.ref_frame,
547 neighbours.above_ref[mi_c],
548 neighbours.above_ref1[mi_c],
549 neighbours.left_ref[mi_r],
550 neighbours.left_ref1[mi_r],
551 );
552 let stack = find_mv_stack(
553 grid,
554 mi_r,
555 mi_c,
556 w_mi,
557 h_mi,
558 info.ref_frame,
559 mi_cols as usize,
560 mi_rows as usize,
561 );
562 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
563 (mv, (0, 0), is_new_mv)
564 };
565 for dr in 0..h_mi {
566 for dc in 0..w_mi {
567 grid.set(
568 mi_r + dr,
569 mi_c + dc,
570 MiInfo {
571 is_inter: true,
572 ref_frame: info.ref_frame,
573 ref_frame1: info.ref1.unwrap_or(NO_REF1),
574 mv1: mv16(mv1),
575 mv: mv16(mv),
576 is_new_mv,
577 size: w_mi as u8,
578 size_h: h_mi as u8,
579 is_global_mv0: false,
580 is_global_mv1: false,
581 },
582 );
583 }
584 }
585 if info.ref1.is_none() {
586 write_motion_mode(
587 enc,
588 cdfs,
589 grid,
590 (mi_r, mi_c),
591 (w_mi, h_mi),
592 (w, h),
593 (mi_cols as usize, mi_rows as usize),
594 info.ref_frame,
595 block.motion_mode,
596 )?;
597 }
598 // The 64x64 mu chunks the residual is coded in, raster order -- the
599 // decoder's own walk: two for a half, one for a square piece.
600 let chunks: &[(usize, usize)] = match (w, h) {
601 (128, 64) => &[(0, 0), (0, 1)],
602 (64, 128) => &[(0, 0), (1, 0)],
603 _ => &[(0, 0)],
604 };
605 // A half's uv plane block (64x32 / 32x64) is wider or taller than its
606 // 32x32 unit, so the unit's `txb_skip_ctx` takes `get_txb_ctx`'s
607 // offset-10 rows (+3 here); a 64x64 piece's uv block IS the unit and
608 // takes none. The half is also the only shape whose chroma is re-stamped
609 // per mu chunk at the end (decode.rs' `mu_chroma`).
610 let is_half = w.max(h) > 64;
611 if tx_select {
612 if block.skip {
613 // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect`
614 // with the BLOCK's own size in both bands, no symbol.
615 neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h));
616 } else if is_half {
617 // The var-tx tree of a 128x64 / 64x128 block enters at TX_64X64
618 // once per mu chunk (`read_block_tx_size_rect`'s `max_tx = 64`
619 // loop), so it is two depth-0 `txfm_split` flags of zero, each
620 // read against the bands the chunks before it published.
621 for &(cr, cc) in chunks {
622 let unit = (mi_r + cr * 16, mi_c + cc * 16);
623 let ctx = txfm_partition_ctx_rect(
624 neighbours.above_txfm[unit.1],
625 neighbours.left_txfm[unit.0],
626 w.max(h),
627 64,
628 64,
629 );
630 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
631 neighbours.record_txfm(unit, 64, 64, 64);
632 }
633 } else {
634 // A 64x64 piece is one whole TX_64X64: the single depth-0 flag
635 // the 64 root's own writer codes (`write_tx_syntax_inter`).
636 write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SB, true, false, 0);
637 }
638 }
639 let zero_grids = [
640 vec![0i32; TX32 * TX32],
641 vec![0i32; TX32 * TX32],
642 vec![0i32; TX32 * TX32],
643 ];
644 // A 128 root's half is always SUB (16 px) aligned, so the coarse mode /
645 // side bands are named by the same SUB-grid origin every square block
646 // uses.
647 let at_sub = (mi_r / (SUB / MI), mi_c / (SUB / MI));
648 if !block.skip {
649 // lane-rectres: the packed 64-wide level grids the search hands over,
650 // one plane each (the same layout `write_inter_block_128` slices for
651 // the whole block, here with the piece's own chunk list).
652 let packed = [
653 level_grid(&block.luma, 64)?,
654 level_grid(&block.u, 64)?,
655 level_grid(&block.v, 64)?,
656 ];
657 let scan32 = default_scan(TX32);
658 let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec<i32> {
659 (0..32)
660 .flat_map(|row| packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec())
661 .collect()
662 };
663 let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
664 for &(cr, cc) in chunks {
665 let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
666 // The luma unit, and the context its all-zero flag reads: a
667 // HALF's unit is smaller than its block (neighbour magnitude
668 // table), a square's IS the whole plane block (fixed zero --
669 // `read_inter_plane`'s `luma_skip_ctx.unwrap_or(0)`, the 64
670 // root's own writer rule). It publishes its context before the
671 // next chunk reads it.
672 let luma = unit_of(0, cr, cc);
673 let skip_ctx = if is_half {
674 neighbours.luma_skip_ctx(unit_mi, 64 / MI)
675 } else {
676 0
677 };
678 let around = neighbours.around_mi(unit_mi, 64);
679 write_coeffs(
680 enc,
681 &mut cdfs.txb(TxbSet::Luma64, 0),
682 &luma,
683 &scan32,
684 skip_ctx,
685 dc_sign_ctx(around[0].dc_vote),
686 Some(0),
687 TxType::DctDct,
688 );
689 neighbours.record_mi_luma(unit_mi, 64, &luma);
690 // Then this chunk's chroma pair, before the next chunk's luma:
691 // libaom codes every plane of a mu chunk before moving on.
692 let mut pair = [Vec::new(), Vec::new()];
693 for plane in 1..3usize {
694 let grid = unit_of(plane, cr, cc);
695 let around = neighbours.around_mi(unit_mi, 64)[plane];
696 write_coeffs(
697 enc,
698 &mut cdfs.txb(TxbSet::Chroma32, 0),
699 &grid,
700 &scan32,
701 usize::from(around.above_coded)
702 + usize::from(around.left_coded)
703 + 3 * usize::from(is_half),
704 dc_sign_ctx(around.dc_vote),
705 Some(plane),
706 TxType::DctDct,
707 );
708 neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
709 pair[plane - 1] = grid;
710 }
711 chroma_units.push((unit_mi, pair));
712 }
713 // decode.rs' own tail (`record_split_luma_rect_mi` then, on a half,
714 // the per-chunk chroma re-stamp): the block-level write off the
715 // whole assembled chroma plane grid, luma kept because each unit
716 // already published its own, and then the per-unit chroma writes
717 // replayed over it -- last writer wins, so the next block reads the
718 // units.
719 let block_grids = [
720 vec![0i32; TX32 * TX32],
721 packed[1].clone(),
722 packed[2].clone(),
723 ];
724 neighbours.record_planes_rect(at_sub, (w, h), 0, &block_grids, false);
725 if is_half {
726 for (unit_mi, pair) in &chroma_units {
727 neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
728 neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
729 }
730 }
731 SB128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
732 } else {
733 neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
734 }
735 neighbours.record_inter_rect_mi((mi_r, mi_c), (w, h), block.skip, true, block_ref(block));
736 if let Some(r1) = info.ref1 {
737 neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1);
738 }
739 // lane-ab128: an AB shape codes its two 64x64 pieces through this same
740 // function, and they are neither a 128x64 nor a 64x128 half -- the
741 // witness reads these two counters for the HORZ/VERT shape alone.
742 if w > h {
743 SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
744 } else if h > w {
745 SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
746 }
747 Ok(())
748}
749
750/// lane-b128hv: how many 128x64 / 64x128 halves the inter writer has coded
751/// since the last [`take_sb128_horz_hits`] / [`take_sb128_vert_hits`] (class
752/// `gate-blind-to-feature`).
753static SB128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
754/// The VERT twin of [`SB128_HORZ_HITS`].
755static SB128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
756
757/// The 128x64-half count since the last call, and zero it.
758pub fn take_sb128_horz_hits() -> usize {
759 SB128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
760}
761
762/// The 64x128-half count since the last call, and zero it.
763pub fn take_sb128_vert_hits() -> usize {
764 SB128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
765}
766
767/// lane-ab128: how many AB-shape roots the inter writer has coded since the
768/// last [`take_sb128_ab_hits`], in `PARTITION_HORZ_A` .. `_VERT_B` order
769/// (class `gate-blind-to-feature`).
770static SB128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
771 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
772
773/// The four per-shape AB-root counts since the last call, and zero them.
774pub fn take_sb128_ab_hits() -> [usize; 4] {
775 std::array::from_fn(|i| SB128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
776}
777
778/// lane-b128r: how many of those blocks carried a REAL residual (four
779/// TX_64X64 luma units plus their per-chunk chroma pair) rather than being
780/// skipped, since the last [`take_sb128_residual_hits`].
781static SB128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
782
783/// The 128x128-with-residual count since the last call, and zero it.
784pub fn take_sb128_residual_hits() -> usize {
785 SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
786}
787/// lane-rectres: how many RECT/AB pieces (the halves and 64x64 squares
788/// [`write_inter_block_128_rect`] codes) carried a REAL residual rather than
789/// being skipped, since the last [`take_sb128_rectres_hits`] -- the writer
790/// side of [`crate::encode::take_b128_rectres_hits`]'s search count.
791static SB128_RECTRES_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
792
793/// The rect/AB-piece-with-residual count since the last call, and zero it.
794pub fn take_sb128_rectres_hits() -> usize {
795 SB128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
796}
797
798/// lane-b128r: how many of those blocks named a SECOND reference (the
799/// compound arm at the 128 root), since the last
800/// [`take_sb128_compound_hits`].
801static SB128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
802
803/// The compound-128 count since the last call, and zero it.
804pub fn take_sb128_compound_hits() -> usize {
805 SB128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
806}
807
808/// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since
809/// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).
810static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
811
812/// The 128x128-block count since the last call, and zero it.
813pub fn take_sb128_none_hits() -> usize {
814 SB128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
815}
816
817/// `read_lr`'s write side, called once at the top of every superblock,
818/// before its partition symbol: writes the units this superblock's own
819/// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
820/// column scaling is the plain mi one).
821fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32, span: u32) {
822 LR_PLAN.with(|c| {
823 let mut plan = c.borrow_mut();
824 let Some(plan) = plan.as_mut() else { return };
825 let unit = plan.unit_size;
826 let rcol0 = (mi_col * 4).div_ceil(unit);
827 let rcol1 = ((mi_col + span) * 4).div_ceil(unit).min(plan.horz_units);
828 let rrow0 = (mi_row * 4).div_ceil(unit);
829 let rrow1 = ((mi_row + span) * 4).div_ceil(unit).min(plan.vert_units);
830 for rrow in rrow0..rrow1 {
831 for rcol in rcol0..rcol1 {
832 let info = plan.units[(rcol + rrow * plan.horz_units) as usize];
833 enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener);
834 if let Some(info) = info {
835 crate::restoration::write_wiener_filter(enc, false, &mut plan.reference, &info);
836 }
837 }
838 }
839 });
840}
841
842/// A 64x64 superblock's width in 4x4 mode-info units (`SB_MI` in
843/// `crate::decode`), the span [`write_lr`] resolves its units over.
844const SB_MI_W: u32 = 16;
845
846/// One tile's own superblock and mode-info span (spec 5.11.1's tile loop
847/// bounds): `MiColStarts[i]..MiColStarts[i+1]` and the same down the rows,
848/// with the superblock indices those mi bounds fall on. The writers walk
849/// exactly this rect, and everything a block reads outside it -- the
850/// neighbour bands, the MV grid -- is left at the "unavailable" state a
851/// tile's own first row and column see, which is how the decoder clips them
852/// (`MiGrid::set_tile_bounds`, `PlaneBuf::set_tile_origin`).
853#[derive(Clone, Copy, Debug, PartialEq, Eq)]
854pub(crate) struct TileRect {
855 pub(crate) sb_col0: u32,
856 pub(crate) sb_col1: u32,
857 pub(crate) sb_row0: u32,
858 pub(crate) sb_row1: u32,
859 pub(crate) mi_col0: u32,
860 pub(crate) mi_col1: u32,
861 pub(crate) mi_row0: u32,
862 pub(crate) mi_row1: u32,
863}
864
865impl TileRect {
866 /// The whole frame as one tile -- what every single-tile caller writes.
867 pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self {
868 let (cols, rows) = block_grid(mi_cols, mi_rows);
869 Self {
870 sb_col0: 0,
871 sb_col1: cols.div_ceil(2),
872 sb_row0: 0,
873 sb_row1: rows.div_ceil(2),
874 mi_col0: 0,
875 mi_col1: mi_cols,
876 mi_row0: 0,
877 mi_row1: mi_rows,
878 }
879 }
880}
881
882/// A frame's uniform tile grid (spec 5.9.15's `uniform_tile_spacing_flag`
883/// arm, mirrored from `ec_av1_syntax::frame::read_tile_info` so that what
884/// this encoder writes and what a decoder derives from the same two log2
885/// fields are the same rects). 64x64 superblocks only, which is the only
886/// size this encoder's sequence header signals.
887#[derive(Clone, Debug)]
888pub(crate) struct TileLayout {
889 pub(crate) cols_log2: u32,
890 pub(crate) rows_log2: u32,
891 /// Tile column starts in superblocks, `cols + 1` entries.
892 col_starts_sb: Vec<u32>,
893 /// Tile row starts in superblocks, `rows + 1` entries.
894 row_starts_sb: Vec<u32>,
895 mi_cols: u32,
896 mi_rows: u32,
897}
898
899impl TileLayout {
900 /// The layout `cols_log2`/`rows_log2` name for this frame's mi grid.
901 pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self {
902 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
903 let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2));
904 // lane-sb128: a tile boundary is a SUPERBLOCK boundary, so under a
905 // 128 superblock the starts are laid out on the 128 grid and then
906 // doubled back into the 64-cell units the writers walk.
907 let unit = u32::from(crate::encode::sb128_on()) + 1;
908 let starts = |total: u32, log2: u32| {
909 let total128 = total.div_ceil(unit);
910 let step = total128.div_ceil(1 << log2).max(1);
911 let mut v: Vec<u32> = (0..total128)
912 .step_by(step as usize)
913 .map(|s| s * unit)
914 .collect();
915 v.push(total);
916 v
917 };
918 Self {
919 cols_log2,
920 rows_log2,
921 col_starts_sb: starts(sb_cols, cols_log2),
922 row_starts_sb: starts(sb_rows, rows_log2),
923 mi_cols,
924 mi_rows,
925 }
926 }
927
928 pub(crate) fn cols(&self) -> u32 {
929 self.col_starts_sb.len() as u32 - 1
930 }
931
932 pub(crate) fn rows(&self) -> u32 {
933 self.row_starts_sb.len() as u32 - 1
934 }
935
936 pub(crate) fn count(&self) -> usize {
937 (self.cols() * self.rows()) as usize
938 }
939
940 /// `MiColStarts`/`MiRowStarts` as the frame header carries them.
941 pub(crate) fn mi_col_starts(&self) -> Vec<u32> {
942 let mut v: Vec<u32> = self.col_starts_sb[..self.cols() as usize]
943 .iter()
944 .map(|sb| sb * SB_MI_W)
945 .collect();
946 v.push(self.mi_cols);
947 v
948 }
949
950 pub(crate) fn mi_row_starts(&self) -> Vec<u32> {
951 let mut v: Vec<u32> = self.row_starts_sb[..self.rows() as usize]
952 .iter()
953 .map(|sb| sb * SB_MI_W)
954 .collect();
955 v.push(self.mi_rows);
956 v
957 }
958
959 /// Tile `index` (row major, `TileNum`) as a rect.
960 pub(crate) fn rect(&self, index: usize) -> TileRect {
961 let (r, c) = (index / self.cols() as usize, index % self.cols() as usize);
962 let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]);
963 let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]);
964 TileRect {
965 sb_col0,
966 sb_col1,
967 sb_row0,
968 sb_row1,
969 mi_col0: sb_col0 * SB_MI_W,
970 mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols),
971 mi_row0: sb_row0 * SB_MI_W,
972 mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows),
973 }
974 }
975
976 /// The largest tile by mi area, `context_update_tile_id`'s own rule
977 /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both
978 /// name the biggest tile, whose end-of-tile tables the frame stores).
979 pub(crate) fn largest_tile(&self) -> usize {
980 (0..self.count())
981 .max_by_key(|&i| {
982 let t = self.rect(i);
983 ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64)
984 })
985 .unwrap_or(0)
986 }
987}
988
989/// lane-edge128: which 64x64 CDEF unit's `cdef_idx` literal covers each unit
990/// of this frame, in the same raster order [`arm_cdef_idx`]'s grid is in.
991///
992/// `read_cdef` (spec 5.11.56) codes ONE literal for the block that first
993/// reaches a unit and copies it over every unit that block SPANS, so a whole
994/// 128x128 root block puts one literal in the stream for all four of its
995/// units -- the encoder's CDEF search, which prices a preset per unit, may
996/// not hand those four units different presets: only the first would be
997/// coded, and every decoder (ours and ffmpeg's alike) would apply it to all
998/// four while the encoder's own filter replay applied four different ones.
999/// That is the shape this map exists to collapse
1000/// ([`crate::filter_search::pick_filters`]).
1001///
1002/// lane-rectres: the same holds for a Rect128 half or an Ab128 half that
1003/// carries a residual (`EC_AV1_RECTRES`) -- it codes one literal at its own
1004/// origin and the decoder stamps BOTH units it spans with it, so its pair is
1005/// collapsed onto the origin unit too. Its 64x64 squares cover exactly one
1006/// unit each, and a SKIP-ONLY rect/AB piece codes no literal at all (the
1007/// decoder's per-piece `cdef_transmitted` reset never fires), so neither
1008/// touches this map -- only pieces the writer really codes a residual for.
1009pub(crate) fn cdef_unit_owner(blocks: &[Quadrant], mi_cols: u32, mi_rows: u32) -> Vec<u32> {
1010 let (cols, rows) = block_grid(mi_cols, mi_rows);
1011 let (sb_cols, sb_rows) = (cols.div_ceil(2) as usize, rows.div_ceil(2) as usize);
1012 let mut owner: Vec<u32> = (0..(sb_cols * sb_rows) as u32).collect();
1013 // Collapses every 64x64 unit `(ur, uc) ..` a residual piece at unit
1014 // `(ur, uc)` with footprint `(w, h)` spans onto the piece's origin --
1015 // [`crate::encode::write_inter_block_128_rect`]'s one `write_cdef_idx`
1016 // is what the decoder copies over all of them.
1017 let collapse = |owner: &mut Vec<u32>, (ur, uc): (usize, usize), (w, h): (usize, usize)| {
1018 let origin = (ur * sb_cols + uc) as u32;
1019 for r in ur..(ur + (h / 64).max(1)).min(sb_rows) {
1020 for c in uc..(uc + (w / 64).max(1)).min(sb_cols) {
1021 owner[r * sb_cols + c] = origin;
1022 }
1023 }
1024 };
1025 for sb_r in (0..sb_rows).step_by(2) {
1026 for sb_c in (0..sb_cols).step_by(2) {
1027 let Some(root) = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize)
1028 .then(|| &blocks[(sb_r * 2) * cols as usize + sb_c * 2])
1029 else {
1030 continue;
1031 };
1032 match root {
1033 Quadrant::Whole128(_) => {
1034 let origin = (sb_r * sb_cols + sb_c) as u32;
1035 for r in sb_r..(sb_r + 2).min(sb_rows) {
1036 for c in sb_c..(sb_c + 2).min(sb_cols) {
1037 owner[r * sb_cols + c] = origin;
1038 }
1039 }
1040 }
1041 // lane-rectres: the two halves of a HORZ/VERT root sit in
1042 // different unit rows (HORZ) / columns (VERT); each
1043 // non-skip half collapses its own pair.
1044 Quadrant::Rect128(horz, halves) => {
1045 for (i, half) in halves.iter().enumerate() {
1046 if half.skip {
1047 continue;
1048 }
1049 let (ur, uc) = if *horz {
1050 (sb_r + i, sb_c)
1051 } else {
1052 (sb_r, sb_c + i)
1053 };
1054 let (w, h) = if *horz { (128, 64) } else { (64, 128) };
1055 collapse(&mut owner, (ur, uc), (w, h));
1056 }
1057 }
1058 // lane-rectres: the AB half is the only multi-unit piece
1059 // (its two squares are one unit each); only a non-skip one
1060 // codes a literal, so only it fires.
1061 Quadrant::Ab128(symbol, pieces) => {
1062 for (piece, ((mi_r, mi_c), (w, h))) in pieces
1063 .iter()
1064 .zip(crate::encode::ab128_pieces(usize::from(*symbol), (0, 0)))
1065 {
1066 if piece.skip {
1067 continue;
1068 }
1069 let (ur, uc) = (sb_r + mi_r / 16, sb_c + mi_c / 16);
1070 collapse(&mut owner, (ur, uc), (w, h));
1071 }
1072 }
1073 _ => {}
1074 }
1075 }
1076 }
1077 owner
1078}
1079
1080/// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
1081struct CdefIdxPlan {
1082 /// The header's `cdef_bits`; never 0 while armed.
1083 bits: u8,
1084 /// Superblocks per row, the stride of `grid`.
1085 sb_cols: usize,
1086 /// One index per 64x64 superblock, in raster order.
1087 grid: Vec<u8>,
1088 /// The superblock whose literal was already written -- the decoder's
1089 /// `cdef_transmitted`, which resets at every superblock and which coding
1090 /// order (each superblock's blocks are contiguous) makes a single slot.
1091 last: Option<usize>,
1092}
1093
1094thread_local! {
1095 static CDEF_IDX: std::cell::RefCell<Option<CdefIdxPlan>> =
1096 const { std::cell::RefCell::new(None) };
1097}
1098
1099/// Arms the next tile write with one `cdef_idx` per 64x64 superblock.
1100/// `bits == 0` disarms (the header codes a single strength pair, so the tile
1101/// carries no literal at all).
1102pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
1103 CDEF_IDX.with(|c| {
1104 *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan {
1105 bits,
1106 sb_cols,
1107 grid,
1108 last: None,
1109 });
1110 });
1111}
1112
1113/// One frame's per-superblock quantizer plan (lane-deltaq, see
1114/// [`arm_delta_q`]): the writer side of decode.rs `maybe_read_delta_q`.
1115struct DeltaQPlan {
1116 /// `1 << delta_q_res`, the multiplier the coded symbol is scaled by --
1117 /// every `grid` entry is congruent to `base` modulo it, so the delta the
1118 /// writer codes is always a whole number of steps.
1119 res: i32,
1120 /// Superblocks per row, the stride of `grid`.
1121 sb_cols: usize,
1122 /// The absolute `qindex` each 64x64 superblock is coded at, raster order.
1123 grid: Vec<u8>,
1124 /// The spec's `CurrentQIndex`, carried across the superblocks of THIS
1125 /// tile -- armed at the frame's `base_q_idx` because a tile writer is
1126 /// armed once per tile (`encode_inter_frame`'s `code_tiles`), which is
1127 /// exactly the spec's own per-tile reset.
1128 cur: i32,
1129}
1130
1131thread_local! {
1132 static DELTA_Q: std::cell::RefCell<Option<DeltaQPlan>> =
1133 const { std::cell::RefCell::new(None) };
1134}
1135
1136/// Arms the next tile write with one absolute `qindex` per 64x64 superblock.
1137/// Disarmed (a plain no-op writer, byte for byte what this crate wrote before
1138/// lane-deltaq) when `res == 0`.
1139pub(crate) fn arm_delta_q(res: i32, sb_cols: usize, grid: Vec<u8>, base: u8) {
1140 DELTA_Q.with(|c| {
1141 *c.borrow_mut() = (res > 0).then(|| DeltaQPlan {
1142 res,
1143 sb_cols,
1144 grid,
1145 cur: i32::from(base),
1146 });
1147 });
1148}
1149
1150thread_local! {
1151 static SIGN_BIAS: std::cell::Cell<crate::mvstack::SignBiasTable> =
1152 const { std::cell::Cell::new(crate::mvstack::NO_SIGN_BIAS) };
1153}
1154
1155/// Arms the next tile write with this frame's `ref_frame_sign_bias` (spec
1156/// 5.9.2), the table its MV-stack scans run under. Armed the same way
1157/// [`arm_cdef_idx`]/[`arm_lr`] are -- and disarmed by the same guard -- so
1158/// that a frame with a backward reference needs no new parameter on the four
1159/// nested writer helpers between here and `find_mv_stack`. A frame that never
1160/// names a future reference leaves this alone: all-`false` is what every
1161/// stream this crate wrote before pyramids existed codes under.
1162pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
1163 SIGN_BIAS.with(|c| c.set(sign_bias));
1164}
1165
1166thread_local! {
1167 static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1168}
1169
1170/// Arms the next tile write with this frame's `allow_screen_content_tools`
1171/// (spec 5.9.2), which is what makes every intra block carry the
1172/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46
1173/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/
1174/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that
1175/// never detected screen content writes exactly the stream it wrote before
1176/// this lane.
1177pub(crate) fn arm_screen(on: bool) {
1178 SCREEN.with(|c| c.set(on));
1179}
1180
1181thread_local! {
1182 /// This frame's `(mi_rows, mi_cols)` (spec `compute_image_size`), armed
1183 /// beside [`SCREEN`] by both frame encoders: a palette block cut by the
1184 /// frame's right/bottom mi edge codes its colour-index map over the
1185 /// ON-SCREEN part only, so the writer needs the same dims the decoder's
1186 /// `palette_onscreen` reads off its `FrameCtx` (lane-palw). `(0, 0)`
1187 /// -- an unarmed writer, i.e. a unit test coding one block -- clamps
1188 /// nothing, which is what every stream without a cut palette block codes.
1189 static FRAME_MI_DIMS: std::cell::Cell<(usize, usize)> =
1190 const { std::cell::Cell::new((0, 0)) };
1191}
1192
1193/// Arms the next tile write with this frame's `(mi_rows, mi_cols)`.
1194pub(crate) fn arm_frame_mi_dims(dims: (usize, usize)) {
1195 FRAME_MI_DIMS.with(|c| c.set(dims));
1196}
1197
1198/// The armed `(mi_rows, mi_cols)`, or a grid big enough to clamp nothing.
1199fn frame_mi_dims() -> (usize, usize) {
1200 match FRAME_MI_DIMS.with(std::cell::Cell::get) {
1201 (0, 0) => (usize::MAX / 8, usize::MAX / 8),
1202 dims => dims,
1203 }
1204}
1205
1206fn screen_armed() -> bool {
1207 SCREEN.with(std::cell::Cell::get)
1208}
1209
1210thread_local! {
1211 /// This frame header's `allow_intrabc` (spec 5.9.2), armed exactly like
1212 /// [`SCREEN`]: with it every intra block of the tile carries a
1213 /// `use_intrabc` symbol right after `skip`/`cdef`/`delta_q` (decode.rs
1214 /// `read_intra_mode`), so a tile written without it and read with it
1215 /// desyncs at the first block.
1216 static INTRABC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1217 /// The mi grid the DV predictor is built off (decode.rs
1218 /// `INTRABC_MI_GRID`/`record_intrabc_mi`): every coded block publishes
1219 /// its own footprint into it, an intrabc one also its DV as an
1220 /// `INTRA_FRAME` candidate. `Some` only while an `allow_intrabc` tile is
1221 /// being written.
1222 static INTRABC_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1223 const { std::cell::RefCell::new(None) };
1224}
1225
1226/// Arms the frame's `allow_intrabc` bit for the next tile written on this
1227/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
1228pub(crate) fn arm_intrabc(on: bool) {
1229 INTRABC.with(|c| c.set(on));
1230}
1231
1232fn intrabc_armed() -> bool {
1233 INTRABC.with(std::cell::Cell::get)
1234}
1235
1236thread_local! {
1237 /// This SEQUENCE header's `enable_filter_intra` (spec 5.5.2), armed
1238 /// exactly like [`SCREEN`]: with it every DC_PRED intra block of at most
1239 /// 32x32 that took no luma palette carries a `use_filter_intra` symbol
1240 /// after the palette colours and before the colour-index maps (decode.rs
1241 /// `read_intra_mode`), so a tile written without it and read with it
1242 /// desyncs at the first such block.
1243 static FILTER_INTRA: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1244}
1245
1246/// Arms the sequence's `enable_filter_intra` bit for the next tile written on
1247/// this thread; cleared by [`CdefIdxGuard`] when that writer returns.
1248pub(crate) fn arm_filter_intra(on: bool) {
1249 FILTER_INTRA.with(|c| c.set(on));
1250}
1251
1252fn filter_intra_armed() -> bool {
1253 FILTER_INTRA.with(std::cell::Cell::get)
1254}
1255
1256/// How many blocks this writer coded `use_filter_intra == 1`, and the
1257/// histogram of the five `filter_intra_mode`s (index 1..=5) -- the fire count
1258/// a gate prints so that "filter intra is on" is a measurement rather than a
1259/// claim (class `gate-blind-to-feature`). Index 0 is the block count.
1260static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] =
1261 [const { std::sync::atomic::AtomicUsize::new(0) }; 6];
1262
1263/// Reads [`FILTER_INTRA_HITS`] and zeroes it, so a gate can attribute the
1264/// counts to its own encode.
1265#[cfg(test)]
1266pub(crate) fn take_filter_intra_hits() -> [usize; 6] {
1267 std::array::from_fn(|i| FILTER_INTRA_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1268}
1269
1270/// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for
1271/// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every
1272/// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <=
1273/// 32, [`crate::decode::filter_intra_size_class`]) and that took no luma
1274/// palette (`av1_filter_intra_allowed`, reconintra.h:77), then the chosen mode
1275/// of five. Sits between the palette COLOUR lists and the colour-index maps,
1276/// where libaom reads it (`av1_visit_palette` runs after
1277/// `read_filter_intra_mode_info`).
1278fn write_filter_intra(
1279 enc: &mut SymbolEncoder,
1280 cdfs: &mut Cdfs,
1281 mode: usize,
1282 side: usize,
1283 has_palette_y: bool,
1284 filter_intra: Option<u8>,
1285) {
1286 if !filter_intra_armed() || mode != DC_PRED || has_palette_y {
1287 debug_assert!(
1288 filter_intra.is_none(),
1289 "no `use_filter_intra` symbol exists here"
1290 );
1291 return;
1292 }
1293 let Some(class) = crate::decode::filter_intra_size_class(side) else {
1294 debug_assert!(
1295 filter_intra.is_none(),
1296 "past av1_filter_intra_allowed_bsize"
1297 );
1298 return;
1299 };
1300 enc.symbol(
1301 usize::from(filter_intra.is_some()),
1302 &mut cdfs.filter_intra[class],
1303 );
1304 if let Some(fi) = filter_intra {
1305 enc.symbol(usize::from(fi), &mut cdfs.filter_intra_mode);
1306 FILTER_INTRA_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1307 FILTER_INTRA_HITS[usize::from(fi) + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1308 }
1309}
1310
1311/// The coefficient-table row a block's luma transform types are coded from:
1312/// `fimode_to_intradir[filter_intra_mode]` for a filter-intra block, its own
1313/// luma mode otherwise (class `filter-intra tx_type row`, decode.rs
1314/// [`crate::decode::fi_tx_row`]). The block still PUBLISHES `DC_PRED` as its
1315/// neighbour mode -- libaom's `mbmi->mode` is unchanged by filter intra.
1316fn tx_row(mode: usize, filter_intra: Option<u8>) -> usize {
1317 crate::decode::fi_tx_row(mode, filter_intra.map(usize::from))
1318}
1319
1320/// How many blocks this writer coded `use_intrabc == 1`, and the histogram of
1321/// their DV magnitudes in full pels (index 1..=6 = 1, 2, 4, 8, 16, 32 pels
1322/// and up, by the larger component) -- the fire count a gate prints so that
1323/// "intrabc is on" is a measurement rather than a claim (class
1324/// `gate-blind-to-feature`). Index 0 is the block count.
1325static INTRABC_HITS: [std::sync::atomic::AtomicUsize; 7] =
1326 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1327
1328fn note_intrabc(dv: (i32, i32)) {
1329 INTRABC_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1330 let px = (dv.0.abs() / 8).max(dv.1.abs() / 8).max(1) as usize;
1331 let bucket = (usize::BITS - px.leading_zeros()) as usize;
1332 INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1333}
1334
1335/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts
1336/// to its own encode.
1337#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1338pub(crate) fn take_intrabc_hits() -> [usize; 7] {
1339 std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1340}
1341
1342thread_local! {
1343 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
1344 /// the same way `arm_sign_bias` arms the sign-bias table rather than
1345 /// threaded through the five nested writer helpers between here and the
1346 /// per-block mode syntax. `true` makes every inter block of size at least
1347 /// 8x8 code a `comp_mode` symbol, exactly where decode.rs `read_comp_mode`
1348 /// reads one.
1349 static REFERENCE_SELECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1350}
1351
1352/// Arms the frame's `reference_select` bit for the next tile written on this
1353/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
1354pub(crate) fn arm_reference_select(on: bool) {
1355 REFERENCE_SELECT.with(|c| c.set(on));
1356}
1357
1358thread_local! {
1359 /// This frame header's own `is_motion_mode_switchable` bit (spec 5.9.2),
1360 /// armed exactly like [`REFERENCE_SELECT`]. `true` makes every
1361 /// single-reference inter block that libaom's `motion_mode_allowed`
1362 /// accepts carry a `motion_mode`/`obmc` symbol right after its MV syntax,
1363 /// exactly where decode.rs' `read_motion_mode` reads one.
1364 static MOTION_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1365}
1366
1367thread_local! {
1368 /// This frame header's own `allow_warped_motion` bit (spec 5.9.2): with
1369 /// it set, every block libaom's `motion_mode_allowed` accepts AND that
1370 /// has at least one warp sample (`num_proj_ref >= 1`) reads the 3-symbol
1371 /// `motion_mode_cdf` alphabet instead of the 2-symbol `obmc_cdf` one.
1372 /// lane-av1obmc2.
1373 static WARPED_MOTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1374 /// The frame geometry the warp-sample walk needs (`num_proj_ref` ->
1375 /// `has_top_right`), which is only ever this writer's own superblock
1376 /// size. Every stream this crate writes uses a 64 superblock, which is
1377 /// `FrameCtx::new`'s default.
1378 /// corner-cut: ceiling is a 128-superblock WRITER -- it must arm the real
1379 /// frame context here (or take one as a parameter) or the warp-sample
1380 /// walk reads the wrong `has_top_right` geometry.
1381 static WRITER_FCTX: crate::decode::FrameCtx = crate::decode::FrameCtx::new();
1382}
1383
1384/// Arms [`WARPED_MOTION`] for the next tile written on this thread.
1385pub(crate) fn arm_warped_motion(on: bool) {
1386 WARPED_MOTION.with(|c| c.set(on));
1387}
1388
1389/// Arms the frame's `is_motion_mode_switchable` bit for the next tile written
1390/// on this thread; cleared by [`CdefIdxGuard`] when that writer returns.
1391pub(crate) fn arm_motion_mode(on: bool) {
1392 MOTION_MODE.with(|c| c.set(on));
1393}
1394
1395/// How many single-reference inter blocks this writer coded a `motion_mode`
1396/// symbol for, split by the value it coded and by the block's own footprint
1397/// -- the histogram a gate prints so that "OBMC is on" is a measurement, not
1398/// a claim (class `gate-blind-to-feature`). Index: `0 + 2 * bucket` for
1399/// SIMPLE, `1 + 2 * bucket` for OBMC, bucket 0/1/2 = 32x32/16x16/8x8.
1400static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] =
1401 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
1402
1403/// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the
1404/// counts to its own encode.
1405#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1406pub(crate) fn take_motion_mode_hits() -> [usize; 9] {
1407 std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1408}
1409
1410/// What the 3-symbol `motion_mode` symbol costs, in bits, against the same
1411/// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off --
1412/// which alphabet a block reads is `motion_mode_allowed`'s own choice
1413/// ([`write_motion_mode`]).
1414pub(crate) fn motion_mode_symbol_bits(row: usize, motion: u8) -> f64 {
1415 PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
1416 Some(s) => crate::encode::symbol_bits(&s.0.motion_mode[row], usize::from(motion)),
1417 None => crate::encode::symbol_bits(&crate::cdf::MOTION_MODE[row], usize::from(motion)),
1418 })
1419}
1420
1421/// What the `motion_mode`/`obmc` symbol costs, in bits, against the tables
1422/// this frame's writer really starts from ([`arm_pricing_cdfs`]) -- the same
1423/// tables the coefficients are priced off since lane-av1price2, rather than
1424/// the static defaults the symbol used to be estimated with. Falls back to
1425/// the default table whenever the search is armed with the defaults (a key
1426/// frame, or a screen frame the gate turned off).
1427pub(crate) fn obmc_symbol_bits(row: usize, obmc: bool) -> f64 {
1428 PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
1429 Some(s) => crate::encode::symbol_bits(&s.0.obmc[row], usize::from(obmc)),
1430 None => crate::encode::symbol_bits(&crate::cdf::OBMC[row], usize::from(obmc)),
1431 })
1432}
1433
1434/// `read_motion_mode`'s write side (spec 5.11.24), called on a
1435/// single-reference inter block right after its MV syntax and before the
1436/// (never switchable here) interpolation filter -- libaom's own sequential
1437/// order in `read_inter_block_mode_info`.
1438///
1439/// Eligibility is decode.rs' own `motion_mode_eligible`, term for term, with
1440/// the terms this writer settles statically dropped: no block it codes is
1441/// `skip_mode`, interintra or a non-IDENTITY-global `GLOBALMV` one, so what
1442/// is left is the footprint floor and the overlappable-neighbour walk
1443/// ([`crate::decode::has_overlappable_neighbour`], shared with the decoder so
1444/// the two cannot drift). The frame header keeps `allow_warped_motion == 0`,
1445/// so the alphabet is always the 2-symbol `obmc_cdf`, never the 3-symbol
1446/// `motion_mode_cdf`.
1447fn write_motion_mode(
1448 enc: &mut SymbolEncoder,
1449 cdfs: &mut Cdfs,
1450 grid: &MiGrid,
1451 (mi_row, mi_col): (usize, usize),
1452 (bw4, bh4): (usize, usize),
1453 (write_w, write_h): (usize, usize),
1454 (mi_cols, mi_rows): (usize, usize),
1455 // This block's own reference, for the warp-sample walk that picks the
1456 // alphabet (`num_proj_ref`).
1457 ref_frame: i8,
1458 // 0 SIMPLE_TRANSLATION, 1 OBMC_CAUSAL, 2 WARPED_CAUSAL -- what the
1459 // encoder's search committed for this block.
1460 motion: u8,
1461) -> Result<()> {
1462 let eligible = MOTION_MODE.with(std::cell::Cell::get)
1463 && write_w.min(write_h) >= 8
1464 && crate::decode::has_overlappable_neighbour(
1465 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows,
1466 );
1467 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
1468 let proj = WRITER_FCTX.with(|fctx| {
1469 crate::decode::num_proj_ref(
1470 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1471 )
1472 });
1473 eprintln!(
1474 "EC_MMW mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} proj={proj} warp_armed={} motion={motion}",
1475 eligible as u8,
1476 WARPED_MOTION.with(std::cell::Cell::get) as u8,
1477 );
1478 }
1479 if !eligible {
1480 // The encoder trialled an OBMC prediction for a block this writer
1481 // codes as SIMPLE_TRANSLATION: its reconstruction is not the
1482 // decoder's (class encoder-grid-drift), which is exactly what the
1483 // `EC_COMP_MISMATCH` rung exists to catch.
1484 if motion != 0 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
1485 eprintln!(
1486 "EC_COMP_MISMATCH motion_mode enc=OBMC wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
1487 );
1488 }
1489 return Ok(());
1490 }
1491 let row = crate::decode::motion_mode_cdf_row(write_w, write_h).ok_or_else(|| {
1492 Error::unsupported(
1493 "AV1 tile",
1494 format!("a {write_w}x{write_h} block has no motion_mode CDF row"),
1495 )
1496 })?;
1497 // libaom `motion_mode_allowed`: the 3-symbol `motion_mode_cdf` alphabet
1498 // exactly when `allow_warped_motion` is on and the block has at least one
1499 // warp sample. The other two vetoes libaom applies there cannot fire for
1500 // a stream this encoder writes -- it codes no scaled reference and no
1501 // inter frame with `force_integer_mv` -- and the decoder checks all three
1502 // (`decode.rs`'s `warp_eligible`), so the two sides agree term for term.
1503 let warp_alphabet = WARPED_MOTION.with(std::cell::Cell::get)
1504 && WRITER_FCTX.with(|fctx| {
1505 crate::decode::num_proj_ref(
1506 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1507 )
1508 }) >= 1;
1509 if warp_alphabet {
1510 enc.symbol(usize::from(motion), &mut cdfs.motion_mode[row]);
1511 } else {
1512 // A warp winner whose block the writer resolves to the 2-symbol
1513 // alphabet would reconstruct as SIMPLE at the decoder: the same
1514 // encoder-grid-drift rung the OBMC case above prints.
1515 if motion == 2 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
1516 eprintln!(
1517 "EC_COMP_MISMATCH motion_mode enc=WARP wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
1518 );
1519 }
1520 enc.symbol(usize::from(motion == 1), &mut cdfs.obmc[row]);
1521 }
1522 let bucket = match write_w.min(write_h) {
1523 32.. => 0,
1524 16 => 1,
1525 _ => 2,
1526 };
1527 MOTION_MODE_HITS[usize::from(motion.min(2)) + 3 * bucket]
1528 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1529 Ok(())
1530}
1531
1532/// The compound half of a block's end-of-block neighbour record: nothing for
1533/// a single-reference or intra block, and `record_compound_mi`'s overwrite of
1534/// the ALTREF default for a compound one (this writer only codes
1535/// `comp_group_idx == 0`, `compound_idx == 1`).
1536fn record_block_compound(
1537 neighbours: &mut Neighbours,
1538 at_mi: (usize, usize),
1539 side: usize,
1540 block: &BlockCoeffs,
1541) {
1542 if let Some(r1) = block.inter.and_then(|i| i.ref1) {
1543 neighbours.record_compound_mi(at_mi, side, r1, 0, 1);
1544 }
1545}
1546
1547/// decode.rs' own `is_uni_comp_ref`: a pair is `UNIDIR_COMP_REFERENCE`
1548/// exactly when both references sit on the same temporal side.
1549use crate::mvstack::is_uni_comp_ref;
1550
1551thread_local! {
1552 /// `(order_hint_bits, this frame's order hint, each reference's order
1553 /// hint)` -- what `get_comp_index_context` (decode.rs) needs to context
1554 /// the `compound_idx` symbol, armed the same way the sign-bias table is.
1555 static ORDER_HINTS: std::cell::Cell<(u32, u32, [u32; 7])> =
1556 const { std::cell::Cell::new((7, 0, [0; 7])) };
1557}
1558
1559/// Arms this frame's order hints for the next tile written on this thread.
1560pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) {
1561 ORDER_HINTS.with(|c| c.set((bits, order_hint, hints)));
1562}
1563
1564/// What [`arm_order_hints`] last armed: `(order_hint_bits, order_hint,
1565/// ref_order_hints)`, for the encoder's own per-reference distance.
1566pub(crate) fn order_hints() -> (u32, u32, [u32; 7]) {
1567 ORDER_HINTS.with(std::cell::Cell::get)
1568}
1569
1570thread_local! {
1571 /// lane-hpmv: this frame's `allow_high_precision_mv`, armed per worker
1572 /// beside [`arm_order_hints`] -- the writer's eighth-pel symbol, the
1573 /// pricer's mv bits and the motion search's finest step all read it.
1574 static HIGH_PRECISION_MV: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1575}
1576
1577/// Arms this frame's `allow_high_precision_mv` for the next tile written --
1578/// or searched -- on this thread.
1579pub(crate) fn arm_high_precision_mv(on: bool) {
1580 HIGH_PRECISION_MV.with(|c| c.set(on));
1581}
1582
1583/// What [`arm_high_precision_mv`] last armed on this thread.
1584pub(crate) fn high_precision_mv() -> bool {
1585 HIGH_PRECISION_MV.with(std::cell::Cell::get)
1586}
1587
1588/// lane-hpmv's witness counters: `[0]` counts every `mv_hp`/`mv_class0_hp`
1589/// symbol this process's writers coded (zero without
1590/// `allow_high_precision_mv`, one per non-zero mv component with it), `[1]`
1591/// counts the ones that came out ZERO -- an eighth-pel vector, i.e. one a
1592/// frame without the flag cannot name at all.
1593static HP_SYMBOLS: [std::sync::atomic::AtomicU64; 2] = [
1594 std::sync::atomic::AtomicU64::new(0),
1595 std::sync::atomic::AtomicU64::new(0),
1596];
1597
1598/// Reads and clears [`HP_SYMBOLS`]: `(hp symbols coded, eighth-pel ones)`.
1599#[allow(dead_code)] // read only from the `#[cfg(test)]` witness
1600pub(crate) fn take_hp_symbols() -> (u64, u64) {
1601 let all = HP_SYMBOLS[0].swap(0, std::sync::atomic::Ordering::Relaxed);
1602 (
1603 all,
1604 HP_SYMBOLS[1].swap(0, std::sync::atomic::Ordering::Relaxed),
1605 )
1606}
1607
1608/// [`take_hp_symbols`] without clearing -- what the NEWMV census prints.
1609pub(crate) fn hp_symbols() -> (u64, u64) {
1610 use std::sync::atomic::Ordering::Relaxed;
1611 (HP_SYMBOLS[0].load(Relaxed), HP_SYMBOLS[1].load(Relaxed))
1612}
1613
1614/// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec
1615/// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref`
1616/// trees), symbol for symbol at the same contexts -- which are, as that
1617/// function's own doc records, `single_ref_p1_ctx`..`single_ref_p6_ctx`/
1618/// `uni_comp_ref_p1_ctx` under libaom's compound names.
1619///
1620/// # Errors
1621/// A pair this writer never forms (its `ref0` is not `LAST_FRAME`).
1622fn write_compound_ref_frames(
1623 enc: &mut SymbolEncoder,
1624 cdfs: &mut Cdfs,
1625 above: Option<crate::mvstack::NeighbourRef>,
1626 left: Option<crate::mvstack::NeighbourRef>,
1627 above_ref: i8,
1628 left_ref: i8,
1629 (ref0, ref1): (i8, i8),
1630) -> Result<()> {
1631 use crate::mvstack::{
1632 comp_reference_type_ctx, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
1633 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
1634 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
1635 LAST_FRAME,
1636 };
1637 let a = (above_ref > 0).then_some(above_ref);
1638 let l = (left_ref > 0).then_some(left_ref);
1639 let a1 = above.and_then(|n| n.ref1);
1640 let l1 = left.and_then(|n| n.ref1);
1641 let unidir = is_uni_comp_ref(ref0, ref1);
1642 enc.symbol(
1643 usize::from(!unidir),
1644 &mut cdfs.comp_ref_type[comp_reference_type_ctx(above, left)],
1645 );
1646 if unidir {
1647 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
1648 enc.symbol(
1649 usize::from(both_backward),
1650 &mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0],
1651 );
1652 if both_backward {
1653 return Ok(());
1654 }
1655 if ref0 != LAST_FRAME {
1656 return Err(Error::unsupported(
1657 "AV1 tile",
1658 "a unidirectional compound pair this writer does not form",
1659 ));
1660 }
1661 let past_last2 = ref1 != LAST2_FRAME;
1662 enc.symbol(
1663 usize::from(past_last2),
1664 &mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
1665 );
1666 if past_last2 {
1667 enc.symbol(
1668 usize::from(ref1 == GOLDEN_FRAME),
1669 &mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
1670 );
1671 }
1672 return Ok(());
1673 }
1674 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
1675 enc.symbol(
1676 usize::from(far),
1677 &mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0],
1678 );
1679 if far {
1680 enc.symbol(
1681 usize::from(ref0 == GOLDEN_FRAME),
1682 &mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
1683 );
1684 } else {
1685 enc.symbol(
1686 usize::from(ref0 == LAST2_FRAME),
1687 &mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1],
1688 );
1689 }
1690 let is_altref = ref1 == ALTREF_FRAME;
1691 enc.symbol(
1692 usize::from(is_altref),
1693 &mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0],
1694 );
1695 if !is_altref {
1696 enc.symbol(
1697 usize::from(ref1 == ALTREF2_FRAME),
1698 &mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1],
1699 );
1700 }
1701 Ok(())
1702}
1703
1704/// Per-mode and per-pair fire counts of [`write_compound_block`], for the
1705/// gate's own census (gate-blind-to-feature): modes indexed by the spec's
1706/// `INTER_COMPOUND_MODES`, pairs by `ref1` (`LAST`..`ALTREF`).
1707static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1708 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1709static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =
1710 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1711
1712/// Takes and clears the compound mode histogram.
1713#[cfg(test)]
1714pub(crate) fn take_compound_mode_hits() -> [usize; 8] {
1715 std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1716}
1717
1718/// Takes and clears the compound pair histogram, indexed by the SECOND
1719/// reference (`LAST` = 0 .. `ALTREF` = 6).
1720#[cfg(test)]
1721pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
1722 std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1723}
1724
1725/// Per-SIZE fire counts of [`write_compound_block`], indexed by
1726/// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
1727/// 32x32-only tool, so the share by size is what says whether the leaf
1728/// candidates fire at all (gate-blind-to-feature).
1729static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
1730 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
1731
1732/// Takes and clears the compound size histogram.
1733#[cfg(test)]
1734pub(crate) fn take_compound_size_hits() -> [usize; 4] {
1735 std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1736}
1737
1738/// The compound mode histogram of the LEAVES alone (`bw4 <= 4`, so 16x16 and
1739/// below). The frame-wide histogram above cannot say whether a mode reaches
1740/// the leaves at all, which is exactly the question every leaf compound step
1741/// asks (gate-blind-to-feature): before lane-av1comp4 gave a leaf its second
1742/// reference search, the two half-new modes were structurally impossible
1743/// there and screen capture's leaf compound was 100% `NEAREST_NEARESTMV`.
1744static COMPOUND_LEAF_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1745 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1746
1747/// Takes and clears the leaf-only compound mode histogram.
1748#[cfg(test)]
1749pub(crate) fn take_compound_leaf_mode_hits() -> [usize; 8] {
1750 std::array::from_fn(|i| {
1751 COMPOUND_LEAF_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)
1752 })
1753}
1754
1755/// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
1756/// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
1757/// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
1758/// order. Returns the two motion vectors the decoder derives (what the MI
1759/// grid must record) and whether the mode was a `NEW*` one.
1760///
1761/// Only the modes [`InterMode::compound_index`] names are written, and
1762/// only the `comp_group_idx == 0`, `compound_idx == 1` blend (spec
1763/// `COMPOUND_AVERAGE`) -- masked compound and the distance-weighted blend are
1764/// not searched.
1765///
1766/// # Errors
1767/// As [`write_mv`], or a pair/mode this writer does not form.
1768#[allow(clippy::too_many_arguments)]
1769fn write_compound_block(
1770 enc: &mut SymbolEncoder,
1771 cdfs: &mut Cdfs,
1772 neighbours: &Neighbours,
1773 grid: &crate::mvstack::MiGrid,
1774 (mi_row, mi_col): (usize, usize),
1775 (bw4, bh4): (usize, usize),
1776 (has_above, has_left): (bool, bool),
1777 info: InterInfo,
1778 (mi_cols, mi_rows): (usize, usize),
1779) -> Result<((i32, i32), (i32, i32), bool)> {
1780 let (Some(ref1), Some(mode)) = (info.ref1, info.mode.compound_index()) else {
1781 return Err(Error::unsupported(
1782 "AV1 tile",
1783 "a compound block needs a second reference and a compound mode",
1784 ));
1785 };
1786 let above = has_above.then(|| neighbours.above_nbr(mi_col));
1787 let left = has_left.then(|| neighbours.left_nbr(mi_row));
1788 write_compound_ref_frames(
1789 enc,
1790 cdfs,
1791 above,
1792 left,
1793 neighbours.above_ref[mi_col],
1794 neighbours.left_ref[mi_row],
1795 (info.ref_frame, ref1),
1796 )?;
1797 let stack = crate::mvstack::find_mv_stack_compound(
1798 grid,
1799 mi_row,
1800 mi_col,
1801 bw4,
1802 bh4,
1803 (info.ref_frame, ref1),
1804 mi_cols,
1805 mi_rows,
1806 grid.sign_bias_table(),
1807 &[(0, 0); 7],
1808 None,
1809 );
1810 let ctx = crate::cdf::COMPOUND_MODE_CTX_MAP[stack.ref_mv_ctx >> 1][stack.new_mv_ctx.min(4)];
1811 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1812 eprintln!(
1813 "EC_WCOMP mi_row={mi_row} mi_col={mi_col} mode={mode} ref0={} ref1={ref1} ctx={ctx} new_mv_ctx={} ref_mv_ctx={} stack={}",
1814 info.ref_frame, stack.new_mv_ctx, stack.ref_mv_ctx, stack.entries.len()
1815 );
1816 }
1817 enc.symbol(mode, &mut cdfs.inter_compound_mode[ctx]);
1818 // `assign_compound_mv`'s own DRL half: `NEW_NEWMV` walks from index 0,
1819 // the two derived modes code no index at all.
1820 let mvs = match info.mode {
1821 InterMode::NearestNearestMv => stack.nearest_mv,
1822 InterMode::GlobalGlobalMv => ((0, 0), (0, 0)),
1823 InterMode::NearNearMv => {
1824 // decode.rs `assign_compound_mv`'s second DRL loop: the index
1825 // starts at 1 and the mode's own `ref_mv_idx` is `idx - 1`, so
1826 // this walk starts at 1 too and reads entry `ref_mv_idx + 1`.
1827 let idx = usize::from(info.ref_mv_idx) + 1;
1828 let mut walk = 1usize;
1829 while walk < 3 && stack.entries.len() > walk + 1 {
1830 let advance = walk < idx;
1831 enc.symbol(
1832 usize::from(advance),
1833 &mut cdfs.drl_mode[stack.drl_ctx[walk]],
1834 );
1835 if !advance {
1836 break;
1837 }
1838 walk += 1;
1839 }
1840 let near = |i: usize| {
1841 stack
1842 .entries
1843 .get(i)
1844 .map_or(stack.near_mv, |e| (e.mv0, e.mv1))
1845 };
1846 if walk != idx && near(walk) != near(idx) {
1847 note_drl_clamp(idx, walk, stack.entries.len());
1848 }
1849 near(walk)
1850 }
1851 InterMode::NearestNewMv | InterMode::NewNearestMv => {
1852 // Neither mode codes a DRL index (the decoder leaves `ref_mv_idx`
1853 // at 0): the NEAREST half is derived, the NEW half codes a
1854 // residual against stack entry 0.
1855 let base = stack
1856 .entries
1857 .first()
1858 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
1859 if matches!(info.mode, InterMode::NearestNewMv) {
1860 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
1861 (stack.nearest_mv.0, info.mv1)
1862 } else {
1863 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
1864 (info.mv, stack.nearest_mv.1)
1865 }
1866 }
1867 _ => {
1868 let idx = usize::from(info.ref_mv_idx);
1869 let mut walk = 0usize;
1870 while walk < 2 && stack.entries.len() > walk + 1 {
1871 let advance = walk < idx;
1872 enc.symbol(
1873 usize::from(advance),
1874 &mut cdfs.drl_mode[stack.drl_ctx[walk]],
1875 );
1876 if !advance {
1877 break;
1878 }
1879 walk += 1;
1880 }
1881 let nearest = |i: usize| {
1882 stack
1883 .entries
1884 .get(i)
1885 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1))
1886 };
1887 if walk != idx && nearest(walk) != nearest(idx) {
1888 note_drl_clamp(idx, walk, stack.entries.len());
1889 }
1890 let base = nearest(walk);
1891 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
1892 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
1893 (info.mv, info.mv1)
1894 }
1895 };
1896 // spec 5.11.25's `comp_group_idx`/`compound_idx` are NOT coded: this
1897 // crate's sequence header carries `enable_masked_compound = false` and
1898 // `enable_jnt_comp = false` (encode.rs), and decode.rs reads neither
1899 // symbol under those bits -- it infers `comp_group_idx = 0`,
1900 // `compound_idx = 1` (the simple average), which is the only blend this
1901 // writer forms anyway. A lane that turns either sequence bit on has to
1902 // write the matching symbol here, at
1903 // `get_comp_group_idx_context`/`get_comp_index_context`'s contexts (which
1904 // is what `Neighbours::above_comp_group_idx`/`above_compound_idx` and the
1905 // armed order hints below are already kept for).
1906 let _ = ORDER_HINTS.with(std::cell::Cell::get);
1907 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1908 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
1909 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1910 COMPOUND_SIZE_HITS[(bw4.max(1).trailing_zeros() as usize).min(3)]
1911 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1912 if bw4 <= 4 {
1913 COMPOUND_LEAF_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1914 }
1915 if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {
1916 eprintln!(
1917 "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",
1918 info.mv, info.mv1, mvs.0, mvs.1
1919 );
1920 }
1921 // decode.rs' own `is_new_mv` for a compound block: modes 2, 3, 4, 5, 7.
1922 Ok((
1923 mvs.0,
1924 mvs.1,
1925 matches!(
1926 info.mode,
1927 InterMode::NewNewMv | InterMode::NearestNewMv | InterMode::NewNearestMv
1928 ),
1929 ))
1930}
1931
1932/// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's
1933/// `comp_mode`): on a `reference_select` frame every inter block whose size
1934/// allows compound (`is_comp_ref_allowed`, always true here -- this writer's
1935/// smallest leaf is 8x8) names SINGLE or COMPOUND, at
1936/// `mvstack::reference_mode_ctx`'s own context off the same two neighbour
1937/// bands decode.rs builds its `NeighbourRef` pair from.
1938fn write_comp_mode(
1939 enc: &mut SymbolEncoder,
1940 cdfs: &mut Cdfs,
1941 neighbours: &Neighbours,
1942 (mi_r, mi_c): (usize, usize),
1943 (has_above, has_left): (bool, bool),
1944 compound: bool,
1945) {
1946 if !REFERENCE_SELECT.with(std::cell::Cell::get) {
1947 return;
1948 }
1949 let above = has_above.then(|| neighbours.above_nbr(mi_c));
1950 let left = has_left.then(|| neighbours.left_nbr(mi_r));
1951 let ctx = crate::mvstack::reference_mode_ctx(above, left);
1952 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1953 eprintln!(
1954 "EC_WCM mi=({mi_r},{mi_c}) ctx={ctx} val={} a={:?} l={:?}",
1955 usize::from(compound),
1956 above.map(|n| (n.is_inter, n.ref0, n.ref1)),
1957 left.map(|n| (n.is_inter, n.ref0, n.ref1))
1958 );
1959 }
1960 enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]);
1961}
1962
1963/// Clears the armed plan when the tile writer that consumed it returns.
1964struct CdefIdxGuard;
1965
1966impl Drop for CdefIdxGuard {
1967 fn drop(&mut self) {
1968 CDEF_IDX.with(|c| *c.borrow_mut() = None);
1969 DELTA_Q.with(|c| *c.borrow_mut() = None);
1970 LR_PLAN.with(|c| *c.borrow_mut() = None);
1971 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
1972 SCREEN.with(|c| c.set(false));
1973 REFERENCE_SELECT.with(|c| c.set(false));
1974 MOTION_MODE.with(|c| c.set(false));
1975 INTRABC.with(|c| c.set(false));
1976 FILTER_INTRA.with(|c| c.set(false));
1977 INTRABC_GRID.with(|c| *c.borrow_mut() = None);
1978 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
1979 }
1980}
1981
1982/// `read_cdef`'s write side, called right after every block's `skip` symbol:
1983/// writes this superblock's `cdef_idx` literal the first time a non-skip
1984/// block of it is coded. `mi` is the block's own position in 4x4 mode-info
1985/// units.
1986fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) {
1987 if skip {
1988 return;
1989 }
1990 CDEF_IDX.with(|c| {
1991 let mut plan = c.borrow_mut();
1992 let Some(plan) = plan.as_mut() else { return };
1993 let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16);
1994 if plan.last == Some(sb) {
1995 return;
1996 }
1997 plan.last = Some(sb);
1998 enc.literal(
1999 u32::from(plan.grid.get(sb).copied().unwrap_or(0)),
2000 u32::from(plan.bits),
2001 );
2002 });
2003}
2004
2005/// `read_delta_qindex`'s write side (spec 5.11.10), called right after every
2006/// block's [`write_cdef_idx`] -- the spec's own `skip -> cdef -> delta_q`
2007/// order, and decode.rs `maybe_read_delta_q` is the reader this mirrors
2008/// symbol for symbol. A no-op unless this block sits at its superblock's own
2009/// top-left mode-info position, and (the one case the reader skips too) when
2010/// that block IS the whole superblock and is skipped, in which case
2011/// `CurrentQIndex` carries over unchanged on both sides.
2012fn write_delta_q(
2013 enc: &mut SymbolEncoder,
2014 cdfs: &mut Cdfs,
2015 mi: (usize, usize),
2016 is_whole_sb: bool,
2017 skip: bool,
2018) {
2019 DELTA_Q.with(|c| {
2020 let mut plan = c.borrow_mut();
2021 let Some(plan) = plan.as_mut() else { return };
2022 // lane-b128m: the delta_q unit is the SUPERBLOCK, so it is 128 wide
2023 // under `EC_AV1_SB128` -- decode.rs `maybe_read_delta_q` gates on
2024 // `sb_mi_cur`, and a writer gating on a hardcoded 64 codes three
2025 // symbol groups per 128 root the reader never reads.
2026 let sb_mi = if sb128_armed() {
2027 SB_MI as usize * 2
2028 } else {
2029 SB_MI as usize
2030 };
2031 if mi.0 % sb_mi != 0 || mi.1 % sb_mi != 0 {
2032 return;
2033 }
2034 if is_whole_sb && skip {
2035 return;
2036 }
2037 let sb = (mi.0 / SB_MI as usize) * plan.sb_cols + (mi.1 / SB_MI as usize);
2038 let target = i32::from(plan.grid.get(sb).copied().unwrap_or(0));
2039 // `reduced` is the spec's `delta_q_abs`/`delta_q_sign_bit` pair: the
2040 // step count, not the qindex difference.
2041 let reduced = (target - plan.cur) / plan.res;
2042 let abs = reduced.unsigned_abs() as usize;
2043 /// spec `DELTA_Q_SMALL`: the largest `delta_q_abs` symbol that is not
2044 /// an escape into the literal pair below.
2045 const DELTA_Q_SMALL: usize = 3;
2046 enc.symbol(abs.min(DELTA_Q_SMALL), &mut cdfs.delta_q);
2047 if abs >= DELTA_Q_SMALL {
2048 // libaom `write_delta_qindex`: `rem_bits = get_msb(abs - 1)`,
2049 // written one less in three bits, and the value offset by the
2050 // threshold `(1 << rem_bits) + 1` the reader adds back.
2051 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
2052 let thr = (1u32 << rem_bits) + 1;
2053 enc.literal(rem_bits - 1, 3);
2054 enc.literal(abs as u32 - thr, rem_bits);
2055 }
2056 if abs != 0 {
2057 enc.literal(u32::from(reduced < 0), 1);
2058 }
2059 plan.cur = (plan.cur + reduced * plan.res).clamp(1, 255);
2060 });
2061}
2062
2063/// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
2064/// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
2065/// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
2066/// same variable, so the two traces line up symbol for symbol. Checked once
2067/// per process, so unset (the default) costs one atomic load per call and no
2068/// allocation. Only the real tile writer below calls this -- the mode/rate
2069/// search's own trial encoders never do -- so the trace does not need the
2070/// throwaway-encoder gating a whole-encoder trace would.
2071fn ec_rng_trace(msg: impl FnOnce() -> String) {
2072 use std::sync::atomic::{AtomicU8, Ordering};
2073 static ON: AtomicU8 = AtomicU8::new(2); // 2 = unknown, 1 = on, 0 = off
2074 let on = match ON.load(Ordering::Relaxed) {
2075 2 => {
2076 let on = u8::from(std::env::var_os("EC_RNG").is_some());
2077 ON.store(on, Ordering::Relaxed);
2078 on
2079 }
2080 v => v,
2081 };
2082 if on == 1 {
2083 eprintln!("{}", msg());
2084 }
2085}
2086
2087/// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
2088const PARTITION_NONE: usize = 0;
2089/// `PARTITION_HORZ` (spec 6.10.4): the block cut into a top and a bottom half.
2090const PARTITION_HORZ: usize = 1;
2091/// `PARTITION_VERT` (spec 6.10.4): the block cut into a left and a right half.
2092const PARTITION_VERT: usize = 2;
2093/// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants.
2094const PARTITION_SPLIT: usize = 3;
2095
2096/// The partition types whose probability mass the split-or-horizontal flag of
2097/// a superblock hanging off the bottom of the frame gathers (spec 9.3,
2098/// `partition_gather_vert_alike`): the flag says split, so everything vertical
2099/// or split lands on it.
2100const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2101
2102/// The same for a superblock hanging off the right-hand edge
2103/// (`partition_gather_horz_alike`).
2104const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2105
2106/// Mode-info units across a 32x32 block.
2107pub(crate) const BLOCK_MI: u32 = SB_MI / 2;
2108
2109/// Mode-info units across a 16x16 block, the smallest this crate's key-frame
2110/// writer codes.
2111pub(crate) const SUB_MI: u32 = BLOCK_MI / 2;
2112
2113/// spec `decode_partition`'s `hasRows`/`hasCols` (5.11.4), recomputed at
2114/// whichever block size is asking: a block of `side_mi` mode-info units at mi
2115/// position `pos` may be coded unsplit (its own `PARTITION_NONE`) only when
2116/// this is true in both directions -- the frame's *true* size can put the
2117/// boundary inside a superblock, a 32x32 quadrant or (since this writer's
2118/// smallest block is 16x16) even a leaf, and each level must ask again with
2119/// its own half, not just once at the superblock.
2120pub(crate) fn has_half(pos: u32, side_mi: u32, bound: u32) -> bool {
2121 pos + side_mi / 2 < bound
2122}
2123
2124/// The number of 32x32 block columns/rows a frame whose *true* (unpadded)
2125/// size gives `mi_cols`/`mi_rows` is coded over: every block whose mi origin
2126/// (`col * BLOCK_MI`) is inside the true bound is coded, so this is a
2127/// ceiling, not the exact division a block-aligned frame would give. Shared
2128/// by the tile writer's own iteration and by [`crate::encode`]'s block/
2129/// superblock generation, which must agree with it exactly.
2130pub(crate) fn block_grid(mi_cols: u32, mi_rows: u32) -> (u32, u32) {
2131 (mi_cols.div_ceil(BLOCK_MI), mi_rows.div_ceil(BLOCK_MI))
2132}
2133/// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode.
2134const DC_PRED: usize = 0;
2135
2136/// `V_PRED` (spec 6.10.2), the first of the eight directional intra modes and
2137/// so the first mode that carries an angle delta.
2138const V_PRED: usize = 1;
2139
2140/// `H_PRED`, which predicts every row from the column to the block's left.
2141#[cfg(test)]
2142const H_PRED: usize = 2;
2143
2144/// The last directional mode, `D67_PRED`.
2145const D67_PRED: usize = 8;
2146
2147/// The number of intra modes a key frame's luma block chooses from,
2148/// `INTRA_MODES` (spec 3).
2149const INTRA_MODES: usize = 13;
2150
2151/// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts
2152/// its neighbours in when they pick the CDF for the next block's mode.
2153pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0];
2154
2155/// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
2156/// +3, so `MAX_ANGLE_DELTA` is the middle of it.
2157pub(crate) const ANGLE_DELTA_ZERO: usize = 3;
2158/// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
2159pub(crate) const SB_MI: u32 = 16;
2160
2161/// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
2162const NUM_BASE_LEVELS: i32 = 2;
2163/// Where DCT_DCT sits in the spec's `Tx_Type_Intra_Inv_Set2`, the set a 16x16
2164/// intra luma transform picks its type from.
2165const TX_TYPE_DCT_DCT_SET2: usize = 1;
2166/// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
2167/// Golomb tail takes over.
2168const COEFF_BASE_RANGE: i32 = 12;
2169/// `BR_CDF_SIZE - 1` (spec 3): the largest increment one base-range symbol
2170/// carries.
2171const BR_STEP: i32 = 3;
2172/// The largest level the base and base-range syntax carry between them.
2173/// Anything above it is written as a Golomb tail on top of this.
2174const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2175/// The largest level this writer codes. The Golomb tail is a length in unary
2176/// followed by that many bits, and the spec's decoder reads at most twenty of
2177/// each, so a level a decoder cannot read back is refused rather than written.
2178const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
2179
2180/// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s
2181/// leading index) a frame's `base_q_idx` picks its default CDFs from.
2182/// [`crate::cdf`] carries all four, one constant set per context.
2183pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
2184 match base_q_idx {
2185 0..=20 => 0,
2186 21..=60 => 1,
2187 61..=120 => 2,
2188 _ => 3,
2189 }
2190}
2191
2192/// Both writers here code whole superblocks only: a partial one forces the
2193/// partition syntax down the block tree, which they do not code yet.
2194/// The probability the CDF gives one symbol on its own.
2195fn element_prob(cdf: &[u16], element: usize) -> u16 {
2196 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2197}
2198
2199/// The two-symbol CDF a partial superblock's partition flag is coded with: the
2200/// mass of the listed partition types becomes the probability of a split, and
2201/// the rest is the one partition the frame edge still allows.
2202fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
2203 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
2204 [32768 - split, 32768, 0]
2205}
2206
2207fn check_superblocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
2208 if mi_cols == 0
2209 || mi_rows == 0
2210 || !mi_cols.is_multiple_of(SB_MI)
2211 || !mi_rows.is_multiple_of(SB_MI)
2212 {
2213 return Err(Error::unsupported(
2214 "AV1 tile",
2215 "a key frame is written only for frames that are a whole number \
2216 of 64x64 superblocks",
2217 ));
2218 }
2219 Ok(())
2220}
2221
2222/// Writes the payload of a one-tile key frame in which every superblock is a
2223/// skipped 64x64 DC-predicted block.
2224///
2225/// `mi_cols` and `mi_rows` are the frame's dimensions in 4x4 mode-info units,
2226/// as the frame header carries them.
2227///
2228/// # Errors
2229/// Returns an error when the frame is not a whole number of 64x64 superblocks:
2230/// a partial superblock forces the partition syntax down the block tree, which
2231/// this writer does not code yet.
2232pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {
2233 check_superblocks(mi_cols, mi_rows)?;
2234 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2235
2236 let mut enc = SymbolEncoder::new();
2237 for r in 0..sb_rows {
2238 for c in 0..sb_cols {
2239 // decode_partition (spec 5.11.4). Every neighbour is a 64x64 block,
2240 // whose stored partition context has a zero bit at this block
2241 // size, so the context is 0 wherever the block sits.
2242 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
2243
2244 // intra_frame_mode_info (spec 5.11.16). Segmentation, delta q,
2245 // delta lf, palette, filter intra and intrabc are all off in the
2246 // frame header, and a skipped block codes no CDEF index, so the
2247 // block is three symbols: the skip flag and the two modes.
2248 let skip_ctx = usize::from(r > 0) + usize::from(c > 0);
2249 enc.symbol_fixed(1, &cdf::SKIP[skip_ctx]);
2250 // Both neighbours are DC-predicted, and an unavailable neighbour
2251 // counts as DC too, so both mode contexts are 0.
2252 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2253 // Chroma from luma is only offered up to 32x32, so the CFL-free
2254 // table is the one a 64x64 block reads.
2255 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
2256
2257 // read_block_tx_size codes nothing while the frame's tx_mode is
2258 // TX_MODE_LARGEST, and a skipped block has no residual, so the
2259 // block ends here.
2260 }
2261 }
2262 Ok(enc.finish())
2263}
2264
2265/// Writes the payload of a one-tile key frame in which every superblock is a
2266/// 64x64 DC-predicted block carrying one luma DC coefficient of `dc_level` and
2267/// no chroma residual.
2268///
2269/// `dc_level` is a quantised level, not a sample value: the decoder multiplies
2270/// it by the frame's DC quantiser and inverse-transforms it over the whole
2271/// block, so the picture it makes is a flat grey some distance either side of
2272/// the mid-grey a zero level gives. `base_q_idx` is the frame header's, and
2273/// picks the coefficient CDFs.
2274///
2275/// # Errors
2276/// As [`dc_key_frame_tile_levels`], which this is the one-level case of.
2277pub fn dc_key_frame_tile(
2278 mi_cols: u32,
2279 mi_rows: u32,
2280 base_q_idx: u8,
2281 dc_level: i32,
2282) -> Result<Vec<u8>> {
2283 check_superblocks(mi_cols, mi_rows)?;
2284 let blocks = ((mi_cols / SB_MI) * (mi_rows / SB_MI)) as usize;
2285 dc_key_frame_tile_levels(mi_cols, mi_rows, base_q_idx, &vec![dc_level; blocks])
2286}
2287
2288/// Writes the payload of a one-tile key frame carrying one luma DC coefficient
2289/// per superblock, `levels` giving them in the raster order the superblocks are
2290/// coded in.
2291///
2292/// Each superblock decodes to a flat block of its own grey, so a frame written
2293/// here is a grid of greys the caller chooses — which is what makes the sign
2294/// context observable: a block's sign context is read off its coded neighbours,
2295/// and a frame whose levels differ in sign exercises the three-way split that a
2296/// single-sign frame cannot reach.
2297///
2298/// # Errors
2299/// Returns an error when the frame is not a whole number of 64x64 superblocks,
2300/// when `levels` does not carry exactly one level per superblock, when a level
2301/// is outside the range the base and base-range syntax carry (`-14..=14`
2302/// without zero).
2303pub fn dc_key_frame_tile_levels(
2304 mi_cols: u32,
2305 mi_rows: u32,
2306 base_q_idx: u8,
2307 levels: &[i32],
2308) -> Result<Vec<u8>> {
2309 check_superblocks(mi_cols, mi_rows)?;
2310 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2311 check_levels(levels, (sb_cols * sb_rows) as usize)?;
2312 let q_ctx = q_ctx_of(base_q_idx);
2313 let txb_skip_luma_64 = crate::cdf_state::pick(
2314 q_ctx,
2315 cdf::TXB_SKIP_LUMA_64_Q0,
2316 cdf::TXB_SKIP_LUMA_64_Q1,
2317 cdf::TXB_SKIP_LUMA_64,
2318 cdf::TXB_SKIP_LUMA_64_Q3,
2319 );
2320 let base_eob_luma_64_dc = crate::cdf_state::pick(
2321 q_ctx,
2322 cdf::COEFF_BASE_EOB_LUMA_64_Q0[0],
2323 cdf::COEFF_BASE_EOB_LUMA_64_Q1[0],
2324 cdf::COEFF_BASE_EOB_LUMA_64[0],
2325 cdf::COEFF_BASE_EOB_LUMA_64_Q3[0],
2326 );
2327 let txb_skip_chroma_32_none = crate::cdf_state::pick(
2328 q_ctx,
2329 cdf::TXB_SKIP_CHROMA_32_Q0[0],
2330 cdf::TXB_SKIP_CHROMA_32_Q1[0],
2331 cdf::TXB_SKIP_CHROMA_32[0],
2332 cdf::TXB_SKIP_CHROMA_32_Q3[0],
2333 );
2334
2335 // The sign of the DC each coded block left behind, for the two neighbours
2336 // the sign context is read from: one row of them above, and the block to
2337 // the left, which is dropped at the start of every superblock row the way a
2338 // decoder clears its left context there.
2339 let mut above: Vec<Option<bool>> = vec![None; sb_cols as usize];
2340 let mut enc = SymbolEncoder::new();
2341 for r in 0..sb_rows {
2342 let mut left: Option<bool> = None;
2343 for c in 0..sb_cols {
2344 let dc_level = levels[(r * sb_cols + c) as usize];
2345 let negative = dc_level < 0;
2346
2347 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
2348
2349 // Nothing is skipped now, so every neighbour's skip flag is 0 and
2350 // the skip context stays 0 across the frame.
2351 enc.symbol_fixed(0, &cdf::SKIP[0]);
2352 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2353 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
2354
2355 write_dc_coeffs(
2356 &mut enc,
2357 dc_level,
2358 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)),
2359 q_ctx,
2360 &txb_skip_luma_64,
2361 &base_eob_luma_64_dc,
2362 );
2363
2364 // Both chroma transform blocks are all-zero. Their planes carry no
2365 // coded coefficient anywhere in the frame, so the neighbour halves
2366 // of their context stay 0 and only the offset for a transform block
2367 // that covers its whole plane block is left: context 7.
2368 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
2369 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
2370
2371 above[c as usize] = Some(negative);
2372 left = Some(negative);
2373 }
2374 }
2375 Ok(enc.finish())
2376}
2377
2378/// Writes the payload of a one-tile key frame in which every superblock is
2379/// split into four 32x32 DC-predicted blocks, each carrying one luma DC
2380/// coefficient and no chroma residual.
2381///
2382/// `levels` gives one level per 32x32 block in raster order across the frame,
2383/// so the grid is twice as wide and twice as tall as the superblock grid. The
2384/// blocks are coded in the z-order a superblock's split walks, but every
2385/// block's neighbours above and to its left are coded before it either way, so
2386/// the picture reads in raster order.
2387///
2388/// # Errors
2389/// As [`dc_key_frame_tile_levels`], with `levels` sized for the 32x32 grid.
2390pub fn split_dc_key_frame_tile(
2391 mi_cols: u32,
2392 mi_rows: u32,
2393 base_q_idx: u8,
2394 levels: &[i32],
2395) -> Result<Vec<u8>> {
2396 check_superblocks(mi_cols, mi_rows)?;
2397 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2398 let (cols, rows) = (sb_cols * 2, sb_rows * 2);
2399 check_levels(levels, (cols * rows) as usize)?;
2400 let q_ctx = q_ctx_of(base_q_idx);
2401 let txb_skip_luma_32 = crate::cdf_state::pick(
2402 q_ctx,
2403 cdf::TXB_SKIP_LUMA_32_Q0,
2404 cdf::TXB_SKIP_LUMA_32_Q1,
2405 cdf::TXB_SKIP_LUMA_32,
2406 cdf::TXB_SKIP_LUMA_32_Q3,
2407 );
2408 let base_eob_luma_32 = crate::cdf_state::pick(
2409 q_ctx,
2410 cdf::COEFF_BASE_EOB_LUMA_32_Q0[0],
2411 cdf::COEFF_BASE_EOB_LUMA_32_Q1[0],
2412 cdf::COEFF_BASE_EOB_LUMA_32[0],
2413 cdf::COEFF_BASE_EOB_LUMA_32_Q3[0],
2414 );
2415 let txb_skip_chroma_16_0 = crate::cdf_state::pick(
2416 q_ctx,
2417 cdf::TXB_SKIP_CHROMA_16_Q0[0],
2418 cdf::TXB_SKIP_CHROMA_16_Q1[0],
2419 cdf::TXB_SKIP_CHROMA_16[0],
2420 cdf::TXB_SKIP_CHROMA_16_Q3[0],
2421 );
2422
2423 let mut above: Vec<Option<bool>> = vec![None; cols as usize];
2424 let mut left: Vec<Option<bool>> = vec![None; rows as usize];
2425
2426 let mut enc = SymbolEncoder::new();
2427 for sb_r in 0..sb_rows {
2428 // A decoder clears its left context at the start of every superblock
2429 // row, and so does the partition context the 64x64 symbol reads.
2430 left.iter_mut().for_each(|l| *l = None);
2431 for sb_c in 0..sb_cols {
2432 // The partition context of a 64x64 block reads the bit its
2433 // neighbours' block size sets at this depth: a 32x32 neighbour sets
2434 // it, and an uncoded one leaves it clear, so the context is just
2435 // which neighbours exist. The 32x32 blocks below read a bit their
2436 // own size leaves clear, so their context is 0 throughout.
2437 // Every superblock here is split, so an existing neighbour always
2438 // sets that bit.
2439 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
2440 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
2441
2442 for quadrant in 0..4 {
2443 let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
2444 let dc_level = levels[(r * cols + c) as usize];
2445 let negative = dc_level < 0;
2446
2447 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
2448 enc.symbol_fixed(0, &cdf::SKIP[0]);
2449 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2450 // Chroma from luma is offered up to 32x32, so the block reads
2451 // the wider table even though it does not take the mode.
2452 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL[DC_PRED]);
2453
2454 write_dc_coeffs(
2455 &mut enc,
2456 dc_level,
2457 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])),
2458 q_ctx,
2459 &txb_skip_luma_32,
2460 &base_eob_luma_32,
2461 );
2462 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
2463 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
2464
2465 above[c as usize] = Some(negative);
2466 left[r as usize] = Some(negative);
2467 }
2468 }
2469 }
2470 Ok(enc.finish())
2471}
2472
2473/// One quantised coefficient of a transform block.
2474///
2475/// `row` and `col` are its position in the transform it belongs to — 32x32 for
2476/// luma, 16x16 for each chroma plane — not in the picture: a coefficient at
2477/// row 0 varies along the picture's width and one at column 0 along its
2478/// height, and the coefficient at the origin is the DC the block's average
2479/// sample value rides on.
2480#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2481pub struct Coeff {
2482 /// The coefficient's row in the transform.
2483 pub row: u8,
2484 /// The coefficient's column in the transform.
2485 pub col: u8,
2486 /// Its quantised level, which the base and base-range syntax carry for
2487 /// magnitudes up to [`MAX_LEVEL`].
2488 pub level: i32,
2489}
2490
2491/// The coefficients of one coded block: a 32x32 luma transform and, at 4:2:0,
2492/// the 16x16 transform each chroma plane covers the same area with.
2493#[derive(Clone, Debug, Default, PartialEq, Eq)]
2494pub struct BlockCoeffs {
2495 /// The luma transform's coefficients.
2496 pub luma: Vec<Coeff>,
2497 /// One transform type per luma transform unit, raster order (lane-txset).
2498 /// Empty is `DCT_DCT` throughout -- what every block coded before the
2499 /// search offered a type, and what an inter block still carries.
2500 pub luma_tx_types: Vec<TxType>,
2501 /// The U plane's.
2502 pub u: Vec<Coeff>,
2503 /// The V plane's.
2504 pub v: Vec<Coeff>,
2505 /// The luma intra mode the block is predicted with, one of the thirteen
2506 /// modes a key frame codes (`DC_PRED` is zero, which is what
2507 /// [`Default`] and a plain coefficient list give).
2508 pub mode: u8,
2509 /// The chroma intra mode both chroma planes are predicted with (spec
2510 /// `uv_mode`, one symbol for the pair). `DC_PRED` is zero, which is what
2511 /// [`Default`] gives; a non-`DC_PRED` mode also changes the transform
2512 /// type the decoder derives for chroma (`Intra_Mode_To_Tx_Type`, spec
2513 /// 9.3), which is never coded as a symbol.
2514 pub uv_mode: u8,
2515 /// Whether the block carries no residual at all (spec `skip`). An intra
2516 /// block may still be skipped; `false` (the [`Default`]) codes whatever
2517 /// `luma`/`u`/`v` carry.
2518 pub skip: bool,
2519 /// The block's inter mode and motion vector, or `None` for an intra
2520 /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key
2521 /// frame writers never read this field.
2522 pub inter: Option<InterInfo>,
2523 /// This (single-reference inter) block's spec `motion_mode`, written by
2524 /// [`write_motion_mode`]: 0 `SIMPLE_TRANSLATION` (the [`Default`], and
2525 /// the only mode this writer coded before lane-av1obmc), 1 `OBMC_CAUSAL`,
2526 /// 2 `WARPED_CAUSAL` (lane-av1obmc2).
2527 pub motion_mode: u8,
2528 /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect),
2529 /// each with its own 8x8 luma transform and 4x4 chroma transforms, in
2530 /// raster order among the leaves that are inside the true frame. `Some`
2531 /// overrides this `BlockCoeffs`'s own `luma`/`u`/`v`/`mode`, which are left
2532 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
2533 /// per-quadrant fields are unused.
2534 pub eight: Option<Vec<BlockCoeffs>>,
2535 /// The luma palette this block is predicted with (spec 5.11.46
2536 /// `palette_mode_info`), or `None` for an ordinary intra block. Only a
2537 /// `DC_PRED` block on a frame whose header set
2538 /// `allow_screen_content_tools` may carry one, and it forces
2539 /// `tx_depth` to zero (the whole block is one transform over the
2540 /// palette's own prediction).
2541 pub palette: Option<PaletteY>,
2542 /// The chroma palette this block's two chroma planes are predicted with
2543 /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a
2544 /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry
2545 /// one; it is independent of [`Self::palette`] (either, both or neither).
2546 pub palette_uv: Option<PaletteUv>,
2547 /// How many times this block's luma transform is halved under
2548 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
2549 /// block). Read only by the writers a `tx_select` frame calls; a
2550 /// `TxMode::Largest` frame codes no symbol and leaves this at zero.
2551 /// `luma` then carries the whole block's levels in BLOCK coordinates,
2552 /// which the writer slices per transform unit.
2553 pub tx_depth: u8,
2554 /// This block's `UV_CFL_PRED` alphas (`alpha_q3` for U and V, spec
2555 /// 5.11.45's `cfl_alpha_signs`/`cfl_alpha_u`/`cfl_alpha_v`), or `None` for
2556 /// any other chroma mode. `Some` iff [`Self::uv_mode`] is
2557 /// [`UV_CFL_PRED`]; at least one of the pair is nonzero, since the joint
2558 /// sign symbol has no (ZERO, ZERO) value.
2559 pub cfl_alphas: Option<(i32, i32)>,
2560 /// This block's `filter_intra_mode` (spec 5.11.14, 0..=4) when it is
2561 /// coded with recursive filter intra, or `None`. `Some` only on a DC_PRED
2562 /// luma block of at most 32x32 with no luma palette, on a sequence whose
2563 /// header set `enable_filter_intra` ([`arm_filter_intra`]); the block's
2564 /// luma transform types are then coded from
2565 /// `fimode_to_intradir[filter_intra_mode]`'s row ([`tx_row`]) while its
2566 /// neighbour mode stays `DC_PRED`.
2567 pub filter_intra: Option<u8>,
2568 /// This block's `angle_delta_y` (spec `read_intra_angle_info`, -3..=3),
2569 /// zero for every non-directional luma mode -- which is what
2570 /// [`Default`] gives, and what every writer coded before lane-av1cfl.
2571 pub angle_delta_y: i8,
2572 /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
2573 /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
2574 /// an ordinary intra block. Only a key frame whose header set
2575 /// `allow_intrabc` ([`arm_intrabc`]) may carry one; the block is then
2576 /// coded `skip` with no residual, no mode, no palette -- exactly what
2577 /// decode.rs `read_intra_mode` reads back and returns early on.
2578 ///
2579 /// lane-av1ibc corner-cut, ceiling named: a residual-carrying intrabc
2580 /// block needs the INTER coefficient tables plus the var-tx tree
2581 /// decode.rs `decode_block`'s `intrabc_vartx` arm reads; the upgrade path
2582 /// is to route the block through [`write_tx_syntax_inter`] instead of
2583 /// returning early here.
2584 pub dv: Option<(i32, i32)>,
2585}
2586
2587/// A block's luma palette: its base colours (ascending, only the first
2588/// `size` entries are real) and the per-pixel colour-index map, `side*side`
2589/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back
2590/// out of the stream.
2591#[derive(Clone, Debug, Default, PartialEq, Eq)]
2592pub struct PaletteY {
2593 /// How many base colours, 2..=8 (spec `PaletteSizeY`).
2594 pub size: u8,
2595 /// The base colours, ascending.
2596 pub colors: [u16; 8],
2597 /// Which colour each pixel takes, row-major over the block's own side.
2598 pub map: Vec<u8>,
2599}
2600
2601/// As [`PaletteY`], for a block's chroma palette -- one colour-index map
2602/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes
2603/// are co-located after 4:2:0 subsampling) plus each plane's own base
2604/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of
2605/// the stream.
2606#[derive(Clone, Debug, Default, PartialEq, Eq)]
2607pub struct PaletteUv {
2608 /// How many base colours, 2..=8 (spec `PaletteSizeUV`).
2609 pub size: u8,
2610 /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv`
2611 /// merges the cached and transmitted lists as two ascending runs, and its
2612 /// delta form only ever steps upwards.
2613 pub u_colors: [u16; 8],
2614 /// V's base colours, in the same cluster order as [`Self::u_colors`] --
2615 /// the shared map indexes both, and V's own coding needs no ordering.
2616 pub v_colors: [u16; 8],
2617 /// Which colour each chroma pixel takes, row-major over the subsampled
2618 /// block's own `(side / 2).max(4)` side.
2619 pub map: Vec<u8>,
2620}
2621
2622/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
2623/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
2624/// [`write_inter_mode`] with the decoder's own contexts.
2625#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2626pub enum InterMode {
2627 /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
2628 NearestMv,
2629 /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names
2630 /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode).
2631 NearMv,
2632 /// `GLOBALMV`: the identity global model's zero vector, two symbols and
2633 /// no MV at all.
2634 GlobalMv,
2635 /// `NEWMV`: codes `mv` as a residual against the stack entry
2636 /// [`InterInfo::ref_mv_idx`] names.
2637 NewMv,
2638 /// `NEAREST_NEARESTMV`: both sides take the compound stack's own nearest
2639 /// pair, no residual, no DRL.
2640 NearestNearestMv,
2641 /// `NEAR_NEARMV`: both sides take compound stack entry
2642 /// [`InterInfo::ref_mv_idx`]` + 1` (decode.rs `assign_compound_mv`'s own
2643 /// `ref_mv_idx + 1`), reached by a DRL walk that starts at index 1.
2644 NearNearMv,
2645 /// `NEAREST_NEWMV`: the first side takes the stack's nearest vector, the
2646 /// second codes a residual against stack entry 0.
2647 NearestNewMv,
2648 /// `NEW_NEARESTMV`: the first side codes a residual against stack entry 0,
2649 /// the second takes the stack's nearest vector.
2650 NewNearestMv,
2651 /// `GLOBAL_GLOBALMV`: both sides take the identity global model's zero
2652 /// vector.
2653 GlobalGlobalMv,
2654 /// `NEW_NEWMV`: both sides code a residual against the compound stack
2655 /// entry [`InterInfo::ref_mv_idx`] names.
2656 NewNewMv,
2657}
2658
2659impl InterMode {
2660 /// The spec's `INTER_COMPOUND_MODES` index (libaom `enums.h` order,
2661 /// `NEAREST_NEARESTMV = 0`..`NEW_NEWMV = 7`) for a compound mode, `None`
2662 /// for a single-reference one.
2663 fn compound_index(self) -> Option<usize> {
2664 match self {
2665 InterMode::NearestNearestMv => Some(0),
2666 InterMode::NearNearMv => Some(1),
2667 InterMode::NearestNewMv => Some(2),
2668 InterMode::NewNearestMv => Some(3),
2669 InterMode::GlobalGlobalMv => Some(6),
2670 InterMode::NewNewMv => Some(7),
2671 _ => None,
2672 }
2673 }
2674}
2675
2676/// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
2677/// `(row, col)` units. For [`InterMode::NearestMv`] this writer ignores `mv`
2678/// and codes the stack's own candidate instead — the decoder derives it, so
2679/// nothing here can disagree with it.
2680#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2681pub struct InterInfo {
2682 /// The mode this block is coded with.
2683 pub mode: InterMode,
2684 /// The motion vector a [`InterMode::NewMv`] block's residual targets.
2685 pub mv: (i32, i32),
2686 /// The reference this block predicts from (`LAST_FRAME`..=`ALTREF_FRAME`,
2687 /// spec 6.10.24's alphabet), written by [`write_single_ref`].
2688 pub ref_frame: i8,
2689 /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which
2690 /// `MvStack::entries` slot `NEWMV` codes its residual against, or
2691 /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
2692 /// index (`NEARESTMV`, `GLOBALMV`).
2693 pub ref_mv_idx: u8,
2694 /// The block's second reference (spec `RefFrames[1]`), `None` for a
2695 /// single-reference block. `Some` only on a `reference_select` frame, and
2696 /// only beside one of [`InterMode`]'s compound modes.
2697 pub ref1: Option<i8>,
2698 /// The motion vector into `ref1`, for the compound modes that code one
2699 /// (`NEW_NEWMV`); the other two derive both sides.
2700 pub mv1: (i32, i32),
2701}
2702
2703impl From<Vec<Coeff>> for BlockCoeffs {
2704 /// A block that codes luma only.
2705 fn from(luma: Vec<Coeff>) -> Self {
2706 Self {
2707 luma,
2708 ..Self::default()
2709 }
2710 }
2711}
2712
2713/// Side of the luma transform the coefficient writer codes.
2714const TX32: usize = 32;
2715/// Side of the larger of the two blocks a superblock splits into, in samples.
2716const BLOCK: usize = 32;
2717/// Side of the chroma transform beside it at 4:2:0, and of the luma transform
2718/// of a 16x16 block.
2719const TX16: usize = 16;
2720/// Side of the chroma transform of a 16x16 block at 4:2:0, and of the luma
2721/// transform of an 8x8 leaf under a straddling 16x16 (lane-av1-rect).
2722const TX8: usize = 8;
2723/// Side of the chroma transform of an 8x8 leaf at 4:2:0 (lane-av1-rect).
2724const TX4: usize = 4;
2725/// Side of a superblock, in samples, which is the size a block outside the
2726/// tile reads as.
2727const SB: usize = 64;
2728
2729/// The `above_side`/`left_side` value a cell with no coded neighbour holds
2730/// (tile start, superblock-row start) -- the writer's copy of
2731/// `crate::decode::NO_NEIGHBOUR_SIDE`, and 128 for the same reason: at 64 it
2732/// reads identically at every level up to 64x64 but sets the bit at the
2733/// `BLOCK_128X128` root (64 * 2 <= 128), putting that root's partition symbol
2734/// on CDF row 3 where libaom uses row 0.
2735const NO_NEIGHBOUR_SIDE: usize = 128;
2736/// Side of the smallest block the writer codes, in samples, which is the grid
2737/// the neighbour bookkeeping is kept on.
2738const SUB: usize = 16;
2739/// Side of a 4x4 mode-info unit, in samples: the granularity libaom's above
2740/// and left entropy-context arrays are actually kept on (spec
2741/// `get_txb_ctx`/`av1_set_entropy_contexts`), finer than [`SUB`].
2742const MI: usize = 4;
2743
2744/// What one coded block leaves behind for the blocks that read it as a
2745/// neighbour: whether it coded anything at all, and the sign of its DC.
2746#[derive(Clone, Copy, Default)]
2747struct Neighbour {
2748 /// Whether the plane's transform block carried a coefficient.
2749 coded: bool,
2750 /// Its cumulative coefficient level (spec `cul_level`, clamped to 7) --
2751 /// what the *luma* `txb_skip_ctx` of a transform unit smaller than its
2752 /// own block reads (`get_txb_ctx_general`, decode.rs `luma_skip_ctx`),
2753 /// where "coded or not" is not enough.
2754 level: u8,
2755 /// The sign of its DC, absent when the DC itself is zero.
2756 dc: Option<bool>,
2757}
2758
2759/// Rejects a frame with no mode-info grid at all.
2760///
2761/// `mi_cols`/`mi_rows` are the frame's *true* (unpadded) size in 4x4 units
2762/// (spec `compute_image_size`), not necessarily a multiple of the 32x32 block
2763/// grid: a block whose origin sits at or past this bound is not coded (spec's
2764/// `decode_partition` never visits it), and one that straddles the bound is
2765/// coded whole, its samples coming from the padded planes.
2766fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
2767 if mi_cols == 0 || mi_rows == 0 {
2768 return Err(Error::unsupported(
2769 "AV1 tile",
2770 "a coefficient key frame needs a nonzero mode-info grid",
2771 ));
2772 }
2773 Ok(())
2774}
2775
2776/// The coefficients of one superblock: either one 64x64 block covering it, or
2777/// the four 32x32 blocks it is split into.
2778///
2779/// A superblock at the right-hand or bottom edge of the frame may be half
2780/// outside it, and such a superblock cannot be left whole — the spec has no
2781/// partition that keeps a block outside the frame — so it must be
2782/// [`Split`](Superblock::Split), and carries only the quadrants that are
2783/// inside, in raster order among themselves.
2784#[derive(Clone, Debug, PartialEq, Eq)]
2785pub enum Superblock {
2786 /// One 64x64 block, whose luma transform is 64x64 — of which only the
2787 /// top-left 32x32 carries coefficients — and whose chroma transforms are
2788 /// 32x32 each at 4:2:0.
2789 Whole(BlockCoeffs),
2790 /// The 32x32 quadrants the superblock is split into, each either one
2791 /// block or four 16x16 blocks of its own.
2792 Split(Vec<Quadrant>),
2793}
2794
2795/// One 32x32 quadrant of a split superblock.
2796#[derive(Clone, Debug, PartialEq, Eq)]
2797pub enum Quadrant {
2798 /// One 32x32 block, with a 32x32 luma transform and a 16x16 transform per
2799 /// chroma plane.
2800 Whole(BlockCoeffs),
2801 /// The four 16x16 blocks it is split into, in raster order, each with a
2802 /// 16x16 luma transform and an 8x8 transform per chroma plane.
2803 Split(Vec<BlockCoeffs>),
2804 /// lane-b64: not a quadrant at all -- the whole 64x64 superblock this
2805 /// quadrant is the TOP-LEFT of, coded as one block (`PARTITION_NONE` at
2806 /// `BLOCK_64X64`). Only the top-left quadrant of a superblock carries it
2807 /// and the other three carry [`Covered`](Quadrant::Covered), so the
2808 /// per-32x32-entry shape the inter writer takes is unchanged.
2809 ///
2810 /// The block is single-reference; the writer refuses a compound one. It
2811 /// may be skipped or carry a real residual -- one TX_64X64 luma transform
2812 /// whose coded quarter is a 32x32 level grid, and one TX_32X32 per chroma
2813 /// plane (lane-tx64, `crate::encode::b64_residual`).
2814 Whole64(BlockCoeffs),
2815 /// lane-b128: the whole 128x128 SUPERBLOCK ROOT this quadrant is the
2816 /// top-left of, coded as one block (`PARTITION_NONE` at the root's
2817 /// `partition_w128` symbol). Carried by the top-left 32x32 entry of the
2818 /// root's sixteen; the other fifteen carry [`Covered`](Quadrant::Covered).
2819 ///
2820 /// SKIP only: a 128x128 block's residual is four TX_64X64 luma units
2821 /// interleaved with its chroma per 64x64 mu chunk, which this writer has
2822 /// no path for; [`crate::tile::write_inter_block_128`] refuses one.
2823 Whole128(BlockCoeffs),
2824 /// lane-b128hv: the two 128x64 (`true`) or 64x128 (`false`) inter blocks a
2825 /// `PARTITION_HORZ` / `PARTITION_VERT` 128 superblock root carries, in the
2826 /// order the decoder reads them (top then bottom, left then right).
2827 /// Carried by the top-left 32x32 entry of the root's sixteen, exactly as
2828 /// [`Whole128`](Quadrant::Whole128) is.
2829 ///
2830 /// Skip-only by default; a piece carries a real residual under
2831 /// `EC_AV1_RECTRES` (`crate::encode::rectres`), single reference or
2832 /// compound either way.
2833 Rect128(bool, Vec<BlockCoeffs>),
2834 /// lane-ab128: the THREE inter blocks an AB shape at a 128 superblock
2835 /// root carries -- two 64x64 pieces and one 128x64 / 64x128 half -- in
2836 /// the order the decoder reads them
2837 /// ([`crate::encode::ab128_pieces`]). The `u8` is the partition symbol
2838 /// itself (4 `PARTITION_HORZ_A` .. 7 `PARTITION_VERT_B`). Carried by the
2839 /// top-left 32x32 entry of the root's sixteen, exactly as
2840 /// [`Rect128`](Quadrant::Rect128) is.
2841 ///
2842 /// Skip-only by default, same writer; under `EC_AV1_RECTRES` any of the
2843 /// three pieces may carry a real residual.
2844 Ab128(u8, Vec<BlockCoeffs>),
2845 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
2846 /// top-left already coded; it carries no block of its own.
2847 Covered,
2848}
2849
2850impl Quadrant {
2851 /// The blocks it carries, in the order they are coded.
2852 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {
2853 match self {
2854 Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {
2855 std::slice::from_ref(block)
2856 }
2857 Quadrant::Split(blocks) | Quadrant::Rect128(_, blocks) | Quadrant::Ab128(_, blocks) => {
2858 blocks.as_slice()
2859 }
2860 Quadrant::Covered => &[],
2861 }
2862 }
2863}
2864
2865/// What the blocks above and to the left of the one being coded left behind,
2866/// kept on the 16x16 grid the smallest block sits on.
2867struct Neighbours {
2868 /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/
2869 /// `MiColStart`): every "is there a neighbour above/left of me" answer is
2870 /// TILE-relative, not frame-relative -- the decoder's own
2871 /// `Neighbours::start_tile` sets the same pair, and a writer that asked
2872 /// `mi_row > 0` instead coded a tile's own first row against a neighbour
2873 /// the decoder does not have (class: new map ignores tile edge).
2874 tile_row0_mi: usize,
2875 tile_col0_mi: usize,
2876 /// Per plane, whether the neighbour coded anything and the sign of its DC.
2877 above: Vec<[Neighbour; 3]>,
2878 /// The same, down the left edge.
2879 left: Vec<[Neighbour; 3]>,
2880 /// The neighbour's luma intra mode, which picks the CDF the next block's
2881 /// mode is coded with.
2882 above_mode: Vec<usize>,
2883 /// The same, down the left edge.
2884 left_mode: Vec<usize>,
2885 /// The side of the neighbour block, in samples, which is what the
2886 /// partition symbol's context reads.
2887 above_side: Vec<usize>,
2888 /// The same, down the left edge.
2889 left_side: Vec<usize>,
2890 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
2891 /// granularity [`Self::above`]/[`Self::left`] are, rather than [`SUB`]:
2892 /// two 8x8 leaves of one straddling 16x16 block (lane-av1-rect) share a
2893 /// single [`SUB`]-grid cell, so a coarse array cannot tell the second
2894 /// leaf's partition symbol that the first one was coded at 8x8 (finer
2895 /// than the 16x16 it sits in) -- exactly what its `above`/`left` context
2896 /// needs to read (spec 9.3's `AbovePartitionContext`/`LeftPartitionContext`,
2897 /// which libaom keeps per mi unit for this reason).
2898 above_side_mi: Vec<usize>,
2899 /// The same, down the left edge.
2900 left_side_mi: Vec<usize>,
2901 /// Whether the neighbour carried no residual, for [`sb_coeff_inter_frame_tile`]'s
2902 /// skip context. Unused (and left at its default) by the key frame writers.
2903 /// Kept per 4x4 mode-info unit, like [`Self::above_side_mi`] and for the
2904 /// same reason: under a real PARTITION_SPLIT to 8x8 the four leaves of a
2905 /// 16x16 read (and leave) different contexts inside one [`SUB`] slot.
2906 above_skip: Vec<bool>,
2907 /// The same, down the left edge.
2908 left_skip: Vec<bool>,
2909 /// The side, in pixels, of the transform last written in this 4x4
2910 /// mode-info column -- the deblock `tx_grid` a key frame's
2911 /// `get_tx_size_context` reads (decode.rs `tx_size_context_txfm`/`tx_px_at`),
2912 /// which is what picks the CDF row of a `TxMode::Select` block's
2913 /// `tx_depth` symbol.
2914 above_tx: Vec<u8>,
2915 /// The same, down the left edge (the transform's HEIGHT, `tx_h_px_at`;
2916 /// every transform this writer codes is square, so one value serves).
2917 left_tx: Vec<u8>,
2918 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), per
2919 /// 4x4 mode-info unit: what an INTER frame's `txfm_split` and `tx_depth`
2920 /// symbols read their context from (decode.rs `txfm_partition_ctx_rect`/
2921 /// `tx_size_context_txfm_rect`). Initialised to the widest transform, not
2922 /// zero (decode.rs `TXFM_CTX_INIT`).
2923 above_txfm: Vec<u8>,
2924 /// The same, down the left edge (transform HEIGHT).
2925 left_txfm: Vec<u8>,
2926 /// The palette size each 4x4 mode-info column last left behind, and its
2927 /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and
2928 /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's
2929 /// own `above_palette_size`/`above_palette_colors` bands (decode.rs
2930 /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content
2931 /// frame writes them, `0` when it took no palette, so a stale size never
2932 /// survives into the next block's context.
2933 above_palette_size: Vec<u8>,
2934 /// The same, down the left edge.
2935 left_palette_size: Vec<u8>,
2936 /// What the block being written right now will leave in the two palette
2937 /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY
2938 /// block of either frame type passes through, so an inter block (or an
2939 /// intra block that took no palette) clears the bands rather than letting
2940 /// an earlier palette block's size stand (the neighbour-band hazard
2941 /// lane-t900 r23 hit on the decoder side).
2942 pending_palette: Option<(u8, [u16; 8])>,
2943 /// The colours beside [`Self::above_palette_size`].
2944 above_palette_colors: Vec<[u16; 8]>,
2945 /// The chroma (U-channel) halves of the three bands above --
2946 /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the
2947 /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`.
2948 above_palette_uv_size: Vec<u8>,
2949 left_palette_uv_size: Vec<u8>,
2950 above_palette_uv_colors: Vec<[u16; 8]>,
2951 left_palette_uv_colors: Vec<[u16; 8]>,
2952 /// [`Self::pending_palette`] for the chroma palette.
2953 pending_palette_uv: Option<(u8, [u16; 8])>,
2954 /// The same, down the left edge.
2955 left_palette_colors: Vec<[u16; 8]>,
2956 /// Whether the neighbour was coded inter, for the `is_inter` context.
2957 /// Unused by the key frame writers.
2958 above_inter: Vec<bool>,
2959 /// The same, down the left edge.
2960 left_inter: Vec<bool>,
2961 /// The reference each neighbour named, `-1` for an intra or unavailable
2962 /// one -- what the decoder keeps in its own `Neighbours::above_ref`
2963 /// (decode.rs) and feeds `read_single_ref`'s context functions.
2964 above_ref: Vec<i8>,
2965 /// The same, down the left edge.
2966 left_ref: Vec<i8>,
2967 /// Each neighbour's SECOND reference, `None` for a single-reference or
2968 /// intra one -- decode.rs `Neighbours::above_ref1`, read by every compound
2969 /// context function (`reference_mode_ctx`, `comp_reference_type_ctx`, the
2970 /// `comp_ref`/`comp_bwdref` votes).
2971 above_ref1: Vec<Option<i8>>,
2972 /// The same, down the left edge.
2973 left_ref1: Vec<Option<i8>>,
2974 /// What decode.rs `Neighbours::above_comp_group_idx` holds: a compound
2975 /// neighbour's own `comp_group_idx`, or libaom's single-reference special
2976 /// case (`3` for an ALTREF block, `0` otherwise).
2977 above_comp_group_idx: Vec<u8>,
2978 /// The same, down the left edge.
2979 left_comp_group_idx: Vec<u8>,
2980 /// The same for `compound_idx` (`1` for a single-ref ALTREF block).
2981 above_compound_idx: Vec<u8>,
2982 /// The same, down the left edge.
2983 left_compound_idx: Vec<u8>,
2984 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
2985 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
2986 /// `av1_set_entropy_contexts`): a block whose row or column run spills
2987 /// past this bound leaves its trailing 4x4 units at their default,
2988 /// mid-cell if need be.
2989 mi_cols: usize,
2990 mi_rows: usize,
2991}
2992
2993/// What one plane's neighbours leave for a block, gathered across every cell
2994/// the block spans -- which is what the decoder's own derivation reads
2995/// (spec 5.11.39), and what a single cell only stands in for while every block
2996/// is the same size.
2997#[derive(Clone, Copy, Default)]
2998struct Around {
2999 /// Whether any transform block above this one carried a coefficient.
3000 above_coded: bool,
3001 /// The same, to the left.
3002 left_coded: bool,
3003 /// The running vote of the neighbours' DC signs: negative DCs count down,
3004 /// positive ones up, and a neighbour with no DC does not count.
3005 dc_vote: i32,
3006}
3007
3008impl Neighbours {
3009 /// The state a tile starts from: a block outside it reads as `DC_PRED`,
3010 /// as having coded nothing, and as unsplit. `cols`/`rows` are in [`SUB`]
3011 /// units; `mi_cols`/`mi_rows` are the frame's true (unpadded) size in 4x4
3012 /// mode-info units.
3013 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
3014 Self {
3015 tile_row0_mi: 0,
3016 tile_col0_mi: 0,
3017 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
3018 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
3019 above_mode: vec![DC_PRED; cols],
3020 left_mode: vec![DC_PRED; rows],
3021 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
3022 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
3023 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
3024 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
3025 above_skip: vec![false; cols * (SUB / MI)],
3026 left_skip: vec![false; rows * (SUB / MI)],
3027 above_inter: vec![false; cols * (SUB / MI)],
3028 left_inter: vec![false; rows * (SUB / MI)],
3029 above_ref: vec![-1; cols * (SUB / MI)],
3030 left_ref: vec![-1; rows * (SUB / MI)],
3031 above_ref1: vec![None; cols * (SUB / MI)],
3032 left_ref1: vec![None; rows * (SUB / MI)],
3033 above_comp_group_idx: vec![0; cols * (SUB / MI)],
3034 left_comp_group_idx: vec![0; rows * (SUB / MI)],
3035 above_compound_idx: vec![0; cols * (SUB / MI)],
3036 left_compound_idx: vec![0; rows * (SUB / MI)],
3037 above_tx: vec![0; cols * (SUB / MI)],
3038 left_tx: vec![0; rows * (SUB / MI)],
3039 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
3040 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
3041 above_palette_size: vec![0; cols * (SUB / MI)],
3042 left_palette_size: vec![0; rows * (SUB / MI)],
3043 pending_palette: None,
3044 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
3045 above_palette_uv_size: vec![0; cols * (SUB / MI)],
3046 left_palette_uv_size: vec![0; rows * (SUB / MI)],
3047 above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)],
3048 left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)],
3049 pending_palette_uv: None,
3050 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
3051 mi_cols,
3052 mi_rows,
3053 }
3054 }
3055
3056 /// Clears the left edge, which a tile starts every superblock row with.
3057 /// Points this writer's availability answers at one tile
3058 /// ([`Self::tile_row0_mi`]).
3059 fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) {
3060 self.tile_row0_mi = row0_mi;
3061 self.tile_col0_mi = col0_mi;
3062 }
3063
3064 /// Whether the block at mode-info row `mi_r` has a neighbour above it
3065 /// INSIDE its own tile, and the same to the left.
3066 fn has_above(&self, mi_r: usize) -> bool {
3067 mi_r > self.tile_row0_mi
3068 }
3069
3070 fn has_left(&self, mi_c: usize) -> bool {
3071 mi_c > self.tile_col0_mi
3072 }
3073
3074 fn start_row(&mut self) {
3075 self.left.iter_mut().for_each(|l| *l = Default::default());
3076 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3077 self.left_side
3078 .iter_mut()
3079 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3080 self.left_side_mi
3081 .iter_mut()
3082 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3083 self.left_skip.iter_mut().for_each(|s| *s = false);
3084 self.left_inter.iter_mut().for_each(|i| *i = false);
3085 self.left_ref.iter_mut().for_each(|r| *r = -1);
3086 self.left_ref1.iter_mut().for_each(|r| *r = None);
3087 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
3088 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
3089 self.left_tx.iter_mut().for_each(|t| *t = 0);
3090 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
3091 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
3092 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
3093 self.left_palette_uv_colors
3094 .iter_mut()
3095 .for_each(|c| *c = [0u16; 8]);
3096 }
3097
3098 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
3099 /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the
3100 /// `palette_y_mode` context (how many of the two neighbours took a
3101 /// palette) and the ascending, deduplicated colour cache the neighbours
3102 /// offer. `mi` is the block's own position in 4x4 units; this writer
3103 /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0`
3104 /// availability terms read against.
3105 fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) {
3106 // `av1_get_palette_cache` drops the above neighbour on a 64-px
3107 // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does
3108 // not, which is why the two terms below are asked separately.
3109 let above_ok = r % 16 != 0;
3110 let above_is_palette = r > 0 && self.above_palette_size[c] > 0;
3111 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3112 (
3113 usize::from(self.above_palette_size[c]),
3114 self.above_palette_colors[c],
3115 )
3116 } else {
3117 (0, [0u16; 8])
3118 };
3119 let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 {
3120 (
3121 usize::from(self.left_palette_size[r]),
3122 self.left_palette_colors[r],
3123 )
3124 } else {
3125 (0, [0u16; 8])
3126 };
3127 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
3128 let mut cache = Vec::with_capacity(16);
3129 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3130 if cache.last() != Some(&v) {
3131 cache.push(v);
3132 }
3133 };
3134 let (mut ai, mut li) = (0usize, 0usize);
3135 while ai < above_n && li < left_n {
3136 let (va, vl) = (above_colors[ai], left_colors[li]);
3137 if vl < va {
3138 push_dedup(&mut cache, vl);
3139 li += 1;
3140 } else {
3141 push_dedup(&mut cache, va);
3142 ai += 1;
3143 if vl == va {
3144 li += 1;
3145 }
3146 }
3147 }
3148 while ai < above_n {
3149 push_dedup(&mut cache, above_colors[ai]);
3150 ai += 1;
3151 }
3152 while li < left_n {
3153 push_dedup(&mut cache, left_colors[li]);
3154 li += 1;
3155 }
3156 (ctx, cache)
3157 }
3158
3159 /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel
3160 /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's
3161 /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no
3162 /// neighbour lookup at all (it is this block's own just-decided Y palette
3163 /// use), so only the cache is wanted here.
3164 fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> {
3165 let above_ok = r % 16 != 0;
3166 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
3167 (
3168 usize::from(self.above_palette_uv_size[c]),
3169 self.above_palette_uv_colors[c],
3170 )
3171 } else {
3172 (0, [0u16; 8])
3173 };
3174 let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 {
3175 (
3176 usize::from(self.left_palette_uv_size[r]),
3177 self.left_palette_uv_colors[r],
3178 )
3179 } else {
3180 (0, [0u16; 8])
3181 };
3182 let mut cache = Vec::with_capacity(16);
3183 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3184 if cache.last() != Some(&v) {
3185 cache.push(v);
3186 }
3187 };
3188 let (mut ai, mut li) = (0usize, 0usize);
3189 while ai < above_n && li < left_n {
3190 let (va, vl) = (above_colors[ai], left_colors[li]);
3191 if vl < va {
3192 push_dedup(&mut cache, vl);
3193 li += 1;
3194 } else {
3195 push_dedup(&mut cache, va);
3196 ai += 1;
3197 if vl == va {
3198 li += 1;
3199 }
3200 }
3201 }
3202 while ai < above_n {
3203 push_dedup(&mut cache, above_colors[ai]);
3204 ai += 1;
3205 }
3206 while li < left_n {
3207 push_dedup(&mut cache, left_colors[li]);
3208 li += 1;
3209 }
3210 cache
3211 }
3212
3213 /// [`Self::record_palette_y`] for the chroma bands (decode.rs
3214 /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same
3215 /// way, and the span is in LUMA pixels for both planes' bands alike.
3216 fn record_palette_uv(
3217 &mut self,
3218 (r, c): (usize, usize),
3219 (w, h): (usize, usize),
3220 size: u8,
3221 colors: [u16; 8],
3222 ) {
3223 // lane-b128hv: the above band spans the block's WIDTH and the left
3224 // band its HEIGHT; identical to the one loop this replaces at w == h.
3225 for cell in 0..(w / MI).max(1) {
3226 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
3227 *e = size;
3228 if size > 0 {
3229 self.above_palette_uv_colors[c + cell] = colors;
3230 }
3231 }
3232 }
3233 for cell in 0..(h / MI).max(1) {
3234 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
3235 *e = size;
3236 if size > 0 {
3237 self.left_palette_uv_colors[r + cell] = colors;
3238 }
3239 }
3240 }
3241 }
3242
3243 /// What a just-written block leaves in the palette bands (decode.rs
3244 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
3245 /// spans, `0` for a block that took no palette.
3246 fn record_palette_y(
3247 &mut self,
3248 (r, c): (usize, usize),
3249 (w, h): (usize, usize),
3250 size: u8,
3251 colors: [u16; 8],
3252 ) {
3253 // lane-b128hv: the above band spans the block's WIDTH and the left
3254 // band its HEIGHT; identical to the one loop this replaces at w == h.
3255 for cell in 0..(w / MI).max(1) {
3256 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
3257 *e = size;
3258 if size > 0 {
3259 self.above_palette_colors[c + cell] = colors;
3260 }
3261 }
3262 }
3263 for cell in 0..(h / MI).max(1) {
3264 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
3265 *e = size;
3266 if size > 0 {
3267 self.left_palette_colors[r + cell] = colors;
3268 }
3269 }
3270 }
3271 }
3272
3273 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block
3274 /// of an INTER frame leaves in the two `TXFM_CONTEXT` bands -- its
3275 /// resolved transform size over the span `(w_px, h_px)`, which for a
3276 /// SKIPPED inter block is its own block size instead.
3277 fn record_txfm(
3278 &mut self,
3279 (mi_r, mi_c): (usize, usize),
3280 tx_px: usize,
3281 w_px: usize,
3282 h_px: usize,
3283 ) {
3284 for i in 0..h_px / MI {
3285 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
3286 *cell = tx_px as u8;
3287 }
3288 }
3289 for i in 0..w_px / MI {
3290 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
3291 *cell = tx_px as u8;
3292 }
3293 }
3294 }
3295
3296 /// lane-b128hv: decode.rs `txfm_partition_update_rect` -- the two bands
3297 /// take the transform's own HEIGHT (left) and WIDTH (above), over the
3298 /// txb's own rect span. [`Self::record_txfm`] is this at `tx_w == tx_h`.
3299 fn record_txfm_rect(
3300 &mut self,
3301 (mi_r, mi_c): (usize, usize),
3302 (tx_w, tx_h): (usize, usize),
3303 (txb_w, txb_h): (usize, usize),
3304 ) {
3305 for i in 0..txb_h / MI {
3306 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
3307 *cell = tx_h as u8;
3308 }
3309 }
3310 for i in 0..txb_w / MI {
3311 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
3312 *cell = tx_w as u8;
3313 }
3314 }
3315 }
3316
3317 /// `get_tx_size_context` as libaom writes it for a block inside an INTER
3318 /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT`
3319 /// bands, except that an *inter* neighbour contributes its own BLOCK size.
3320 ///
3321 /// lane-av1tx2 r1: a neighbour OUTSIDE the tile contributes nothing at all
3322 /// -- the decoder's `tx_size_context_txfm` drops the whole term when
3323 /// `has_above`/`has_left` is false, where this counted the band's
3324 /// [`TXFM_CTX_INIT`] (64, the widest transform) as a real neighbour. Every
3325 /// intra block on a tile's top row or left column then took its `tx_depth`
3326 /// off a CDF row one higher than the decoder's, which is the first
3327 /// divergence of the inter `TxMode::Select` stream.
3328 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
3329 let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c));
3330 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
3331 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
3332 if has_above && self.above_inter[mi_c] {
3333 above = self.above_side_mi[mi_c] >= own_side;
3334 }
3335 if has_left && self.left_inter[mi_r] {
3336 left = self.left_side_mi[mi_r] >= own_side;
3337 }
3338 usize::from(has_above && above) + usize::from(has_left && left)
3339 }
3340
3341 /// `get_tx_size_context` (decode.rs [`crate::decode::tx_size_context_txfm`]):
3342 /// whether the transform above is at least as wide as this block's own
3343 /// largest transform, plus whether the one to the left is at least as
3344 /// tall. A neighbour outside the tile contributes nothing.
3345 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
3346 usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
3347 + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
3348 }
3349
3350 /// Publishes one block's resolved transform side over every 4x4 unit it
3351 /// covers, the way the decoder's `fill_lf_grid` does at the end of every
3352 /// block.
3353 fn record_tx(&mut self, (mi_r, mi_c): (usize, usize), side: usize, tx_px: usize) {
3354 for cell in 0..side / MI {
3355 if mi_r + cell < self.left_tx.len() {
3356 self.left_tx[mi_r + cell] = tx_px as u8;
3357 }
3358 if mi_c + cell < self.above_tx.len() {
3359 self.above_tx[mi_c + cell] = tx_px as u8;
3360 }
3361 }
3362 }
3363
3364 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
3365 /// (decode.rs `Neighbours::luma_skip_ctx`): the above and left magnitude
3366 /// tiers, each ORed over the unit's own span and clamped to 4.
3367 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
3368 let mut top = 0u8;
3369 let mut left = 0u8;
3370 for cell in 0..side_mi {
3371 top |= self.above[mi_c + cell][0].level;
3372 left |= self.left[mi_r + cell][0].level;
3373 }
3374 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3375 }
3376
3377 /// Publishes ONE luma transform unit's coefficient context, the way the
3378 /// decoder's `record_mi_luma` does between the units of a split block.
3379 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
3380 let state = neighbour_state(grid);
3381 for cell in 0..tx_px / MI {
3382 if mi_r + cell < self.mi_rows {
3383 self.left[mi_r + cell][0] = state;
3384 }
3385 if mi_c + cell < self.mi_cols {
3386 self.above[mi_c + cell][0] = state;
3387 }
3388 }
3389 }
3390
3391 /// lane-b128r: publishes ONE chroma transform unit's coefficient context,
3392 /// the decoder's own `record_mi_chroma` -- a 128x128 block's chroma is one
3393 /// TX_32X32 unit per plane per 64x64 mu chunk, and the next chunk reads
3394 /// the previous one's state (its `txb_skip_ctx` base 1 from the left
3395 /// neighbour). `span_px` is the unit's LUMA span, which is what the
3396 /// luma-mi-indexed bands are addressed in.
3397 fn record_mi_chroma(
3398 &mut self,
3399 (mi_r, mi_c): (usize, usize),
3400 span_px: usize,
3401 plane: usize,
3402 grid: &[i32],
3403 ) {
3404 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3405 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
3406 let state = neighbour_state(grid);
3407 for cell in 0..(span_px / MI).min(bound_h.saturating_sub(mi_r)) {
3408 self.left[mi_r + cell][plane] = state;
3409 }
3410 for cell in 0..(span_px / MI).min(bound_w.saturating_sub(mi_c)) {
3411 self.above[mi_c + cell][plane] = state;
3412 }
3413 }
3414
3415 /// Writes one coded block into every 16x16 column and row it covers, and,
3416 /// on the finer 4x4 grid libaom's entropy context arrays are actually
3417 /// kept on, into every unit up to the true frame edge -- the units past
3418 /// it are left at their default (uncoded), even mid-16x16-cell (spec
3419 /// `av1_set_entropy_contexts`, which clamps to `blocks_wide`/`blocks_high`
3420 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own
3421 /// side).
3422 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
3423 self.record_planes(at, side, mode, grids, true);
3424 }
3425
3426 /// [`Self::record`] with a switch for plane 0: a block whose luma was
3427 /// written as several transform units published each unit's own context
3428 /// as it went ([`Self::record_mi_luma`]), so the whole-block write here
3429 /// would clobber what the next block reads (decode.rs
3430 /// `record_split_luma`).
3431 fn record_planes(
3432 &mut self,
3433 at: (usize, usize),
3434 side: usize,
3435 mode: usize,
3436 grids: &[Vec<i32>; 3],
3437 luma: bool,
3438 ) {
3439 self.record_planes_rect(at, (side, side), mode, grids, luma);
3440 }
3441
3442 /// lane-b128hv: [`Self::record_planes`] with independent above (width) /
3443 /// left (height) extents, decode.rs `record_rect_mi`'s own split -- the
3444 /// 128 root's HORZ/VERT halves are the writer's first rect blocks.
3445 fn record_planes_rect(
3446 &mut self,
3447 at: (usize, usize),
3448 (w, h): (usize, usize),
3449 mode: usize,
3450 grids: &[Vec<i32>; 3],
3451 luma: bool,
3452 ) {
3453 let (r, c) = at;
3454 for cell in 0..w / SUB {
3455 self.above_mode[c + cell] = mode;
3456 self.above_side[c + cell] = w;
3457 }
3458 for cell in 0..h / SUB {
3459 self.left_mode[r + cell] = mode;
3460 self.left_side[r + cell] = h;
3461 }
3462 self.record_mi_planes_rect((r * (SUB / MI), c * (SUB / MI)), (w, h), grids, luma);
3463 }
3464
3465 /// The coefficient-context half of [`Self::record`], taking the block's
3466 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
3467 /// (r, c): an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at a
3468 /// mi offset [`Self::record`]'s SUB-unit `at` cannot name, but the
3469 /// `above`/`left` arrays it writes into are already sized to the full mi
3470 /// grid, so no resizing is needed to write into them at this
3471 /// finer-than-SUB granularity.
3472 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
3473 self.record_mi_planes(at_mi, side, grids, true);
3474 }
3475
3476 /// [`Self::record_mi`] with [`Self::record_planes`]'s plane-0 switch.
3477 fn record_mi_planes(
3478 &mut self,
3479 at_mi: (usize, usize),
3480 side: usize,
3481 grids: &[Vec<i32>; 3],
3482 luma: bool,
3483 ) {
3484 self.record_mi_planes_rect(at_mi, (side, side), grids, luma);
3485 }
3486
3487 /// [`Self::record_mi_planes`] with independent above (width) / left
3488 /// (height) extents (lane-b128hv, decode.rs `record_mi_rect`).
3489 fn record_mi_planes_rect(
3490 &mut self,
3491 at_mi: (usize, usize),
3492 (w, h): (usize, usize),
3493 grids: &[Vec<i32>; 3],
3494 luma: bool,
3495 ) {
3496 let (mi_r, mi_c) = at_mi;
3497 if screen_armed() {
3498 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
3499 self.record_palette_y(at_mi, (w, h), size, colors);
3500 let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8]));
3501 self.record_palette_uv(at_mi, (w, h), uv_size, uv_colors);
3502 }
3503 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
3504 let (w_mi, h_mi) = (w / MI, h / MI);
3505 for cell in 0..h_mi {
3506 self.left_side_mi[mi_r + cell] = h;
3507 }
3508 for cell in 0..w_mi {
3509 self.above_side_mi[mi_c + cell] = w;
3510 }
3511 // libaom rounds the luma edge up to the plane's own 4x4 unit before
3512 // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high,
3513 // subsampling_y)` in av1_write_intra_coeffs_mb, encodetxb.c:456-459):
3514 // a chroma 4x4 unit straddling the true luma edge is still whole in
3515 // chroma's own halved grid, so it stays valid one luma-mi row/col
3516 // past where luma's own edge falls when that edge is odd.
3517 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3518 let bound_h = [
3519 self.mi_rows,
3520 round_up_even(self.mi_rows),
3521 round_up_even(self.mi_rows),
3522 ];
3523 let bound_w = [
3524 self.mi_cols,
3525 round_up_even(self.mi_cols),
3526 round_up_even(self.mi_cols),
3527 ];
3528 for cell in 0..h_mi {
3529 let keep_left = self.left[mi_r + cell][0];
3530 self.left[mi_r + cell] = std::array::from_fn(|plane| {
3531 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
3532 states[plane]
3533 } else {
3534 Default::default()
3535 }
3536 });
3537 if !luma {
3538 self.left[mi_r + cell][0] = keep_left;
3539 }
3540 }
3541 for cell in 0..w_mi {
3542 let keep_above = self.above[mi_c + cell][0];
3543 self.above[mi_c + cell] = std::array::from_fn(|plane| {
3544 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
3545 states[plane]
3546 } else {
3547 Default::default()
3548 }
3549 });
3550 if !luma {
3551 self.above[mi_c + cell][0] = keep_above;
3552 }
3553 }
3554 }
3555
3556 /// Writes one inter-frame block's skip flag and inter/intra state into
3557 /// every 16x16 column and row it covers, the same span [`Self::record`]
3558 /// fills for the coefficient and mode state.
3559 fn record_inter(
3560 &mut self,
3561 at: (usize, usize),
3562 side: usize,
3563 skip: bool,
3564 is_inter: bool,
3565 ref_frame: i8,
3566 ) {
3567 let (r, c) = at;
3568 self.record_inter_mi(
3569 (r * (SUB / MI), c * (SUB / MI)),
3570 side,
3571 skip,
3572 is_inter,
3573 ref_frame,
3574 );
3575 }
3576
3577 /// lane-b128hv: [`Self::record_inter_mi`] with independent above (width)
3578 /// / left (height) spans, decode.rs `record_inter_rect_mi`'s own split.
3579 fn record_inter_rect_mi(
3580 &mut self,
3581 (mi_r, mi_c): (usize, usize),
3582 (w, h): (usize, usize),
3583 skip: bool,
3584 is_inter: bool,
3585 ref_frame: i8,
3586 ) {
3587 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3588 for cell in 0..h / MI {
3589 self.left_skip[mi_r + cell] = skip;
3590 self.left_inter[mi_r + cell] = is_inter;
3591 self.left_ref[mi_r + cell] = ref_frame;
3592 self.left_ref1[mi_r + cell] = None;
3593 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
3594 self.left_compound_idx[mi_r + cell] = u8::from(altref);
3595 }
3596 for cell in 0..w / MI {
3597 self.above_skip[mi_c + cell] = skip;
3598 self.above_inter[mi_c + cell] = is_inter;
3599 self.above_ref[mi_c + cell] = ref_frame;
3600 self.above_ref1[mi_c + cell] = None;
3601 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
3602 self.above_compound_idx[mi_c + cell] = u8::from(altref);
3603 }
3604 }
3605
3606 /// [`Self::record_compound_mi`] over a rect block's own two spans.
3607 fn record_compound_rect_mi(
3608 &mut self,
3609 (mi_r, mi_c): (usize, usize),
3610 (w, h): (usize, usize),
3611 ref1: i8,
3612 comp_group_idx: u8,
3613 compound_idx: u8,
3614 ) {
3615 for cell in 0..h / MI {
3616 self.left_ref1[mi_r + cell] = Some(ref1);
3617 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
3618 self.left_compound_idx[mi_r + cell] = compound_idx;
3619 }
3620 for cell in 0..w / MI {
3621 self.above_ref1[mi_c + cell] = Some(ref1);
3622 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
3623 self.above_compound_idx[mi_c + cell] = compound_idx;
3624 }
3625 }
3626
3627 /// [`Self::record_inter_mi`]'s compound half (decode.rs
3628 /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF
3629 /// single-reference default with a real compound block's own second
3630 /// reference and `comp_group_idx`/`compound_idx` bits, called right after
3631 /// it for every compound-coded block.
3632 fn record_compound_mi(
3633 &mut self,
3634 (mi_r, mi_c): (usize, usize),
3635 side: usize,
3636 ref1: i8,
3637 comp_group_idx: u8,
3638 compound_idx: u8,
3639 ) {
3640 for cell in 0..side / MI {
3641 self.above_ref1[mi_c + cell] = Some(ref1);
3642 self.left_ref1[mi_r + cell] = Some(ref1);
3643 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
3644 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
3645 self.above_compound_idx[mi_c + cell] = compound_idx;
3646 self.left_compound_idx[mi_r + cell] = compound_idx;
3647 }
3648 }
3649
3650 /// [`Self::record_inter`] taking the block's position directly in 4x4
3651 /// mode-info units, for a block finer than one [`SUB`] slot.
3652 fn record_inter_mi(
3653 &mut self,
3654 (mi_r, mi_c): (usize, usize),
3655 side: usize,
3656 skip: bool,
3657 is_inter: bool,
3658 ref_frame: i8,
3659 ) {
3660 for cell in 0..side / MI {
3661 self.above_skip[mi_c + cell] = skip;
3662 self.left_skip[mi_r + cell] = skip;
3663 self.above_inter[mi_c + cell] = is_inter;
3664 self.left_inter[mi_r + cell] = is_inter;
3665 self.above_ref[mi_c + cell] = ref_frame;
3666 self.left_ref[mi_r + cell] = ref_frame;
3667 // decode.rs `record_inter`'s single-reference default: no second
3668 // reference, and libaom's ALTREF special case in the two compound
3669 // context bands. `record_compound_mi` overwrites both for a real
3670 // compound block.
3671 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3672 self.above_ref1[mi_c + cell] = None;
3673 self.left_ref1[mi_r + cell] = None;
3674 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
3675 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
3676 self.above_compound_idx[mi_c + cell] = u8::from(altref);
3677 self.left_compound_idx[mi_r + cell] = u8::from(altref);
3678 }
3679 }
3680
3681 /// The above neighbour as decode.rs' own `NeighbourRef`, for every
3682 /// compound context function (`reference_mode_ctx`,
3683 /// `comp_reference_type_ctx`, the `comp_ref`/`comp_bwdref` votes).
3684 fn above_nbr(&self, mi_c: usize) -> crate::mvstack::NeighbourRef {
3685 let is_inter = self.above_inter[mi_c];
3686 let ref0 = if is_inter { self.above_ref[mi_c] } else { 0 };
3687 let ref1 = self.above_ref1[mi_c];
3688 crate::mvstack::NeighbourRef {
3689 is_inter,
3690 ref0,
3691 ref1,
3692 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
3693 }
3694 }
3695
3696 /// [`Self::above_nbr`], down the left edge.
3697 fn left_nbr(&self, mi_r: usize) -> crate::mvstack::NeighbourRef {
3698 let is_inter = self.left_inter[mi_r];
3699 let ref0 = if is_inter { self.left_ref[mi_r] } else { 0 };
3700 let ref1 = self.left_ref1[mi_r];
3701 crate::mvstack::NeighbourRef {
3702 is_inter,
3703 ref0,
3704 ref1,
3705 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
3706 }
3707 }
3708
3709 /// The context of a block's partition symbol (spec 9.3): whether the
3710 /// blocks above it and to its left were split finer than it is.
3711 /// The gathered state of the blocks above and to the left of one block,
3712 /// per plane.
3713 fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] {
3714 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
3715 }
3716
3717 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
3718 /// units, for the same reason [`Self::record_mi`] does.
3719 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [Around; 3] {
3720 let side_mi = side / MI;
3721 std::array::from_fn(|plane| {
3722 let mut around = Around::default();
3723 for cell in 0..side_mi {
3724 let (above, left) = (
3725 &self.above[mi_c + cell][plane],
3726 &self.left[mi_r + cell][plane],
3727 );
3728 around.above_coded |= above.coded;
3729 around.left_coded |= left.coded;
3730 around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc);
3731 }
3732 around
3733 })
3734 }
3735
3736 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
3737 // Delegates to the mi-precise reader (same pattern as `around` /
3738 // `around_mi`): `above_side`/`left_side` are only ever advanced in
3739 // whole-[`SUB`] steps by [`Self::record`], so a leaf8's `record_mi`
3740 // (lane-av1-rect) -- which only touches the finer mi arrays -- leaves
3741 // them stale for the *next* sibling's own partition symbol, reading a
3742 // 16x16-slot side that already split into 8x8s underneath it.
3743 let (r, c) = at;
3744 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
3745 }
3746
3747 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
3748 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
3749 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
3750 /// than the enclosing 16x16 slot's stale, shared state.
3751 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
3752 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
3753 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
3754 }
3755}
3756
3757/// Writes the payload of a one-tile key frame built from `superblocks`, each
3758/// either one 64x64 block or the 32x32 blocks it splits into.
3759///
3760/// `superblocks` gives one entry per superblock in raster order across the
3761/// frame. Every block is DC-predicted unless its [`BlockCoeffs::mode`] says
3762/// otherwise, and carries the coefficients its lists give; the coefficients
3763/// may sit anywhere in their transform, so a block is a picture rather than a
3764/// flat grey.
3765///
3766/// # Errors
3767/// Returns an error when the frame is not a whole number of 32x32 blocks, when
3768/// `superblocks` does not carry exactly one entry per superblock or an entry
3769/// does not carry one block per quadrant inside the frame, when a superblock
3770/// that is half outside the frame is left whole, when a block names an intra
3771/// mode a key frame does not code, when a coefficient sits outside its
3772/// transform, repeats a position, carries a zero level or one wider than the
3773/// Golomb tail reaches.
3774pub fn sb_coeff_key_frame_tile(
3775 mi_cols: u32,
3776 mi_rows: u32,
3777 base_q_idx: u8,
3778 superblocks: &[Superblock],
3779) -> Result<Vec<u8>> {
3780 sb_coeff_key_frame_tile_tx(mi_cols, mi_rows, base_q_idx, superblocks, false)
3781}
3782
3783/// [`sb_coeff_key_frame_tile`] for a frame header carrying
3784/// `tx_mode == TxMode::Select` (`tx_select`): every block then codes a
3785/// `tx_depth` symbol and, where that depth is nonzero, its luma residual as
3786/// several transform units ([`write_luma_select`]). With `tx_select` false
3787/// this writes exactly the stream it always did.
3788///
3789/// # Errors
3790/// As [`sb_coeff_key_frame_tile`], plus a 64x64 block whose `tx_depth` is
3791/// nonzero (not written yet).
3792pub fn sb_coeff_key_frame_tile_tx(
3793 mi_cols: u32,
3794 mi_rows: u32,
3795 base_q_idx: u8,
3796 superblocks: &[Superblock],
3797 tx_select: bool,
3798) -> Result<Vec<u8>> {
3799 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3800 sb_coeff_key_frame_tile_cdfs(
3801 mi_cols,
3802 mi_rows,
3803 base_q_idx,
3804 superblocks,
3805 tx_select,
3806 &mut cdfs,
3807 TileRect::whole(mi_cols, mi_rows),
3808 )
3809}
3810
3811/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
3812/// caller's own CDF state, which is what a frame whose
3813/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must
3814/// start where this tile ended (spec 7.20, mirrored by
3815/// `crate::stream::stored_cdfs_for`).
3816///
3817/// # Errors
3818/// As [`sb_coeff_key_frame_tile_tx`].
3819pub(crate) fn sb_coeff_key_frame_tile_cdfs(
3820 mi_cols: u32,
3821 mi_rows: u32,
3822 _base_q_idx: u8,
3823 superblocks: &[Superblock],
3824 tx_select: bool,
3825 cdfs: &mut Cdfs,
3826 // This tile's own span (spec 5.11.1): the writer walks only these
3827 // superblocks, and its neighbour bands start blank, so everything
3828 // outside reads as unavailable exactly as the decoder's own per-tile
3829 // reset makes it.
3830 tile: TileRect,
3831) -> Result<Vec<u8>> {
3832 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3833 let _cdef_idx = CdefIdxGuard;
3834 check_blocks(mi_cols, mi_rows)?;
3835 // The DV predictor's own mi grid, per tile exactly as decode.rs builds it
3836 // per frame (`decode_key_frame_tile_lr`'s `intrabc_mi_grid`): a tile that
3837 // allows no intrabc arms none and every `record_intrabc_mi` below is a
3838 // no-op.
3839 if intrabc_armed() {
3840 // No `set_tile_bounds`: decode.rs builds this grid for the WHOLE
3841 // frame with the default (whole-grid) bounds, so the writer must
3842 // too. `encode_key_frame_inner` only allows intrabc on a
3843 // single-tile frame, where the two grids are the same grid.
3844 let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize);
3845 INTRABC_GRID.with(|g| {
3846 *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize));
3847 });
3848 }
3849 let (cols, rows) = block_grid(mi_cols, mi_rows);
3850 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3851 if superblocks.len() != (sb_cols * sb_rows) as usize {
3852 return Err(Error::unsupported(
3853 "AV1 tile",
3854 "a coefficient key frame needs one entry per superblock",
3855 ));
3856 }
3857 let mut coded: Vec<&BlockCoeffs> = Vec::new();
3858 for superblock in superblocks {
3859 match superblock {
3860 Superblock::Whole(block) => coded.push(block),
3861 Superblock::Split(quadrants) => {
3862 for block in quadrants.iter().flat_map(Quadrant::blocks) {
3863 match &block.eight {
3864 Some(leaves) => coded.extend(leaves.iter()),
3865 None => coded.push(block),
3866 }
3867 }
3868 }
3869 }
3870 }
3871 if let Some(bad) = coded
3872 .into_iter()
3873 .find(|b| usize::from(b.mode) >= INTRA_MODES)
3874 {
3875 return Err(Error::unsupported(
3876 "AV1 tile",
3877 format!(
3878 "intra mode {} is not one of the thirteen a key frame codes",
3879 bad.mode
3880 ),
3881 ));
3882 }
3883
3884 let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8];
3885 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
3886 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
3887 let scans = [
3888 default_scan(TX32),
3889 default_scan(TX16),
3890 default_scan(TX8),
3891 default_scan(TX4),
3892 ];
3893 // The blocks above and to the left, on the 16x16 grid. The left edge is
3894 // reset at every superblock row because a tile starts each row with no
3895 // left neighbour.
3896 let mut neighbours = Neighbours::new(
3897 cols as usize * 2,
3898 rows as usize * 2,
3899 mi_cols as usize,
3900 mi_rows as usize,
3901 );
3902 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
3903
3904 // The tile adapts every non-literal CDF it writes, exactly as the decoder
3905 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
3906 // off.
3907 let mut cdfs = cdfs;
3908 let mut enc = SymbolEncoder::new();
3909 let sb128 = sb128_armed();
3910 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
3911 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
3912 // and partition symbol first; at a 64 one this is plain raster and every
3913 // cell is its own superblock, i.e. byte-identical to the loop before.
3914 for (sb_r, sb_c, row_start, sb_start) in sb_write_order(
3915 tile.sb_row0,
3916 tile.sb_row1.min(sb_rows),
3917 tile.sb_col0,
3918 tile.sb_col1.min(sb_cols),
3919 sb128,
3920 ) {
3921 if row_start {
3922 neighbours.start_row();
3923 }
3924 if sb128 && sb_start {
3925 write_sb128_root(
3926 &mut enc,
3927 &mut cdfs,
3928 &neighbours,
3929 sb_r,
3930 sb_c,
3931 mi_cols,
3932 mi_rows,
3933 PARTITION_SPLIT,
3934 );
3935 }
3936 {
3937 if !sb128 {
3938 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W);
3939 }
3940 let at = (sb_r as usize * 4, sb_c as usize * 4);
3941 let ctx = neighbours.partition_ctx(at, SB);
3942 ec_rng_trace(|| {
3943 format!(
3944 "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={}",
3945 at.0 * 4,
3946 at.1 * 4,
3947 ctx,
3948 enc.tell()
3949 )
3950 });
3951 // A superblock whose bottom or right half is outside the frame
3952 // cannot be left unsplit, so the decoder reads a flag instead of
3953 // the partition symbol — and reads nothing at all when both halves
3954 // are outside, where the split is the only partition left.
3955 let (has_cols, has_rows) = (
3956 sb_c * SB_MI + SB_MI / 2 < mi_cols,
3957 sb_r * SB_MI + SB_MI / 2 < mi_rows,
3958 );
3959 // The quadrants of this superblock that are inside the frame, as
3960 // positions in the 32x32 block grid.
3961 let quadrant_positions: Vec<(usize, usize)> = (0..4)
3962 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
3963 .filter(|&(r, c)| r < rows && c < cols)
3964 .map(|(r, c)| (r as usize, c as usize))
3965 .collect();
3966
3967 match &superblocks[(sb_r * sb_cols + sb_c) as usize] {
3968 Superblock::Whole(block) => {
3969 if !has_cols || !has_rows {
3970 return Err(Error::unsupported(
3971 "AV1 tile",
3972 "a superblock that is half outside the frame cannot be left whole",
3973 ));
3974 }
3975 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
3976 let grids = [
3977 level_grid(&block.luma, TX32)?,
3978 level_grid(&block.u, TX32)?,
3979 level_grid(&block.v, TX32)?,
3980 ];
3981 write_block(
3982 &mut enc,
3983 &mut cdfs,
3984 &mut neighbours,
3985 block,
3986 at,
3987 SB,
3988 &whole_planes,
3989 &grids,
3990 [&scans[0], &scans[0], &scans[0]],
3991 // A 64x64 block is too big to be offered chroma from
3992 // luma, so its chroma mode reads the table without it.
3993 false,
3994 tx_select,
3995 &scans,
3996 )?;
3997 ec_rng_trace(|| {
3998 format!(
3999 "EC_TOK mi_row={} mi_col={} tell={}",
4000 at.0 * 4,
4001 at.1 * 4,
4002 enc.tell()
4003 )
4004 });
4005 }
4006 Superblock::Split(quadrants) => {
4007 match (has_cols, has_rows) {
4008 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
4009 // The gathered CDF an edge superblock reads is built
4010 // for the read and thrown away: the decoder never
4011 // stores it back, so nothing adapts here.
4012 (true, false) => {
4013 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
4014 }
4015 (false, true) => {
4016 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
4017 }
4018 (false, false) => {}
4019 }
4020 if quadrants.len() != quadrant_positions.len() {
4021 return Err(Error::unsupported(
4022 "AV1 tile",
4023 "a split superblock needs one block per quadrant inside the frame",
4024 ));
4025 }
4026 for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) {
4027 let at = (r * 2, c * 2);
4028 let ctx = neighbours.partition_ctx(at, BLOCK);
4029 // Recomputed at this 32x32 block's own half (spec
4030 // `decode_partition`, called again at every size, not
4031 // just once for the superblock): the true frame edge
4032 // can fall inside this quadrant even when the
4033 // superblock it sits in was itself whole or safely
4034 // split above.
4035 let (has_cols32, has_rows32) = (
4036 has_half(c as u32 * BLOCK_MI, BLOCK_MI, mi_cols),
4037 has_half(r as u32 * BLOCK_MI, BLOCK_MI, mi_rows),
4038 );
4039 ec_rng_trace(|| {
4040 format!(
4041 "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={}",
4042 at.0 * 4,
4043 at.1 * 4,
4044 ctx,
4045 enc.tell()
4046 )
4047 });
4048 match quadrant {
4049 // A 64x64 root is an INTER-frame partition; a
4050 // key frame codes one as `Superblock::Whole`.
4051 Quadrant::Whole64(_)
4052 | Quadrant::Whole128(_)
4053 | Quadrant::Rect128(..)
4054 | Quadrant::Ab128(..)
4055 | Quadrant::Covered => {
4056 return Err(Error::unsupported(
4057 "AV1 tile",
4058 "a key frame codes a 64x64 block as `Superblock::Whole`",
4059 ));
4060 }
4061 Quadrant::Whole(block) => {
4062 if !has_cols32 || !has_rows32 {
4063 return Err(Error::unsupported(
4064 "AV1 tile",
4065 "a 32x32 block that is half outside the true frame \
4066 cannot be left whole",
4067 ));
4068 }
4069 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]);
4070 let grids = [
4071 level_grid(&block.luma, TX32)?,
4072 level_grid(&block.u, TX16)?,
4073 level_grid(&block.v, TX16)?,
4074 ];
4075 write_block(
4076 &mut enc,
4077 &mut cdfs,
4078 &mut neighbours,
4079 block,
4080 at,
4081 BLOCK,
4082 &split_planes,
4083 &grids,
4084 [&scans[0], &scans[1], &scans[1]],
4085 true,
4086 tx_select,
4087 &scans,
4088 )?;
4089 ec_rng_trace(|| {
4090 format!(
4091 "EC_TOK mi_row={} mi_col={} tell={}",
4092 at.0 * 4,
4093 at.1 * 4,
4094 enc.tell()
4095 )
4096 });
4097 }
4098 Quadrant::Split(blocks) => {
4099 // The 16x16 sub-blocks this quadrant's split
4100 // carries: only those whose own mi origin is
4101 // inside the true frame (spec `decode_partition`'s
4102 // `r >= MiRows || c >= MiCols` early return),
4103 // which need not be all four when the true
4104 // edge falls inside this quadrant.
4105 let sub_positions: Vec<(usize, usize)> = (0..4)
4106 .map(|i| (r * 2 + i / 2, c * 2 + i % 2))
4107 .filter(|&(sr, sc)| {
4108 (sr as u32) * SUB_MI < mi_rows
4109 && (sc as u32) * SUB_MI < mi_cols
4110 })
4111 .collect();
4112 if blocks.len() != sub_positions.len() {
4113 return Err(Error::unsupported(
4114 "AV1 tile",
4115 "a split 32x32 block needs one 16x16 entry per \
4116 sub-block inside the true frame",
4117 ));
4118 }
4119 // Same three-way spec signaling as the
4120 // superblock level above, recomputed at this
4121 // block's own half: a full alphabet symbol
4122 // only when both halves are inside, a single
4123 // gathered bit when just one is, and nothing
4124 // at all (SPLIT is inferred) when neither is.
4125 match (has_cols32, has_rows32) {
4126 (true, true) => {
4127 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]);
4128 }
4129 (true, false) => {
4130 enc.symbol_fixed(
4131 1,
4132 &gather(&cdfs.partition_w32[ctx], VERT_ALIKE),
4133 );
4134 }
4135 (false, true) => {
4136 enc.symbol_fixed(
4137 1,
4138 &gather(&cdfs.partition_w32[ctx], HORZ_ALIKE),
4139 );
4140 }
4141 (false, false) => {}
4142 }
4143 for (block, (sr, sc)) in blocks.iter().zip(sub_positions) {
4144 // A 16x16 leaf's own hasRows/hasCols,
4145 // recomputed at this leaf's own half
4146 // (same three-way signaling as the 32x32
4147 // and 64x64 levels above).
4148 let (has_cols16, has_rows16) = (
4149 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
4150 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
4151 );
4152 let at = (sr, sc);
4153 let ctx = neighbours.partition_ctx(at, SUB);
4154 ec_rng_trace(|| {
4155 format!(
4156 "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={}",
4157 at.0 * 4,
4158 at.1 * 4,
4159 ctx,
4160 enc.tell()
4161 )
4162 });
4163 if has_cols16 && has_rows16 {
4164 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]);
4165 let grids = [
4166 level_grid(&block.luma, TX16)?,
4167 level_grid(&block.u, TX8)?,
4168 level_grid(&block.v, TX8)?,
4169 ];
4170 write_block(
4171 &mut enc,
4172 &mut cdfs,
4173 &mut neighbours,
4174 block,
4175 at,
4176 SUB,
4177 &sub_planes,
4178 &grids,
4179 [&scans[1], &scans[2], &scans[2]],
4180 true,
4181 tx_select,
4182 &scans,
4183 )?;
4184 ec_rng_trace(|| {
4185 format!(
4186 "EC_TOK mi_row={} mi_col={} tell={}",
4187 at.0 * 4,
4188 at.1 * 4,
4189 enc.tell()
4190 )
4191 });
4192 continue;
4193 }
4194 // The true edge falls inside this 16x16
4195 // leaf itself: the block splits into the
4196 // 8x8s that are inside, each its own
4197 // leaf. Same three-way spec signaling as
4198 // every level above -- a single gathered
4199 // bit when one half is outside, and
4200 // nothing at all when BOTH are, where
4201 // `decode_partition` infers the split
4202 // (lane-av1rect: no rectangular
4203 // transform is needed for this, the
4204 // earlier refusal here misread 5.11.4).
4205 match (has_cols16, has_rows16) {
4206 (true, false) => enc.symbol_fixed(
4207 1,
4208 &gather(&cdfs.partition_w16[ctx], VERT_ALIKE),
4209 ),
4210 (false, true) => enc.symbol_fixed(
4211 1,
4212 &gather(&cdfs.partition_w16[ctx], HORZ_ALIKE),
4213 ),
4214 _ => {}
4215 }
4216 let leaves = block.eight.as_ref().ok_or_else(|| {
4217 Error::unsupported(
4218 "AV1 tile",
4219 "a 16x16 block the true frame edge cuts through \
4220 needs its `eight` leaves populated",
4221 )
4222 })?;
4223 let (mi_row0, mi_col0) =
4224 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
4225 let leaf_positions: Vec<(u32, u32)> = (0..4)
4226 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
4227 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
4228 .collect();
4229 if leaves.len() != leaf_positions.len() {
4230 return Err(Error::unsupported(
4231 "AV1 tile",
4232 "a straddling 16x16 block needs one `eight` entry \
4233 per 8x8 leaf inside the true frame",
4234 ));
4235 }
4236 // r11: the enclosing 16x16 slot's
4237 // above_mode/left_mode arrays are too
4238 // coarse for a second leaf whose true
4239 // above (or left) neighbour is the FIRST
4240 // leaf -- track it here and hand it to
4241 // write_leaf8 as a context override.
4242 let mut prev_leaf: Option<((usize, usize), usize)> = None;
4243 for (leaf, (mr, mc)) in leaves.iter().zip(leaf_positions) {
4244 let leaf_mi = (mr as usize, mc as usize);
4245 // r8: read at mi granularity, not the
4246 // enclosing 16x16 slot -- the first
4247 // leaf's `record_mi` call below
4248 // updates `above_side_mi`/
4249 // `left_side_mi` at this leaf's own
4250 // mi position, which the second
4251 // leaf's ctx lookup then sees.
4252 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
4253 ec_rng_trace(|| {
4254 format!(
4255 "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={}",
4256 leaf_mi.0,
4257 leaf_mi.1,
4258 leaf_ctx,
4259 enc.tell()
4260 )
4261 });
4262 enc.symbol(
4263 PARTITION_NONE,
4264 &mut cdfs.partition_w8[leaf_ctx],
4265 );
4266 let grids = [
4267 level_grid(&leaf.luma, TX8)?,
4268 level_grid(&leaf.u, TX4)?,
4269 level_grid(&leaf.v, TX4)?,
4270 ];
4271 let leaf_mode = write_leaf8(
4272 &mut enc,
4273 &mut cdfs,
4274 &mut neighbours,
4275 leaf,
4276 at,
4277 leaf_mi,
4278 &grids,
4279 [&scans[2], &scans[3], &scans[3]],
4280 prev_leaf,
4281 tx_select,
4282 &scans,
4283 )?;
4284 prev_leaf = Some((leaf_mi, leaf_mode));
4285 ec_rng_trace(|| {
4286 format!(
4287 "EC_TOK mi_row={} mi_col={} tell={}",
4288 leaf_mi.0,
4289 leaf_mi.1,
4290 enc.tell()
4291 )
4292 });
4293 }
4294 // `record()`'s `above_mode`/`left_mode`
4295 // write is a no-op at an 8x8 leaf's own
4296 // side (`side / SUB == 0`), so the next
4297 // 16x16 quadrant beyond this straddling
4298 // one would otherwise see whatever stale
4299 // mode sat here before it: force the
4300 // write once the whole quadrant's leaves
4301 // are done, from the last (bottom/right-
4302 // most) leaf -- lane-av1-rect r15: doing
4303 // this *inside* `write_leaf8`, once per
4304 // leaf, let the first leaf's write
4305 // clobber the true external neighbour a
4306 // second leaf of the *same* quadrant
4307 // still needed to read on its
4308 // non-adjacency axis.
4309 if let Some((_, mode)) = prev_leaf {
4310 neighbours.above_mode[at.1] = mode;
4311 neighbours.left_mode[at.0] = mode;
4312 }
4313 }
4314 }
4315 }
4316 }
4317 }
4318 }
4319 }
4320 }
4321 Ok(enc.finish())
4322}
4323
4324/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`,
4325/// which the palette colour-index map's first (context-free) symbol is coded
4326/// with.
4327fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) {
4328 let l = crate::decode::ceil_log2(n as u32);
4329 let m = (1usize << l) - n;
4330 if value < m {
4331 enc.literal(value as u32, l - 1);
4332 } else {
4333 enc.literal(((value + m) >> 1) as u32, l - 1);
4334 enc.literal(((value + m) & 1) as u32, 1);
4335 }
4336}
4337
4338/// `write_palette_colors_y` (bitstream.c:1178), the write side of
4339/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache
4340/// entry (taken when this palette holds that colour, in cache order, stopping
4341/// once `n` are cached), then the colours the cache did not supply -- the
4342/// first raw, the rest as deltas off a bit width that shrinks with the range
4343/// left. `colors` is ascending and distinct, so the decoder's `merge_colors`
4344/// of the two ascending lists puts it back exactly.
4345fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) {
4346 let n = colors.len();
4347 let mut cached: Vec<u16> = Vec::with_capacity(n);
4348 for &c in cache {
4349 if cached.len() >= n {
4350 break;
4351 }
4352 let take = colors.contains(&c);
4353 enc.literal(u32::from(take), 1);
4354 if take {
4355 cached.push(c);
4356 }
4357 }
4358 let transmitted: Vec<u16> = colors
4359 .iter()
4360 .copied()
4361 .filter(|c| !cached.contains(c))
4362 .collect();
4363 if transmitted.is_empty() {
4364 return;
4365 }
4366 enc.literal(u32::from(transmitted[0]), 8);
4367 if transmitted.len() == 1 {
4368 return;
4369 }
4370 // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one
4371 // under which every delta still fits its (shrinking) width. `extra == 3`
4372 // always works -- a delta can never exceed the range left -- so the
4373 // search below always finds one.
4374 let fits = |extra: u32| -> bool {
4375 let mut bits = 5 + extra;
4376 let mut range = 255i32 - i32::from(transmitted[0]);
4377 for w in transmitted.windows(2) {
4378 let delta = i32::from(w[1]) - i32::from(w[0]);
4379 if delta - 1 >= (1i32 << bits) {
4380 return false;
4381 }
4382 range -= delta;
4383 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4384 }
4385 true
4386 };
4387 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
4388 enc.literal(extra, 2);
4389 let mut bits = 5 + extra;
4390 let mut range = 255i32 - i32::from(transmitted[0]);
4391 for w in transmitted.windows(2) {
4392 let delta = i32::from(w[1]) - i32::from(w[0]);
4393 enc.literal((delta - 1) as u32, bits);
4394 range -= delta;
4395 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4396 }
4397}
4398
4399/// `write_palette_colors_uv` (bitstream.c:1236), the write side of
4400/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is
4401/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two
4402/// documented differences -- the shrinking range starts at `256 - first`
4403/// (not `255 - first`) and each delta is written unbiased (no `-1`).
4404///
4405/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n`
4406/// 8-bit literals) rather than its first-value-plus-signed-deltas form.
4407/// Ceiling: about `n` bits per chroma-palette block more than the delta form
4408/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer
4409/// below sees, so it only ever makes the encoder take FEWER chroma palettes
4410/// than it should -- never a wrong stream. Upgrade path: price both forms
4411/// here and write the cheaper one under its own leading bit.
4412fn write_palette_colors_uv(
4413 enc: &mut SymbolEncoder,
4414 u_colors: &[u16],
4415 v_colors: &[u16],
4416 cache: &[u16],
4417) {
4418 let n = u_colors.len();
4419 let mut cached: Vec<u16> = Vec::with_capacity(n);
4420 for &c in cache {
4421 if cached.len() >= n {
4422 break;
4423 }
4424 let take = u_colors.contains(&c);
4425 enc.literal(u32::from(take), 1);
4426 if take {
4427 PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4428 cached.push(c);
4429 }
4430 }
4431 let transmitted: Vec<u16> = u_colors
4432 .iter()
4433 .copied()
4434 .filter(|c| !cached.contains(c))
4435 .collect();
4436 if !transmitted.is_empty() {
4437 enc.literal(u32::from(transmitted[0]), 8);
4438 if transmitted.len() > 1 {
4439 let fits = |extra: u32| -> bool {
4440 let mut bits = 5 + extra;
4441 let mut range = 256i32 - i32::from(transmitted[0]);
4442 for w in transmitted.windows(2) {
4443 let delta = i32::from(w[1]) - i32::from(w[0]);
4444 if delta >= (1i32 << bits) {
4445 return false;
4446 }
4447 range -= delta;
4448 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4449 }
4450 true
4451 };
4452 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
4453 enc.literal(extra, 2);
4454 let mut bits = 5 + extra;
4455 let mut range = 256i32 - i32::from(transmitted[0]);
4456 for w in transmitted.windows(2) {
4457 let delta = i32::from(w[1]) - i32::from(w[0]);
4458 enc.literal(delta as u32, bits);
4459 range -= delta;
4460 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4461 }
4462 }
4463 }
4464 enc.literal(0, 1);
4465 for &v in v_colors {
4466 enc.literal(u32::from(v), 8);
4467 }
4468}
4469
4470/// `write_palette_color_map` (bitstream.c), the write side of
4471/// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
4472/// each symbol written as the position its colour takes in the neighbour
4473/// ordering `av1_get_palette_color_index_context` hands back.
4474fn write_color_index_map(
4475 enc: &mut SymbolEncoder,
4476 idx_cdfs: &mut [[u16; 9]; 5],
4477 map: &[u8],
4478 side: usize,
4479 n: usize,
4480 // spec 5.11.50 `onscreenWidth`/`onscreenHeight` in this map's own units:
4481 // a block cut by the frame's right/bottom mi edge codes ONLY this corner
4482 // and the decoder replicates it outward (`decode::palette_replicate`).
4483 // Writing the full grid spent symbols a conformant decoder never reads,
4484 // desyncing the rest of the tile (lane-palw, class
4485 // writer-phantom-units-past-edge).
4486 on: (usize, usize),
4487) {
4488 let (on_w, on_h) = (on.0.clamp(1, side), on.1.clamp(1, side));
4489 write_uniform(enc, usize::from(map[0]), n);
4490 for i in 1..(on_w + on_h - 1) {
4491 for j in (i.saturating_sub(on_h - 1)..=i.min(on_w - 1)).rev() {
4492 let (row, col) = (i - j, j);
4493 let (ctx, color_order) =
4494 crate::decode::palette_color_index_context(map, side, row, col, n);
4495 let want = map[row * side + col];
4496 let symbol = color_order[..n]
4497 .iter()
4498 .position(|&c| c == want)
4499 .expect("every colour index is in the block\'s own palette");
4500 enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]);
4501 }
4502 }
4503}
4504
4505/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag,
4506/// the size symbol, the colours and the whole colour-index map, priced
4507/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the
4508/// search reads the rate the tile will really spend, not an estimate of it.
4509/// The neighbour cache is taken as empty (the search runs before the tile
4510/// knows what its neighbours will be), which only ever over-prices.
4511pub(crate) fn palette_bits(pal: &PaletteY, side: usize, on: (usize, usize)) -> f64 {
4512 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
4513 return f64::INFINITY;
4514 };
4515 let n = usize::from(pal.size);
4516 let mut enc = SymbolEncoder::pricer();
4517 let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0];
4518 enc.symbol(1, &mut mode_cdf);
4519 let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx];
4520 enc.symbol(n - 2, &mut size_cdf);
4521 write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
4522 let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];
4523 write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n, on);
4524 enc.bits()
4525}
4526
4527/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
4528/// size symbol, both colour lists and the shared colour-index map, priced
4529/// through the very writers above (empty cache, which only over-prices).
4530pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize, on: (usize, usize)) -> f64 {
4531 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
4532 return f64::INFINITY;
4533 };
4534 let n = usize::from(pal.size);
4535 let mut enc = SymbolEncoder::pricer();
4536 let mut mode_cdf = cdf::PALETTE_UV_MODE[0];
4537 enc.symbol(1, &mut mode_cdf);
4538 let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx];
4539 enc.symbol(n - 2, &mut size_cdf);
4540 write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
4541 let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];
4542 write_color_index_map(
4543 &mut enc,
4544 &mut idx_cdfs,
4545 &pal.map,
4546 palette_uv_side(side),
4547 n,
4548 on,
4549 );
4550 enc.bits()
4551}
4552
4553/// Writes everything a key frame's block carries before its coefficients: the
4554/// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
4555/// the angle a directional mode is steered by, and its chroma mode. Hands back
4556/// the luma mode, which is what the blocks beside it read.
4557/// The DV predictor decode.rs `read_intrabc_dv` derives, mirrored line for
4558/// line off the writer's own copy of the intrabc mi grid: the `INTRA_FRAME`
4559/// stack's `nearest_mv` (or `near_mv` when that is zero), or -- when both are
4560/// -- `av1_find_ref_dv`'s fallback one superblock up, or 256 pixels plus one
4561/// superblock to the left on the tile's first superblock row, then floored to
4562/// full pel. Returns `(0, 0)` when no grid is armed, which no `allow_intrabc`
4563/// tile ever reaches.
4564fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) {
4565 const INTRABC_DELAY_PIXELS: i32 = 256;
4566 let n4 = side / MI;
4567 let stack_pred = INTRABC_GRID.with(|g| {
4568 let g = g.borrow();
4569 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
4570 let stack = crate::mvstack::find_mv_stack(
4571 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
4572 *mi_cols, *mi_rows,
4573 );
4574 if stack.nearest_mv == (0, 0) {
4575 stack.near_mv
4576 } else {
4577 stack.nearest_mv
4578 }
4579 })
4580 });
4581 let mut pred = stack_pred.unwrap_or((0, 0));
4582 if pred == (0, 0) {
4583 // `av1_find_ref_dv` takes `mib_size`, the SEQUENCE's superblock size
4584 // in mi units (lane-b128m: hardcoding 16 here made the writer's DV
4585 // predictor one 64 superblock up while decode.rs `read_intrabc_dv`
4586 // took 128 -- identical symbols, different reconstructed DV). The
4587 // tile row start is 0, exactly as the reader takes it -- both are
4588 // written for the single-tile-row streams this encoder produces.
4589 let sb_mi = if sb128_armed() { 32i32 } else { 16i32 };
4590 let sb_px = sb_mi * MI as i32;
4591 pred = if (mi_r as i32) < sb_mi {
4592 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
4593 } else {
4594 (-sb_px * 8, 0)
4595 };
4596 }
4597 ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8)
4598}
4599
4600/// Publishes one coded block into [`INTRABC_GRID`], mirroring decode.rs
4601/// `record_intrabc_mi`: every block contributes its size, an intrabc one also
4602/// its DV as an `INTRA_FRAME` candidate.
4603fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
4604 INTRABC_GRID.with(|g| {
4605 let mut g = g.borrow_mut();
4606 let Some((grid, _, _)) = g.as_mut() else {
4607 return;
4608 };
4609 let info = crate::mvstack::MiInfo {
4610 is_inter: dv.is_some(),
4611 ref_frame: 0,
4612 ref_frame1: crate::mvstack::NO_REF1,
4613 mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))),
4614 mv1: (0, 0),
4615 is_new_mv: dv.is_some(),
4616 is_global_mv0: false,
4617 is_global_mv1: false,
4618 size: n4 as u8,
4619 size_h: n4 as u8,
4620 };
4621 for r in mi_r..mi_r + n4 {
4622 for c in mi_c..mi_c + n4 {
4623 grid.set(r, c, info);
4624 }
4625 }
4626 });
4627}
4628
4629/// One full-pel block-vector component, [`write_mv_component`]'s
4630/// `force_integer_mv` twin: decode.rs `read_mv_component` infers `mv_fr`/
4631/// `mv_class0_fr` as 3 and the high-precision bit as 1 under
4632/// `force_integer_mv`, so neither symbol is written here -- writing them
4633/// would leave the decoder two symbols behind from this block on.
4634fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
4635 let mag = diff.unsigned_abs() as i32;
4636 if mag % 8 != 0 {
4637 return Err(Error::unsupported(
4638 "AV1 tile",
4639 "a block vector is coded at full-pel precision only",
4640 ));
4641 }
4642 enc.symbol(usize::from(diff < 0), &mut c.sign);
4643 let z = mag - 1;
4644 let class = mv_class_of(z);
4645 enc.symbol(class, &mut c.class);
4646 let local = z - mv_class_base(class);
4647 if class == 0 {
4648 enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit);
4649 } else {
4650 let d = local >> 3;
4651 for i in 0..class {
4652 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
4653 }
4654 }
4655 Ok(())
4656}
4657
4658/// One intrabc block's DV as a residual against [`intrabc_dv_pred`], off the
4659/// `dv` nmv context (decode.rs `read_intrabc_dv` -> `read_mv`).
4660fn write_dv(
4661 enc: &mut SymbolEncoder,
4662 cdfs: &mut Cdfs,
4663 dv: (i32, i32),
4664 pred: (i32, i32),
4665) -> Result<()> {
4666 let diff = (dv.0 - pred.0, dv.1 - pred.1);
4667 let joint = match (diff.0 != 0, diff.1 != 0) {
4668 (false, false) => 0,
4669 (false, true) => 1,
4670 (true, false) => 2,
4671 (true, true) => 3,
4672 };
4673 enc.symbol(joint, &mut cdfs.dv_joint);
4674 if diff.0 != 0 {
4675 write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?;
4676 }
4677 if diff.1 != 0 {
4678 write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?;
4679 }
4680 Ok(())
4681}
4682
4683/// The mode-info half of an intrabc block (decode.rs `read_intra_mode`'s
4684/// early return): `skip`, `cdef_idx`, `use_intrabc` and the DV, then nothing
4685/// -- no y/uv mode, no angle delta, no palette, and (because it is skipped)
4686/// no transform size and no residual. Publishes the block into every
4687/// neighbour band an ordinary block leaves behind, at the DC_PRED/uncoded/
4688/// skipped state a decoder reads back for it.
4689fn write_intrabc_block(
4690 enc: &mut SymbolEncoder,
4691 cdfs: &mut Cdfs,
4692 neighbours: &mut Neighbours,
4693 dv: (i32, i32),
4694 mi: (usize, usize),
4695 side: usize,
4696) -> Result<()> {
4697 let skip_ctx =
4698 usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
4699 enc.symbol(1, &mut cdfs.skip[skip_ctx]);
4700 write_cdef_idx(enc, mi, true);
4701 enc.symbol(1, &mut cdfs.intrabc);
4702 write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?;
4703 note_intrabc(dv);
4704 // The bands: DC_PRED mode (what the decoder forces), no coefficients
4705 // anywhere (skip), the block's own side for the partition context, the
4706 // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm)
4707 // for the deblock grid, and `skip` itself for the next block's skip
4708 // context.
4709 // One zero level per plane: `neighbour_state` reads `grid[0]` for the DC
4710 // sign vote, and a skipped block leaves every context cleared.
4711 let empty: [Vec<i32>; 3] = [vec![0], vec![0], vec![0]];
4712 for cell in 0..(side / SUB).max(1) {
4713 let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI));
4714 neighbours.above_mode[c + cell] = DC_PRED;
4715 neighbours.left_mode[r + cell] = DC_PRED;
4716 neighbours.above_side[c + cell] = side;
4717 neighbours.left_side[r + cell] = side;
4718 }
4719 neighbours.record_mi_planes(mi, side, &empty, true);
4720 neighbours.record_tx(mi, side, side.min(64));
4721 for cell in 0..side / MI {
4722 neighbours.above_skip[mi.1 + cell] = true;
4723 neighbours.left_skip[mi.0 + cell] = true;
4724 }
4725 Ok(())
4726}
4727
4728/// `UV_CFL_PRED` (spec 6.10.19's chroma mode enum), the fourteenth entry of
4729/// [`crate::cdf::UV_MODE_CFL`] -- the writer's twin of the decoder's own
4730/// constant.
4731pub(crate) const UV_CFL_PRED: usize = 13;
4732
4733/// The `cfl_alpha_signs` joint value (0..8) that codes this signed alpha pair,
4734/// inverting the decoder's own `read_cfl_alphas` split (`sign_u =
4735/// ((joint+1)*11)>>5`, `sign_v = (joint+1) - 3*sign_u`, with 0 ZERO, 1 NEG,
4736/// 2 POS). There is no (ZERO, ZERO) joint value, so at least one alpha of a
4737/// CfL block is nonzero by construction.
4738pub(crate) fn cfl_joint_sign(alpha_u: i32, alpha_v: i32) -> usize {
4739 let sign = |a: i32| match a.signum() {
4740 0 => 0,
4741 -1 => 1,
4742 _ => 2,
4743 };
4744 let (want_u, want_v) = (sign(alpha_u), sign(alpha_v));
4745 (0..8)
4746 .find(|&j| {
4747 let su = ((j + 1) * 11) >> 5;
4748 (su, (j + 1) - 3 * su) == (want_u, want_v)
4749 })
4750 .expect("cfl_alpha_signs covers every pair but (ZERO, ZERO)") as usize
4751}
4752
4753/// The `cfl_alpha_u`/`cfl_alpha_v` magnitude CDF row for one plane, by the
4754/// same `CFL_CONTEXT_U`/`CFL_CONTEXT_V` derivation the decoder reads with
4755/// (libaom cfl.h). `joint` is [`cfl_joint_sign`]'s value.
4756fn cfl_alpha_ctx(joint: usize, plane: usize) -> usize {
4757 let joint = joint as i32;
4758 let su = ((joint + 1) * 11) >> 5;
4759 let sv = (joint + 1) - 3 * su;
4760 if plane == 0 {
4761 (joint + 1 - 3) as usize
4762 } else {
4763 (sv * 3 + su - 3) as usize
4764 }
4765}
4766
4767/// What [`write_cfl_alphas`] will spend on this alpha pair, through the same
4768/// tables -- the encoder's RD price for the CfL arm.
4769pub(crate) fn cfl_alpha_bits(alpha_u: i32, alpha_v: i32) -> f64 {
4770 use crate::encode::symbol_bits;
4771 let joint = cfl_joint_sign(alpha_u, alpha_v);
4772 let mut bits = symbol_bits(&crate::cdf::CFL_SIGN, joint);
4773 for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
4774 if alpha != 0 {
4775 bits += symbol_bits(
4776 &crate::cdf::CFL_ALPHA[cfl_alpha_ctx(joint, plane)],
4777 (alpha.unsigned_abs() - 1) as usize,
4778 );
4779 }
4780 }
4781 bits
4782}
4783
4784/// `read_cfl_alphas` (spec 5.11.45) written: the joint sign, then each
4785/// plane's magnitude where its sign is nonzero.
4786fn write_cfl_alphas(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, (alpha_u, alpha_v): (i32, i32)) {
4787 let joint = cfl_joint_sign(alpha_u, alpha_v);
4788 enc.symbol(joint, &mut cdfs.cfl_sign);
4789 for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
4790 if alpha != 0 {
4791 enc.symbol(
4792 (alpha.unsigned_abs() - 1) as usize,
4793 &mut cdfs.cfl_alpha[cfl_alpha_ctx(joint, plane)],
4794 );
4795 }
4796 }
4797}
4798
4799fn write_intra_mode(
4800 enc: &mut SymbolEncoder,
4801 cdfs: &mut Cdfs,
4802 neighbours: &mut Neighbours,
4803 block: &BlockCoeffs,
4804 above_mode: usize,
4805 left_mode: usize,
4806 cfl: bool,
4807 // This block's own position in 4x4 mode-info units, for the `cdef_idx`
4808 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
4809 mi: (usize, usize),
4810 // The block's side in samples, which gates the palette syntax below
4811 // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]).
4812 side: usize,
4813) -> usize {
4814 let mode = usize::from(block.mode);
4815 // `av1_get_skip_txfm_context` (decode.rs `Neighbours::skip_txfm_ctx`):
4816 // above + left. Every block this writer codes outside an `allow_intrabc`
4817 // frame is unskipped, so both bands stay false and this stays 0 -- the
4818 // literal every stream before this lane was written with.
4819 let skip_ctx =
4820 usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
4821 enc.symbol(0, &mut cdfs.skip[skip_ctx]);
4822 write_cdef_idx(enc, mi, false);
4823 // `read_intrabc_info` (spec 5.11.13): the flag is read for EVERY intra
4824 // block of an `allow_intrabc` frame, not only the ones that use it.
4825 if intrabc_armed() {
4826 enc.symbol(0, &mut cdfs.intrabc);
4827 }
4828 enc.symbol(
4829 mode,
4830 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
4831 );
4832 ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng()));
4833 if (V_PRED..=D67_PRED).contains(&mode) {
4834 enc.symbol(
4835 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
4836 &mut cdfs.angle_delta[mode - V_PRED],
4837 );
4838 }
4839 // A block small enough to be offered chroma from luma reads the wider
4840 // table even when it does not take the mode.
4841 let uv_mode = usize::from(block.uv_mode);
4842 if cfl {
4843 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
4844 } else {
4845 debug_assert_ne!(uv_mode, UV_CFL_PRED, "is_cfl_allowed excludes this block");
4846 enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);
4847 }
4848 if uv_mode == UV_CFL_PRED {
4849 write_cfl_alphas(
4850 enc,
4851 cdfs,
4852 block
4853 .cfl_alphas
4854 .expect("a UV_CFL_PRED block carries its alphas"),
4855 );
4856 }
4857 // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array
4858 // the luma delta reads, indexed by the chroma mode.
4859 if (V_PRED..=D67_PRED).contains(&uv_mode) {
4860 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
4861 }
4862 // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from
4863 // the decoder's own read in `read_intra_mode`: on a frame whose header set
4864 // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED`
4865 // chroma pair each carry a use-palette flag. Both contexts are 0 here --
4866 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
4867 // codes none -- exactly the ctx-0 read the decoder does under the same
4868 // condition.
4869 write_palette_syntax(
4870 enc,
4871 cdfs,
4872 neighbours,
4873 block.palette.as_ref(),
4874 block.palette_uv.as_ref(),
4875 block.filter_intra,
4876 mode,
4877 uv_mode,
4878 mi,
4879 side,
4880 );
4881 mode
4882}
4883
4884/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for
4885/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose
4886/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a
4887/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette
4888/// then codes its size, its colours (against the neighbour colour cache) and
4889/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs
4890/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and
4891/// by the three intra arms of the inter-frame writers, which read the same
4892/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`.
4893///
4894/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the
4895/// one point every block passes through), so a block that takes no palette
4896/// still clears what the column held.
4897#[allow(clippy::too_many_arguments)]
4898fn write_palette_syntax(
4899 enc: &mut SymbolEncoder,
4900 cdfs: &mut Cdfs,
4901 neighbours: &mut Neighbours,
4902 palette: Option<&PaletteY>,
4903 palette_uv: Option<&PaletteUv>,
4904 // lane-fintra: this block's chosen `filter_intra_mode`, or `None`. Written
4905 // here rather than by the caller because its symbol sits BETWEEN the
4906 // palette colour lists and the colour-index maps (decode.rs
4907 // `read_intra_mode`), which is inside this function.
4908 filter_intra: Option<u8>,
4909 mode: usize,
4910 uv_mode: usize,
4911 mi: (usize, usize),
4912 side: usize,
4913) {
4914 if !screen_armed() {
4915 write_filter_intra(enc, cdfs, mode, side, false, filter_intra);
4916 return;
4917 }
4918 let palette = palette.filter(|_| mode == DC_PRED);
4919 let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
4920 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
4921 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
4922 let uv_cache = neighbours.palette_uv_cache(mi);
4923 if mode == DC_PRED {
4924 enc.symbol(
4925 usize::from(palette.is_some()),
4926 &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],
4927 );
4928 }
4929 if let Some(pal) = palette {
4930 let n = usize::from(pal.size);
4931 enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);
4932 write_palette_colors_y(enc, &pal.colors[..n], &cache);
4933 }
4934 if uv_mode == DC_PRED {
4935 enc.symbol(
4936 usize::from(palette_uv.is_some()),
4937 &mut cdfs.palette_uv_mode[usize::from(palette.is_some())],
4938 );
4939 }
4940 if let Some(pal) = palette_uv {
4941 let n = usize::from(pal.size);
4942 enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]);
4943 write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache);
4944 }
4945 write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra);
4946 // Both colour-index maps come after BOTH colour lists, in plane order
4947 // (`av1_visit_palette` runs from the caller, past `filter_intra`).
4948 // The on-screen extent of THIS block, from the frame mi dims armed
4949 // for this tile write -- the decoder's `palette_onscreen` half.
4950 let on = crate::decode::palette_onscreen_dims(mi.0, mi.1, side, side, frame_mi_dims());
4951 if (on.0 < side || on.1 < side) && (palette.is_some() || palette_uv.is_some()) {
4952 PALETTE_CUT_MAPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4953 }
4954 if let Some(pal) = palette {
4955 let n = usize::from(pal.size);
4956 write_color_index_map(
4957 enc,
4958 &mut cdfs.palette_y_color_index[n - 2],
4959 &pal.map,
4960 side,
4961 n,
4962 on,
4963 );
4964 note_palette(n);
4965 }
4966 if let Some(pal) = palette_uv {
4967 let n = usize::from(pal.size);
4968 let uv_side = palette_uv_side(side);
4969 write_color_index_map(
4970 enc,
4971 &mut cdfs.palette_uv_color_index[n - 2],
4972 &pal.map,
4973 uv_side,
4974 n,
4975 // The encoder writes 4:2:0 only (`palette_uv_side` above).
4976 crate::decode::palette_onscreen_uv((side, side), on, (uv_side, uv_side), (1, 1)),
4977 );
4978 note_palette_uv(n);
4979 }
4980 } else {
4981 // Below `av1_allow_palette`'s size bound there is no palette syntax at
4982 // all, but `av1_filter_intra_allowed_bsize` still admits the block.
4983 write_filter_intra(enc, cdfs, mode, side, false, filter_intra);
4984 }
4985 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
4986 neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors));
4987}
4988
4989/// The side of a chroma palette's shared colour-index map for a square luma
4990/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at
4991/// the 4-px transform, NOT a plain halving (decode.rs reads the map at
4992/// exactly this size).
4993pub(crate) fn palette_uv_side(side: usize) -> usize {
4994 (side / 2).max(4)
4995}
4996
4997/// How many blocks took a palette, and of what size -- the fire count a gate
4998/// prints so that "palette is on" is a measurement rather than a claim
4999/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the
5000/// per-size histogram.
5001static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
5002 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
5003
5004/// lane-palw: colour-index maps written over the ON-SCREEN corner only,
5005/// i.e. palette blocks this writer cut at the frame's right/bottom mi edge.
5006/// A gate asserts it non-zero so it cannot pass on a stream that never cuts
5007/// one (class `gate-blind-to-feature`).
5008static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
5009
5010/// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps).
5011pub fn palette_cut_maps_written() -> usize {
5012 PALETTE_CUT_MAPS.load(std::sync::atomic::Ordering::Relaxed)
5013}
5014
5015/// Zeroes [`PALETTE_CUT_MAPS`] before a gate's own encode.
5016pub fn reset_palette_cut_maps_written() {
5017 PALETTE_CUT_MAPS.store(0, std::sync::atomic::Ordering::Relaxed);
5018}
5019
5020fn note_palette(n: usize) {
5021 PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5022 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5023}
5024
5025/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can
5026/// print the share of each plane's palette separately.
5027static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] =
5028 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
5029
5030fn note_palette_uv(n: usize) {
5031 PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5032 PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5033}
5034
5035/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than
5036/// the stream -- the half of `write_palette_colors_uv` a test cannot see from
5037/// the block counts alone, and the one that desyncs the tile if this writer's
5038/// cache ever disagrees with the decoder's (`gate-blind-to-feature`).
5039static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize =
5040 std::sync::atomic::AtomicUsize::new(0);
5041
5042/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it.
5043#[cfg(test)]
5044pub(crate) fn take_palette_uv_cache_hits() -> usize {
5045 PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
5046}
5047
5048/// [`take_palette_hits`] for the chroma palette.
5049#[cfg(test)]
5050pub(crate) fn take_palette_uv_hits() -> [usize; 9] {
5051 std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5052}
5053
5054/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
5055/// its own encode.
5056#[cfg(test)]
5057pub(crate) fn take_palette_hits() -> [usize; 9] {
5058 std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5059}
5060
5061/// Writes one coded block: its mode, its three transform blocks, and what it
5062/// leaves behind for the blocks beside it. Its partition symbol is already
5063/// written, because only the caller knows what tree led here.
5064#[allow(clippy::too_many_arguments)]
5065fn write_block(
5066 enc: &mut SymbolEncoder,
5067 cdfs: &mut Cdfs,
5068 neighbours: &mut Neighbours,
5069 block: &BlockCoeffs,
5070 at: (usize, usize),
5071 side: usize,
5072 planes: &[TxbSet; 3],
5073 grids: &[Vec<i32>; 3],
5074 scans: [&Vec<u16>; 3],
5075 cfl: bool,
5076 // The frame's `tx_mode == TxMode::Select`, and the block's own chosen
5077 // depth: with it the luma residual goes through [`write_luma_select`]
5078 // (one `tx_depth` symbol, then one transform unit per tile of the block)
5079 // instead of the single whole-block transform below.
5080 tx_select: bool,
5081 all_scans: &[Vec<u16>; 4],
5082) -> Result<()> {
5083 let (r, c) = at;
5084 let at_mi = (r * (SUB / MI), c * (SUB / MI));
5085 if let Some(dv) = block.dv {
5086 write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?;
5087 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv));
5088 return Ok(());
5089 }
5090 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
5091 let mode = write_intra_mode(
5092 enc, cdfs, neighbours, block, above_mode, left_mode, cfl, at_mi, side,
5093 );
5094 // The coefficient tables read `fimode_to_intradir[filter_intra_mode]`'s
5095 // row on a filter-intra block; the neighbour publication below still gets
5096 // the block's own `DC_PRED` ([`tx_row`]).
5097 let tx_mode = tx_row(mode, block.filter_intra);
5098 let split = if tx_select {
5099 let tx = write_luma_select(
5100 enc,
5101 cdfs,
5102 neighbours,
5103 at_mi,
5104 side,
5105 usize::from(block.tx_depth),
5106 &grids[0],
5107 tx_mode,
5108 all_scans,
5109 &block.luma_tx_types,
5110 )?;
5111 tx < side
5112 } else {
5113 false
5114 };
5115 write_block_planes(
5116 enc,
5117 cdfs,
5118 planes,
5119 grids,
5120 &scans,
5121 &neighbours.around(at, side),
5122 tx_mode,
5123 tx_select,
5124 block_tx_type(block),
5125 false,
5126 );
5127 neighbours.record_planes(at, side, mode, grids, !split);
5128 clear_skip_band(neighbours, at_mi, side);
5129 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None);
5130 Ok(())
5131}
5132
5133/// An unskipped block's own `skip` publication: only an `allow_intrabc`
5134/// frame ever sets these bands, so a frame without one leaves them exactly
5135/// as they were before this lane (all false).
5136fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) {
5137 if !intrabc_armed() {
5138 return;
5139 }
5140 for cell in 0..side / MI {
5141 neighbours.above_skip[mi.1 + cell] = false;
5142 neighbours.left_skip[mi.0 + cell] = false;
5143 }
5144}
5145
5146/// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
5147/// luma transform and 4x4 chroma transforms, coded exactly like
5148/// [`write_block`] but reading its intra-mode context from the *enclosing*
5149/// 16x16 slot -- `outer_at`, in [`SUB`]-grid units -- rather than from its own
5150/// finer position, since [`Neighbours`]'s `above_mode`/`left_mode` arrays stay
5151/// at [`SUB`] (16-sample) granularity. `leaf_mi` is this leaf's own position
5152/// in 4x4 mode-info units, which is what its coefficient context (finer than
5153/// [`SUB`]) is kept and read at.
5154#[allow(clippy::too_many_arguments)]
5155fn write_leaf8(
5156 enc: &mut SymbolEncoder,
5157 cdfs: &mut Cdfs,
5158 neighbours: &mut Neighbours,
5159 block: &BlockCoeffs,
5160 outer_at: (usize, usize),
5161 leaf_mi: (usize, usize),
5162 grids: &[Vec<i32>; 3],
5163 scans: [&Vec<u16>; 3],
5164 prev_leaf: Option<((usize, usize), usize)>,
5165 tx_select: bool,
5166 all_scans: &[Vec<u16>; 4],
5167) -> Result<usize> {
5168 let (r, c) = outer_at;
5169 if let Some(dv) = block.dv {
5170 write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?;
5171 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv));
5172 return Ok(DC_PRED);
5173 }
5174 let mut above_mode = neighbours.above_mode[c];
5175 let mut left_mode = neighbours.left_mode[r];
5176 // The previous leaf sits directly above (same column, two mi rows up)
5177 // or directly to the left (same row, two mi cols over) of this one --
5178 // in either case its just-written mode, not the enclosing 16x16 slot's
5179 // stale neighbour, is what a decoder reads as this leaf's context.
5180 if let Some(((pr, pc), pmode)) = prev_leaf {
5181 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
5182 above_mode = pmode;
5183 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
5184 left_mode = pmode;
5185 }
5186 }
5187 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
5188 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF -- like every
5189 // other `write_block` caller at 16x16 and up -- not the narrower
5190 // no-CFL one: r12 lane-av1-rect, this leaf's own `cfl: false` was the
5191 // true first divergence (a differently-sized alphabet under the same
5192 // DC_PRED decision desyncs the coder even though the decoded mode is
5193 // unchanged).
5194 let mode = write_intra_mode(
5195 enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8,
5196 );
5197 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
5198 // As [`write_block`]: the coefficient row follows the filter-intra mode,
5199 // the mode this leaf publishes (and returns to the next leaf) does not.
5200 let tx_mode = tx_row(mode, block.filter_intra);
5201 let split = if tx_select {
5202 let tx = write_luma_select(
5203 enc,
5204 cdfs,
5205 neighbours,
5206 leaf_mi,
5207 8,
5208 usize::from(block.tx_depth),
5209 &grids[0],
5210 tx_mode,
5211 all_scans,
5212 &block.luma_tx_types,
5213 )?;
5214 tx < 8
5215 } else {
5216 false
5217 };
5218 write_block_planes(
5219 enc,
5220 cdfs,
5221 &planes,
5222 grids,
5223 &scans,
5224 &neighbours.around_mi(leaf_mi, 8),
5225 tx_mode,
5226 tx_select,
5227 block_tx_type(block),
5228 false,
5229 );
5230 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
5231 clear_skip_band(neighbours, leaf_mi, 8);
5232 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None);
5233 Ok(mode)
5234}
5235
5236/// Writes the three transform blocks of one coded block, in the order a
5237/// decoder reads them.
5238#[allow(clippy::too_many_arguments)]
5239fn write_block_planes(
5240 enc: &mut SymbolEncoder,
5241 cdfs: &mut Cdfs,
5242 planes: &[TxbSet; 3],
5243 grids: &[Vec<i32>; 3],
5244 scans: &[&Vec<u16>; 3],
5245 around: &[Around; 3],
5246 mode: usize,
5247 // A block whose luma was already written as several transform units
5248 // ([`write_luma_select`]) has only its chroma planes left here.
5249 skip_luma: bool,
5250 // This block's single luma transform type (lane-txset); chroma's is
5251 // derived from its mode by the decoder and codes no symbol.
5252 luma_tx_type: TxType,
5253 // lane-intertx: an INTER block's chroma transforms INHERIT the luma
5254 // type (reduced to the chroma set against this frame's own
5255 // `reduced_tx_set` bit); an intra block's comes off its UV mode and
5256 // rides `DCT_DCT`'s 2D class exactly as before.
5257 inter: bool,
5258) {
5259 // lane-intertx, desync (b): the writer used to code every chroma plane
5260 // `DCT_DCT`. Chroma codes no `tx_type` symbol, but the type names the
5261 // transform class, and the class picks the scan, the `eob_pt` row and
5262 // the context offsets (the lane-txw note in `write_coeffs`) -- so an
5263 // inherited 1-D luma type desynced the chroma exactly as luma itself
5264 // once did. The reduced bit read here is the frame's own header bit,
5265 // the ONE the writer's `Cdfs` is armed with (`Cdfs::reduced_tx_set`).
5266 let reduced = cdfs.reduced_tx_set;
5267 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
5268 if plane == 0 && skip_luma {
5269 continue;
5270 }
5271 // Luma's transform covers its whole block, which fixes the all-zero
5272 // flag's context at zero; a chroma transform reads whether its
5273 // neighbours coded anything, on top of the offset the chroma tables
5274 // start at.
5275 let skip_ctx = if plane == 0 {
5276 0
5277 } else {
5278 usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
5279 };
5280 #[cfg(test)]
5281 let before = enc.tell();
5282 #[cfg(test)]
5283 let q_ctx = cdfs.q_ctx;
5284 let mut coding = cdfs.txb(planes[plane], mode);
5285 let tx_type = if plane == 0 {
5286 luma_tx_type
5287 } else if inter {
5288 crate::decode::reduce_inherited_chroma_tx_type_flagged(
5289 luma_tx_type,
5290 coding.side.min(32),
5291 coding.side.min(32),
5292 reduced,
5293 )
5294 } else {
5295 TxType::DctDct
5296 };
5297 write_coeffs(
5298 enc,
5299 &mut coding,
5300 grid,
5301 scan,
5302 skip_ctx,
5303 dc_sign_ctx(around[plane].dc_vote),
5304 Some(plane),
5305 tx_type,
5306 );
5307 #[cfg(test)]
5308 census_record(
5309 planes[plane],
5310 q_ctx,
5311 grid,
5312 f64::from(enc.tell() - before),
5313 skip_ctx,
5314 dc_sign_ctx(around[plane].dc_vote),
5315 );
5316 ec_rng_trace(|| {
5317 format!(
5318 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
5319 grid.iter().filter(|&&l| l != 0).count(),
5320 enc.tell()
5321 )
5322 });
5323 }
5324}
5325
5326/// The single luma transform type a block carries, `DCT_DCT` for one that
5327/// never searched one (lane-txset).
5328fn block_tx_type(block: &BlockCoeffs) -> TxType {
5329 block
5330 .luma_tx_types
5331 .first()
5332 .copied()
5333 .unwrap_or(TxType::DctDct)
5334}
5335
5336/// The `(side / tx)^2` transform units of one block's luma residual, raster
5337/// order, each with its own coefficient context and each published before the
5338/// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch).
5339/// `grid` is the block's levels in BLOCK coordinates when the transform
5340/// splits, and the single transform's own coefficient grid when it does not.
5341#[allow(clippy::too_many_arguments)]
5342fn write_luma_tus(
5343 enc: &mut SymbolEncoder,
5344 cdfs: &mut Cdfs,
5345 neighbours: &mut Neighbours,
5346 at_mi: (usize, usize),
5347 side: usize,
5348 tx: usize,
5349 grid: &[i32],
5350 mode: usize,
5351 scans: &[Vec<u16>; 4],
5352 // lane-av1tx2 r2: an INTER block's split units read the inter coefficient
5353 // tables, not the intra ones (`TxbSet::Luma*Inter`).
5354 inter: bool,
5355 // One transform type per unit in this same raster order (lane-txset).
5356 // Empty -- what every caller that never searched a type passes -- is
5357 // `DCT_DCT` throughout, the one type this writer used to code.
5358 tx_types: &[TxType],
5359) -> Result<()> {
5360 if tx < side && side > 32 && tx < 32 {
5361 // A 64x64 block's own levels reach the writer as the 32x32 corner a
5362 // 64-point transform codes unless the whole block was SPLIT into
5363 // TX_32X32 units (lane-b64b), so any finer split has nothing to slice.
5364 return Err(Error::unsupported(
5365 "AV1 tile",
5366 "a 64x64 block's luma transform splits no finer than TX_32X32",
5367 ));
5368 }
5369 let coeff_side = tx.min(32);
5370 let n = side / tx;
5371 let set = match (tx, inter) {
5372 (32, false) => TxbSet::Luma32,
5373 (16, false) => TxbSet::Luma16,
5374 (8, false) => TxbSet::Luma8,
5375 (4, false) => TxbSet::Luma4,
5376 (32, true) => TxbSet::Luma32Inter,
5377 (16, true) => TxbSet::Luma16Inter,
5378 (8, true) => TxbSet::Luma8Inter,
5379 (4, true) => TxbSet::Luma4Inter,
5380 _ => TxbSet::Luma64,
5381 };
5382 let scan = match coeff_side {
5383 32 => &scans[0],
5384 16 => &scans[1],
5385 8 => &scans[2],
5386 _ => &scans[3],
5387 };
5388 let (mi_r, mi_c) = at_mi;
5389 for tu_row in 0..n {
5390 for tu_col in 0..n {
5391 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
5392 // lane-av1straddle: libaom clips the transform loop to
5393 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
5394 // off the frame's true `mi_cols`/`mi_rows`), and decode.rs does
5395 // the same (`tu_px >= y.true_width` there): a unit whose TOP-LEFT
5396 // sample is outside the frame is NEVER coded. Writing one -- as
5397 // this loop did for the phantom right-hand column of a 32x32 at
5398 // x=192 in a 216-wide frame -- desyncs the tile at the very next
5399 // symbol, which is what made an odd-size GOP's last block
5400 // reconstruct differently and both ffmpeg decoders (libdav1d and
5401 // libaom) refuse the whole key frame.
5402 if tu_mi.0 >= neighbours.mi_rows || tu_mi.1 >= neighbours.mi_cols {
5403 continue;
5404 }
5405 let unit = if n == 1 {
5406 grid.to_vec()
5407 } else {
5408 (0..tx)
5409 .flat_map(|row| grid[(tu_row * tx + row) * side + tu_col * tx..][..tx].to_vec())
5410 .collect()
5411 };
5412 // spec `get_txb_ctx_general`: a lone transform unit covering its
5413 // whole block reads context 0, a smaller one the neighbour
5414 // magnitude table.
5415 let skip_ctx = if n == 1 {
5416 0
5417 } else {
5418 neighbours.luma_skip_ctx(tu_mi, tx / MI)
5419 };
5420 let around = neighbours.around_mi(tu_mi, tx)[0];
5421 #[cfg(test)]
5422 let before = enc.tell();
5423 #[cfg(test)]
5424 let q_ctx = cdfs.q_ctx;
5425 write_coeffs(
5426 enc,
5427 &mut cdfs.txb(set, mode),
5428 &unit,
5429 scan,
5430 skip_ctx,
5431 dc_sign_ctx(around.dc_vote),
5432 Some(0),
5433 tx_types
5434 .get(tu_row * n + tu_col)
5435 .copied()
5436 .unwrap_or(TxType::DctDct),
5437 );
5438 #[cfg(test)]
5439 census_record(
5440 set,
5441 q_ctx,
5442 &unit,
5443 f64::from(enc.tell() - before),
5444 skip_ctx,
5445 dc_sign_ctx(around.dc_vote),
5446 );
5447 if n > 1 {
5448 neighbours.record_mi_luma(tu_mi, tx, &unit);
5449 }
5450 }
5451 }
5452 Ok(())
5453}
5454
5455/// Writes one intra block's luma residual under `TxMode::Select`: the
5456/// `tx_depth` symbol (spec 5.11.16 `read_selected_tx_size`, off the size
5457/// category's own CDF at [`Neighbours::tx_size_ctx`]'s row), then the
5458/// `(side / tx)^2` transform units in raster order -- each predicted and
5459/// coded against what the units before it already left behind, which is why
5460/// every unit publishes its own coefficient context before the next one reads
5461/// it (decode.rs `decode_block`'s multi-transform-unit branch).
5462///
5463/// `grid` is the block's levels in BLOCK coordinates (`side` by `side`) when
5464/// the transform splits, and the single transform's own coefficient grid when
5465/// it does not. Hands back the resolved transform side in pixels.
5466#[allow(clippy::too_many_arguments)]
5467fn write_luma_select(
5468 enc: &mut SymbolEncoder,
5469 cdfs: &mut Cdfs,
5470 neighbours: &mut Neighbours,
5471 at_mi: (usize, usize),
5472 side: usize,
5473 depth: usize,
5474 grid: &[i32],
5475 mode: usize,
5476 scans: &[Vec<u16>; 4],
5477 tx_types: &[TxType],
5478) -> Result<usize> {
5479 let max_tx = side.min(64);
5480 let ctx = neighbours.tx_size_ctx(at_mi, max_tx);
5481 match max_tx {
5482 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
5483 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
5484 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
5485 64 => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
5486 _ => {
5487 return Err(Error::unsupported(
5488 "AV1 tile",
5489 "a tx_depth symbol is only coded at 8/16/32/64",
5490 ));
5491 }
5492 }
5493 let tx = max_tx >> depth;
5494 write_luma_tus(
5495 enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false, tx_types,
5496 )?;
5497 neighbours.record_tx(at_mi, side, tx);
5498 Ok(tx)
5499}
5500
5501/// The transform syntax one block of an INTER frame coded with
5502/// `tx_mode == TxMode::Select` carries, in the place spec 5.11.16's
5503/// `read_block_tx_size` reads it -- after the modes and the motion vector,
5504/// before the residual:
5505/// * an inter block that codes a residual walks a var-tx tree; this writer
5506/// keeps it at its own largest transform, so that is one `txfm_split` flag
5507/// of zero, off `txfm_partition_ctx_rect`'s row, publishing the bands per
5508/// unit the way `read_var_tx_size` does.
5509/// * a skipped inter block codes nothing and records its own BLOCK size
5510/// (`set_txfm_ctxs`'s `skip_inter` term).
5511/// * an intra block codes `tx_depth` like a key frame's, but off the
5512/// `TXFM_CONTEXT` bands rather than the deblock grid.
5513///
5514/// Hands back the block's resolved luma transform side.
5515#[allow(clippy::too_many_arguments)]
5516fn write_tx_syntax_inter(
5517 enc: &mut SymbolEncoder,
5518 cdfs: &mut Cdfs,
5519 neighbours: &mut Neighbours,
5520 at_mi: (usize, usize),
5521 side: usize,
5522 is_inter: bool,
5523 skip: bool,
5524 depth: usize,
5525) -> usize {
5526 let max_tx = side.min(64);
5527 let (mi_r, mi_c) = at_mi;
5528 if is_inter {
5529 if !skip {
5530 let ctx = txfm_partition_ctx_rect(
5531 neighbours.above_txfm[mi_c],
5532 neighbours.left_txfm[mi_r],
5533 side,
5534 max_tx,
5535 max_tx,
5536 );
5537 enc.symbol(usize::from(depth != 0), &mut cdfs.txfm_partition[ctx]);
5538 if depth == 0 {
5539 neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx);
5540 return max_tx;
5541 }
5542 // lane-av1tx2 r2: one halving of the var-tx tree. Each child of a
5543 // split root codes its own `txfm_split` (decode.rs
5544 // `read_var_tx_size` only stops symbol-free at `MAX_VARTX_DEPTH`
5545 // or at a 4x4 sub-size), off the bands the children before it
5546 // published -- so the context read and the update interleave per
5547 // unit, exactly as the reader's recursion does.
5548 let tx = max_tx / 2;
5549 for row in (0..max_tx / MI).step_by(tx / MI) {
5550 for col in (0..max_tx / MI).step_by(tx / MI) {
5551 let unit = (mi_r + row, mi_c + col);
5552 // The encoder only picks depth 1 for a block wholly
5553 // inside the frame; the reader skips a unit past the true
5554 // edge, which would leave the residual units unpaired.
5555 debug_assert!(
5556 unit.0 < neighbours.mi_rows && unit.1 < neighbours.mi_cols,
5557 "a split inter transform unit past the frame edge"
5558 );
5559 let ctx = txfm_partition_ctx_rect(
5560 neighbours.above_txfm[unit.1],
5561 neighbours.left_txfm[unit.0],
5562 side,
5563 tx,
5564 tx,
5565 );
5566 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
5567 neighbours.record_txfm(unit, tx, tx, tx);
5568 }
5569 }
5570 return tx;
5571 }
5572 neighbours.record_txfm(at_mi, side, side, side);
5573 return max_tx;
5574 }
5575 let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx);
5576 match max_tx {
5577 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
5578 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
5579 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
5580 _ => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
5581 }
5582 let tx = max_tx >> depth;
5583 neighbours.record_txfm(at_mi, tx, side, side);
5584 tx
5585}
5586
5587/// What a coded transform block leaves behind for the blocks that read it as a
5588/// neighbour.
5589fn neighbour_state(grid: &[i32]) -> Neighbour {
5590 Neighbour {
5591 coded: grid.iter().any(|&l| l != 0),
5592 level: grid.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8,
5593 dc: (grid[0] != 0).then_some(grid[0] < 0),
5594 }
5595}
5596
5597/// Writes the payload of a one-tile key frame in which every superblock is
5598/// split into 32x32 blocks, each carrying the coefficients `blocks` gives it.
5599///
5600/// `blocks` gives one coefficient set per 32x32 block in raster order across
5601/// the frame. This is [`sb_coeff_key_frame_tile`] with every superblock split.
5602///
5603/// # Errors
5604/// As [`sb_coeff_key_frame_tile`], with `blocks` sized for the 32x32 grid.
5605pub fn split_coeff_key_frame_tile(
5606 mi_cols: u32,
5607 mi_rows: u32,
5608 base_q_idx: u8,
5609 blocks: &[BlockCoeffs],
5610) -> Result<Vec<u8>> {
5611 check_blocks(mi_cols, mi_rows)?;
5612 let (cols, rows) = block_grid(mi_cols, mi_rows);
5613 if blocks.len() != (cols * rows) as usize {
5614 return Err(Error::unsupported(
5615 "AV1 tile",
5616 "a coefficient key frame needs one coefficient set per 32x32 block",
5617 ));
5618 }
5619 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
5620 let superblocks: Vec<Superblock> = (0..sb_rows)
5621 .flat_map(|sb_r| (0..sb_cols).map(move |sb_c| (sb_r, sb_c)))
5622 .map(|(sb_r, sb_c)| {
5623 Superblock::Split(
5624 (0..4)
5625 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
5626 .filter(|&(r, c)| r < rows && c < cols)
5627 .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone()))
5628 .collect(),
5629 )
5630 })
5631 .collect();
5632 sb_coeff_key_frame_tile(mi_cols, mi_rows, base_q_idx, &superblocks)
5633}
5634
5635/// Lays one plane's coefficient list out over its transform, rejecting the
5636/// positions and levels the writer does not code.
5637fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
5638 let mut grid = vec![0i32; side * side];
5639 for coeff in coeffs {
5640 if usize::from(coeff.row) >= side || usize::from(coeff.col) >= side {
5641 return Err(Error::unsupported(
5642 "AV1 tile",
5643 "a coefficient sits outside the transform of its plane",
5644 ));
5645 }
5646 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
5647 return Err(Error::unsupported(
5648 "AV1 tile",
5649 format!(
5650 "coefficients are written for levels -{MAX_LEVEL}..={MAX_LEVEL} without zero"
5651 ),
5652 ));
5653 }
5654 let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
5655 if grid[pos] != 0 {
5656 return Err(Error::unsupported(
5657 "AV1 tile",
5658 "two coefficients of one block share a position",
5659 ));
5660 }
5661 grid[pos] = coeff.level;
5662 }
5663 Ok(grid)
5664}
5665
5666/// The default scan of a square transform (spec 8.4.2's `Default_Scan_NxN`),
5667/// as raster positions in the order they are coded.
5668///
5669/// The table is a rule rather than hundreds of pinned numbers: the scan walks
5670/// the anti-diagonals of the transform outwards from the origin, each diagonal
5671/// from its top-right end on odd diagonals and from its bottom-left end on
5672/// even ones.
5673fn default_scan(side: usize) -> Vec<u16> {
5674 let mut scan = Vec::with_capacity(side * side);
5675 for d in 0..(2 * side - 1) {
5676 let lo = d.saturating_sub(side - 1);
5677 let hi = d.min(side - 1);
5678 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5679 if d % 2 == 0 {
5680 scan.extend(diagonal.rev());
5681 } else {
5682 scan.extend(diagonal);
5683 }
5684 }
5685 scan
5686}
5687
5688/// What one 32x32 luma transform block's levels cost, in bits, priced through
5689/// the very CDFs [`write_coeffs`] will write them with -- end-of-block
5690/// position, base levels, base range, signs and the Golomb tail all included.
5691///
5692/// The mode search calls this before the block's neighbours exist, so the two
5693/// neighbour-derived contexts (the block-skip context and the DC sign context)
5694/// are taken as zero. Every other context inside the block is exact, because
5695/// those are read from the block's own levels.
5696///
5697/// The encoder codes 32x32 luma only -- every superblock it emits is split --
5698/// so one table is all the search needs; a second block size would need its
5699/// own entry point rather than a size argument, because the table and the scan
5700/// have to agree.
5701/// What the search paid for every coefficient of `blocks`, in bits: the same
5702/// [`coeff_bits`] price the mode search ranked those blocks by, summed over
5703/// the blocks that were actually kept.
5704///
5705/// The instrument behind `predicted_coeff_bits_track_the_tile_the_writer_wrote`
5706/// (lane-av1rd1): the writer codes these levels against a state that has
5707/// adapted away from the defaults `coeff_bits` prices with, and against real
5708/// neighbour contexts instead of the empty ones, so the sum here and the tile
5709/// the writer produced differ by exactly that drift plus the non-coefficient
5710/// syntax (partition/mode/skip/mv symbols) the sum leaves out.
5711#[cfg(test)]
5712fn dense(coeffs: &[Coeff], side: usize) -> Vec<i32> {
5713 let mut grid = vec![0i32; side * side];
5714 for c in coeffs {
5715 grid[usize::from(c.row) * side + usize::from(c.col)] = c.level;
5716 }
5717 grid
5718}
5719
5720#[cfg(test)]
5721pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8) -> f64 {
5722 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
5723 superblocks
5724 .iter()
5725 .map(|sb| match sb {
5726 // A whole 64x64 codes its luma through `TxbSet::Luma64` (only the
5727 // top-left 32x32 carries coefficients) and each chroma plane at
5728 // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here.
5729 Superblock::Whole(block) if !block.skip => {
5730 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
5731 + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5732 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5733 }
5734 Superblock::Whole(_) => 0.0,
5735 Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx),
5736 })
5737 .sum()
5738}
5739
5740#[cfg(test)]
5741pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
5742 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
5743 fn block_bits(block: &BlockCoeffs, side: usize, q_ctx: usize) -> f64 {
5744 if let Some(leaves) = &block.eight {
5745 return leaves.iter().map(|l| block_bits(l, 8, q_ctx)).sum();
5746 }
5747 if block.skip {
5748 return 0.0;
5749 }
5750 let inter = block.inter.is_some();
5751 let (luma, chroma) = match (side, inter) {
5752 (32, false) => (TxbSet::Luma32, TxbSet::Chroma16),
5753 (32, true) => (TxbSet::Luma32Inter, TxbSet::Chroma16),
5754 (16, false) => (TxbSet::Luma16, TxbSet::Chroma8),
5755 (16, true) => (TxbSet::Luma16Inter, TxbSet::Chroma8),
5756 (_, false) => (TxbSet::Luma8, TxbSet::Chroma4),
5757 (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4),
5758 };
5759 coeff_bits(&dense(&block.luma, side), luma, q_ctx, 0, 0)
5760 + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx, 0, 0)
5761 + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx, 0, 0)
5762 }
5763 blocks
5764 .iter()
5765 .map(|q| {
5766 let side = match q {
5767 // lane-b128: a 128x128 root is SKIP by construction (the
5768 // writer refuses a residual at that size), so it names no
5769 // coefficients on any plane.
5770 Quadrant::Whole128(_) | Quadrant::Rect128(..) | Quadrant::Ab128(..) => {
5771 return 0.0;
5772 }
5773 Quadrant::Whole(_) => 32,
5774 Quadrant::Split(_) => 16,
5775 // lane-tx64: a 64x64 root that codes a residual pays for one
5776 // TX_64X64 luma transform (only the top-left 32x32 carries
5777 // coefficients) and one TX_32X32 per chroma plane -- the same
5778 // three prices `predicted_coeff_bits_sb` takes for a key
5779 // frame's whole superblock, and the same sets the writer's
5780 // `Whole64` arm codes. `block_bits`'s table has no 64 row, so
5781 // it is spelled out here.
5782 Quadrant::Whole64(block) => {
5783 return match block.skip {
5784 true => 0.0,
5785 false => {
5786 // lane-b64b: at `tx_depth = 1` the luma levels are
5787 // the whole 64-sided block, written as four
5788 // TX_32X32 units, so the pricer slices them the
5789 // same way the writer does.
5790 let luma = if block.tx_depth == 1 {
5791 let g = dense(&block.luma, 64);
5792 (0..4)
5793 .map(|tu| {
5794 let (r0, c0) = ((tu / 2) * 32, (tu % 2) * 32);
5795 let unit: Vec<i32> = (0..32)
5796 .flat_map(|row| {
5797 g[(r0 + row) * 64 + c0..][..32].to_vec()
5798 })
5799 .collect();
5800 coeff_bits(&unit, TxbSet::Luma32Inter, q_ctx, 0, 0)
5801 })
5802 .sum::<f64>()
5803 } else {
5804 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
5805 };
5806 luma + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5807 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5808 }
5809 };
5810 }
5811 Quadrant::Covered => return 0.0,
5812 };
5813 q.blocks()
5814 .iter()
5815 .map(|b| block_bits(b, side, q_ctx))
5816 .sum::<f64>()
5817 })
5818 .sum()
5819}
5820
5821#[cfg(test)]
5822pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
5823 coeff_bits(grid, TxbSet::Luma32, 2, 0, 0)
5824}
5825
5826/// What one transform block's levels cost through the CDFs of `set`, in bits.
5827///
5828/// The search runs before the tile is written, so the adapted state the block
5829/// will really be coded against does not exist yet: the price is taken against
5830/// the defaults every tile starts from, at the frame's own coefficient
5831/// q-context (`q_ctx_of(base_q_idx)`, what `Cdfs::new` is given at
5832/// `sb_coeff_*_tile` -- lane-av1rd1: this used to be pinned at 2, so two of
5833/// the four points of the BD ladder were priced against another quantizer's
5834/// tables), and against the contexts a block whose neighbours coded nothing
5835/// reads.
5836///
5837/// lane-av1skipctx CLOSED that row: `skip_ctx`/`sign_ctx` are the caller's
5838/// now, and [`crate::encode::CoefCtxMap`] -- a per-plane, per-4x4-cell map
5839/// committed in coding order and undone with a losing partition trial's
5840/// pixels -- is the per-trial neighbour state the previous lane said the
5841/// search did not have. The census (6 frames of each clip at 640x384, q=100,
5842/// `pricer_error_census_on_clips`) moved:
5843///
5844/// | row | before | after |
5845/// |---|---|---|
5846/// | screen total | +10.3% | +9.5% |
5847/// | screen Chroma8 nz=0 | -73.0% | -1.9% |
5848/// | screen Chroma16 nz=0 | -48% | -23.4% |
5849/// | screen Chroma4 nz=0 | -74% | -6.7% |
5850/// | screen Chroma8 nz=1 / nz=2 | +32.2% / +26.2% | +4.9% / +7.9% |
5851/// | screen Luma4 nz=0 | +464% | +89.5% |
5852/// | film total | +5.3% | +1.5% |
5853///
5854/// What is left in the all-zero rows is table ADAPTATION, not context: the
5855/// price is taken against the frame's starting tables, and a frame whose
5856/// blocks mostly code nothing narrows `txb_skip` far below where it started.
5857/// A whole-block luma transform still reads context 0 -- that is what the
5858/// writer codes (`write_luma_tus`, `n == 1`), not an approximation.
5859/// The default scan of one transform size, built once per size: the search
5860/// prices thirteen modes for every block, and the scan is the same table
5861/// every time.
5862fn scan_of(side: usize) -> &'static Vec<u16> {
5863 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {
5864 [
5865 default_scan(TX4),
5866 default_scan(TX8),
5867 default_scan(TX16),
5868 default_scan(TX32),
5869 ]
5870 });
5871 match side {
5872 TX4 => &SCANS[0],
5873 TX8 => &SCANS[1],
5874 TX16 => &SCANS[2],
5875 _ => &SCANS[3],
5876 }
5877}
5878
5879/// [`scan_of`]'s `TX_CLASS_HORIZ`/`TX_CLASS_VERT` sibling (lane-txw): the
5880/// `Mrow_Scan`/`Mcol_Scan` a `V_DCT`/`H_DCT` unit is coded in, built off the
5881/// DECODER's own table so the two cannot drift, cached per size and class.
5882fn class_scan_of(side: usize, class: crate::decode::TxClass) -> &'static [u16] {
5883 static SCANS: LazyLock<[[Vec<u16>; 2]; 4]> = LazyLock::new(|| {
5884 use crate::decode::{class_scan_table, TxClass};
5885 [TX4, TX8, TX16, TX32].map(|side| {
5886 [
5887 class_scan_table(side, TxClass::Horiz),
5888 class_scan_table(side, TxClass::Vert),
5889 ]
5890 })
5891 });
5892 let size = match side {
5893 TX4 => 0,
5894 TX8 => 1,
5895 TX16 => 2,
5896 _ => 3,
5897 };
5898 let idx = usize::from(class == crate::decode::TxClass::Vert);
5899 &SCANS[size][idx]
5900}
5901
5902/// [`coeff_bits_typed`] at `DCT_DCT`, the only type the test-only pricers
5903/// ([`predicted_coeff_bits`]) model.
5904#[cfg(test)]
5905pub(crate) fn coeff_bits(
5906 grid: &[i32],
5907 set: TxbSet,
5908 q_ctx: usize,
5909 skip_ctx: usize,
5910 sign_ctx: usize,
5911) -> f64 {
5912 coeff_bits_typed(grid, set, q_ctx, skip_ctx, sign_ctx, TxType::DctDct)
5913}
5914
5915/// What levels a named transform type produced cost: the `tx_type`
5916/// symbol is part of what the block spends, so a search comparing types has
5917/// to see each one's own symbol priced (lane-txset).
5918pub(crate) fn coeff_bits_typed(
5919 grid: &[i32],
5920 set: TxbSet,
5921 q_ctx: usize,
5922 // lane-av1skipctx: the two neighbour-derived contexts, mirrored from the
5923 // writer's own (`write_block_planes`/`write_luma_tus`) off the search's
5924 // coding-order-committed map ([`crate::encode::CoefCtxMap`]). `(0, 0)` is
5925 // what every caller passed before the map existed -- exact for a luma
5926 // transform covering its whole block, and the census row that was the
5927 // largest remaining pricer error for every other block.
5928 skip_ctx: usize,
5929 sign_ctx: usize,
5930 tx_type: TxType,
5931) -> f64 {
5932 // `Cdfs::new` builds every table a tile writer adapts -- tens of
5933 // kilobytes -- and this function is called once per priced candidate:
5934 // together with the copy behind it that was 9% of the encoder's profile
5935 // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the
5936 // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per
5937 // q-context per thread beside a pristine one and restore just those from
5938 // it. The state the price is taken against is identical to a fresh
5939 // `Cdfs::new(q_ctx)`, so every price is bit-identical.
5940 // lane-av1txbits: an inter frame's writer does NOT start from the
5941 // defaults -- it starts from the tables the previous frame stored (spec
5942 // 7.20, `start_cdfs` in `encode_inter_frame`) -- so pricing against the
5943 // defaults charged the search for a narrowing the writer no longer pays.
5944 // The census measured that at +31% on the one-coefficient inter blocks
5945 // the search lives on. `arm_pricing_cdfs` puts the frame's own starting
5946 // tables under the price; nothing armed keeps the old default behaviour.
5947 let price = |slot: &mut (Cdfs, Cdfs)| {
5948 let (pristine, scratch) = (&mut slot.0, &mut slot.1);
5949 let src = pristine.txb(set, DC_PRED);
5950 let mut coding = scratch.txb(set, DC_PRED);
5951 coding.txb_skip.copy_from_slice(src.txb_skip);
5952 coding.eob_pt.copy_from_slice(src.eob_pt);
5953 if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) {
5954 dst.copy_from_slice(src);
5955 }
5956 *coding.eob_extra = *src.eob_extra;
5957 *coding.base = *src.base;
5958 *coding.base_eob = *src.base_eob;
5959 *coding.br = *src.br;
5960 *coding.dc_sign = *src.dc_sign;
5961 if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) {
5962 dst.copy_from_slice(src);
5963 }
5964 let scan = scan_of(coding.side);
5965 let mut enc = SymbolEncoder::pricer();
5966 write_coeffs(
5967 &mut enc,
5968 &mut coding,
5969 grid,
5970 scan,
5971 skip_ctx,
5972 sign_ctx,
5973 None,
5974 tx_type,
5975 );
5976 enc.bits()
5977 };
5978 // lane-av1speed2: 60% of the transform units of an inter stream hold no
5979 // coefficient, and for those `write_coeffs` codes ONE symbol -- the
5980 // all-zero flag -- and returns. Restoring the eight tables it might have
5981 // touched (~800 bytes of `copy_from_slice`, the largest `memmove` in the
5982 // encoder's profile) buys nothing there, so price that symbol straight
5983 // off the pristine table on a copy of its own row. Identical bits: the
5984 // scratch's `txb_skip[skip_ctx]` was restored from exactly this row, and
5985 // nothing after the flag runs.
5986 let zero_price = |slot: &mut (Cdfs, Cdfs)| {
5987 let mut row = slot.0.txb(set, DC_PRED).txb_skip[skip_ctx];
5988 let mut enc = SymbolEncoder::pricer();
5989 enc.symbol(1, &mut row);
5990 enc.bits()
5991 };
5992 let all_zero = grid.iter().all(|&level| level == 0);
5993 PRICING_BASE.with_borrow_mut(|base| {
5994 if let Some(slot) = base.as_deref_mut().filter(|s| s.0.q_ctx == q_ctx) {
5995 return if all_zero {
5996 zero_price(slot)
5997 } else {
5998 price(slot)
5999 };
6000 }
6001 PRICING.with_borrow_mut(|slots| {
6002 let slot = slots[q_ctx.min(3)]
6003 .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
6004 if all_zero {
6005 zero_price(slot)
6006 } else {
6007 price(slot)
6008 }
6009 })
6010 })
6011}
6012
6013/// The largest level [`rdoq`] offers a candidate for, and the most prices it
6014/// may spend on one block. `EC_AV1_RDOQ_MAXLEVEL` / `EC_AV1_RDOQ_BUDGET`
6015/// sweep them; see [`rdoq`] for why both exist.
6016const RDOQ_MAX_LEVEL: u32 = 2;
6017const RDOQ_BUDGET: u32 = 24;
6018
6019fn rdoq_max_level() -> u32 {
6020 static ENV: LazyLock<u32> = LazyLock::new(|| {
6021 crate::envflags::var("EC_AV1_RDOQ_MAXLEVEL")
6022 .ok()
6023 .and_then(|v| v.parse().ok())
6024 .unwrap_or(RDOQ_MAX_LEVEL)
6025 });
6026 *ENV
6027}
6028
6029fn rdoq_budget() -> u32 {
6030 static ENV: LazyLock<u32> = LazyLock::new(|| {
6031 crate::envflags::var("EC_AV1_RDOQ_BUDGET")
6032 .ok()
6033 .and_then(|v| v.parse().ok())
6034 .unwrap_or(RDOQ_BUDGET)
6035 });
6036 *ENV
6037}
6038
6039/// Rate-distortion optimised quantisation (lane-rdoq): the pass every
6040/// reference encoder runs after the quantiser and this one did not have.
6041///
6042/// The deadzone quantiser rounds each coefficient on its own, blind to what
6043/// the coded level costs. Every reference decides that per coefficient
6044/// against the entropy coder (libaom `av1_optimize_txb`, rav1e
6045/// `optimize_txb`): a level is lowered toward zero when the bits it gives
6046/// back are worth more than the squared error it adds, which also shortens
6047/// the eob when the tail levels go to zero.
6048///
6049/// Mirroring rav1e's shape without its incremental cost model: the candidate
6050/// set per coefficient is `{level, level - 1, .., 0}` walked one step at a
6051/// time in REVERSE scan order (the tail first, so a dropped tail is retried
6052/// against the shorter eob it leaves), and each candidate is priced by
6053/// re-coding the whole block through [`coeff_bits`] -- the same CDFs, the
6054/// same neighbour contexts and the same writer the search already prices
6055/// with, so no second cost model can drift from the writer (class
6056/// `table-and-reader-move-together`). That costs one `write_coeffs` per
6057/// candidate instead of rav1e's table lookup, which is why this is a preset
6058/// lever (`crate::speed::RDOQ`) and not unconditional.
6059///
6060/// `levels` is the side-strided grid the inverse transform and the writer
6061/// will read, `scaled` the pre-rounding `coeff / q` of each position
6062/// (`crate::transform::forward_and_quantize_scaled`). `lambda` is the rate
6063/// weight in units of ONE SQUARED AC QUANTISER STEP: the search's own
6064/// `sse + lambda * bits` is `step^2 * (sum (scaled - level)^2 + LAMBDA_SCALE
6065/// * bits)` once the pixel-domain error of a level is written through the
6066/// orthonormal transform (`(coeff - level * q) / 8`, `INVERSE_GAIN_RECIPROCAL`),
6067/// so `step^2` divides out of every comparison here and the DC's different
6068/// quantiser is the only per-position weight left.
6069///
6070/// Returns what the block's levels cost after the pass, so the caller prices
6071/// the tile it will actually write and never the pre-RDOQ grid.
6072#[allow(clippy::too_many_arguments)]
6073pub(crate) fn rdoq(
6074 levels: &mut [i32],
6075 scaled: &[f32],
6076 side: usize,
6077 base_q_idx: u8,
6078 set: TxbSet,
6079 skip_ctx: usize,
6080 sign_ctx: usize,
6081 lambda: f64,
6082 tx_type: TxType,
6083) -> f64 {
6084 // A 64-point transform carries its top-left 32x32 alone, and that corner
6085 // is what the writer and the pricer take (`coded_corner`).
6086 let coded = side.min(TX32);
6087 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
6088 let mut dense = if coded == side {
6089 Vec::new()
6090 } else {
6091 vec![0i32; coded * coded]
6092 };
6093 fn price(
6094 levels: &[i32],
6095 dense: &mut [i32],
6096 side: usize,
6097 coded: usize,
6098 set: TxbSet,
6099 q_ctx: usize,
6100 skip_ctx: usize,
6101 sign_ctx: usize,
6102 tx_type: TxType,
6103 ) -> f64 {
6104 if dense.is_empty() {
6105 return coeff_bits_typed(levels, set, q_ctx, skip_ctx, sign_ctx, tx_type);
6106 }
6107 for row in 0..coded {
6108 dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]);
6109 }
6110 coeff_bits_typed(dense, set, q_ctx, skip_ctx, sign_ctx, tx_type)
6111 }
6112 let mut bits = price(
6113 levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type,
6114 );
6115 // The DC has its own quantiser, so its squared error per unit of level is
6116 // `(dc_q / ac_q)^2` of an AC coefficient's.
6117 let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx)));
6118 let ac = f64::from(crate::quant::ac_q(8, i32::from(base_q_idx)));
6119 let dc_weight = (dc / ac) * (dc / ac);
6120 let census = crate::envflags::env_flag!("EC_AV1_RDOQ_CENSUS");
6121 if census {
6122 census_block(levels, scaled, side, coded, bits);
6123 }
6124 // Where the pass may spend its prices. Every candidate here costs a whole
6125 // `write_coeffs`, where rav1e's incremental model costs a table lookup,
6126 // so both bounds exist to keep that affordable -- and both cut where the
6127 // decisions do not pay anyway:
6128 // * a level above [`RDOQ_MAX_LEVEL`] is never a candidate: one step off
6129 // a big level gives back a fraction of a bit for a whole quantiser
6130 // step of squared error. What pays is `1 -> 0` and `2 -> 1`.
6131 // * at most [`RDOQ_BUDGET`] prices per block, spent from the TAIL
6132 // backwards -- the eob end, where dropping a level also shortens the
6133 // eob -- so a fine-quantizer block carrying two hundred coefficients
6134 // cannot cost two hundred re-codings.
6135 let mut budget = rdoq_budget();
6136 let max_level = rdoq_max_level();
6137 // lane-txw: the tail this walks back from is the tail of the unit's OWN
6138 // scan -- a `V_DCT`/`H_DCT` unit is coded in `Mrow_Scan`/`Mcol_Scan`, so
6139 // the 2D zigzag's last positions are not the ones whose removal shortens
6140 // its eob. Every candidate is still priced through the class-aware writer
6141 // ([`write_coeffs`]), so this changes which positions the budget reaches,
6142 // never whether a decision is right.
6143 let class = crate::decode::TxClass::of(tx_type);
6144 let order: &[u16] = if class == crate::decode::TxClass::TwoD {
6145 scan_of(coded)
6146 } else {
6147 class_scan_of(coded, class)
6148 };
6149 for &position in order.iter().rev() {
6150 if budget == 0 {
6151 break;
6152 }
6153 let (row, col) = (usize::from(position) / coded, usize::from(position) % coded);
6154 let i = row * side + col;
6155 if levels[i] == 0 || levels[i].unsigned_abs() > max_level {
6156 continue;
6157 }
6158 let s = f64::from(scaled[i]);
6159 let weight = if i == 0 { dc_weight } else { 1.0 };
6160 while budget > 0 {
6161 let level = levels[i];
6162 let candidate = level - level.signum();
6163 levels[i] = candidate;
6164 budget -= 1;
6165 let after = price(
6166 levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type,
6167 );
6168 let distortion =
6169 weight * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2));
6170 if distortion + lambda * (after - bits) < 0.0 {
6171 bits = after;
6172 if census {
6173 RDOQ_STATS[if candidate == 0 { 4 } else { 5 }].fetch_add(1, Ordering::Relaxed);
6174 }
6175 if candidate == 0 {
6176 break;
6177 }
6178 } else {
6179 levels[i] = level;
6180 break;
6181 }
6182 }
6183 }
6184 if census {
6185 RDOQ_STATS[6].fetch_add((bits * 64.0) as u64, Ordering::Relaxed);
6186 }
6187 bits
6188}
6189
6190/// blocks, coded coefficients, +-1 levels, trailing +-1 levels (a run of them
6191/// at the end of the scan), zeroed coefficients, lowered coefficients, bits
6192/// after the pass * 64, bits before the pass * 64.
6193pub(crate) static RDOQ_STATS: [AtomicU64; 8] = [
6194 AtomicU64::new(0),
6195 AtomicU64::new(0),
6196 AtomicU64::new(0),
6197 AtomicU64::new(0),
6198 AtomicU64::new(0),
6199 AtomicU64::new(0),
6200 AtomicU64::new(0),
6201 AtomicU64::new(0),
6202];
6203
6204/// The pre-pass half of [`RDOQ_STATS`] (`EC_AV1_RDOQ_CENSUS`): what the
6205/// quantiser handed the pass, which is the instrument for how much is at
6206/// stake before any decision is taken.
6207fn census_block(levels: &[i32], _scaled: &[f32], side: usize, coded: usize, bits: f64) {
6208 let scan = scan_of(coded);
6209 let at = |p: u16| levels[usize::from(p) / coded * side + usize::from(p) % coded];
6210 let nonzero = scan.iter().filter(|&&p| at(p) != 0).count();
6211 let ones = scan.iter().filter(|&&p| at(p).abs() == 1).count();
6212 let trailing = scan
6213 .iter()
6214 .rev()
6215 .skip_while(|&&p| at(p) == 0)
6216 .take_while(|&&p| at(p).abs() == 1)
6217 .count();
6218 RDOQ_STATS[0].fetch_add(1, Ordering::Relaxed);
6219 RDOQ_STATS[1].fetch_add(nonzero as u64, Ordering::Relaxed);
6220 RDOQ_STATS[2].fetch_add(ones as u64, Ordering::Relaxed);
6221 RDOQ_STATS[3].fetch_add(trailing as u64, Ordering::Relaxed);
6222 RDOQ_STATS[7].fetch_add((bits * 64.0) as u64, Ordering::Relaxed);
6223}
6224
6225/// Reads and clears [`RDOQ_STATS`].
6226pub fn take_rdoq_stats() -> [u64; 8] {
6227 std::array::from_fn(|i| RDOQ_STATS[i].swap(0, Ordering::Relaxed))
6228}
6229
6230thread_local! {
6231 /// The default tables every price falls back to, one pristine/scratch
6232 /// pair per q-context (see [`coeff_bits`] for why the pair is kept).
6233 static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
6234 const { RefCell::new([None, None, None, None]) };
6235 /// The tables the frame being searched will really be written against,
6236 /// armed per frame by the encoder ([`arm_pricing_cdfs`]) on every thread
6237 /// that prices -- the search jobs re-arm their own worker, exactly like
6238 /// the other tile thread-locals.
6239 static PRICING_BASE: RefCell<Option<Box<(Cdfs, Cdfs)>>> = const { RefCell::new(None) };
6240}
6241
6242/// Arms the tables [`coeff_bits`] prices against on this thread: the state
6243/// this frame's tile writer starts from. `None` goes back to the per-q-context
6244/// defaults (a key frame, whose writer really does start there), and so does
6245/// any frame the screen detector said yes to (`screen`).
6246///
6247/// ON by default for non-screen frames since lane-av1price2;
6248/// `EC_AV1_PRICE_FRAME_CDFS` selects 0 = never (the pre-lane behaviour),
6249/// 1 = always, unset/2 = the screen-gated default.
6250///
6251/// Pricing against the frame's REAL starting tables is the more accurate
6252/// estimate by measurement -- the pricer census
6253/// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every
6254/// transform block, and the one- and two-coefficient inter blocks the search
6255/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy only
6256/// converts into ladder bytes on camera content. Measured on ONE build
6257/// (lane-av1price2, mode 0 vs mode 2), BD-rate vs libaom / vs rav1e:
6258///
6259/// | clip | 640x384 base | 640x384 gated | native base | native gated |
6260/// |---|---|---|---|---|
6261/// | film 1080p | +79.9 / +37.3 | +78.8 / +36.1 | +18.7 / +1.4 | +18.0 / +0.7 |
6262/// | film 2160p | +94.6 / +55.7 | +95.1 / +56.4 | +48.1 / +19.8 | +47.3 / +19.2 |
6263/// | screen | +54.5 / +1.1 | +54.5 / +1.1 | +59.4 / -10.0 | +59.4 / -10.0 |
6264///
6265/// The screen rows are not merely close, they are byte-identical (the ladders
6266/// print 8832/13507/18772/24754 and 39312/52829/70719/92134 in both modes):
6267/// the gate is per frame and the detector fires on 48 of 48 screen frames, so
6268/// no screen frame is ever armed with anything but the defaults. At native
6269/// resolution -- the resolution his library is in -- both films come down
6270/// against both references and the screen capture is flat, which is this
6271/// lane's keep rule. At the downscaled 640x384 gate the 2160p film goes the
6272/// other way (+0.5/+0.7) while the 1080p one comes down further (-1.1/-1.2);
6273/// the downscale is the same recipe that exaggerated the frame pyramid's loss
6274/// sixfold, so the native table decides and the 640x384 2160p regression is
6275/// recorded here rather than argued away.
6276///
6277/// Why the screen capture needs the gate at all is in the census
6278/// (`pricer_error_census_on_clips`, 6 frames of each clip at 640x384, q=100).
6279/// Real tables take the film clip's total pricer error from +7.8% to +5.3%
6280/// and flatten its inter classes outright (Luma8Inter/Luma16Inter/Luma32Inter
6281/// 1-coefficient rows from +11.7%/+17.4%/+24.9% to -0.3%/-5.5%/+8.8%). On the
6282/// screen capture the total only moves +12.8% -> +10.3%, because the classes
6283/// that dominate a screen frame are not the ones the tables fix: its chroma
6284/// stays over-priced (Chroma8 nz=1 +32.2% -> +31.8%, nz=2 +26.2% -> +26.2%,
6285/// unmoved) and its all-zero blocks stay hugely UNDER-priced (Chroma8 nz=0
6286/// -73.0% -> -73.0%, Luma4 nz=0 +464% -> +467% -- both a pricer that assumes
6287/// `skip_ctx` 0, not a table set). So on screen the change makes the inter
6288/// luma price accurate while leaving the bigger chroma and all-zero errors
6289/// exactly where they were, which SKEWS the search's tradeoffs between them
6290/// instead of correcting them -- and the bytes get worse. The fix for that
6291/// row was the neighbour skip context, not another table set, and
6292/// lane-av1skipctx landed it (see [`coeff_bits`]): with the real contexts
6293/// under every price the screen capture comes down +59.4 -> +58.3 vs libaom
6294/// at native, still with every one of its frames armed with the defaults.
6295pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {
6296 static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
6297 let mode = *MODE.get_or_init(
6298 || match std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() {
6299 Ok("0") => 0,
6300 Ok("1") => 1,
6301 _ => 2,
6302 },
6303 );
6304 let on = match mode {
6305 0 => false,
6306 1 => true,
6307 _ => !screen,
6308 };
6309 PRICING_HITS[usize::from(on && base.is_some())].fetch_add(1, Ordering::Relaxed);
6310 PRICING_BASE.with_borrow_mut(|slot| {
6311 *slot = base
6312 .filter(|_| on)
6313 .map(|c| Box::new((c.clone(), c.clone())));
6314 });
6315}
6316
6317/// How many times a frame's search was armed with the DEFAULT tables and how
6318/// many with the frame's REAL starting tables ([`arm_pricing_cdfs`]), so a
6319/// gate can print which side of the screen gate every frame landed on. Counts
6320/// arming calls, not frames: a multi-tile frame arms one worker per tile.
6321pub(crate) static PRICING_HITS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)];
6322
6323/// Reads and clears [`PRICING_HITS`]: (default-table armings, real-table
6324/// armings).
6325#[cfg(test)]
6326pub(crate) fn take_pricing_hits() -> (usize, usize) {
6327 (
6328 PRICING_HITS[0].swap(0, Ordering::Relaxed),
6329 PRICING_HITS[1].swap(0, Ordering::Relaxed),
6330 )
6331}
6332
6333/// The pricer census (`pricer_census_on`): for every transform block the tile
6334/// writer really codes, the bits it spent against the bits [`coeff_bits`]
6335/// prices those very levels at -- the search's rate term measured against the
6336/// rate it is meant to predict. Keyed by (table set, non-zero bucket) so a
6337/// class that is systematically mispriced (all-zero blocks' `txb_skip`, the
6338/// eob of a one-coefficient block, a whole size) shows up on its own row
6339/// rather than inside one average.
6340/// Thread-local, so a census cannot pick up the blocks of another test's
6341/// encode running beside it; a multi-tile, multi-threaded encode would
6342/// therefore only census the tiles this thread wrote, which is every tile of
6343/// the one-tile-one-thread encodes the gates print it from.
6344#[cfg(test)]
6345type CensusRows = BTreeMap<(String, usize), (u64, f64, f64)>;
6346#[cfg(test)]
6347thread_local! {
6348 static CENSUS: RefCell<Option<CensusRows>> = const { RefCell::new(None) };
6349}
6350
6351/// Starts a census on this thread, discarding anything a previous one left.
6352#[cfg(test)]
6353pub(crate) fn pricer_census_on() {
6354 CENSUS.with_borrow_mut(|c| *c = Some(BTreeMap::new()));
6355}
6356
6357/// Stops the census and hands back its rows: (set, non-zero bucket) ->
6358/// (blocks, priced bits, written bits).
6359#[cfg(test)]
6360pub(crate) fn take_pricer_census() -> CensusRows {
6361 CENSUS.with_borrow_mut(|c| c.take()).unwrap_or_default()
6362}
6363
6364/// The label of a non-zero bucket, for the tables the gates print.
6365#[cfg(test)]
6366pub(crate) fn census_bucket_label(bucket: usize) -> &'static str {
6367 ["0", "1", "2", "3-4", "5-8", "9-16", "17+"][bucket]
6368}
6369
6370#[cfg(test)]
6371fn census_record(
6372 set: TxbSet,
6373 q_ctx: usize,
6374 grid: &[i32],
6375 written: f64,
6376 // The writer's own neighbour contexts for this very transform block: the
6377 // census prices the search's estimate the way the search now takes it
6378 // (lane-av1skipctx), so a row's error is the table/adaptation drift that
6379 // is left once the context is right.
6380 skip_ctx: usize,
6381 sign_ctx: usize,
6382) {
6383 if CENSUS.with_borrow(|c| c.is_none()) {
6384 return;
6385 }
6386 let nz = grid.iter().filter(|&&l| l != 0).count();
6387 let bucket = match nz {
6388 0 => 0,
6389 1 => 1,
6390 2 => 2,
6391 3..=4 => 3,
6392 5..=8 => 4,
6393 9..=16 => 5,
6394 _ => 6,
6395 };
6396 let priced = coeff_bits(grid, set, q_ctx, skip_ctx, sign_ctx);
6397 CENSUS.with_borrow_mut(|rows| {
6398 let rows = rows.as_mut().expect("the census is on");
6399 let row = rows.entry((format!("{set:?}"), bucket)).or_default();
6400 row.0 += 1;
6401 row.1 += priced;
6402 row.2 += written;
6403 });
6404}
6405
6406/// What the partition symbol of a block of `side` samples costs, in bits, when
6407/// it says the block is split (or that it is not).
6408///
6409/// The price is taken at context zero — a block whose neighbours are no finer
6410/// than it is — because the search that reads it runs before the tile knows
6411/// what its neighbours will be.
6412pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
6413 // Read-only, and the same tables every call: built once (see
6414 // [`coeff_bits`] for why that matters here).
6415 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
6416 let cdfs = &*CDFS;
6417 let cdf: &[u16] = match side {
6418 // lane-b128: the 128 superblock root's own eight-symbol alphabet.
6419 128 => &cdfs.partition_w128[0],
6420 SB => &cdfs.partition_w64[0],
6421 BLOCK => &cdfs.partition_w32[0],
6422 TX8 => &cdfs.partition_w8[0],
6423 _ => &cdfs.partition_w16[0],
6424 };
6425 let symbol = if split {
6426 PARTITION_SPLIT
6427 } else {
6428 PARTITION_NONE
6429 };
6430 crate::encode::symbol_bits(cdf, symbol)
6431}
6432
6433/// lane-b128hv: [`partition_bits`] for any partition symbol, at the same
6434/// fixed (round-2) tables -- what the 128 root's HORZ/VERT candidate is priced
6435/// with (`PARTITION_HORZ` = 1, `PARTITION_VERT` = 2).
6436pub(crate) fn partition_bits_sym(side: usize, symbol: usize) -> f64 {
6437 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
6438 let cdfs = &*CDFS;
6439 let cdf: &[u16] = match side {
6440 128 => &cdfs.partition_w128[0],
6441 SB => &cdfs.partition_w64[0],
6442 BLOCK => &cdfs.partition_w32[0],
6443 TX8 => &cdfs.partition_w8[0],
6444 _ => &cdfs.partition_w16[0],
6445 };
6446 crate::encode::symbol_bits(cdf, symbol)
6447}
6448
6449/// coeffs() for one plane's transform block of any coefficients the base and
6450/// base-range syntax reach (spec 5.11.39).
6451///
6452/// A 16x16 luma transform codes which transform type it is, because its set
6453/// holds more than one; 32x32 and 64x64 are DCT-only by spec 5.11.40. The
6454/// levels the contexts below are read from are the levels of
6455/// coefficients later in the scan, which a decoder walking the scan backwards
6456/// already has.
6457#[allow(clippy::too_many_arguments)]
6458fn write_coeffs(
6459 enc: &mut SymbolEncoder,
6460 coding: &mut TxbTables,
6461 grid: &[i32],
6462 scan: &[u16],
6463 skip_ctx: usize,
6464 sign_ctx: usize,
6465 plane: Option<usize>,
6466 // Which transform type these levels were produced with (lane-txset).
6467 // Only a luma set whose alphabet holds more than one type codes it;
6468 // chroma never codes a `tx_type` symbol at all.
6469 tx_type: TxType,
6470) {
6471 if let Some(plane) = plane {
6472 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));
6473 }
6474 let side = coding.side;
6475 // lane-txw ROOT CAUSE: this writer used to code every transform unit as
6476 // `TX_CLASS_2D` -- default zigzag scan, the 2D `eob_pt` table and the 2D
6477 // neighbour taps -- while the decoder resolves `V_DCT`/`H_DCT` to
6478 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`decode::TxClass::of`), which read
6479 // their own scan (`class_scan_table`), their own `eob_pt` row
6480 // (`eob_pt_class1`) and their own context offsets. So the first 1-D type
6481 // the search ever offered (the wider `reduced_tx_set == 0` alphabets)
6482 // desynced the tile from its own trial decode. The class is a property of
6483 // the type alone, so it is resolved here, once per unit, exactly as the
6484 // reader does it.
6485 let class = crate::decode::TxClass::of(tx_type);
6486 let scan: &[u16] = if class == crate::decode::TxClass::TwoD {
6487 scan
6488 } else {
6489 class_scan_of(side, class)
6490 };
6491 // The scan-order search reads the grid in scan order, one dependent load
6492 // per position, and an all-zero block makes it walk every one of them --
6493 // which the pricer does for candidate after candidate. A straight-line
6494 // pass settles that case first: it vectorises, and a block that codes
6495 // anything at all almost always codes its DC, so it stops at the first
6496 // element.
6497 let eob = if grid.iter().all(|&level| level == 0) {
6498 0
6499 } else {
6500 scan.iter()
6501 .rposition(|&pos| grid[pos as usize] != 0)
6502 .map_or(0, |i| i + 1)
6503 };
6504 enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]);
6505 if plane.is_some() {
6506 ec_rng_trace(|| {
6507 format!(
6508 "EC_TXBSKIP ctx={skip_ctx} eob0={} tell={} rng={}",
6509 usize::from(eob == 0),
6510 enc.tell(),
6511 enc.rng()
6512 )
6513 });
6514 }
6515 if eob == 0 {
6516 return;
6517 }
6518 // A luma transform whose type set holds more than one type codes which it
6519 // is, right after the all-zero flag (spec 5.11.39). The writer only ever
6520 // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.
6521 if let Some(cdf) = coding.tx_type.as_deref_mut() {
6522 // The symbol comes from the DECODER's own map, keyed by this set's
6523 // alphabet width, so a type this set cannot express is caught here
6524 // rather than desyncing the tile. The search only ever offers types
6525 // the set holds ([`crate::encode::tx_type_candidates`]).
6526 let symbol = crate::decode::tx_type_symbol(cdf.len(), tx_type);
6527 debug_assert!(
6528 symbol.is_some(),
6529 "{tx_type:?} is not in the {}-symbol tx_type set",
6530 cdf.len() - 1
6531 );
6532 enc.symbol(symbol.unwrap_or(TX_TYPE_DCT_DCT_SET2), cdf);
6533 if plane.is_some() {
6534 ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng()));
6535 }
6536 }
6537
6538 write_eob(enc, coding, eob, plane, class);
6539
6540 // lane-av1speed3: `side` is 4, 8, 16 or 32, but it is a runtime value --
6541 // `pos / side` compiles to a real integer division, once per coefficient,
6542 // in the encoder's largest self-time symbol. Same row and column.
6543 debug_assert!(
6544 side.is_power_of_two(),
6545 "the scan splits a position by shifting"
6546 );
6547 let (shift, mask) = (side.trailing_zeros(), side - 1);
6548 for scan_idx in (0..eob).rev() {
6549 let pos = scan[scan_idx] as usize;
6550 let (row, col) = (pos >> shift, pos & mask);
6551 let level = grid[pos].abs();
6552 if scan_idx == eob - 1 {
6553 let ctx = eob_coeff_ctx(scan_idx, side * side);
6554 let sym = (level.min(NUM_BASE_LEVELS + 1) - 1) as usize;
6555 enc.symbol(sym, &mut coding.base_eob[ctx]);
6556 if plane.is_some() {
6557 ec_rng_trace(|| {
6558 format!(
6559 "EC_BASEEOB scan_idx={scan_idx} ctx={ctx} level={} tell={}",
6560 sym + 1,
6561 enc.tell()
6562 )
6563 });
6564 }
6565 } else {
6566 let ctx = base_ctx(grid, side, row, col, class);
6567 let sym = level.min(NUM_BASE_LEVELS + 1) as usize;
6568 enc.symbol(sym, &mut coding.base[ctx]);
6569 if plane.is_some() {
6570 ec_rng_trace(|| {
6571 format!(
6572 "EC_BASE scan_idx={scan_idx} ctx={ctx} level={sym} tell={}",
6573 enc.tell()
6574 )
6575 });
6576 }
6577 }
6578 if level > NUM_BASE_LEVELS {
6579 let ctx = br_ctx(grid, side, row, col, class);
6580 let mut remaining = level - (NUM_BASE_LEVELS + 1);
6581 let mut sent = 0;
6582 while sent < COEFF_BASE_RANGE {
6583 let k = remaining.min(BR_STEP);
6584 enc.symbol(k as usize, &mut coding.br[ctx]);
6585 if plane.is_some() {
6586 ec_rng_trace(|| {
6587 format!(
6588 "EC_BR scan_idx={scan_idx} ctx={ctx} k={k} tell={}",
6589 enc.tell()
6590 )
6591 });
6592 }
6593 if k < BR_STEP {
6594 break;
6595 }
6596 remaining -= k;
6597 sent += BR_STEP;
6598 }
6599 }
6600 }
6601
6602 // The signs come after the levels, in scan order, the DC's from a CDF and
6603 // the rest as raw bits (spec 5.11.39).
6604 for &pos in &scan[..eob] {
6605 let level = grid[pos as usize];
6606 if level == 0 {
6607 continue;
6608 }
6609 if pos == 0 {
6610 enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]);
6611 if plane.is_some() {
6612 ec_rng_trace(|| {
6613 format!(
6614 "EC_DCSIGN ctx={sign_ctx} neg={} tell={}",
6615 usize::from(level < 0),
6616 enc.tell()
6617 )
6618 });
6619 }
6620 } else {
6621 enc.literal(u32::from(level < 0), 1);
6622 }
6623 // A level the base and base-range syntax cannot reach carries the rest
6624 // of itself here, after its own sign (spec 5.11.39).
6625 if level.abs() > MAX_BR_LEVEL {
6626 write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32);
6627 if plane.is_some() {
6628 ec_rng_trace(|| format!("EC_GOLOMB tell={}", enc.tell()));
6629 }
6630 }
6631 }
6632 if let Some(plane) = plane {
6633 ec_rng_trace(|| format!("EC_PLANE plane={plane} eob={eob} tell_after={}", enc.tell()));
6634 }
6635}
6636
6637/// The end-of-block position (spec 5.11.39): which group of scan positions the
6638/// last coded coefficient falls in, then its offset inside that group — the
6639/// offset's top bit from a CDF and the rest as raw bits.
6640fn write_eob(
6641 enc: &mut SymbolEncoder,
6642 coding: &mut TxbTables,
6643 eob: usize,
6644 plane: Option<usize>,
6645 class: crate::decode::TxClass,
6646) {
6647 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
6648 /// end-of-block positions covers, indexed by the group's own number.
6649 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
6650 /// `Eob_Offset_Bits` (spec 5.11.39): how wide each group's offset is.
6651 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
6652
6653 let group = GROUP_START
6654 .iter()
6655 .rposition(|&start| start <= eob)
6656 .expect("the first group starts at zero");
6657 // The groups are numbered from one, and how many of them the transform
6658 // reaches is the size of its own end-of-block alphabet. A
6659 // `TX_CLASS_HORIZ`/`TX_CLASS_VERT` unit adapts a wholly separate row
6660 // (libaom's `eob_multi_ctx`), which is what `decode::read_eob` reads.
6661 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
6662 (crate::decode::TxClass::TwoD, _) | (_, None) => coding.eob_pt,
6663 (_, Some(class1)) => class1,
6664 };
6665 enc.symbol(group - 1, eob_pt);
6666 if let Some(plane) = plane {
6667 ec_rng_trace(|| {
6668 format!(
6669 "EC_EOBPT plane={plane} eob_pt={group} tell={} rng={}",
6670 enc.tell(),
6671 enc.rng()
6672 )
6673 });
6674 }
6675
6676 let bits = OFFSET_BITS[group];
6677 if bits > 0 {
6678 let offset = (eob - GROUP_START[group]) as u32;
6679 let top = (offset >> (bits - 1)) & 1;
6680 enc.symbol(top as usize, &mut coding.eob_extra[group - 3]);
6681 if let Some(plane) = plane {
6682 ec_rng_trace(|| {
6683 format!(
6684 "EC_EOBEXTRA plane={plane} eob_ctx={} top={top} tell={}",
6685 group - 3,
6686 enc.tell()
6687 )
6688 });
6689 }
6690 if bits > 1 {
6691 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
6692 if let Some(plane) = plane {
6693 ec_rng_trace(|| {
6694 format!(
6695 "EC_EOBBITS plane={plane} eob_extra={offset} tell={}",
6696 enc.tell()
6697 )
6698 });
6699 }
6700 }
6701 }
6702}
6703
6704/// Writes the remainder of a level the base and base-range syntax could not
6705/// reach (spec 5.11.40): the value plus one, as its bit length in unary
6706/// followed by the value's own bits, most significant first.
6707pub(crate) fn write_golomb(enc: &mut SymbolEncoder, value: u32) {
6708 let x = value + 1;
6709 let length = 32 - x.leading_zeros();
6710 for _ in 0..length - 1 {
6711 enc.literal(0, 1);
6712 }
6713 for i in (0..length).rev() {
6714 enc.literal((x >> i) & 1, 1);
6715 }
6716}
6717
6718/// The context of the level of the last coded coefficient (spec 8.3.2): how
6719/// far into the scan it sits, in quarters and eighths of the transform.
6720fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
6721 match scan_idx {
6722 0 => 0,
6723 i if i <= area / 8 => 1,
6724 i if i <= area / 4 => 2,
6725 _ => 3,
6726 }
6727}
6728
6729/// The context of a coefficient's level (spec 8.3.2): the magnitudes of the
6730/// five neighbours below and to the right of it — the ones a decoder walking
6731/// the scan backwards already has — plus a term for where in the transform it
6732/// sits. The DC reads context 0 whatever its neighbours carry.
6733fn base_ctx(
6734 grid: &[i32],
6735 side: usize,
6736 row: usize,
6737 col: usize,
6738 class: crate::decode::TxClass,
6739) -> usize {
6740 use crate::decode::TxClass;
6741 // Only `TX_CLASS_2D` short-circuits its DC to context 0
6742 // (`get_nz_map_ctx_from_stats`'s `(tx_class | coeff_idx) == 0`); a 1-D
6743 // class runs the DC through the same neighbour sum as every other
6744 // position.
6745 if class == TxClass::TwoD && row == 0 && col == 0 {
6746 return 0;
6747 }
6748 if class != TxClass::TwoD {
6749 let offsets: [(usize, usize); 5] = if class == TxClass::Horiz {
6750 [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)]
6751 } else {
6752 [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)]
6753 };
6754 let mag: i32 = offsets
6755 .iter()
6756 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
6757 .sum();
6758 let along = if class == TxClass::Horiz { col } else { row };
6759 return (((mag + 1) >> 1).min(4) as usize)
6760 + crate::decode::nz_map_ctx_offset_1d(along.min(31));
6761 }
6762 // A coefficient two rows and two columns clear of the far edges reaches
6763 // all five neighbours, so the gather is five loads off one index with no
6764 // per-neighbour edge test -- which is where this writer spends a third of
6765 // its coefficient loop.
6766 let p = row * side + col;
6767 let mag: i32 = if row + 2 < side && col + 2 < side {
6768 [p + side, p + 1, p + side + 1, p + 2 * side, p + 2]
6769 .iter()
6770 .map(|&i| grid[i].abs().min(3))
6771 .sum()
6772 } else {
6773 [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
6774 .iter()
6775 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
6776 .sum()
6777 };
6778 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
6779 (((mag + 1) >> 1).min(4) as usize) + offset
6780}
6781
6782/// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes
6783/// of its three closest neighbours below and to the right, uncapped, and a
6784/// term separating the DC, the corner of the transform, and the rest.
6785fn br_ctx(
6786 grid: &[i32],
6787 side: usize,
6788 row: usize,
6789 col: usize,
6790 class: crate::decode::TxClass,
6791) -> usize {
6792 use crate::decode::TxClass;
6793 if class != TxClass::TwoD {
6794 let extra = if class == TxClass::Horiz {
6795 neighbour(grid, side, row, col + 2)
6796 } else {
6797 neighbour(grid, side, row + 2, col)
6798 };
6799 let mag = neighbour(grid, side, row + 1, col).abs()
6800 + neighbour(grid, side, row, col + 1).abs()
6801 + extra.abs();
6802 let mag = (((mag + 1) >> 1).min(6)) as usize;
6803 if row == 0 && col == 0 {
6804 return mag;
6805 }
6806 let near_origin = if class == TxClass::Horiz {
6807 col == 0
6808 } else {
6809 row == 0
6810 };
6811 return if near_origin { mag + 7 } else { mag + 14 };
6812 }
6813 let p = row * side + col;
6814 let mag: i32 = if row + 1 < side && col + 1 < side {
6815 grid[p + side].abs() + grid[p + 1].abs() + grid[p + side + 1].abs()
6816 } else {
6817 [(1, 0), (0, 1), (1, 1)]
6818 .iter()
6819 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
6820 .sum()
6821 };
6822 let mag = (((mag + 1) >> 1).min(6)) as usize;
6823 if row == 0 && col == 0 {
6824 mag
6825 } else if row < 2 && col < 2 {
6826 mag + 7
6827 } else {
6828 mag + 14
6829 }
6830}
6831
6832/// A level at a position that may fall off the transform, where the levels a
6833/// context reads are zero.
6834fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
6835 if row >= side || col >= side {
6836 0
6837 } else {
6838 grid[row * side + col]
6839 }
6840}
6841
6842/// Shared by both DC writers: one level per block, none of them zero.
6843fn check_levels(levels: &[i32], blocks: usize) -> Result<()> {
6844 if levels.len() != blocks {
6845 return Err(Error::unsupported(
6846 "AV1 tile",
6847 "a DC-only key frame needs one level per coded block",
6848 ));
6849 }
6850 if levels.iter().any(|&l| l == 0 || l.abs() > MAX_BR_LEVEL) {
6851 return Err(Error::unsupported(
6852 "AV1 tile",
6853 "a DC-only key frame is written for levels -14..=14 without zero; \
6854 wider levels need the Golomb tail",
6855 ));
6856 }
6857 Ok(())
6858}
6859
6860/// coeffs() for a luma transform block whose only coefficient is the DC (spec
6861/// 5.11.39). The block size is the transform size, so the all-zero flag's
6862/// context is 0; an end-of-block of one is token 0 of the position alphabet
6863/// with no extra bits; the transform sizes here are all DCT-only, so no
6864/// transform type is coded; and the DC's own neighbours are zero, so its
6865/// magnitude contexts are 0 throughout.
6866fn write_dc_coeffs(
6867 enc: &mut SymbolEncoder,
6868 dc_level: i32,
6869 sign_ctx: usize,
6870 q_ctx: usize,
6871 txb_skip: &[u16],
6872 base_eob: &[u16],
6873) {
6874 use crate::cdf_state::pick;
6875 let level = dc_level.abs();
6876 let eob_pt = pick(
6877 q_ctx,
6878 cdf::EOB_PT_1024_LUMA_Q0,
6879 cdf::EOB_PT_1024_LUMA_Q1,
6880 cdf::EOB_PT_1024_LUMA,
6881 cdf::EOB_PT_1024_LUMA_Q3,
6882 );
6883 let br = pick(
6884 q_ctx,
6885 cdf::COEFF_BR_LUMA_32_Q0,
6886 cdf::COEFF_BR_LUMA_32_Q1,
6887 cdf::COEFF_BR_LUMA_32,
6888 cdf::COEFF_BR_LUMA_32_Q3,
6889 );
6890 enc.symbol_fixed(0, txb_skip);
6891 enc.symbol_fixed(0, &eob_pt);
6892 enc.symbol_fixed((level.min(NUM_BASE_LEVELS + 1) - 1) as usize, base_eob);
6893 if level > NUM_BASE_LEVELS {
6894 let mut remaining = level - (NUM_BASE_LEVELS + 1);
6895 let mut sent = 0;
6896 while sent < COEFF_BASE_RANGE {
6897 let k = remaining.min(BR_STEP);
6898 enc.symbol_fixed(k as usize, &br[0]);
6899 if k < BR_STEP {
6900 break;
6901 }
6902 remaining -= k;
6903 sent += BR_STEP;
6904 }
6905 }
6906 // The signs come after the levels, DC first (spec 5.11.39).
6907 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
6908}
6909
6910/// One 4x4 unit's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for a
6911/// positive DC, minus one for a negative one, nothing for a unit whose block
6912/// carried no DC or that sits past the frame's true edge (spec
6913/// `av1_set_entropy_contexts`), which is why the vote is gathered per 4x4
6914/// unit and not per coded cell -- a unit past the edge does not vote even
6915/// when the rest of its cell does.
6916fn dc_vote(dc: Option<bool>) -> i32 {
6917 match dc {
6918 None => 0,
6919 Some(true) => -1,
6920 Some(false) => 1,
6921 }
6922}
6923
6924/// Which of the three DC sign contexts a gathered vote picks.
6925fn dc_sign_ctx(vote: i32) -> usize {
6926 match vote.signum() {
6927 0 => 0,
6928 -1 => 1,
6929 _ => 2,
6930 }
6931}
6932
6933/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`,
6934/// `pred_common.c`): both neighbours' intra/inter state when both are
6935/// available, one neighbour's when only one is, and zero at a tile's own
6936/// top-left corner.
6937pub(crate) fn intra_inter_ctx(
6938 has_above: bool,
6939 has_left: bool,
6940 above_inter: bool,
6941 left_inter: bool,
6942) -> usize {
6943 match (has_above, has_left) {
6944 (true, true) => {
6945 let (above_intra, left_intra) = (!above_inter, !left_inter);
6946 if above_intra && left_intra {
6947 3
6948 } else {
6949 usize::from(above_intra || left_intra)
6950 }
6951 }
6952 (true, false) => 2 * usize::from(!above_inter),
6953 (false, true) => 2 * usize::from(!left_inter),
6954 (false, false) => 0,
6955 }
6956}
6957
6958/// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`
6959/// component's own bits start counting from; class zero starts at zero.
6960fn mv_class_base(class: usize) -> i32 {
6961 if class == 0 {
6962 0
6963 } else {
6964 2i32 << (class + 2)
6965 }
6966}
6967
6968/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse
6969/// of `mv_class_base`'s doubling ranges, ported from libaom's
6970/// `av1_get_mv_class` (`mv.h`).
6971fn mv_class_of(z: i32) -> usize {
6972 let mut class = 0;
6973 while class < 10 && mv_class_base(class + 1) <= z {
6974 class += 1;
6975 }
6976 class
6977}
6978
6979/// Writes one motion vector component's non-zero diff (spec 5.11.32
6980/// `read_mv_component`, run backwards): sign, class, then the class's own
6981/// bits, and (lane-hpmv) the eighth-pel bit when the frame armed through
6982/// [`arm_high_precision_mv`] carries `allow_high_precision_mv`. Without that
6983/// flag the eighth-pel bit is inferred as one rather than coded, so only
6984/// diffs whose eighth-pel bit really is one are representable; anything else
6985/// is refused rather than rounded, since rounding would silently code a
6986/// different vector than the caller asked for.
6987///
6988/// # Errors
6989/// Returns an error when `diff` needs eighth-pel precision in a frame coded
6990/// without `allow_high_precision_mv`.
6991fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
6992 debug_assert_ne!(diff, 0);
6993 let hp_frame = high_precision_mv();
6994 let sign = diff < 0;
6995 enc.symbol(usize::from(sign), &mut c.sign);
6996 let mag = diff.unsigned_abs() as i32;
6997 let z = mag - 1;
6998 if !hp_frame && z & 1 == 0 {
6999 return Err(Error::unsupported(
7000 "AV1 tile",
7001 "a motion vector component needs eighth-pel precision, which \
7002 allow_high_precision_mv off does not carry",
7003 ));
7004 }
7005 let class = mv_class_of(z);
7006 enc.symbol(class, &mut c.class);
7007 let local = z - mv_class_base(class);
7008 let hp = (local & 1) as usize;
7009 if class == 0 {
7010 let bit = (local >> 3) & 1;
7011 let fr = (local >> 1) & 3;
7012 enc.symbol(bit as usize, &mut c.class0_bit);
7013 enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]);
7014 // spec 5.11.32: the eighth-pel bit is CODED when the frame allows
7015 // high-precision motion vectors, and inferred as one otherwise ("if
7016 // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
7017 if hp_frame {
7018 enc.symbol(hp, &mut c.class0_hp);
7019 }
7020 } else {
7021 let d = local >> 3;
7022 let fr = (local >> 1) & 3;
7023 for i in 0..class {
7024 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
7025 }
7026 enc.symbol(fr as usize, &mut c.fr);
7027 if hp_frame {
7028 enc.symbol(hp, &mut c.hp);
7029 }
7030 }
7031 if hp_frame {
7032 HP_SYMBOLS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7033 if hp == 0 {
7034 HP_SYMBOLS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7035 }
7036 }
7037 Ok(())
7038}
7039
7040/// Writes a motion vector as a residual against `pred` (spec 5.11.32
7041/// `read_mv`): the joint symbol naming which components differ, then each
7042/// differing component.
7043fn write_mv(
7044 enc: &mut SymbolEncoder,
7045 mv_comp: &mut [MvComponentCdfs; 2],
7046 mv_joint: &mut [u16; 5],
7047 mv: (i32, i32),
7048 pred: (i32, i32),
7049) -> Result<()> {
7050 let diff = (mv.0 - pred.0, mv.1 - pred.1);
7051 let joint = match (diff.0 != 0, diff.1 != 0) {
7052 (false, false) => 0, // MV_JOINT_ZERO
7053 (false, true) => 1, // MV_JOINT_HNZVZ: column only
7054 (true, false) => 2, // MV_JOINT_HZVNZ: row only
7055 (true, true) => 3, // MV_JOINT_HNZVNZ
7056 };
7057 enc.symbol(joint, mv_joint);
7058 if diff.0 != 0 {
7059 write_mv_component(enc, &mut mv_comp[0], diff.0)?;
7060 }
7061 if diff.1 != 0 {
7062 write_mv_component(enc, &mut mv_comp[1], diff.1)?;
7063 }
7064 Ok(())
7065}
7066
7067/// What a block leaves in the neighbour reference bands: its own reference,
7068/// or `-1` when it is intra (decode.rs `Neighbours::above_ref`'s convention).
7069fn block_ref(block: &BlockCoeffs) -> i8 {
7070 block.inter.map_or(-1, |i| i.ref_frame)
7071}
7072
7073/// Writer-side counterpart of decode.rs `read_single_ref` (spec 5.11.25's
7074/// `single_ref_p1`..`p6` tree): codes `ref_frame` bit by bit, each symbol at
7075/// the context its own `single_ref_p*_ctx` derives from the immediate
7076/// above/left neighbours' references -- the same functions the decoder calls,
7077/// with `-1` standing for an intra or unavailable neighbour and no second
7078/// reference (this writer codes no compound block).
7079fn write_single_ref(
7080 enc: &mut SymbolEncoder,
7081 cdfs: &mut Cdfs,
7082 ref_frame: i8,
7083 above_ref: i8,
7084 above_ref1: Option<i8>,
7085 left_ref: i8,
7086 left_ref1: Option<i8>,
7087) {
7088 REF_HITS[(ref_frame.max(1) - 1) as usize % 7]
7089 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7090 use crate::mvstack::{
7091 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
7092 single_ref_p5_ctx, single_ref_p6_ctx, ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME,
7093 GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
7094 };
7095 let above = (above_ref > 0).then_some(above_ref);
7096 let left = (left_ref > 0).then_some(left_ref);
7097 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
7098 // neighbour's references (decode.rs `read_single_ref`'s own
7099 // `above_ref1`/`left_ref1`): dropping the second one reads a different
7100 // context row for every block sitting under a compound neighbour, and so
7101 // decodes a different reference NAME.
7102 let backward = ref_frame >= BWDREF_FRAME;
7103 enc.symbol(
7104 usize::from(backward),
7105 &mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0],
7106 );
7107 if backward {
7108 let is_altref = ref_frame == ALTREF_FRAME;
7109 enc.symbol(
7110 usize::from(is_altref),
7111 &mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1],
7112 );
7113 if !is_altref {
7114 enc.symbol(
7115 usize::from(ref_frame == ALTREF2_FRAME),
7116 &mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5],
7117 );
7118 }
7119 return;
7120 }
7121 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
7122 enc.symbol(
7123 usize::from(far),
7124 &mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2],
7125 );
7126 if far {
7127 enc.symbol(
7128 usize::from(ref_frame == GOLDEN_FRAME),
7129 &mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4],
7130 );
7131 } else {
7132 enc.symbol(
7133 usize::from(ref_frame == LAST2_FRAME),
7134 &mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3],
7135 );
7136 }
7137}
7138
7139/// Per-mode fire counts of [`write_inter_mode`], indexed
7140/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block
7141/// coded (bucket 3 collects any index past 2). Read by the BD gate, which
7142/// is the only thing that proves a newly added mode ever fires
7143/// (gate-blind-to-feature).
7144static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [
7145 std::sync::atomic::AtomicUsize::new(0),
7146 std::sync::atomic::AtomicUsize::new(0),
7147 std::sync::atomic::AtomicUsize::new(0),
7148 std::sync::atomic::AtomicUsize::new(0),
7149];
7150static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [
7151 std::sync::atomic::AtomicUsize::new(0),
7152 std::sync::atomic::AtomicUsize::new(0),
7153 std::sync::atomic::AtomicUsize::new(0),
7154 std::sync::atomic::AtomicUsize::new(0),
7155];
7156
7157/// One counter per reference name (`LAST`..`ALTREF`), for the gate's own
7158/// census of what the encoder actually picks.
7159static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [
7160 std::sync::atomic::AtomicUsize::new(0),
7161 std::sync::atomic::AtomicUsize::new(0),
7162 std::sync::atomic::AtomicUsize::new(0),
7163 std::sync::atomic::AtomicUsize::new(0),
7164 std::sync::atomic::AtomicUsize::new(0),
7165 std::sync::atomic::AtomicUsize::new(0),
7166 std::sync::atomic::AtomicUsize::new(0),
7167];
7168
7169/// Takes and clears the per-reference histogram.
7170#[cfg(test)]
7171pub(crate) fn take_ref_hits() -> [usize; 7] {
7172 std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7173}
7174
7175/// Bumps the two histograms for one coded inter block.
7176/// How many blocks this process wrote whose search-chosen `ref_mv_idx` the
7177/// write-time stack could not carry, so the writer signalled a SMALLER index
7178/// (lane-sb128b). Every one of these used to price its residual against a
7179/// predictor the decoder never derives.
7180static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7181
7182/// Counts one clamped DRL index whose predictor differs from the one the
7183/// search asked for -- the harmful case, and the only one a witness can see.
7184fn note_drl_clamp(target: usize, signalled: usize, entries: usize) {
7185 DRL_CLAMP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7186 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7187 eprintln!("DRL_CLAMP target={target} signalled={signalled} entries={entries}");
7188 }
7189}
7190
7191/// Takes and clears [`DRL_CLAMP_HITS`], for a gate's own before/after delta.
7192#[cfg(test)]
7193pub(crate) fn take_drl_clamp_hits() -> usize {
7194 DRL_CLAMP_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
7195}
7196
7197fn note_inter_mode(mode: usize, drl: usize) {
7198 INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7199 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7200}
7201
7202/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW).
7203#[cfg(test)]
7204pub(crate) fn take_inter_mode_hits() -> [usize; 4] {
7205 [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7206}
7207
7208/// Takes and clears the DRL-index histogram (0, 1, 2, 3+).
7209#[cfg(test)]
7210pub(crate) fn take_drl_hits() -> [usize; 4] {
7211 [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7212}
7213
7214/// Writes the DRL index of one block: the loop the decoder runs (spec
7215/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
7216/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
7217/// stop, at most two bits. `drl_ctx[idx]` is the context between
7218/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses
7219/// between. Returns the index the symbols actually SIGNAL, which is `target`
7220/// clamped by the stack (`min(target, start + 2, entries.len() - 1)`): the
7221/// decoder derives its predictor from THAT index, so every caller must take
7222/// its own base MV from the returned value and not from `target` (lane-sb128b:
7223/// a search-chosen `ref_mv_idx` of 2 against a two-entry write-time stack
7224/// signalled index 1 and priced the residual against `pred_mv`, and the
7225/// decoder's MV silently drifted a whole frame before the drl symbols
7226/// desynced).
7227/// The DRL index [`write_drl_idx`]'s walk can actually SIGNAL against a stack
7228/// of `entries` candidates: at most two `drl_mode` symbols past `start`, and
7229/// each one needs a further entry to advance into (spec 5.11.24's
7230/// `for (idx = 0; idx < 2; idx++) if (NumMvFound > idx + 1)`).
7231///
7232/// A search that offers an index this clamps prices its residual against a
7233/// predictor the decoder never derives (lane-sb128b's silent MV drift); the
7234/// pricer's own offer set is enumerated against this rule by
7235/// `crate::encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`.
7236pub(crate) fn signalled_drl_idx(entries: usize, start: usize, target: usize) -> usize {
7237 target
7238 .min(start + 2)
7239 .min(entries.saturating_sub(1))
7240 .max(start)
7241}
7242
7243fn write_drl_idx(
7244 enc: &mut SymbolEncoder,
7245 cdfs: &mut Cdfs,
7246 stack: &crate::mvstack::MvStack,
7247 start: usize,
7248 target: usize,
7249) -> usize {
7250 debug_assert_eq!(
7251 signalled_drl_idx(stack.entries.len(), start, target),
7252 {
7253 let mut i = start;
7254 while i < start + 2 && stack.entries.len() > i + 1 && i < target {
7255 i += 1;
7256 }
7257 i
7258 },
7259 "the drl clamp rule and the writer's own walk disagree",
7260 );
7261 let mut idx = start;
7262 while idx < start + 2 && stack.entries.len() > idx + 1 {
7263 let advance = idx < target;
7264 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]);
7265 if !advance {
7266 return idx;
7267 }
7268 idx += 1;
7269 }
7270 idx
7271}
7272
7273/// Writer-side counterpart of the decoder's single-reference
7274/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s
7275/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV
7276/// residual against the DRL-selected predictor. Returns the motion vector
7277/// the decoder will derive for the block (what the MI grid must record) and
7278/// whether it is `NEWMV`.
7279///
7280/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global
7281/// motion parameters at all, so every `gm_get_motion_vector` the decoder
7282/// runs is the identity model's zero vector; a lane that starts writing
7283/// real `gm_params` has to feed the same vector in here.
7284///
7285/// # Errors
7286/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision.
7287fn write_inter_mode(
7288 enc: &mut SymbolEncoder,
7289 cdfs: &mut Cdfs,
7290 info: InterInfo,
7291 stack: &crate::mvstack::MvStack,
7292) -> Result<((i32, i32), bool)> {
7293 let idx = usize::from(info.ref_mv_idx);
7294 if info.mode.compound_index().is_some() {
7295 return Err(Error::unsupported(
7296 "AV1 tile",
7297 "a compound mode is written by `write_compound_block`, not here",
7298 ));
7299 }
7300 match info.mode {
7301 InterMode::NewMv => {
7302 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
7303 let signalled = write_drl_idx(enc, cdfs, stack, 0, idx);
7304 let base = stack.entries.get(signalled).map_or(stack.pred_mv, |e| e.mv);
7305 if signalled != idx && base != stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv) {
7306 note_drl_clamp(idx, signalled, stack.entries.len());
7307 }
7308 let idx = signalled;
7309 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?;
7310 note_inter_mode(3, idx);
7311 Ok((info.mv, true))
7312 }
7313 InterMode::GlobalMv => {
7314 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7315 enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV
7316 note_inter_mode(2, 0);
7317 Ok(((0, 0), false))
7318 }
7319 InterMode::NearestMv => {
7320 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7321 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
7322 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
7323 note_inter_mode(0, 0);
7324 Ok((stack.nearest_mv, false))
7325 }
7326 InterMode::NearMv => {
7327 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7328 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
7329 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV
7330 // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24).
7331 let idx = idx.max(1);
7332 let signalled = write_drl_idx(enc, cdfs, stack, 1, idx);
7333 let mv = stack.entries.get(signalled).map_or(stack.near_mv, |e| e.mv);
7334 if signalled != idx && mv != stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) {
7335 note_drl_clamp(idx, signalled, stack.entries.len());
7336 }
7337 let idx = signalled;
7338 note_inter_mode(1, idx);
7339 Ok((mv, false))
7340 }
7341 _ => unreachable!("compound modes are refused above"),
7342 }
7343}
7344
7345/// Writes the payload of a one-tile inter frame built from `blocks`, one
7346/// 32x32 block per entry in raster order across the frame — every superblock
7347/// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
7348/// codes a key frame, because a mixed-size partition tree buys this writer's
7349/// gate nothing a flat grid does not already prove: the CDF state, the
7350/// neighbour contexts and the single-reference/MV-stack machinery below are
7351/// exactly as size-sensitive whether the tree recurses or not, and recursing
7352/// it would be undirected scaffolding — see `sb_coeff_key_frame_tile` for
7353/// where that tree already lives, ready to graft this block's mode reads
7354/// onto once a real partition search needs it.
7355///
7356/// A block whose [`BlockCoeffs::inter`] is `Some` is coded inter: `skip`,
7357/// then `is_inter`, then a single-reference chain that always names `LAST`
7358/// (spec 5.11.25 `single_ref_p1`/`p3`/`p4`, this crate's only reference so
7359/// far), then the two-mode `read_inter_mode` chain (spec 5.11.24) and, for
7360/// [`InterMode::NewMv`], a DRL index (always zero) and a coded motion vector
7361/// residual. A block whose `inter` is `None` codes intra, through the
7362/// *inter*-frame intra path (spec 5.11.16's `intra_frame_mode_info` is the
7363/// key frame writers' path; this is `inter_frame_mode_info`'s intra branch):
7364/// `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour context, since
7365/// an inter frame's intra blocks do not read their neighbours' modes.
7366///
7367/// # Errors
7368/// Returns an error when the frame is not a whole number of 64x64
7369/// superblocks, when `blocks` does not carry exactly one entry per 32x32
7370/// block, when an intra block names a mode a key frame does not code, when a
7371/// coefficient sits outside its transform or is one the writer cannot code,
7372/// when a `NEWMV` block's motion vector needs eighth-pel precision.
7373pub fn sb_coeff_inter_frame_tile(
7374 mi_cols: u32,
7375 mi_rows: u32,
7376 base_q_idx: u8,
7377 blocks: &[Quadrant],
7378) -> Result<Vec<u8>> {
7379 sb_coeff_inter_frame_tile_tx(mi_cols, mi_rows, base_q_idx, blocks, false)
7380}
7381
7382/// [`sb_coeff_inter_frame_tile`] for a frame header carrying
7383/// `tx_mode == TxMode::Select`: every block then codes the transform syntax
7384/// [`write_tx_syntax_inter`] writes -- one `txfm_split` flag on an inter
7385/// block that carries a residual, a `tx_depth` symbol on an intra one -- and
7386/// an intra block whose depth is nonzero codes its luma as several transform
7387/// units. With `tx_select` false this writes exactly the stream it always did.
7388///
7389/// # Errors
7390/// As [`sb_coeff_inter_frame_tile`].
7391pub fn sb_coeff_inter_frame_tile_tx(
7392 mi_cols: u32,
7393 mi_rows: u32,
7394 base_q_idx: u8,
7395 blocks: &[Quadrant],
7396 tx_select: bool,
7397) -> Result<Vec<u8>> {
7398 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
7399 sb_coeff_inter_frame_tile_cdfs(
7400 mi_cols,
7401 mi_rows,
7402 base_q_idx,
7403 blocks,
7404 tx_select,
7405 &mut cdfs,
7406 TileRect::whole(mi_cols, mi_rows),
7407 &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
7408 )
7409}
7410
7411/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
7412/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`].
7413///
7414/// # Errors
7415/// As [`sb_coeff_inter_frame_tile_tx`].
7416pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
7417 mi_cols: u32,
7418 mi_rows: u32,
7419 _base_q_idx: u8,
7420 blocks: &[Quadrant],
7421 tx_select: bool,
7422 cdfs: &mut Cdfs,
7423 // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
7424 tile: TileRect,
7425 // The frame's MV grid, carried across the frame's tiles by the caller
7426 // (see the comment at `set_tile_bounds` below).
7427 grid: &mut MiGrid,
7428) -> Result<Vec<u8>> {
7429 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
7430 let _cdef_idx = CdefIdxGuard;
7431 check_blocks(mi_cols, mi_rows)?;
7432 // `block_grid`'s ceiling, not a plain division: a true frame size that is
7433 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has
7434 // one more block/superblock whose own origin is inside the true frame,
7435 // same as `sb_coeff_key_frame_tile`.
7436 let (cols, rows) = block_grid(mi_cols, mi_rows);
7437 if blocks.len() != (cols * rows) as usize {
7438 return Err(Error::unsupported(
7439 "AV1 tile",
7440 "an inter frame needs one entry per 32x32 block inside the true frame",
7441 ));
7442 }
7443 let coded: Vec<&BlockCoeffs> = blocks.iter().flat_map(Quadrant::blocks).collect();
7444 if let Some(bad) = coded
7445 .into_iter()
7446 .find(|b| b.inter.is_none() && usize::from(b.mode) >= INTRA_MODES)
7447 {
7448 return Err(Error::unsupported(
7449 "AV1 tile",
7450 format!(
7451 "intra mode {} is not one of the thirteen this writer codes",
7452 bad.mode
7453 ),
7454 ));
7455 }
7456
7457 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only
7458 /// size this writer's inter branch codes.
7459 const SIZE_GROUP_32: usize = 3;
7460
7461 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
7462 let mut neighbours = Neighbours::new(
7463 cols as usize * 2,
7464 rows as usize * 2,
7465 mi_cols as usize,
7466 mi_rows as usize,
7467 );
7468 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
7469 // The MV grid spans the FRAME and carries every tile written before this
7470 // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
7471 // keeps one grid for the whole frame and narrows its read window per
7472 // tile): the tile bounds below are what stops a candidate scan reaching
7473 // across the boundary, and a grid that was merely empty out there would
7474 // not read the same as the decoder's wherever a scan reads the array
7475 // without asking `MiGrid::get` first.
7476 let mut grid = &mut *grid;
7477 grid.set_tile_bounds(
7478 tile.mi_row0 as usize,
7479 tile.mi_col0 as usize,
7480 tile.mi_row1 as usize,
7481 tile.mi_col1 as usize,
7482 );
7483 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
7484 let mut cdfs = cdfs;
7485 let mut enc = SymbolEncoder::new();
7486 // An `is_inter` block's 32x32 luma transform reads a different
7487 // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see
7488 // `TxbSet::Luma32Inter`'s doc comment); chroma's transform type is
7489 // derived from luma's, not coded, so it never differs between the two.
7490 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
7491 let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16];
7492 // A 64x64 root's planes (lane-tx64): TX_64X64 luma -- DCT-only at this
7493 // size for an inter block too (spec `av1_get_ext_tx_set_type` returns
7494 // `TX_SET_DCTONLY` for `tx_size_sqr_up == TX_64X64`), so `Luma64` carries
7495 // no `tx_type` symbol and there is no `Luma64Inter` to write -- and one
7496 // TX_32X32 per chroma plane.
7497 let sb64_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
7498 let scan32 = default_scan(TX32);
7499 let scan16 = default_scan(TX16);
7500 let scan8 = default_scan(TX8);
7501 let scan4 = default_scan(TX4);
7502 // The same four tables again as one array, which is what the per-unit
7503 // luma writer indexes by transform side.
7504 let all_scans = [scan32.clone(), scan16.clone(), scan8.clone(), scan4.clone()];
7505 let zero_grids = [
7506 vec![0i32; TX32 * TX32],
7507 vec![0i32; TX16 * TX16],
7508 vec![0i32; TX16 * TX16],
7509 ];
7510
7511 let sb128 = sb128_armed();
7512 // lane-b128: set at a root whose own `PARTITION_NONE` 128x128 block was
7513 // just written, so the root's remaining 64x64 cells code nothing.
7514 let mut sb128_none = false;
7515 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
7516 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
7517 // and partition symbol first; at a 64 one this is plain raster and every
7518 // cell is its own superblock, i.e. byte-identical to the loop before.
7519 for (sb_r, sb_c, row_start, sb_start) in sb_write_order(
7520 tile.sb_row0,
7521 tile.sb_row1.min(sb_rows),
7522 tile.sb_col0,
7523 tile.sb_col1.min(sb_cols),
7524 sb128,
7525 ) {
7526 if row_start {
7527 neighbours.start_row();
7528 }
7529 if sb_start {
7530 sb128_none = false;
7531 }
7532 // lane-b128: the remaining three 64x64 cells of a root the search
7533 // left WHOLE carry no syntax at all -- the same skip the decoder's
7534 // own `sb128_none` runs.
7535 if sb128_none {
7536 continue;
7537 }
7538 if sb128 && sb_start {
7539 // The 128x128 block a `PARTITION_NONE` root carries, held by the
7540 // top-left 32x32 entry of the root's sixteen.
7541 let root_entry = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols)
7542 .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize]);
7543 let root_block = root_entry.and_then(|q| match q {
7544 Quadrant::Whole128(block) => Some(block),
7545 _ => None,
7546 });
7547 // lane-b128hv: the two rectangular halves a HORZ/VERT root carries.
7548 let root_rect = root_entry.and_then(|q| match q {
7549 Quadrant::Rect128(horz, halves) => Some((*horz, halves)),
7550 _ => None,
7551 });
7552 // lane-ab128: the three pieces an AB-shape root carries, and the
7553 // partition symbol it is coded under.
7554 let root_ab = root_entry.and_then(|q| match q {
7555 Quadrant::Ab128(symbol, pieces) => Some((*symbol as usize, pieces)),
7556 _ => None,
7557 });
7558 write_sb128_root(
7559 &mut enc,
7560 &mut cdfs,
7561 &neighbours,
7562 sb_r,
7563 sb_c,
7564 mi_cols,
7565 mi_rows,
7566 match (root_block.is_some(), root_rect, root_ab) {
7567 (true, ..) => PARTITION_NONE,
7568 (_, Some((true, _)), _) => PARTITION_HORZ,
7569 (_, Some((false, _)), _) => PARTITION_VERT,
7570 (_, _, Some((symbol, _))) => symbol,
7571 _ => PARTITION_SPLIT,
7572 },
7573 );
7574 if let Some(block) = root_block {
7575 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
7576 write_inter_block_128(
7577 &mut enc,
7578 &mut cdfs,
7579 &mut neighbours,
7580 &mut grid,
7581 at128,
7582 block,
7583 mi_cols,
7584 mi_rows,
7585 tx_select,
7586 )?;
7587 sb128_none = true;
7588 continue;
7589 }
7590 if let Some((horz, halves)) = root_rect {
7591 // libaom `decode_partition` at BLOCK_128X128: `subsize` at
7592 // (mi_row, mi_col) and a second one at + hbs (16 mi) along the
7593 // cut axis, the second only when it is inside the frame -- the
7594 // search only offers a root wholly inside, so both are.
7595 let base_mi = (
7596 (sb_r & !1) as usize * SB_MI as usize,
7597 (sb_c & !1) as usize * SB_MI as usize,
7598 );
7599 let (w, h) = if horz { (128usize, 64usize) } else { (64, 128) };
7600 for (i, half) in halves.iter().enumerate() {
7601 let at_mi = if horz {
7602 (base_mi.0 + i * 16, base_mi.1)
7603 } else {
7604 (base_mi.0, base_mi.1 + i * 16)
7605 };
7606 write_inter_block_128_rect(
7607 &mut enc,
7608 &mut cdfs,
7609 &mut neighbours,
7610 &mut grid,
7611 at_mi,
7612 (w, h),
7613 half,
7614 mi_cols,
7615 mi_rows,
7616 tx_select,
7617 )?;
7618 }
7619 sb128_none = true;
7620 continue;
7621 }
7622 if let Some((symbol, pieces)) = root_ab {
7623 // libaom `decode_partition` at BLOCK_128X128, AB arm: two
7624 // 64x64 blocks and one 128x64 / 64x128 half, in the order
7625 // decode.rs' `sb128_ab` reads them
7626 // ([`crate::encode::ab128_pieces`]). An AB shape only comes
7627 // from the full alphabet symbol (both halves in frame), so
7628 // there is no edge break to mirror -- the search offers one
7629 // only at a root wholly inside.
7630 let base_mi = (
7631 (sb_r & !1) as usize * SB_MI as usize,
7632 (sb_c & !1) as usize * SB_MI as usize,
7633 );
7634 for (((mi_r, mi_c), (w, h)), piece) in crate::encode::ab128_pieces(symbol, base_mi)
7635 .iter()
7636 .zip(pieces)
7637 {
7638 write_inter_block_128_rect(
7639 &mut enc,
7640 &mut cdfs,
7641 &mut neighbours,
7642 &mut grid,
7643 (*mi_r, *mi_c),
7644 (*w, *h),
7645 piece,
7646 mi_cols,
7647 mi_rows,
7648 tx_select,
7649 )?;
7650 }
7651 SB128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7652 sb128_none = true;
7653 continue;
7654 }
7655 }
7656 {
7657 if !sb128 {
7658 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W);
7659 }
7660 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
7661 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
7662 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
7663 // whose bottom or right half falls outside the true frame cannot
7664 // be left whole, so the only question there is which of the three
7665 // partition symbols the split takes — same three-way signaling as
7666 // `sb_coeff_key_frame_tile`'s superblock level.
7667 let (has_cols, has_rows) = (
7668 sb_c * SB_MI + SB_MI / 2 < mi_cols,
7669 sb_r * SB_MI + SB_MI / 2 < mi_rows,
7670 );
7671 // lane-b64: a superblock the search left WHOLE — one 64x64 block
7672 // at `PARTITION_NONE`, carried by its top-left quadrant's entry
7673 // ([`Quadrant::Whole64`]). Single-reference; skipped, or with a
7674 // real residual through `TxbSet::Luma64` + two `Chroma32`
7675 // (lane-tx64).
7676 let sb64 = ((sb_r * 2) < rows && (sb_c * 2) < cols)
7677 .then(|| &blocks[((sb_r * 2) * cols + sb_c * 2) as usize])
7678 .and_then(|q| match q {
7679 Quadrant::Whole64(block) => Some(block),
7680 _ => None,
7681 });
7682 if let Some(block) = sb64 {
7683 if !has_cols || !has_rows {
7684 return Err(Error::unsupported(
7685 "AV1 tile",
7686 "a superblock that is half outside the true frame cannot be left whole",
7687 ));
7688 }
7689 let info = block.inter.ok_or_else(|| {
7690 Error::unsupported("AV1 tile", "a 64x64 root block is coded inter")
7691 })?;
7692 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[sb_ctx]);
7693 let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
7694 let has_above = neighbours.has_above(mi_r);
7695 let has_left = neighbours.has_left(mi_c);
7696 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
7697 + usize::from(neighbours.left_skip[mi_r]);
7698 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
7699 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
7700 write_delta_q(
7701 &mut enc,
7702 &mut cdfs,
7703 (mi_r, mi_c),
7704 !sb128_armed(),
7705 block.skip,
7706 );
7707 let ii_ctx = intra_inter_ctx(
7708 has_above,
7709 has_left,
7710 neighbours.above_inter[mi_c],
7711 neighbours.left_inter[mi_r],
7712 );
7713 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
7714 write_comp_mode(
7715 &mut enc,
7716 &mut cdfs,
7717 &neighbours,
7718 (mi_r, mi_c),
7719 (has_above, has_left),
7720 info.ref1.is_some(),
7721 );
7722 // lane-b64b: a COMPOUND 64x64 root takes the same mode chain
7723 // every other compound block does, at this superblock's own
7724 // 16x16-mi window.
7725 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
7726 write_compound_block(
7727 &mut enc,
7728 &mut cdfs,
7729 &neighbours,
7730 &grid,
7731 (mi_r, mi_c),
7732 (SB_MI as usize, SB_MI as usize),
7733 (has_above, has_left),
7734 info,
7735 (mi_cols as usize, mi_rows as usize),
7736 )?
7737 } else {
7738 write_single_ref(
7739 &mut enc,
7740 &mut cdfs,
7741 info.ref_frame,
7742 neighbours.above_ref[mi_c],
7743 neighbours.above_ref1[mi_c],
7744 neighbours.left_ref[mi_r],
7745 neighbours.left_ref1[mi_r],
7746 );
7747 let stack = find_mv_stack(
7748 &grid,
7749 mi_r,
7750 mi_c,
7751 SB_MI as usize,
7752 SB_MI as usize,
7753 info.ref_frame,
7754 mi_cols as usize,
7755 mi_rows as usize,
7756 );
7757 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
7758 if crate::msac::symtrace::dir().is_some() {
7759 crate::msac::symtrace::note(&format!(
7760 " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
7761 info.mode, info.ref_mv_idx, info.mv
7762 ));
7763 }
7764 (mv, (0, 0), is_new_mv)
7765 };
7766 for dr in 0..SB_MI as usize {
7767 for dc in 0..SB_MI as usize {
7768 grid.set(
7769 mi_r + dr,
7770 mi_c + dc,
7771 MiInfo {
7772 is_inter: true,
7773 ref_frame: info.ref_frame,
7774 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7775 mv1: mv16(mv1),
7776 mv: mv16(mv),
7777 is_new_mv,
7778 size: SB_MI as u8,
7779 size_h: SB_MI as u8,
7780 is_global_mv0: false,
7781 is_global_mv1: false,
7782 },
7783 );
7784 }
7785 }
7786 if info.ref1.is_none() {
7787 // libaom's `motion_mode_allowed` fails on a compound
7788 // block, so the decoder reads no symbol for one.
7789 write_motion_mode(
7790 &mut enc,
7791 &mut cdfs,
7792 &grid,
7793 (mi_r, mi_c),
7794 (SB_MI as usize, SB_MI as usize),
7795 (SB, SB),
7796 (mi_cols as usize, mi_rows as usize),
7797 info.ref_frame,
7798 block.motion_mode,
7799 )?;
7800 }
7801 if tx_select {
7802 // A skipped inter block writes no `txfm_split` at all --
7803 // that call only publishes the max transform size the
7804 // reader infers for it; an unskipped one writes the
7805 // `txfm_split` flag: 0 when the root's luma is one whole
7806 // TX_64X64, 1 when it is the four TX_32X32 units
7807 // lane-b64b's var-tx arm chose.
7808 write_tx_syntax_inter(
7809 &mut enc,
7810 &mut cdfs,
7811 &mut neighbours,
7812 (mi_r, mi_c),
7813 SB,
7814 true,
7815 block.skip,
7816 usize::from(block.tx_depth),
7817 );
7818 }
7819 if block.skip {
7820 neighbours.record(sb_at, SB, 0, &zero_grids);
7821 } else {
7822 // lane-tx64: the 64x64 root's real residual. Luma is one
7823 // TX_64X64 whose coded quarter is a 32x32 level grid
7824 // (`TxbSet::Luma64`, `TX32`'s own scan -- the same pair
7825 // `sb_coeff_key_frame_tile`'s `Superblock::Whole` writes),
7826 // chroma one whole TX_32X32 per plane, and `split` is
7827 // false because the luma transform covers the block.
7828 // lane-b64b: at `txfm_split = 1` the luma levels arrive in
7829 // 64x64 block coordinates and are written as the four
7830 // TX_32X32 units `write_luma_tus` slices out, each
7831 // publishing its own coefficient context before the next
7832 // one reads it; chroma is one TX_32X32 per plane either
7833 // way.
7834 let split = block.tx_depth == 1;
7835 let grids = [
7836 level_grid(&block.luma, if split { SB } else { TX32 })?,
7837 level_grid(&block.u, TX32)?,
7838 level_grid(&block.v, TX32)?,
7839 ];
7840 if split {
7841 write_luma_tus(
7842 &mut enc,
7843 &mut cdfs,
7844 &mut neighbours,
7845 (mi_r, mi_c),
7846 SB,
7847 TX32,
7848 &grids[0],
7849 0,
7850 &all_scans,
7851 true,
7852 &block.luma_tx_types,
7853 )?;
7854 }
7855 write_block_planes(
7856 &mut enc,
7857 &mut cdfs,
7858 &sb64_planes,
7859 &grids,
7860 &[&scan32, &scan32, &scan32],
7861 &neighbours.around(sb_at, SB),
7862 0,
7863 split,
7864 block_tx_type(block),
7865 true,
7866 );
7867 neighbours.record_planes(sb_at, SB, 0, &grids, !split);
7868 }
7869 neighbours.record_inter(sb_at, SB, block.skip, true, block_ref(block));
7870 record_block_compound(&mut neighbours, (mi_r, mi_c), SB, block);
7871 continue;
7872 }
7873 match (has_cols, has_rows) {
7874 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]),
7875 (true, false) => {
7876 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
7877 }
7878 (false, true) => {
7879 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
7880 }
7881 (false, false) => {}
7882 }
7883
7884 for quadrant in 0..4 {
7885 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
7886 // Only a quadrant whose own mi origin is inside the true
7887 // frame is coded at all (spec `decode_partition`'s
7888 // `r >= MiRows || c >= MiCols` early return), same filter as
7889 // `sb_coeff_key_frame_tile`'s `quadrant_positions`.
7890 if r32 >= rows || c32 >= cols {
7891 continue;
7892 }
7893 let site = &blocks[(r32 * cols + c32) as usize];
7894 let at = (r32 as usize * 2, c32 as usize * 2);
7895 let ctx32 = neighbours.partition_ctx(at, BLOCK);
7896 // spec `decode_partition`'s hasRows/hasCols recomputed at this
7897 // quadrant's own half: a whole 32x32 block cannot be left
7898 // whole once its own half straddles the true edge, mirroring
7899 // `sb_coeff_key_frame_tile`'s "cannot be left whole" refusal.
7900 let (has_cols32, has_rows32) = (
7901 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
7902 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
7903 );
7904 let block = match site {
7905 // Already coded by the `Whole64` above -- but only inside
7906 // a superblock that really carried one.
7907 Quadrant::Whole64(_)
7908 | Quadrant::Whole128(_)
7909 | Quadrant::Rect128(..)
7910 | Quadrant::Ab128(..)
7911 | Quadrant::Covered => {
7912 return Err(Error::unsupported(
7913 "AV1 tile",
7914 "a `Whole64`/`Covered` quadrant needs its superblock's \
7915 top-left entry to be the `Whole64`",
7916 ));
7917 }
7918 Quadrant::Whole(block) => {
7919 if !has_cols32 || !has_rows32 {
7920 return Err(Error::unsupported(
7921 "AV1 tile",
7922 "a 32x32 block that is half outside the true frame \
7923 cannot be left whole",
7924 ));
7925 }
7926 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]);
7927 block
7928 }
7929 Quadrant::Split(sub_blocks) => {
7930 // Same filter as `sb_coeff_key_frame_tile`'s
7931 // `sub_positions`: only the 16x16 leaves whose own mi
7932 // origin is inside the true frame are coded.
7933 let sub_positions: Vec<(usize, usize)> = (0..4)
7934 .map(|i| (r32 as usize * 2 + i / 2, c32 as usize * 2 + i % 2))
7935 .filter(|&(sr, sc)| {
7936 (sr as u32) * SUB_MI < mi_rows && (sc as u32) * SUB_MI < mi_cols
7937 })
7938 .collect();
7939 if sub_blocks.len() != sub_positions.len() {
7940 return Err(Error::unsupported(
7941 "AV1 tile",
7942 "a split 32x32 inter-frame block needs one 16x16 entry \
7943 per sub-block inside the true frame",
7944 ));
7945 }
7946 // Same three-way spec signaling as the superblock
7947 // level above, recomputed at this quadrant's own half.
7948 match (has_cols32, has_rows32) {
7949 (true, true) => {
7950 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx32]);
7951 }
7952 (true, false) => {
7953 enc.symbol_fixed(
7954 1,
7955 &gather(&cdfs.partition_w32[ctx32], VERT_ALIKE),
7956 );
7957 }
7958 (false, true) => {
7959 enc.symbol_fixed(
7960 1,
7961 &gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE),
7962 );
7963 }
7964 (false, false) => {}
7965 }
7966 for (leaf, (sr, sc)) in sub_blocks.iter().zip(sub_positions) {
7967 // A 16x16 leaf whose own half straddles the true
7968 // frame edge splits into the 8x8 leaves that are
7969 // inside it (lane-av1inter8), same split the key
7970 // frame search takes at this geometry -- on both
7971 // axes too, where `decode_partition` infers the
7972 // split and reads no symbol at all
7973 // (lane-av1rect).
7974 let (has_cols16, has_rows16) = (
7975 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
7976 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
7977 );
7978 let at16 = (sr, sc);
7979 if has_cols16 && has_rows16 {
7980 let ctx16 = neighbours.partition_ctx(at16, SUB);
7981 // A 16x16 leaf wholly inside the frame that
7982 // carries `eight` split itself further, on
7983 // cost rather than on geometry (lane-av1rd2):
7984 // spec PARTITION_SPLIT at BLOCK_16X16, then
7985 // the same four 8x8 leaves the straddling
7986 // branch below writes -- all four inside, so
7987 // the partition symbol is a real one rather
7988 // than the edge's gathered flag.
7989 if let Some(leaves) = &leaf.eight {
7990 if leaves.len() != 4 {
7991 return Err(Error::unsupported(
7992 "AV1 tile",
7993 "a 16x16 inter-frame block inside the frame that splits needs all four 8x8 leaves",
7994 ));
7995 }
7996 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w16[ctx16]);
7997 let (mi_row0, mi_col0) =
7998 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
7999 for (i, leaf8) in leaves.iter().enumerate() {
8000 let leaf_mi = (
8001 (mi_row0 + (i as u32 / 2) * 2) as usize,
8002 (mi_col0 + (i as u32 % 2) * 2) as usize,
8003 );
8004 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
8005 enc.symbol(
8006 PARTITION_NONE,
8007 &mut cdfs.partition_w8[leaf_ctx],
8008 );
8009 let (skip, is_inter) = write_inter_frame_leaf8(
8010 &mut enc,
8011 &mut cdfs,
8012 &mut neighbours,
8013 &mut grid,
8014 mi_cols,
8015 mi_rows,
8016 leaf8,
8017 leaf_mi,
8018 &scan8,
8019 &scan4,
8020 tx_select,
8021 &all_scans,
8022 )?;
8023 let _ = (skip, is_inter);
8024 }
8025 continue;
8026 }
8027 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]);
8028 write_inter_frame_leaf(
8029 &mut enc,
8030 &mut cdfs,
8031 &mut neighbours,
8032 &mut grid,
8033 mi_cols,
8034 mi_rows,
8035 leaf,
8036 at16,
8037 &scan16,
8038 &scan8,
8039 tx_select,
8040 &all_scans,
8041 )?;
8042 } else {
8043 let ctx16 = neighbours.partition_ctx(at16, SUB);
8044 match (has_cols16, has_rows16) {
8045 (true, false) => enc.symbol_fixed(
8046 1,
8047 &gather(&cdfs.partition_w16[ctx16], VERT_ALIKE),
8048 ),
8049 (false, true) => enc.symbol_fixed(
8050 1,
8051 &gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE),
8052 ),
8053 // Both halves outside: SPLIT is inferred.
8054 _ => {}
8055 }
8056 let leaves = leaf.eight.as_ref().ok_or_else(|| {
8057 Error::unsupported(
8058 "AV1 tile",
8059 "a 16x16 inter-frame block the true frame edge cuts \
8060 through needs its `eight` leaves populated",
8061 )
8062 })?;
8063 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
8064 let leaf_positions: Vec<(u32, u32)> = (0..4)
8065 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
8066 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
8067 .collect();
8068 if leaves.len() != leaf_positions.len() {
8069 return Err(Error::unsupported(
8070 "AV1 tile",
8071 "a straddling 16x16 inter-frame block needs one \
8072 `eight` entry per 8x8 leaf inside the true frame",
8073 ));
8074 }
8075 for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) {
8076 let leaf_mi = (mr as usize, mc as usize);
8077 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
8078 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w8[leaf_ctx]);
8079 let (skip, is_inter) = write_inter_frame_leaf8(
8080 &mut enc,
8081 &mut cdfs,
8082 &mut neighbours,
8083 &mut grid,
8084 mi_cols,
8085 mi_rows,
8086 leaf8,
8087 leaf_mi,
8088 &scan8,
8089 &scan4,
8090 tx_select,
8091 &all_scans,
8092 )?;
8093 let _ = (skip, is_inter);
8094 }
8095 // Same write-back-once-from-the-last-leaf rule
8096 // as the key frame search's `write_leaf8`
8097 // caller (r15): the SUB-grid skip/inter arrays
8098 // are otherwise left stale for the next
8099 // 16x16 slot.
8100 }
8101 }
8102 continue;
8103 }
8104 };
8105
8106 let (r, c) = at;
8107 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8108 let has_above = neighbours.has_above(mi_r);
8109 let has_left = neighbours.has_left(mi_c);
8110 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
8111 + usize::from(neighbours.left_skip[mi_r]);
8112 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
8113 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
8114 write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), false, block.skip);
8115
8116 let is_inter = block.inter.is_some();
8117 let (above_inter, left_inter) =
8118 (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
8119 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8120 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
8121
8122 let mode_for_tx;
8123 if let Some(info) = block.inter {
8124 write_comp_mode(
8125 &mut enc,
8126 &mut cdfs,
8127 &neighbours,
8128 (mi_r, mi_c),
8129 (has_above, has_left),
8130 info.ref1.is_some(),
8131 );
8132 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
8133 if info.ref1.is_some() {
8134 let (mv, mv1, is_new_mv) = write_compound_block(
8135 &mut enc,
8136 &mut cdfs,
8137 &neighbours,
8138 &grid,
8139 (mi_row, mi_col),
8140 (8, 8),
8141 (has_above, has_left),
8142 info,
8143 (mi_cols as usize, mi_rows as usize),
8144 )?;
8145 for dr in 0..8 {
8146 for dc in 0..8 {
8147 grid.set(
8148 mi_row + dr,
8149 mi_col + dc,
8150 MiInfo {
8151 is_inter: true,
8152 ref_frame: info.ref_frame,
8153 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8154 mv1: mv16(mv1),
8155 mv: mv16(mv),
8156 is_new_mv,
8157 size: 8,
8158 size_h: 8,
8159 is_global_mv0: false,
8160 is_global_mv1: false,
8161 },
8162 );
8163 }
8164 }
8165 mode_for_tx = 0;
8166 } else {
8167 write_single_ref(
8168 &mut enc,
8169 &mut cdfs,
8170 info.ref_frame,
8171 neighbours.above_ref[mi_c],
8172 neighbours.above_ref1[mi_c],
8173 neighbours.left_ref[mi_r],
8174 neighbours.left_ref1[mi_r],
8175 );
8176
8177 let stack = find_mv_stack(
8178 &grid,
8179 mi_row,
8180 mi_col,
8181 8,
8182 8,
8183 info.ref_frame,
8184 mi_cols as usize,
8185 mi_rows as usize,
8186 );
8187
8188 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
8189 if crate::msac::symtrace::dir().is_some() {
8190 crate::msac::symtrace::note(&format!(
8191 " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
8192 info.mode, info.ref_mv_idx, info.mv
8193 ));
8194 }
8195 grid.set(
8196 mi_row,
8197 mi_col,
8198 MiInfo {
8199 is_inter: true,
8200 ref_frame: info.ref_frame,
8201 ref_frame1: NO_REF1,
8202 mv1: (0, 0),
8203 mv: mv16(mv),
8204 is_new_mv,
8205 size: 8,
8206 size_h: 8,
8207 is_global_mv0: false,
8208 is_global_mv1: false,
8209 },
8210 );
8211 for dr in 0..8 {
8212 for dc in 0..8 {
8213 if dr == 0 && dc == 0 {
8214 continue;
8215 }
8216 grid.set(
8217 mi_row + dr,
8218 mi_col + dc,
8219 MiInfo {
8220 is_inter: true,
8221 ref_frame: info.ref_frame,
8222 ref_frame1: NO_REF1,
8223 mv1: (0, 0),
8224 mv: mv16(mv),
8225 is_new_mv,
8226 size: 8,
8227 size_h: 8,
8228 is_global_mv0: false,
8229 is_global_mv1: false,
8230 },
8231 );
8232 }
8233 }
8234 write_motion_mode(
8235 &mut enc,
8236 &mut cdfs,
8237 &grid,
8238 (mi_row, mi_col),
8239 (8, 8),
8240 (BLOCK, BLOCK),
8241 (mi_cols as usize, mi_rows as usize),
8242 info.ref_frame,
8243 block.motion_mode,
8244 )?;
8245 mode_for_tx = 0;
8246 }
8247 } else {
8248 let mode = usize::from(block.mode);
8249 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
8250 if (V_PRED..=D67_PRED).contains(&mode) {
8251 enc.symbol(
8252 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8253 &mut cdfs.angle_delta[mode - V_PRED],
8254 );
8255 }
8256 let uv_mode = usize::from(block.uv_mode);
8257 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8258 if uv_mode == UV_CFL_PRED {
8259 write_cfl_alphas(&mut enc, &mut cdfs, block.cfl_alphas.expect("cfl"));
8260 }
8261 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8262 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8263 }
8264 mode_for_tx = tx_row(mode, block.filter_intra);
8265 // Intra: no vote, but still a coded cell -- mvstack's
8266 // extended-scan coverage must see it (module doc).
8267 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
8268 write_palette_syntax(
8269 &mut enc,
8270 &mut cdfs,
8271 &mut neighbours,
8272 block.palette.as_ref(),
8273 block.palette_uv.as_ref(),
8274 block.filter_intra,
8275 mode,
8276 uv_mode,
8277 (mi_row, mi_col),
8278 BLOCK,
8279 );
8280 for dr in 0..8 {
8281 for dc in 0..8 {
8282 grid.set(
8283 mi_row + dr,
8284 mi_col + dc,
8285 MiInfo {
8286 is_inter: false,
8287 ref_frame: -1,
8288 ref_frame1: NO_REF1,
8289 mv1: (0, 0),
8290 mv: (0, 0),
8291 is_new_mv: false,
8292 size: 8,
8293 size_h: 8,
8294 is_global_mv0: false,
8295 is_global_mv1: false,
8296 },
8297 );
8298 }
8299 }
8300 }
8301
8302 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
8303 let tx = if tx_select {
8304 write_tx_syntax_inter(
8305 &mut enc,
8306 &mut cdfs,
8307 &mut neighbours,
8308 at_mi,
8309 BLOCK,
8310 is_inter,
8311 block.skip,
8312 usize::from(block.tx_depth),
8313 )
8314 } else {
8315 BLOCK
8316 };
8317 let split = tx < BLOCK;
8318 if block.skip {
8319 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
8320 } else {
8321 let grids = [
8322 level_grid(&block.luma, TX32)?,
8323 level_grid(&block.u, TX16)?,
8324 level_grid(&block.v, TX16)?,
8325 ];
8326 if split {
8327 write_luma_tus(
8328 &mut enc,
8329 &mut cdfs,
8330 &mut neighbours,
8331 at_mi,
8332 BLOCK,
8333 tx,
8334 &grids[0],
8335 mode_for_tx,
8336 &all_scans,
8337 is_inter,
8338 &block.luma_tx_types,
8339 )?;
8340 }
8341 write_block_planes(
8342 &mut enc,
8343 &mut cdfs,
8344 if is_inter {
8345 &inter_planes
8346 } else {
8347 &intra_planes
8348 },
8349 &grids,
8350 &[&scan32, &scan16, &scan16],
8351 &neighbours.around(at, BLOCK),
8352 mode_for_tx,
8353 split,
8354 block_tx_type(block),
8355 is_inter,
8356 );
8357 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
8358 }
8359 neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));
8360 record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block);
8361 }
8362 }
8363 }
8364 Ok(enc.finish())
8365}
8366
8367/// Writes one 16x16 leaf a straddling 32x32 quadrant's [`Quadrant::Split`]
8368/// splits into: intra (spec `inter_frame_mode_info`'s intra branch, the only
8369/// one this writer used to code here) or real inter (`is_inter` coded
8370/// `true`), `NEARESTMV` only -- `NEWMV` at this size is this function's
8371/// caller's to never build (`Quadrant::Split`'s `BlockCoeffs.inter`) -- same
8372/// `single_ref`/mv-stack/DRL symbol chain as the whole-32x32 branch above,
8373/// just at this leaf's own 4x4-mi window (`bw4`/`bh4` of 4, not 8) and coded
8374/// through [`TxbSet::Luma16Inter`] rather than [`TxbSet::Luma32Inter`]. Its
8375/// own `PARTITION_NONE` symbol is already written, same contract as
8376/// [`write_block`].
8377#[allow(clippy::too_many_arguments)]
8378fn write_inter_frame_leaf(
8379 enc: &mut SymbolEncoder,
8380 cdfs: &mut Cdfs,
8381 neighbours: &mut Neighbours,
8382 grid: &mut MiGrid,
8383 mi_cols: u32,
8384 mi_rows: u32,
8385 block: &BlockCoeffs,
8386 at: (usize, usize),
8387 scan16: &Vec<u16>,
8388 scan8: &Vec<u16>,
8389 tx_select: bool,
8390 all_scans: &[Vec<u16>; 4],
8391) -> Result<()> {
8392 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
8393 return Err(Error::unsupported(
8394 "AV1 tile",
8395 format!(
8396 "intra mode {} is not one of the thirteen this writer codes",
8397 block.mode
8398 ),
8399 ));
8400 }
8401 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
8402 /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size.
8403 const SIZE_GROUP_16: usize = 2;
8404
8405 let (r, c) = at;
8406 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8407 let skip_ctx =
8408 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
8409 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
8410 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
8411 write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
8412
8413 let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c));
8414 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
8415 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8416 let is_inter = block.inter.is_some();
8417 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
8418
8419 let mode_for_tx;
8420 if let Some(info) = block.inter {
8421 write_comp_mode(
8422 enc,
8423 cdfs,
8424 neighbours,
8425 (mi_r, mi_c),
8426 (has_above, has_left),
8427 info.ref1.is_some(),
8428 );
8429 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8430 if info.ref1.is_some() {
8431 let n = SUB_MI as usize;
8432 let (mv, mv1, is_new_mv) = write_compound_block(
8433 enc,
8434 cdfs,
8435 neighbours,
8436 grid,
8437 (mi_row, mi_col),
8438 (n, n),
8439 (has_above, has_left),
8440 info,
8441 (mi_cols as usize, mi_rows as usize),
8442 )?;
8443 for dr in 0..n {
8444 for dc in 0..n {
8445 grid.set(
8446 mi_row + dr,
8447 mi_col + dc,
8448 MiInfo {
8449 is_inter: true,
8450 ref_frame: info.ref_frame,
8451 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8452 mv1: mv16(mv1),
8453 mv: mv16(mv),
8454 is_new_mv,
8455 size: n as u8,
8456 size_h: n as u8,
8457 is_global_mv0: false,
8458 is_global_mv1: false,
8459 },
8460 );
8461 }
8462 }
8463 mode_for_tx = 0;
8464 } else {
8465 write_single_ref(
8466 enc,
8467 cdfs,
8468 info.ref_frame,
8469 neighbours.above_ref[mi_c],
8470 neighbours.above_ref1[mi_c],
8471 neighbours.left_ref[mi_r],
8472 neighbours.left_ref1[mi_r],
8473 );
8474
8475 let stack = find_mv_stack(
8476 grid,
8477 mi_row,
8478 mi_col,
8479 SUB_MI as usize,
8480 SUB_MI as usize,
8481 info.ref_frame,
8482 mi_cols as usize,
8483 mi_rows as usize,
8484 );
8485
8486 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
8487 for dr in 0..SUB_MI as usize {
8488 for dc in 0..SUB_MI as usize {
8489 grid.set(
8490 mi_row + dr,
8491 mi_col + dc,
8492 MiInfo {
8493 is_inter: true,
8494 ref_frame: info.ref_frame,
8495 ref_frame1: NO_REF1,
8496 mv1: (0, 0),
8497 mv: mv16(mv),
8498 is_new_mv,
8499 size: SUB_MI as usize as u8,
8500 size_h: SUB_MI as usize as u8,
8501 is_global_mv0: false,
8502 is_global_mv1: false,
8503 },
8504 );
8505 }
8506 }
8507 write_motion_mode(
8508 enc,
8509 cdfs,
8510 grid,
8511 (mi_row, mi_col),
8512 (SUB_MI as usize, SUB_MI as usize),
8513 (SUB, SUB),
8514 (mi_cols as usize, mi_rows as usize),
8515 info.ref_frame,
8516 block.motion_mode,
8517 )?;
8518 mode_for_tx = 0;
8519 }
8520 } else {
8521 let mode = usize::from(block.mode);
8522 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);
8523 if (V_PRED..=D67_PRED).contains(&mode) {
8524 enc.symbol(
8525 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8526 &mut cdfs.angle_delta[mode - V_PRED],
8527 );
8528 }
8529 let uv_mode = usize::from(block.uv_mode);
8530 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8531 if uv_mode == UV_CFL_PRED {
8532 write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
8533 }
8534 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8535 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8536 }
8537 mode_for_tx = tx_row(mode, block.filter_intra);
8538 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
8539 // coverage must see it (module doc).
8540 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8541 write_palette_syntax(
8542 enc,
8543 cdfs,
8544 neighbours,
8545 block.palette.as_ref(),
8546 block.palette_uv.as_ref(),
8547 block.filter_intra,
8548 mode,
8549 uv_mode,
8550 (mi_row, mi_col),
8551 SUB,
8552 );
8553 for dr in 0..SUB_MI as usize {
8554 for dc in 0..SUB_MI as usize {
8555 grid.set(
8556 mi_row + dr,
8557 mi_col + dc,
8558 MiInfo {
8559 is_inter: false,
8560 ref_frame: -1,
8561 ref_frame1: NO_REF1,
8562 mv1: (0, 0),
8563 mv: (0, 0),
8564 is_new_mv: false,
8565 size: SUB_MI as usize as u8,
8566 size_h: SUB_MI as usize as u8,
8567 is_global_mv0: false,
8568 is_global_mv1: false,
8569 },
8570 );
8571 }
8572 }
8573 }
8574
8575 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
8576 let tx = if tx_select {
8577 write_tx_syntax_inter(
8578 enc,
8579 cdfs,
8580 neighbours,
8581 at_mi,
8582 SUB,
8583 is_inter,
8584 block.skip,
8585 usize::from(block.tx_depth),
8586 )
8587 } else {
8588 SUB
8589 };
8590 let split = tx < SUB;
8591 if block.skip {
8592 let zero_grids = [
8593 vec![0i32; TX16 * TX16],
8594 vec![0i32; TX8 * TX8],
8595 vec![0i32; TX8 * TX8],
8596 ];
8597 neighbours.record(at, SUB, mode_for_tx, &zero_grids);
8598 } else {
8599 let grids = [
8600 level_grid(&block.luma, TX16)?,
8601 level_grid(&block.u, TX8)?,
8602 level_grid(&block.v, TX8)?,
8603 ];
8604 if split {
8605 write_luma_tus(
8606 enc,
8607 cdfs,
8608 neighbours,
8609 at_mi,
8610 SUB,
8611 tx,
8612 &grids[0],
8613 mode_for_tx,
8614 all_scans,
8615 is_inter,
8616 &block.luma_tx_types,
8617 )?;
8618 }
8619 write_block_planes(
8620 enc,
8621 cdfs,
8622 if is_inter {
8623 &[TxbSet::Luma16Inter, TxbSet::Chroma8, TxbSet::Chroma8]
8624 } else {
8625 &[TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8]
8626 },
8627 &grids,
8628 &[scan16, scan8, scan8],
8629 &neighbours.around(at, SUB),
8630 mode_for_tx,
8631 split,
8632 block_tx_type(block),
8633 is_inter,
8634 );
8635 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
8636 }
8637 neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block));
8638 record_block_compound(neighbours, (mi_r, mi_c), SUB, block);
8639 Ok(())
8640}
8641
8642/// Writes one 8x8 leaf of a straddling 16x16 inter-frame block
8643/// (lane-av1inter8): its own skip flag, intra/inter choice and (when inter)
8644/// `NEARESTMV`/`NEWMV` chain, or (when intra) `Y_MODE`, then its own luma and
8645/// two chroma transform blocks -- coded exactly like
8646/// [`write_inter_frame_leaf`] but through [`TxbSet::Luma8Inter`]/
8647/// [`TxbSet::Chroma4`] and at this leaf's own 2x2-mi mv-stack window, reading
8648/// its skip/intra-inter context from the *enclosing* 16x16 slot's
8649/// [`Neighbours`] arrays (`outer_at`, in [`SUB`]-grid units) unless
8650/// `prev_leaf` names this straddling block's own first leaf as the true
8651/// mi-adjacent neighbour -- the same override [`write_leaf8`] applies to its
8652/// mode context, needed for the same reason: `Neighbours`' above/left arrays
8653/// only resolve to [`SUB`] granularity, too coarse for the second leaf of a
8654/// straddling 16x16 to see the first. `Y_MODE`'s own context (`Size_Group`)
8655/// is not neighbour-dependent, unlike the key frame path's `kf_y_mode`, so no
8656/// override is needed there. Hands back this leaf's own skip flag and
8657/// intra/inter choice, which is what the next leaf (or the caller's final
8658/// write-back, mirroring `write_leaf8`'s caller) reads.
8659#[allow(clippy::too_many_arguments)]
8660fn write_inter_frame_leaf8(
8661 enc: &mut SymbolEncoder,
8662 cdfs: &mut Cdfs,
8663 neighbours: &mut Neighbours,
8664 grid: &mut MiGrid,
8665 mi_cols: u32,
8666 mi_rows: u32,
8667 block: &BlockCoeffs,
8668 leaf_mi: (usize, usize),
8669 scan8: &Vec<u16>,
8670 scan4: &Vec<u16>,
8671 tx_select: bool,
8672 all_scans: &[Vec<u16>; 4],
8673) -> Result<(bool, bool)> {
8674 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
8675 return Err(Error::unsupported(
8676 "AV1 tile",
8677 format!(
8678 "intra mode {} is not one of the thirteen this writer codes",
8679 block.mode
8680 ),
8681 ));
8682 }
8683 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
8684 /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size.
8685 const SIZE_GROUP_8: usize = 1;
8686
8687 // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's:
8688 // under a real PARTITION_SPLIT all four leaves are coded, so the
8689 // bottom-left leaf's true above neighbour is the FIRST leaf and the
8690 // bottom-right's above and left are two DIFFERENT ones (lane-av1rd2 --
8691 // reading the coarse slot desynced the stream, and so did an override
8692 // that remembered only the previous leaf).
8693 let above_skip = neighbours.above_skip[leaf_mi.1];
8694 let left_skip = neighbours.left_skip[leaf_mi.0];
8695 let above_inter = neighbours.above_inter[leaf_mi.1];
8696 let left_inter = neighbours.left_inter[leaf_mi.0];
8697 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
8698 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
8699 write_cdef_idx(enc, leaf_mi, block.skip);
8700 write_delta_q(enc, cdfs, leaf_mi, false, block.skip);
8701
8702 let (has_above, has_left) = (
8703 neighbours.has_above(leaf_mi.0),
8704 neighbours.has_left(leaf_mi.1),
8705 );
8706 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8707 let is_inter = block.inter.is_some();
8708 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
8709
8710 let mode_for_tx;
8711 if let Some(info) = block.inter {
8712 write_comp_mode(
8713 enc,
8714 cdfs,
8715 neighbours,
8716 leaf_mi,
8717 (has_above, has_left),
8718 info.ref1.is_some(),
8719 );
8720 let (mi_row, mi_col) = leaf_mi;
8721 if info.ref1.is_some() {
8722 let (mv, mv1, is_new_mv) = write_compound_block(
8723 enc,
8724 cdfs,
8725 neighbours,
8726 grid,
8727 (mi_row, mi_col),
8728 (2, 2),
8729 (has_above, has_left),
8730 info,
8731 (mi_cols as usize, mi_rows as usize),
8732 )?;
8733 for dr in 0..2 {
8734 for dc in 0..2 {
8735 grid.set(
8736 mi_row + dr,
8737 mi_col + dc,
8738 MiInfo {
8739 is_inter: true,
8740 ref_frame: info.ref_frame,
8741 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8742 mv1: mv16(mv1),
8743 mv: mv16(mv),
8744 is_new_mv,
8745 size: 2,
8746 size_h: 2,
8747 is_global_mv0: false,
8748 is_global_mv1: false,
8749 },
8750 );
8751 }
8752 }
8753 mode_for_tx = 0;
8754 } else {
8755 write_single_ref(
8756 enc,
8757 cdfs,
8758 info.ref_frame,
8759 neighbours.above_ref[leaf_mi.1],
8760 neighbours.above_ref1[leaf_mi.1],
8761 neighbours.left_ref[leaf_mi.0],
8762 neighbours.left_ref1[leaf_mi.0],
8763 );
8764
8765 let stack = find_mv_stack(
8766 grid,
8767 mi_row,
8768 mi_col,
8769 2,
8770 2,
8771 info.ref_frame,
8772 mi_cols as usize,
8773 mi_rows as usize,
8774 );
8775
8776 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
8777 for dr in 0..2 {
8778 for dc in 0..2 {
8779 grid.set(
8780 mi_row + dr,
8781 mi_col + dc,
8782 MiInfo {
8783 is_inter: true,
8784 ref_frame: info.ref_frame,
8785 ref_frame1: NO_REF1,
8786 mv1: (0, 0),
8787 mv: mv16(mv),
8788 is_new_mv,
8789 size: 2,
8790 size_h: 2,
8791 is_global_mv0: false,
8792 is_global_mv1: false,
8793 },
8794 );
8795 }
8796 }
8797 write_motion_mode(
8798 enc,
8799 cdfs,
8800 grid,
8801 (mi_row, mi_col),
8802 (2, 2),
8803 (8, 8),
8804 (mi_cols as usize, mi_rows as usize),
8805 info.ref_frame,
8806 block.motion_mode,
8807 )?;
8808 mode_for_tx = 0;
8809 }
8810 } else {
8811 let mode = usize::from(block.mode);
8812 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);
8813 if (V_PRED..=D67_PRED).contains(&mode) {
8814 enc.symbol(
8815 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8816 &mut cdfs.angle_delta[mode - V_PRED],
8817 );
8818 }
8819 let uv_mode = usize::from(block.uv_mode);
8820 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8821 if uv_mode == UV_CFL_PRED {
8822 write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
8823 }
8824 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8825 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8826 }
8827 mode_for_tx = tx_row(mode, block.filter_intra);
8828 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
8829 // coverage must see it (module doc).
8830 let (mi_row, mi_col) = leaf_mi;
8831 write_palette_syntax(
8832 enc,
8833 cdfs,
8834 neighbours,
8835 block.palette.as_ref(),
8836 block.palette_uv.as_ref(),
8837 block.filter_intra,
8838 mode,
8839 uv_mode,
8840 leaf_mi,
8841 8,
8842 );
8843 for dr in 0..2 {
8844 for dc in 0..2 {
8845 grid.set(
8846 mi_row + dr,
8847 mi_col + dc,
8848 MiInfo {
8849 is_inter: false,
8850 ref_frame: -1,
8851 ref_frame1: NO_REF1,
8852 mv1: (0, 0),
8853 mv: (0, 0),
8854 is_new_mv: false,
8855 size: 2,
8856 size_h: 2,
8857 is_global_mv0: false,
8858 is_global_mv1: false,
8859 },
8860 );
8861 }
8862 }
8863 }
8864
8865 let planes = if is_inter {
8866 [TxbSet::Luma8Inter, TxbSet::Chroma4, TxbSet::Chroma4]
8867 } else {
8868 [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]
8869 };
8870 let tx = if tx_select {
8871 write_tx_syntax_inter(
8872 enc,
8873 cdfs,
8874 neighbours,
8875 leaf_mi,
8876 8,
8877 is_inter,
8878 block.skip,
8879 usize::from(block.tx_depth),
8880 )
8881 } else {
8882 8
8883 };
8884 let split = tx < 8;
8885 if block.skip {
8886 let zero_grids = [
8887 vec![0i32; TX8 * TX8],
8888 vec![0i32; TX4 * TX4],
8889 vec![0i32; TX4 * TX4],
8890 ];
8891 neighbours.record_mi(leaf_mi, 8, &zero_grids);
8892 neighbours.record_inter_mi(
8893 leaf_mi,
8894 8,
8895 block.skip,
8896 block.inter.is_some(),
8897 block_ref(block),
8898 );
8899 record_block_compound(neighbours, leaf_mi, 8, block);
8900 } else {
8901 let grids = [
8902 level_grid(&block.luma, TX8)?,
8903 level_grid(&block.u, TX4)?,
8904 level_grid(&block.v, TX4)?,
8905 ];
8906 if split {
8907 write_luma_tus(
8908 enc,
8909 cdfs,
8910 neighbours,
8911 leaf_mi,
8912 8,
8913 tx,
8914 &grids[0],
8915 mode_for_tx,
8916 all_scans,
8917 is_inter,
8918 &block.luma_tx_types,
8919 )?;
8920 }
8921 write_block_planes(
8922 enc,
8923 cdfs,
8924 &planes,
8925 &grids,
8926 &[scan8, scan4, scan4],
8927 &neighbours.around_mi(leaf_mi, 8),
8928 mode_for_tx,
8929 split,
8930 block_tx_type(block),
8931 is_inter,
8932 );
8933 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
8934 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));
8935 record_block_compound(neighbours, leaf_mi, 8, block);
8936 }
8937 Ok((block.skip, is_inter))
8938}
8939
8940#[cfg(test)]
8941mod tests {
8942 use super::*;
8943 use crate::frame::frame_obu;
8944 use crate::obu::temporal_delimiter;
8945 use crate::probe::run_with_stdin;
8946 use crate::sequence::sequence_header_obu;
8947 use ec_av1_syntax::sequence::SequenceHeader;
8948 use ec_av1_syntax::{
8949 FrameHeader, FrameType, LoopFilterParams, QuantizationParams, TileInfo, TxMode,
8950 PRIMARY_REF_NONE,
8951 };
8952 use std::process::{Command, Stdio};
8953
8954 /// A 64x64 sequence with every tool this writer does not code turned off:
8955 /// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter
8956 /// intra, and no screen content tools (which is what keeps intra block copy
8957 /// and palette out of the block syntax).
8958 fn sequence_64() -> SequenceHeader {
8959 let mut seq = crate::sequence::tests::sample_1080p();
8960 seq.frame_width_bits = 7;
8961 seq.frame_height_bits = 7;
8962 seq.max_frame_width = 64;
8963 seq.max_frame_height = 64;
8964 seq.use_128x128_superblock = false;
8965 seq.enable_filter_intra = false;
8966 seq.enable_cdef = false;
8967 seq.enable_restoration = false;
8968 seq.enable_superres = false;
8969 seq.seq_force_screen_content_tools = 0;
8970 seq.seq_force_integer_mv = 0;
8971 seq
8972 }
8973
8974 /// The key frame the tile above belongs to: one tile, quantised so nothing
8975 /// is lossless, one transform size per block, no in-loop filtering, and no
8976 /// CDF adaptation (the writer codes against the defaults).
8977 fn flat_key_frame() -> FrameHeader {
8978 FrameHeader {
8979 frame_type: FrameType::Key,
8980 frame_is_intra: true,
8981 show_frame: true,
8982 error_resilient_mode: true,
8983 disable_cdf_update: true,
8984 allow_screen_content_tools: false,
8985 force_integer_mv: true,
8986 refresh_frame_flags: 0xFF,
8987 primary_ref_frame: PRIMARY_REF_NONE,
8988 frame_width: 64,
8989 frame_height: 64,
8990 upscaled_width: 64,
8991 render_width: 64,
8992 render_height: 64,
8993 mi_cols: 16,
8994 mi_rows: 16,
8995 tile_info: TileInfo {
8996 uniform_spacing: true,
8997 cols: 1,
8998 rows: 1,
8999 cols_log2: 0,
9000 rows_log2: 0,
9001 mi_col_starts: vec![0, 16],
9002 mi_row_starts: vec![0, 16],
9003 context_update_tile_id: 0,
9004 tile_size_bytes: 1,
9005 },
9006 quantization: QuantizationParams {
9007 base_q_idx: 100,
9008 ..QuantizationParams::default()
9009 },
9010 loop_filter: LoopFilterParams::default(),
9011 tx_mode: TxMode::Largest,
9012 reduced_tx_set: false,
9013 ..FrameHeader::default()
9014 }
9015 }
9016
9017 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
9018 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
9019 /// aomenc gate decodes its stream through ffmpeg and is meaningless
9020 /// without it -- turns it into a hard failure. Without this the require
9021 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
9022 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
9023 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
9024 fn have_ffmpeg() -> bool {
9025 let present = Command::new("ffmpeg")
9026 .arg("-version")
9027 .stdout(Stdio::null())
9028 .stderr(Stdio::null())
9029 .status()
9030 .is_ok_and(|s| s.success());
9031 assert!(
9032 present
9033 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
9034 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
9035 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
9036 );
9037 present
9038 }
9039
9040 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
9041 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
9042 let out = run_with_stdin(
9043 Command::new("ffmpeg").args([
9044 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
9045 ]),
9046 stream,
9047 );
9048 assert!(
9049 out.status.success(),
9050 "ffmpeg refused the stream: {}",
9051 String::from_utf8_lossy(&out.stderr)
9052 );
9053 assert_eq!(
9054 out.stdout.len(),
9055 w * h * 3 / 2,
9056 "expected one 4:2:0 frame, ffmpeg said: {}",
9057 String::from_utf8_lossy(&out.stderr)
9058 );
9059 out.stdout
9060 }
9061
9062 #[test]
9063 fn flat_key_frame_decodes_to_mid_grey() {
9064 if !have_ffmpeg() {
9065 eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH");
9066 return;
9067 }
9068 let seq = sequence_64();
9069 let header = flat_key_frame();
9070 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();
9071
9072 let mut stream = temporal_delimiter();
9073 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9074 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9075
9076 let planes = ffmpeg_decode(&stream, 64, 64);
9077 // A DC prediction with no neighbour to average is the middle of the
9078 // range, and a skipped block adds no residual, so every sample of every
9079 // plane is 128 — one wrong symbol anywhere in the tile shows up here.
9080 for (i, &s) in planes.iter().enumerate() {
9081 assert_eq!(s, 128, "sample {i} of the decoded frame");
9082 }
9083 }
9084
9085 /// The one q-context whose CDFs this crate carries; the decoded table
9086 /// below is pinned at this quantiser and nowhere else.
9087 const Q_IDX: u8 = 100;
9088
9089 /// Encode a 64x64 key frame carrying `dc_level` and hand back its planes.
9090 fn decode_dc_frame(dc_level: i32) -> Vec<u8> {
9091 let seq = sequence_64();
9092 let mut header = flat_key_frame();
9093 header.quantization.base_q_idx = Q_IDX;
9094 let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap();
9095 let mut stream = temporal_delimiter();
9096 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9097 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9098 ffmpeg_decode(&stream, 64, 64)
9099 }
9100
9101 /// What a reference decoder makes of each DC level at `base_q_idx` 100:
9102 /// the level times the DC quantiser, inverse-transformed over a whole
9103 /// 64x64 block — which spreads one coefficient over 4096 samples, so a
9104 /// level moves the picture by a sample or two, not by tens. These numbers
9105 /// are pinned from the decoder rather than derived: this crate has no
9106 /// inverse transform of its own yet to derive them with. What the test
9107 /// asserts around them — flat planes, untouched chroma, monotone in the
9108 /// level, and the sign going the right way — is derived, and it is what a
9109 /// desync in the coefficient syntax breaks first.
9110 const DECODED_AT_Q100: [(i32, u8); 28] = [
9111 (1, 128),
9112 (2, 128),
9113 (3, 129),
9114 (4, 129),
9115 (5, 129),
9116 (6, 129),
9117 (7, 129),
9118 (8, 129),
9119 (9, 130),
9120 (10, 130),
9121 (11, 130),
9122 (12, 130),
9123 (13, 130),
9124 (14, 131),
9125 (-1, 128),
9126 (-2, 128),
9127 (-3, 128),
9128 (-4, 127),
9129 (-5, 127),
9130 (-6, 127),
9131 (-7, 127),
9132 (-8, 127),
9133 (-9, 126),
9134 (-10, 126),
9135 (-11, 126),
9136 (-12, 126),
9137 (-13, 126),
9138 (-14, 126),
9139 ];
9140
9141 #[test]
9142 fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
9143 if !have_ffmpeg() {
9144 eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
9145 return;
9146 }
9147 let mut seen = Vec::new();
9148 for (level, want) in DECODED_AT_Q100 {
9149 let planes = decode_dc_frame(level);
9150 let (luma, chroma) = planes.split_at(64 * 64);
9151 for (i, &sample) in luma.iter().enumerate() {
9152 assert_eq!(sample, want, "luma sample {i} at dc level {level}");
9153 }
9154 // The chroma transform blocks are all-zero, so both planes stay at
9155 // the prediction. A desync in the luma coefficient syntax lands
9156 // here first: the chroma flags are the next symbols after it.
9157 for (i, &sample) in chroma.iter().enumerate() {
9158 assert_eq!(sample, 128, "chroma sample {i} at dc level {level}");
9159 }
9160 seen.push((level, want));
9161 }
9162 // The picture moves off mid-grey the way the level says: up for a
9163 // positive level, down for a negative one, and never back towards it
9164 // as the level grows.
9165 for w in seen.windows(2) {
9166 let ((prev_level, prev), (level, value)) = (w[0], w[1]);
9167 if prev_level.signum() != level.signum() {
9168 continue;
9169 }
9170 if level > 0 {
9171 assert!(
9172 value >= prev,
9173 "level {level} decoded below level {prev_level}"
9174 );
9175 assert!(value >= 128, "a positive level darkened the picture");
9176 } else {
9177 assert!(
9178 value <= prev,
9179 "level {level} decoded above level {prev_level}"
9180 );
9181 assert!(value <= 128, "a negative level brightened the picture");
9182 }
9183 }
9184 assert!(
9185 DECODED_AT_Q100.iter().any(|&(_, v)| v > 128)
9186 && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128),
9187 "the pinned table has to move the picture both ways"
9188 );
9189 }
9190
9191 /// Encode a grid of 64x64 superblocks, each carrying its own DC level, and
9192 /// hand back the decoded planes.
9193 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
9194 let (w, h) = (64 * sb_cols, 64 * sb_rows);
9195 let (seq, mut header) = frame_of(w, h);
9196 // The DC fixture writers code against the default CDFs and never
9197 // update them, so their frames say so.
9198 header.disable_cdf_update = true;
9199 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
9200 let mut stream = temporal_delimiter();
9201 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9202 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9203 ffmpeg_decode(&stream, w as usize, h as usize)
9204 }
9205
9206 /// A sequence and key frame header for a `w` by `h` frame of whole
9207 /// superblocks.
9208 fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) {
9209 let mut seq = sequence_64();
9210 seq.max_frame_width = w;
9211 seq.max_frame_height = h;
9212 let mut header = flat_key_frame();
9213 // Every tile these headers carry is written by the adapting writer.
9214 header.disable_cdf_update = false;
9215 header.frame_width = w;
9216 header.frame_height = h;
9217 header.upscaled_width = w;
9218 header.render_width = w;
9219 header.render_height = h;
9220 header.mi_cols = w / 4;
9221 header.mi_rows = h / 4;
9222 header.tile_info.mi_col_starts = vec![0, header.mi_cols];
9223 header.tile_info.mi_row_starts = vec![0, header.mi_rows];
9224 header.quantization.base_q_idx = Q_IDX;
9225 (seq, header)
9226 }
9227
9228 fn decoded_value(level: i32) -> u8 {
9229 DECODED_AT_Q100
9230 .iter()
9231 .find(|&&(l, _)| l == level)
9232 .map(|&(_, v)| v)
9233 .expect("the level is in the pinned table")
9234 }
9235
9236 /// `dc_predict` (spec 7.11.2) for the flat case: a block whose neighbours
9237 /// are themselves flat predicts their average, and predicts mid-grey with
9238 /// no neighbour at all. Every block here is a whole 64x64 superblock, so
9239 /// the above row and the left column weigh the same.
9240 fn dc_prediction(above: Option<u8>, left: Option<u8>) -> u8 {
9241 match (above, left) {
9242 (None, None) => 128,
9243 (Some(a), None) => a,
9244 (None, Some(l)) => l,
9245 (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8,
9246 }
9247 }
9248
9249 /// What a DC level adds to the prediction: the pinned table is that sum
9250 /// against a mid-grey prediction, and the residual does not depend on what
9251 /// it is added to.
9252 fn dc_residual(level: i32) -> i32 {
9253 i32::from(decoded_value(level)) - 128
9254 }
9255
9256 /// Every block reads its DC sign context off the coded blocks above and to
9257 /// its left, and the three ways that can land — no coded neighbour, the
9258 /// neighbours leaning one way, the neighbours cancelling — are only
9259 /// reachable in a frame whose levels differ in sign. Getting the context
9260 /// wrong desyncs the arithmetic decoder, so the check is that every block
9261 /// still decodes to the grey its own level asks for.
9262 #[test]
9263 fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {
9264 if !have_ffmpeg() {
9265 eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg");
9266 return;
9267 }
9268 // Read in raster order the two grids put a positive, a negative and a
9269 // cancelling sign context in front of the bottom-right block, and a
9270 // leaning-down one in front of the second grid's right and bottom
9271 // blocks.
9272 for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] {
9273 let planes = decode_level_grid(&levels, 2, 2);
9274 let (luma, chroma) = planes.split_at(128 * 128);
9275 // The blocks are not independent: a DC prediction reads the
9276 // reconstructed neighbours, so each block's grey is its
9277 // neighbours' average plus its own residual.
9278 let mut recon = [0u8; 4];
9279 for (block, level) in levels.iter().enumerate() {
9280 let (br, bc) = (block / 2, block % 2);
9281 let above = (br > 0).then(|| recon[block - 2]);
9282 let left = (bc > 0).then(|| recon[block - 1]);
9283 let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level))
9284 .clamp(0, 255) as u8;
9285 recon[block] = want;
9286 for y in 0..64 {
9287 for x in 0..64 {
9288 let i = (br * 64 + y) * 128 + bc * 64 + x;
9289 assert_eq!(
9290 luma[i], want,
9291 "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}"
9292 );
9293 }
9294 }
9295 }
9296 for (i, &sample) in chroma.iter().enumerate() {
9297 assert_eq!(sample, 128, "chroma sample {i} of {levels:?}");
9298 }
9299 }
9300 }
9301
9302 /// What a DC level adds to a 32x32 block's prediction at `base_q_idx` 100,
9303 /// pinned from the decoder the way [`DECODED_AT_Q100`] is. A 32x32
9304 /// transform spreads its DC over a quarter of the samples a 64x64 one
9305 /// does, so the same level moves the picture further: level 14 is five
9306 /// sample values here against three there.
9307 const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [
9308 (1, 0),
9309 (2, 1),
9310 (3, 1),
9311 (4, 1),
9312 (5, 2),
9313 (6, 2),
9314 (7, 3),
9315 (8, 3),
9316 (9, 3),
9317 (10, 4),
9318 (11, 4),
9319 (12, 4),
9320 (13, 5),
9321 (14, 5),
9322 (-1, 0),
9323 (-2, -1),
9324 (-3, -1),
9325 (-4, -1),
9326 (-5, -2),
9327 (-6, -2),
9328 (-7, -2),
9329 (-8, -3),
9330 (-9, -3),
9331 (-10, -4),
9332 (-11, -4),
9333 (-12, -4),
9334 (-13, -5),
9335 (-14, -5),
9336 ];
9337
9338 fn split_residual(level: i32) -> i32 {
9339 SPLIT_RESIDUAL_AT_Q100
9340 .iter()
9341 .find(|&&(l, _)| l == level)
9342 .map(|&(_, r)| r)
9343 .expect("the level is in the pinned table")
9344 }
9345
9346 /// Splitting a superblock puts three more syntax elements in front of every
9347 /// block — the split partition itself, the 32x32 partition below it and a
9348 /// chroma mode from the wider table CFL-capable blocks read — and moves the
9349 /// coefficients onto the 32x32 CDFs. Getting any of them wrong desyncs the
9350 /// arithmetic decoder, and the check is that all sixteen blocks still land
9351 /// on the grey their own level and their neighbours ask for.
9352 #[test]
9353 fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
9354 if !have_ffmpeg() {
9355 eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
9356 return;
9357 }
9358 // Four by four 32x32 blocks over two by two superblocks, so the walk
9359 // crosses superblock boundaries in both directions, and signs that
9360 // alternate so the DC sign context lands on all three of its values.
9361 let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1];
9362 let planes = decode_split_grid(&levels, 2, 2);
9363 let (luma, chroma) = planes.split_at(128 * 128);
9364
9365 let mut recon = [0i32; 16];
9366 for (block, level) in levels.iter().enumerate() {
9367 let (br, bc) = (block / 4, block % 4);
9368 let above = (br > 0).then(|| recon[block - 4] as u8);
9369 let left = (bc > 0).then(|| recon[block - 1] as u8);
9370 let want =
9371 (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255);
9372 recon[block] = want;
9373 for y in 0..32 {
9374 for x in 0..32 {
9375 let i = (br * 32 + y) * 128 + bc * 32 + x;
9376 assert_eq!(
9377 i32::from(luma[i]),
9378 want,
9379 "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \
9380 column {bc}"
9381 );
9382 }
9383 }
9384 }
9385 for (i, &sample) in chroma.iter().enumerate() {
9386 assert_eq!(sample, 128, "chroma sample {i}");
9387 }
9388 }
9389
9390 /// Encode a grid of 32x32 blocks, each carrying its own DC level.
9391 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
9392 let (w, h) = (64 * sb_cols, 64 * sb_rows);
9393 let (seq, mut header) = frame_of(w, h);
9394 // The DC fixture writers code against the default CDFs and never
9395 // update them, so their frames say so.
9396 header.disable_cdf_update = true;
9397 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
9398 let mut stream = temporal_delimiter();
9399 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9400 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9401 ffmpeg_decode(&stream, w as usize, h as usize)
9402 }
9403
9404 #[test]
9405 fn a_level_grid_that_does_not_cover_the_frame_is_refused() {
9406 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err());
9407 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err());
9408 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());
9409 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());
9410 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());
9411 }
9412
9413 #[test]
9414 fn dc_levels_the_base_syntax_cannot_carry_are_refused() {
9415 assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());
9416 assert!(dc_key_frame_tile(16, 16, 100, 15).is_err());
9417 assert!(dc_key_frame_tile(16, 16, 100, -15).is_err());
9418 }
9419
9420 #[test]
9421 fn partial_superblocks_are_refused() {
9422 assert!(flat_key_frame_tile(16, 20).is_err());
9423 assert!(flat_key_frame_tile(0, 16).is_err());
9424 }
9425
9426 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
9427 /// hands back the luma plane as rows of samples.
9428 fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {
9429 let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect();
9430 let [luma, u, v] = decode_coeff_planes(&blocks);
9431 for (name, plane) in [("U", &u), ("V", &v)] {
9432 for (y, row) in plane.iter().enumerate() {
9433 for (x, &s) in row.iter().enumerate() {
9434 assert_eq!(
9435 s, 128,
9436 "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \
9437 DC prediction with no coded neighbour is mid-grey"
9438 );
9439 }
9440 }
9441 }
9442 luma
9443 }
9444
9445 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
9446 /// hands back its three planes as rows of samples: 64 rows of luma and, at
9447 /// 4:2:0, 32 rows of each chroma plane.
9448 fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] {
9449 let (seq, header) = frame_of(64, 64);
9450 let tile =
9451 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
9452 let mut stream = temporal_delimiter();
9453 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9454 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9455 let planes = ffmpeg_decode(&stream, 64, 64);
9456 let (luma, chroma) = planes.split_at(64 * 64);
9457 let (u, v) = chroma.split_at(32 * 32);
9458 [
9459 luma.chunks_exact(64).map(<[u8]>::to_vec).collect(),
9460 u.chunks_exact(32).map(<[u8]>::to_vec).collect(),
9461 v.chunks_exact(32).map(<[u8]>::to_vec).collect(),
9462 ]
9463 }
9464
9465 /// The top-left 32x32 block of a decoded frame, which is the only one whose
9466 /// prediction has no neighbour to lean on.
9467 fn top_left_block(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
9468 rows[..32].iter().map(|r| r[..32].to_vec()).collect()
9469 }
9470
9471 /// A transform's basis functions all average to zero except the DC's, so a
9472 /// block carrying no DC decodes to samples that average to its prediction —
9473 /// mid-grey for the block with no neighbours. Rounding of the inverse
9474 /// transform moves the average by less than a sample.
9475 fn assert_mean_is_mid_grey(block: &[Vec<u8>]) {
9476 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
9477 let mean = f64::from(sum) / (32.0 * 32.0);
9478 assert!(
9479 (mean - 128.0).abs() <= 1.0,
9480 "a block with no DC coefficient averages to its mid-grey prediction, got {mean}"
9481 );
9482 }
9483
9484 /// A coefficient at row 0, column 1 selects the basis function that is flat
9485 /// down the block and a half-cycle of a cosine across it. Nothing about
9486 /// that shape is pinned here: every row of the block must be the same row,
9487 /// the samples must fall from left to right and actually move, and the
9488 /// block must still average to its prediction. A desync in the scan, the
9489 /// end-of-block position or the level contexts breaks one of those.
9490 #[test]
9491 fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
9492 if !have_ffmpeg() {
9493 eprintln!(
9494 "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg"
9495 );
9496 return;
9497 }
9498 let blocks = vec![
9499 vec![Coeff {
9500 row: 0,
9501 col: 1,
9502 level: 12,
9503 }],
9504 Vec::new(),
9505 Vec::new(),
9506 Vec::new(),
9507 ];
9508 let rows = decode_coeff_quadrants(&blocks);
9509 let block = top_left_block(&rows);
9510
9511 for (y, row) in block.iter().enumerate() {
9512 assert_eq!(row, &block[0], "row {y} of a horizontal basis function");
9513 }
9514 assert!(
9515 block[0][0] > block[0][31],
9516 "a positive coefficient leans the block towards its left edge: {:?}",
9517 block[0]
9518 );
9519 for x in 1..32 {
9520 assert!(
9521 block[0][x] <= block[0][x - 1],
9522 "the half-cycle falls from left to right, broke at column {x}: {:?}",
9523 block[0]
9524 );
9525 }
9526 assert_mean_is_mid_grey(&block);
9527
9528 // The same coefficient transposed selects the basis function that is
9529 // flat across the block and a half-cycle down it.
9530 let blocks = vec![
9531 vec![Coeff {
9532 row: 1,
9533 col: 0,
9534 level: 12,
9535 }],
9536 Vec::new(),
9537 Vec::new(),
9538 Vec::new(),
9539 ];
9540 let rows = decode_coeff_quadrants(&blocks);
9541 let block = top_left_block(&rows);
9542 for (y, row) in block.iter().enumerate() {
9543 for (x, &s) in row.iter().enumerate() {
9544 assert_eq!(s, row[0], "sample ({y},{x}) of a vertical basis function");
9545 }
9546 }
9547 assert!(
9548 block[0][0] > block[31][0],
9549 "a positive coefficient leans the block up"
9550 );
9551 for y in 1..32 {
9552 assert!(
9553 block[y][0] <= block[y - 1][0],
9554 "the half-cycle falls from top to bottom, broke at row {y}"
9555 );
9556 }
9557 assert_mean_is_mid_grey(&block);
9558 }
9559
9560 /// A coefficient late in the scan pushes the end-of-block position into a
9561 /// group that carries an offset — the far corner of a 32x32 transform is
9562 /// the last of the eleven groups, whose offset is nine bits wide, one of
9563 /// them from a CDF and the rest raw. Every coefficient before it is coded
9564 /// too, so this also walks the base and base-range contexts over a block
9565 /// with neighbours that carry levels rather than zeros.
9566 #[test]
9567 fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {
9568 if !have_ffmpeg() {
9569 eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group");
9570 return;
9571 }
9572 let block = vec![
9573 Coeff {
9574 row: 31,
9575 col: 31,
9576 level: 5,
9577 },
9578 Coeff {
9579 row: 5,
9580 col: 7,
9581 level: -9,
9582 },
9583 Coeff {
9584 row: 1,
9585 col: 1,
9586 level: 14,
9587 },
9588 Coeff {
9589 row: 0,
9590 col: 2,
9591 level: -3,
9592 },
9593 Coeff {
9594 row: 2,
9595 col: 0,
9596 level: 2,
9597 },
9598 Coeff {
9599 row: 1,
9600 col: 2,
9601 level: -1,
9602 },
9603 ];
9604 let rows = decode_coeff_quadrants(&[block, Vec::new(), Vec::new(), Vec::new()]);
9605 let block = top_left_block(&rows);
9606 assert_mean_is_mid_grey(&block);
9607 assert!(
9608 block.iter().flatten().any(|&s| s != block[0][0]),
9609 "six coefficients do not decode to a flat block"
9610 );
9611 // The blocks that carry nothing are flat: their prediction is whatever
9612 // their neighbours left, and they add no residual to it.
9613 for (name, ys, xs) in [("top right", 0..32, 32..64), ("bottom left", 32..64, 0..32)] {
9614 let first = rows[ys.start][xs.start];
9615 for y in ys {
9616 for x in xs.clone() {
9617 assert_eq!(rows[y][x], first, "the {name} block carries no coefficient");
9618 }
9619 }
9620 }
9621 }
9622
9623 /// The price the mode search pays for a block's levels has to be the price
9624 /// the writer charges for them, or the search is ranking modes by a
9625 /// fiction. Both halves are asked for the same grids under the same
9626 /// neutral contexts, and the priced bits are compared against the bytes
9627 /// the writer really spends.
9628 #[test]
9629 fn the_priced_coefficient_bits_match_the_bytes_written() {
9630 let scan = default_scan(TX32);
9631 // Three grids that reach different parts of the syntax: a lone DC, a
9632 // sparse spread of small levels with both signs, and levels past the
9633 // base-range alphabet so the Golomb tail runs.
9634 let mut grids = vec![vec![0i32; TX32 * TX32]; 3];
9635 grids[0][0] = -7;
9636 for (i, &pos) in scan.iter().enumerate().take(400) {
9637 if i % 7 == 0 {
9638 grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 };
9639 }
9640 }
9641 grids[2][0] = 40;
9642 for (i, &pos) in scan.iter().enumerate().take(64) {
9643 grids[2][pos as usize] += i as i32 % 23 - 11;
9644 }
9645
9646 // A single block is too short for the coder's own flush to average
9647 // out, so all three go through one encoder and one flush.
9648 let mut enc = SymbolEncoder::new();
9649 let mut priced = 0.0;
9650 for grid in &grids {
9651 write_coeffs(
9652 &mut enc,
9653 &mut Cdfs::new(2).txb(TxbSet::Luma32, 0),
9654 grid,
9655 &scan,
9656 0,
9657 0,
9658 None,
9659 TxType::DctDct,
9660 );
9661 priced += luma_32_coeff_bits(grid);
9662 }
9663 let spent = enc.finish().len() as f64 * 8.0;
9664 assert!(
9665 (priced - spent).abs() / spent < 0.02,
9666 "priced {priced} bits, wrote {spent}"
9667 );
9668 }
9669
9670 /// A rate term the search can read as constant is a rate term that ranks
9671 /// nothing, so the price is checked to move the way the levels move: an
9672 /// empty block is the cheapest thing there is, one coefficient costs more
9673 /// than none, and both spreading the coefficients and growing them costs
9674 /// more again.
9675 #[test]
9676 fn the_price_grows_with_the_levels() {
9677 let grid = |f: &dyn Fn(&mut Vec<i32>)| {
9678 let mut g = vec![0i32; TX32 * TX32];
9679 f(&mut g);
9680 luma_32_coeff_bits(&g)
9681 };
9682 let empty = grid(&|_| {});
9683 let one = grid(&|g| g[0] = 1);
9684 let bigger = grid(&|g| g[0] = 30);
9685 let spread = grid(&|g| {
9686 for i in 0..TX32 {
9687 g[i * TX32 + i] = 1;
9688 }
9689 });
9690 assert!(empty < one, "{empty} {one}");
9691 assert!(one < bigger, "{one} {bigger}");
9692 assert!(one < spread, "{one} {spread}");
9693 // An empty block is one symbol -- an expensive one, because a block
9694 // with no coefficients at all is the rarer of the two under the
9695 // neutral context -- and nothing else.
9696 assert!(
9697 empty < 6.0,
9698 "an empty block is one skip symbol, not {empty}"
9699 );
9700 }
9701
9702 /// Neighbouring blocks that each carry coefficients read their DC sign
9703 /// context, their prediction and their own contexts off each other, so a
9704 /// frame whose four blocks all carry mixed-sign coefficients exercises what
9705 /// a single coded block cannot. The check is that it decodes at all — a
9706 /// desync anywhere fails the decode or the frame size — and that the block
9707 /// with no neighbours still averages to mid-grey.
9708 #[test]
9709 fn every_quadrant_carries_its_own_coefficients() {
9710 if !have_ffmpeg() {
9711 eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg");
9712 return;
9713 }
9714 let blocks = vec![
9715 vec![
9716 Coeff {
9717 row: 0,
9718 col: 1,
9719 level: 7,
9720 },
9721 Coeff {
9722 row: 3,
9723 col: 4,
9724 level: -14,
9725 },
9726 ],
9727 vec![
9728 Coeff {
9729 row: 0,
9730 col: 0,
9731 level: -6,
9732 },
9733 Coeff {
9734 row: 2,
9735 col: 2,
9736 level: 9,
9737 },
9738 ],
9739 vec![
9740 Coeff {
9741 row: 0,
9742 col: 0,
9743 level: 6,
9744 },
9745 Coeff {
9746 row: 1,
9747 col: 0,
9748 level: -2,
9749 },
9750 Coeff {
9751 row: 8,
9752 col: 9,
9753 level: 3,
9754 },
9755 ],
9756 vec![
9757 Coeff {
9758 row: 0,
9759 col: 0,
9760 level: 11,
9761 },
9762 Coeff {
9763 row: 16,
9764 col: 1,
9765 level: -4,
9766 },
9767 ],
9768 ];
9769 let rows = decode_coeff_quadrants(&blocks);
9770 assert_mean_is_mid_grey(&top_left_block(&rows));
9771 for (name, ys, xs) in [
9772 ("top right", 0..32, 32..64),
9773 ("bottom left", 32..64, 0..32),
9774 ("bottom right", 32..64, 32..64),
9775 ] {
9776 let block: Vec<Vec<u8>> = rows[ys].iter().map(|r| r[xs.clone()].to_vec()).collect();
9777 assert!(
9778 block.iter().flatten().any(|&s| s != block[0][0]),
9779 "the {name} block carries coefficients, so it is not flat"
9780 );
9781 }
9782 }
9783
9784 /// The top-left 16x16 block of a decoded chroma plane, which is the only
9785 /// one whose prediction has no neighbour to lean on.
9786 fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
9787 rows[..16].iter().map(|r| r[..16].to_vec()).collect()
9788 }
9789
9790 /// The mean of a decoded block, which every basis function but the DC's
9791 /// leaves at the block's prediction.
9792 fn mean(block: &[Vec<u8>]) -> f64 {
9793 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
9794 let count = block.iter().map(Vec::len).sum::<usize>() as f64;
9795 f64::from(sum) / count
9796 }
9797
9798 /// A chroma plane's coefficients ride their own transform, their own CDFs
9799 /// and their own end-of-block alphabet, so a chroma basis function is the
9800 /// gate on all three: U carries the coefficient that is flat down the block
9801 /// and a half-cycle across it, V the one turned a quarter turn, and neither
9802 /// may reach the other plane or luma.
9803 #[test]
9804 fn each_chroma_plane_codes_its_own_basis_function() {
9805 if !have_ffmpeg() {
9806 eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
9807 return;
9808 }
9809 let mut blocks = vec![BlockCoeffs::default(); 4];
9810 blocks[0].u = vec![Coeff {
9811 row: 0,
9812 col: 1,
9813 level: 12,
9814 }];
9815 blocks[0].v = vec![Coeff {
9816 row: 1,
9817 col: 0,
9818 level: 12,
9819 }];
9820 let [luma, u, v] = decode_coeff_planes(&blocks);
9821
9822 for (y, row) in luma.iter().enumerate() {
9823 for (x, &s) in row.iter().enumerate() {
9824 assert_eq!(
9825 s, 128,
9826 "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \
9827 stays at its mid-grey prediction"
9828 );
9829 }
9830 }
9831
9832 let u_block = top_left_chroma(&u);
9833 for (y, row) in u_block.iter().enumerate() {
9834 assert_eq!(
9835 row, &u_block[0],
9836 "row {y} of a horizontal chroma basis function"
9837 );
9838 }
9839 assert!(
9840 u_block[0][0] > u_block[0][15],
9841 "a positive coefficient leans the U block towards its left edge: {:?}",
9842 u_block[0]
9843 );
9844
9845 let v_block = top_left_chroma(&v);
9846 for (x, &top) in v_block[0].iter().enumerate() {
9847 assert_eq!(
9848 top, v_block[0][0],
9849 "column {x} of a vertical chroma basis function"
9850 );
9851 let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect();
9852 assert!(
9853 column[0] > column[15],
9854 "a positive coefficient leans the V column towards its top edge: {column:?}"
9855 );
9856 }
9857
9858 for (name, block) in [("U", &u_block), ("V", &v_block)] {
9859 let mean = mean(block);
9860 assert!(
9861 (mean - 128.0).abs() <= 1.0,
9862 "the {name} block carries no DC, so it averages to its mid-grey prediction, \
9863 got {mean}"
9864 );
9865 }
9866 }
9867
9868 /// Every block coding chroma puts the chroma all-zero flag on the contexts
9869 /// a coded neighbour above and to the left select, and the DC sign on the
9870 /// contexts their signs select. A frame whose four blocks all carry chroma
9871 /// DCs of mixed sign walks those contexts; the picture that comes back must
9872 /// still lean the way each block's own DC asks.
9873 #[test]
9874 fn chroma_dc_signs_read_their_neighbours() {
9875 if !have_ffmpeg() {
9876 eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
9877 return;
9878 }
9879 let dc = |level| {
9880 vec![Coeff {
9881 row: 0,
9882 col: 0,
9883 level,
9884 }]
9885 };
9886 let signs = [8, -8, -8, 8];
9887 let blocks: Vec<BlockCoeffs> = signs
9888 .iter()
9889 .map(|&level| BlockCoeffs {
9890 luma: Vec::new(),
9891 u: dc(level),
9892 v: dc(-level),
9893 ..BlockCoeffs::default()
9894 })
9895 .collect();
9896 let [luma, u, v] = decode_coeff_planes(&blocks);
9897
9898 for (y, row) in luma.iter().enumerate() {
9899 for (x, &s) in row.iter().enumerate() {
9900 assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient");
9901 }
9902 }
9903
9904 // A DC prediction leans on the neighbours a block has, so each block is
9905 // measured against the prediction it was given rather than mid-grey:
9906 // the only block with no neighbour is the first, and the rest are read
9907 // as a step away from the block above them and to their left.
9908 for (i, &level) in signs.iter().enumerate() {
9909 let (r, c) = (i / 2, i % 2);
9910 let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> {
9911 plane[r * 16..r * 16 + 16]
9912 .iter()
9913 .map(|row| row[c * 16..c * 16 + 16].to_vec())
9914 .collect()
9915 };
9916 for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] {
9917 let block = block(plane);
9918 let mean = mean(&block);
9919 for (y, row) in block.iter().enumerate() {
9920 assert_eq!(
9921 row.iter().collect::<std::collections::HashSet<_>>().len(),
9922 1,
9923 "row {y} of a DC-only {name} block is flat"
9924 );
9925 }
9926 if i == 0 {
9927 assert!(
9928 (want > 0) == (mean > 128.0),
9929 "{name} block {i} carries a DC of {want}, so it must lean off its \
9930 mid-grey prediction that way, got {mean}"
9931 );
9932 }
9933 }
9934 }
9935 assert_ne!(u, v, "the two chroma planes carry opposite DCs");
9936 }
9937
9938 /// The coefficient writer refuses what it cannot code rather than writing a
9939 /// stream a decoder walks off the end of.
9940 /// The 32x32 block at the given block row and column of a decoded plane.
9941 fn block_at(rows: &[Vec<u8>], block_row: usize, block_col: usize) -> Vec<Vec<u8>> {
9942 rows[block_row * 32..block_row * 32 + 32]
9943 .iter()
9944 .map(|r| r[block_col * 32..block_col * 32 + 32].to_vec())
9945 .collect()
9946 }
9947
9948 /// Encodes a key frame of the given size, whose 32x32 blocks carry
9949 /// `blocks` in raster order, and hands back its luma plane as rows of
9950 /// The neighbour context a block reads is gathered across every cell it
9951 /// spans, not taken from the first one: a 32x32 block whose left-hand
9952 /// neighbour cells disagree still sees the coded one. Reading a single
9953 /// cell agreed with the decoder only while every block was the same size,
9954 /// and desynchronised the arithmetic decoder the moment a 16x16 one
9955 /// appeared beside a 32x32 one.
9956 #[test]
9957 fn a_block_gathers_the_cells_its_neighbours_cover() {
9958 let mut neighbours = Neighbours::new(4, 4, 64, 64);
9959 let quiet = [
9960 vec![0i32; TX16 * TX16],
9961 vec![0; TX8 * TX8],
9962 vec![0; TX8 * TX8],
9963 ];
9964 let mut loud = quiet.clone();
9965 loud[1][0] = -3;
9966 // Two 16x16 blocks above the right-hand 32x32 block of the row, of
9967 // which only the second codes anything.
9968 neighbours.record((0, 2), SUB, DC_PRED, &quiet);
9969 neighbours.record((0, 3), SUB, DC_PRED, &loud);
9970 let around = neighbours.around((2, 2), BLOCK);
9971 assert!(
9972 around[1].above_coded,
9973 "the coded cell has to reach the block below it"
9974 );
9975 assert_eq!(
9976 dc_sign_ctx(around[1].dc_vote),
9977 1,
9978 "the one negative DC above the block is what it votes"
9979 );
9980 // The same read one cell at a time misses it, which is the bug this
9981 // gate is here for. `above[8]` is the first 4x4 unit the quiet block
9982 // at `(0, 2)` wrote (2 SUB units * 4 4x4-units-per-SUB).
9983 assert!(!neighbours.above[8][1].coded);
9984 }
9985
9986 /// samples.
9987 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
9988 let (seq, header) = frame_of(width as u32, height as u32);
9989 let tile =
9990 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
9991 let mut stream = temporal_delimiter();
9992 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9993 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9994 let planes = ffmpeg_decode(&stream, width, height);
9995 planes[..width * height]
9996 .chunks_exact(width)
9997 .map(<[u8]>::to_vec)
9998 .collect()
9999 }
10000
10001 /// Every row of a block is the same row, and that row falls from left to
10002 /// right — the shape of a coefficient at row 0, column 1.
10003 fn assert_falls_across(block: &[Vec<u8>], name: &str) {
10004 for row in block {
10005 assert_eq!(
10006 row, &block[0],
10007 "{name}: every row of the block is the same row"
10008 );
10009 }
10010 assert!(
10011 block[0][0] > block[0][31],
10012 "{name}: the row falls from left to right, got {} then {}",
10013 block[0][0],
10014 block[0][31]
10015 );
10016 }
10017
10018 /// Every column of a block is constant across it and falls down it — the
10019 /// shape of a coefficient at row 1, column 0.
10020 fn assert_falls_down(block: &[Vec<u8>], name: &str) {
10021 for (y, row) in block.iter().enumerate() {
10022 assert!(
10023 row.iter().all(|&s| s == row[0]),
10024 "{name}: row {y} of the block is one constant"
10025 );
10026 }
10027 assert!(
10028 block[0][0] > block[31][0],
10029 "{name}: the column falls down the block, got {} then {}",
10030 block[0][0],
10031 block[31][0]
10032 );
10033 }
10034
10035 /// The mean sample of a decoded block.
10036 fn mean_of(block: &[Vec<u8>]) -> f64 {
10037 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
10038 f64::from(sum) / (block.len() * block[0].len()) as f64
10039 }
10040
10041 /// The top-left block of a frame whose only coefficient is a luma DC of
10042 /// `level`.
10043 fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> {
10044 let blocks = vec![
10045 vec![Coeff {
10046 row: 0,
10047 col: 0,
10048 level,
10049 }],
10050 Vec::new(),
10051 Vec::new(),
10052 Vec::new(),
10053 ];
10054 top_left_block(&decode_coeff_quadrants(&blocks))
10055 }
10056
10057 /// `read_golomb` (spec 5.11.40), written from the specification's
10058 /// pseudocode, and the level its caller builds from it: a level above the
10059 /// base-range tail is fifteen plus what the tail carries.
10060 fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 {
10061 let mut length = 0;
10062 while dec.literal(1) == 0 {
10063 length += 1;
10064 assert!(
10065 length < 20,
10066 "the tail's length prefix runs past twenty bits"
10067 );
10068 }
10069 let mut x = 1;
10070 for _ in 0..length {
10071 x = (x << 1) | dec.literal(1);
10072 }
10073 (MAX_BR_LEVEL + 1) as u32 + (x - 1)
10074 }
10075
10076 /// The tail says how much of the level the base and base-range syntax could
10077 /// not carry, and the spec's own reader must hand back the level that was
10078 /// asked for — not one either side of it. A tail written a bit long, a bit
10079 /// short, or against the wrong base fails this at the first level it
10080 /// reaches.
10081 #[test]
10082 fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
10083 for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300)
10084 .chain([MAX_LEVEL - 1, MAX_LEVEL])
10085 .map(|l| l as u32)
10086 {
10087 let mut enc = SymbolEncoder::new();
10088 write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32);
10089 // The tail is raw bits, so it needs no padding beyond what the
10090 // encoder's own flush writes.
10091 let data = enc.finish();
10092 let mut dec = crate::msac::tests::SymbolDecoder::new(&data);
10093 assert_eq!(
10094 read_golomb_level(&mut dec),
10095 level,
10096 "the tail of level {level}"
10097 );
10098 }
10099 }
10100
10101 /// The base and base-range syntax reach level fourteen between them;
10102 /// anything above that carries the rest of itself as a Golomb tail, written
10103 /// after its own sign. A DC level moves the whole block off its mid-grey
10104 /// prediction by an amount that grows with the level, so a run of levels
10105 /// either side of the tail's threshold — spaced wide enough that the
10106 /// quantiser separates them — must decode to a run of steadily
10107 /// brighter blocks — and the negatives of the same levels to steadily
10108 /// darker ones. A tail written with the wrong length, in the wrong place in
10109 /// the syntax, or off by one desyncs the decoder outright.
10110 #[test]
10111 fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
10112 if !have_ffmpeg() {
10113 eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
10114 return;
10115 }
10116 let mut brighter = Vec::new();
10117 let mut darker = Vec::new();
10118 for level in [10, 14, 18, 31, 60, 400] {
10119 brighter.push((level, mean_of(&decode_dc_level_block(level))));
10120 darker.push((level, mean_of(&decode_dc_level_block(-level))));
10121 }
10122 for pair in brighter.windows(2) {
10123 let [(low, dim), (high, bright)] = [pair[0], pair[1]];
10124 assert!(
10125 bright > dim,
10126 "level {high} decodes brighter than level {low}, got {bright} against {dim}"
10127 );
10128 }
10129 for pair in darker.windows(2) {
10130 let [(low, bright), (high, dim)] = [pair[0], pair[1]];
10131 assert!(
10132 dim < bright,
10133 "level -{high} decodes darker than level -{low}, got {dim} against {bright}"
10134 );
10135 }
10136 let (_, mid) = brighter[0];
10137 assert!(
10138 mid > 128.0 && darker[0].1 < 128.0,
10139 "a positive level brightens its block and a negative one darkens it, got {mid} and {}",
10140 darker[0].1
10141 );
10142 }
10143
10144 /// A frame need not be a whole number of superblocks. A 96x64 frame is a
10145 /// superblock and a half across: the second superblock has no right-hand
10146 /// half, so its partition is a gathered flag rather than the full symbol,
10147 /// and the two blocks that would sit in that half are never coded at all.
10148 /// Each of the six blocks that do exist carries one of two basis functions,
10149 /// alternating, so a block written into the wrong place or a flag the
10150 /// decoder reads as a different number of bits shows up as a block with the
10151 /// other block's shape — or as a decode failure.
10152 fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8>> {
10153 let (seq, header) = frame_of(width as u32, height as u32);
10154 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap();
10155 let mut stream = temporal_delimiter();
10156 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
10157 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
10158 let planes = ffmpeg_decode(&stream, width, height);
10159 planes[..width * height]
10160 .chunks_exact(width)
10161 .map(<[u8]>::to_vec)
10162 .collect()
10163 }
10164
10165 /// A superblock left whole carries one 64x64 transform, whose lowest
10166 /// horizontal basis function falls across the whole sixty-four samples in
10167 /// one stroke. Were the same superblock split, each half would restart the
10168 /// gradient at its own left edge and the picture would rise again in the
10169 /// middle, so the walk across the row is what tells the two apart — and
10170 /// the split superblock beside it proves the two partitions still agree on
10171 /// where the next one begins.
10172 #[test]
10173 fn a_whole_superblock_covers_all_four_of_its_quadrants() {
10174 if !have_ffmpeg() {
10175 eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg");
10176 return;
10177 }
10178 let across = BlockCoeffs::from(vec![Coeff {
10179 row: 0,
10180 col: 1,
10181 level: 20,
10182 }]);
10183 let down = BlockCoeffs::from(vec![Coeff {
10184 row: 1,
10185 col: 0,
10186 level: 20,
10187 }]);
10188 let sbs = [
10189 Superblock::Whole(across),
10190 Superblock::Split(vec![
10191 Quadrant::Whole(down.clone()),
10192 Quadrant::Whole(down.clone()),
10193 Quadrant::Whole(down.clone()),
10194 Quadrant::Whole(down),
10195 ]),
10196 ];
10197 let rows = decode_luma_sb(128, 64, &sbs);
10198
10199 for (y, row) in rows.iter().enumerate() {
10200 assert_eq!(
10201 &row[..64],
10202 &rows[0][..64],
10203 "row {y} of the whole superblock repeats its first row"
10204 );
10205 }
10206 let first = &rows[0][..64];
10207 assert!(
10208 first.windows(2).all(|w| w[0] >= w[1]),
10209 "the whole superblock falls across its sixty-four samples without \
10210 restarting: {first:?}"
10211 );
10212 assert!(
10213 first[0] > first[63],
10214 "the whole superblock falls from left to right, got {} then {}",
10215 first[0],
10216 first[63]
10217 );
10218 for block_row in 0..2 {
10219 for block_col in 2..4 {
10220 let block = block_at(&rows, block_row, block_col);
10221 assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})"));
10222 }
10223 }
10224 }
10225
10226 /// A quadrant may be split again into four 16x16 blocks, each carrying its
10227 /// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block
10228 /// makes each of the four a flat grey of its own, so the quadrant reads as
10229 /// four squares rather than one — which is what tells the extra split from
10230 /// a 32x32 block that merely carries the same coefficients.
10231 #[test]
10232 fn a_quadrant_splits_into_four_sixteens() {
10233 if !have_ffmpeg() {
10234 eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
10235 return;
10236 }
10237 let dc = |level: i32| {
10238 BlockCoeffs::from(vec![Coeff {
10239 row: 0,
10240 col: 0,
10241 level,
10242 }])
10243 };
10244 let levels = [14, 8, -8, -14];
10245 let flat = BlockCoeffs::from(Vec::new());
10246 let sbs = [Superblock::Split(vec![
10247 Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()),
10248 Quadrant::Whole(flat.clone()),
10249 Quadrant::Whole(flat.clone()),
10250 Quadrant::Whole(flat),
10251 ])];
10252 let rows = decode_luma_sb(64, 64, &sbs);
10253
10254 let mut greys = Vec::new();
10255 for i in 0..levels.len() {
10256 let (y0, x0) = ((i / 2) * 16, (i % 2) * 16);
10257 let grey = rows[y0][x0];
10258 for (y, row) in rows.iter().enumerate().skip(y0).take(16) {
10259 for (x, &sample) in row.iter().enumerate().skip(x0).take(16) {
10260 assert_eq!(
10261 sample, grey,
10262 "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not"
10263 );
10264 }
10265 }
10266 greys.push(grey);
10267 }
10268
10269 // Each block is predicted DC from the blocks the decoder has already
10270 // rebuilt, so what its own level does is move it off that prediction,
10271 // in the level's own direction.
10272 let g = |i: usize| i32::from(greys[i]);
10273 let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2];
10274 for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() {
10275 assert_eq!(
10276 (g(i) - prediction).signum(),
10277 level.signum(),
10278 "the 16x16 block {i} carries level {level}, so it sits on the \
10279 {} side of the {prediction} its neighbours predict, not at {}",
10280 if level > 0 { "bright" } else { "dark" },
10281 g(i)
10282 );
10283 }
10284 assert_eq!(
10285 greys.iter().collect::<std::collections::HashSet<_>>().len(),
10286 4,
10287 "the four blocks are four different greys, not one: {greys:?}"
10288 );
10289 }
10290
10291 /// A superblock half outside the frame has no partition that keeps a block
10292 /// outside it, so it cannot be left whole.
10293 #[test]
10294 fn a_whole_superblock_at_the_frame_edge_is_refused() {
10295 let block = BlockCoeffs::from(vec![Coeff {
10296 row: 0,
10297 col: 0,
10298 level: 4,
10299 }]);
10300 let sbs = [
10301 Superblock::Split(vec![
10302 Quadrant::Whole(block.clone()),
10303 Quadrant::Whole(block.clone()),
10304 Quadrant::Whole(block.clone()),
10305 Quadrant::Whole(block.clone()),
10306 ]),
10307 Superblock::Whole(block.clone()),
10308 ];
10309 // Ninety-six samples across is three 32x32 blocks, so the second
10310 // superblock hangs half outside the frame.
10311 let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err();
10312 assert!(
10313 format!("{err}").contains("half outside the frame"),
10314 "got {err}"
10315 );
10316 }
10317
10318 #[test]
10319 fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
10320 if !have_ffmpeg() {
10321 eprintln!(
10322 "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \
10323 ffmpeg"
10324 );
10325 return;
10326 }
10327 let blocks: Vec<BlockCoeffs> = (0..6)
10328 .map(|i| {
10329 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
10330 BlockCoeffs::from(vec![Coeff {
10331 row,
10332 col,
10333 level: 12,
10334 }])
10335 })
10336 .collect();
10337 let rows = decode_luma_at(96, 64, &blocks);
10338 for block_row in 0..2 {
10339 for block_col in 0..3 {
10340 let name = format!("block ({block_row},{block_col})");
10341 let block = block_at(&rows, block_row, block_col);
10342 if (block_row * 3 + block_col) % 2 == 0 {
10343 assert_falls_across(&block, &name);
10344 } else {
10345 assert_falls_down(&block, &name);
10346 }
10347 }
10348 }
10349 }
10350
10351 /// The transpose of [`a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block`]:
10352 /// an odd number of 32x32 block *rows* (superblock hangs off the
10353 /// *bottom*, `has_cols=true, has_rows=false`) rather than an odd number of
10354 /// columns (hangs off the *right*, `has_cols=false, has_rows=true`) --
10355 /// the two halves of the `(has_cols, has_rows)` match in
10356 /// `sb_coeff_key_frame_tile` gather from different tables
10357 /// (`VERT_ALIKE`/`HORZ_ALIKE`), and only the right-hand-edge direction had
10358 /// a real-decoder test before this one.
10359 #[test]
10360 fn a_frame_that_hangs_off_the_bottom_codes_every_block() {
10361 if !have_ffmpeg() {
10362 eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg");
10363 return;
10364 }
10365 let blocks: Vec<BlockCoeffs> = (0..6)
10366 .map(|i| {
10367 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
10368 BlockCoeffs::from(vec![Coeff {
10369 row,
10370 col,
10371 level: 12,
10372 }])
10373 })
10374 .collect();
10375 let rows = decode_luma_at(64, 96, &blocks);
10376 for block_row in 0..3 {
10377 for block_col in 0..2 {
10378 let name = format!("block ({block_row},{block_col})");
10379 let block = block_at(&rows, block_row, block_col);
10380 if (block_row * 2 + block_col) % 2 == 0 {
10381 assert_falls_across(&block, &name);
10382 } else {
10383 assert_falls_down(&block, &name);
10384 }
10385 }
10386 }
10387 }
10388
10389 /// A frame whose blocks do not tile it is refused rather than written as a
10390 /// stream a decoder walks off the end of.
10391 #[test]
10392 fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() {
10393 let (_, header) = frame_of(80, 64);
10394 let blocks = vec![BlockCoeffs::default(); 4];
10395 let err = split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, &blocks)
10396 .expect_err("80 is not a whole number of 32x32 blocks");
10397 assert!(
10398 format!("{err}").contains("32x32"),
10399 "the refusal names the block size, got {err}"
10400 );
10401 }
10402
10403 /// A directional intra mode says where its prediction comes from, and with
10404 /// no residual of its own a block must be exactly that prediction. The
10405 /// top-left block is given a basis function that is flat across it and
10406 /// falls down it; the block to its right is coded `H_PRED`, so every one of
10407 /// its rows must be the constant its left neighbour's rightmost column
10408 /// hands it, and the block below is coded `V_PRED`, so every one of its
10409 /// columns must be the constant the row above it ends on — a single flat
10410 /// value for the whole block. Nothing here pins the transform's shape or
10411 /// the mode's CDF: a mode written with the wrong context, an angle delta
10412 /// left out or a mode index off by one desyncs the symbol decoder and the
10413 /// two empty blocks stop mirroring their neighbours.
10414 #[test]
10415 fn directional_modes_predict_from_the_neighbours_they_name() {
10416 if !have_ffmpeg() {
10417 eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg");
10418 return;
10419 }
10420 let gradient = BlockCoeffs {
10421 luma: vec![Coeff {
10422 row: 1,
10423 col: 0,
10424 level: 12,
10425 }],
10426 ..BlockCoeffs::default()
10427 };
10428 let blocks = [
10429 gradient,
10430 BlockCoeffs {
10431 mode: H_PRED as u8,
10432 ..BlockCoeffs::default()
10433 },
10434 BlockCoeffs {
10435 mode: V_PRED as u8,
10436 ..BlockCoeffs::default()
10437 },
10438 BlockCoeffs::default(),
10439 ];
10440 let [luma, ..] = decode_coeff_planes(&blocks);
10441
10442 let source = block_at(&luma, 0, 0);
10443 for (r, row) in source.iter().enumerate() {
10444 assert!(
10445 row.iter().all(|&s| s == row[0]),
10446 "the basis function at row 1, column 0 is flat across the block, row {r} is not: {row:?}"
10447 );
10448 }
10449 let profile: Vec<u8> = source.iter().map(|r| r[0]).collect();
10450 assert!(
10451 profile.windows(2).all(|w| w[0] >= w[1]) && profile[0] > profile[31],
10452 "the block must fall from top to bottom, got {profile:?}"
10453 );
10454
10455 let horizontal = block_at(&luma, 0, 1);
10456 for (r, row) in horizontal.iter().enumerate() {
10457 assert!(
10458 row.iter().all(|&s| s == profile[r]),
10459 "an H_PRED block repeats the column to its left, row {r} should be all {} but is {row:?}",
10460 profile[r]
10461 );
10462 }
10463
10464 let vertical = block_at(&luma, 1, 0);
10465 let bottom = profile[31];
10466 assert!(
10467 vertical.iter().flatten().all(|&s| s == bottom),
10468 "a V_PRED block repeats the row above it, which is all {bottom} here, got rows \
10469 {:?} and {:?}",
10470 vertical[0],
10471 vertical[31]
10472 );
10473 }
10474
10475 /// The mode index is checked before anything is written.
10476 #[test]
10477 fn an_intra_mode_outside_the_key_frame_set_is_refused() {
10478 let mut blocks = vec![BlockCoeffs::default(); 4];
10479 blocks[2].mode = INTRA_MODES as u8;
10480 let message = split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks)
10481 .unwrap_err()
10482 .to_string();
10483 assert!(
10484 message.contains("intra mode 13"),
10485 "the refusal must name the mode, got {message}"
10486 );
10487 }
10488
10489 #[test]
10490 fn coefficients_the_writer_cannot_code_are_refused() {
10491 let empty = || vec![BlockCoeffs::default(); 4];
10492 let cases: [(&str, Vec<BlockCoeffs>); 6] = [
10493 ("one set short", vec![BlockCoeffs::default(); 3]),
10494 ("off the transform", {
10495 let mut b = empty();
10496 b[0].luma = vec![Coeff {
10497 row: 32,
10498 col: 0,
10499 level: 1,
10500 }];
10501 b
10502 }),
10503 ("a zero level", {
10504 let mut b = empty();
10505 b[1].luma = vec![Coeff {
10506 row: 0,
10507 col: 0,
10508 level: 0,
10509 }];
10510 b
10511 }),
10512 ("a level past the Golomb tail's reach", {
10513 let mut b = empty();
10514 b[2].luma = vec![Coeff {
10515 row: 0,
10516 col: 0,
10517 level: MAX_LEVEL + 1,
10518 }];
10519 b
10520 }),
10521 ("two coefficients at one position", {
10522 let mut b = empty();
10523 b[3].luma = vec![
10524 Coeff {
10525 row: 4,
10526 col: 4,
10527 level: 1,
10528 },
10529 Coeff {
10530 row: 4,
10531 col: 4,
10532 level: 2,
10533 },
10534 ];
10535 b
10536 }),
10537 ("off the chroma transform", {
10538 let mut b = empty();
10539 b[0].u = vec![Coeff {
10540 row: 0,
10541 col: 16,
10542 level: 1,
10543 }];
10544 b
10545 }),
10546 ];
10547 for (name, blocks) in cases {
10548 assert!(
10549 split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks).is_err(),
10550 "{name} must be refused"
10551 );
10552 }
10553 }
10554
10555 /// The default scan is written as the rule that generates it rather than a
10556 /// thousand pinned numbers, so the rule is checked against what a scan must
10557 /// be: every position exactly once, the origin first, and never a position
10558 /// before one it sits diagonally behind — which is what lets a decoder read
10559 /// a coefficient's context off the coefficients it has already decoded.
10560 /// lane-rdoq's two contracts, on a block shaped like the ones the pass
10561 /// exists for (a strong DC, two mid levels and a tail of barely-rounded
10562 /// +-1s): it may only move a block to a LOWER `D + lambda * R`, and the
10563 /// bits it hands back must be the price of the grid it leaves behind --
10564 /// the search takes that number as the block's rate, so a stale one
10565 /// would price a tile nobody writes.
10566 #[test]
10567 fn rdoq_only_lowers_the_cost_and_reports_its_own_grid() {
10568 let (side, set, q, lambda) = (16usize, TxbSet::Luma16, 150u8, 0.0275);
10569 let mut scaled = vec![0f32; side * side];
10570 for (i, v) in [
10571 (0usize, 7.4f32),
10572 (1, 2.6),
10573 (side, -1.55),
10574 // The tail the pass exists for: coefficients the deadzone only
10575 // just rounded up to +-1, which give a whole level back for a
10576 // fraction of one step of squared error.
10577 (2, 0.55),
10578 (2 * side + 1, -0.52),
10579 (3 * side + 3, 0.51),
10580 ] {
10581 scaled[i] = v;
10582 }
10583 // The deadzone quantiser this pass runs after, at the shipped 0.5.
10584 let mut levels: Vec<i32> = scaled
10585 .iter()
10586 .map(|&v| {
10587 let m = f64::from(v).abs() + 0.5;
10588 let l = if m < 1.0 { 0 } else { m.floor() as i32 };
10589 if v < 0.0 {
10590 -l
10591 } else {
10592 l
10593 }
10594 })
10595 .collect();
10596 let before = levels.clone();
10597 let dc = f64::from(crate::quant::dc_q(8, i32::from(q)));
10598 let ac = f64::from(crate::quant::ac_q(8, i32::from(q)));
10599 let dc_weight = (dc / ac) * (dc / ac);
10600 let cost = |grid: &[i32]| -> f64 {
10601 let d: f64 = grid
10602 .iter()
10603 .zip(&scaled)
10604 .enumerate()
10605 .map(|(i, (&l, &s))| {
10606 (if i == 0 { dc_weight } else { 1.0 }) * (f64::from(s) - f64::from(l)).powi(2)
10607 })
10608 .sum();
10609 d + lambda * coeff_bits(grid, set, crate::decode::q_ctx_of(q), 0, 0)
10610 };
10611 let bits = rdoq(
10612 &mut levels,
10613 &scaled,
10614 side,
10615 q,
10616 set,
10617 0,
10618 0,
10619 lambda,
10620 TxType::DctDct,
10621 );
10622 assert_eq!(
10623 bits,
10624 coeff_bits(&levels, set, crate::decode::q_ctx_of(q), 0, 0)
10625 );
10626 assert!(
10627 cost(&levels) <= cost(&before),
10628 "{:?} vs {:?}",
10629 cost(&levels),
10630 cost(&before)
10631 );
10632 // The tail is what it is for: the last coded position moves earlier.
10633 let last = |g: &[i32]| scan_of(side).iter().rposition(|&p| g[usize::from(p)] != 0);
10634 assert!(
10635 last(&levels) < last(&before),
10636 "eob {:?} -> {:?}",
10637 last(&before),
10638 last(&levels)
10639 );
10640 // A 64-point transform is priced on its top-left 32x32 corner, and
10641 // the pass has to hand back THAT price (the dense path).
10642 let (side, set) = (64usize, TxbSet::Luma64);
10643 let mut scaled = vec![0f32; side * side];
10644 for (i, v) in [(0usize, 6.1f32), (1, 0.55), (side + 1, -0.53)] {
10645 scaled[i] = v;
10646 }
10647 let mut levels: Vec<i32> = scaled
10648 .iter()
10649 .map(|&v| {
10650 let m = f64::from(v).abs() + 0.5;
10651 let l = if m < 1.0 { 0 } else { m.floor() as i32 };
10652 if v < 0.0 {
10653 -l
10654 } else {
10655 l
10656 }
10657 })
10658 .collect();
10659 let bits = rdoq(
10660 &mut levels,
10661 &scaled,
10662 side,
10663 q,
10664 set,
10665 0,
10666 0,
10667 lambda,
10668 TxType::DctDct,
10669 );
10670 let corner: Vec<i32> = (0..32)
10671 .flat_map(|row| levels[row * side..][..32].to_vec())
10672 .collect();
10673 assert_eq!(
10674 bits,
10675 coeff_bits(&corner, set, crate::decode::q_ctx_of(q), 0, 0)
10676 );
10677 }
10678
10679 #[test]
10680 fn the_default_scan_walks_every_position_outwards() {
10681 for side in [TX16, TX32] {
10682 let area = side * side;
10683 let scan = default_scan(side);
10684 assert_eq!(scan.len(), area);
10685 let mut seen = vec![false; area];
10686 for &pos in &scan {
10687 assert!(
10688 !seen[pos as usize],
10689 "position {pos} is scanned twice in {side}x{side}"
10690 );
10691 seen[pos as usize] = true;
10692 }
10693 assert_eq!(scan[0], 0, "the scan starts at the DC");
10694
10695 let mut order = vec![0usize; area];
10696 for (i, &pos) in scan.iter().enumerate() {
10697 order[pos as usize] = i;
10698 }
10699 for row in 0..side {
10700 for col in 0..side {
10701 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
10702 let (nr, nc) = (row + dr, col + dc);
10703 if nr < side && nc < side {
10704 assert!(
10705 order[nr * side + nc] > order[row * side + col],
10706 "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
10707 be scanned after it"
10708 );
10709 }
10710 }
10711 }
10712 }
10713 }
10714 }
10715
10716 /// The whole point of the inverse transform living in the encoder is that
10717 /// it predicts the decoder without asking one. The residual a DC-only
10718 /// 64x64 transform produces has already been pinned from a real decoder in
10719 /// [`DECODED_AT_Q100`], so that table is the gate: every level in it, both
10720 /// signs, has to come back out of `dequant_and_inverse` exactly.
10721 #[test]
10722 fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() {
10723 for (level, _) in DECODED_AT_Q100 {
10724 let mut levels = vec![0i32; 64 * 64];
10725 levels[0] = level;
10726 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
10727 let want = dc_residual(level);
10728 assert!(
10729 residual.iter().all(|&r| r == want),
10730 "level {level}: want a flat {want}, got {}..{} (first {})",
10731 residual.iter().min().unwrap(),
10732 residual.iter().max().unwrap(),
10733 residual[0]
10734 );
10735 }
10736 }
10737
10738 /// The same gate at the other transform size the encoder codes: a split
10739 /// superblock's 32x32 blocks, whose residuals are pinned in
10740 /// [`SPLIT_RESIDUAL_AT_Q100`]. The two sizes divide the dequantized
10741 /// coefficient by different denominators, so a size-blind dequantizer
10742 /// passes one table and fails the other.
10743 #[test]
10744 fn the_inverse_transform_reproduces_the_pinned_split_residuals() {
10745 for (level, want) in SPLIT_RESIDUAL_AT_Q100 {
10746 let mut levels = vec![0i32; 32 * 32];
10747 levels[0] = level;
10748 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
10749 assert!(
10750 residual.iter().all(|&r| r == want),
10751 "level {level}: want a flat {want}, got {}..{} (first {})",
10752 residual.iter().min().unwrap(),
10753 residual.iter().max().unwrap(),
10754 residual[0]
10755 );
10756 }
10757 }
10758
10759 /// A DC-only transform is flat, which is exactly the case that cannot tell
10760 /// a transposed or mis-permuted butterfly network from a correct one. An AC
10761 /// coefficient in the first row must vary along the row and stay constant
10762 /// down each column, and the one in the first column the other way round;
10763 /// a transposed network swaps the two.
10764 #[test]
10765 fn a_single_ac_coefficient_varies_along_its_own_axis() {
10766 for side in [4, 8, 16, 32, 64] {
10767 let mut horizontal = vec![0i32; side * side];
10768 horizontal[1] = 100;
10769 let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX));
10770 let mut vertical = vec![0i32; side * side];
10771 vertical[side] = 100;
10772 let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX));
10773 for row in 0..side {
10774 for col in 0..side {
10775 assert_eq!(
10776 h[row * side + col],
10777 h[col],
10778 "{side}: a first-row coefficient is constant down column {col}"
10779 );
10780 assert_eq!(
10781 v[row * side + col],
10782 v[row * side],
10783 "{side}: a first-column coefficient is constant along row {row}"
10784 );
10785 }
10786 }
10787 // The two are each other's transpose. Only to within a rounding
10788 // step: the spec rounds halves up rather than away from zero, so a
10789 // basis function and its transpose can land a count apart where
10790 // the row and column passes round opposite ways.
10791 assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies");
10792 for row in 0..side {
10793 for col in 0..side {
10794 let (a, b) = (h[row * side + col], v[col * side + row]);
10795 assert!(
10796 (a - b).abs() <= 1,
10797 "{side}: transpose at ({row},{col}): {a} vs {b}"
10798 );
10799 }
10800 }
10801 }
10802 }
10803
10804 /// Negating every level negates every residual, to within the one count
10805 /// the spec's round-halves-up leaves behind. A dequantizer that rounded a
10806 /// negative coefficient away from zero instead of toward it would shift a
10807 /// whole basis function, not a count of it, so the bound is what makes
10808 /// this a test rather than a restatement.
10809 #[test]
10810 fn negating_the_levels_negates_the_residual() {
10811 for side in [32, 64] {
10812 for level in [1, 2, 3, 5, 9, 14, 40, 100] {
10813 let mut levels = vec![0i32; side * side];
10814 levels[0] = level;
10815 levels[1] = -level;
10816 levels[side + 1] = level * 2;
10817 let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
10818 let negated: Vec<i32> = levels.iter().map(|&l| -l).collect();
10819 let neg =
10820 crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX));
10821 let worst = pos
10822 .iter()
10823 .zip(&neg)
10824 .map(|(&p, &n)| (p + n).abs())
10825 .max()
10826 .expect("the block is not empty");
10827 assert!(worst <= 1, "side {side} level {level}: off by {worst}");
10828 }
10829 }
10830 }
10831
10832 /// The pinned tables above are DC-only, and a flat residual cannot tell a
10833 /// correct butterfly network from one that is merely correct at DC. This
10834 /// is the same claim against a real decoder and with real AC content: the
10835 /// top-left block of a key frame predicts a flat mid-grey with no
10836 /// neighbours to read, so what ffmpeg shows there is exactly 128 plus the
10837 /// residual the encoder's own inverse transform computes. Every sample has
10838 /// to agree, not most of them.
10839 #[test]
10840 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
10841 if !have_ffmpeg() {
10842 eprintln!(
10843 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg"
10844 );
10845 return;
10846 }
10847 // A DC, two low-frequency terms of each orientation, a diagonal and a
10848 // far corner, with both signs among them.
10849 let coeffs = [
10850 (0u8, 0u8, 9i32),
10851 (0, 1, -14),
10852 (1, 0, 7),
10853 (0, 3, 5),
10854 (3, 0, -3),
10855 (2, 2, 11),
10856 (7, 5, -6),
10857 (31, 31, 4),
10858 ];
10859 let block: BlockCoeffs = coeffs
10860 .iter()
10861 .map(|&(row, col, level)| Coeff { row, col, level })
10862 .collect::<Vec<_>>()
10863 .into();
10864 let rows = decode_luma_at(
10865 64,
10866 64,
10867 &[
10868 block,
10869 BlockCoeffs::default(),
10870 BlockCoeffs::default(),
10871 BlockCoeffs::default(),
10872 ],
10873 );
10874
10875 let mut levels = vec![0i32; 32 * 32];
10876 for &(row, col, level) in &coeffs {
10877 levels[usize::from(row) * 32 + usize::from(col)] = level;
10878 }
10879 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
10880 for row in 0..32 {
10881 for col in 0..32 {
10882 let want = (128 + residual[row * 32 + col]).clamp(0, 255);
10883 assert_eq!(
10884 i32::from(rows[row][col]),
10885 want,
10886 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
10887 rows[row][col]
10888 );
10889 }
10890 }
10891 // The block is not flat, so the agreement is about the transform and
10892 // not about a prediction both sides got trivially right.
10893 let (lo, hi) = (
10894 rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(),
10895 rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(),
10896 );
10897 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
10898 }
10899
10900 /// The same against the smallest transform the writer codes, the 16x16 one
10901 /// a split quadrant carries. Its rounding is the one the split path rests
10902 /// on, and nothing else in the crate exercises it against a decoder.
10903 #[test]
10904 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
10905 if !have_ffmpeg() {
10906 eprintln!(
10907 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
10908 );
10909 return;
10910 }
10911 let coeffs = [
10912 (0u8, 0u8, 9i32),
10913 (0, 1, -14),
10914 (1, 0, 7),
10915 (0, 3, 5),
10916 (3, 0, -3),
10917 (2, 2, 11),
10918 (7, 5, -6),
10919 (15, 15, 4),
10920 ];
10921 let block: BlockCoeffs = coeffs
10922 .iter()
10923 .map(|&(row, col, level)| Coeff { row, col, level })
10924 .collect::<Vec<_>>()
10925 .into();
10926 let (seq, header) = frame_of(64, 64);
10927 let quadrants = vec![
10928 Quadrant::Split(vec![
10929 block,
10930 BlockCoeffs::default(),
10931 BlockCoeffs::default(),
10932 BlockCoeffs::default(),
10933 ]),
10934 Quadrant::Whole(BlockCoeffs::default()),
10935 Quadrant::Whole(BlockCoeffs::default()),
10936 Quadrant::Whole(BlockCoeffs::default()),
10937 ];
10938 let tile = sb_coeff_key_frame_tile(
10939 header.mi_cols,
10940 header.mi_rows,
10941 Q_IDX,
10942 &[Superblock::Split(quadrants)],
10943 )
10944 .unwrap();
10945 let mut stream = temporal_delimiter();
10946 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
10947 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
10948 let planes = ffmpeg_decode(&stream, 64, 64);
10949
10950 let mut levels = vec![0i32; TX16 * TX16];
10951 for &(row, col, level) in &coeffs {
10952 levels[usize::from(row) * TX16 + usize::from(col)] = level;
10953 }
10954 let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX));
10955 for row in 0..TX16 {
10956 for col in 0..TX16 {
10957 let want = (128 + residual[row * TX16 + col]).clamp(0, 255);
10958 assert_eq!(
10959 i32::from(planes[row * 64 + col]),
10960 want,
10961 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
10962 planes[row * 64 + col]
10963 );
10964 }
10965 }
10966 }
10967
10968 /// The same against the other transform size, the 64x64 one a whole
10969 /// superblock carries. Only its top-left 32x32 can hold coefficients, and
10970 /// the spec zeroes the rest before the row transform — a 64-point network
10971 /// that read the missing half as anything else would disagree here.
10972 #[test]
10973 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {
10974 if !have_ffmpeg() {
10975 eprintln!(
10976 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg"
10977 );
10978 return;
10979 }
10980 let coeffs = [
10981 (0u8, 0u8, 12i32),
10982 (0, 2, -9),
10983 (2, 0, 6),
10984 (1, 1, -5),
10985 (5, 9, 8),
10986 (31, 0, -4),
10987 (0, 31, 3),
10988 ];
10989 let block: BlockCoeffs = coeffs
10990 .iter()
10991 .map(|&(row, col, level)| Coeff { row, col, level })
10992 .collect::<Vec<_>>()
10993 .into();
10994 let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]);
10995
10996 let mut levels = vec![0i32; 64 * 64];
10997 for &(row, col, level) in &coeffs {
10998 levels[usize::from(row) * 64 + usize::from(col)] = level;
10999 }
11000 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
11001 for row in 0..64 {
11002 for col in 0..64 {
11003 let want = (128 + residual[row * 64 + col]).clamp(0, 255);
11004 assert_eq!(
11005 i32::from(rows[row][col]),
11006 want,
11007 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
11008 rows[row][col]
11009 );
11010 }
11011 }
11012 }
11013
11014 /// The AV1 transforms are normalized so that a quantized level means the
11015 /// same thing at every size: doubling the transform's side halves what a
11016 /// DC level is worth, which is the job the per-size row shift and the
11017 /// dequantizer's denominator split between them. The frame syntax only
11018 /// codes 32x32 and 64x64 transforms, so this is what holds the four
11019 /// smaller sizes' shifts to the spec's table — a shift wrong by one at any
11020 /// size doubles or halves that size's step alone.
11021 #[test]
11022 fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() {
11023 let mut previous: Option<i32> = None;
11024 for side in [4usize, 8, 16, 32, 64] {
11025 let mut levels = vec![0i32; side * side];
11026 levels[0] = 100;
11027 let residual =
11028 crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
11029 let dc = residual[0];
11030 assert!(
11031 residual.iter().all(|&r| r == dc),
11032 "side {side}: a DC coefficient reconstructs flat"
11033 );
11034 if let Some(previous) = previous {
11035 assert!(
11036 (dc * 2 - previous).abs() <= 1,
11037 "side {side}: {dc} is not half of the previous size's {previous}"
11038 );
11039 }
11040 previous = Some(dc);
11041 }
11042 }
11043
11044 /// The encoder's own round trip, through a real bitstream.
11045 ///
11046 /// A picture is chosen, its residual against the DC prediction of 128 is
11047 /// forward-transformed and quantized, the levels are written into a tile,
11048 /// and ffmpeg decodes it. Two things have to hold: what comes back is
11049 /// exactly what the encoder's own inverse said it would be — sample for
11050 /// sample, which is what lets a rate-distortion loop trust its
11051 /// reconstruction — and it is within a quantizer step of the picture that
11052 /// was asked for, which is what makes the forward transform an encoder
11053 /// rather than a scrambler.
11054 #[test]
11055 fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {
11056 if !have_ffmpeg() {
11057 eprintln!(
11058 "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
11059 );
11060 return;
11061 }
11062 // A gradient, a ripple and a corner patch: low frequencies, a mid one
11063 // and an edge, none of them a basis function of the transform.
11064 let mut residual = vec![0i32; 32 * 32];
11065 for row in 0..32usize {
11066 for col in 0..32usize {
11067 let gradient = row as f64 * 2.0 - 32.0;
11068 let ripple = 25.0
11069 * (col as f64 * std::f64::consts::PI / 6.0).sin()
11070 * (row as f64 * std::f64::consts::PI / 11.0).cos();
11071 let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 };
11072 residual[row * 32 + col] = (gradient + ripple + patch).round() as i32;
11073 }
11074 }
11075
11076 let levels =
11077 crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5);
11078 assert!(
11079 levels.iter().any(|&l| l != 0),
11080 "the picture quantized away entirely"
11081 );
11082 let coded: Vec<Coeff> = levels
11083 .iter()
11084 .enumerate()
11085 .filter(|&(_, &level)| level != 0)
11086 .map(|(i, &level)| Coeff {
11087 row: (i / 32) as u8,
11088 col: (i % 32) as u8,
11089 level,
11090 })
11091 .collect();
11092
11093 let rows = decode_luma_at(
11094 64,
11095 64,
11096 &[
11097 coded.into(),
11098 BlockCoeffs::default(),
11099 BlockCoeffs::default(),
11100 BlockCoeffs::default(),
11101 ],
11102 );
11103 let reconstruction =
11104 crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
11105
11106 let mut squared = 0.0f64;
11107 for row in 0..32 {
11108 for col in 0..32 {
11109 let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255);
11110 assert_eq!(
11111 i32::from(rows[row][col]),
11112 want,
11113 "sample ({row},{col}): the decoder and the encoder disagree"
11114 );
11115 let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]);
11116 squared += error * error;
11117 }
11118 }
11119 let rmse = (squared / 1024.0).sqrt();
11120 // A quantizer step is q/8 in residual units. Rounding to nearest
11121 // spreads the error over a step, and a quarter of one is a bound this
11122 // picture clears with room to spare (2.2 of 14 as written) while a
11123 // forward transform that is merely energy-preserving does not: a
11124 // transposed column pass measures 13.3 here.
11125 let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0;
11126 assert!(
11127 rmse < step / 4.0,
11128 "the decoded picture is {rmse} off, a step being {step}"
11129 );
11130 }
11131
11132 /// The inverse of [`write_mv_component`], mirroring [`SymbolDecoder`]
11133 /// against the spec's own `read_mv_component` pseudocode.
11134 fn decode_mv_component(
11135 dec: &mut crate::msac::tests::SymbolDecoder,
11136 c: &mut MvComponentCdfs,
11137 ) -> i32 {
11138 let sign = dec.symbol(&mut c.sign);
11139 let class = dec.symbol(&mut c.class);
11140 let local = if class == 0 {
11141 let bit = dec.symbol(&mut c.class0_bit);
11142 let fr = dec.symbol(&mut c.class0_fr[bit]);
11143 (bit << 3) | (fr << 1) | 1
11144 } else {
11145 let mut d = 0;
11146 for i in 0..class {
11147 d |= dec.symbol(&mut c.bit[i]) << i;
11148 }
11149 let fr = dec.symbol(&mut c.fr);
11150 (d << 3) | (fr << 1) | 1
11151 };
11152 let mag = mv_class_base(class) + local as i32 + 1;
11153 if sign == 1 {
11154 -mag
11155 } else {
11156 mag
11157 }
11158 }
11159
11160 /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,
11161 /// mirroring the writer's own context tracking (partition, skip,
11162 /// is_inter, and the MV stack) symbol for symbol against a fresh
11163 /// [`Cdfs`], so a desync between the two shows up as a wrong decoded
11164 /// value rather than a silent pass. Every block here is skipped, so no
11165 /// coefficient symbols are read. `wrong_y_mode` swaps in `KF_Y_MODE`'s
11166 /// (0, 0) row for an intra block's mode read, to show that reading the
11167 /// wrong table decodes the wrong mode rather than the one that was
11168 /// written.
11169 ///
11170 /// One decoded block's `(skip, is_inter, mode, mv)` — `mode` is `None`
11171 /// for an inter block, `mv` is `(0, 0)` for an intra one.
11172 type DecodedBlock = (bool, bool, Option<usize>, (i32, i32));
11173
11174 /// Returns the number of symbols and literals read, and each block's
11175 /// decoded state.
11176 fn decode_inter_sb(
11177 data: &[u8],
11178 mi_cols: u32,
11179 mi_rows: u32,
11180 wrong_y_mode: bool,
11181 ) -> (usize, Vec<DecodedBlock>) {
11182 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
11183 let mut cdfs = Cdfs::new(2);
11184 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
11185 let mut above_skip = [false; 2];
11186 let mut left_skip = [false; 2];
11187 let mut above_inter = [false; 2];
11188 let mut left_inter = [false; 2];
11189 let mut count = 0usize;
11190
11191 count += 1;
11192 dec.symbol(&mut cdfs.partition_w64[0]);
11193
11194 let mut results = Vec::new();
11195 for quadrant in 0..4usize {
11196 let (r32, c32) = (quadrant / 2, quadrant % 2);
11197 count += 1;
11198 dec.symbol(&mut cdfs.partition_w32[0]);
11199
11200 let (has_above, has_left) = (r32 > 0, c32 > 0);
11201 let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]);
11202 count += 1;
11203 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
11204
11205 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]);
11206 count += 1;
11207 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
11208
11209 let (mode, mv) = if is_inter {
11210 let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]);
11211 count += 3;
11212 assert_eq!(
11213 dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
11214 0,
11215 "single_ref p1"
11216 );
11217 assert_eq!(
11218 dec.symbol(&mut cdfs.single_ref[sr_ctx][2]),
11219 0,
11220 "single_ref p3"
11221 );
11222 assert_eq!(
11223 dec.symbol(&mut cdfs.single_ref[sr_ctx][3]),
11224 0,
11225 "single_ref p4"
11226 );
11227
11228 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
11229 let stack = find_mv_stack(
11230 &grid,
11231 mi_row,
11232 mi_col,
11233 8,
11234 8,
11235 1,
11236 mi_cols as usize,
11237 mi_rows as usize,
11238 );
11239
11240 count += 1;
11241 let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0;
11242 let (mv, is_new_mv) = if new_mv {
11243 if stack.entries.len() > 1 {
11244 count += 1;
11245 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
11246 }
11247 count += 1;
11248 let joint = dec.symbol(&mut cdfs.mv_joint);
11249 let mut diff = (0, 0);
11250 if joint == 2 || joint == 3 {
11251 // sign, class, class0_bit, class0_fr for this test's
11252 // small (class 0) components.
11253 count += 4;
11254 diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]);
11255 }
11256 if joint == 1 || joint == 3 {
11257 count += 4;
11258 diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]);
11259 }
11260 ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true)
11261 } else {
11262 count += 2;
11263 assert_eq!(
11264 dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]),
11265 1,
11266 "zero_mv"
11267 );
11268 assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv");
11269 (stack.nearest_mv, false)
11270 };
11271 for dr in 0..8 {
11272 for dc in 0..8 {
11273 grid.set(
11274 mi_row + dr,
11275 mi_col + dc,
11276 MiInfo {
11277 is_inter: true,
11278 ref_frame: 1,
11279 ref_frame1: NO_REF1,
11280 mv1: (0, 0),
11281 mv: mv16(mv),
11282 is_new_mv,
11283 size: 8,
11284 size_h: 8,
11285 is_global_mv0: false,
11286 is_global_mv1: false,
11287 },
11288 );
11289 }
11290 }
11291 (None, mv)
11292 } else {
11293 count += 1;
11294 let m = if wrong_y_mode {
11295 dec.symbol(&mut cdfs.kf_y_mode[0][0])
11296 } else {
11297 dec.symbol(&mut cdfs.y_mode[3])
11298 };
11299 if (V_PRED..=D67_PRED).contains(&m) {
11300 count += 1;
11301 dec.symbol(&mut cdfs.angle_delta[m - V_PRED]);
11302 }
11303 count += 1;
11304 dec.symbol(&mut cdfs.uv_mode_cfl[m]);
11305 (Some(m), (0, 0))
11306 };
11307
11308 above_skip[c32] = skip;
11309 left_skip[r32] = skip;
11310 above_inter[c32] = is_inter;
11311 left_inter[r32] = is_inter;
11312 results.push((skip, is_inter, mode, mv));
11313 }
11314 (count, results)
11315 }
11316
11317 /// Every superblock here skips: no residual, so the only symbols are the
11318 /// mode chain, and the byte count and the symbol count both come out
11319 /// small enough to hand-check.
11320 #[test]
11321 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
11322 let block = BlockCoeffs {
11323 inter: Some(InterInfo {
11324 ref1: None,
11325 mv1: (0, 0),
11326 ref_frame: crate::mvstack::LAST_FRAME,
11327 mode: InterMode::NearestMv,
11328 mv: (0, 0),
11329 ref_mv_idx: 0,
11330 }),
11331 skip: true,
11332 ..BlockCoeffs::default()
11333 };
11334 let blocks = vec![
11335 Quadrant::Whole(block.clone()),
11336 Quadrant::Whole(block.clone()),
11337 Quadrant::Whole(block.clone()),
11338 Quadrant::Whole(block),
11339 ];
11340 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11341 // Hand count: one partition_w64, then per block partition_w32 + skip +
11342 // is_inter + 3 single_ref + new_mv + zero_mv + ref_mv = 9, times four.
11343 assert!(
11344 data.len() <= 16,
11345 "an all-skip NEARESTMV superblock took {} bytes",
11346 data.len()
11347 );
11348
11349 let (count, results) = decode_inter_sb(&data, 16, 16, false);
11350 assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count");
11351 for (skip, is_inter, mode, mv) in results {
11352 assert!(skip);
11353 assert!(is_inter);
11354 assert_eq!(mode, None);
11355 // Every block's only inter neighbours carry (0, 0), so the stack's
11356 // nearest candidate is (0, 0) throughout.
11357 assert_eq!(mv, (0, 0));
11358 }
11359 }
11360
11361 /// The fourth block codes NEWMV against a (0, 0) predictor with a coded
11362 /// column component: the symbol sequence a decoder reads back has to be
11363 /// exactly what [`write_mv`] wrote, not a residual that merely decodes
11364 /// to *some* valid vector.
11365 #[test]
11366 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
11367 let nearest = BlockCoeffs {
11368 inter: Some(InterInfo {
11369 ref1: None,
11370 mv1: (0, 0),
11371 ref_frame: crate::mvstack::LAST_FRAME,
11372 mode: InterMode::NearestMv,
11373 mv: (0, 0),
11374 ref_mv_idx: 0,
11375 }),
11376 skip: true,
11377 ..BlockCoeffs::default()
11378 };
11379 let newmv = BlockCoeffs {
11380 inter: Some(InterInfo {
11381 ref1: None,
11382 mv1: (0, 0),
11383 ref_frame: crate::mvstack::LAST_FRAME,
11384 mode: InterMode::NewMv,
11385 mv: (0, 2),
11386 ref_mv_idx: 0,
11387 }),
11388 skip: true,
11389 ..BlockCoeffs::default()
11390 };
11391 let blocks = vec![
11392 Quadrant::Whole(nearest.clone()),
11393 Quadrant::Whole(nearest.clone()),
11394 Quadrant::Whole(nearest),
11395 Quadrant::Whole(newmv),
11396 ];
11397 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11398
11399 let (count, results) = decode_inter_sb(&data, 16, 16, false);
11400 // Three NEARESTMV blocks at 9 symbols each, one NEWMV block at
11401 // partition + skip + is_inter + 3 single_ref + new_mv + mv_joint +
11402 // (sign, class, class0_bit, class0_fr for the one nonzero component)
11403 // = 12, plus the superblock's partition_w64.
11404 assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count");
11405 let (skip, is_inter, mode, mv) = results[3];
11406 assert!(skip);
11407 assert!(is_inter);
11408 assert_eq!(mode, None);
11409 assert_eq!(
11410 mv,
11411 (0, 2),
11412 "the decoded motion vector must be exactly what was written"
11413 );
11414 }
11415
11416 /// Decodes only the first 32x32 block's mode symbol of a superblock: the
11417 /// tile's own first block always reads partition, skip and is_inter at
11418 /// context zero, so this needs none of [`decode_inter_sb`]'s neighbour
11419 /// bookkeeping — which matters here because the mutation this feeds
11420 /// desyncs everything after the one symbol it is testing, and a decoder
11421 /// that kept reading past it would be asserting on garbage.
11422 fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize {
11423 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
11424 let mut cdfs = Cdfs::new(2);
11425 dec.symbol(&mut cdfs.partition_w64[0]);
11426 dec.symbol(&mut cdfs.partition_w32[0]);
11427 dec.symbol(&mut cdfs.skip[0]);
11428 dec.symbol(&mut cdfs.intra_inter[0]);
11429 if wrong_y_mode {
11430 dec.symbol(&mut cdfs.kf_y_mode[0][0])
11431 } else {
11432 dec.symbol(&mut cdfs.y_mode[3])
11433 }
11434 }
11435
11436 /// An inter frame's intra block reads its mode against `Y_MODE`'s size
11437 /// group, not `KF_Y_MODE`'s neighbour-context table a key frame's block
11438 /// reads. Reading the wrong table back — `KF_Y_MODE`'s `(0, 0)` row —
11439 /// decodes a different mode than the one [`sb_coeff_inter_frame_tile`]
11440 /// wrote, because the two tables carry different default probabilities
11441 /// even though a row of each is the same fourteen-entry width. (The swap
11442 /// this test's name warns of does not typecheck as a one-line
11443 /// substitution at the write site either — `cdfs.kf_y_mode[3]` is a
11444 /// `[[u16; 14]; 5]` row, not the single `[u16; 14]` `Y_MODE` indexing
11445 /// needs — so a mutation that got the *outer* shape wrong would be
11446 /// caught by `cargo check` before it ever reached a test; this test is
11447 /// what catches getting the *right* leaf shape from the *wrong* table.)
11448 #[test]
11449 fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() {
11450 let block = BlockCoeffs {
11451 mode: H_PRED as u8,
11452 skip: true,
11453 ..BlockCoeffs::default()
11454 };
11455 let blocks = vec![Quadrant::Whole(block); 4];
11456 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11457
11458 assert_eq!(
11459 decode_first_block_mode(&data, false),
11460 H_PRED,
11461 "the right table reads the mode back exactly"
11462 );
11463 assert_ne!(
11464 decode_first_block_mode(&data, true),
11465 H_PRED,
11466 "KF_Y_MODE's different probabilities must decode a different mode"
11467 );
11468 }
11469
11470 /// lane-rectdq witness: [`crate::encode::delta_q_bits`] prices exactly
11471 /// what [`write_delta_q`] writes, over the whole `delta_q_abs` domain
11472 /// (0..=20 steps, both signs -- the escape literal pair starts at 3 and
11473 /// its `rem_bits` widens at 4, 5, 9 and 17). The writer is run into a
11474 /// PRICING coder whose account (`SymbolEncoder::bits`) is the same
11475 /// arithmetic-coder cost the pricer's `symbol_bits` sums, so the two
11476 /// agree to floating-point noise, not to a tolerance band.
11477 ///
11478 /// Both sides read the DEFAULT `delta_q` row: the writer's `cdfs` is
11479 /// rebuilt per case, exactly as every tile's is armed before its first
11480 /// superblock.
11481 #[test]
11482 fn the_delta_q_pricer_matches_the_writer_over_the_whole_domain() {
11483 const RES: i32 = 4;
11484 const CUR: i32 = 128;
11485 for steps in -20i32..=20 {
11486 let target = CUR + steps * RES;
11487 arm_delta_q(RES, 1, vec![u8::try_from(target).expect("in range")], 128);
11488 let mut cdfs = Cdfs::new(2);
11489 let mut enc = SymbolEncoder::pricer();
11490 enc.reset_bits();
11491 // `is_whole_sb = false`: the rect half / 64-superblock shape,
11492 // the one whose pricer this witnesses.
11493 write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
11494 let written = enc.bits();
11495 let priced = crate::encode::delta_q_bits(target, CUR, RES);
11496 assert!(
11497 (written - priced).abs() < 1e-9,
11498 "steps {steps}: writer {written} bits, pricer {priced}"
11499 );
11500 }
11501 // Disarmed plan: the writer codes nothing and the pricer charges
11502 // nothing.
11503 arm_delta_q(0, 1, Vec::new(), 128);
11504 let mut cdfs = Cdfs::new(2);
11505 let mut enc = SymbolEncoder::pricer();
11506 enc.reset_bits();
11507 write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
11508 assert!(enc.bits().abs() < 1e-9, "a disarmed plan writes no symbol");
11509 assert!((crate::encode::delta_q_bits(200, 128, 0)).abs() < 1e-9);
11510 }
11511}