forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

tile.rs11205 lines, 468.4 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::LazyLock;
16use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
17
18use ec_core::{Error, Result};
19
20use crate::cdf;
21use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
22use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
23use crate::msac::SymbolEncoder;
24use crate::transform::TxType;
25use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};
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| {
390 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec()
391 })
392 .collect()
393 };
394 let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
395 for (cr, cc) in CHUNKS {
396 let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
397 // The luma unit: its own `txb_skip_ctx` is the neighbour
398 // magnitude table (the unit is smaller than its block), and it
399 // publishes its context before the next chunk reads it.
400 let luma = unit_of(0, cr, cc);
401 let skip_ctx = neighbours.luma_skip_ctx(unit_mi, 64 / MI);
402 let around = neighbours.around_mi(unit_mi, 64);
403 write_coeffs(
404 enc,
405 &mut cdfs.txb(TxbSet::Luma64, 0),
406 &luma,
407 &scan32,
408 skip_ctx,
409 dc_sign_ctx(around[0].dc_vote),
410 Some(0),
411 TxType::DctDct,
412 );
413 neighbours.record_mi_luma(unit_mi, 64, &luma);
414 // Then this chunk's chroma pair, before the next chunk's luma:
415 // libaom codes every plane of a mu chunk before moving on. The
416 // chroma `txb_skip_ctx` takes `get_txb_ctx`'s offset-10 rows
417 // (+3 here) because the uv plane block is bigger than the unit.
418 let mut pair = [Vec::new(), Vec::new()];
419 for plane in 1..3usize {
420 let grid = unit_of(plane, cr, cc);
421 let around = neighbours.around_mi(unit_mi, 64)[plane];
422 write_coeffs(
423 enc,
424 &mut cdfs.txb(TxbSet::Chroma32, 0),
425 &grid,
426 &scan32,
427 usize::from(around.above_coded) + usize::from(around.left_coded) + 3,
428 dc_sign_ctx(around.dc_vote),
429 Some(plane),
430 TxType::DctDct,
431 );
432 neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
433 pair[plane - 1] = grid;
434 }
435 chroma_units.push((unit_mi, pair));
436 }
437 // decode.rs' own tail (`record_split_luma_rect_mi` then the
438 // `mu_chroma_units` re-stamp): the block-level write off the WHOLE
439 // assembled chroma plane grid, luma kept because each unit already
440 // published its own, and then the per-unit chroma writes replayed
441 // over it -- last writer wins, so the next block reads the units.
442 let block_grids = [
443 vec![0i32; TX32 * TX32],
444 packed[1].clone(),
445 packed[2].clone(),
446 ];
447 neighbours.record_planes(sb_at, SIDE, 0, &block_grids, false);
448 for (unit_mi, pair) in &chroma_units {
449 neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
450 neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
451 }
452 } else {
453 neighbours.record(sb_at, SIDE, 0, &zero_grids);
454 }
455 neighbours.record_inter(sb_at, SIDE, block.skip, true, block_ref(block));
456 record_block_compound(neighbours, (mi_r, mi_c), SIDE, block);
457 SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
458 if !block.skip {
459 SB128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
460 }
461 if info.ref1.is_some() {
462 SB128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
463 }
464 Ok(())
465}
466
467/// lane-b128hv: one 128x64 (HORZ) or 64x128 (VERT) inter block, the two
468/// halves a `PARTITION_HORZ`/`PARTITION_VERT` 128 superblock root carries --
469/// the syntax `decode_inter_block` reads for `sb128_rect` (decode.rs ~35343):
470/// the same chain [`write_inter_block_128`] writes, at the block's own
471/// rectangular window. Every CDF/context decision is taken at the enclosing
472/// square `side` of 128 (what the decoder's `inter_piece!` passes), and the
473/// block's true footprint governs only its mv-stack window, its mi/grid stamp
474/// and its neighbour bands (decode.rs' own `write_w`/`write_h` split).
475///
476/// lane-ab128: also the two 64x64 squares an AB shape codes (the `w == h`
477/// arm below) and its 128x64 / 64x128 half.
478///
479/// lane-rectres: a piece may CARRY A RESIDUAL -- the search only ever hands
480/// one over under `EC_AV1_RECTRES` ([`crate::encode::rectres`]), and then it
481/// is coded here exactly as `decode_inter_block` reads it: one TX_64X64 luma
482/// unit plus a TX_32X32 chroma pair per 64x64 mu chunk (two chunks for a
483/// half, one for a square), each depth-0 in the var-tx tree (a half codes
484/// two `txfm_partition` flags under `TxMode::Select`, a square one).
485///
486/// # Errors
487/// A block that is intra.
488#[allow(clippy::too_many_arguments)]
489fn write_inter_block_128_rect(
490 enc: &mut SymbolEncoder,
491 cdfs: &mut Cdfs,
492 neighbours: &mut Neighbours,
493 grid: &mut MiGrid,
494 // The half's own top-left position in mode-info (4x4) units.
495 at_mi: (usize, usize),
496 // Its true footprint in samples: (128, 64) at HORZ, (64, 128) at VERT.
497 (w, h): (usize, usize),
498 block: &BlockCoeffs,
499 mi_cols: u32,
500 mi_rows: u32,
501 tx_select: bool,
502) -> Result<()> {
503 let info = block.inter.ok_or_else(|| {
504 Error::unsupported("AV1 tile", "a 128-root rectangular half is coded inter")
505 })?;
506 let (mi_r, mi_c) = at_mi;
507 let (w_mi, h_mi) = (w / MI, h / MI);
508 let has_above = neighbours.has_above(mi_r);
509 let has_left = neighbours.has_left(mi_c);
510 let skip_ctx =
511 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
512 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
513 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
514 // NOT a whole superblock: decode.rs' `whole_sb` is `write_w == write_h ==
515 // sb_px`, so a rect half reads its `delta_q` group even when skipped.
516 write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
517 let ii_ctx = intra_inter_ctx(
518 has_above,
519 has_left,
520 neighbours.above_inter[mi_c],
521 neighbours.left_inter[mi_r],
522 );
523 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
524 write_comp_mode(
525 enc,
526 cdfs,
527 neighbours,
528 (mi_r, mi_c),
529 (has_above, has_left),
530 info.ref1.is_some(),
531 );
532 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
533 write_compound_block(
534 enc,
535 cdfs,
536 neighbours,
537 grid,
538 (mi_r, mi_c),
539 (w_mi, h_mi),
540 (has_above, has_left),
541 info,
542 (mi_cols as usize, mi_rows as usize),
543 )?
544 } else {
545 write_single_ref(
546 enc,
547 cdfs,
548 info.ref_frame,
549 neighbours.above_ref[mi_c],
550 neighbours.above_ref1[mi_c],
551 neighbours.left_ref[mi_r],
552 neighbours.left_ref1[mi_r],
553 );
554 let stack = find_mv_stack(
555 grid,
556 mi_r,
557 mi_c,
558 w_mi,
559 h_mi,
560 info.ref_frame,
561 mi_cols as usize,
562 mi_rows as usize,
563 );
564 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
565 (mv, (0, 0), is_new_mv)
566 };
567 for dr in 0..h_mi {
568 for dc in 0..w_mi {
569 grid.set(
570 mi_r + dr,
571 mi_c + dc,
572 MiInfo {
573 is_inter: true,
574 ref_frame: info.ref_frame,
575 ref_frame1: info.ref1.unwrap_or(NO_REF1),
576 mv1: mv16(mv1),
577 mv: mv16(mv),
578 is_new_mv,
579 size: w_mi as u8,
580 size_h: h_mi as u8,
581 is_global_mv0: false,
582 is_global_mv1: false,
583 },
584 );
585 }
586 }
587 if info.ref1.is_none() {
588 write_motion_mode(
589 enc,
590 cdfs,
591 grid,
592 (mi_r, mi_c),
593 (w_mi, h_mi),
594 (w, h),
595 (mi_cols as usize, mi_rows as usize),
596 info.ref_frame,
597 block.motion_mode,
598 )?;
599 }
600 // The 64x64 mu chunks the residual is coded in, raster order -- the
601 // decoder's own walk: two for a half, one for a square piece.
602 let chunks: &[(usize, usize)] = match (w, h) {
603 (128, 64) => &[(0, 0), (0, 1)],
604 (64, 128) => &[(0, 0), (1, 0)],
605 _ => &[(0, 0)],
606 };
607 // A half's uv plane block (64x32 / 32x64) is wider or taller than its
608 // 32x32 unit, so the unit's `txb_skip_ctx` takes `get_txb_ctx`'s
609 // offset-10 rows (+3 here); a 64x64 piece's uv block IS the unit and
610 // takes none. The half is also the only shape whose chroma is re-stamped
611 // per mu chunk at the end (decode.rs' `mu_chroma`).
612 let is_half = w.max(h) > 64;
613 if tx_select {
614 if block.skip {
615 // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect`
616 // with the BLOCK's own size in both bands, no symbol.
617 neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h));
618 } else if is_half {
619 // The var-tx tree of a 128x64 / 64x128 block enters at TX_64X64
620 // once per mu chunk (`read_block_tx_size_rect`'s `max_tx = 64`
621 // loop), so it is two depth-0 `txfm_split` flags of zero, each
622 // read against the bands the chunks before it published.
623 for &(cr, cc) in chunks {
624 let unit = (mi_r + cr * 16, mi_c + cc * 16);
625 let ctx = txfm_partition_ctx_rect(
626 neighbours.above_txfm[unit.1],
627 neighbours.left_txfm[unit.0],
628 w.max(h),
629 64,
630 64,
631 );
632 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
633 neighbours.record_txfm(unit, 64, 64, 64);
634 }
635 } else {
636 // A 64x64 piece is one whole TX_64X64: the single depth-0 flag
637 // the 64 root's own writer codes (`write_tx_syntax_inter`).
638 write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SB, true, false, 0);
639 }
640 }
641 let zero_grids = [
642 vec![0i32; TX32 * TX32],
643 vec![0i32; TX32 * TX32],
644 vec![0i32; TX32 * TX32],
645 ];
646 // A 128 root's half is always SUB (16 px) aligned, so the coarse mode /
647 // side bands are named by the same SUB-grid origin every square block
648 // uses.
649 let at_sub = (mi_r / (SUB / MI), mi_c / (SUB / MI));
650 if !block.skip {
651 // lane-rectres: the packed 64-wide level grids the search hands over,
652 // one plane each (the same layout `write_inter_block_128` slices for
653 // the whole block, here with the piece's own chunk list).
654 let packed = [
655 level_grid(&block.luma, 64)?,
656 level_grid(&block.u, 64)?,
657 level_grid(&block.v, 64)?,
658 ];
659 let scan32 = default_scan(TX32);
660 let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec<i32> {
661 (0..32)
662 .flat_map(|row| {
663 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec()
664 })
665 .collect()
666 };
667 let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
668 for &(cr, cc) in chunks {
669 let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
670 // The luma unit, and the context its all-zero flag reads: a
671 // HALF's unit is smaller than its block (neighbour magnitude
672 // table), a square's IS the whole plane block (fixed zero --
673 // `read_inter_plane`'s `luma_skip_ctx.unwrap_or(0)`, the 64
674 // root's own writer rule). It publishes its context before the
675 // next chunk reads it.
676 let luma = unit_of(0, cr, cc);
677 let skip_ctx = if is_half {
678 neighbours.luma_skip_ctx(unit_mi, 64 / MI)
679 } else {
680 0
681 };
682 let around = neighbours.around_mi(unit_mi, 64);
683 write_coeffs(
684 enc,
685 &mut cdfs.txb(TxbSet::Luma64, 0),
686 &luma,
687 &scan32,
688 skip_ctx,
689 dc_sign_ctx(around[0].dc_vote),
690 Some(0),
691 TxType::DctDct,
692 );
693 neighbours.record_mi_luma(unit_mi, 64, &luma);
694 // Then this chunk's chroma pair, before the next chunk's luma:
695 // libaom codes every plane of a mu chunk before moving on.
696 let mut pair = [Vec::new(), Vec::new()];
697 for plane in 1..3usize {
698 let grid = unit_of(plane, cr, cc);
699 let around = neighbours.around_mi(unit_mi, 64)[plane];
700 write_coeffs(
701 enc,
702 &mut cdfs.txb(TxbSet::Chroma32, 0),
703 &grid,
704 &scan32,
705 usize::from(around.above_coded) + usize::from(around.left_coded)
706 + 3 * usize::from(is_half),
707 dc_sign_ctx(around.dc_vote),
708 Some(plane),
709 TxType::DctDct,
710 );
711 neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
712 pair[plane - 1] = grid;
713 }
714 chroma_units.push((unit_mi, pair));
715 }
716 // decode.rs' own tail (`record_split_luma_rect_mi` then, on a half,
717 // the per-chunk chroma re-stamp): the block-level write off the
718 // whole assembled chroma plane grid, luma kept because each unit
719 // already published its own, and then the per-unit chroma writes
720 // replayed over it -- last writer wins, so the next block reads the
721 // units.
722 let block_grids = [
723 vec![0i32; TX32 * TX32],
724 packed[1].clone(),
725 packed[2].clone(),
726 ];
727 neighbours.record_planes_rect(at_sub, (w, h), 0, &block_grids, false);
728 if is_half {
729 for (unit_mi, pair) in &chroma_units {
730 neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
731 neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
732 }
733 }
734 SB128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
735 } else {
736 neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
737 }
738 neighbours.record_inter_rect_mi((mi_r, mi_c), (w, h), block.skip, true, block_ref(block));
739 if let Some(r1) = info.ref1 {
740 neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1);
741 }
742 // lane-ab128: an AB shape codes its two 64x64 pieces through this same
743 // function, and they are neither a 128x64 nor a 64x128 half -- the
744 // witness reads these two counters for the HORZ/VERT shape alone.
745 if w > h {
746 SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
747 } else if h > w {
748 SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
749 }
750 Ok(())
751}
752
753/// lane-b128hv: how many 128x64 / 64x128 halves the inter writer has coded
754/// since the last [`take_sb128_horz_hits`] / [`take_sb128_vert_hits`] (class
755/// `gate-blind-to-feature`).
756static SB128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
757/// The VERT twin of [`SB128_HORZ_HITS`].
758static SB128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
759
760/// The 128x64-half count since the last call, and zero it.
761pub fn take_sb128_horz_hits() -> usize {
762 SB128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
763}
764
765/// The 64x128-half count since the last call, and zero it.
766pub fn take_sb128_vert_hits() -> usize {
767 SB128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
768}
769
770/// lane-ab128: how many AB-shape roots the inter writer has coded since the
771/// last [`take_sb128_ab_hits`], in `PARTITION_HORZ_A` .. `_VERT_B` order
772/// (class `gate-blind-to-feature`).
773static SB128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
774 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
775
776/// The four per-shape AB-root counts since the last call, and zero them.
777pub fn take_sb128_ab_hits() -> [usize; 4] {
778 std::array::from_fn(|i| SB128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
779}
780
781/// lane-b128r: how many of those blocks carried a REAL residual (four
782/// TX_64X64 luma units plus their per-chunk chroma pair) rather than being
783/// skipped, since the last [`take_sb128_residual_hits`].
784static SB128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
785 std::sync::atomic::AtomicUsize::new(0);
786
787/// The 128x128-with-residual count since the last call, and zero it.
788pub fn take_sb128_residual_hits() -> usize {
789 SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
790}
791/// lane-rectres: how many RECT/AB pieces (the halves and 64x64 squares
792/// [`write_inter_block_128_rect`] codes) carried a REAL residual rather than
793/// being skipped, since the last [`take_sb128_rectres_hits`] -- the writer
794/// side of [`crate::encode::take_b128_rectres_hits`]'s search count.
795static SB128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
796 std::sync::atomic::AtomicUsize::new(0);
797
798/// The rect/AB-piece-with-residual count since the last call, and zero it.
799pub fn take_sb128_rectres_hits() -> usize {
800 SB128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
801}
802
803/// lane-b128r: how many of those blocks named a SECOND reference (the
804/// compound arm at the 128 root), since the last
805/// [`take_sb128_compound_hits`].
806static SB128_COMPOUND_HITS: std::sync::atomic::AtomicUsize =
807 std::sync::atomic::AtomicUsize::new(0);
808
809/// The compound-128 count since the last call, and zero it.
810pub fn take_sb128_compound_hits() -> usize {
811 SB128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
812}
813
814/// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since
815/// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).
816static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
817
818/// The 128x128-block count since the last call, and zero it.
819pub fn take_sb128_none_hits() -> usize {
820 SB128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
821}
822
823/// `read_lr`'s write side, called once at the top of every superblock,
824/// before its partition symbol: writes the units this superblock's own
825/// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
826/// column scaling is the plain mi one).
827fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32, span: u32) {
828 LR_PLAN.with(|c| {
829 let mut plan = c.borrow_mut();
830 let Some(plan) = plan.as_mut() else { return };
831 let unit = plan.unit_size;
832 let rcol0 = (mi_col * 4).div_ceil(unit);
833 let rcol1 = ((mi_col + span) * 4).div_ceil(unit).min(plan.horz_units);
834 let rrow0 = (mi_row * 4).div_ceil(unit);
835 let rrow1 = ((mi_row + span) * 4).div_ceil(unit).min(plan.vert_units);
836 for rrow in rrow0..rrow1 {
837 for rcol in rcol0..rcol1 {
838 let info = plan.units[(rcol + rrow * plan.horz_units) as usize];
839 enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener);
840 if let Some(info) = info {
841 crate::restoration::write_wiener_filter(
842 enc,
843 false,
844 &mut plan.reference,
845 &info,
846 );
847 }
848 }
849 }
850 });
851}
852
853/// A 64x64 superblock's width in 4x4 mode-info units (`SB_MI` in
854/// `crate::decode`), the span [`write_lr`] resolves its units over.
855const SB_MI_W: u32 = 16;
856
857/// One tile's own superblock and mode-info span (spec 5.11.1's tile loop
858/// bounds): `MiColStarts[i]..MiColStarts[i+1]` and the same down the rows,
859/// with the superblock indices those mi bounds fall on. The writers walk
860/// exactly this rect, and everything a block reads outside it -- the
861/// neighbour bands, the MV grid -- is left at the "unavailable" state a
862/// tile's own first row and column see, which is how the decoder clips them
863/// (`MiGrid::set_tile_bounds`, `PlaneBuf::set_tile_origin`).
864#[derive(Clone, Copy, Debug, PartialEq, Eq)]
865pub(crate) struct TileRect {
866 pub(crate) sb_col0: u32,
867 pub(crate) sb_col1: u32,
868 pub(crate) sb_row0: u32,
869 pub(crate) sb_row1: u32,
870 pub(crate) mi_col0: u32,
871 pub(crate) mi_col1: u32,
872 pub(crate) mi_row0: u32,
873 pub(crate) mi_row1: u32,
874}
875
876impl TileRect {
877 /// The whole frame as one tile -- what every single-tile caller writes.
878 pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self {
879 let (cols, rows) = block_grid(mi_cols, mi_rows);
880 Self {
881 sb_col0: 0,
882 sb_col1: cols.div_ceil(2),
883 sb_row0: 0,
884 sb_row1: rows.div_ceil(2),
885 mi_col0: 0,
886 mi_col1: mi_cols,
887 mi_row0: 0,
888 mi_row1: mi_rows,
889 }
890 }
891}
892
893/// A frame's uniform tile grid (spec 5.9.15's `uniform_tile_spacing_flag`
894/// arm, mirrored from `ec_av1_syntax::frame::read_tile_info` so that what
895/// this encoder writes and what a decoder derives from the same two log2
896/// fields are the same rects). 64x64 superblocks only, which is the only
897/// size this encoder's sequence header signals.
898#[derive(Clone, Debug)]
899pub(crate) struct TileLayout {
900 pub(crate) cols_log2: u32,
901 pub(crate) rows_log2: u32,
902 /// Tile column starts in superblocks, `cols + 1` entries.
903 col_starts_sb: Vec<u32>,
904 /// Tile row starts in superblocks, `rows + 1` entries.
905 row_starts_sb: Vec<u32>,
906 mi_cols: u32,
907 mi_rows: u32,
908}
909
910impl TileLayout {
911 /// The layout `cols_log2`/`rows_log2` name for this frame's mi grid.
912 pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self {
913 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
914 let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2));
915 // lane-sb128: a tile boundary is a SUPERBLOCK boundary, so under a
916 // 128 superblock the starts are laid out on the 128 grid and then
917 // doubled back into the 64-cell units the writers walk.
918 let unit = u32::from(crate::encode::sb128_on()) + 1;
919 let starts = |total: u32, log2: u32| {
920 let total128 = total.div_ceil(unit);
921 let step = total128.div_ceil(1 << log2).max(1);
922 let mut v: Vec<u32> = (0..total128).step_by(step as usize).map(|s| s * unit).collect();
923 v.push(total);
924 v
925 };
926 Self {
927 cols_log2,
928 rows_log2,
929 col_starts_sb: starts(sb_cols, cols_log2),
930 row_starts_sb: starts(sb_rows, rows_log2),
931 mi_cols,
932 mi_rows,
933 }
934 }
935
936 pub(crate) fn cols(&self) -> u32 {
937 self.col_starts_sb.len() as u32 - 1
938 }
939
940 pub(crate) fn rows(&self) -> u32 {
941 self.row_starts_sb.len() as u32 - 1
942 }
943
944 pub(crate) fn count(&self) -> usize {
945 (self.cols() * self.rows()) as usize
946 }
947
948 /// `MiColStarts`/`MiRowStarts` as the frame header carries them.
949 pub(crate) fn mi_col_starts(&self) -> Vec<u32> {
950 let mut v: Vec<u32> = self.col_starts_sb[..self.cols() as usize]
951 .iter()
952 .map(|sb| sb * SB_MI_W)
953 .collect();
954 v.push(self.mi_cols);
955 v
956 }
957
958 pub(crate) fn mi_row_starts(&self) -> Vec<u32> {
959 let mut v: Vec<u32> = self.row_starts_sb[..self.rows() as usize]
960 .iter()
961 .map(|sb| sb * SB_MI_W)
962 .collect();
963 v.push(self.mi_rows);
964 v
965 }
966
967 /// Tile `index` (row major, `TileNum`) as a rect.
968 pub(crate) fn rect(&self, index: usize) -> TileRect {
969 let (r, c) = (index / self.cols() as usize, index % self.cols() as usize);
970 let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]);
971 let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]);
972 TileRect {
973 sb_col0,
974 sb_col1,
975 sb_row0,
976 sb_row1,
977 mi_col0: sb_col0 * SB_MI_W,
978 mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols),
979 mi_row0: sb_row0 * SB_MI_W,
980 mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows),
981 }
982 }
983
984 /// The largest tile by mi area, `context_update_tile_id`'s own rule
985 /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both
986 /// name the biggest tile, whose end-of-tile tables the frame stores).
987 pub(crate) fn largest_tile(&self) -> usize {
988 (0..self.count())
989 .max_by_key(|&i| {
990 let t = self.rect(i);
991 ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64)
992 })
993 .unwrap_or(0)
994 }
995}
996
997/// lane-edge128: which 64x64 CDEF unit's `cdef_idx` literal covers each unit
998/// of this frame, in the same raster order [`arm_cdef_idx`]'s grid is in.
999///
1000/// `read_cdef` (spec 5.11.56) codes ONE literal for the block that first
1001/// reaches a unit and copies it over every unit that block SPANS, so a whole
1002/// 128x128 root block puts one literal in the stream for all four of its
1003/// units -- the encoder's CDEF search, which prices a preset per unit, may
1004/// not hand those four units different presets: only the first would be
1005/// coded, and every decoder (ours and ffmpeg's alike) would apply it to all
1006/// four while the encoder's own filter replay applied four different ones.
1007/// That is the shape this map exists to collapse
1008/// ([`crate::filter_search::pick_filters`]).
1009///
1010/// lane-rectres: the same holds for a Rect128 half or an Ab128 half that
1011/// carries a residual (`EC_AV1_RECTRES`) -- it codes one literal at its own
1012/// origin and the decoder stamps BOTH units it spans with it, so its pair is
1013/// collapsed onto the origin unit too. Its 64x64 squares cover exactly one
1014/// unit each, and a SKIP-ONLY rect/AB piece codes no literal at all (the
1015/// decoder's per-piece `cdef_transmitted` reset never fires), so neither
1016/// touches this map -- only pieces the writer really codes a residual for.
1017pub(crate) fn cdef_unit_owner(blocks: &[Quadrant], mi_cols: u32, mi_rows: u32) -> Vec<u32> {
1018 let (cols, rows) = block_grid(mi_cols, mi_rows);
1019 let (sb_cols, sb_rows) = (cols.div_ceil(2) as usize, rows.div_ceil(2) as usize);
1020 let mut owner: Vec<u32> = (0..(sb_cols * sb_rows) as u32).collect();
1021 // Collapses every 64x64 unit `(ur, uc) ..` a residual piece at unit
1022 // `(ur, uc)` with footprint `(w, h)` spans onto the piece's origin --
1023 // [`crate::encode::write_inter_block_128_rect`]'s one `write_cdef_idx`
1024 // is what the decoder copies over all of them.
1025 let collapse = |owner: &mut Vec<u32>, (ur, uc): (usize, usize), (w, h): (usize, usize)| {
1026 let origin = (ur * sb_cols + uc) as u32;
1027 for r in ur..(ur + (h / 64).max(1)).min(sb_rows) {
1028 for c in uc..(uc + (w / 64).max(1)).min(sb_cols) {
1029 owner[r * sb_cols + c] = origin;
1030 }
1031 }
1032 };
1033 for sb_r in (0..sb_rows).step_by(2) {
1034 for sb_c in (0..sb_cols).step_by(2) {
1035 let Some(root) = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize)
1036 .then(|| &blocks[(sb_r * 2) * cols as usize + sb_c * 2])
1037 else {
1038 continue;
1039 };
1040 match root {
1041 Quadrant::Whole128(_) => {
1042 let origin = (sb_r * sb_cols + sb_c) as u32;
1043 for r in sb_r..(sb_r + 2).min(sb_rows) {
1044 for c in sb_c..(sb_c + 2).min(sb_cols) {
1045 owner[r * sb_cols + c] = origin;
1046 }
1047 }
1048 }
1049 // lane-rectres: the two halves of a HORZ/VERT root sit in
1050 // different unit rows (HORZ) / columns (VERT); each
1051 // non-skip half collapses its own pair.
1052 Quadrant::Rect128(horz, halves) => {
1053 for (i, half) in halves.iter().enumerate() {
1054 if half.skip {
1055 continue;
1056 }
1057 let (ur, uc) = if *horz {
1058 (sb_r + i, sb_c)
1059 } else {
1060 (sb_r, sb_c + i)
1061 };
1062 let (w, h) = if *horz { (128, 64) } else { (64, 128) };
1063 collapse(&mut owner, (ur, uc), (w, h));
1064 }
1065 }
1066 // lane-rectres: the AB half is the only multi-unit piece
1067 // (its two squares are one unit each); only a non-skip one
1068 // codes a literal, so only it fires.
1069 Quadrant::Ab128(symbol, pieces) => {
1070 for (piece, ((mi_r, mi_c), (w, h))) in
1071 pieces.iter().zip(crate::encode::ab128_pieces(
1072 usize::from(*symbol),
1073 (0, 0),
1074 ))
1075 {
1076 if piece.skip {
1077 continue;
1078 }
1079 let (ur, uc) = (sb_r + mi_r / 16, sb_c + mi_c / 16);
1080 collapse(&mut owner, (ur, uc), (w, h));
1081 }
1082 }
1083 _ => {}
1084 }
1085 }
1086 }
1087 owner
1088}
1089
1090/// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
1091struct CdefIdxPlan {
1092 /// The header's `cdef_bits`; never 0 while armed.
1093 bits: u8,
1094 /// Superblocks per row, the stride of `grid`.
1095 sb_cols: usize,
1096 /// One index per 64x64 superblock, in raster order.
1097 grid: Vec<u8>,
1098 /// The superblock whose literal was already written -- the decoder's
1099 /// `cdef_transmitted`, which resets at every superblock and which coding
1100 /// order (each superblock's blocks are contiguous) makes a single slot.
1101 last: Option<usize>,
1102}
1103
1104thread_local! {
1105 static CDEF_IDX: std::cell::RefCell<Option<CdefIdxPlan>> =
1106 const { std::cell::RefCell::new(None) };
1107}
1108
1109/// Arms the next tile write with one `cdef_idx` per 64x64 superblock.
1110/// `bits == 0` disarms (the header codes a single strength pair, so the tile
1111/// carries no literal at all).
1112pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
1113 CDEF_IDX.with(|c| {
1114 *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan { bits, sb_cols, grid, last: None });
1115 });
1116}
1117
1118/// One frame's per-superblock quantizer plan (lane-deltaq, see
1119/// [`arm_delta_q`]): the writer side of decode.rs `maybe_read_delta_q`.
1120struct DeltaQPlan {
1121 /// `1 << delta_q_res`, the multiplier the coded symbol is scaled by --
1122 /// every `grid` entry is congruent to `base` modulo it, so the delta the
1123 /// writer codes is always a whole number of steps.
1124 res: i32,
1125 /// Superblocks per row, the stride of `grid`.
1126 sb_cols: usize,
1127 /// The absolute `qindex` each 64x64 superblock is coded at, raster order.
1128 grid: Vec<u8>,
1129 /// The spec's `CurrentQIndex`, carried across the superblocks of THIS
1130 /// tile -- armed at the frame's `base_q_idx` because a tile writer is
1131 /// armed once per tile (`encode_inter_frame`'s `code_tiles`), which is
1132 /// exactly the spec's own per-tile reset.
1133 cur: i32,
1134}
1135
1136thread_local! {
1137 static DELTA_Q: std::cell::RefCell<Option<DeltaQPlan>> =
1138 const { std::cell::RefCell::new(None) };
1139}
1140
1141/// Arms the next tile write with one absolute `qindex` per 64x64 superblock.
1142/// Disarmed (a plain no-op writer, byte for byte what this crate wrote before
1143/// lane-deltaq) when `res == 0`.
1144pub(crate) fn arm_delta_q(res: i32, sb_cols: usize, grid: Vec<u8>, base: u8) {
1145 DELTA_Q.with(|c| {
1146 *c.borrow_mut() =
1147 (res > 0).then(|| DeltaQPlan { res, sb_cols, grid, cur: i32::from(base) });
1148 });
1149}
1150
1151thread_local! {
1152 static SIGN_BIAS: std::cell::Cell<crate::mvstack::SignBiasTable> =
1153 const { std::cell::Cell::new(crate::mvstack::NO_SIGN_BIAS) };
1154}
1155
1156/// Arms the next tile write with this frame's `ref_frame_sign_bias` (spec
1157/// 5.9.2), the table its MV-stack scans run under. Armed the same way
1158/// [`arm_cdef_idx`]/[`arm_lr`] are -- and disarmed by the same guard -- so
1159/// that a frame with a backward reference needs no new parameter on the four
1160/// nested writer helpers between here and `find_mv_stack`. A frame that never
1161/// names a future reference leaves this alone: all-`false` is what every
1162/// stream this crate wrote before pyramids existed codes under.
1163pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
1164 SIGN_BIAS.with(|c| c.set(sign_bias));
1165}
1166
1167thread_local! {
1168 static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1169}
1170
1171/// Arms the next tile write with this frame's `allow_screen_content_tools`
1172/// (spec 5.9.2), which is what makes every intra block carry the
1173/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46
1174/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/
1175/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that
1176/// never detected screen content writes exactly the stream it wrote before
1177/// this lane.
1178pub(crate) fn arm_screen(on: bool) {
1179 SCREEN.with(|c| c.set(on));
1180}
1181
1182thread_local! {
1183 /// This frame's `(mi_rows, mi_cols)` (spec `compute_image_size`), armed
1184 /// beside [`SCREEN`] by both frame encoders: a palette block cut by the
1185 /// frame's right/bottom mi edge codes its colour-index map over the
1186 /// ON-SCREEN part only, so the writer needs the same dims the decoder's
1187 /// `palette_onscreen` reads off its `FrameCtx` (lane-palw). `(0, 0)`
1188 /// -- an unarmed writer, i.e. a unit test coding one block -- clamps
1189 /// nothing, which is what every stream without a cut palette block codes.
1190 static FRAME_MI_DIMS: std::cell::Cell<(usize, usize)> =
1191 const { std::cell::Cell::new((0, 0)) };
1192}
1193
1194/// Arms the next tile write with this frame's `(mi_rows, mi_cols)`.
1195pub(crate) fn arm_frame_mi_dims(dims: (usize, usize)) {
1196 FRAME_MI_DIMS.with(|c| c.set(dims));
1197}
1198
1199/// The armed `(mi_rows, mi_cols)`, or a grid big enough to clamp nothing.
1200fn frame_mi_dims() -> (usize, usize) {
1201 match FRAME_MI_DIMS.with(std::cell::Cell::get) {
1202 (0, 0) => (usize::MAX / 8, usize::MAX / 8),
1203 dims => dims,
1204 }
1205}
1206
1207fn screen_armed() -> bool {
1208 SCREEN.with(std::cell::Cell::get)
1209}
1210
1211thread_local! {
1212 /// This frame header's `allow_intrabc` (spec 5.9.2), armed exactly like
1213 /// [`SCREEN`]: with it every intra block of the tile carries a
1214 /// `use_intrabc` symbol right after `skip`/`cdef`/`delta_q` (decode.rs
1215 /// `read_intra_mode`), so a tile written without it and read with it
1216 /// desyncs at the first block.
1217 static INTRABC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1218 /// The mi grid the DV predictor is built off (decode.rs
1219 /// `INTRABC_MI_GRID`/`record_intrabc_mi`): every coded block publishes
1220 /// its own footprint into it, an intrabc one also its DV as an
1221 /// `INTRA_FRAME` candidate. `Some` only while an `allow_intrabc` tile is
1222 /// being written.
1223 static INTRABC_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1224 const { std::cell::RefCell::new(None) };
1225}
1226
1227/// Arms the frame's `allow_intrabc` bit for the next tile written on this
1228/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
1229pub(crate) fn arm_intrabc(on: bool) {
1230 INTRABC.with(|c| c.set(on));
1231}
1232
1233fn intrabc_armed() -> bool {
1234 INTRABC.with(std::cell::Cell::get)
1235}
1236
1237thread_local! {
1238 /// This SEQUENCE header's `enable_filter_intra` (spec 5.5.2), armed
1239 /// exactly like [`SCREEN`]: with it every DC_PRED intra block of at most
1240 /// 32x32 that took no luma palette carries a `use_filter_intra` symbol
1241 /// after the palette colours and before the colour-index maps (decode.rs
1242 /// `read_intra_mode`), so a tile written without it and read with it
1243 /// desyncs at the first such block.
1244 static FILTER_INTRA: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1245}
1246
1247/// Arms the sequence's `enable_filter_intra` bit for the next tile written on
1248/// this thread; cleared by [`CdefIdxGuard`] when that writer returns.
1249pub(crate) fn arm_filter_intra(on: bool) {
1250 FILTER_INTRA.with(|c| c.set(on));
1251}
1252
1253fn filter_intra_armed() -> bool {
1254 FILTER_INTRA.with(std::cell::Cell::get)
1255}
1256
1257/// How many blocks this writer coded `use_filter_intra == 1`, and the
1258/// histogram of the five `filter_intra_mode`s (index 1..=5) -- the fire count
1259/// a gate prints so that "filter intra is on" is a measurement rather than a
1260/// claim (class `gate-blind-to-feature`). Index 0 is the block count.
1261static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] =
1262 [const { std::sync::atomic::AtomicUsize::new(0) }; 6];
1263
1264/// Reads [`FILTER_INTRA_HITS`] and zeroes it, so a gate can attribute the
1265/// counts to its own encode.
1266#[cfg(test)]
1267pub(crate) fn take_filter_intra_hits() -> [usize; 6] {
1268 std::array::from_fn(|i| FILTER_INTRA_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1269}
1270
1271/// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for
1272/// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every
1273/// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <=
1274/// 32, [`crate::decode::filter_intra_size_class`]) and that took no luma
1275/// palette (`av1_filter_intra_allowed`, reconintra.h:77), then the chosen mode
1276/// of five. Sits between the palette COLOUR lists and the colour-index maps,
1277/// where libaom reads it (`av1_visit_palette` runs after
1278/// `read_filter_intra_mode_info`).
1279fn write_filter_intra(
1280 enc: &mut SymbolEncoder,
1281 cdfs: &mut Cdfs,
1282 mode: usize,
1283 side: usize,
1284 has_palette_y: bool,
1285 filter_intra: Option<u8>,
1286) {
1287 if !filter_intra_armed() || mode != DC_PRED || has_palette_y {
1288 debug_assert!(filter_intra.is_none(), "no `use_filter_intra` symbol exists here");
1289 return;
1290 }
1291 let Some(class) = crate::decode::filter_intra_size_class(side) else {
1292 debug_assert!(filter_intra.is_none(), "past av1_filter_intra_allowed_bsize");
1293 return;
1294 };
1295 enc.symbol(usize::from(filter_intra.is_some()), &mut cdfs.filter_intra[class]);
1296 if let Some(fi) = filter_intra {
1297 enc.symbol(usize::from(fi), &mut cdfs.filter_intra_mode);
1298 FILTER_INTRA_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1299 FILTER_INTRA_HITS[usize::from(fi) + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1300 }
1301}
1302
1303/// The coefficient-table row a block's luma transform types are coded from:
1304/// `fimode_to_intradir[filter_intra_mode]` for a filter-intra block, its own
1305/// luma mode otherwise (class `filter-intra tx_type row`, decode.rs
1306/// [`crate::decode::fi_tx_row`]). The block still PUBLISHES `DC_PRED` as its
1307/// neighbour mode -- libaom's `mbmi->mode` is unchanged by filter intra.
1308fn tx_row(mode: usize, filter_intra: Option<u8>) -> usize {
1309 crate::decode::fi_tx_row(mode, filter_intra.map(usize::from))
1310}
1311
1312/// How many blocks this writer coded `use_intrabc == 1`, and the histogram of
1313/// their DV magnitudes in full pels (index 1..=6 = 1, 2, 4, 8, 16, 32 pels
1314/// and up, by the larger component) -- the fire count a gate prints so that
1315/// "intrabc is on" is a measurement rather than a claim (class
1316/// `gate-blind-to-feature`). Index 0 is the block count.
1317static INTRABC_HITS: [std::sync::atomic::AtomicUsize; 7] =
1318 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1319
1320fn note_intrabc(dv: (i32, i32)) {
1321 INTRABC_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1322 let px = (dv.0.abs() / 8).max(dv.1.abs() / 8).max(1) as usize;
1323 let bucket = (usize::BITS - px.leading_zeros()) as usize;
1324 INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1325}
1326
1327/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts
1328/// to its own encode.
1329#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1330pub(crate) fn take_intrabc_hits() -> [usize; 7] {
1331 std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1332}
1333
1334thread_local! {
1335 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
1336 /// the same way `arm_sign_bias` arms the sign-bias table rather than
1337 /// threaded through the five nested writer helpers between here and the
1338 /// per-block mode syntax. `true` makes every inter block of size at least
1339 /// 8x8 code a `comp_mode` symbol, exactly where decode.rs `read_comp_mode`
1340 /// reads one.
1341 static REFERENCE_SELECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1342}
1343
1344/// Arms the frame's `reference_select` bit for the next tile written on this
1345/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
1346pub(crate) fn arm_reference_select(on: bool) {
1347 REFERENCE_SELECT.with(|c| c.set(on));
1348}
1349
1350thread_local! {
1351 /// This frame header's own `is_motion_mode_switchable` bit (spec 5.9.2),
1352 /// armed exactly like [`REFERENCE_SELECT`]. `true` makes every
1353 /// single-reference inter block that libaom's `motion_mode_allowed`
1354 /// accepts carry a `motion_mode`/`obmc` symbol right after its MV syntax,
1355 /// exactly where decode.rs' `read_motion_mode` reads one.
1356 static MOTION_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1357}
1358
1359thread_local! {
1360 /// This frame header's own `allow_warped_motion` bit (spec 5.9.2): with
1361 /// it set, every block libaom's `motion_mode_allowed` accepts AND that
1362 /// has at least one warp sample (`num_proj_ref >= 1`) reads the 3-symbol
1363 /// `motion_mode_cdf` alphabet instead of the 2-symbol `obmc_cdf` one.
1364 /// lane-av1obmc2.
1365 static WARPED_MOTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1366 /// The frame geometry the warp-sample walk needs (`num_proj_ref` ->
1367 /// `has_top_right`), which is only ever this writer's own superblock
1368 /// size. Every stream this crate writes uses a 64 superblock, which is
1369 /// `FrameCtx::new`'s default.
1370 /// corner-cut: ceiling is a 128-superblock WRITER -- it must arm the real
1371 /// frame context here (or take one as a parameter) or the warp-sample
1372 /// walk reads the wrong `has_top_right` geometry.
1373 static WRITER_FCTX: crate::decode::FrameCtx = crate::decode::FrameCtx::new();
1374}
1375
1376/// Arms [`WARPED_MOTION`] for the next tile written on this thread.
1377pub(crate) fn arm_warped_motion(on: bool) {
1378 WARPED_MOTION.with(|c| c.set(on));
1379}
1380
1381/// Arms the frame's `is_motion_mode_switchable` bit for the next tile written
1382/// on this thread; cleared by [`CdefIdxGuard`] when that writer returns.
1383pub(crate) fn arm_motion_mode(on: bool) {
1384 MOTION_MODE.with(|c| c.set(on));
1385}
1386
1387/// How many single-reference inter blocks this writer coded a `motion_mode`
1388/// symbol for, split by the value it coded and by the block's own footprint
1389/// -- the histogram a gate prints so that "OBMC is on" is a measurement, not
1390/// a claim (class `gate-blind-to-feature`). Index: `0 + 2 * bucket` for
1391/// SIMPLE, `1 + 2 * bucket` for OBMC, bucket 0/1/2 = 32x32/16x16/8x8.
1392static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] =
1393 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
1394
1395/// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the
1396/// counts to its own encode.
1397#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1398pub(crate) fn take_motion_mode_hits() -> [usize; 9] {
1399 std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1400}
1401
1402/// What the 3-symbol `motion_mode` symbol costs, in bits, against the same
1403/// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off --
1404/// which alphabet a block reads is `motion_mode_allowed`'s own choice
1405/// ([`write_motion_mode`]).
1406pub(crate) fn motion_mode_symbol_bits(row: usize, motion: u8) -> f64 {
1407 PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
1408 Some(s) => crate::encode::symbol_bits(&s.0.motion_mode[row], usize::from(motion)),
1409 None => crate::encode::symbol_bits(&crate::cdf::MOTION_MODE[row], usize::from(motion)),
1410 })
1411}
1412
1413/// What the `motion_mode`/`obmc` symbol costs, in bits, against the tables
1414/// this frame's writer really starts from ([`arm_pricing_cdfs`]) -- the same
1415/// tables the coefficients are priced off since lane-av1price2, rather than
1416/// the static defaults the symbol used to be estimated with. Falls back to
1417/// the default table whenever the search is armed with the defaults (a key
1418/// frame, or a screen frame the gate turned off).
1419pub(crate) fn obmc_symbol_bits(row: usize, obmc: bool) -> f64 {
1420 PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
1421 Some(s) => crate::encode::symbol_bits(&s.0.obmc[row], usize::from(obmc)),
1422 None => crate::encode::symbol_bits(&crate::cdf::OBMC[row], usize::from(obmc)),
1423 })
1424}
1425
1426/// `read_motion_mode`'s write side (spec 5.11.24), called on a
1427/// single-reference inter block right after its MV syntax and before the
1428/// (never switchable here) interpolation filter -- libaom's own sequential
1429/// order in `read_inter_block_mode_info`.
1430///
1431/// Eligibility is decode.rs' own `motion_mode_eligible`, term for term, with
1432/// the terms this writer settles statically dropped: no block it codes is
1433/// `skip_mode`, interintra or a non-IDENTITY-global `GLOBALMV` one, so what
1434/// is left is the footprint floor and the overlappable-neighbour walk
1435/// ([`crate::decode::has_overlappable_neighbour`], shared with the decoder so
1436/// the two cannot drift). The frame header keeps `allow_warped_motion == 0`,
1437/// so the alphabet is always the 2-symbol `obmc_cdf`, never the 3-symbol
1438/// `motion_mode_cdf`.
1439fn write_motion_mode(
1440 enc: &mut SymbolEncoder,
1441 cdfs: &mut Cdfs,
1442 grid: &MiGrid,
1443 (mi_row, mi_col): (usize, usize),
1444 (bw4, bh4): (usize, usize),
1445 (write_w, write_h): (usize, usize),
1446 (mi_cols, mi_rows): (usize, usize),
1447 // This block's own reference, for the warp-sample walk that picks the
1448 // alphabet (`num_proj_ref`).
1449 ref_frame: i8,
1450 // 0 SIMPLE_TRANSLATION, 1 OBMC_CAUSAL, 2 WARPED_CAUSAL -- what the
1451 // encoder's search committed for this block.
1452 motion: u8,
1453) -> Result<()> {
1454 let eligible = MOTION_MODE.with(std::cell::Cell::get)
1455 && write_w.min(write_h) >= 8
1456 && crate::decode::has_overlappable_neighbour(
1457 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows,
1458 );
1459 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
1460 let proj = WRITER_FCTX.with(|fctx| {
1461 crate::decode::num_proj_ref(
1462 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1463 )
1464 });
1465 eprintln!(
1466 "EC_MMW mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} proj={proj} warp_armed={} motion={motion}",
1467 eligible as u8,
1468 WARPED_MOTION.with(std::cell::Cell::get) as u8,
1469 );
1470 }
1471 if !eligible {
1472 // The encoder trialled an OBMC prediction for a block this writer
1473 // codes as SIMPLE_TRANSLATION: its reconstruction is not the
1474 // decoder's (class encoder-grid-drift), which is exactly what the
1475 // `EC_COMP_MISMATCH` rung exists to catch.
1476 if motion != 0 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
1477 eprintln!(
1478 "EC_COMP_MISMATCH motion_mode enc=OBMC wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
1479 );
1480 }
1481 return Ok(());
1482 }
1483 let row = crate::decode::motion_mode_cdf_row(write_w, write_h).ok_or_else(|| {
1484 Error::unsupported(
1485 "AV1 tile",
1486 format!("a {write_w}x{write_h} block has no motion_mode CDF row"),
1487 )
1488 })?;
1489 // libaom `motion_mode_allowed`: the 3-symbol `motion_mode_cdf` alphabet
1490 // exactly when `allow_warped_motion` is on and the block has at least one
1491 // warp sample. The other two vetoes libaom applies there cannot fire for
1492 // a stream this encoder writes -- it codes no scaled reference and no
1493 // inter frame with `force_integer_mv` -- and the decoder checks all three
1494 // (`decode.rs`'s `warp_eligible`), so the two sides agree term for term.
1495 let warp_alphabet = WARPED_MOTION.with(std::cell::Cell::get)
1496 && WRITER_FCTX.with(|fctx| {
1497 crate::decode::num_proj_ref(
1498 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1499 )
1500 }) >= 1;
1501 if warp_alphabet {
1502 enc.symbol(usize::from(motion), &mut cdfs.motion_mode[row]);
1503 } else {
1504 // A warp winner whose block the writer resolves to the 2-symbol
1505 // alphabet would reconstruct as SIMPLE at the decoder: the same
1506 // encoder-grid-drift rung the OBMC case above prints.
1507 if motion == 2 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
1508 eprintln!(
1509 "EC_COMP_MISMATCH motion_mode enc=WARP wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
1510 );
1511 }
1512 enc.symbol(usize::from(motion == 1), &mut cdfs.obmc[row]);
1513 }
1514 let bucket = match write_w.min(write_h) {
1515 32.. => 0,
1516 16 => 1,
1517 _ => 2,
1518 };
1519 MOTION_MODE_HITS[usize::from(motion.min(2)) + 3 * bucket]
1520 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1521 Ok(())
1522}
1523
1524/// The compound half of a block's end-of-block neighbour record: nothing for
1525/// a single-reference or intra block, and `record_compound_mi`'s overwrite of
1526/// the ALTREF default for a compound one (this writer only codes
1527/// `comp_group_idx == 0`, `compound_idx == 1`).
1528fn record_block_compound(neighbours: &mut Neighbours, at_mi: (usize, usize), side: usize, block: &BlockCoeffs) {
1529 if let Some(r1) = block.inter.and_then(|i| i.ref1) {
1530 neighbours.record_compound_mi(at_mi, side, r1, 0, 1);
1531 }
1532}
1533
1534/// decode.rs' own `is_uni_comp_ref`: a pair is `UNIDIR_COMP_REFERENCE`
1535/// exactly when both references sit on the same temporal side.
1536use crate::mvstack::is_uni_comp_ref;
1537
1538thread_local! {
1539 /// `(order_hint_bits, this frame's order hint, each reference's order
1540 /// hint)` -- what `get_comp_index_context` (decode.rs) needs to context
1541 /// the `compound_idx` symbol, armed the same way the sign-bias table is.
1542 static ORDER_HINTS: std::cell::Cell<(u32, u32, [u32; 7])> =
1543 const { std::cell::Cell::new((7, 0, [0; 7])) };
1544}
1545
1546/// Arms this frame's order hints for the next tile written on this thread.
1547pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) {
1548 ORDER_HINTS.with(|c| c.set((bits, order_hint, hints)));
1549}
1550
1551/// What [`arm_order_hints`] last armed: `(order_hint_bits, order_hint,
1552/// ref_order_hints)`, for the encoder's own per-reference distance.
1553pub(crate) fn order_hints() -> (u32, u32, [u32; 7]) {
1554 ORDER_HINTS.with(std::cell::Cell::get)
1555}
1556
1557thread_local! {
1558 /// lane-hpmv: this frame's `allow_high_precision_mv`, armed per worker
1559 /// beside [`arm_order_hints`] -- the writer's eighth-pel symbol, the
1560 /// pricer's mv bits and the motion search's finest step all read it.
1561 static HIGH_PRECISION_MV: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1562}
1563
1564/// Arms this frame's `allow_high_precision_mv` for the next tile written --
1565/// or searched -- on this thread.
1566pub(crate) fn arm_high_precision_mv(on: bool) {
1567 HIGH_PRECISION_MV.with(|c| c.set(on));
1568}
1569
1570/// What [`arm_high_precision_mv`] last armed on this thread.
1571pub(crate) fn high_precision_mv() -> bool {
1572 HIGH_PRECISION_MV.with(std::cell::Cell::get)
1573}
1574
1575/// lane-hpmv's witness counters: `[0]` counts every `mv_hp`/`mv_class0_hp`
1576/// symbol this process's writers coded (zero without
1577/// `allow_high_precision_mv`, one per non-zero mv component with it), `[1]`
1578/// counts the ones that came out ZERO -- an eighth-pel vector, i.e. one a
1579/// frame without the flag cannot name at all.
1580static HP_SYMBOLS: [std::sync::atomic::AtomicU64; 2] =
1581 [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
1582
1583/// Reads and clears [`HP_SYMBOLS`]: `(hp symbols coded, eighth-pel ones)`.
1584#[allow(dead_code)] // read only from the `#[cfg(test)]` witness
1585pub(crate) fn take_hp_symbols() -> (u64, u64) {
1586 let all = HP_SYMBOLS[0].swap(0, std::sync::atomic::Ordering::Relaxed);
1587 (all, HP_SYMBOLS[1].swap(0, std::sync::atomic::Ordering::Relaxed))
1588}
1589
1590/// [`take_hp_symbols`] without clearing -- what the NEWMV census prints.
1591pub(crate) fn hp_symbols() -> (u64, u64) {
1592 use std::sync::atomic::Ordering::Relaxed;
1593 (HP_SYMBOLS[0].load(Relaxed), HP_SYMBOLS[1].load(Relaxed))
1594}
1595
1596/// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec
1597/// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref`
1598/// trees), symbol for symbol at the same contexts -- which are, as that
1599/// function's own doc records, `single_ref_p1_ctx`..`single_ref_p6_ctx`/
1600/// `uni_comp_ref_p1_ctx` under libaom's compound names.
1601///
1602/// # Errors
1603/// A pair this writer never forms (its `ref0` is not `LAST_FRAME`).
1604fn write_compound_ref_frames(
1605 enc: &mut SymbolEncoder,
1606 cdfs: &mut Cdfs,
1607 above: Option<crate::mvstack::NeighbourRef>,
1608 left: Option<crate::mvstack::NeighbourRef>,
1609 above_ref: i8,
1610 left_ref: i8,
1611 (ref0, ref1): (i8, i8),
1612) -> Result<()> {
1613 use crate::mvstack::{
1614 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
1615 LAST_FRAME, comp_reference_type_ctx, single_ref_p1_ctx, single_ref_p2_ctx,
1616 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
1617 uni_comp_ref_p1_ctx,
1618 };
1619 let a = (above_ref > 0).then_some(above_ref);
1620 let l = (left_ref > 0).then_some(left_ref);
1621 let a1 = above.and_then(|n| n.ref1);
1622 let l1 = left.and_then(|n| n.ref1);
1623 let unidir = is_uni_comp_ref(ref0, ref1);
1624 enc.symbol(
1625 usize::from(!unidir),
1626 &mut cdfs.comp_ref_type[comp_reference_type_ctx(above, left)],
1627 );
1628 if unidir {
1629 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
1630 enc.symbol(
1631 usize::from(both_backward),
1632 &mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0],
1633 );
1634 if both_backward {
1635 return Ok(());
1636 }
1637 if ref0 != LAST_FRAME {
1638 return Err(Error::unsupported(
1639 "AV1 tile",
1640 "a unidirectional compound pair this writer does not form",
1641 ));
1642 }
1643 let past_last2 = ref1 != LAST2_FRAME;
1644 enc.symbol(
1645 usize::from(past_last2),
1646 &mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
1647 );
1648 if past_last2 {
1649 enc.symbol(
1650 usize::from(ref1 == GOLDEN_FRAME),
1651 &mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
1652 );
1653 }
1654 return Ok(());
1655 }
1656 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
1657 enc.symbol(
1658 usize::from(far),
1659 &mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0],
1660 );
1661 if far {
1662 enc.symbol(
1663 usize::from(ref0 == GOLDEN_FRAME),
1664 &mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
1665 );
1666 } else {
1667 enc.symbol(
1668 usize::from(ref0 == LAST2_FRAME),
1669 &mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1],
1670 );
1671 }
1672 let is_altref = ref1 == ALTREF_FRAME;
1673 enc.symbol(
1674 usize::from(is_altref),
1675 &mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0],
1676 );
1677 if !is_altref {
1678 enc.symbol(
1679 usize::from(ref1 == ALTREF2_FRAME),
1680 &mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1],
1681 );
1682 }
1683 Ok(())
1684}
1685
1686/// Per-mode and per-pair fire counts of [`write_compound_block`], for the
1687/// gate's own census (gate-blind-to-feature): modes indexed by the spec's
1688/// `INTER_COMPOUND_MODES`, pairs by `ref1` (`LAST`..`ALTREF`).
1689static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1690 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1691static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =
1692 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1693
1694/// Takes and clears the compound mode histogram.
1695#[cfg(test)]
1696pub(crate) fn take_compound_mode_hits() -> [usize; 8] {
1697 std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1698}
1699
1700/// Takes and clears the compound pair histogram, indexed by the SECOND
1701/// reference (`LAST` = 0 .. `ALTREF` = 6).
1702#[cfg(test)]
1703pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
1704 std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1705}
1706
1707/// Per-SIZE fire counts of [`write_compound_block`], indexed by
1708/// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
1709/// 32x32-only tool, so the share by size is what says whether the leaf
1710/// candidates fire at all (gate-blind-to-feature).
1711static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
1712 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
1713
1714/// Takes and clears the compound size histogram.
1715#[cfg(test)]
1716pub(crate) fn take_compound_size_hits() -> [usize; 4] {
1717 std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1718}
1719
1720/// The compound mode histogram of the LEAVES alone (`bw4 <= 4`, so 16x16 and
1721/// below). The frame-wide histogram above cannot say whether a mode reaches
1722/// the leaves at all, which is exactly the question every leaf compound step
1723/// asks (gate-blind-to-feature): before lane-av1comp4 gave a leaf its second
1724/// reference search, the two half-new modes were structurally impossible
1725/// there and screen capture's leaf compound was 100% `NEAREST_NEARESTMV`.
1726static COMPOUND_LEAF_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1727 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1728
1729/// Takes and clears the leaf-only compound mode histogram.
1730#[cfg(test)]
1731pub(crate) fn take_compound_leaf_mode_hits() -> [usize; 8] {
1732 std::array::from_fn(|i| {
1733 COMPOUND_LEAF_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)
1734 })
1735}
1736
1737/// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
1738/// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
1739/// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
1740/// order. Returns the two motion vectors the decoder derives (what the MI
1741/// grid must record) and whether the mode was a `NEW*` one.
1742///
1743/// Only the modes [`InterMode::compound_index`] names are written, and
1744/// only the `comp_group_idx == 0`, `compound_idx == 1` blend (spec
1745/// `COMPOUND_AVERAGE`) -- masked compound and the distance-weighted blend are
1746/// not searched.
1747///
1748/// # Errors
1749/// As [`write_mv`], or a pair/mode this writer does not form.
1750#[allow(clippy::too_many_arguments)]
1751fn write_compound_block(
1752 enc: &mut SymbolEncoder,
1753 cdfs: &mut Cdfs,
1754 neighbours: &Neighbours,
1755 grid: &crate::mvstack::MiGrid,
1756 (mi_row, mi_col): (usize, usize),
1757 (bw4, bh4): (usize, usize),
1758 (has_above, has_left): (bool, bool),
1759 info: InterInfo,
1760 (mi_cols, mi_rows): (usize, usize),
1761) -> Result<((i32, i32), (i32, i32), bool)> {
1762 let (Some(ref1), Some(mode)) = (info.ref1, info.mode.compound_index()) else {
1763 return Err(Error::unsupported(
1764 "AV1 tile",
1765 "a compound block needs a second reference and a compound mode",
1766 ));
1767 };
1768 let above = has_above.then(|| neighbours.above_nbr(mi_col));
1769 let left = has_left.then(|| neighbours.left_nbr(mi_row));
1770 write_compound_ref_frames(
1771 enc,
1772 cdfs,
1773 above,
1774 left,
1775 neighbours.above_ref[mi_col],
1776 neighbours.left_ref[mi_row],
1777 (info.ref_frame, ref1),
1778 )?;
1779 let stack = crate::mvstack::find_mv_stack_compound(
1780 grid,
1781 mi_row,
1782 mi_col,
1783 bw4,
1784 bh4,
1785 (info.ref_frame, ref1),
1786 mi_cols,
1787 mi_rows,
1788 grid.sign_bias_table(),
1789 &[(0, 0); 7],
1790 None,
1791 );
1792 let ctx = crate::cdf::COMPOUND_MODE_CTX_MAP[stack.ref_mv_ctx >> 1][stack.new_mv_ctx.min(4)];
1793 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1794 eprintln!(
1795 "EC_WCOMP mi_row={mi_row} mi_col={mi_col} mode={mode} ref0={} ref1={ref1} ctx={ctx} new_mv_ctx={} ref_mv_ctx={} stack={}",
1796 info.ref_frame, stack.new_mv_ctx, stack.ref_mv_ctx, stack.entries.len()
1797 );
1798 }
1799 enc.symbol(mode, &mut cdfs.inter_compound_mode[ctx]);
1800 // `assign_compound_mv`'s own DRL half: `NEW_NEWMV` walks from index 0,
1801 // the two derived modes code no index at all.
1802 let mvs = match info.mode {
1803 InterMode::NearestNearestMv => stack.nearest_mv,
1804 InterMode::GlobalGlobalMv => ((0, 0), (0, 0)),
1805 InterMode::NearNearMv => {
1806 // decode.rs `assign_compound_mv`'s second DRL loop: the index
1807 // starts at 1 and the mode's own `ref_mv_idx` is `idx - 1`, so
1808 // this walk starts at 1 too and reads entry `ref_mv_idx + 1`.
1809 let idx = usize::from(info.ref_mv_idx) + 1;
1810 let mut walk = 1usize;
1811 while walk < 3 && stack.entries.len() > walk + 1 {
1812 let advance = walk < idx;
1813 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]);
1814 if !advance {
1815 break;
1816 }
1817 walk += 1;
1818 }
1819 let near = |i: usize| {
1820 stack.entries.get(i).map_or(stack.near_mv, |e| (e.mv0, e.mv1))
1821 };
1822 if walk != idx && near(walk) != near(idx) {
1823 note_drl_clamp(idx, walk, stack.entries.len());
1824 }
1825 near(walk)
1826 }
1827 InterMode::NearestNewMv | InterMode::NewNearestMv => {
1828 // Neither mode codes a DRL index (the decoder leaves `ref_mv_idx`
1829 // at 0): the NEAREST half is derived, the NEW half codes a
1830 // residual against stack entry 0.
1831 let base = stack
1832 .entries
1833 .first()
1834 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
1835 if matches!(info.mode, InterMode::NearestNewMv) {
1836 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
1837 (stack.nearest_mv.0, info.mv1)
1838 } else {
1839 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
1840 (info.mv, stack.nearest_mv.1)
1841 }
1842 }
1843 _ => {
1844 let idx = usize::from(info.ref_mv_idx);
1845 let mut walk = 0usize;
1846 while walk < 2 && stack.entries.len() > walk + 1 {
1847 let advance = walk < idx;
1848 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]);
1849 if !advance {
1850 break;
1851 }
1852 walk += 1;
1853 }
1854 let nearest = |i: usize| {
1855 stack.entries.get(i).map_or(stack.nearest_mv, |e| (e.mv0, e.mv1))
1856 };
1857 if walk != idx && nearest(walk) != nearest(idx) {
1858 note_drl_clamp(idx, walk, stack.entries.len());
1859 }
1860 let base = nearest(walk);
1861 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
1862 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
1863 (info.mv, info.mv1)
1864 }
1865 };
1866 // spec 5.11.25's `comp_group_idx`/`compound_idx` are NOT coded: this
1867 // crate's sequence header carries `enable_masked_compound = false` and
1868 // `enable_jnt_comp = false` (encode.rs), and decode.rs reads neither
1869 // symbol under those bits -- it infers `comp_group_idx = 0`,
1870 // `compound_idx = 1` (the simple average), which is the only blend this
1871 // writer forms anyway. A lane that turns either sequence bit on has to
1872 // write the matching symbol here, at
1873 // `get_comp_group_idx_context`/`get_comp_index_context`'s contexts (which
1874 // is what `Neighbours::above_comp_group_idx`/`above_compound_idx` and the
1875 // armed order hints below are already kept for).
1876 let _ = ORDER_HINTS.with(std::cell::Cell::get);
1877 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1878 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
1879 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1880 COMPOUND_SIZE_HITS[(bw4.max(1).trailing_zeros() as usize).min(3)]
1881 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1882 if bw4 <= 4 {
1883 COMPOUND_LEAF_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1884 }
1885 if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {
1886 eprintln!(
1887 "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",
1888 info.mv, info.mv1, mvs.0, mvs.1
1889 );
1890 }
1891 // decode.rs' own `is_new_mv` for a compound block: modes 2, 3, 4, 5, 7.
1892 Ok((
1893 mvs.0,
1894 mvs.1,
1895 matches!(
1896 info.mode,
1897 InterMode::NewNewMv | InterMode::NearestNewMv | InterMode::NewNearestMv
1898 ),
1899 ))
1900}
1901
1902/// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's
1903/// `comp_mode`): on a `reference_select` frame every inter block whose size
1904/// allows compound (`is_comp_ref_allowed`, always true here -- this writer's
1905/// smallest leaf is 8x8) names SINGLE or COMPOUND, at
1906/// `mvstack::reference_mode_ctx`'s own context off the same two neighbour
1907/// bands decode.rs builds its `NeighbourRef` pair from.
1908fn write_comp_mode(
1909 enc: &mut SymbolEncoder,
1910 cdfs: &mut Cdfs,
1911 neighbours: &Neighbours,
1912 (mi_r, mi_c): (usize, usize),
1913 (has_above, has_left): (bool, bool),
1914 compound: bool,
1915) {
1916 if !REFERENCE_SELECT.with(std::cell::Cell::get) {
1917 return;
1918 }
1919 let above = has_above.then(|| neighbours.above_nbr(mi_c));
1920 let left = has_left.then(|| neighbours.left_nbr(mi_r));
1921 let ctx = crate::mvstack::reference_mode_ctx(above, left);
1922 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1923 eprintln!(
1924 "EC_WCM mi=({mi_r},{mi_c}) ctx={ctx} val={} a={:?} l={:?}",
1925 usize::from(compound),
1926 above.map(|n| (n.is_inter, n.ref0, n.ref1)),
1927 left.map(|n| (n.is_inter, n.ref0, n.ref1))
1928 );
1929 }
1930 enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]);
1931}
1932
1933/// Clears the armed plan when the tile writer that consumed it returns.
1934struct CdefIdxGuard;
1935
1936impl Drop for CdefIdxGuard {
1937 fn drop(&mut self) {
1938 CDEF_IDX.with(|c| *c.borrow_mut() = None);
1939 DELTA_Q.with(|c| *c.borrow_mut() = None);
1940 LR_PLAN.with(|c| *c.borrow_mut() = None);
1941 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
1942 SCREEN.with(|c| c.set(false));
1943 REFERENCE_SELECT.with(|c| c.set(false));
1944 MOTION_MODE.with(|c| c.set(false));
1945 INTRABC.with(|c| c.set(false));
1946 FILTER_INTRA.with(|c| c.set(false));
1947 INTRABC_GRID.with(|c| *c.borrow_mut() = None);
1948 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
1949 }
1950}
1951
1952/// `read_cdef`'s write side, called right after every block's `skip` symbol:
1953/// writes this superblock's `cdef_idx` literal the first time a non-skip
1954/// block of it is coded. `mi` is the block's own position in 4x4 mode-info
1955/// units.
1956fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) {
1957 if skip {
1958 return;
1959 }
1960 CDEF_IDX.with(|c| {
1961 let mut plan = c.borrow_mut();
1962 let Some(plan) = plan.as_mut() else { return };
1963 let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16);
1964 if plan.last == Some(sb) {
1965 return;
1966 }
1967 plan.last = Some(sb);
1968 enc.literal(
1969 u32::from(plan.grid.get(sb).copied().unwrap_or(0)),
1970 u32::from(plan.bits),
1971 );
1972 });
1973}
1974
1975/// `read_delta_qindex`'s write side (spec 5.11.10), called right after every
1976/// block's [`write_cdef_idx`] -- the spec's own `skip -> cdef -> delta_q`
1977/// order, and decode.rs `maybe_read_delta_q` is the reader this mirrors
1978/// symbol for symbol. A no-op unless this block sits at its superblock's own
1979/// top-left mode-info position, and (the one case the reader skips too) when
1980/// that block IS the whole superblock and is skipped, in which case
1981/// `CurrentQIndex` carries over unchanged on both sides.
1982fn write_delta_q(
1983 enc: &mut SymbolEncoder,
1984 cdfs: &mut Cdfs,
1985 mi: (usize, usize),
1986 is_whole_sb: bool,
1987 skip: bool,
1988) {
1989 DELTA_Q.with(|c| {
1990 let mut plan = c.borrow_mut();
1991 let Some(plan) = plan.as_mut() else { return };
1992 // lane-b128m: the delta_q unit is the SUPERBLOCK, so it is 128 wide
1993 // under `EC_AV1_SB128` -- decode.rs `maybe_read_delta_q` gates on
1994 // `sb_mi_cur`, and a writer gating on a hardcoded 64 codes three
1995 // symbol groups per 128 root the reader never reads.
1996 let sb_mi = if sb128_armed() { SB_MI as usize * 2 } else { SB_MI as usize };
1997 if mi.0 % sb_mi != 0 || mi.1 % sb_mi != 0 {
1998 return;
1999 }
2000 if is_whole_sb && skip {
2001 return;
2002 }
2003 let sb = (mi.0 / SB_MI as usize) * plan.sb_cols + (mi.1 / SB_MI as usize);
2004 let target = i32::from(plan.grid.get(sb).copied().unwrap_or(0));
2005 // `reduced` is the spec's `delta_q_abs`/`delta_q_sign_bit` pair: the
2006 // step count, not the qindex difference.
2007 let reduced = (target - plan.cur) / plan.res;
2008 let abs = reduced.unsigned_abs() as usize;
2009 /// spec `DELTA_Q_SMALL`: the largest `delta_q_abs` symbol that is not
2010 /// an escape into the literal pair below.
2011 const DELTA_Q_SMALL: usize = 3;
2012 enc.symbol(abs.min(DELTA_Q_SMALL), &mut cdfs.delta_q);
2013 if abs >= DELTA_Q_SMALL {
2014 // libaom `write_delta_qindex`: `rem_bits = get_msb(abs - 1)`,
2015 // written one less in three bits, and the value offset by the
2016 // threshold `(1 << rem_bits) + 1` the reader adds back.
2017 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
2018 let thr = (1u32 << rem_bits) + 1;
2019 enc.literal(rem_bits - 1, 3);
2020 enc.literal(abs as u32 - thr, rem_bits);
2021 }
2022 if abs != 0 {
2023 enc.literal(u32::from(reduced < 0), 1);
2024 }
2025 plan.cur = (plan.cur + reduced * plan.res).clamp(1, 255);
2026 });
2027}
2028
2029/// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
2030/// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
2031/// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
2032/// same variable, so the two traces line up symbol for symbol. Checked once
2033/// per process, so unset (the default) costs one atomic load per call and no
2034/// allocation. Only the real tile writer below calls this -- the mode/rate
2035/// search's own trial encoders never do -- so the trace does not need the
2036/// throwaway-encoder gating a whole-encoder trace would.
2037fn ec_rng_trace(msg: impl FnOnce() -> String) {
2038 use std::sync::atomic::{AtomicU8, Ordering};
2039 static ON: AtomicU8 = AtomicU8::new(2); // 2 = unknown, 1 = on, 0 = off
2040 let on = match ON.load(Ordering::Relaxed) {
2041 2 => {
2042 let on = u8::from(std::env::var_os("EC_RNG").is_some());
2043 ON.store(on, Ordering::Relaxed);
2044 on
2045 }
2046 v => v,
2047 };
2048 if on == 1 {
2049 eprintln!("{}", msg());
2050 }
2051}
2052
2053/// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
2054const PARTITION_NONE: usize = 0;
2055/// `PARTITION_HORZ` (spec 6.10.4): the block cut into a top and a bottom half.
2056const PARTITION_HORZ: usize = 1;
2057/// `PARTITION_VERT` (spec 6.10.4): the block cut into a left and a right half.
2058const PARTITION_VERT: usize = 2;
2059/// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants.
2060const PARTITION_SPLIT: usize = 3;
2061
2062/// The partition types whose probability mass the split-or-horizontal flag of
2063/// a superblock hanging off the bottom of the frame gathers (spec 9.3,
2064/// `partition_gather_vert_alike`): the flag says split, so everything vertical
2065/// or split lands on it.
2066const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2067
2068/// The same for a superblock hanging off the right-hand edge
2069/// (`partition_gather_horz_alike`).
2070const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2071
2072/// Mode-info units across a 32x32 block.
2073pub(crate) const BLOCK_MI: u32 = SB_MI / 2;
2074
2075/// Mode-info units across a 16x16 block, the smallest this crate's key-frame
2076/// writer codes.
2077pub(crate) const SUB_MI: u32 = BLOCK_MI / 2;
2078
2079/// spec `decode_partition`'s `hasRows`/`hasCols` (5.11.4), recomputed at
2080/// whichever block size is asking: a block of `side_mi` mode-info units at mi
2081/// position `pos` may be coded unsplit (its own `PARTITION_NONE`) only when
2082/// this is true in both directions -- the frame's *true* size can put the
2083/// boundary inside a superblock, a 32x32 quadrant or (since this writer's
2084/// smallest block is 16x16) even a leaf, and each level must ask again with
2085/// its own half, not just once at the superblock.
2086pub(crate) fn has_half(pos: u32, side_mi: u32, bound: u32) -> bool {
2087 pos + side_mi / 2 < bound
2088}
2089
2090/// The number of 32x32 block columns/rows a frame whose *true* (unpadded)
2091/// size gives `mi_cols`/`mi_rows` is coded over: every block whose mi origin
2092/// (`col * BLOCK_MI`) is inside the true bound is coded, so this is a
2093/// ceiling, not the exact division a block-aligned frame would give. Shared
2094/// by the tile writer's own iteration and by [`crate::encode`]'s block/
2095/// superblock generation, which must agree with it exactly.
2096pub(crate) fn block_grid(mi_cols: u32, mi_rows: u32) -> (u32, u32) {
2097 (mi_cols.div_ceil(BLOCK_MI), mi_rows.div_ceil(BLOCK_MI))
2098}
2099/// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode.
2100const DC_PRED: usize = 0;
2101
2102/// `V_PRED` (spec 6.10.2), the first of the eight directional intra modes and
2103/// so the first mode that carries an angle delta.
2104const V_PRED: usize = 1;
2105
2106/// `H_PRED`, which predicts every row from the column to the block's left.
2107#[cfg(test)]
2108const H_PRED: usize = 2;
2109
2110/// The last directional mode, `D67_PRED`.
2111const D67_PRED: usize = 8;
2112
2113/// The number of intra modes a key frame's luma block chooses from,
2114/// `INTRA_MODES` (spec 3).
2115const INTRA_MODES: usize = 13;
2116
2117/// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts
2118/// its neighbours in when they pick the CDF for the next block's mode.
2119pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0];
2120
2121/// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
2122/// +3, so `MAX_ANGLE_DELTA` is the middle of it.
2123pub(crate) const ANGLE_DELTA_ZERO: usize = 3;
2124/// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
2125pub(crate) const SB_MI: u32 = 16;
2126
2127/// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
2128const NUM_BASE_LEVELS: i32 = 2;
2129/// Where DCT_DCT sits in the spec's `Tx_Type_Intra_Inv_Set2`, the set a 16x16
2130/// intra luma transform picks its type from.
2131const TX_TYPE_DCT_DCT_SET2: usize = 1;
2132/// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
2133/// Golomb tail takes over.
2134const COEFF_BASE_RANGE: i32 = 12;
2135/// `BR_CDF_SIZE - 1` (spec 3): the largest increment one base-range symbol
2136/// carries.
2137const BR_STEP: i32 = 3;
2138/// The largest level the base and base-range syntax carry between them.
2139/// Anything above it is written as a Golomb tail on top of this.
2140const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2141/// The largest level this writer codes. The Golomb tail is a length in unary
2142/// followed by that many bits, and the spec's decoder reads at most twenty of
2143/// each, so a level a decoder cannot read back is refused rather than written.
2144const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
2145
2146/// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s
2147/// leading index) a frame's `base_q_idx` picks its default CDFs from.
2148/// [`crate::cdf`] carries all four, one constant set per context.
2149pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
2150 match base_q_idx {
2151 0..=20 => 0,
2152 21..=60 => 1,
2153 61..=120 => 2,
2154 _ => 3,
2155 }
2156}
2157
2158/// Both writers here code whole superblocks only: a partial one forces the
2159/// partition syntax down the block tree, which they do not code yet.
2160/// The probability the CDF gives one symbol on its own.
2161fn element_prob(cdf: &[u16], element: usize) -> u16 {
2162 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2163}
2164
2165/// The two-symbol CDF a partial superblock's partition flag is coded with: the
2166/// mass of the listed partition types becomes the probability of a split, and
2167/// the rest is the one partition the frame edge still allows.
2168fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
2169 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
2170 [32768 - split, 32768, 0]
2171}
2172
2173fn check_superblocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
2174 if mi_cols == 0
2175 || mi_rows == 0
2176 || !mi_cols.is_multiple_of(SB_MI)
2177 || !mi_rows.is_multiple_of(SB_MI)
2178 {
2179 return Err(Error::unsupported(
2180 "AV1 tile",
2181 "a key frame is written only for frames that are a whole number \
2182 of 64x64 superblocks",
2183 ));
2184 }
2185 Ok(())
2186}
2187
2188/// Writes the payload of a one-tile key frame in which every superblock is a
2189/// skipped 64x64 DC-predicted block.
2190///
2191/// `mi_cols` and `mi_rows` are the frame's dimensions in 4x4 mode-info units,
2192/// as the frame header carries them.
2193///
2194/// # Errors
2195/// Returns an error when the frame is not a whole number of 64x64 superblocks:
2196/// a partial superblock forces the partition syntax down the block tree, which
2197/// this writer does not code yet.
2198pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {
2199 check_superblocks(mi_cols, mi_rows)?;
2200 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2201
2202 let mut enc = SymbolEncoder::new();
2203 for r in 0..sb_rows {
2204 for c in 0..sb_cols {
2205 // decode_partition (spec 5.11.4). Every neighbour is a 64x64 block,
2206 // whose stored partition context has a zero bit at this block
2207 // size, so the context is 0 wherever the block sits.
2208 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
2209
2210 // intra_frame_mode_info (spec 5.11.16). Segmentation, delta q,
2211 // delta lf, palette, filter intra and intrabc are all off in the
2212 // frame header, and a skipped block codes no CDEF index, so the
2213 // block is three symbols: the skip flag and the two modes.
2214 let skip_ctx = usize::from(r > 0) + usize::from(c > 0);
2215 enc.symbol_fixed(1, &cdf::SKIP[skip_ctx]);
2216 // Both neighbours are DC-predicted, and an unavailable neighbour
2217 // counts as DC too, so both mode contexts are 0.
2218 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2219 // Chroma from luma is only offered up to 32x32, so the CFL-free
2220 // table is the one a 64x64 block reads.
2221 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
2222
2223 // read_block_tx_size codes nothing while the frame's tx_mode is
2224 // TX_MODE_LARGEST, and a skipped block has no residual, so the
2225 // block ends here.
2226 }
2227 }
2228 Ok(enc.finish())
2229}
2230
2231/// Writes the payload of a one-tile key frame in which every superblock is a
2232/// 64x64 DC-predicted block carrying one luma DC coefficient of `dc_level` and
2233/// no chroma residual.
2234///
2235/// `dc_level` is a quantised level, not a sample value: the decoder multiplies
2236/// it by the frame's DC quantiser and inverse-transforms it over the whole
2237/// block, so the picture it makes is a flat grey some distance either side of
2238/// the mid-grey a zero level gives. `base_q_idx` is the frame header's, and
2239/// picks the coefficient CDFs.
2240///
2241/// # Errors
2242/// As [`dc_key_frame_tile_levels`], which this is the one-level case of.
2243pub fn dc_key_frame_tile(
2244 mi_cols: u32,
2245 mi_rows: u32,
2246 base_q_idx: u8,
2247 dc_level: i32,
2248) -> Result<Vec<u8>> {
2249 check_superblocks(mi_cols, mi_rows)?;
2250 let blocks = ((mi_cols / SB_MI) * (mi_rows / SB_MI)) as usize;
2251 dc_key_frame_tile_levels(mi_cols, mi_rows, base_q_idx, &vec![dc_level; blocks])
2252}
2253
2254/// Writes the payload of a one-tile key frame carrying one luma DC coefficient
2255/// per superblock, `levels` giving them in the raster order the superblocks are
2256/// coded in.
2257///
2258/// Each superblock decodes to a flat block of its own grey, so a frame written
2259/// here is a grid of greys the caller chooses — which is what makes the sign
2260/// context observable: a block's sign context is read off its coded neighbours,
2261/// and a frame whose levels differ in sign exercises the three-way split that a
2262/// single-sign frame cannot reach.
2263///
2264/// # Errors
2265/// Returns an error when the frame is not a whole number of 64x64 superblocks,
2266/// when `levels` does not carry exactly one level per superblock, when a level
2267/// is outside the range the base and base-range syntax carry (`-14..=14`
2268/// without zero).
2269pub fn dc_key_frame_tile_levels(
2270 mi_cols: u32,
2271 mi_rows: u32,
2272 base_q_idx: u8,
2273 levels: &[i32],
2274) -> Result<Vec<u8>> {
2275 check_superblocks(mi_cols, mi_rows)?;
2276 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2277 check_levels(levels, (sb_cols * sb_rows) as usize)?;
2278 let q_ctx = q_ctx_of(base_q_idx);
2279 let txb_skip_luma_64 = crate::cdf_state::pick(
2280 q_ctx,
2281 cdf::TXB_SKIP_LUMA_64_Q0,
2282 cdf::TXB_SKIP_LUMA_64_Q1,
2283 cdf::TXB_SKIP_LUMA_64,
2284 cdf::TXB_SKIP_LUMA_64_Q3,
2285 );
2286 let base_eob_luma_64_dc = crate::cdf_state::pick(
2287 q_ctx,
2288 cdf::COEFF_BASE_EOB_LUMA_64_Q0[0],
2289 cdf::COEFF_BASE_EOB_LUMA_64_Q1[0],
2290 cdf::COEFF_BASE_EOB_LUMA_64[0],
2291 cdf::COEFF_BASE_EOB_LUMA_64_Q3[0],
2292 );
2293 let txb_skip_chroma_32_none = crate::cdf_state::pick(
2294 q_ctx,
2295 cdf::TXB_SKIP_CHROMA_32_Q0[0],
2296 cdf::TXB_SKIP_CHROMA_32_Q1[0],
2297 cdf::TXB_SKIP_CHROMA_32[0],
2298 cdf::TXB_SKIP_CHROMA_32_Q3[0],
2299 );
2300
2301 // The sign of the DC each coded block left behind, for the two neighbours
2302 // the sign context is read from: one row of them above, and the block to
2303 // the left, which is dropped at the start of every superblock row the way a
2304 // decoder clears its left context there.
2305 let mut above: Vec<Option<bool>> = vec![None; sb_cols as usize];
2306 let mut enc = SymbolEncoder::new();
2307 for r in 0..sb_rows {
2308 let mut left: Option<bool> = None;
2309 for c in 0..sb_cols {
2310 let dc_level = levels[(r * sb_cols + c) as usize];
2311 let negative = dc_level < 0;
2312
2313 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
2314
2315 // Nothing is skipped now, so every neighbour's skip flag is 0 and
2316 // the skip context stays 0 across the frame.
2317 enc.symbol_fixed(0, &cdf::SKIP[0]);
2318 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2319 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
2320
2321 write_dc_coeffs(
2322 &mut enc,
2323 dc_level,
2324 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)),
2325 q_ctx,
2326 &txb_skip_luma_64,
2327 &base_eob_luma_64_dc,
2328 );
2329
2330 // Both chroma transform blocks are all-zero. Their planes carry no
2331 // coded coefficient anywhere in the frame, so the neighbour halves
2332 // of their context stay 0 and only the offset for a transform block
2333 // that covers its whole plane block is left: context 7.
2334 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
2335 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
2336
2337 above[c as usize] = Some(negative);
2338 left = Some(negative);
2339 }
2340 }
2341 Ok(enc.finish())
2342}
2343
2344/// Writes the payload of a one-tile key frame in which every superblock is
2345/// split into four 32x32 DC-predicted blocks, each carrying one luma DC
2346/// coefficient and no chroma residual.
2347///
2348/// `levels` gives one level per 32x32 block in raster order across the frame,
2349/// so the grid is twice as wide and twice as tall as the superblock grid. The
2350/// blocks are coded in the z-order a superblock's split walks, but every
2351/// block's neighbours above and to its left are coded before it either way, so
2352/// the picture reads in raster order.
2353///
2354/// # Errors
2355/// As [`dc_key_frame_tile_levels`], with `levels` sized for the 32x32 grid.
2356pub fn split_dc_key_frame_tile(
2357 mi_cols: u32,
2358 mi_rows: u32,
2359 base_q_idx: u8,
2360 levels: &[i32],
2361) -> Result<Vec<u8>> {
2362 check_superblocks(mi_cols, mi_rows)?;
2363 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2364 let (cols, rows) = (sb_cols * 2, sb_rows * 2);
2365 check_levels(levels, (cols * rows) as usize)?;
2366 let q_ctx = q_ctx_of(base_q_idx);
2367 let txb_skip_luma_32 = crate::cdf_state::pick(
2368 q_ctx,
2369 cdf::TXB_SKIP_LUMA_32_Q0,
2370 cdf::TXB_SKIP_LUMA_32_Q1,
2371 cdf::TXB_SKIP_LUMA_32,
2372 cdf::TXB_SKIP_LUMA_32_Q3,
2373 );
2374 let base_eob_luma_32 = crate::cdf_state::pick(
2375 q_ctx,
2376 cdf::COEFF_BASE_EOB_LUMA_32_Q0[0],
2377 cdf::COEFF_BASE_EOB_LUMA_32_Q1[0],
2378 cdf::COEFF_BASE_EOB_LUMA_32[0],
2379 cdf::COEFF_BASE_EOB_LUMA_32_Q3[0],
2380 );
2381 let txb_skip_chroma_16_0 = crate::cdf_state::pick(
2382 q_ctx,
2383 cdf::TXB_SKIP_CHROMA_16_Q0[0],
2384 cdf::TXB_SKIP_CHROMA_16_Q1[0],
2385 cdf::TXB_SKIP_CHROMA_16[0],
2386 cdf::TXB_SKIP_CHROMA_16_Q3[0],
2387 );
2388
2389 let mut above: Vec<Option<bool>> = vec![None; cols as usize];
2390 let mut left: Vec<Option<bool>> = vec![None; rows as usize];
2391
2392 let mut enc = SymbolEncoder::new();
2393 for sb_r in 0..sb_rows {
2394 // A decoder clears its left context at the start of every superblock
2395 // row, and so does the partition context the 64x64 symbol reads.
2396 left.iter_mut().for_each(|l| *l = None);
2397 for sb_c in 0..sb_cols {
2398 // The partition context of a 64x64 block reads the bit its
2399 // neighbours' block size sets at this depth: a 32x32 neighbour sets
2400 // it, and an uncoded one leaves it clear, so the context is just
2401 // which neighbours exist. The 32x32 blocks below read a bit their
2402 // own size leaves clear, so their context is 0 throughout.
2403 // Every superblock here is split, so an existing neighbour always
2404 // sets that bit.
2405 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
2406 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
2407
2408 for quadrant in 0..4 {
2409 let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
2410 let dc_level = levels[(r * cols + c) as usize];
2411 let negative = dc_level < 0;
2412
2413 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
2414 enc.symbol_fixed(0, &cdf::SKIP[0]);
2415 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2416 // Chroma from luma is offered up to 32x32, so the block reads
2417 // the wider table even though it does not take the mode.
2418 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL[DC_PRED]);
2419
2420 write_dc_coeffs(
2421 &mut enc,
2422 dc_level,
2423 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])),
2424 q_ctx,
2425 &txb_skip_luma_32,
2426 &base_eob_luma_32,
2427 );
2428 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
2429 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
2430
2431 above[c as usize] = Some(negative);
2432 left[r as usize] = Some(negative);
2433 }
2434 }
2435 }
2436 Ok(enc.finish())
2437}
2438
2439/// One quantised coefficient of a transform block.
2440///
2441/// `row` and `col` are its position in the transform it belongs to — 32x32 for
2442/// luma, 16x16 for each chroma plane — not in the picture: a coefficient at
2443/// row 0 varies along the picture's width and one at column 0 along its
2444/// height, and the coefficient at the origin is the DC the block's average
2445/// sample value rides on.
2446#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2447pub struct Coeff {
2448 /// The coefficient's row in the transform.
2449 pub row: u8,
2450 /// The coefficient's column in the transform.
2451 pub col: u8,
2452 /// Its quantised level, which the base and base-range syntax carry for
2453 /// magnitudes up to [`MAX_LEVEL`].
2454 pub level: i32,
2455}
2456
2457/// The coefficients of one coded block: a 32x32 luma transform and, at 4:2:0,
2458/// the 16x16 transform each chroma plane covers the same area with.
2459#[derive(Clone, Debug, Default, PartialEq, Eq)]
2460pub struct BlockCoeffs {
2461 /// The luma transform's coefficients.
2462 pub luma: Vec<Coeff>,
2463 /// One transform type per luma transform unit, raster order (lane-txset).
2464 /// Empty is `DCT_DCT` throughout -- what every block coded before the
2465 /// search offered a type, and what an inter block still carries.
2466 pub luma_tx_types: Vec<TxType>,
2467 /// The U plane's.
2468 pub u: Vec<Coeff>,
2469 /// The V plane's.
2470 pub v: Vec<Coeff>,
2471 /// The luma intra mode the block is predicted with, one of the thirteen
2472 /// modes a key frame codes (`DC_PRED` is zero, which is what
2473 /// [`Default`] and a plain coefficient list give).
2474 pub mode: u8,
2475 /// The chroma intra mode both chroma planes are predicted with (spec
2476 /// `uv_mode`, one symbol for the pair). `DC_PRED` is zero, which is what
2477 /// [`Default`] gives; a non-`DC_PRED` mode also changes the transform
2478 /// type the decoder derives for chroma (`Intra_Mode_To_Tx_Type`, spec
2479 /// 9.3), which is never coded as a symbol.
2480 pub uv_mode: u8,
2481 /// Whether the block carries no residual at all (spec `skip`). An intra
2482 /// block may still be skipped; `false` (the [`Default`]) codes whatever
2483 /// `luma`/`u`/`v` carry.
2484 pub skip: bool,
2485 /// The block's inter mode and motion vector, or `None` for an intra
2486 /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key
2487 /// frame writers never read this field.
2488 pub inter: Option<InterInfo>,
2489 /// This (single-reference inter) block's spec `motion_mode`, written by
2490 /// [`write_motion_mode`]: 0 `SIMPLE_TRANSLATION` (the [`Default`], and
2491 /// the only mode this writer coded before lane-av1obmc), 1 `OBMC_CAUSAL`,
2492 /// 2 `WARPED_CAUSAL` (lane-av1obmc2).
2493 pub motion_mode: u8,
2494 /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect),
2495 /// each with its own 8x8 luma transform and 4x4 chroma transforms, in
2496 /// raster order among the leaves that are inside the true frame. `Some`
2497 /// overrides this `BlockCoeffs`'s own `luma`/`u`/`v`/`mode`, which are left
2498 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
2499 /// per-quadrant fields are unused.
2500 pub eight: Option<Vec<BlockCoeffs>>,
2501 /// The luma palette this block is predicted with (spec 5.11.46
2502 /// `palette_mode_info`), or `None` for an ordinary intra block. Only a
2503 /// `DC_PRED` block on a frame whose header set
2504 /// `allow_screen_content_tools` may carry one, and it forces
2505 /// `tx_depth` to zero (the whole block is one transform over the
2506 /// palette's own prediction).
2507 pub palette: Option<PaletteY>,
2508 /// The chroma palette this block's two chroma planes are predicted with
2509 /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a
2510 /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry
2511 /// one; it is independent of [`Self::palette`] (either, both or neither).
2512 pub palette_uv: Option<PaletteUv>,
2513 /// How many times this block's luma transform is halved under
2514 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
2515 /// block). Read only by the writers a `tx_select` frame calls; a
2516 /// `TxMode::Largest` frame codes no symbol and leaves this at zero.
2517 /// `luma` then carries the whole block's levels in BLOCK coordinates,
2518 /// which the writer slices per transform unit.
2519 pub tx_depth: u8,
2520 /// This block's `UV_CFL_PRED` alphas (`alpha_q3` for U and V, spec
2521 /// 5.11.45's `cfl_alpha_signs`/`cfl_alpha_u`/`cfl_alpha_v`), or `None` for
2522 /// any other chroma mode. `Some` iff [`Self::uv_mode`] is
2523 /// [`UV_CFL_PRED`]; at least one of the pair is nonzero, since the joint
2524 /// sign symbol has no (ZERO, ZERO) value.
2525 pub cfl_alphas: Option<(i32, i32)>,
2526 /// This block's `filter_intra_mode` (spec 5.11.14, 0..=4) when it is
2527 /// coded with recursive filter intra, or `None`. `Some` only on a DC_PRED
2528 /// luma block of at most 32x32 with no luma palette, on a sequence whose
2529 /// header set `enable_filter_intra` ([`arm_filter_intra`]); the block's
2530 /// luma transform types are then coded from
2531 /// `fimode_to_intradir[filter_intra_mode]`'s row ([`tx_row`]) while its
2532 /// neighbour mode stays `DC_PRED`.
2533 pub filter_intra: Option<u8>,
2534 /// This block's `angle_delta_y` (spec `read_intra_angle_info`, -3..=3),
2535 /// zero for every non-directional luma mode -- which is what
2536 /// [`Default`] gives, and what every writer coded before lane-av1cfl.
2537 pub angle_delta_y: i8,
2538 /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
2539 /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
2540 /// an ordinary intra block. Only a key frame whose header set
2541 /// `allow_intrabc` ([`arm_intrabc`]) may carry one; the block is then
2542 /// coded `skip` with no residual, no mode, no palette -- exactly what
2543 /// decode.rs `read_intra_mode` reads back and returns early on.
2544 ///
2545 /// lane-av1ibc corner-cut, ceiling named: a residual-carrying intrabc
2546 /// block needs the INTER coefficient tables plus the var-tx tree
2547 /// decode.rs `decode_block`'s `intrabc_vartx` arm reads; the upgrade path
2548 /// is to route the block through [`write_tx_syntax_inter`] instead of
2549 /// returning early here.
2550 pub dv: Option<(i32, i32)>,
2551}
2552
2553/// A block's luma palette: its base colours (ascending, only the first
2554/// `size` entries are real) and the per-pixel colour-index map, `side*side`
2555/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back
2556/// out of the stream.
2557#[derive(Clone, Debug, Default, PartialEq, Eq)]
2558pub struct PaletteY {
2559 /// How many base colours, 2..=8 (spec `PaletteSizeY`).
2560 pub size: u8,
2561 /// The base colours, ascending.
2562 pub colors: [u16; 8],
2563 /// Which colour each pixel takes, row-major over the block's own side.
2564 pub map: Vec<u8>,
2565}
2566
2567/// As [`PaletteY`], for a block's chroma palette -- one colour-index map
2568/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes
2569/// are co-located after 4:2:0 subsampling) plus each plane's own base
2570/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of
2571/// the stream.
2572#[derive(Clone, Debug, Default, PartialEq, Eq)]
2573pub struct PaletteUv {
2574 /// How many base colours, 2..=8 (spec `PaletteSizeUV`).
2575 pub size: u8,
2576 /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv`
2577 /// merges the cached and transmitted lists as two ascending runs, and its
2578 /// delta form only ever steps upwards.
2579 pub u_colors: [u16; 8],
2580 /// V's base colours, in the same cluster order as [`Self::u_colors`] --
2581 /// the shared map indexes both, and V's own coding needs no ordering.
2582 pub v_colors: [u16; 8],
2583 /// Which colour each chroma pixel takes, row-major over the subsampled
2584 /// block's own `(side / 2).max(4)` side.
2585 pub map: Vec<u8>,
2586}
2587
2588/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
2589/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
2590/// [`write_inter_mode`] with the decoder's own contexts.
2591#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2592pub enum InterMode {
2593 /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
2594 NearestMv,
2595 /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names
2596 /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode).
2597 NearMv,
2598 /// `GLOBALMV`: the identity global model's zero vector, two symbols and
2599 /// no MV at all.
2600 GlobalMv,
2601 /// `NEWMV`: codes `mv` as a residual against the stack entry
2602 /// [`InterInfo::ref_mv_idx`] names.
2603 NewMv,
2604 /// `NEAREST_NEARESTMV`: both sides take the compound stack's own nearest
2605 /// pair, no residual, no DRL.
2606 NearestNearestMv,
2607 /// `NEAR_NEARMV`: both sides take compound stack entry
2608 /// [`InterInfo::ref_mv_idx`]` + 1` (decode.rs `assign_compound_mv`'s own
2609 /// `ref_mv_idx + 1`), reached by a DRL walk that starts at index 1.
2610 NearNearMv,
2611 /// `NEAREST_NEWMV`: the first side takes the stack's nearest vector, the
2612 /// second codes a residual against stack entry 0.
2613 NearestNewMv,
2614 /// `NEW_NEARESTMV`: the first side codes a residual against stack entry 0,
2615 /// the second takes the stack's nearest vector.
2616 NewNearestMv,
2617 /// `GLOBAL_GLOBALMV`: both sides take the identity global model's zero
2618 /// vector.
2619 GlobalGlobalMv,
2620 /// `NEW_NEWMV`: both sides code a residual against the compound stack
2621 /// entry [`InterInfo::ref_mv_idx`] names.
2622 NewNewMv,
2623}
2624
2625impl InterMode {
2626 /// The spec's `INTER_COMPOUND_MODES` index (libaom `enums.h` order,
2627 /// `NEAREST_NEARESTMV = 0`..`NEW_NEWMV = 7`) for a compound mode, `None`
2628 /// for a single-reference one.
2629 fn compound_index(self) -> Option<usize> {
2630 match self {
2631 InterMode::NearestNearestMv => Some(0),
2632 InterMode::NearNearMv => Some(1),
2633 InterMode::NearestNewMv => Some(2),
2634 InterMode::NewNearestMv => Some(3),
2635 InterMode::GlobalGlobalMv => Some(6),
2636 InterMode::NewNewMv => Some(7),
2637 _ => None,
2638 }
2639 }
2640}
2641
2642/// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
2643/// `(row, col)` units. For [`InterMode::NearestMv`] this writer ignores `mv`
2644/// and codes the stack's own candidate instead — the decoder derives it, so
2645/// nothing here can disagree with it.
2646#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2647pub struct InterInfo {
2648 /// The mode this block is coded with.
2649 pub mode: InterMode,
2650 /// The motion vector a [`InterMode::NewMv`] block's residual targets.
2651 pub mv: (i32, i32),
2652 /// The reference this block predicts from (`LAST_FRAME`..=`ALTREF_FRAME`,
2653 /// spec 6.10.24's alphabet), written by [`write_single_ref`].
2654 pub ref_frame: i8,
2655 /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which
2656 /// `MvStack::entries` slot `NEWMV` codes its residual against, or
2657 /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
2658 /// index (`NEARESTMV`, `GLOBALMV`).
2659 pub ref_mv_idx: u8,
2660 /// The block's second reference (spec `RefFrames[1]`), `None` for a
2661 /// single-reference block. `Some` only on a `reference_select` frame, and
2662 /// only beside one of [`InterMode`]'s compound modes.
2663 pub ref1: Option<i8>,
2664 /// The motion vector into `ref1`, for the compound modes that code one
2665 /// (`NEW_NEWMV`); the other two derive both sides.
2666 pub mv1: (i32, i32),
2667}
2668
2669impl From<Vec<Coeff>> for BlockCoeffs {
2670 /// A block that codes luma only.
2671 fn from(luma: Vec<Coeff>) -> Self {
2672 Self {
2673 luma,
2674 ..Self::default()
2675 }
2676 }
2677}
2678
2679/// Side of the luma transform the coefficient writer codes.
2680const TX32: usize = 32;
2681/// Side of the larger of the two blocks a superblock splits into, in samples.
2682const BLOCK: usize = 32;
2683/// Side of the chroma transform beside it at 4:2:0, and of the luma transform
2684/// of a 16x16 block.
2685const TX16: usize = 16;
2686/// Side of the chroma transform of a 16x16 block at 4:2:0, and of the luma
2687/// transform of an 8x8 leaf under a straddling 16x16 (lane-av1-rect).
2688const TX8: usize = 8;
2689/// Side of the chroma transform of an 8x8 leaf at 4:2:0 (lane-av1-rect).
2690const TX4: usize = 4;
2691/// Side of a superblock, in samples, which is the size a block outside the
2692/// tile reads as.
2693const SB: usize = 64;
2694
2695/// The `above_side`/`left_side` value a cell with no coded neighbour holds
2696/// (tile start, superblock-row start) -- the writer's copy of
2697/// `crate::decode::NO_NEIGHBOUR_SIDE`, and 128 for the same reason: at 64 it
2698/// reads identically at every level up to 64x64 but sets the bit at the
2699/// `BLOCK_128X128` root (64 * 2 <= 128), putting that root's partition symbol
2700/// on CDF row 3 where libaom uses row 0.
2701const NO_NEIGHBOUR_SIDE: usize = 128;
2702/// Side of the smallest block the writer codes, in samples, which is the grid
2703/// the neighbour bookkeeping is kept on.
2704const SUB: usize = 16;
2705/// Side of a 4x4 mode-info unit, in samples: the granularity libaom's above
2706/// and left entropy-context arrays are actually kept on (spec
2707/// `get_txb_ctx`/`av1_set_entropy_contexts`), finer than [`SUB`].
2708const MI: usize = 4;
2709
2710/// What one coded block leaves behind for the blocks that read it as a
2711/// neighbour: whether it coded anything at all, and the sign of its DC.
2712#[derive(Clone, Copy, Default)]
2713struct Neighbour {
2714 /// Whether the plane's transform block carried a coefficient.
2715 coded: bool,
2716 /// Its cumulative coefficient level (spec `cul_level`, clamped to 7) --
2717 /// what the *luma* `txb_skip_ctx` of a transform unit smaller than its
2718 /// own block reads (`get_txb_ctx_general`, decode.rs `luma_skip_ctx`),
2719 /// where "coded or not" is not enough.
2720 level: u8,
2721 /// The sign of its DC, absent when the DC itself is zero.
2722 dc: Option<bool>,
2723}
2724
2725/// Rejects a frame with no mode-info grid at all.
2726///
2727/// `mi_cols`/`mi_rows` are the frame's *true* (unpadded) size in 4x4 units
2728/// (spec `compute_image_size`), not necessarily a multiple of the 32x32 block
2729/// grid: a block whose origin sits at or past this bound is not coded (spec's
2730/// `decode_partition` never visits it), and one that straddles the bound is
2731/// coded whole, its samples coming from the padded planes.
2732fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
2733 if mi_cols == 0 || mi_rows == 0 {
2734 return Err(Error::unsupported(
2735 "AV1 tile",
2736 "a coefficient key frame needs a nonzero mode-info grid",
2737 ));
2738 }
2739 Ok(())
2740}
2741
2742/// The coefficients of one superblock: either one 64x64 block covering it, or
2743/// the four 32x32 blocks it is split into.
2744///
2745/// A superblock at the right-hand or bottom edge of the frame may be half
2746/// outside it, and such a superblock cannot be left whole — the spec has no
2747/// partition that keeps a block outside the frame — so it must be
2748/// [`Split`](Superblock::Split), and carries only the quadrants that are
2749/// inside, in raster order among themselves.
2750#[derive(Clone, Debug, PartialEq, Eq)]
2751pub enum Superblock {
2752 /// One 64x64 block, whose luma transform is 64x64 — of which only the
2753 /// top-left 32x32 carries coefficients — and whose chroma transforms are
2754 /// 32x32 each at 4:2:0.
2755 Whole(BlockCoeffs),
2756 /// The 32x32 quadrants the superblock is split into, each either one
2757 /// block or four 16x16 blocks of its own.
2758 Split(Vec<Quadrant>),
2759}
2760
2761/// One 32x32 quadrant of a split superblock.
2762#[derive(Clone, Debug, PartialEq, Eq)]
2763pub enum Quadrant {
2764 /// One 32x32 block, with a 32x32 luma transform and a 16x16 transform per
2765 /// chroma plane.
2766 Whole(BlockCoeffs),
2767 /// The four 16x16 blocks it is split into, in raster order, each with a
2768 /// 16x16 luma transform and an 8x8 transform per chroma plane.
2769 Split(Vec<BlockCoeffs>),
2770 /// lane-b64: not a quadrant at all -- the whole 64x64 superblock this
2771 /// quadrant is the TOP-LEFT of, coded as one block (`PARTITION_NONE` at
2772 /// `BLOCK_64X64`). Only the top-left quadrant of a superblock carries it
2773 /// and the other three carry [`Covered`](Quadrant::Covered), so the
2774 /// per-32x32-entry shape the inter writer takes is unchanged.
2775 ///
2776 /// The block is single-reference; the writer refuses a compound one. It
2777 /// may be skipped or carry a real residual -- one TX_64X64 luma transform
2778 /// whose coded quarter is a 32x32 level grid, and one TX_32X32 per chroma
2779 /// plane (lane-tx64, `crate::encode::b64_residual`).
2780 Whole64(BlockCoeffs),
2781 /// lane-b128: the whole 128x128 SUPERBLOCK ROOT this quadrant is the
2782 /// top-left of, coded as one block (`PARTITION_NONE` at the root's
2783 /// `partition_w128` symbol). Carried by the top-left 32x32 entry of the
2784 /// root's sixteen; the other fifteen carry [`Covered`](Quadrant::Covered).
2785 ///
2786 /// SKIP only: a 128x128 block's residual is four TX_64X64 luma units
2787 /// interleaved with its chroma per 64x64 mu chunk, which this writer has
2788 /// no path for; [`crate::tile::write_inter_block_128`] refuses one.
2789 Whole128(BlockCoeffs),
2790 /// lane-b128hv: the two 128x64 (`true`) or 64x128 (`false`) inter blocks a
2791 /// `PARTITION_HORZ` / `PARTITION_VERT` 128 superblock root carries, in the
2792 /// order the decoder reads them (top then bottom, left then right).
2793 /// Carried by the top-left 32x32 entry of the root's sixteen, exactly as
2794 /// [`Whole128`](Quadrant::Whole128) is.
2795 ///
2796 /// Skip-only by default; a piece carries a real residual under
2797 /// `EC_AV1_RECTRES` (`crate::encode::rectres`), single reference or
2798 /// compound either way.
2799 Rect128(bool, Vec<BlockCoeffs>),
2800 /// lane-ab128: the THREE inter blocks an AB shape at a 128 superblock
2801 /// root carries -- two 64x64 pieces and one 128x64 / 64x128 half -- in
2802 /// the order the decoder reads them
2803 /// ([`crate::encode::ab128_pieces`]). The `u8` is the partition symbol
2804 /// itself (4 `PARTITION_HORZ_A` .. 7 `PARTITION_VERT_B`). Carried by the
2805 /// top-left 32x32 entry of the root's sixteen, exactly as
2806 /// [`Rect128`](Quadrant::Rect128) is.
2807 ///
2808 /// Skip-only by default, same writer; under `EC_AV1_RECTRES` any of the
2809 /// three pieces may carry a real residual.
2810 Ab128(u8, Vec<BlockCoeffs>),
2811 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
2812 /// top-left already coded; it carries no block of its own.
2813 Covered,
2814}
2815
2816impl Quadrant {
2817 /// The blocks it carries, in the order they are coded.
2818 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {
2819 match self {
2820 Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {
2821 std::slice::from_ref(block)
2822 }
2823 Quadrant::Split(blocks)
2824 | Quadrant::Rect128(_, blocks)
2825 | Quadrant::Ab128(_, blocks) => blocks.as_slice(),
2826 Quadrant::Covered => &[],
2827 }
2828 }
2829}
2830
2831/// What the blocks above and to the left of the one being coded left behind,
2832/// kept on the 16x16 grid the smallest block sits on.
2833struct Neighbours {
2834 /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/
2835 /// `MiColStart`): every "is there a neighbour above/left of me" answer is
2836 /// TILE-relative, not frame-relative -- the decoder's own
2837 /// `Neighbours::start_tile` sets the same pair, and a writer that asked
2838 /// `mi_row > 0` instead coded a tile's own first row against a neighbour
2839 /// the decoder does not have (class: new map ignores tile edge).
2840 tile_row0_mi: usize,
2841 tile_col0_mi: usize,
2842 /// Per plane, whether the neighbour coded anything and the sign of its DC.
2843 above: Vec<[Neighbour; 3]>,
2844 /// The same, down the left edge.
2845 left: Vec<[Neighbour; 3]>,
2846 /// The neighbour's luma intra mode, which picks the CDF the next block's
2847 /// mode is coded with.
2848 above_mode: Vec<usize>,
2849 /// The same, down the left edge.
2850 left_mode: Vec<usize>,
2851 /// The side of the neighbour block, in samples, which is what the
2852 /// partition symbol's context reads.
2853 above_side: Vec<usize>,
2854 /// The same, down the left edge.
2855 left_side: Vec<usize>,
2856 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
2857 /// granularity [`Self::above`]/[`Self::left`] are, rather than [`SUB`]:
2858 /// two 8x8 leaves of one straddling 16x16 block (lane-av1-rect) share a
2859 /// single [`SUB`]-grid cell, so a coarse array cannot tell the second
2860 /// leaf's partition symbol that the first one was coded at 8x8 (finer
2861 /// than the 16x16 it sits in) -- exactly what its `above`/`left` context
2862 /// needs to read (spec 9.3's `AbovePartitionContext`/`LeftPartitionContext`,
2863 /// which libaom keeps per mi unit for this reason).
2864 above_side_mi: Vec<usize>,
2865 /// The same, down the left edge.
2866 left_side_mi: Vec<usize>,
2867 /// Whether the neighbour carried no residual, for [`sb_coeff_inter_frame_tile`]'s
2868 /// skip context. Unused (and left at its default) by the key frame writers.
2869 /// Kept per 4x4 mode-info unit, like [`Self::above_side_mi`] and for the
2870 /// same reason: under a real PARTITION_SPLIT to 8x8 the four leaves of a
2871 /// 16x16 read (and leave) different contexts inside one [`SUB`] slot.
2872 above_skip: Vec<bool>,
2873 /// The same, down the left edge.
2874 left_skip: Vec<bool>,
2875 /// The side, in pixels, of the transform last written in this 4x4
2876 /// mode-info column -- the deblock `tx_grid` a key frame's
2877 /// `get_tx_size_context` reads (decode.rs `tx_size_context`/`tx_px_at`),
2878 /// which is what picks the CDF row of a `TxMode::Select` block's
2879 /// `tx_depth` symbol.
2880 above_tx: Vec<u8>,
2881 /// The same, down the left edge (the transform's HEIGHT, `tx_h_px_at`;
2882 /// every transform this writer codes is square, so one value serves).
2883 left_tx: Vec<u8>,
2884 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), per
2885 /// 4x4 mode-info unit: what an INTER frame's `txfm_split` and `tx_depth`
2886 /// symbols read their context from (decode.rs `txfm_partition_ctx_rect`/
2887 /// `tx_size_context_txfm_rect`). Initialised to the widest transform, not
2888 /// zero (decode.rs `TXFM_CTX_INIT`).
2889 above_txfm: Vec<u8>,
2890 /// The same, down the left edge (transform HEIGHT).
2891 left_txfm: Vec<u8>,
2892 /// The palette size each 4x4 mode-info column last left behind, and its
2893 /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and
2894 /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's
2895 /// own `above_palette_size`/`above_palette_colors` bands (decode.rs
2896 /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content
2897 /// frame writes them, `0` when it took no palette, so a stale size never
2898 /// survives into the next block's context.
2899 above_palette_size: Vec<u8>,
2900 /// The same, down the left edge.
2901 left_palette_size: Vec<u8>,
2902 /// What the block being written right now will leave in the two palette
2903 /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY
2904 /// block of either frame type passes through, so an inter block (or an
2905 /// intra block that took no palette) clears the bands rather than letting
2906 /// an earlier palette block's size stand (the neighbour-band hazard
2907 /// lane-t900 r23 hit on the decoder side).
2908 pending_palette: Option<(u8, [u16; 8])>,
2909 /// The colours beside [`Self::above_palette_size`].
2910 above_palette_colors: Vec<[u16; 8]>,
2911 /// The chroma (U-channel) halves of the three bands above --
2912 /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the
2913 /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`.
2914 above_palette_uv_size: Vec<u8>,
2915 left_palette_uv_size: Vec<u8>,
2916 above_palette_uv_colors: Vec<[u16; 8]>,
2917 left_palette_uv_colors: Vec<[u16; 8]>,
2918 /// [`Self::pending_palette`] for the chroma palette.
2919 pending_palette_uv: Option<(u8, [u16; 8])>,
2920 /// The same, down the left edge.
2921 left_palette_colors: Vec<[u16; 8]>,
2922 /// Whether the neighbour was coded inter, for the `is_inter` context.
2923 /// Unused by the key frame writers.
2924 above_inter: Vec<bool>,
2925 /// The same, down the left edge.
2926 left_inter: Vec<bool>,
2927 /// The reference each neighbour named, `-1` for an intra or unavailable
2928 /// one -- what the decoder keeps in its own `Neighbours::above_ref`
2929 /// (decode.rs) and feeds `read_single_ref`'s context functions.
2930 above_ref: Vec<i8>,
2931 /// The same, down the left edge.
2932 left_ref: Vec<i8>,
2933 /// Each neighbour's SECOND reference, `None` for a single-reference or
2934 /// intra one -- decode.rs `Neighbours::above_ref1`, read by every compound
2935 /// context function (`reference_mode_ctx`, `comp_reference_type_ctx`, the
2936 /// `comp_ref`/`comp_bwdref` votes).
2937 above_ref1: Vec<Option<i8>>,
2938 /// The same, down the left edge.
2939 left_ref1: Vec<Option<i8>>,
2940 /// What decode.rs `Neighbours::above_comp_group_idx` holds: a compound
2941 /// neighbour's own `comp_group_idx`, or libaom's single-reference special
2942 /// case (`3` for an ALTREF block, `0` otherwise).
2943 above_comp_group_idx: Vec<u8>,
2944 /// The same, down the left edge.
2945 left_comp_group_idx: Vec<u8>,
2946 /// The same for `compound_idx` (`1` for a single-ref ALTREF block).
2947 above_compound_idx: Vec<u8>,
2948 /// The same, down the left edge.
2949 left_compound_idx: Vec<u8>,
2950 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
2951 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
2952 /// `av1_set_entropy_contexts`): a block whose row or column run spills
2953 /// past this bound leaves its trailing 4x4 units at their default,
2954 /// mid-cell if need be.
2955 mi_cols: usize,
2956 mi_rows: usize,
2957}
2958
2959/// What one plane's neighbours leave for a block, gathered across every cell
2960/// the block spans -- which is what the decoder's own derivation reads
2961/// (spec 5.11.39), and what a single cell only stands in for while every block
2962/// is the same size.
2963#[derive(Clone, Copy, Default)]
2964struct Around {
2965 /// Whether any transform block above this one carried a coefficient.
2966 above_coded: bool,
2967 /// The same, to the left.
2968 left_coded: bool,
2969 /// The running vote of the neighbours' DC signs: negative DCs count down,
2970 /// positive ones up, and a neighbour with no DC does not count.
2971 dc_vote: i32,
2972}
2973
2974impl Neighbours {
2975 /// The state a tile starts from: a block outside it reads as `DC_PRED`,
2976 /// as having coded nothing, and as unsplit. `cols`/`rows` are in [`SUB`]
2977 /// units; `mi_cols`/`mi_rows` are the frame's true (unpadded) size in 4x4
2978 /// mode-info units.
2979 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
2980 Self {
2981 tile_row0_mi: 0,
2982 tile_col0_mi: 0,
2983 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
2984 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
2985 above_mode: vec![DC_PRED; cols],
2986 left_mode: vec![DC_PRED; rows],
2987 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
2988 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
2989 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
2990 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
2991 above_skip: vec![false; cols * (SUB / MI)],
2992 left_skip: vec![false; rows * (SUB / MI)],
2993 above_inter: vec![false; cols * (SUB / MI)],
2994 left_inter: vec![false; rows * (SUB / MI)],
2995 above_ref: vec![-1; cols * (SUB / MI)],
2996 left_ref: vec![-1; rows * (SUB / MI)],
2997 above_ref1: vec![None; cols * (SUB / MI)],
2998 left_ref1: vec![None; rows * (SUB / MI)],
2999 above_comp_group_idx: vec![0; cols * (SUB / MI)],
3000 left_comp_group_idx: vec![0; rows * (SUB / MI)],
3001 above_compound_idx: vec![0; cols * (SUB / MI)],
3002 left_compound_idx: vec![0; rows * (SUB / MI)],
3003 above_tx: vec![0; cols * (SUB / MI)],
3004 left_tx: vec![0; rows * (SUB / MI)],
3005 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
3006 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
3007 above_palette_size: vec![0; cols * (SUB / MI)],
3008 left_palette_size: vec![0; rows * (SUB / MI)],
3009 pending_palette: None,
3010 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
3011 above_palette_uv_size: vec![0; cols * (SUB / MI)],
3012 left_palette_uv_size: vec![0; rows * (SUB / MI)],
3013 above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)],
3014 left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)],
3015 pending_palette_uv: None,
3016 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
3017 mi_cols,
3018 mi_rows,
3019 }
3020 }
3021
3022 /// Clears the left edge, which a tile starts every superblock row with.
3023 /// Points this writer's availability answers at one tile
3024 /// ([`Self::tile_row0_mi`]).
3025 fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) {
3026 self.tile_row0_mi = row0_mi;
3027 self.tile_col0_mi = col0_mi;
3028 }
3029
3030 /// Whether the block at mode-info row `mi_r` has a neighbour above it
3031 /// INSIDE its own tile, and the same to the left.
3032 fn has_above(&self, mi_r: usize) -> bool {
3033 mi_r > self.tile_row0_mi
3034 }
3035
3036 fn has_left(&self, mi_c: usize) -> bool {
3037 mi_c > self.tile_col0_mi
3038 }
3039
3040 fn start_row(&mut self) {
3041 self.left.iter_mut().for_each(|l| *l = Default::default());
3042 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3043 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3044 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3045 self.left_skip.iter_mut().for_each(|s| *s = false);
3046 self.left_inter.iter_mut().for_each(|i| *i = false);
3047 self.left_ref.iter_mut().for_each(|r| *r = -1);
3048 self.left_ref1.iter_mut().for_each(|r| *r = None);
3049 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
3050 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
3051 self.left_tx.iter_mut().for_each(|t| *t = 0);
3052 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
3053 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
3054 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
3055 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
3056 }
3057
3058 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
3059 /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the
3060 /// `palette_y_mode` context (how many of the two neighbours took a
3061 /// palette) and the ascending, deduplicated colour cache the neighbours
3062 /// offer. `mi` is the block's own position in 4x4 units; this writer
3063 /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0`
3064 /// availability terms read against.
3065 fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) {
3066 // `av1_get_palette_cache` drops the above neighbour on a 64-px
3067 // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does
3068 // not, which is why the two terms below are asked separately.
3069 let above_ok = r % 16 != 0;
3070 let above_is_palette = r > 0 && self.above_palette_size[c] > 0;
3071 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3072 (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
3073 } else {
3074 (0, [0u16; 8])
3075 };
3076 let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 {
3077 (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
3078 } else {
3079 (0, [0u16; 8])
3080 };
3081 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
3082 let mut cache = Vec::with_capacity(16);
3083 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3084 if cache.last() != Some(&v) {
3085 cache.push(v);
3086 }
3087 };
3088 let (mut ai, mut li) = (0usize, 0usize);
3089 while ai < above_n && li < left_n {
3090 let (va, vl) = (above_colors[ai], left_colors[li]);
3091 if vl < va {
3092 push_dedup(&mut cache, vl);
3093 li += 1;
3094 } else {
3095 push_dedup(&mut cache, va);
3096 ai += 1;
3097 if vl == va {
3098 li += 1;
3099 }
3100 }
3101 }
3102 while ai < above_n {
3103 push_dedup(&mut cache, above_colors[ai]);
3104 ai += 1;
3105 }
3106 while li < left_n {
3107 push_dedup(&mut cache, left_colors[li]);
3108 li += 1;
3109 }
3110 (ctx, cache)
3111 }
3112
3113 /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel
3114 /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's
3115 /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no
3116 /// neighbour lookup at all (it is this block's own just-decided Y palette
3117 /// use), so only the cache is wanted here.
3118 fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> {
3119 let above_ok = r % 16 != 0;
3120 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
3121 (
3122 usize::from(self.above_palette_uv_size[c]),
3123 self.above_palette_uv_colors[c],
3124 )
3125 } else {
3126 (0, [0u16; 8])
3127 };
3128 let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 {
3129 (
3130 usize::from(self.left_palette_uv_size[r]),
3131 self.left_palette_uv_colors[r],
3132 )
3133 } else {
3134 (0, [0u16; 8])
3135 };
3136 let mut cache = Vec::with_capacity(16);
3137 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3138 if cache.last() != Some(&v) {
3139 cache.push(v);
3140 }
3141 };
3142 let (mut ai, mut li) = (0usize, 0usize);
3143 while ai < above_n && li < left_n {
3144 let (va, vl) = (above_colors[ai], left_colors[li]);
3145 if vl < va {
3146 push_dedup(&mut cache, vl);
3147 li += 1;
3148 } else {
3149 push_dedup(&mut cache, va);
3150 ai += 1;
3151 if vl == va {
3152 li += 1;
3153 }
3154 }
3155 }
3156 while ai < above_n {
3157 push_dedup(&mut cache, above_colors[ai]);
3158 ai += 1;
3159 }
3160 while li < left_n {
3161 push_dedup(&mut cache, left_colors[li]);
3162 li += 1;
3163 }
3164 cache
3165 }
3166
3167 /// [`Self::record_palette_y`] for the chroma bands (decode.rs
3168 /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same
3169 /// way, and the span is in LUMA pixels for both planes' bands alike.
3170 fn record_palette_uv(&mut self, (r, c): (usize, usize), (w, h): (usize, usize), size: u8, colors: [u16; 8]) {
3171 // lane-b128hv: the above band spans the block's WIDTH and the left
3172 // band its HEIGHT; identical to the one loop this replaces at w == h.
3173 for cell in 0..(w / MI).max(1) {
3174 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
3175 *e = size;
3176 if size > 0 {
3177 self.above_palette_uv_colors[c + cell] = colors;
3178 }
3179 }
3180 }
3181 for cell in 0..(h / MI).max(1) {
3182 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
3183 *e = size;
3184 if size > 0 {
3185 self.left_palette_uv_colors[r + cell] = colors;
3186 }
3187 }
3188 }
3189 }
3190
3191 /// What a just-written block leaves in the palette bands (decode.rs
3192 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
3193 /// spans, `0` for a block that took no palette.
3194 fn record_palette_y(&mut self, (r, c): (usize, usize), (w, h): (usize, usize), size: u8, colors: [u16; 8]) {
3195 // lane-b128hv: the above band spans the block's WIDTH and the left
3196 // band its HEIGHT; identical to the one loop this replaces at w == h.
3197 for cell in 0..(w / MI).max(1) {
3198 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
3199 *e = size;
3200 if size > 0 {
3201 self.above_palette_colors[c + cell] = colors;
3202 }
3203 }
3204 }
3205 for cell in 0..(h / MI).max(1) {
3206 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
3207 *e = size;
3208 if size > 0 {
3209 self.left_palette_colors[r + cell] = colors;
3210 }
3211 }
3212 }
3213 }
3214
3215 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block
3216 /// of an INTER frame leaves in the two `TXFM_CONTEXT` bands -- its
3217 /// resolved transform size over the span `(w_px, h_px)`, which for a
3218 /// SKIPPED inter block is its own block size instead.
3219 fn record_txfm(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, w_px: usize, h_px: usize) {
3220 for i in 0..h_px / MI {
3221 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
3222 *cell = tx_px as u8;
3223 }
3224 }
3225 for i in 0..w_px / MI {
3226 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
3227 *cell = tx_px as u8;
3228 }
3229 }
3230 }
3231
3232 /// lane-b128hv: decode.rs `txfm_partition_update_rect` -- the two bands
3233 /// take the transform's own HEIGHT (left) and WIDTH (above), over the
3234 /// txb's own rect span. [`Self::record_txfm`] is this at `tx_w == tx_h`.
3235 fn record_txfm_rect(
3236 &mut self,
3237 (mi_r, mi_c): (usize, usize),
3238 (tx_w, tx_h): (usize, usize),
3239 (txb_w, txb_h): (usize, usize),
3240 ) {
3241 for i in 0..txb_h / MI {
3242 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
3243 *cell = tx_h as u8;
3244 }
3245 }
3246 for i in 0..txb_w / MI {
3247 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
3248 *cell = tx_w as u8;
3249 }
3250 }
3251 }
3252
3253 /// `get_tx_size_context` as libaom writes it for a block inside an INTER
3254 /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT`
3255 /// bands, except that an *inter* neighbour contributes its own BLOCK size.
3256 ///
3257 /// lane-av1tx2 r1: a neighbour OUTSIDE the tile contributes nothing at all
3258 /// -- the decoder's `tx_size_context_txfm` drops the whole term when
3259 /// `has_above`/`has_left` is false, where this counted the band's
3260 /// [`TXFM_CTX_INIT`] (64, the widest transform) as a real neighbour. Every
3261 /// intra block on a tile's top row or left column then took its `tx_depth`
3262 /// off a CDF row one higher than the decoder's, which is the first
3263 /// divergence of the inter `TxMode::Select` stream.
3264 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
3265 let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c));
3266 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
3267 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
3268 if has_above && self.above_inter[mi_c] {
3269 above = self.above_side_mi[mi_c] >= own_side;
3270 }
3271 if has_left && self.left_inter[mi_r] {
3272 left = self.left_side_mi[mi_r] >= own_side;
3273 }
3274 usize::from(has_above && above) + usize::from(has_left && left)
3275 }
3276
3277 /// `get_tx_size_context` (decode.rs [`crate::decode::tx_size_context`]):
3278 /// whether the transform above is at least as wide as this block's own
3279 /// largest transform, plus whether the one to the left is at least as
3280 /// tall. A neighbour outside the tile contributes nothing.
3281 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
3282 usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
3283 + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
3284 }
3285
3286 /// Publishes one block's resolved transform side over every 4x4 unit it
3287 /// covers, the way the decoder's `fill_lf_grid` does at the end of every
3288 /// block.
3289 fn record_tx(&mut self, (mi_r, mi_c): (usize, usize), side: usize, tx_px: usize) {
3290 for cell in 0..side / MI {
3291 if mi_r + cell < self.left_tx.len() {
3292 self.left_tx[mi_r + cell] = tx_px as u8;
3293 }
3294 if mi_c + cell < self.above_tx.len() {
3295 self.above_tx[mi_c + cell] = tx_px as u8;
3296 }
3297 }
3298 }
3299
3300 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
3301 /// (decode.rs `Neighbours::luma_skip_ctx`): the above and left magnitude
3302 /// tiers, each ORed over the unit's own span and clamped to 4.
3303 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
3304 let mut top = 0u8;
3305 let mut left = 0u8;
3306 for cell in 0..side_mi {
3307 top |= self.above[mi_c + cell][0].level;
3308 left |= self.left[mi_r + cell][0].level;
3309 }
3310 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3311 }
3312
3313 /// Publishes ONE luma transform unit's coefficient context, the way the
3314 /// decoder's `record_mi_luma` does between the units of a split block.
3315 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
3316 let state = neighbour_state(grid);
3317 for cell in 0..tx_px / MI {
3318 if mi_r + cell < self.mi_rows {
3319 self.left[mi_r + cell][0] = state;
3320 }
3321 if mi_c + cell < self.mi_cols {
3322 self.above[mi_c + cell][0] = state;
3323 }
3324 }
3325 }
3326
3327 /// lane-b128r: publishes ONE chroma transform unit's coefficient context,
3328 /// the decoder's own `record_mi_chroma` -- a 128x128 block's chroma is one
3329 /// TX_32X32 unit per plane per 64x64 mu chunk, and the next chunk reads
3330 /// the previous one's state (its `txb_skip_ctx` base 1 from the left
3331 /// neighbour). `span_px` is the unit's LUMA span, which is what the
3332 /// luma-mi-indexed bands are addressed in.
3333 fn record_mi_chroma(
3334 &mut self,
3335 (mi_r, mi_c): (usize, usize),
3336 span_px: usize,
3337 plane: usize,
3338 grid: &[i32],
3339 ) {
3340 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3341 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
3342 let state = neighbour_state(grid);
3343 for cell in 0..(span_px / MI).min(bound_h.saturating_sub(mi_r)) {
3344 self.left[mi_r + cell][plane] = state;
3345 }
3346 for cell in 0..(span_px / MI).min(bound_w.saturating_sub(mi_c)) {
3347 self.above[mi_c + cell][plane] = state;
3348 }
3349 }
3350
3351 /// Writes one coded block into every 16x16 column and row it covers, and,
3352 /// on the finer 4x4 grid libaom's entropy context arrays are actually
3353 /// kept on, into every unit up to the true frame edge -- the units past
3354 /// it are left at their default (uncoded), even mid-16x16-cell (spec
3355 /// `av1_set_entropy_contexts`, which clamps to `blocks_wide`/`blocks_high`
3356 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own
3357 /// side).
3358 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
3359 self.record_planes(at, side, mode, grids, true);
3360 }
3361
3362 /// [`Self::record`] with a switch for plane 0: a block whose luma was
3363 /// written as several transform units published each unit's own context
3364 /// as it went ([`Self::record_mi_luma`]), so the whole-block write here
3365 /// would clobber what the next block reads (decode.rs
3366 /// `record_split_luma`).
3367 fn record_planes(
3368 &mut self,
3369 at: (usize, usize),
3370 side: usize,
3371 mode: usize,
3372 grids: &[Vec<i32>; 3],
3373 luma: bool,
3374 ) {
3375 self.record_planes_rect(at, (side, side), mode, grids, luma);
3376 }
3377
3378 /// lane-b128hv: [`Self::record_planes`] with independent above (width) /
3379 /// left (height) extents, decode.rs `record_rect_mi`'s own split -- the
3380 /// 128 root's HORZ/VERT halves are the writer's first rect blocks.
3381 fn record_planes_rect(
3382 &mut self,
3383 at: (usize, usize),
3384 (w, h): (usize, usize),
3385 mode: usize,
3386 grids: &[Vec<i32>; 3],
3387 luma: bool,
3388 ) {
3389 let (r, c) = at;
3390 for cell in 0..w / SUB {
3391 self.above_mode[c + cell] = mode;
3392 self.above_side[c + cell] = w;
3393 }
3394 for cell in 0..h / SUB {
3395 self.left_mode[r + cell] = mode;
3396 self.left_side[r + cell] = h;
3397 }
3398 self.record_mi_planes_rect((r * (SUB / MI), c * (SUB / MI)), (w, h), grids, luma);
3399 }
3400
3401 /// The coefficient-context half of [`Self::record`], taking the block's
3402 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
3403 /// (r, c): an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at a
3404 /// mi offset [`Self::record`]'s SUB-unit `at` cannot name, but the
3405 /// `above`/`left` arrays it writes into are already sized to the full mi
3406 /// grid, so no resizing is needed to write into them at this
3407 /// finer-than-SUB granularity.
3408 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
3409 self.record_mi_planes(at_mi, side, grids, true);
3410 }
3411
3412 /// [`Self::record_mi`] with [`Self::record_planes`]'s plane-0 switch.
3413 fn record_mi_planes(
3414 &mut self,
3415 at_mi: (usize, usize),
3416 side: usize,
3417 grids: &[Vec<i32>; 3],
3418 luma: bool,
3419 ) {
3420 self.record_mi_planes_rect(at_mi, (side, side), grids, luma);
3421 }
3422
3423 /// [`Self::record_mi_planes`] with independent above (width) / left
3424 /// (height) extents (lane-b128hv, decode.rs `record_mi_rect`).
3425 fn record_mi_planes_rect(
3426 &mut self,
3427 at_mi: (usize, usize),
3428 (w, h): (usize, usize),
3429 grids: &[Vec<i32>; 3],
3430 luma: bool,
3431 ) {
3432 let (mi_r, mi_c) = at_mi;
3433 if screen_armed() {
3434 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
3435 self.record_palette_y(at_mi, (w, h), size, colors);
3436 let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8]));
3437 self.record_palette_uv(at_mi, (w, h), uv_size, uv_colors);
3438 }
3439 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
3440 let (w_mi, h_mi) = (w / MI, h / MI);
3441 for cell in 0..h_mi {
3442 self.left_side_mi[mi_r + cell] = h;
3443 }
3444 for cell in 0..w_mi {
3445 self.above_side_mi[mi_c + cell] = w;
3446 }
3447 // libaom rounds the luma edge up to the plane's own 4x4 unit before
3448 // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high,
3449 // subsampling_y)` in av1_write_intra_coeffs_mb, encodetxb.c:456-459):
3450 // a chroma 4x4 unit straddling the true luma edge is still whole in
3451 // chroma's own halved grid, so it stays valid one luma-mi row/col
3452 // past where luma's own edge falls when that edge is odd.
3453 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3454 let bound_h = [
3455 self.mi_rows,
3456 round_up_even(self.mi_rows),
3457 round_up_even(self.mi_rows),
3458 ];
3459 let bound_w = [
3460 self.mi_cols,
3461 round_up_even(self.mi_cols),
3462 round_up_even(self.mi_cols),
3463 ];
3464 for cell in 0..h_mi {
3465 let keep_left = self.left[mi_r + cell][0];
3466 self.left[mi_r + cell] = std::array::from_fn(|plane| {
3467 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
3468 states[plane]
3469 } else {
3470 Default::default()
3471 }
3472 });
3473 if !luma {
3474 self.left[mi_r + cell][0] = keep_left;
3475 }
3476 }
3477 for cell in 0..w_mi {
3478 let keep_above = self.above[mi_c + cell][0];
3479 self.above[mi_c + cell] = std::array::from_fn(|plane| {
3480 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
3481 states[plane]
3482 } else {
3483 Default::default()
3484 }
3485 });
3486 if !luma {
3487 self.above[mi_c + cell][0] = keep_above;
3488 }
3489 }
3490 }
3491
3492 /// Writes one inter-frame block's skip flag and inter/intra state into
3493 /// every 16x16 column and row it covers, the same span [`Self::record`]
3494 /// fills for the coefficient and mode state.
3495 fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) {
3496 let (r, c) = at;
3497 self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame);
3498 }
3499
3500 /// lane-b128hv: [`Self::record_inter_mi`] with independent above (width)
3501 /// / left (height) spans, decode.rs `record_inter_rect_mi`'s own split.
3502 fn record_inter_rect_mi(
3503 &mut self,
3504 (mi_r, mi_c): (usize, usize),
3505 (w, h): (usize, usize),
3506 skip: bool,
3507 is_inter: bool,
3508 ref_frame: i8,
3509 ) {
3510 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3511 for cell in 0..h / MI {
3512 self.left_skip[mi_r + cell] = skip;
3513 self.left_inter[mi_r + cell] = is_inter;
3514 self.left_ref[mi_r + cell] = ref_frame;
3515 self.left_ref1[mi_r + cell] = None;
3516 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
3517 self.left_compound_idx[mi_r + cell] = u8::from(altref);
3518 }
3519 for cell in 0..w / MI {
3520 self.above_skip[mi_c + cell] = skip;
3521 self.above_inter[mi_c + cell] = is_inter;
3522 self.above_ref[mi_c + cell] = ref_frame;
3523 self.above_ref1[mi_c + cell] = None;
3524 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
3525 self.above_compound_idx[mi_c + cell] = u8::from(altref);
3526 }
3527 }
3528
3529 /// [`Self::record_compound_mi`] over a rect block's own two spans.
3530 fn record_compound_rect_mi(
3531 &mut self,
3532 (mi_r, mi_c): (usize, usize),
3533 (w, h): (usize, usize),
3534 ref1: i8,
3535 comp_group_idx: u8,
3536 compound_idx: u8,
3537 ) {
3538 for cell in 0..h / MI {
3539 self.left_ref1[mi_r + cell] = Some(ref1);
3540 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
3541 self.left_compound_idx[mi_r + cell] = compound_idx;
3542 }
3543 for cell in 0..w / MI {
3544 self.above_ref1[mi_c + cell] = Some(ref1);
3545 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
3546 self.above_compound_idx[mi_c + cell] = compound_idx;
3547 }
3548 }
3549
3550 /// [`Self::record_inter_mi`]'s compound half (decode.rs
3551 /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF
3552 /// single-reference default with a real compound block's own second
3553 /// reference and `comp_group_idx`/`compound_idx` bits, called right after
3554 /// it for every compound-coded block.
3555 fn record_compound_mi(
3556 &mut self,
3557 (mi_r, mi_c): (usize, usize),
3558 side: usize,
3559 ref1: i8,
3560 comp_group_idx: u8,
3561 compound_idx: u8,
3562 ) {
3563 for cell in 0..side / MI {
3564 self.above_ref1[mi_c + cell] = Some(ref1);
3565 self.left_ref1[mi_r + cell] = Some(ref1);
3566 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
3567 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
3568 self.above_compound_idx[mi_c + cell] = compound_idx;
3569 self.left_compound_idx[mi_r + cell] = compound_idx;
3570 }
3571 }
3572
3573 /// [`Self::record_inter`] taking the block's position directly in 4x4
3574 /// mode-info units, for a block finer than one [`SUB`] slot.
3575 fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) {
3576 for cell in 0..side / MI {
3577 self.above_skip[mi_c + cell] = skip;
3578 self.left_skip[mi_r + cell] = skip;
3579 self.above_inter[mi_c + cell] = is_inter;
3580 self.left_inter[mi_r + cell] = is_inter;
3581 self.above_ref[mi_c + cell] = ref_frame;
3582 self.left_ref[mi_r + cell] = ref_frame;
3583 // decode.rs `record_inter`'s single-reference default: no second
3584 // reference, and libaom's ALTREF special case in the two compound
3585 // context bands. `record_compound_mi` overwrites both for a real
3586 // compound block.
3587 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3588 self.above_ref1[mi_c + cell] = None;
3589 self.left_ref1[mi_r + cell] = None;
3590 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
3591 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
3592 self.above_compound_idx[mi_c + cell] = u8::from(altref);
3593 self.left_compound_idx[mi_r + cell] = u8::from(altref);
3594 }
3595 }
3596
3597 /// The above neighbour as decode.rs' own `NeighbourRef`, for every
3598 /// compound context function (`reference_mode_ctx`,
3599 /// `comp_reference_type_ctx`, the `comp_ref`/`comp_bwdref` votes).
3600 fn above_nbr(&self, mi_c: usize) -> crate::mvstack::NeighbourRef {
3601 let is_inter = self.above_inter[mi_c];
3602 let ref0 = if is_inter { self.above_ref[mi_c] } else { 0 };
3603 let ref1 = self.above_ref1[mi_c];
3604 crate::mvstack::NeighbourRef {
3605 is_inter,
3606 ref0,
3607 ref1,
3608 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
3609 }
3610 }
3611
3612 /// [`Self::above_nbr`], down the left edge.
3613 fn left_nbr(&self, mi_r: usize) -> crate::mvstack::NeighbourRef {
3614 let is_inter = self.left_inter[mi_r];
3615 let ref0 = if is_inter { self.left_ref[mi_r] } else { 0 };
3616 let ref1 = self.left_ref1[mi_r];
3617 crate::mvstack::NeighbourRef {
3618 is_inter,
3619 ref0,
3620 ref1,
3621 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
3622 }
3623 }
3624
3625 /// The context of a block's partition symbol (spec 9.3): whether the
3626 /// blocks above it and to its left were split finer than it is.
3627 /// The gathered state of the blocks above and to the left of one block,
3628 /// per plane.
3629 fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] {
3630 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
3631 }
3632
3633 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
3634 /// units, for the same reason [`Self::record_mi`] does.
3635 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [Around; 3] {
3636 let side_mi = side / MI;
3637 std::array::from_fn(|plane| {
3638 let mut around = Around::default();
3639 for cell in 0..side_mi {
3640 let (above, left) = (
3641 &self.above[mi_c + cell][plane],
3642 &self.left[mi_r + cell][plane],
3643 );
3644 around.above_coded |= above.coded;
3645 around.left_coded |= left.coded;
3646 around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc);
3647 }
3648 around
3649 })
3650 }
3651
3652 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
3653 // Delegates to the mi-precise reader (same pattern as `around` /
3654 // `around_mi`): `above_side`/`left_side` are only ever advanced in
3655 // whole-[`SUB`] steps by [`Self::record`], so a leaf8's `record_mi`
3656 // (lane-av1-rect) -- which only touches the finer mi arrays -- leaves
3657 // them stale for the *next* sibling's own partition symbol, reading a
3658 // 16x16-slot side that already split into 8x8s underneath it.
3659 let (r, c) = at;
3660 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
3661 }
3662
3663 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
3664 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
3665 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
3666 /// than the enclosing 16x16 slot's stale, shared state.
3667 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
3668 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
3669 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
3670 }
3671}
3672
3673/// Writes the payload of a one-tile key frame built from `superblocks`, each
3674/// either one 64x64 block or the 32x32 blocks it splits into.
3675///
3676/// `superblocks` gives one entry per superblock in raster order across the
3677/// frame. Every block is DC-predicted unless its [`BlockCoeffs::mode`] says
3678/// otherwise, and carries the coefficients its lists give; the coefficients
3679/// may sit anywhere in their transform, so a block is a picture rather than a
3680/// flat grey.
3681///
3682/// # Errors
3683/// Returns an error when the frame is not a whole number of 32x32 blocks, when
3684/// `superblocks` does not carry exactly one entry per superblock or an entry
3685/// does not carry one block per quadrant inside the frame, when a superblock
3686/// that is half outside the frame is left whole, when a block names an intra
3687/// mode a key frame does not code, when a coefficient sits outside its
3688/// transform, repeats a position, carries a zero level or one wider than the
3689/// Golomb tail reaches.
3690pub fn sb_coeff_key_frame_tile(
3691 mi_cols: u32,
3692 mi_rows: u32,
3693 base_q_idx: u8,
3694 superblocks: &[Superblock],
3695) -> Result<Vec<u8>> {
3696 sb_coeff_key_frame_tile_tx(mi_cols, mi_rows, base_q_idx, superblocks, false)
3697}
3698
3699/// [`sb_coeff_key_frame_tile`] for a frame header carrying
3700/// `tx_mode == TxMode::Select` (`tx_select`): every block then codes a
3701/// `tx_depth` symbol and, where that depth is nonzero, its luma residual as
3702/// several transform units ([`write_luma_select`]). With `tx_select` false
3703/// this writes exactly the stream it always did.
3704///
3705/// # Errors
3706/// As [`sb_coeff_key_frame_tile`], plus a 64x64 block whose `tx_depth` is
3707/// nonzero (not written yet).
3708pub fn sb_coeff_key_frame_tile_tx(
3709 mi_cols: u32,
3710 mi_rows: u32,
3711 base_q_idx: u8,
3712 superblocks: &[Superblock],
3713 tx_select: bool,
3714) -> Result<Vec<u8>> {
3715 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3716 sb_coeff_key_frame_tile_cdfs(
3717 mi_cols,
3718 mi_rows,
3719 base_q_idx,
3720 superblocks,
3721 tx_select,
3722 &mut cdfs,
3723 TileRect::whole(mi_cols, mi_rows),
3724 )
3725}
3726
3727/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
3728/// caller's own CDF state, which is what a frame whose
3729/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must
3730/// start where this tile ended (spec 7.20, mirrored by
3731/// `crate::stream::stored_cdfs_for`).
3732///
3733/// # Errors
3734/// As [`sb_coeff_key_frame_tile_tx`].
3735pub(crate) fn sb_coeff_key_frame_tile_cdfs(
3736 mi_cols: u32,
3737 mi_rows: u32,
3738 _base_q_idx: u8,
3739 superblocks: &[Superblock],
3740 tx_select: bool,
3741 cdfs: &mut Cdfs,
3742 // This tile's own span (spec 5.11.1): the writer walks only these
3743 // superblocks, and its neighbour bands start blank, so everything
3744 // outside reads as unavailable exactly as the decoder's own per-tile
3745 // reset makes it.
3746 tile: TileRect,
3747) -> Result<Vec<u8>> {
3748 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
3749 let _cdef_idx = CdefIdxGuard;
3750 check_blocks(mi_cols, mi_rows)?;
3751 // The DV predictor's own mi grid, per tile exactly as decode.rs builds it
3752 // per frame (`decode_key_frame_tile_lr`'s `intrabc_mi_grid`): a tile that
3753 // allows no intrabc arms none and every `record_intrabc_mi` below is a
3754 // no-op.
3755 if intrabc_armed() {
3756 // No `set_tile_bounds`: decode.rs builds this grid for the WHOLE
3757 // frame with the default (whole-grid) bounds, so the writer must
3758 // too. `encode_key_frame_inner` only allows intrabc on a
3759 // single-tile frame, where the two grids are the same grid.
3760 let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize);
3761 INTRABC_GRID.with(|g| {
3762 *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize));
3763 });
3764 }
3765 let (cols, rows) = block_grid(mi_cols, mi_rows);
3766 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3767 if superblocks.len() != (sb_cols * sb_rows) as usize {
3768 return Err(Error::unsupported(
3769 "AV1 tile",
3770 "a coefficient key frame needs one entry per superblock",
3771 ));
3772 }
3773 let mut coded: Vec<&BlockCoeffs> = Vec::new();
3774 for superblock in superblocks {
3775 match superblock {
3776 Superblock::Whole(block) => coded.push(block),
3777 Superblock::Split(quadrants) => {
3778 for block in quadrants.iter().flat_map(Quadrant::blocks) {
3779 match &block.eight {
3780 Some(leaves) => coded.extend(leaves.iter()),
3781 None => coded.push(block),
3782 }
3783 }
3784 }
3785 }
3786 }
3787 if let Some(bad) = coded
3788 .into_iter()
3789 .find(|b| usize::from(b.mode) >= INTRA_MODES)
3790 {
3791 return Err(Error::unsupported(
3792 "AV1 tile",
3793 format!(
3794 "intra mode {} is not one of the thirteen a key frame codes",
3795 bad.mode
3796 ),
3797 ));
3798 }
3799
3800 let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8];
3801 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
3802 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
3803 let scans = [
3804 default_scan(TX32),
3805 default_scan(TX16),
3806 default_scan(TX8),
3807 default_scan(TX4),
3808 ];
3809 // The blocks above and to the left, on the 16x16 grid. The left edge is
3810 // reset at every superblock row because a tile starts each row with no
3811 // left neighbour.
3812 let mut neighbours = Neighbours::new(
3813 cols as usize * 2,
3814 rows as usize * 2,
3815 mi_cols as usize,
3816 mi_rows as usize,
3817 );
3818 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
3819
3820 // The tile adapts every non-literal CDF it writes, exactly as the decoder
3821 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
3822 // off.
3823 let mut cdfs = cdfs;
3824 let mut enc = SymbolEncoder::new();
3825 let sb128 = sb128_armed();
3826 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
3827 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
3828 // and partition symbol first; at a 64 one this is plain raster and every
3829 // cell is its own superblock, i.e. byte-identical to the loop before.
3830 for (sb_r, sb_c, row_start, sb_start) in sb_write_order(
3831 tile.sb_row0,
3832 tile.sb_row1.min(sb_rows),
3833 tile.sb_col0,
3834 tile.sb_col1.min(sb_cols),
3835 sb128,
3836 ) {
3837 if row_start {
3838 neighbours.start_row();
3839 }
3840 if sb128 && sb_start {
3841 write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows, PARTITION_SPLIT);
3842 }
3843 {
3844 if !sb128 {
3845 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W);
3846 }
3847 let at = (sb_r as usize * 4, sb_c as usize * 4);
3848 let ctx = neighbours.partition_ctx(at, SB);
3849 ec_rng_trace(|| {
3850 format!(
3851 "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={}",
3852 at.0 * 4,
3853 at.1 * 4,
3854 ctx,
3855 enc.tell()
3856 )
3857 });
3858 // A superblock whose bottom or right half is outside the frame
3859 // cannot be left unsplit, so the decoder reads a flag instead of
3860 // the partition symbol — and reads nothing at all when both halves
3861 // are outside, where the split is the only partition left.
3862 let (has_cols, has_rows) = (
3863 sb_c * SB_MI + SB_MI / 2 < mi_cols,
3864 sb_r * SB_MI + SB_MI / 2 < mi_rows,
3865 );
3866 // The quadrants of this superblock that are inside the frame, as
3867 // positions in the 32x32 block grid.
3868 let quadrant_positions: Vec<(usize, usize)> = (0..4)
3869 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
3870 .filter(|&(r, c)| r < rows && c < cols)
3871 .map(|(r, c)| (r as usize, c as usize))
3872 .collect();
3873
3874 match &superblocks[(sb_r * sb_cols + sb_c) as usize] {
3875 Superblock::Whole(block) => {
3876 if !has_cols || !has_rows {
3877 return Err(Error::unsupported(
3878 "AV1 tile",
3879 "a superblock that is half outside the frame cannot be left whole",
3880 ));
3881 }
3882 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
3883 let grids = [
3884 level_grid(&block.luma, TX32)?,
3885 level_grid(&block.u, TX32)?,
3886 level_grid(&block.v, TX32)?,
3887 ];
3888 write_block(
3889 &mut enc,
3890 &mut cdfs,
3891 &mut neighbours,
3892 block,
3893 at,
3894 SB,
3895 &whole_planes,
3896 &grids,
3897 [&scans[0], &scans[0], &scans[0]],
3898 // A 64x64 block is too big to be offered chroma from
3899 // luma, so its chroma mode reads the table without it.
3900 false,
3901 tx_select,
3902 &scans,
3903 )?;
3904 ec_rng_trace(|| {
3905 format!(
3906 "EC_TOK mi_row={} mi_col={} tell={}",
3907 at.0 * 4,
3908 at.1 * 4,
3909 enc.tell()
3910 )
3911 });
3912 }
3913 Superblock::Split(quadrants) => {
3914 match (has_cols, has_rows) {
3915 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
3916 // The gathered CDF an edge superblock reads is built
3917 // for the read and thrown away: the decoder never
3918 // stores it back, so nothing adapts here.
3919 (true, false) => {
3920 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
3921 }
3922 (false, true) => {
3923 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
3924 }
3925 (false, false) => {}
3926 }
3927 if quadrants.len() != quadrant_positions.len() {
3928 return Err(Error::unsupported(
3929 "AV1 tile",
3930 "a split superblock needs one block per quadrant inside the frame",
3931 ));
3932 }
3933 for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) {
3934 let at = (r * 2, c * 2);
3935 let ctx = neighbours.partition_ctx(at, BLOCK);
3936 // Recomputed at this 32x32 block's own half (spec
3937 // `decode_partition`, called again at every size, not
3938 // just once for the superblock): the true frame edge
3939 // can fall inside this quadrant even when the
3940 // superblock it sits in was itself whole or safely
3941 // split above.
3942 let (has_cols32, has_rows32) = (
3943 has_half(c as u32 * BLOCK_MI, BLOCK_MI, mi_cols),
3944 has_half(r as u32 * BLOCK_MI, BLOCK_MI, mi_rows),
3945 );
3946 ec_rng_trace(|| {
3947 format!(
3948 "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={}",
3949 at.0 * 4,
3950 at.1 * 4,
3951 ctx,
3952 enc.tell()
3953 )
3954 });
3955 match quadrant {
3956 // A 64x64 root is an INTER-frame partition; a
3957 // key frame codes one as `Superblock::Whole`.
3958 Quadrant::Whole64(_)
3959 | Quadrant::Whole128(_)
3960 | Quadrant::Rect128(..)
3961 | Quadrant::Ab128(..)
3962 | Quadrant::Covered => {
3963 return Err(Error::unsupported(
3964 "AV1 tile",
3965 "a key frame codes a 64x64 block as `Superblock::Whole`",
3966 ));
3967 }
3968 Quadrant::Whole(block) => {
3969 if !has_cols32 || !has_rows32 {
3970 return Err(Error::unsupported(
3971 "AV1 tile",
3972 "a 32x32 block that is half outside the true frame \
3973 cannot be left whole",
3974 ));
3975 }
3976 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]);
3977 let grids = [
3978 level_grid(&block.luma, TX32)?,
3979 level_grid(&block.u, TX16)?,
3980 level_grid(&block.v, TX16)?,
3981 ];
3982 write_block(
3983 &mut enc,
3984 &mut cdfs,
3985 &mut neighbours,
3986 block,
3987 at,
3988 BLOCK,
3989 &split_planes,
3990 &grids,
3991 [&scans[0], &scans[1], &scans[1]],
3992 true,
3993 tx_select,
3994 &scans,
3995 )?;
3996 ec_rng_trace(|| {
3997 format!(
3998 "EC_TOK mi_row={} mi_col={} tell={}",
3999 at.0 * 4,
4000 at.1 * 4,
4001 enc.tell()
4002 )
4003 });
4004 }
4005 Quadrant::Split(blocks) => {
4006 // The 16x16 sub-blocks this quadrant's split
4007 // carries: only those whose own mi origin is
4008 // inside the true frame (spec `decode_partition`'s
4009 // `r >= MiRows || c >= MiCols` early return),
4010 // which need not be all four when the true
4011 // edge falls inside this quadrant.
4012 let sub_positions: Vec<(usize, usize)> = (0..4)
4013 .map(|i| (r * 2 + i / 2, c * 2 + i % 2))
4014 .filter(|&(sr, sc)| {
4015 (sr as u32) * SUB_MI < mi_rows
4016 && (sc as u32) * SUB_MI < mi_cols
4017 })
4018 .collect();
4019 if blocks.len() != sub_positions.len() {
4020 return Err(Error::unsupported(
4021 "AV1 tile",
4022 "a split 32x32 block needs one 16x16 entry per \
4023 sub-block inside the true frame",
4024 ));
4025 }
4026 // Same three-way spec signaling as the
4027 // superblock level above, recomputed at this
4028 // block's own half: a full alphabet symbol
4029 // only when both halves are inside, a single
4030 // gathered bit when just one is, and nothing
4031 // at all (SPLIT is inferred) when neither is.
4032 match (has_cols32, has_rows32) {
4033 (true, true) => {
4034 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]);
4035 }
4036 (true, false) => {
4037 enc.symbol_fixed(
4038 1,
4039 &gather(&cdfs.partition_w32[ctx], VERT_ALIKE),
4040 );
4041 }
4042 (false, true) => {
4043 enc.symbol_fixed(
4044 1,
4045 &gather(&cdfs.partition_w32[ctx], HORZ_ALIKE),
4046 );
4047 }
4048 (false, false) => {}
4049 }
4050 for (block, (sr, sc)) in blocks.iter().zip(sub_positions) {
4051 // A 16x16 leaf's own hasRows/hasCols,
4052 // recomputed at this leaf's own half
4053 // (same three-way signaling as the 32x32
4054 // and 64x64 levels above).
4055 let (has_cols16, has_rows16) = (
4056 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
4057 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
4058 );
4059 let at = (sr, sc);
4060 let ctx = neighbours.partition_ctx(at, SUB);
4061 ec_rng_trace(|| {
4062 format!(
4063 "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={}",
4064 at.0 * 4,
4065 at.1 * 4,
4066 ctx,
4067 enc.tell()
4068 )
4069 });
4070 if has_cols16 && has_rows16 {
4071 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]);
4072 let grids = [
4073 level_grid(&block.luma, TX16)?,
4074 level_grid(&block.u, TX8)?,
4075 level_grid(&block.v, TX8)?,
4076 ];
4077 write_block(
4078 &mut enc,
4079 &mut cdfs,
4080 &mut neighbours,
4081 block,
4082 at,
4083 SUB,
4084 &sub_planes,
4085 &grids,
4086 [&scans[1], &scans[2], &scans[2]],
4087 true,
4088 tx_select,
4089 &scans,
4090 )?;
4091 ec_rng_trace(|| {
4092 format!(
4093 "EC_TOK mi_row={} mi_col={} tell={}",
4094 at.0 * 4,
4095 at.1 * 4,
4096 enc.tell()
4097 )
4098 });
4099 continue;
4100 }
4101 // The true edge falls inside this 16x16
4102 // leaf itself: the block splits into the
4103 // 8x8s that are inside, each its own
4104 // leaf. Same three-way spec signaling as
4105 // every level above -- a single gathered
4106 // bit when one half is outside, and
4107 // nothing at all when BOTH are, where
4108 // `decode_partition` infers the split
4109 // (lane-av1rect: no rectangular
4110 // transform is needed for this, the
4111 // earlier refusal here misread 5.11.4).
4112 match (has_cols16, has_rows16) {
4113 (true, false) => enc.symbol_fixed(
4114 1,
4115 &gather(&cdfs.partition_w16[ctx], VERT_ALIKE),
4116 ),
4117 (false, true) => enc.symbol_fixed(
4118 1,
4119 &gather(&cdfs.partition_w16[ctx], HORZ_ALIKE),
4120 ),
4121 _ => {}
4122 }
4123 let leaves = block.eight.as_ref().ok_or_else(|| {
4124 Error::unsupported(
4125 "AV1 tile",
4126 "a 16x16 block the true frame edge cuts through \
4127 needs its `eight` leaves populated",
4128 )
4129 })?;
4130 let (mi_row0, mi_col0) =
4131 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
4132 let leaf_positions: Vec<(u32, u32)> = (0..4)
4133 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
4134 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
4135 .collect();
4136 if leaves.len() != leaf_positions.len() {
4137 return Err(Error::unsupported(
4138 "AV1 tile",
4139 "a straddling 16x16 block needs one `eight` entry \
4140 per 8x8 leaf inside the true frame",
4141 ));
4142 }
4143 // r11: the enclosing 16x16 slot's
4144 // above_mode/left_mode arrays are too
4145 // coarse for a second leaf whose true
4146 // above (or left) neighbour is the FIRST
4147 // leaf -- track it here and hand it to
4148 // write_leaf8 as a context override.
4149 let mut prev_leaf: Option<((usize, usize), usize)> = None;
4150 for (leaf, (mr, mc)) in leaves.iter().zip(leaf_positions) {
4151 let leaf_mi = (mr as usize, mc as usize);
4152 // r8: read at mi granularity, not the
4153 // enclosing 16x16 slot -- the first
4154 // leaf's `record_mi` call below
4155 // updates `above_side_mi`/
4156 // `left_side_mi` at this leaf's own
4157 // mi position, which the second
4158 // leaf's ctx lookup then sees.
4159 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
4160 ec_rng_trace(|| {
4161 format!(
4162 "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={}",
4163 leaf_mi.0,
4164 leaf_mi.1,
4165 leaf_ctx,
4166 enc.tell()
4167 )
4168 });
4169 enc.symbol(
4170 PARTITION_NONE,
4171 &mut cdfs.partition_w8[leaf_ctx],
4172 );
4173 let grids = [
4174 level_grid(&leaf.luma, TX8)?,
4175 level_grid(&leaf.u, TX4)?,
4176 level_grid(&leaf.v, TX4)?,
4177 ];
4178 let leaf_mode = write_leaf8(
4179 &mut enc,
4180 &mut cdfs,
4181 &mut neighbours,
4182 leaf,
4183 at,
4184 leaf_mi,
4185 &grids,
4186 [&scans[2], &scans[3], &scans[3]],
4187 prev_leaf,
4188 tx_select,
4189 &scans,
4190 )?;
4191 prev_leaf = Some((leaf_mi, leaf_mode));
4192 ec_rng_trace(|| {
4193 format!(
4194 "EC_TOK mi_row={} mi_col={} tell={}",
4195 leaf_mi.0,
4196 leaf_mi.1,
4197 enc.tell()
4198 )
4199 });
4200 }
4201 // `record()`'s `above_mode`/`left_mode`
4202 // write is a no-op at an 8x8 leaf's own
4203 // side (`side / SUB == 0`), so the next
4204 // 16x16 quadrant beyond this straddling
4205 // one would otherwise see whatever stale
4206 // mode sat here before it: force the
4207 // write once the whole quadrant's leaves
4208 // are done, from the last (bottom/right-
4209 // most) leaf -- lane-av1-rect r15: doing
4210 // this *inside* `write_leaf8`, once per
4211 // leaf, let the first leaf's write
4212 // clobber the true external neighbour a
4213 // second leaf of the *same* quadrant
4214 // still needed to read on its
4215 // non-adjacency axis.
4216 if let Some((_, mode)) = prev_leaf {
4217 neighbours.above_mode[at.1] = mode;
4218 neighbours.left_mode[at.0] = mode;
4219 }
4220 }
4221 }
4222 }
4223 }
4224 }
4225 }
4226 }
4227 }
4228 Ok(enc.finish())
4229}
4230
4231/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`,
4232/// which the palette colour-index map's first (context-free) symbol is coded
4233/// with.
4234fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) {
4235 let l = crate::decode::ceil_log2(n as u32);
4236 let m = (1usize << l) - n;
4237 if value < m {
4238 enc.literal(value as u32, l - 1);
4239 } else {
4240 enc.literal(((value + m) >> 1) as u32, l - 1);
4241 enc.literal(((value + m) & 1) as u32, 1);
4242 }
4243}
4244
4245/// `write_palette_colors_y` (bitstream.c:1178), the write side of
4246/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache
4247/// entry (taken when this palette holds that colour, in cache order, stopping
4248/// once `n` are cached), then the colours the cache did not supply -- the
4249/// first raw, the rest as deltas off a bit width that shrinks with the range
4250/// left. `colors` is ascending and distinct, so the decoder's `merge_colors`
4251/// of the two ascending lists puts it back exactly.
4252fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) {
4253 let n = colors.len();
4254 let mut cached: Vec<u16> = Vec::with_capacity(n);
4255 for &c in cache {
4256 if cached.len() >= n {
4257 break;
4258 }
4259 let take = colors.contains(&c);
4260 enc.literal(u32::from(take), 1);
4261 if take {
4262 cached.push(c);
4263 }
4264 }
4265 let transmitted: Vec<u16> = colors
4266 .iter()
4267 .copied()
4268 .filter(|c| !cached.contains(c))
4269 .collect();
4270 if transmitted.is_empty() {
4271 return;
4272 }
4273 enc.literal(u32::from(transmitted[0]), 8);
4274 if transmitted.len() == 1 {
4275 return;
4276 }
4277 // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one
4278 // under which every delta still fits its (shrinking) width. `extra == 3`
4279 // always works -- a delta can never exceed the range left -- so the
4280 // search below always finds one.
4281 let fits = |extra: u32| -> bool {
4282 let mut bits = 5 + extra;
4283 let mut range = 255i32 - i32::from(transmitted[0]);
4284 for w in transmitted.windows(2) {
4285 let delta = i32::from(w[1]) - i32::from(w[0]);
4286 if delta - 1 >= (1i32 << bits) {
4287 return false;
4288 }
4289 range -= delta;
4290 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4291 }
4292 true
4293 };
4294 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
4295 enc.literal(extra, 2);
4296 let mut bits = 5 + extra;
4297 let mut range = 255i32 - i32::from(transmitted[0]);
4298 for w in transmitted.windows(2) {
4299 let delta = i32::from(w[1]) - i32::from(w[0]);
4300 enc.literal((delta - 1) as u32, bits);
4301 range -= delta;
4302 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4303 }
4304}
4305
4306/// `write_palette_colors_uv` (bitstream.c:1236), the write side of
4307/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is
4308/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two
4309/// documented differences -- the shrinking range starts at `256 - first`
4310/// (not `255 - first`) and each delta is written unbiased (no `-1`).
4311///
4312/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n`
4313/// 8-bit literals) rather than its first-value-plus-signed-deltas form.
4314/// Ceiling: about `n` bits per chroma-palette block more than the delta form
4315/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer
4316/// below sees, so it only ever makes the encoder take FEWER chroma palettes
4317/// than it should -- never a wrong stream. Upgrade path: price both forms
4318/// here and write the cheaper one under its own leading bit.
4319fn write_palette_colors_uv(enc: &mut SymbolEncoder, u_colors: &[u16], v_colors: &[u16], cache: &[u16]) {
4320 let n = u_colors.len();
4321 let mut cached: Vec<u16> = Vec::with_capacity(n);
4322 for &c in cache {
4323 if cached.len() >= n {
4324 break;
4325 }
4326 let take = u_colors.contains(&c);
4327 enc.literal(u32::from(take), 1);
4328 if take {
4329 PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4330 cached.push(c);
4331 }
4332 }
4333 let transmitted: Vec<u16> = u_colors
4334 .iter()
4335 .copied()
4336 .filter(|c| !cached.contains(c))
4337 .collect();
4338 if !transmitted.is_empty() {
4339 enc.literal(u32::from(transmitted[0]), 8);
4340 if transmitted.len() > 1 {
4341 let fits = |extra: u32| -> bool {
4342 let mut bits = 5 + extra;
4343 let mut range = 256i32 - i32::from(transmitted[0]);
4344 for w in transmitted.windows(2) {
4345 let delta = i32::from(w[1]) - i32::from(w[0]);
4346 if delta >= (1i32 << bits) {
4347 return false;
4348 }
4349 range -= delta;
4350 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4351 }
4352 true
4353 };
4354 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
4355 enc.literal(extra, 2);
4356 let mut bits = 5 + extra;
4357 let mut range = 256i32 - i32::from(transmitted[0]);
4358 for w in transmitted.windows(2) {
4359 let delta = i32::from(w[1]) - i32::from(w[0]);
4360 enc.literal(delta as u32, bits);
4361 range -= delta;
4362 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
4363 }
4364 }
4365 }
4366 enc.literal(0, 1);
4367 for &v in v_colors {
4368 enc.literal(u32::from(v), 8);
4369 }
4370}
4371
4372/// `write_palette_color_map` (bitstream.c), the write side of
4373/// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
4374/// each symbol written as the position its colour takes in the neighbour
4375/// ordering `av1_get_palette_color_index_context` hands back.
4376fn write_color_index_map(
4377 enc: &mut SymbolEncoder,
4378 idx_cdfs: &mut [[u16; 9]; 5],
4379 map: &[u8],
4380 side: usize,
4381 n: usize,
4382 // spec 5.11.50 `onscreenWidth`/`onscreenHeight` in this map's own units:
4383 // a block cut by the frame's right/bottom mi edge codes ONLY this corner
4384 // and the decoder replicates it outward (`decode::palette_replicate`).
4385 // Writing the full grid spent symbols a conformant decoder never reads,
4386 // desyncing the rest of the tile (lane-palw, class
4387 // writer-phantom-units-past-edge).
4388 on: (usize, usize),
4389) {
4390 let (on_w, on_h) = (on.0.clamp(1, side), on.1.clamp(1, side));
4391 write_uniform(enc, usize::from(map[0]), n);
4392 for i in 1..(on_w + on_h - 1) {
4393 for j in (i.saturating_sub(on_h - 1)..=i.min(on_w - 1)).rev() {
4394 let (row, col) = (i - j, j);
4395 let (ctx, color_order) =
4396 crate::decode::palette_color_index_context(map, side, row, col, n);
4397 let want = map[row * side + col];
4398 let symbol = color_order[..n]
4399 .iter()
4400 .position(|&c| c == want)
4401 .expect("every colour index is in the block\'s own palette");
4402 enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]);
4403 }
4404 }
4405}
4406
4407/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag,
4408/// the size symbol, the colours and the whole colour-index map, priced
4409/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the
4410/// search reads the rate the tile will really spend, not an estimate of it.
4411/// The neighbour cache is taken as empty (the search runs before the tile
4412/// knows what its neighbours will be), which only ever over-prices.
4413pub(crate) fn palette_bits(pal: &PaletteY, side: usize, on: (usize, usize)) -> f64 {
4414 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
4415 return f64::INFINITY;
4416 };
4417 let n = usize::from(pal.size);
4418 let mut enc = SymbolEncoder::pricer();
4419 let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0];
4420 enc.symbol(1, &mut mode_cdf);
4421 let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx];
4422 enc.symbol(n - 2, &mut size_cdf);
4423 write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
4424 let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];
4425 write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n, on);
4426 enc.bits()
4427}
4428
4429/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
4430/// size symbol, both colour lists and the shared colour-index map, priced
4431/// through the very writers above (empty cache, which only over-prices).
4432pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize, on: (usize, usize)) -> f64 {
4433 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
4434 return f64::INFINITY;
4435 };
4436 let n = usize::from(pal.size);
4437 let mut enc = SymbolEncoder::pricer();
4438 let mut mode_cdf = cdf::PALETTE_UV_MODE[0];
4439 enc.symbol(1, &mut mode_cdf);
4440 let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx];
4441 enc.symbol(n - 2, &mut size_cdf);
4442 write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
4443 let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];
4444 write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n, on);
4445 enc.bits()
4446}
4447
4448/// Writes everything a key frame's block carries before its coefficients: the
4449/// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
4450/// the angle a directional mode is steered by, and its chroma mode. Hands back
4451/// the luma mode, which is what the blocks beside it read.
4452/// The DV predictor decode.rs `read_intrabc_dv` derives, mirrored line for
4453/// line off the writer's own copy of the intrabc mi grid: the `INTRA_FRAME`
4454/// stack's `nearest_mv` (or `near_mv` when that is zero), or -- when both are
4455/// -- `av1_find_ref_dv`'s fallback one superblock up, or 256 pixels plus one
4456/// superblock to the left on the tile's first superblock row, then floored to
4457/// full pel. Returns `(0, 0)` when no grid is armed, which no `allow_intrabc`
4458/// tile ever reaches.
4459fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) {
4460 const INTRABC_DELAY_PIXELS: i32 = 256;
4461 let n4 = side / MI;
4462 let stack_pred = INTRABC_GRID.with(|g| {
4463 let g = g.borrow();
4464 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
4465 let stack = crate::mvstack::find_mv_stack(
4466 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
4467 *mi_cols, *mi_rows,
4468 );
4469 if stack.nearest_mv == (0, 0) {
4470 stack.near_mv
4471 } else {
4472 stack.nearest_mv
4473 }
4474 })
4475 });
4476 let mut pred = stack_pred.unwrap_or((0, 0));
4477 if pred == (0, 0) {
4478 // `av1_find_ref_dv` takes `mib_size`, the SEQUENCE's superblock size
4479 // in mi units (lane-b128m: hardcoding 16 here made the writer's DV
4480 // predictor one 64 superblock up while decode.rs `read_intrabc_dv`
4481 // took 128 -- identical symbols, different reconstructed DV). The
4482 // tile row start is 0, exactly as the reader takes it -- both are
4483 // written for the single-tile-row streams this encoder produces.
4484 let sb_mi = if sb128_armed() { 32i32 } else { 16i32 };
4485 let sb_px = sb_mi * MI as i32;
4486 pred = if (mi_r as i32) < sb_mi {
4487 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
4488 } else {
4489 (-sb_px * 8, 0)
4490 };
4491 }
4492 ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8)
4493}
4494
4495/// Publishes one coded block into [`INTRABC_GRID`], mirroring decode.rs
4496/// `record_intrabc_mi`: every block contributes its size, an intrabc one also
4497/// its DV as an `INTRA_FRAME` candidate.
4498fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
4499 INTRABC_GRID.with(|g| {
4500 let mut g = g.borrow_mut();
4501 let Some((grid, _, _)) = g.as_mut() else {
4502 return;
4503 };
4504 let info = crate::mvstack::MiInfo {
4505 is_inter: dv.is_some(),
4506 ref_frame: 0,
4507 ref_frame1: crate::mvstack::NO_REF1,
4508 mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))),
4509 mv1: (0, 0),
4510 is_new_mv: dv.is_some(),
4511 is_global_mv0: false,
4512 is_global_mv1: false,
4513 size: n4 as u8,
4514 size_h: n4 as u8,
4515 };
4516 for r in mi_r..mi_r + n4 {
4517 for c in mi_c..mi_c + n4 {
4518 grid.set(r, c, info);
4519 }
4520 }
4521 });
4522}
4523
4524/// One full-pel block-vector component, [`write_mv_component`]'s
4525/// `force_integer_mv` twin: decode.rs `read_mv_component` infers `mv_fr`/
4526/// `mv_class0_fr` as 3 and the high-precision bit as 1 under
4527/// `force_integer_mv`, so neither symbol is written here -- writing them
4528/// would leave the decoder two symbols behind from this block on.
4529fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
4530 let mag = diff.unsigned_abs() as i32;
4531 if mag % 8 != 0 {
4532 return Err(Error::unsupported(
4533 "AV1 tile",
4534 "a block vector is coded at full-pel precision only",
4535 ));
4536 }
4537 enc.symbol(usize::from(diff < 0), &mut c.sign);
4538 let z = mag - 1;
4539 let class = mv_class_of(z);
4540 enc.symbol(class, &mut c.class);
4541 let local = z - mv_class_base(class);
4542 if class == 0 {
4543 enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit);
4544 } else {
4545 let d = local >> 3;
4546 for i in 0..class {
4547 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
4548 }
4549 }
4550 Ok(())
4551}
4552
4553/// One intrabc block's DV as a residual against [`intrabc_dv_pred`], off the
4554/// `dv` nmv context (decode.rs `read_intrabc_dv` -> `read_mv`).
4555fn write_dv(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, dv: (i32, i32), pred: (i32, i32)) -> Result<()> {
4556 let diff = (dv.0 - pred.0, dv.1 - pred.1);
4557 let joint = match (diff.0 != 0, diff.1 != 0) {
4558 (false, false) => 0,
4559 (false, true) => 1,
4560 (true, false) => 2,
4561 (true, true) => 3,
4562 };
4563 enc.symbol(joint, &mut cdfs.dv_joint);
4564 if diff.0 != 0 {
4565 write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?;
4566 }
4567 if diff.1 != 0 {
4568 write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?;
4569 }
4570 Ok(())
4571}
4572
4573/// The mode-info half of an intrabc block (decode.rs `read_intra_mode`'s
4574/// early return): `skip`, `cdef_idx`, `use_intrabc` and the DV, then nothing
4575/// -- no y/uv mode, no angle delta, no palette, and (because it is skipped)
4576/// no transform size and no residual. Publishes the block into every
4577/// neighbour band an ordinary block leaves behind, at the DC_PRED/uncoded/
4578/// skipped state a decoder reads back for it.
4579fn write_intrabc_block(
4580 enc: &mut SymbolEncoder,
4581 cdfs: &mut Cdfs,
4582 neighbours: &mut Neighbours,
4583 dv: (i32, i32),
4584 mi: (usize, usize),
4585 side: usize,
4586) -> Result<()> {
4587 let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
4588 enc.symbol(1, &mut cdfs.skip[skip_ctx]);
4589 write_cdef_idx(enc, mi, true);
4590 enc.symbol(1, &mut cdfs.intrabc);
4591 write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?;
4592 note_intrabc(dv);
4593 // The bands: DC_PRED mode (what the decoder forces), no coefficients
4594 // anywhere (skip), the block's own side for the partition context, the
4595 // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm)
4596 // for the deblock grid, and `skip` itself for the next block's skip
4597 // context.
4598 // One zero level per plane: `neighbour_state` reads `grid[0]` for the DC
4599 // sign vote, and a skipped block leaves every context cleared.
4600 let empty: [Vec<i32>; 3] = [vec![0], vec![0], vec![0]];
4601 for cell in 0..(side / SUB).max(1) {
4602 let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI));
4603 neighbours.above_mode[c + cell] = DC_PRED;
4604 neighbours.left_mode[r + cell] = DC_PRED;
4605 neighbours.above_side[c + cell] = side;
4606 neighbours.left_side[r + cell] = side;
4607 }
4608 neighbours.record_mi_planes(mi, side, &empty, true);
4609 neighbours.record_tx(mi, side, side.min(64));
4610 for cell in 0..side / MI {
4611 neighbours.above_skip[mi.1 + cell] = true;
4612 neighbours.left_skip[mi.0 + cell] = true;
4613 }
4614 Ok(())
4615}
4616
4617/// `UV_CFL_PRED` (spec 6.10.19's chroma mode enum), the fourteenth entry of
4618/// [`crate::cdf::UV_MODE_CFL`] -- the writer's twin of the decoder's own
4619/// constant.
4620pub(crate) const UV_CFL_PRED: usize = 13;
4621
4622/// The `cfl_alpha_signs` joint value (0..8) that codes this signed alpha pair,
4623/// inverting the decoder's own `read_cfl_alphas` split (`sign_u =
4624/// ((joint+1)*11)>>5`, `sign_v = (joint+1) - 3*sign_u`, with 0 ZERO, 1 NEG,
4625/// 2 POS). There is no (ZERO, ZERO) joint value, so at least one alpha of a
4626/// CfL block is nonzero by construction.
4627pub(crate) fn cfl_joint_sign(alpha_u: i32, alpha_v: i32) -> usize {
4628 let sign = |a: i32| match a.signum() {
4629 0 => 0,
4630 -1 => 1,
4631 _ => 2,
4632 };
4633 let (want_u, want_v) = (sign(alpha_u), sign(alpha_v));
4634 (0..8)
4635 .find(|&j| {
4636 let su = ((j + 1) * 11) >> 5;
4637 (su, (j + 1) - 3 * su) == (want_u, want_v)
4638 })
4639 .expect("cfl_alpha_signs covers every pair but (ZERO, ZERO)") as usize
4640}
4641
4642/// The `cfl_alpha_u`/`cfl_alpha_v` magnitude CDF row for one plane, by the
4643/// same `CFL_CONTEXT_U`/`CFL_CONTEXT_V` derivation the decoder reads with
4644/// (libaom cfl.h). `joint` is [`cfl_joint_sign`]'s value.
4645fn cfl_alpha_ctx(joint: usize, plane: usize) -> usize {
4646 let joint = joint as i32;
4647 let su = ((joint + 1) * 11) >> 5;
4648 let sv = (joint + 1) - 3 * su;
4649 if plane == 0 {
4650 (joint + 1 - 3) as usize
4651 } else {
4652 (sv * 3 + su - 3) as usize
4653 }
4654}
4655
4656/// What [`write_cfl_alphas`] will spend on this alpha pair, through the same
4657/// tables -- the encoder's RD price for the CfL arm.
4658pub(crate) fn cfl_alpha_bits(alpha_u: i32, alpha_v: i32) -> f64 {
4659 use crate::encode::symbol_bits;
4660 let joint = cfl_joint_sign(alpha_u, alpha_v);
4661 let mut bits = symbol_bits(&crate::cdf::CFL_SIGN, joint);
4662 for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
4663 if alpha != 0 {
4664 bits += symbol_bits(
4665 &crate::cdf::CFL_ALPHA[cfl_alpha_ctx(joint, plane)],
4666 (alpha.unsigned_abs() - 1) as usize,
4667 );
4668 }
4669 }
4670 bits
4671}
4672
4673/// `read_cfl_alphas` (spec 5.11.45) written: the joint sign, then each
4674/// plane's magnitude where its sign is nonzero.
4675fn write_cfl_alphas(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, (alpha_u, alpha_v): (i32, i32)) {
4676 let joint = cfl_joint_sign(alpha_u, alpha_v);
4677 enc.symbol(joint, &mut cdfs.cfl_sign);
4678 for (plane, alpha) in [alpha_u, alpha_v].into_iter().enumerate() {
4679 if alpha != 0 {
4680 enc.symbol(
4681 (alpha.unsigned_abs() - 1) as usize,
4682 &mut cdfs.cfl_alpha[cfl_alpha_ctx(joint, plane)],
4683 );
4684 }
4685 }
4686}
4687
4688fn write_intra_mode(
4689 enc: &mut SymbolEncoder,
4690 cdfs: &mut Cdfs,
4691 neighbours: &mut Neighbours,
4692 block: &BlockCoeffs,
4693 above_mode: usize,
4694 left_mode: usize,
4695 cfl: bool,
4696 // This block's own position in 4x4 mode-info units, for the `cdef_idx`
4697 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
4698 mi: (usize, usize),
4699 // The block's side in samples, which gates the palette syntax below
4700 // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]).
4701 side: usize,
4702) -> usize {
4703 let mode = usize::from(block.mode);
4704 // `av1_get_skip_txfm_context` (decode.rs `Neighbours::skip_txfm_ctx`):
4705 // above + left. Every block this writer codes outside an `allow_intrabc`
4706 // frame is unskipped, so both bands stay false and this stays 0 -- the
4707 // literal every stream before this lane was written with.
4708 let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
4709 enc.symbol(0, &mut cdfs.skip[skip_ctx]);
4710 write_cdef_idx(enc, mi, false);
4711 // `read_intrabc_info` (spec 5.11.13): the flag is read for EVERY intra
4712 // block of an `allow_intrabc` frame, not only the ones that use it.
4713 if intrabc_armed() {
4714 enc.symbol(0, &mut cdfs.intrabc);
4715 }
4716 enc.symbol(
4717 mode,
4718 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
4719 );
4720 ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng()));
4721 if (V_PRED..=D67_PRED).contains(&mode) {
4722 enc.symbol(
4723 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
4724 &mut cdfs.angle_delta[mode - V_PRED],
4725 );
4726 }
4727 // A block small enough to be offered chroma from luma reads the wider
4728 // table even when it does not take the mode.
4729 let uv_mode = usize::from(block.uv_mode);
4730 if cfl {
4731 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
4732 } else {
4733 debug_assert_ne!(uv_mode, UV_CFL_PRED, "is_cfl_allowed excludes this block");
4734 enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);
4735 }
4736 if uv_mode == UV_CFL_PRED {
4737 write_cfl_alphas(
4738 enc,
4739 cdfs,
4740 block.cfl_alphas.expect("a UV_CFL_PRED block carries its alphas"),
4741 );
4742 }
4743 // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array
4744 // the luma delta reads, indexed by the chroma mode.
4745 if (V_PRED..=D67_PRED).contains(&uv_mode) {
4746 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
4747 }
4748 // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from
4749 // the decoder's own read in `read_intra_mode`: on a frame whose header set
4750 // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED`
4751 // chroma pair each carry a use-palette flag. Both contexts are 0 here --
4752 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
4753 // codes none -- exactly the ctx-0 read the decoder does under the same
4754 // condition.
4755 write_palette_syntax(
4756 enc,
4757 cdfs,
4758 neighbours,
4759 block.palette.as_ref(),
4760 block.palette_uv.as_ref(),
4761 block.filter_intra,
4762 mode,
4763 uv_mode,
4764 mi,
4765 side,
4766 );
4767 mode
4768}
4769
4770/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for
4771/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose
4772/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a
4773/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette
4774/// then codes its size, its colours (against the neighbour colour cache) and
4775/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs
4776/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and
4777/// by the three intra arms of the inter-frame writers, which read the same
4778/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`.
4779///
4780/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the
4781/// one point every block passes through), so a block that takes no palette
4782/// still clears what the column held.
4783#[allow(clippy::too_many_arguments)]
4784fn write_palette_syntax(
4785 enc: &mut SymbolEncoder,
4786 cdfs: &mut Cdfs,
4787 neighbours: &mut Neighbours,
4788 palette: Option<&PaletteY>,
4789 palette_uv: Option<&PaletteUv>,
4790 // lane-fintra: this block's chosen `filter_intra_mode`, or `None`. Written
4791 // here rather than by the caller because its symbol sits BETWEEN the
4792 // palette colour lists and the colour-index maps (decode.rs
4793 // `read_intra_mode`), which is inside this function.
4794 filter_intra: Option<u8>,
4795 mode: usize,
4796 uv_mode: usize,
4797 mi: (usize, usize),
4798 side: usize,
4799) {
4800 if !screen_armed() {
4801 write_filter_intra(enc, cdfs, mode, side, false, filter_intra);
4802 return;
4803 }
4804 let palette = palette.filter(|_| mode == DC_PRED);
4805 let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
4806 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
4807 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
4808 let uv_cache = neighbours.palette_uv_cache(mi);
4809 if mode == DC_PRED {
4810 enc.symbol(
4811 usize::from(palette.is_some()),
4812 &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],
4813 );
4814 }
4815 if let Some(pal) = palette {
4816 let n = usize::from(pal.size);
4817 enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);
4818 write_palette_colors_y(enc, &pal.colors[..n], &cache);
4819 }
4820 if uv_mode == DC_PRED {
4821 enc.symbol(
4822 usize::from(palette_uv.is_some()),
4823 &mut cdfs.palette_uv_mode[usize::from(palette.is_some())],
4824 );
4825 }
4826 if let Some(pal) = palette_uv {
4827 let n = usize::from(pal.size);
4828 enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]);
4829 write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache);
4830 }
4831 write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra);
4832 // Both colour-index maps come after BOTH colour lists, in plane order
4833 // (`av1_visit_palette` runs from the caller, past `filter_intra`).
4834 // The on-screen extent of THIS block, from the frame mi dims armed
4835 // for this tile write -- the decoder's `palette_onscreen` half.
4836 let on = crate::decode::palette_onscreen_dims(mi.0, mi.1, side, side, frame_mi_dims());
4837 if (on.0 < side || on.1 < side) && (palette.is_some() || palette_uv.is_some()) {
4838 PALETTE_CUT_MAPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4839 }
4840 if let Some(pal) = palette {
4841 let n = usize::from(pal.size);
4842 write_color_index_map(
4843 enc,
4844 &mut cdfs.palette_y_color_index[n - 2],
4845 &pal.map,
4846 side,
4847 n,
4848 on,
4849 );
4850 note_palette(n);
4851 }
4852 if let Some(pal) = palette_uv {
4853 let n = usize::from(pal.size);
4854 let uv_side = palette_uv_side(side);
4855 write_color_index_map(
4856 enc,
4857 &mut cdfs.palette_uv_color_index[n - 2],
4858 &pal.map,
4859 uv_side,
4860 n,
4861 crate::decode::palette_onscreen_uv((side, side), on, (uv_side, uv_side)),
4862 );
4863 note_palette_uv(n);
4864 }
4865 } else {
4866 // Below `av1_allow_palette`'s size bound there is no palette syntax at
4867 // all, but `av1_filter_intra_allowed_bsize` still admits the block.
4868 write_filter_intra(enc, cdfs, mode, side, false, filter_intra);
4869 }
4870 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
4871 neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors));
4872}
4873
4874/// The side of a chroma palette's shared colour-index map for a square luma
4875/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at
4876/// the 4-px transform, NOT a plain halving (decode.rs reads the map at
4877/// exactly this size).
4878pub(crate) fn palette_uv_side(side: usize) -> usize {
4879 (side / 2).max(4)
4880}
4881
4882/// How many blocks took a palette, and of what size -- the fire count a gate
4883/// prints so that "palette is on" is a measurement rather than a claim
4884/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the
4885/// per-size histogram.
4886static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
4887 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
4888
4889/// lane-palw: colour-index maps written over the ON-SCREEN corner only,
4890/// i.e. palette blocks this writer cut at the frame's right/bottom mi edge.
4891/// A gate asserts it non-zero so it cannot pass on a stream that never cuts
4892/// one (class `gate-blind-to-feature`).
4893static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize =
4894 std::sync::atomic::AtomicUsize::new(0);
4895
4896/// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps).
4897pub fn palette_cut_maps_written() -> usize {
4898 PALETTE_CUT_MAPS.load(std::sync::atomic::Ordering::Relaxed)
4899}
4900
4901/// Zeroes [`PALETTE_CUT_MAPS`] before a gate's own encode.
4902pub fn reset_palette_cut_maps_written() {
4903 PALETTE_CUT_MAPS.store(0, std::sync::atomic::Ordering::Relaxed);
4904}
4905
4906fn note_palette(n: usize) {
4907 PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4908 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4909}
4910
4911/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can
4912/// print the share of each plane's palette separately.
4913static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] =
4914 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
4915
4916fn note_palette_uv(n: usize) {
4917 PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4918 PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4919}
4920
4921/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than
4922/// the stream -- the half of `write_palette_colors_uv` a test cannot see from
4923/// the block counts alone, and the one that desyncs the tile if this writer's
4924/// cache ever disagrees with the decoder's (`gate-blind-to-feature`).
4925static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize =
4926 std::sync::atomic::AtomicUsize::new(0);
4927
4928/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it.
4929#[cfg(test)]
4930pub(crate) fn take_palette_uv_cache_hits() -> usize {
4931 PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
4932}
4933
4934/// [`take_palette_hits`] for the chroma palette.
4935#[cfg(test)]
4936pub(crate) fn take_palette_uv_hits() -> [usize; 9] {
4937 std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4938}
4939
4940/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
4941/// its own encode.
4942#[cfg(test)]
4943pub(crate) fn take_palette_hits() -> [usize; 9] {
4944 std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4945}
4946
4947/// Writes one coded block: its mode, its three transform blocks, and what it
4948/// leaves behind for the blocks beside it. Its partition symbol is already
4949/// written, because only the caller knows what tree led here.
4950#[allow(clippy::too_many_arguments)]
4951fn write_block(
4952 enc: &mut SymbolEncoder,
4953 cdfs: &mut Cdfs,
4954 neighbours: &mut Neighbours,
4955 block: &BlockCoeffs,
4956 at: (usize, usize),
4957 side: usize,
4958 planes: &[TxbSet; 3],
4959 grids: &[Vec<i32>; 3],
4960 scans: [&Vec<u16>; 3],
4961 cfl: bool,
4962 // The frame's `tx_mode == TxMode::Select`, and the block's own chosen
4963 // depth: with it the luma residual goes through [`write_luma_select`]
4964 // (one `tx_depth` symbol, then one transform unit per tile of the block)
4965 // instead of the single whole-block transform below.
4966 tx_select: bool,
4967 all_scans: &[Vec<u16>; 4],
4968) -> Result<()> {
4969 let (r, c) = at;
4970 let at_mi = (r * (SUB / MI), c * (SUB / MI));
4971 if let Some(dv) = block.dv {
4972 write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?;
4973 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv));
4974 return Ok(());
4975 }
4976 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
4977 let mode = write_intra_mode(
4978 enc,
4979 cdfs,
4980 neighbours,
4981 block,
4982 above_mode,
4983 left_mode,
4984 cfl,
4985 at_mi,
4986 side,
4987 );
4988 // The coefficient tables read `fimode_to_intradir[filter_intra_mode]`'s
4989 // row on a filter-intra block; the neighbour publication below still gets
4990 // the block's own `DC_PRED` ([`tx_row`]).
4991 let tx_mode = tx_row(mode, block.filter_intra);
4992 let split = if tx_select {
4993 let tx = write_luma_select(
4994 enc,
4995 cdfs,
4996 neighbours,
4997 at_mi,
4998 side,
4999 usize::from(block.tx_depth),
5000 &grids[0],
5001 tx_mode,
5002 all_scans,
5003 &block.luma_tx_types,
5004 )?;
5005 tx < side
5006 } else {
5007 false
5008 };
5009 write_block_planes(
5010 enc,
5011 cdfs,
5012 planes,
5013 grids,
5014 &scans,
5015 &neighbours.around(at, side),
5016 tx_mode,
5017 tx_select,
5018 block_tx_type(block),
5019 false,
5020 );
5021 neighbours.record_planes(at, side, mode, grids, !split);
5022 clear_skip_band(neighbours, at_mi, side);
5023 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None);
5024 Ok(())
5025}
5026
5027/// An unskipped block's own `skip` publication: only an `allow_intrabc`
5028/// frame ever sets these bands, so a frame without one leaves them exactly
5029/// as they were before this lane (all false).
5030fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) {
5031 if !intrabc_armed() {
5032 return;
5033 }
5034 for cell in 0..side / MI {
5035 neighbours.above_skip[mi.1 + cell] = false;
5036 neighbours.left_skip[mi.0 + cell] = false;
5037 }
5038}
5039
5040/// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
5041/// luma transform and 4x4 chroma transforms, coded exactly like
5042/// [`write_block`] but reading its intra-mode context from the *enclosing*
5043/// 16x16 slot -- `outer_at`, in [`SUB`]-grid units -- rather than from its own
5044/// finer position, since [`Neighbours`]'s `above_mode`/`left_mode` arrays stay
5045/// at [`SUB`] (16-sample) granularity. `leaf_mi` is this leaf's own position
5046/// in 4x4 mode-info units, which is what its coefficient context (finer than
5047/// [`SUB`]) is kept and read at.
5048#[allow(clippy::too_many_arguments)]
5049fn write_leaf8(
5050 enc: &mut SymbolEncoder,
5051 cdfs: &mut Cdfs,
5052 neighbours: &mut Neighbours,
5053 block: &BlockCoeffs,
5054 outer_at: (usize, usize),
5055 leaf_mi: (usize, usize),
5056 grids: &[Vec<i32>; 3],
5057 scans: [&Vec<u16>; 3],
5058 prev_leaf: Option<((usize, usize), usize)>,
5059 tx_select: bool,
5060 all_scans: &[Vec<u16>; 4],
5061) -> Result<usize> {
5062 let (r, c) = outer_at;
5063 if let Some(dv) = block.dv {
5064 write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?;
5065 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv));
5066 return Ok(DC_PRED);
5067 }
5068 let mut above_mode = neighbours.above_mode[c];
5069 let mut left_mode = neighbours.left_mode[r];
5070 // The previous leaf sits directly above (same column, two mi rows up)
5071 // or directly to the left (same row, two mi cols over) of this one --
5072 // in either case its just-written mode, not the enclosing 16x16 slot's
5073 // stale neighbour, is what a decoder reads as this leaf's context.
5074 if let Some(((pr, pc), pmode)) = prev_leaf {
5075 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
5076 above_mode = pmode;
5077 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
5078 left_mode = pmode;
5079 }
5080 }
5081 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
5082 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF -- like every
5083 // other `write_block` caller at 16x16 and up -- not the narrower
5084 // no-CFL one: r12 lane-av1-rect, this leaf's own `cfl: false` was the
5085 // true first divergence (a differently-sized alphabet under the same
5086 // DC_PRED decision desyncs the coder even though the decoded mode is
5087 // unchanged).
5088 let mode = write_intra_mode(enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8);
5089 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
5090 // As [`write_block`]: the coefficient row follows the filter-intra mode,
5091 // the mode this leaf publishes (and returns to the next leaf) does not.
5092 let tx_mode = tx_row(mode, block.filter_intra);
5093 let split = if tx_select {
5094 let tx = write_luma_select(
5095 enc,
5096 cdfs,
5097 neighbours,
5098 leaf_mi,
5099 8,
5100 usize::from(block.tx_depth),
5101 &grids[0],
5102 tx_mode,
5103 all_scans,
5104 &block.luma_tx_types,
5105 )?;
5106 tx < 8
5107 } else {
5108 false
5109 };
5110 write_block_planes(
5111 enc,
5112 cdfs,
5113 &planes,
5114 grids,
5115 &scans,
5116 &neighbours.around_mi(leaf_mi, 8),
5117 tx_mode,
5118 tx_select,
5119 block_tx_type(block),
5120 false,
5121 );
5122 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
5123 clear_skip_band(neighbours, leaf_mi, 8);
5124 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None);
5125 Ok(mode)
5126}
5127
5128/// Writes the three transform blocks of one coded block, in the order a
5129/// decoder reads them.
5130#[allow(clippy::too_many_arguments)]
5131fn write_block_planes(
5132 enc: &mut SymbolEncoder,
5133 cdfs: &mut Cdfs,
5134 planes: &[TxbSet; 3],
5135 grids: &[Vec<i32>; 3],
5136 scans: &[&Vec<u16>; 3],
5137 around: &[Around; 3],
5138 mode: usize,
5139 // A block whose luma was already written as several transform units
5140 // ([`write_luma_select`]) has only its chroma planes left here.
5141 skip_luma: bool,
5142 // This block's single luma transform type (lane-txset); chroma's is
5143 // derived from its mode by the decoder and codes no symbol.
5144 luma_tx_type: TxType,
5145 // lane-intertx: an INTER block's chroma transforms INHERIT the luma
5146 // type (reduced to the chroma set against this frame's own
5147 // `reduced_tx_set` bit); an intra block's comes off its UV mode and
5148 // rides `DCT_DCT`'s 2D class exactly as before.
5149 inter: bool,
5150) {
5151 // lane-intertx, desync (b): the writer used to code every chroma plane
5152 // `DCT_DCT`. Chroma codes no `tx_type` symbol, but the type names the
5153 // transform class, and the class picks the scan, the `eob_pt` row and
5154 // the context offsets (the lane-txw note in `write_coeffs`) -- so an
5155 // inherited 1-D luma type desynced the chroma exactly as luma itself
5156 // once did. The reduced bit read here is the frame's own header bit,
5157 // the ONE the writer's `Cdfs` is armed with (`Cdfs::reduced_tx_set`).
5158 let reduced = cdfs.reduced_tx_set;
5159 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
5160 if plane == 0 && skip_luma {
5161 continue;
5162 }
5163 // Luma's transform covers its whole block, which fixes the all-zero
5164 // flag's context at zero; a chroma transform reads whether its
5165 // neighbours coded anything, on top of the offset the chroma tables
5166 // start at.
5167 let skip_ctx = if plane == 0 {
5168 0
5169 } else {
5170 usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
5171 };
5172 #[cfg(test)]
5173 let before = enc.tell();
5174 #[cfg(test)]
5175 let q_ctx = cdfs.q_ctx;
5176 let mut coding = cdfs.txb(planes[plane], mode);
5177 let tx_type = if plane == 0 {
5178 luma_tx_type
5179 } else if inter {
5180 crate::decode::reduce_inherited_chroma_tx_type_flagged(
5181 luma_tx_type,
5182 coding.side.min(32),
5183 coding.side.min(32),
5184 reduced,
5185 )
5186 } else {
5187 TxType::DctDct
5188 };
5189 write_coeffs(
5190 enc,
5191 &mut coding,
5192 grid,
5193 scan,
5194 skip_ctx,
5195 dc_sign_ctx(around[plane].dc_vote),
5196 Some(plane),
5197 tx_type,
5198 );
5199 #[cfg(test)]
5200 census_record(
5201 planes[plane],
5202 q_ctx,
5203 grid,
5204 f64::from(enc.tell() - before),
5205 skip_ctx,
5206 dc_sign_ctx(around[plane].dc_vote),
5207 );
5208 ec_rng_trace(|| {
5209 format!(
5210 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
5211 grid.iter().filter(|&&l| l != 0).count(),
5212 enc.tell()
5213 )
5214 });
5215 }
5216}
5217
5218/// The single luma transform type a block carries, `DCT_DCT` for one that
5219/// never searched one (lane-txset).
5220fn block_tx_type(block: &BlockCoeffs) -> TxType {
5221 block.luma_tx_types.first().copied().unwrap_or(TxType::DctDct)
5222}
5223
5224/// The `(side / tx)^2` transform units of one block's luma residual, raster
5225/// order, each with its own coefficient context and each published before the
5226/// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch).
5227/// `grid` is the block's levels in BLOCK coordinates when the transform
5228/// splits, and the single transform's own coefficient grid when it does not.
5229#[allow(clippy::too_many_arguments)]
5230fn write_luma_tus(
5231 enc: &mut SymbolEncoder,
5232 cdfs: &mut Cdfs,
5233 neighbours: &mut Neighbours,
5234 at_mi: (usize, usize),
5235 side: usize,
5236 tx: usize,
5237 grid: &[i32],
5238 mode: usize,
5239 scans: &[Vec<u16>; 4],
5240 // lane-av1tx2 r2: an INTER block's split units read the inter coefficient
5241 // tables, not the intra ones (`TxbSet::Luma*Inter`).
5242 inter: bool,
5243 // One transform type per unit in this same raster order (lane-txset).
5244 // Empty -- what every caller that never searched a type passes -- is
5245 // `DCT_DCT` throughout, the one type this writer used to code.
5246 tx_types: &[TxType],
5247) -> Result<()> {
5248 if tx < side && side > 32 && tx < 32 {
5249 // A 64x64 block's own levels reach the writer as the 32x32 corner a
5250 // 64-point transform codes unless the whole block was SPLIT into
5251 // TX_32X32 units (lane-b64b), so any finer split has nothing to slice.
5252 return Err(Error::unsupported(
5253 "AV1 tile",
5254 "a 64x64 block's luma transform splits no finer than TX_32X32",
5255 ));
5256 }
5257 let coeff_side = tx.min(32);
5258 let n = side / tx;
5259 let set = match (tx, inter) {
5260 (32, false) => TxbSet::Luma32,
5261 (16, false) => TxbSet::Luma16,
5262 (8, false) => TxbSet::Luma8,
5263 (4, false) => TxbSet::Luma4,
5264 (32, true) => TxbSet::Luma32Inter,
5265 (16, true) => TxbSet::Luma16Inter,
5266 (8, true) => TxbSet::Luma8Inter,
5267 (4, true) => TxbSet::Luma4Inter,
5268 _ => TxbSet::Luma64,
5269 };
5270 let scan = match coeff_side {
5271 32 => &scans[0],
5272 16 => &scans[1],
5273 8 => &scans[2],
5274 _ => &scans[3],
5275 };
5276 let (mi_r, mi_c) = at_mi;
5277 for tu_row in 0..n {
5278 for tu_col in 0..n {
5279 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
5280 // lane-av1straddle: libaom clips the transform loop to
5281 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
5282 // off the frame's true `mi_cols`/`mi_rows`), and decode.rs does
5283 // the same (`tu_px >= y.true_width` there): a unit whose TOP-LEFT
5284 // sample is outside the frame is NEVER coded. Writing one -- as
5285 // this loop did for the phantom right-hand column of a 32x32 at
5286 // x=192 in a 216-wide frame -- desyncs the tile at the very next
5287 // symbol, which is what made an odd-size GOP's last block
5288 // reconstruct differently and both ffmpeg decoders (libdav1d and
5289 // libaom) refuse the whole key frame.
5290 if tu_mi.0 >= neighbours.mi_rows || tu_mi.1 >= neighbours.mi_cols {
5291 continue;
5292 }
5293 let unit = if n == 1 {
5294 grid.to_vec()
5295 } else {
5296 (0..tx)
5297 .flat_map(|row| {
5298 grid[(tu_row * tx + row) * side + tu_col * tx..][..tx].to_vec()
5299 })
5300 .collect()
5301 };
5302 // spec `get_txb_ctx_general`: a lone transform unit covering its
5303 // whole block reads context 0, a smaller one the neighbour
5304 // magnitude table.
5305 let skip_ctx = if n == 1 {
5306 0
5307 } else {
5308 neighbours.luma_skip_ctx(tu_mi, tx / MI)
5309 };
5310 let around = neighbours.around_mi(tu_mi, tx)[0];
5311 #[cfg(test)]
5312 let before = enc.tell();
5313 #[cfg(test)]
5314 let q_ctx = cdfs.q_ctx;
5315 write_coeffs(
5316 enc,
5317 &mut cdfs.txb(set, mode),
5318 &unit,
5319 scan,
5320 skip_ctx,
5321 dc_sign_ctx(around.dc_vote),
5322 Some(0),
5323 tx_types
5324 .get(tu_row * n + tu_col)
5325 .copied()
5326 .unwrap_or(TxType::DctDct),
5327 );
5328 #[cfg(test)]
5329 census_record(
5330 set,
5331 q_ctx,
5332 &unit,
5333 f64::from(enc.tell() - before),
5334 skip_ctx,
5335 dc_sign_ctx(around.dc_vote),
5336 );
5337 if n > 1 {
5338 neighbours.record_mi_luma(tu_mi, tx, &unit);
5339 }
5340 }
5341 }
5342 Ok(())
5343}
5344
5345/// Writes one intra block's luma residual under `TxMode::Select`: the
5346/// `tx_depth` symbol (spec 5.11.16 `read_selected_tx_size`, off the size
5347/// category's own CDF at [`Neighbours::tx_size_ctx`]'s row), then the
5348/// `(side / tx)^2` transform units in raster order -- each predicted and
5349/// coded against what the units before it already left behind, which is why
5350/// every unit publishes its own coefficient context before the next one reads
5351/// it (decode.rs `decode_block`'s multi-transform-unit branch).
5352///
5353/// `grid` is the block's levels in BLOCK coordinates (`side` by `side`) when
5354/// the transform splits, and the single transform's own coefficient grid when
5355/// it does not. Hands back the resolved transform side in pixels.
5356#[allow(clippy::too_many_arguments)]
5357fn write_luma_select(
5358 enc: &mut SymbolEncoder,
5359 cdfs: &mut Cdfs,
5360 neighbours: &mut Neighbours,
5361 at_mi: (usize, usize),
5362 side: usize,
5363 depth: usize,
5364 grid: &[i32],
5365 mode: usize,
5366 scans: &[Vec<u16>; 4],
5367 tx_types: &[TxType],
5368) -> Result<usize> {
5369 let max_tx = side.min(64);
5370 let ctx = neighbours.tx_size_ctx(at_mi, max_tx);
5371 match max_tx {
5372 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
5373 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
5374 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
5375 64 => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
5376 _ => {
5377 return Err(Error::unsupported(
5378 "AV1 tile",
5379 "a tx_depth symbol is only coded at 8/16/32/64",
5380 ));
5381 }
5382 }
5383 let tx = max_tx >> depth;
5384 write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false, tx_types)?;
5385 neighbours.record_tx(at_mi, side, tx);
5386 Ok(tx)
5387}
5388
5389/// The transform syntax one block of an INTER frame coded with
5390/// `tx_mode == TxMode::Select` carries, in the place spec 5.11.16's
5391/// `read_block_tx_size` reads it -- after the modes and the motion vector,
5392/// before the residual:
5393/// * an inter block that codes a residual walks a var-tx tree; this writer
5394/// keeps it at its own largest transform, so that is one `txfm_split` flag
5395/// of zero, off `txfm_partition_ctx_rect`'s row, publishing the bands per
5396/// unit the way `read_var_tx_size` does.
5397/// * a skipped inter block codes nothing and records its own BLOCK size
5398/// (`set_txfm_ctxs`'s `skip_inter` term).
5399/// * an intra block codes `tx_depth` like a key frame's, but off the
5400/// `TXFM_CONTEXT` bands rather than the deblock grid.
5401///
5402/// Hands back the block's resolved luma transform side.
5403#[allow(clippy::too_many_arguments)]
5404fn write_tx_syntax_inter(
5405 enc: &mut SymbolEncoder,
5406 cdfs: &mut Cdfs,
5407 neighbours: &mut Neighbours,
5408 at_mi: (usize, usize),
5409 side: usize,
5410 is_inter: bool,
5411 skip: bool,
5412 depth: usize,
5413) -> usize {
5414 let max_tx = side.min(64);
5415 let (mi_r, mi_c) = at_mi;
5416 if is_inter {
5417 if !skip {
5418 let ctx = txfm_partition_ctx_rect(
5419 neighbours.above_txfm[mi_c],
5420 neighbours.left_txfm[mi_r],
5421 side,
5422 max_tx,
5423 max_tx,
5424 );
5425 enc.symbol(usize::from(depth != 0), &mut cdfs.txfm_partition[ctx]);
5426 if depth == 0 {
5427 neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx);
5428 return max_tx;
5429 }
5430 // lane-av1tx2 r2: one halving of the var-tx tree. Each child of a
5431 // split root codes its own `txfm_split` (decode.rs
5432 // `read_var_tx_size` only stops symbol-free at `MAX_VARTX_DEPTH`
5433 // or at a 4x4 sub-size), off the bands the children before it
5434 // published -- so the context read and the update interleave per
5435 // unit, exactly as the reader's recursion does.
5436 let tx = max_tx / 2;
5437 for row in (0..max_tx / MI).step_by(tx / MI) {
5438 for col in (0..max_tx / MI).step_by(tx / MI) {
5439 let unit = (mi_r + row, mi_c + col);
5440 // The encoder only picks depth 1 for a block wholly
5441 // inside the frame; the reader skips a unit past the true
5442 // edge, which would leave the residual units unpaired.
5443 debug_assert!(
5444 unit.0 < neighbours.mi_rows && unit.1 < neighbours.mi_cols,
5445 "a split inter transform unit past the frame edge"
5446 );
5447 let ctx = txfm_partition_ctx_rect(
5448 neighbours.above_txfm[unit.1],
5449 neighbours.left_txfm[unit.0],
5450 side,
5451 tx,
5452 tx,
5453 );
5454 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
5455 neighbours.record_txfm(unit, tx, tx, tx);
5456 }
5457 }
5458 return tx;
5459 }
5460 neighbours.record_txfm(at_mi, side, side, side);
5461 return max_tx;
5462 }
5463 let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx);
5464 match max_tx {
5465 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
5466 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
5467 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
5468 _ => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
5469 }
5470 let tx = max_tx >> depth;
5471 neighbours.record_txfm(at_mi, tx, side, side);
5472 tx
5473}
5474
5475/// What a coded transform block leaves behind for the blocks that read it as a
5476/// neighbour.
5477fn neighbour_state(grid: &[i32]) -> Neighbour {
5478 Neighbour {
5479 coded: grid.iter().any(|&l| l != 0),
5480 level: grid.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8,
5481 dc: (grid[0] != 0).then_some(grid[0] < 0),
5482 }
5483}
5484
5485/// Writes the payload of a one-tile key frame in which every superblock is
5486/// split into 32x32 blocks, each carrying the coefficients `blocks` gives it.
5487///
5488/// `blocks` gives one coefficient set per 32x32 block in raster order across
5489/// the frame. This is [`sb_coeff_key_frame_tile`] with every superblock split.
5490///
5491/// # Errors
5492/// As [`sb_coeff_key_frame_tile`], with `blocks` sized for the 32x32 grid.
5493pub fn split_coeff_key_frame_tile(
5494 mi_cols: u32,
5495 mi_rows: u32,
5496 base_q_idx: u8,
5497 blocks: &[BlockCoeffs],
5498) -> Result<Vec<u8>> {
5499 check_blocks(mi_cols, mi_rows)?;
5500 let (cols, rows) = block_grid(mi_cols, mi_rows);
5501 if blocks.len() != (cols * rows) as usize {
5502 return Err(Error::unsupported(
5503 "AV1 tile",
5504 "a coefficient key frame needs one coefficient set per 32x32 block",
5505 ));
5506 }
5507 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
5508 let superblocks: Vec<Superblock> = (0..sb_rows)
5509 .flat_map(|sb_r| (0..sb_cols).map(move |sb_c| (sb_r, sb_c)))
5510 .map(|(sb_r, sb_c)| {
5511 Superblock::Split(
5512 (0..4)
5513 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
5514 .filter(|&(r, c)| r < rows && c < cols)
5515 .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone()))
5516 .collect(),
5517 )
5518 })
5519 .collect();
5520 sb_coeff_key_frame_tile(mi_cols, mi_rows, base_q_idx, &superblocks)
5521}
5522
5523/// Lays one plane's coefficient list out over its transform, rejecting the
5524/// positions and levels the writer does not code.
5525fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
5526 let mut grid = vec![0i32; side * side];
5527 for coeff in coeffs {
5528 if usize::from(coeff.row) >= side || usize::from(coeff.col) >= side {
5529 return Err(Error::unsupported(
5530 "AV1 tile",
5531 "a coefficient sits outside the transform of its plane",
5532 ));
5533 }
5534 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
5535 return Err(Error::unsupported(
5536 "AV1 tile",
5537 format!(
5538 "coefficients are written for levels -{MAX_LEVEL}..={MAX_LEVEL} without zero"
5539 ),
5540 ));
5541 }
5542 let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
5543 if grid[pos] != 0 {
5544 return Err(Error::unsupported(
5545 "AV1 tile",
5546 "two coefficients of one block share a position",
5547 ));
5548 }
5549 grid[pos] = coeff.level;
5550 }
5551 Ok(grid)
5552}
5553
5554/// The default scan of a square transform (spec 8.4.2's `Default_Scan_NxN`),
5555/// as raster positions in the order they are coded.
5556///
5557/// The table is a rule rather than hundreds of pinned numbers: the scan walks
5558/// the anti-diagonals of the transform outwards from the origin, each diagonal
5559/// from its top-right end on odd diagonals and from its bottom-left end on
5560/// even ones.
5561fn default_scan(side: usize) -> Vec<u16> {
5562 let mut scan = Vec::with_capacity(side * side);
5563 for d in 0..(2 * side - 1) {
5564 let lo = d.saturating_sub(side - 1);
5565 let hi = d.min(side - 1);
5566 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5567 if d % 2 == 0 {
5568 scan.extend(diagonal.rev());
5569 } else {
5570 scan.extend(diagonal);
5571 }
5572 }
5573 scan
5574}
5575
5576/// What one 32x32 luma transform block's levels cost, in bits, priced through
5577/// the very CDFs [`write_coeffs`] will write them with -- end-of-block
5578/// position, base levels, base range, signs and the Golomb tail all included.
5579///
5580/// The mode search calls this before the block's neighbours exist, so the two
5581/// neighbour-derived contexts (the block-skip context and the DC sign context)
5582/// are taken as zero. Every other context inside the block is exact, because
5583/// those are read from the block's own levels.
5584///
5585/// The encoder codes 32x32 luma only -- every superblock it emits is split --
5586/// so one table is all the search needs; a second block size would need its
5587/// own entry point rather than a size argument, because the table and the scan
5588/// have to agree.
5589/// What the search paid for every coefficient of `blocks`, in bits: the same
5590/// [`coeff_bits`] price the mode search ranked those blocks by, summed over
5591/// the blocks that were actually kept.
5592///
5593/// The instrument behind `predicted_coeff_bits_track_the_tile_the_writer_wrote`
5594/// (lane-av1rd1): the writer codes these levels against a state that has
5595/// adapted away from the defaults `coeff_bits` prices with, and against real
5596/// neighbour contexts instead of the empty ones, so the sum here and the tile
5597/// the writer produced differ by exactly that drift plus the non-coefficient
5598/// syntax (partition/mode/skip/mv symbols) the sum leaves out.
5599#[cfg(test)]
5600fn dense(coeffs: &[Coeff], side: usize) -> Vec<i32> {
5601 let mut grid = vec![0i32; side * side];
5602 for c in coeffs {
5603 grid[usize::from(c.row) * side + usize::from(c.col)] = c.level;
5604 }
5605 grid
5606}
5607
5608#[cfg(test)]
5609pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8) -> f64 {
5610 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
5611 superblocks
5612 .iter()
5613 .map(|sb| match sb {
5614 // A whole 64x64 codes its luma through `TxbSet::Luma64` (only the
5615 // top-left 32x32 carries coefficients) and each chroma plane at
5616 // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here.
5617 Superblock::Whole(block) if !block.skip => {
5618 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
5619 + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5620 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5621 }
5622 Superblock::Whole(_) => 0.0,
5623 Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx),
5624 })
5625 .sum()
5626}
5627
5628#[cfg(test)]
5629pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
5630 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
5631 fn block_bits(block: &BlockCoeffs, side: usize, q_ctx: usize) -> f64 {
5632 if let Some(leaves) = &block.eight {
5633 return leaves.iter().map(|l| block_bits(l, 8, q_ctx)).sum();
5634 }
5635 if block.skip {
5636 return 0.0;
5637 }
5638 let inter = block.inter.is_some();
5639 let (luma, chroma) = match (side, inter) {
5640 (32, false) => (TxbSet::Luma32, TxbSet::Chroma16),
5641 (32, true) => (TxbSet::Luma32Inter, TxbSet::Chroma16),
5642 (16, false) => (TxbSet::Luma16, TxbSet::Chroma8),
5643 (16, true) => (TxbSet::Luma16Inter, TxbSet::Chroma8),
5644 (_, false) => (TxbSet::Luma8, TxbSet::Chroma4),
5645 (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4),
5646 };
5647 coeff_bits(&dense(&block.luma, side), luma, q_ctx, 0, 0)
5648 + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx, 0, 0)
5649 + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx, 0, 0)
5650 }
5651 blocks
5652 .iter()
5653 .map(|q| {
5654 let side = match q {
5655 // lane-b128: a 128x128 root is SKIP by construction (the
5656 // writer refuses a residual at that size), so it names no
5657 // coefficients on any plane.
5658 Quadrant::Whole128(_) | Quadrant::Rect128(..) | Quadrant::Ab128(..) => {
5659 return 0.0;
5660 }
5661 Quadrant::Whole(_) => 32,
5662 Quadrant::Split(_) => 16,
5663 // lane-tx64: a 64x64 root that codes a residual pays for one
5664 // TX_64X64 luma transform (only the top-left 32x32 carries
5665 // coefficients) and one TX_32X32 per chroma plane -- the same
5666 // three prices `predicted_coeff_bits_sb` takes for a key
5667 // frame's whole superblock, and the same sets the writer's
5668 // `Whole64` arm codes. `block_bits`'s table has no 64 row, so
5669 // it is spelled out here.
5670 Quadrant::Whole64(block) => {
5671 return match block.skip {
5672 true => 0.0,
5673 false => {
5674 // lane-b64b: at `tx_depth = 1` the luma levels are
5675 // the whole 64-sided block, written as four
5676 // TX_32X32 units, so the pricer slices them the
5677 // same way the writer does.
5678 let luma = if block.tx_depth == 1 {
5679 let g = dense(&block.luma, 64);
5680 (0..4)
5681 .map(|tu| {
5682 let (r0, c0) = ((tu / 2) * 32, (tu % 2) * 32);
5683 let unit: Vec<i32> = (0..32)
5684 .flat_map(|row| g[(r0 + row) * 64 + c0..][..32].to_vec())
5685 .collect();
5686 coeff_bits(&unit, TxbSet::Luma32Inter, q_ctx, 0, 0)
5687 })
5688 .sum::<f64>()
5689 } else {
5690 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
5691 };
5692 luma + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5693 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
5694 }
5695 };
5696 }
5697 Quadrant::Covered => return 0.0,
5698 };
5699 q.blocks().iter().map(|b| block_bits(b, side, q_ctx)).sum::<f64>()
5700 })
5701 .sum()
5702}
5703
5704#[cfg(test)]
5705pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
5706 coeff_bits(grid, TxbSet::Luma32, 2, 0, 0)
5707}
5708
5709/// What one transform block's levels cost through the CDFs of `set`, in bits.
5710///
5711/// The search runs before the tile is written, so the adapted state the block
5712/// will really be coded against does not exist yet: the price is taken against
5713/// the defaults every tile starts from, at the frame's own coefficient
5714/// q-context (`q_ctx_of(base_q_idx)`, what `Cdfs::new` is given at
5715/// `sb_coeff_*_tile` -- lane-av1rd1: this used to be pinned at 2, so two of
5716/// the four points of the BD ladder were priced against another quantizer's
5717/// tables), and against the contexts a block whose neighbours coded nothing
5718/// reads.
5719///
5720/// lane-av1skipctx CLOSED that row: `skip_ctx`/`sign_ctx` are the caller's
5721/// now, and [`crate::encode::CoefCtxMap`] -- a per-plane, per-4x4-cell map
5722/// committed in coding order and undone with a losing partition trial's
5723/// pixels -- is the per-trial neighbour state the previous lane said the
5724/// search did not have. The census (6 frames of each clip at 640x384, q=100,
5725/// `pricer_error_census_on_clips`) moved:
5726///
5727/// | row | before | after |
5728/// |---|---|---|
5729/// | screen total | +10.3% | +9.5% |
5730/// | screen Chroma8 nz=0 | -73.0% | -1.9% |
5731/// | screen Chroma16 nz=0 | -48% | -23.4% |
5732/// | screen Chroma4 nz=0 | -74% | -6.7% |
5733/// | screen Chroma8 nz=1 / nz=2 | +32.2% / +26.2% | +4.9% / +7.9% |
5734/// | screen Luma4 nz=0 | +464% | +89.5% |
5735/// | film total | +5.3% | +1.5% |
5736///
5737/// What is left in the all-zero rows is table ADAPTATION, not context: the
5738/// price is taken against the frame's starting tables, and a frame whose
5739/// blocks mostly code nothing narrows `txb_skip` far below where it started.
5740/// A whole-block luma transform still reads context 0 -- that is what the
5741/// writer codes (`write_luma_tus`, `n == 1`), not an approximation.
5742/// The default scan of one transform size, built once per size: the search
5743/// prices thirteen modes for every block, and the scan is the same table
5744/// every time.
5745fn scan_of(side: usize) -> &'static Vec<u16> {
5746 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {
5747 [
5748 default_scan(TX4),
5749 default_scan(TX8),
5750 default_scan(TX16),
5751 default_scan(TX32),
5752 ]
5753 });
5754 match side {
5755 TX4 => &SCANS[0],
5756 TX8 => &SCANS[1],
5757 TX16 => &SCANS[2],
5758 _ => &SCANS[3],
5759 }
5760}
5761
5762/// [`scan_of`]'s `TX_CLASS_HORIZ`/`TX_CLASS_VERT` sibling (lane-txw): the
5763/// `Mrow_Scan`/`Mcol_Scan` a `V_DCT`/`H_DCT` unit is coded in, built off the
5764/// DECODER's own table so the two cannot drift, cached per size and class.
5765fn class_scan_of(side: usize, class: crate::decode::TxClass) -> &'static [u16] {
5766 static SCANS: LazyLock<[[Vec<u16>; 2]; 4]> = LazyLock::new(|| {
5767 use crate::decode::{TxClass, class_scan_table};
5768 [TX4, TX8, TX16, TX32].map(|side| {
5769 [
5770 class_scan_table(side, TxClass::Horiz),
5771 class_scan_table(side, TxClass::Vert),
5772 ]
5773 })
5774 });
5775 let size = match side {
5776 TX4 => 0,
5777 TX8 => 1,
5778 TX16 => 2,
5779 _ => 3,
5780 };
5781 let idx = usize::from(class == crate::decode::TxClass::Vert);
5782 &SCANS[size][idx]
5783}
5784
5785/// [`coeff_bits_typed`] at `DCT_DCT`, the only type the test-only pricers
5786/// ([`predicted_coeff_bits`]) model.
5787#[cfg(test)]
5788pub(crate) fn coeff_bits(
5789 grid: &[i32],
5790 set: TxbSet,
5791 q_ctx: usize,
5792 skip_ctx: usize,
5793 sign_ctx: usize,
5794) -> f64 {
5795 coeff_bits_typed(grid, set, q_ctx, skip_ctx, sign_ctx, TxType::DctDct)
5796}
5797
5798/// What levels a named transform type produced cost: the `tx_type`
5799/// symbol is part of what the block spends, so a search comparing types has
5800/// to see each one's own symbol priced (lane-txset).
5801pub(crate) fn coeff_bits_typed(
5802 grid: &[i32],
5803 set: TxbSet,
5804 q_ctx: usize,
5805 // lane-av1skipctx: the two neighbour-derived contexts, mirrored from the
5806 // writer's own (`write_block_planes`/`write_luma_tus`) off the search's
5807 // coding-order-committed map ([`crate::encode::CoefCtxMap`]). `(0, 0)` is
5808 // what every caller passed before the map existed -- exact for a luma
5809 // transform covering its whole block, and the census row that was the
5810 // largest remaining pricer error for every other block.
5811 skip_ctx: usize,
5812 sign_ctx: usize,
5813 tx_type: TxType,
5814) -> f64 {
5815 // `Cdfs::new` builds every table a tile writer adapts -- tens of
5816 // kilobytes -- and this function is called once per priced candidate:
5817 // together with the copy behind it that was 9% of the encoder's profile
5818 // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the
5819 // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per
5820 // q-context per thread beside a pristine one and restore just those from
5821 // it. The state the price is taken against is identical to a fresh
5822 // `Cdfs::new(q_ctx)`, so every price is bit-identical.
5823 // lane-av1txbits: an inter frame's writer does NOT start from the
5824 // defaults -- it starts from the tables the previous frame stored (spec
5825 // 7.20, `start_cdfs` in `encode_inter_frame`) -- so pricing against the
5826 // defaults charged the search for a narrowing the writer no longer pays.
5827 // The census measured that at +31% on the one-coefficient inter blocks
5828 // the search lives on. `arm_pricing_cdfs` puts the frame's own starting
5829 // tables under the price; nothing armed keeps the old default behaviour.
5830 let price = |slot: &mut (Cdfs, Cdfs)| {
5831 let (pristine, scratch) = (&mut slot.0, &mut slot.1);
5832 let src = pristine.txb(set, DC_PRED);
5833 let mut coding = scratch.txb(set, DC_PRED);
5834 coding.txb_skip.copy_from_slice(src.txb_skip);
5835 coding.eob_pt.copy_from_slice(src.eob_pt);
5836 if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) {
5837 dst.copy_from_slice(src);
5838 }
5839 *coding.eob_extra = *src.eob_extra;
5840 *coding.base = *src.base;
5841 *coding.base_eob = *src.base_eob;
5842 *coding.br = *src.br;
5843 *coding.dc_sign = *src.dc_sign;
5844 if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) {
5845 dst.copy_from_slice(src);
5846 }
5847 let scan = scan_of(coding.side);
5848 let mut enc = SymbolEncoder::pricer();
5849 write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None, tx_type);
5850 enc.bits()
5851 };
5852 // lane-av1speed2: 60% of the transform units of an inter stream hold no
5853 // coefficient, and for those `write_coeffs` codes ONE symbol -- the
5854 // all-zero flag -- and returns. Restoring the eight tables it might have
5855 // touched (~800 bytes of `copy_from_slice`, the largest `memmove` in the
5856 // encoder's profile) buys nothing there, so price that symbol straight
5857 // off the pristine table on a copy of its own row. Identical bits: the
5858 // scratch's `txb_skip[skip_ctx]` was restored from exactly this row, and
5859 // nothing after the flag runs.
5860 let zero_price = |slot: &mut (Cdfs, Cdfs)| {
5861 let mut row = slot.0.txb(set, DC_PRED).txb_skip[skip_ctx];
5862 let mut enc = SymbolEncoder::pricer();
5863 enc.symbol(1, &mut row);
5864 enc.bits()
5865 };
5866 let all_zero = grid.iter().all(|&level| level == 0);
5867 PRICING_BASE.with_borrow_mut(|base| {
5868 if let Some(slot) = base.as_deref_mut().filter(|s| s.0.q_ctx == q_ctx) {
5869 return if all_zero { zero_price(slot) } else { price(slot) };
5870 }
5871 PRICING.with_borrow_mut(|slots| {
5872 let slot = slots[q_ctx.min(3)]
5873 .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
5874 if all_zero { zero_price(slot) } else { price(slot) }
5875 })
5876 })
5877}
5878
5879/// The largest level [`rdoq`] offers a candidate for, and the most prices it
5880/// may spend on one block. `EC_AV1_RDOQ_MAXLEVEL` / `EC_AV1_RDOQ_BUDGET`
5881/// sweep them; see [`rdoq`] for why both exist.
5882const RDOQ_MAX_LEVEL: u32 = 2;
5883const RDOQ_BUDGET: u32 = 24;
5884
5885fn rdoq_max_level() -> u32 {
5886 static ENV: LazyLock<u32> = LazyLock::new(|| {
5887 crate::envflags::var("EC_AV1_RDOQ_MAXLEVEL")
5888 .ok()
5889 .and_then(|v| v.parse().ok())
5890 .unwrap_or(RDOQ_MAX_LEVEL)
5891 });
5892 *ENV
5893}
5894
5895fn rdoq_budget() -> u32 {
5896 static ENV: LazyLock<u32> = LazyLock::new(|| {
5897 crate::envflags::var("EC_AV1_RDOQ_BUDGET")
5898 .ok()
5899 .and_then(|v| v.parse().ok())
5900 .unwrap_or(RDOQ_BUDGET)
5901 });
5902 *ENV
5903}
5904
5905/// Rate-distortion optimised quantisation (lane-rdoq): the pass every
5906/// reference encoder runs after the quantiser and this one did not have.
5907///
5908/// The deadzone quantiser rounds each coefficient on its own, blind to what
5909/// the coded level costs. Every reference decides that per coefficient
5910/// against the entropy coder (libaom `av1_optimize_txb`, rav1e
5911/// `optimize_txb`): a level is lowered toward zero when the bits it gives
5912/// back are worth more than the squared error it adds, which also shortens
5913/// the eob when the tail levels go to zero.
5914///
5915/// Mirroring rav1e's shape without its incremental cost model: the candidate
5916/// set per coefficient is `{level, level - 1, .., 0}` walked one step at a
5917/// time in REVERSE scan order (the tail first, so a dropped tail is retried
5918/// against the shorter eob it leaves), and each candidate is priced by
5919/// re-coding the whole block through [`coeff_bits`] -- the same CDFs, the
5920/// same neighbour contexts and the same writer the search already prices
5921/// with, so no second cost model can drift from the writer (class
5922/// `table-and-reader-move-together`). That costs one `write_coeffs` per
5923/// candidate instead of rav1e's table lookup, which is why this is a preset
5924/// lever (`crate::speed::RDOQ`) and not unconditional.
5925///
5926/// `levels` is the side-strided grid the inverse transform and the writer
5927/// will read, `scaled` the pre-rounding `coeff / q` of each position
5928/// (`crate::transform::forward_and_quantize_scaled`). `lambda` is the rate
5929/// weight in units of ONE SQUARED AC QUANTISER STEP: the search's own
5930/// `sse + lambda * bits` is `step^2 * (sum (scaled - level)^2 + LAMBDA_SCALE
5931/// * bits)` once the pixel-domain error of a level is written through the
5932/// orthonormal transform (`(coeff - level * q) / 8`, `INVERSE_GAIN_RECIPROCAL`),
5933/// so `step^2` divides out of every comparison here and the DC's different
5934/// quantiser is the only per-position weight left.
5935///
5936/// Returns what the block's levels cost after the pass, so the caller prices
5937/// the tile it will actually write and never the pre-RDOQ grid.
5938#[allow(clippy::too_many_arguments)]
5939pub(crate) fn rdoq(
5940 levels: &mut [i32],
5941 scaled: &[f32],
5942 side: usize,
5943 base_q_idx: u8,
5944 set: TxbSet,
5945 skip_ctx: usize,
5946 sign_ctx: usize,
5947 lambda: f64,
5948 tx_type: TxType,
5949) -> f64 {
5950 // A 64-point transform carries its top-left 32x32 alone, and that corner
5951 // is what the writer and the pricer take (`coded_corner`).
5952 let coded = side.min(TX32);
5953 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
5954 let mut dense = if coded == side { Vec::new() } else { vec![0i32; coded * coded] };
5955 fn price(
5956 levels: &[i32],
5957 dense: &mut [i32],
5958 side: usize,
5959 coded: usize,
5960 set: TxbSet,
5961 q_ctx: usize,
5962 skip_ctx: usize,
5963 sign_ctx: usize,
5964 tx_type: TxType,
5965 ) -> f64 {
5966 if dense.is_empty() {
5967 return coeff_bits_typed(levels, set, q_ctx, skip_ctx, sign_ctx, tx_type);
5968 }
5969 for row in 0..coded {
5970 dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]);
5971 }
5972 coeff_bits_typed(dense, set, q_ctx, skip_ctx, sign_ctx, tx_type)
5973 }
5974 let mut bits = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type);
5975 // The DC has its own quantiser, so its squared error per unit of level is
5976 // `(dc_q / ac_q)^2` of an AC coefficient's.
5977 let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx)));
5978 let ac = f64::from(crate::quant::ac_q(8, i32::from(base_q_idx)));
5979 let dc_weight = (dc / ac) * (dc / ac);
5980 let census = crate::envflags::env_flag!("EC_AV1_RDOQ_CENSUS");
5981 if census {
5982 census_block(levels, scaled, side, coded, bits);
5983 }
5984 // Where the pass may spend its prices. Every candidate here costs a whole
5985 // `write_coeffs`, where rav1e's incremental model costs a table lookup,
5986 // so both bounds exist to keep that affordable -- and both cut where the
5987 // decisions do not pay anyway:
5988 // * a level above [`RDOQ_MAX_LEVEL`] is never a candidate: one step off
5989 // a big level gives back a fraction of a bit for a whole quantiser
5990 // step of squared error. What pays is `1 -> 0` and `2 -> 1`.
5991 // * at most [`RDOQ_BUDGET`] prices per block, spent from the TAIL
5992 // backwards -- the eob end, where dropping a level also shortens the
5993 // eob -- so a fine-quantizer block carrying two hundred coefficients
5994 // cannot cost two hundred re-codings.
5995 let mut budget = rdoq_budget();
5996 let max_level = rdoq_max_level();
5997 // lane-txw: the tail this walks back from is the tail of the unit's OWN
5998 // scan -- a `V_DCT`/`H_DCT` unit is coded in `Mrow_Scan`/`Mcol_Scan`, so
5999 // the 2D zigzag's last positions are not the ones whose removal shortens
6000 // its eob. Every candidate is still priced through the class-aware writer
6001 // ([`write_coeffs`]), so this changes which positions the budget reaches,
6002 // never whether a decision is right.
6003 let class = crate::decode::TxClass::of(tx_type);
6004 let order: &[u16] = if class == crate::decode::TxClass::TwoD {
6005 scan_of(coded)
6006 } else {
6007 class_scan_of(coded, class)
6008 };
6009 for &position in order.iter().rev() {
6010 if budget == 0 {
6011 break;
6012 }
6013 let (row, col) = (usize::from(position) / coded, usize::from(position) % coded);
6014 let i = row * side + col;
6015 if levels[i] == 0 || levels[i].unsigned_abs() > max_level {
6016 continue;
6017 }
6018 let s = f64::from(scaled[i]);
6019 let weight = if i == 0 { dc_weight } else { 1.0 };
6020 while budget > 0 {
6021 let level = levels[i];
6022 let candidate = level - level.signum();
6023 levels[i] = candidate;
6024 budget -= 1;
6025 let after = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type);
6026 let distortion = weight
6027 * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2));
6028 if distortion + lambda * (after - bits) < 0.0 {
6029 bits = after;
6030 if census {
6031 RDOQ_STATS[if candidate == 0 { 4 } else { 5 }].fetch_add(1, Ordering::Relaxed);
6032 }
6033 if candidate == 0 {
6034 break;
6035 }
6036 } else {
6037 levels[i] = level;
6038 break;
6039 }
6040 }
6041 }
6042 if census {
6043 RDOQ_STATS[6].fetch_add((bits * 64.0) as u64, Ordering::Relaxed);
6044 }
6045 bits
6046}
6047
6048/// blocks, coded coefficients, +-1 levels, trailing +-1 levels (a run of them
6049/// at the end of the scan), zeroed coefficients, lowered coefficients, bits
6050/// after the pass * 64, bits before the pass * 64.
6051pub(crate) static RDOQ_STATS: [AtomicU64; 8] = [
6052 AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0),
6053 AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0),
6054];
6055
6056/// The pre-pass half of [`RDOQ_STATS`] (`EC_AV1_RDOQ_CENSUS`): what the
6057/// quantiser handed the pass, which is the instrument for how much is at
6058/// stake before any decision is taken.
6059fn census_block(levels: &[i32], _scaled: &[f32], side: usize, coded: usize, bits: f64) {
6060 let scan = scan_of(coded);
6061 let at = |p: u16| levels[usize::from(p) / coded * side + usize::from(p) % coded];
6062 let nonzero = scan.iter().filter(|&&p| at(p) != 0).count();
6063 let ones = scan.iter().filter(|&&p| at(p).abs() == 1).count();
6064 let trailing = scan
6065 .iter()
6066 .rev()
6067 .skip_while(|&&p| at(p) == 0)
6068 .take_while(|&&p| at(p).abs() == 1)
6069 .count();
6070 RDOQ_STATS[0].fetch_add(1, Ordering::Relaxed);
6071 RDOQ_STATS[1].fetch_add(nonzero as u64, Ordering::Relaxed);
6072 RDOQ_STATS[2].fetch_add(ones as u64, Ordering::Relaxed);
6073 RDOQ_STATS[3].fetch_add(trailing as u64, Ordering::Relaxed);
6074 RDOQ_STATS[7].fetch_add((bits * 64.0) as u64, Ordering::Relaxed);
6075}
6076
6077/// Reads and clears [`RDOQ_STATS`].
6078pub fn take_rdoq_stats() -> [u64; 8] {
6079 std::array::from_fn(|i| RDOQ_STATS[i].swap(0, Ordering::Relaxed))
6080}
6081
6082thread_local! {
6083 /// The default tables every price falls back to, one pristine/scratch
6084 /// pair per q-context (see [`coeff_bits`] for why the pair is kept).
6085 static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
6086 const { RefCell::new([None, None, None, None]) };
6087 /// The tables the frame being searched will really be written against,
6088 /// armed per frame by the encoder ([`arm_pricing_cdfs`]) on every thread
6089 /// that prices -- the search jobs re-arm their own worker, exactly like
6090 /// the other tile thread-locals.
6091 static PRICING_BASE: RefCell<Option<Box<(Cdfs, Cdfs)>>> = const { RefCell::new(None) };
6092}
6093
6094/// Arms the tables [`coeff_bits`] prices against on this thread: the state
6095/// this frame's tile writer starts from. `None` goes back to the per-q-context
6096/// defaults (a key frame, whose writer really does start there), and so does
6097/// any frame the screen detector said yes to (`screen`).
6098///
6099/// ON by default for non-screen frames since lane-av1price2;
6100/// `EC_AV1_PRICE_FRAME_CDFS` selects 0 = never (the pre-lane behaviour),
6101/// 1 = always, unset/2 = the screen-gated default.
6102///
6103/// Pricing against the frame's REAL starting tables is the more accurate
6104/// estimate by measurement -- the pricer census
6105/// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every
6106/// transform block, and the one- and two-coefficient inter blocks the search
6107/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy only
6108/// converts into ladder bytes on camera content. Measured on ONE build
6109/// (lane-av1price2, mode 0 vs mode 2), BD-rate vs libaom / vs rav1e:
6110///
6111/// | clip | 640x384 base | 640x384 gated | native base | native gated |
6112/// |---|---|---|---|---|
6113/// | film 1080p | +79.9 / +37.3 | +78.8 / +36.1 | +18.7 / +1.4 | +18.0 / +0.7 |
6114/// | film 2160p | +94.6 / +55.7 | +95.1 / +56.4 | +48.1 / +19.8 | +47.3 / +19.2 |
6115/// | screen | +54.5 / +1.1 | +54.5 / +1.1 | +59.4 / -10.0 | +59.4 / -10.0 |
6116///
6117/// The screen rows are not merely close, they are byte-identical (the ladders
6118/// print 8832/13507/18772/24754 and 39312/52829/70719/92134 in both modes):
6119/// the gate is per frame and the detector fires on 48 of 48 screen frames, so
6120/// no screen frame is ever armed with anything but the defaults. At native
6121/// resolution -- the resolution his library is in -- both films come down
6122/// against both references and the screen capture is flat, which is this
6123/// lane's keep rule. At the downscaled 640x384 gate the 2160p film goes the
6124/// other way (+0.5/+0.7) while the 1080p one comes down further (-1.1/-1.2);
6125/// the downscale is the same recipe that exaggerated the frame pyramid's loss
6126/// sixfold, so the native table decides and the 640x384 2160p regression is
6127/// recorded here rather than argued away.
6128///
6129/// Why the screen capture needs the gate at all is in the census
6130/// (`pricer_error_census_on_clips`, 6 frames of each clip at 640x384, q=100).
6131/// Real tables take the film clip's total pricer error from +7.8% to +5.3%
6132/// and flatten its inter classes outright (Luma8Inter/Luma16Inter/Luma32Inter
6133/// 1-coefficient rows from +11.7%/+17.4%/+24.9% to -0.3%/-5.5%/+8.8%). On the
6134/// screen capture the total only moves +12.8% -> +10.3%, because the classes
6135/// that dominate a screen frame are not the ones the tables fix: its chroma
6136/// stays over-priced (Chroma8 nz=1 +32.2% -> +31.8%, nz=2 +26.2% -> +26.2%,
6137/// unmoved) and its all-zero blocks stay hugely UNDER-priced (Chroma8 nz=0
6138/// -73.0% -> -73.0%, Luma4 nz=0 +464% -> +467% -- both a pricer that assumes
6139/// `skip_ctx` 0, not a table set). So on screen the change makes the inter
6140/// luma price accurate while leaving the bigger chroma and all-zero errors
6141/// exactly where they were, which SKEWS the search's tradeoffs between them
6142/// instead of correcting them -- and the bytes get worse. The fix for that
6143/// row was the neighbour skip context, not another table set, and
6144/// lane-av1skipctx landed it (see [`coeff_bits`]): with the real contexts
6145/// under every price the screen capture comes down +59.4 -> +58.3 vs libaom
6146/// at native, still with every one of its frames armed with the defaults.
6147pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {
6148 static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
6149 let mode = *MODE.get_or_init(|| match std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() {
6150 Ok("0") => 0,
6151 Ok("1") => 1,
6152 _ => 2,
6153 });
6154 let on = match mode {
6155 0 => false,
6156 1 => true,
6157 _ => !screen,
6158 };
6159 PRICING_HITS[usize::from(on && base.is_some())].fetch_add(1, Ordering::Relaxed);
6160 PRICING_BASE.with_borrow_mut(|slot| {
6161 *slot = base.filter(|_| on).map(|c| Box::new((c.clone(), c.clone())));
6162 });
6163}
6164
6165/// How many times a frame's search was armed with the DEFAULT tables and how
6166/// many with the frame's REAL starting tables ([`arm_pricing_cdfs`]), so a
6167/// gate can print which side of the screen gate every frame landed on. Counts
6168/// arming calls, not frames: a multi-tile frame arms one worker per tile.
6169pub(crate) static PRICING_HITS: [AtomicUsize; 2] =
6170 [AtomicUsize::new(0), AtomicUsize::new(0)];
6171
6172/// Reads and clears [`PRICING_HITS`]: (default-table armings, real-table
6173/// armings).
6174#[cfg(test)]
6175pub(crate) fn take_pricing_hits() -> (usize, usize) {
6176 (
6177 PRICING_HITS[0].swap(0, Ordering::Relaxed),
6178 PRICING_HITS[1].swap(0, Ordering::Relaxed),
6179 )
6180}
6181
6182/// The pricer census (`pricer_census_on`): for every transform block the tile
6183/// writer really codes, the bits it spent against the bits [`coeff_bits`]
6184/// prices those very levels at -- the search's rate term measured against the
6185/// rate it is meant to predict. Keyed by (table set, non-zero bucket) so a
6186/// class that is systematically mispriced (all-zero blocks' `txb_skip`, the
6187/// eob of a one-coefficient block, a whole size) shows up on its own row
6188/// rather than inside one average.
6189/// Thread-local, so a census cannot pick up the blocks of another test's
6190/// encode running beside it; a multi-tile, multi-threaded encode would
6191/// therefore only census the tiles this thread wrote, which is every tile of
6192/// the one-tile-one-thread encodes the gates print it from.
6193#[cfg(test)]
6194type CensusRows = BTreeMap<(String, usize), (u64, f64, f64)>;
6195#[cfg(test)]
6196thread_local! {
6197 static CENSUS: RefCell<Option<CensusRows>> = const { RefCell::new(None) };
6198}
6199
6200/// Starts a census on this thread, discarding anything a previous one left.
6201#[cfg(test)]
6202pub(crate) fn pricer_census_on() {
6203 CENSUS.with_borrow_mut(|c| *c = Some(BTreeMap::new()));
6204}
6205
6206/// Stops the census and hands back its rows: (set, non-zero bucket) ->
6207/// (blocks, priced bits, written bits).
6208#[cfg(test)]
6209pub(crate) fn take_pricer_census() -> CensusRows {
6210 CENSUS.with_borrow_mut(|c| c.take()).unwrap_or_default()
6211}
6212
6213/// The label of a non-zero bucket, for the tables the gates print.
6214#[cfg(test)]
6215pub(crate) fn census_bucket_label(bucket: usize) -> &'static str {
6216 ["0", "1", "2", "3-4", "5-8", "9-16", "17+"][bucket]
6217}
6218
6219#[cfg(test)]
6220fn census_record(
6221 set: TxbSet,
6222 q_ctx: usize,
6223 grid: &[i32],
6224 written: f64,
6225 // The writer's own neighbour contexts for this very transform block: the
6226 // census prices the search's estimate the way the search now takes it
6227 // (lane-av1skipctx), so a row's error is the table/adaptation drift that
6228 // is left once the context is right.
6229 skip_ctx: usize,
6230 sign_ctx: usize,
6231) {
6232 if CENSUS.with_borrow(|c| c.is_none()) {
6233 return;
6234 }
6235 let nz = grid.iter().filter(|&&l| l != 0).count();
6236 let bucket = match nz {
6237 0 => 0,
6238 1 => 1,
6239 2 => 2,
6240 3..=4 => 3,
6241 5..=8 => 4,
6242 9..=16 => 5,
6243 _ => 6,
6244 };
6245 let priced = coeff_bits(grid, set, q_ctx, skip_ctx, sign_ctx);
6246 CENSUS.with_borrow_mut(|rows| {
6247 let rows = rows.as_mut().expect("the census is on");
6248 let row = rows.entry((format!("{set:?}"), bucket)).or_default();
6249 row.0 += 1;
6250 row.1 += priced;
6251 row.2 += written;
6252 });
6253}
6254
6255/// What the partition symbol of a block of `side` samples costs, in bits, when
6256/// it says the block is split (or that it is not).
6257///
6258/// The price is taken at context zero — a block whose neighbours are no finer
6259/// than it is — because the search that reads it runs before the tile knows
6260/// what its neighbours will be.
6261pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
6262 // Read-only, and the same tables every call: built once (see
6263 // [`coeff_bits`] for why that matters here).
6264 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
6265 let cdfs = &*CDFS;
6266 let cdf: &[u16] = match side {
6267 // lane-b128: the 128 superblock root's own eight-symbol alphabet.
6268 128 => &cdfs.partition_w128[0],
6269 SB => &cdfs.partition_w64[0],
6270 BLOCK => &cdfs.partition_w32[0],
6271 TX8 => &cdfs.partition_w8[0],
6272 _ => &cdfs.partition_w16[0],
6273 };
6274 let symbol = if split {
6275 PARTITION_SPLIT
6276 } else {
6277 PARTITION_NONE
6278 };
6279 crate::encode::symbol_bits(cdf, symbol)
6280}
6281
6282/// lane-b128hv: [`partition_bits`] for any partition symbol, at the same
6283/// fixed (round-2) tables -- what the 128 root's HORZ/VERT candidate is priced
6284/// with (`PARTITION_HORZ` = 1, `PARTITION_VERT` = 2).
6285pub(crate) fn partition_bits_sym(side: usize, symbol: usize) -> f64 {
6286 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
6287 let cdfs = &*CDFS;
6288 let cdf: &[u16] = match side {
6289 128 => &cdfs.partition_w128[0],
6290 SB => &cdfs.partition_w64[0],
6291 BLOCK => &cdfs.partition_w32[0],
6292 TX8 => &cdfs.partition_w8[0],
6293 _ => &cdfs.partition_w16[0],
6294 };
6295 crate::encode::symbol_bits(cdf, symbol)
6296}
6297
6298/// coeffs() for one plane's transform block of any coefficients the base and
6299/// base-range syntax reach (spec 5.11.39).
6300///
6301/// A 16x16 luma transform codes which transform type it is, because its set
6302/// holds more than one; 32x32 and 64x64 are DCT-only by spec 5.11.40. The
6303/// levels the contexts below are read from are the levels of
6304/// coefficients later in the scan, which a decoder walking the scan backwards
6305/// already has.
6306#[allow(clippy::too_many_arguments)]
6307fn write_coeffs(
6308 enc: &mut SymbolEncoder,
6309 coding: &mut TxbTables,
6310 grid: &[i32],
6311 scan: &[u16],
6312 skip_ctx: usize,
6313 sign_ctx: usize,
6314 plane: Option<usize>,
6315 // Which transform type these levels were produced with (lane-txset).
6316 // Only a luma set whose alphabet holds more than one type codes it;
6317 // chroma never codes a `tx_type` symbol at all.
6318 tx_type: TxType,
6319) {
6320 if let Some(plane) = plane {
6321 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));
6322 }
6323 let side = coding.side;
6324 // lane-txw ROOT CAUSE: this writer used to code every transform unit as
6325 // `TX_CLASS_2D` -- default zigzag scan, the 2D `eob_pt` table and the 2D
6326 // neighbour taps -- while the decoder resolves `V_DCT`/`H_DCT` to
6327 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`decode::TxClass::of`), which read
6328 // their own scan (`class_scan_table`), their own `eob_pt` row
6329 // (`eob_pt_class1`) and their own context offsets. So the first 1-D type
6330 // the search ever offered (the wider `reduced_tx_set == 0` alphabets)
6331 // desynced the tile from its own trial decode. The class is a property of
6332 // the type alone, so it is resolved here, once per unit, exactly as the
6333 // reader does it.
6334 let class = crate::decode::TxClass::of(tx_type);
6335 let scan: &[u16] = if class == crate::decode::TxClass::TwoD {
6336 scan
6337 } else {
6338 class_scan_of(side, class)
6339 };
6340 // The scan-order search reads the grid in scan order, one dependent load
6341 // per position, and an all-zero block makes it walk every one of them --
6342 // which the pricer does for candidate after candidate. A straight-line
6343 // pass settles that case first: it vectorises, and a block that codes
6344 // anything at all almost always codes its DC, so it stops at the first
6345 // element.
6346 let eob = if grid.iter().all(|&level| level == 0) {
6347 0
6348 } else {
6349 scan.iter()
6350 .rposition(|&pos| grid[pos as usize] != 0)
6351 .map_or(0, |i| i + 1)
6352 };
6353 enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]);
6354 if plane.is_some() {
6355 ec_rng_trace(|| {
6356 format!(
6357 "EC_TXBSKIP ctx={skip_ctx} eob0={} tell={} rng={}",
6358 usize::from(eob == 0),
6359 enc.tell(),
6360 enc.rng()
6361 )
6362 });
6363 }
6364 if eob == 0 {
6365 return;
6366 }
6367 // A luma transform whose type set holds more than one type codes which it
6368 // is, right after the all-zero flag (spec 5.11.39). The writer only ever
6369 // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.
6370 if let Some(cdf) = coding.tx_type.as_deref_mut() {
6371 // The symbol comes from the DECODER's own map, keyed by this set's
6372 // alphabet width, so a type this set cannot express is caught here
6373 // rather than desyncing the tile. The search only ever offers types
6374 // the set holds ([`crate::encode::tx_type_candidates`]).
6375 let symbol = crate::decode::tx_type_symbol(cdf.len(), tx_type);
6376 debug_assert!(
6377 symbol.is_some(),
6378 "{tx_type:?} is not in the {}-symbol tx_type set",
6379 cdf.len() - 1
6380 );
6381 enc.symbol(symbol.unwrap_or(TX_TYPE_DCT_DCT_SET2), cdf);
6382 if plane.is_some() {
6383 ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng()));
6384 }
6385 }
6386
6387 write_eob(enc, coding, eob, plane, class);
6388
6389 // lane-av1speed3: `side` is 4, 8, 16 or 32, but it is a runtime value --
6390 // `pos / side` compiles to a real integer division, once per coefficient,
6391 // in the encoder's largest self-time symbol. Same row and column.
6392 debug_assert!(side.is_power_of_two(), "the scan splits a position by shifting");
6393 let (shift, mask) = (side.trailing_zeros(), side - 1);
6394 for scan_idx in (0..eob).rev() {
6395 let pos = scan[scan_idx] as usize;
6396 let (row, col) = (pos >> shift, pos & mask);
6397 let level = grid[pos].abs();
6398 if scan_idx == eob - 1 {
6399 let ctx = eob_coeff_ctx(scan_idx, side * side);
6400 let sym = (level.min(NUM_BASE_LEVELS + 1) - 1) as usize;
6401 enc.symbol(sym, &mut coding.base_eob[ctx]);
6402 if plane.is_some() {
6403 ec_rng_trace(|| {
6404 format!(
6405 "EC_BASEEOB scan_idx={scan_idx} ctx={ctx} level={} tell={}",
6406 sym + 1,
6407 enc.tell()
6408 )
6409 });
6410 }
6411 } else {
6412 let ctx = base_ctx(grid, side, row, col, class);
6413 let sym = level.min(NUM_BASE_LEVELS + 1) as usize;
6414 enc.symbol(sym, &mut coding.base[ctx]);
6415 if plane.is_some() {
6416 ec_rng_trace(|| {
6417 format!(
6418 "EC_BASE scan_idx={scan_idx} ctx={ctx} level={sym} tell={}",
6419 enc.tell()
6420 )
6421 });
6422 }
6423 }
6424 if level > NUM_BASE_LEVELS {
6425 let ctx = br_ctx(grid, side, row, col, class);
6426 let mut remaining = level - (NUM_BASE_LEVELS + 1);
6427 let mut sent = 0;
6428 while sent < COEFF_BASE_RANGE {
6429 let k = remaining.min(BR_STEP);
6430 enc.symbol(k as usize, &mut coding.br[ctx]);
6431 if plane.is_some() {
6432 ec_rng_trace(|| {
6433 format!(
6434 "EC_BR scan_idx={scan_idx} ctx={ctx} k={k} tell={}",
6435 enc.tell()
6436 )
6437 });
6438 }
6439 if k < BR_STEP {
6440 break;
6441 }
6442 remaining -= k;
6443 sent += BR_STEP;
6444 }
6445 }
6446 }
6447
6448 // The signs come after the levels, in scan order, the DC's from a CDF and
6449 // the rest as raw bits (spec 5.11.39).
6450 for &pos in &scan[..eob] {
6451 let level = grid[pos as usize];
6452 if level == 0 {
6453 continue;
6454 }
6455 if pos == 0 {
6456 enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]);
6457 if plane.is_some() {
6458 ec_rng_trace(|| {
6459 format!(
6460 "EC_DCSIGN ctx={sign_ctx} neg={} tell={}",
6461 usize::from(level < 0),
6462 enc.tell()
6463 )
6464 });
6465 }
6466 } else {
6467 enc.literal(u32::from(level < 0), 1);
6468 }
6469 // A level the base and base-range syntax cannot reach carries the rest
6470 // of itself here, after its own sign (spec 5.11.39).
6471 if level.abs() > MAX_BR_LEVEL {
6472 write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32);
6473 if plane.is_some() {
6474 ec_rng_trace(|| format!("EC_GOLOMB tell={}", enc.tell()));
6475 }
6476 }
6477 }
6478 if let Some(plane) = plane {
6479 ec_rng_trace(|| format!("EC_PLANE plane={plane} eob={eob} tell_after={}", enc.tell()));
6480 }
6481}
6482
6483/// The end-of-block position (spec 5.11.39): which group of scan positions the
6484/// last coded coefficient falls in, then its offset inside that group — the
6485/// offset's top bit from a CDF and the rest as raw bits.
6486fn write_eob(
6487 enc: &mut SymbolEncoder,
6488 coding: &mut TxbTables,
6489 eob: usize,
6490 plane: Option<usize>,
6491 class: crate::decode::TxClass,
6492) {
6493 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
6494 /// end-of-block positions covers, indexed by the group's own number.
6495 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
6496 /// `Eob_Offset_Bits` (spec 5.11.39): how wide each group's offset is.
6497 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
6498
6499 let group = GROUP_START
6500 .iter()
6501 .rposition(|&start| start <= eob)
6502 .expect("the first group starts at zero");
6503 // The groups are numbered from one, and how many of them the transform
6504 // reaches is the size of its own end-of-block alphabet. A
6505 // `TX_CLASS_HORIZ`/`TX_CLASS_VERT` unit adapts a wholly separate row
6506 // (libaom's `eob_multi_ctx`), which is what `decode::read_eob` reads.
6507 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
6508 (crate::decode::TxClass::TwoD, _) | (_, None) => coding.eob_pt,
6509 (_, Some(class1)) => class1,
6510 };
6511 enc.symbol(group - 1, eob_pt);
6512 if let Some(plane) = plane {
6513 ec_rng_trace(|| {
6514 format!(
6515 "EC_EOBPT plane={plane} eob_pt={group} tell={} rng={}",
6516 enc.tell(),
6517 enc.rng()
6518 )
6519 });
6520 }
6521
6522 let bits = OFFSET_BITS[group];
6523 if bits > 0 {
6524 let offset = (eob - GROUP_START[group]) as u32;
6525 let top = (offset >> (bits - 1)) & 1;
6526 enc.symbol(top as usize, &mut coding.eob_extra[group - 3]);
6527 if let Some(plane) = plane {
6528 ec_rng_trace(|| {
6529 format!(
6530 "EC_EOBEXTRA plane={plane} eob_ctx={} top={top} tell={}",
6531 group - 3,
6532 enc.tell()
6533 )
6534 });
6535 }
6536 if bits > 1 {
6537 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
6538 if let Some(plane) = plane {
6539 ec_rng_trace(|| {
6540 format!(
6541 "EC_EOBBITS plane={plane} eob_extra={offset} tell={}",
6542 enc.tell()
6543 )
6544 });
6545 }
6546 }
6547 }
6548}
6549
6550/// Writes the remainder of a level the base and base-range syntax could not
6551/// reach (spec 5.11.40): the value plus one, as its bit length in unary
6552/// followed by the value's own bits, most significant first.
6553pub(crate) fn write_golomb(enc: &mut SymbolEncoder, value: u32) {
6554 let x = value + 1;
6555 let length = 32 - x.leading_zeros();
6556 for _ in 0..length - 1 {
6557 enc.literal(0, 1);
6558 }
6559 for i in (0..length).rev() {
6560 enc.literal((x >> i) & 1, 1);
6561 }
6562}
6563
6564/// The context of the level of the last coded coefficient (spec 8.3.2): how
6565/// far into the scan it sits, in quarters and eighths of the transform.
6566fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
6567 match scan_idx {
6568 0 => 0,
6569 i if i <= area / 8 => 1,
6570 i if i <= area / 4 => 2,
6571 _ => 3,
6572 }
6573}
6574
6575/// The context of a coefficient's level (spec 8.3.2): the magnitudes of the
6576/// five neighbours below and to the right of it — the ones a decoder walking
6577/// the scan backwards already has — plus a term for where in the transform it
6578/// sits. The DC reads context 0 whatever its neighbours carry.
6579fn base_ctx(
6580 grid: &[i32],
6581 side: usize,
6582 row: usize,
6583 col: usize,
6584 class: crate::decode::TxClass,
6585) -> usize {
6586 use crate::decode::TxClass;
6587 // Only `TX_CLASS_2D` short-circuits its DC to context 0
6588 // (`get_nz_map_ctx_from_stats`'s `(tx_class | coeff_idx) == 0`); a 1-D
6589 // class runs the DC through the same neighbour sum as every other
6590 // position.
6591 if class == TxClass::TwoD && row == 0 && col == 0 {
6592 return 0;
6593 }
6594 if class != TxClass::TwoD {
6595 let offsets: [(usize, usize); 5] = if class == TxClass::Horiz {
6596 [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)]
6597 } else {
6598 [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)]
6599 };
6600 let mag: i32 = offsets
6601 .iter()
6602 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
6603 .sum();
6604 let along = if class == TxClass::Horiz { col } else { row };
6605 return (((mag + 1) >> 1).min(4) as usize)
6606 + crate::decode::nz_map_ctx_offset_1d(along.min(31));
6607 }
6608 // A coefficient two rows and two columns clear of the far edges reaches
6609 // all five neighbours, so the gather is five loads off one index with no
6610 // per-neighbour edge test -- which is where this writer spends a third of
6611 // its coefficient loop.
6612 let p = row * side + col;
6613 let mag: i32 = if row + 2 < side && col + 2 < side {
6614 [p + side, p + 1, p + side + 1, p + 2 * side, p + 2]
6615 .iter()
6616 .map(|&i| grid[i].abs().min(3))
6617 .sum()
6618 } else {
6619 [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
6620 .iter()
6621 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
6622 .sum()
6623 };
6624 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
6625 (((mag + 1) >> 1).min(4) as usize) + offset
6626}
6627
6628/// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes
6629/// of its three closest neighbours below and to the right, uncapped, and a
6630/// term separating the DC, the corner of the transform, and the rest.
6631fn br_ctx(
6632 grid: &[i32],
6633 side: usize,
6634 row: usize,
6635 col: usize,
6636 class: crate::decode::TxClass,
6637) -> usize {
6638 use crate::decode::TxClass;
6639 if class != TxClass::TwoD {
6640 let extra = if class == TxClass::Horiz {
6641 neighbour(grid, side, row, col + 2)
6642 } else {
6643 neighbour(grid, side, row + 2, col)
6644 };
6645 let mag = neighbour(grid, side, row + 1, col).abs()
6646 + neighbour(grid, side, row, col + 1).abs()
6647 + extra.abs();
6648 let mag = (((mag + 1) >> 1).min(6)) as usize;
6649 if row == 0 && col == 0 {
6650 return mag;
6651 }
6652 let near_origin = if class == TxClass::Horiz { col == 0 } else { row == 0 };
6653 return if near_origin { mag + 7 } else { mag + 14 };
6654 }
6655 let p = row * side + col;
6656 let mag: i32 = if row + 1 < side && col + 1 < side {
6657 grid[p + side].abs() + grid[p + 1].abs() + grid[p + side + 1].abs()
6658 } else {
6659 [(1, 0), (0, 1), (1, 1)]
6660 .iter()
6661 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
6662 .sum()
6663 };
6664 let mag = (((mag + 1) >> 1).min(6)) as usize;
6665 if row == 0 && col == 0 {
6666 mag
6667 } else if row < 2 && col < 2 {
6668 mag + 7
6669 } else {
6670 mag + 14
6671 }
6672}
6673
6674/// A level at a position that may fall off the transform, where the levels a
6675/// context reads are zero.
6676fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
6677 if row >= side || col >= side {
6678 0
6679 } else {
6680 grid[row * side + col]
6681 }
6682}
6683
6684/// Shared by both DC writers: one level per block, none of them zero.
6685fn check_levels(levels: &[i32], blocks: usize) -> Result<()> {
6686 if levels.len() != blocks {
6687 return Err(Error::unsupported(
6688 "AV1 tile",
6689 "a DC-only key frame needs one level per coded block",
6690 ));
6691 }
6692 if levels.iter().any(|&l| l == 0 || l.abs() > MAX_BR_LEVEL) {
6693 return Err(Error::unsupported(
6694 "AV1 tile",
6695 "a DC-only key frame is written for levels -14..=14 without zero; \
6696 wider levels need the Golomb tail",
6697 ));
6698 }
6699 Ok(())
6700}
6701
6702/// coeffs() for a luma transform block whose only coefficient is the DC (spec
6703/// 5.11.39). The block size is the transform size, so the all-zero flag's
6704/// context is 0; an end-of-block of one is token 0 of the position alphabet
6705/// with no extra bits; the transform sizes here are all DCT-only, so no
6706/// transform type is coded; and the DC's own neighbours are zero, so its
6707/// magnitude contexts are 0 throughout.
6708fn write_dc_coeffs(
6709 enc: &mut SymbolEncoder,
6710 dc_level: i32,
6711 sign_ctx: usize,
6712 q_ctx: usize,
6713 txb_skip: &[u16],
6714 base_eob: &[u16],
6715) {
6716 use crate::cdf_state::pick;
6717 let level = dc_level.abs();
6718 let eob_pt = pick(
6719 q_ctx,
6720 cdf::EOB_PT_1024_LUMA_Q0,
6721 cdf::EOB_PT_1024_LUMA_Q1,
6722 cdf::EOB_PT_1024_LUMA,
6723 cdf::EOB_PT_1024_LUMA_Q3,
6724 );
6725 let br = pick(
6726 q_ctx,
6727 cdf::COEFF_BR_LUMA_32_Q0,
6728 cdf::COEFF_BR_LUMA_32_Q1,
6729 cdf::COEFF_BR_LUMA_32,
6730 cdf::COEFF_BR_LUMA_32_Q3,
6731 );
6732 enc.symbol_fixed(0, txb_skip);
6733 enc.symbol_fixed(0, &eob_pt);
6734 enc.symbol_fixed((level.min(NUM_BASE_LEVELS + 1) - 1) as usize, base_eob);
6735 if level > NUM_BASE_LEVELS {
6736 let mut remaining = level - (NUM_BASE_LEVELS + 1);
6737 let mut sent = 0;
6738 while sent < COEFF_BASE_RANGE {
6739 let k = remaining.min(BR_STEP);
6740 enc.symbol_fixed(k as usize, &br[0]);
6741 if k < BR_STEP {
6742 break;
6743 }
6744 remaining -= k;
6745 sent += BR_STEP;
6746 }
6747 }
6748 // The signs come after the levels, DC first (spec 5.11.39).
6749 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
6750}
6751
6752/// One 4x4 unit's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for a
6753/// positive DC, minus one for a negative one, nothing for a unit whose block
6754/// carried no DC or that sits past the frame's true edge (spec
6755/// `av1_set_entropy_contexts`), which is why the vote is gathered per 4x4
6756/// unit and not per coded cell -- a unit past the edge does not vote even
6757/// when the rest of its cell does.
6758fn dc_vote(dc: Option<bool>) -> i32 {
6759 match dc {
6760 None => 0,
6761 Some(true) => -1,
6762 Some(false) => 1,
6763 }
6764}
6765
6766/// Which of the three DC sign contexts a gathered vote picks.
6767fn dc_sign_ctx(vote: i32) -> usize {
6768 match vote.signum() {
6769 0 => 0,
6770 -1 => 1,
6771 _ => 2,
6772 }
6773}
6774
6775/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`,
6776/// `pred_common.c`): both neighbours' intra/inter state when both are
6777/// available, one neighbour's when only one is, and zero at a tile's own
6778/// top-left corner.
6779pub(crate) fn intra_inter_ctx(
6780 has_above: bool,
6781 has_left: bool,
6782 above_inter: bool,
6783 left_inter: bool,
6784) -> usize {
6785 match (has_above, has_left) {
6786 (true, true) => {
6787 let (above_intra, left_intra) = (!above_inter, !left_inter);
6788 if above_intra && left_intra {
6789 3
6790 } else {
6791 usize::from(above_intra || left_intra)
6792 }
6793 }
6794 (true, false) => 2 * usize::from(!above_inter),
6795 (false, true) => 2 * usize::from(!left_inter),
6796 (false, false) => 0,
6797 }
6798}
6799
6800/// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`
6801/// component's own bits start counting from; class zero starts at zero.
6802fn mv_class_base(class: usize) -> i32 {
6803 if class == 0 { 0 } else { 2i32 << (class + 2) }
6804}
6805
6806/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse
6807/// of `mv_class_base`'s doubling ranges, ported from libaom's
6808/// `av1_get_mv_class` (`mv.h`).
6809fn mv_class_of(z: i32) -> usize {
6810 let mut class = 0;
6811 while class < 10 && mv_class_base(class + 1) <= z {
6812 class += 1;
6813 }
6814 class
6815}
6816
6817/// Writes one motion vector component's non-zero diff (spec 5.11.32
6818/// `read_mv_component`, run backwards): sign, class, then the class's own
6819/// bits, and (lane-hpmv) the eighth-pel bit when the frame armed through
6820/// [`arm_high_precision_mv`] carries `allow_high_precision_mv`. Without that
6821/// flag the eighth-pel bit is inferred as one rather than coded, so only
6822/// diffs whose eighth-pel bit really is one are representable; anything else
6823/// is refused rather than rounded, since rounding would silently code a
6824/// different vector than the caller asked for.
6825///
6826/// # Errors
6827/// Returns an error when `diff` needs eighth-pel precision in a frame coded
6828/// without `allow_high_precision_mv`.
6829fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
6830 debug_assert_ne!(diff, 0);
6831 let hp_frame = high_precision_mv();
6832 let sign = diff < 0;
6833 enc.symbol(usize::from(sign), &mut c.sign);
6834 let mag = diff.unsigned_abs() as i32;
6835 let z = mag - 1;
6836 if !hp_frame && z & 1 == 0 {
6837 return Err(Error::unsupported(
6838 "AV1 tile",
6839 "a motion vector component needs eighth-pel precision, which \
6840 allow_high_precision_mv off does not carry",
6841 ));
6842 }
6843 let class = mv_class_of(z);
6844 enc.symbol(class, &mut c.class);
6845 let local = z - mv_class_base(class);
6846 let hp = (local & 1) as usize;
6847 if class == 0 {
6848 let bit = (local >> 3) & 1;
6849 let fr = (local >> 1) & 3;
6850 enc.symbol(bit as usize, &mut c.class0_bit);
6851 enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]);
6852 // spec 5.11.32: the eighth-pel bit is CODED when the frame allows
6853 // high-precision motion vectors, and inferred as one otherwise ("if
6854 // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
6855 if hp_frame {
6856 enc.symbol(hp, &mut c.class0_hp);
6857 }
6858 } else {
6859 let d = local >> 3;
6860 let fr = (local >> 1) & 3;
6861 for i in 0..class {
6862 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
6863 }
6864 enc.symbol(fr as usize, &mut c.fr);
6865 if hp_frame {
6866 enc.symbol(hp, &mut c.hp);
6867 }
6868 }
6869 if hp_frame {
6870 HP_SYMBOLS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6871 if hp == 0 {
6872 HP_SYMBOLS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6873 }
6874 }
6875 Ok(())
6876}
6877
6878/// Writes a motion vector as a residual against `pred` (spec 5.11.32
6879/// `read_mv`): the joint symbol naming which components differ, then each
6880/// differing component.
6881fn write_mv(
6882 enc: &mut SymbolEncoder,
6883 mv_comp: &mut [MvComponentCdfs; 2],
6884 mv_joint: &mut [u16; 5],
6885 mv: (i32, i32),
6886 pred: (i32, i32),
6887) -> Result<()> {
6888 let diff = (mv.0 - pred.0, mv.1 - pred.1);
6889 let joint = match (diff.0 != 0, diff.1 != 0) {
6890 (false, false) => 0, // MV_JOINT_ZERO
6891 (false, true) => 1, // MV_JOINT_HNZVZ: column only
6892 (true, false) => 2, // MV_JOINT_HZVNZ: row only
6893 (true, true) => 3, // MV_JOINT_HNZVNZ
6894 };
6895 enc.symbol(joint, mv_joint);
6896 if diff.0 != 0 {
6897 write_mv_component(enc, &mut mv_comp[0], diff.0)?;
6898 }
6899 if diff.1 != 0 {
6900 write_mv_component(enc, &mut mv_comp[1], diff.1)?;
6901 }
6902 Ok(())
6903}
6904
6905/// What a block leaves in the neighbour reference bands: its own reference,
6906/// or `-1` when it is intra (decode.rs `Neighbours::above_ref`'s convention).
6907fn block_ref(block: &BlockCoeffs) -> i8 {
6908 block.inter.map_or(-1, |i| i.ref_frame)
6909}
6910
6911/// Writer-side counterpart of decode.rs `read_single_ref` (spec 5.11.25's
6912/// `single_ref_p1`..`p6` tree): codes `ref_frame` bit by bit, each symbol at
6913/// the context its own `single_ref_p*_ctx` derives from the immediate
6914/// above/left neighbours' references -- the same functions the decoder calls,
6915/// with `-1` standing for an intra or unavailable neighbour and no second
6916/// reference (this writer codes no compound block).
6917fn write_single_ref(
6918 enc: &mut SymbolEncoder,
6919 cdfs: &mut Cdfs,
6920 ref_frame: i8,
6921 above_ref: i8,
6922 above_ref1: Option<i8>,
6923 left_ref: i8,
6924 left_ref1: Option<i8>,
6925) {
6926 REF_HITS[(ref_frame.max(1) - 1) as usize % 7].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6927 use crate::mvstack::{
6928 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
6929 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
6930 single_ref_p5_ctx, single_ref_p6_ctx,
6931 };
6932 let above = (above_ref > 0).then_some(above_ref);
6933 let left = (left_ref > 0).then_some(left_ref);
6934 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
6935 // neighbour's references (decode.rs `read_single_ref`'s own
6936 // `above_ref1`/`left_ref1`): dropping the second one reads a different
6937 // context row for every block sitting under a compound neighbour, and so
6938 // decodes a different reference NAME.
6939 let backward = ref_frame >= BWDREF_FRAME;
6940 enc.symbol(
6941 usize::from(backward),
6942 &mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0],
6943 );
6944 if backward {
6945 let is_altref = ref_frame == ALTREF_FRAME;
6946 enc.symbol(
6947 usize::from(is_altref),
6948 &mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1],
6949 );
6950 if !is_altref {
6951 enc.symbol(
6952 usize::from(ref_frame == ALTREF2_FRAME),
6953 &mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5],
6954 );
6955 }
6956 return;
6957 }
6958 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
6959 enc.symbol(
6960 usize::from(far),
6961 &mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2],
6962 );
6963 if far {
6964 enc.symbol(
6965 usize::from(ref_frame == GOLDEN_FRAME),
6966 &mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4],
6967 );
6968 } else {
6969 enc.symbol(
6970 usize::from(ref_frame == LAST2_FRAME),
6971 &mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3],
6972 );
6973 }
6974}
6975
6976/// Per-mode fire counts of [`write_inter_mode`], indexed
6977/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block
6978/// coded (bucket 3 collects any index past 2). Read by the BD gate, which
6979/// is the only thing that proves a newly added mode ever fires
6980/// (gate-blind-to-feature).
6981static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [
6982 std::sync::atomic::AtomicUsize::new(0),
6983 std::sync::atomic::AtomicUsize::new(0),
6984 std::sync::atomic::AtomicUsize::new(0),
6985 std::sync::atomic::AtomicUsize::new(0),
6986];
6987static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [
6988 std::sync::atomic::AtomicUsize::new(0),
6989 std::sync::atomic::AtomicUsize::new(0),
6990 std::sync::atomic::AtomicUsize::new(0),
6991 std::sync::atomic::AtomicUsize::new(0),
6992];
6993
6994/// One counter per reference name (`LAST`..`ALTREF`), for the gate's own
6995/// census of what the encoder actually picks.
6996static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [
6997 std::sync::atomic::AtomicUsize::new(0),
6998 std::sync::atomic::AtomicUsize::new(0),
6999 std::sync::atomic::AtomicUsize::new(0),
7000 std::sync::atomic::AtomicUsize::new(0),
7001 std::sync::atomic::AtomicUsize::new(0),
7002 std::sync::atomic::AtomicUsize::new(0),
7003 std::sync::atomic::AtomicUsize::new(0),
7004];
7005
7006/// Takes and clears the per-reference histogram.
7007#[cfg(test)]
7008pub(crate) fn take_ref_hits() -> [usize; 7] {
7009 std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7010}
7011
7012/// Bumps the two histograms for one coded inter block.
7013/// How many blocks this process wrote whose search-chosen `ref_mv_idx` the
7014/// write-time stack could not carry, so the writer signalled a SMALLER index
7015/// (lane-sb128b). Every one of these used to price its residual against a
7016/// predictor the decoder never derives.
7017static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7018
7019/// Counts one clamped DRL index whose predictor differs from the one the
7020/// search asked for -- the harmful case, and the only one a witness can see.
7021fn note_drl_clamp(target: usize, signalled: usize, entries: usize) {
7022 DRL_CLAMP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7023 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7024 eprintln!("DRL_CLAMP target={target} signalled={signalled} entries={entries}");
7025 }
7026}
7027
7028/// Takes and clears [`DRL_CLAMP_HITS`], for a gate's own before/after delta.
7029#[cfg(test)]
7030pub(crate) fn take_drl_clamp_hits() -> usize {
7031 DRL_CLAMP_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
7032}
7033
7034fn note_inter_mode(mode: usize, drl: usize) {
7035 INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7036 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7037}
7038
7039/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW).
7040#[cfg(test)]
7041pub(crate) fn take_inter_mode_hits() -> [usize; 4] {
7042 [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7043}
7044
7045/// Takes and clears the DRL-index histogram (0, 1, 2, 3+).
7046#[cfg(test)]
7047pub(crate) fn take_drl_hits() -> [usize; 4] {
7048 [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7049}
7050
7051/// Writes the DRL index of one block: the loop the decoder runs (spec
7052/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
7053/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
7054/// stop, at most two bits. `drl_ctx[idx]` is the context between
7055/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses
7056/// between. Returns the index the symbols actually SIGNAL, which is `target`
7057/// clamped by the stack (`min(target, start + 2, entries.len() - 1)`): the
7058/// decoder derives its predictor from THAT index, so every caller must take
7059/// its own base MV from the returned value and not from `target` (lane-sb128b:
7060/// a search-chosen `ref_mv_idx` of 2 against a two-entry write-time stack
7061/// signalled index 1 and priced the residual against `pred_mv`, and the
7062/// decoder's MV silently drifted a whole frame before the drl symbols
7063/// desynced).
7064/// The DRL index [`write_drl_idx`]'s walk can actually SIGNAL against a stack
7065/// of `entries` candidates: at most two `drl_mode` symbols past `start`, and
7066/// each one needs a further entry to advance into (spec 5.11.24's
7067/// `for (idx = 0; idx < 2; idx++) if (NumMvFound > idx + 1)`).
7068///
7069/// A search that offers an index this clamps prices its residual against a
7070/// predictor the decoder never derives (lane-sb128b's silent MV drift); the
7071/// pricer's own offer set is enumerated against this rule by
7072/// `crate::encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`.
7073pub(crate) fn signalled_drl_idx(entries: usize, start: usize, target: usize) -> usize {
7074 target.min(start + 2).min(entries.saturating_sub(1)).max(start)
7075}
7076
7077fn write_drl_idx(
7078 enc: &mut SymbolEncoder,
7079 cdfs: &mut Cdfs,
7080 stack: &crate::mvstack::MvStack,
7081 start: usize,
7082 target: usize,
7083) -> usize {
7084 debug_assert_eq!(
7085 signalled_drl_idx(stack.entries.len(), start, target),
7086 {
7087 let mut i = start;
7088 while i < start + 2 && stack.entries.len() > i + 1 && i < target {
7089 i += 1;
7090 }
7091 i
7092 },
7093 "the drl clamp rule and the writer's own walk disagree",
7094 );
7095 let mut idx = start;
7096 while idx < start + 2 && stack.entries.len() > idx + 1 {
7097 let advance = idx < target;
7098 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]);
7099 if !advance {
7100 return idx;
7101 }
7102 idx += 1;
7103 }
7104 idx
7105}
7106
7107/// Writer-side counterpart of the decoder's single-reference
7108/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s
7109/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV
7110/// residual against the DRL-selected predictor. Returns the motion vector
7111/// the decoder will derive for the block (what the MI grid must record) and
7112/// whether it is `NEWMV`.
7113///
7114/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global
7115/// motion parameters at all, so every `gm_get_motion_vector` the decoder
7116/// runs is the identity model's zero vector; a lane that starts writing
7117/// real `gm_params` has to feed the same vector in here.
7118///
7119/// # Errors
7120/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision.
7121fn write_inter_mode(
7122 enc: &mut SymbolEncoder,
7123 cdfs: &mut Cdfs,
7124 info: InterInfo,
7125 stack: &crate::mvstack::MvStack,
7126) -> Result<((i32, i32), bool)> {
7127 let idx = usize::from(info.ref_mv_idx);
7128 if info.mode.compound_index().is_some() {
7129 return Err(Error::unsupported(
7130 "AV1 tile",
7131 "a compound mode is written by `write_compound_block`, not here",
7132 ));
7133 }
7134 match info.mode {
7135 InterMode::NewMv => {
7136 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
7137 let signalled = write_drl_idx(enc, cdfs, stack, 0, idx);
7138 let base = stack.entries.get(signalled).map_or(stack.pred_mv, |e| e.mv);
7139 if signalled != idx && base != stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv) {
7140 note_drl_clamp(idx, signalled, stack.entries.len());
7141 }
7142 let idx = signalled;
7143 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?;
7144 note_inter_mode(3, idx);
7145 Ok((info.mv, true))
7146 }
7147 InterMode::GlobalMv => {
7148 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7149 enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV
7150 note_inter_mode(2, 0);
7151 Ok(((0, 0), false))
7152 }
7153 InterMode::NearestMv => {
7154 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7155 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
7156 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
7157 note_inter_mode(0, 0);
7158 Ok((stack.nearest_mv, false))
7159 }
7160 InterMode::NearMv => {
7161 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
7162 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
7163 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV
7164 // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24).
7165 let idx = idx.max(1);
7166 let signalled = write_drl_idx(enc, cdfs, stack, 1, idx);
7167 let mv = stack.entries.get(signalled).map_or(stack.near_mv, |e| e.mv);
7168 if signalled != idx && mv != stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) {
7169 note_drl_clamp(idx, signalled, stack.entries.len());
7170 }
7171 let idx = signalled;
7172 note_inter_mode(1, idx);
7173 Ok((mv, false))
7174 }
7175 _ => unreachable!("compound modes are refused above"),
7176 }
7177}
7178
7179/// Writes the payload of a one-tile inter frame built from `blocks`, one
7180/// 32x32 block per entry in raster order across the frame — every superblock
7181/// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
7182/// codes a key frame, because a mixed-size partition tree buys this writer's
7183/// gate nothing a flat grid does not already prove: the CDF state, the
7184/// neighbour contexts and the single-reference/MV-stack machinery below are
7185/// exactly as size-sensitive whether the tree recurses or not, and recursing
7186/// it would be undirected scaffolding — see `sb_coeff_key_frame_tile` for
7187/// where that tree already lives, ready to graft this block's mode reads
7188/// onto once a real partition search needs it.
7189///
7190/// A block whose [`BlockCoeffs::inter`] is `Some` is coded inter: `skip`,
7191/// then `is_inter`, then a single-reference chain that always names `LAST`
7192/// (spec 5.11.25 `single_ref_p1`/`p3`/`p4`, this crate's only reference so
7193/// far), then the two-mode `read_inter_mode` chain (spec 5.11.24) and, for
7194/// [`InterMode::NewMv`], a DRL index (always zero) and a coded motion vector
7195/// residual. A block whose `inter` is `None` codes intra, through the
7196/// *inter*-frame intra path (spec 5.11.16's `intra_frame_mode_info` is the
7197/// key frame writers' path; this is `inter_frame_mode_info`'s intra branch):
7198/// `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour context, since
7199/// an inter frame's intra blocks do not read their neighbours' modes.
7200///
7201/// # Errors
7202/// Returns an error when the frame is not a whole number of 64x64
7203/// superblocks, when `blocks` does not carry exactly one entry per 32x32
7204/// block, when an intra block names a mode a key frame does not code, when a
7205/// coefficient sits outside its transform or is one the writer cannot code,
7206/// when a `NEWMV` block's motion vector needs eighth-pel precision.
7207pub fn sb_coeff_inter_frame_tile(
7208 mi_cols: u32,
7209 mi_rows: u32,
7210 base_q_idx: u8,
7211 blocks: &[Quadrant],
7212) -> Result<Vec<u8>> {
7213 sb_coeff_inter_frame_tile_tx(mi_cols, mi_rows, base_q_idx, blocks, false)
7214}
7215
7216/// [`sb_coeff_inter_frame_tile`] for a frame header carrying
7217/// `tx_mode == TxMode::Select`: every block then codes the transform syntax
7218/// [`write_tx_syntax_inter`] writes -- one `txfm_split` flag on an inter
7219/// block that carries a residual, a `tx_depth` symbol on an intra one -- and
7220/// an intra block whose depth is nonzero codes its luma as several transform
7221/// units. With `tx_select` false this writes exactly the stream it always did.
7222///
7223/// # Errors
7224/// As [`sb_coeff_inter_frame_tile`].
7225pub fn sb_coeff_inter_frame_tile_tx(
7226 mi_cols: u32,
7227 mi_rows: u32,
7228 base_q_idx: u8,
7229 blocks: &[Quadrant],
7230 tx_select: bool,
7231) -> Result<Vec<u8>> {
7232 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
7233 sb_coeff_inter_frame_tile_cdfs(
7234 mi_cols,
7235 mi_rows,
7236 base_q_idx,
7237 blocks,
7238 tx_select,
7239 &mut cdfs,
7240 TileRect::whole(mi_cols, mi_rows),
7241 &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
7242 )
7243}
7244
7245/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
7246/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`].
7247///
7248/// # Errors
7249/// As [`sb_coeff_inter_frame_tile_tx`].
7250pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
7251 mi_cols: u32,
7252 mi_rows: u32,
7253 _base_q_idx: u8,
7254 blocks: &[Quadrant],
7255 tx_select: bool,
7256 cdfs: &mut Cdfs,
7257 // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
7258 tile: TileRect,
7259 // The frame's MV grid, carried across the frame's tiles by the caller
7260 // (see the comment at `set_tile_bounds` below).
7261 grid: &mut MiGrid,
7262) -> Result<Vec<u8>> {
7263 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
7264 let _cdef_idx = CdefIdxGuard;
7265 check_blocks(mi_cols, mi_rows)?;
7266 // `block_grid`'s ceiling, not a plain division: a true frame size that is
7267 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has
7268 // one more block/superblock whose own origin is inside the true frame,
7269 // same as `sb_coeff_key_frame_tile`.
7270 let (cols, rows) = block_grid(mi_cols, mi_rows);
7271 if blocks.len() != (cols * rows) as usize {
7272 return Err(Error::unsupported(
7273 "AV1 tile",
7274 "an inter frame needs one entry per 32x32 block inside the true frame",
7275 ));
7276 }
7277 let coded: Vec<&BlockCoeffs> = blocks.iter().flat_map(Quadrant::blocks).collect();
7278 if let Some(bad) = coded
7279 .into_iter()
7280 .find(|b| b.inter.is_none() && usize::from(b.mode) >= INTRA_MODES)
7281 {
7282 return Err(Error::unsupported(
7283 "AV1 tile",
7284 format!(
7285 "intra mode {} is not one of the thirteen this writer codes",
7286 bad.mode
7287 ),
7288 ));
7289 }
7290
7291 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only
7292 /// size this writer's inter branch codes.
7293 const SIZE_GROUP_32: usize = 3;
7294
7295 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
7296 let mut neighbours = Neighbours::new(
7297 cols as usize * 2,
7298 rows as usize * 2,
7299 mi_cols as usize,
7300 mi_rows as usize,
7301 );
7302 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
7303 // The MV grid spans the FRAME and carries every tile written before this
7304 // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
7305 // keeps one grid for the whole frame and narrows its read window per
7306 // tile): the tile bounds below are what stops a candidate scan reaching
7307 // across the boundary, and a grid that was merely empty out there would
7308 // not read the same as the decoder's wherever a scan reads the array
7309 // without asking `MiGrid::get` first.
7310 let mut grid = &mut *grid;
7311 grid.set_tile_bounds(
7312 tile.mi_row0 as usize,
7313 tile.mi_col0 as usize,
7314 tile.mi_row1 as usize,
7315 tile.mi_col1 as usize,
7316 );
7317 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
7318 let mut cdfs = cdfs;
7319 let mut enc = SymbolEncoder::new();
7320 // An `is_inter` block's 32x32 luma transform reads a different
7321 // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see
7322 // `TxbSet::Luma32Inter`'s doc comment); chroma's transform type is
7323 // derived from luma's, not coded, so it never differs between the two.
7324 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
7325 let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16];
7326 // A 64x64 root's planes (lane-tx64): TX_64X64 luma -- DCT-only at this
7327 // size for an inter block too (spec `av1_get_ext_tx_set_type` returns
7328 // `TX_SET_DCTONLY` for `tx_size_sqr_up == TX_64X64`), so `Luma64` carries
7329 // no `tx_type` symbol and there is no `Luma64Inter` to write -- and one
7330 // TX_32X32 per chroma plane.
7331 let sb64_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
7332 let scan32 = default_scan(TX32);
7333 let scan16 = default_scan(TX16);
7334 let scan8 = default_scan(TX8);
7335 let scan4 = default_scan(TX4);
7336 // The same four tables again as one array, which is what the per-unit
7337 // luma writer indexes by transform side.
7338 let all_scans = [
7339 scan32.clone(),
7340 scan16.clone(),
7341 scan8.clone(),
7342 scan4.clone(),
7343 ];
7344 let zero_grids = [
7345 vec![0i32; TX32 * TX32],
7346 vec![0i32; TX16 * TX16],
7347 vec![0i32; TX16 * TX16],
7348 ];
7349
7350 let sb128 = sb128_armed();
7351 // lane-b128: set at a root whose own `PARTITION_NONE` 128x128 block was
7352 // just written, so the root's remaining 64x64 cells code nothing.
7353 let mut sb128_none = false;
7354 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
7355 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
7356 // and partition symbol first; at a 64 one this is plain raster and every
7357 // cell is its own superblock, i.e. byte-identical to the loop before.
7358 for (sb_r, sb_c, row_start, sb_start) in sb_write_order(
7359 tile.sb_row0,
7360 tile.sb_row1.min(sb_rows),
7361 tile.sb_col0,
7362 tile.sb_col1.min(sb_cols),
7363 sb128,
7364 ) {
7365 if row_start {
7366 neighbours.start_row();
7367 }
7368 if sb_start {
7369 sb128_none = false;
7370 }
7371 // lane-b128: the remaining three 64x64 cells of a root the search
7372 // left WHOLE carry no syntax at all -- the same skip the decoder's
7373 // own `sb128_none` runs.
7374 if sb128_none {
7375 continue;
7376 }
7377 if sb128 && sb_start {
7378 // The 128x128 block a `PARTITION_NONE` root carries, held by the
7379 // top-left 32x32 entry of the root's sixteen.
7380 let root_entry = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols)
7381 .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize]);
7382 let root_block = root_entry.and_then(|q| match q {
7383 Quadrant::Whole128(block) => Some(block),
7384 _ => None,
7385 });
7386 // lane-b128hv: the two rectangular halves a HORZ/VERT root carries.
7387 let root_rect = root_entry.and_then(|q| match q {
7388 Quadrant::Rect128(horz, halves) => Some((*horz, halves)),
7389 _ => None,
7390 });
7391 // lane-ab128: the three pieces an AB-shape root carries, and the
7392 // partition symbol it is coded under.
7393 let root_ab = root_entry.and_then(|q| match q {
7394 Quadrant::Ab128(symbol, pieces) => Some((*symbol as usize, pieces)),
7395 _ => None,
7396 });
7397 write_sb128_root(
7398 &mut enc,
7399 &mut cdfs,
7400 &neighbours,
7401 sb_r,
7402 sb_c,
7403 mi_cols,
7404 mi_rows,
7405 match (root_block.is_some(), root_rect, root_ab) {
7406 (true, ..) => PARTITION_NONE,
7407 (_, Some((true, _)), _) => PARTITION_HORZ,
7408 (_, Some((false, _)), _) => PARTITION_VERT,
7409 (_, _, Some((symbol, _))) => symbol,
7410 _ => PARTITION_SPLIT,
7411 },
7412 );
7413 if let Some(block) = root_block {
7414 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
7415 write_inter_block_128(
7416 &mut enc,
7417 &mut cdfs,
7418 &mut neighbours,
7419 &mut grid,
7420 at128,
7421 block,
7422 mi_cols,
7423 mi_rows,
7424 tx_select,
7425 )?;
7426 sb128_none = true;
7427 continue;
7428 }
7429 if let Some((horz, halves)) = root_rect {
7430 // libaom `decode_partition` at BLOCK_128X128: `subsize` at
7431 // (mi_row, mi_col) and a second one at + hbs (16 mi) along the
7432 // cut axis, the second only when it is inside the frame -- the
7433 // search only offers a root wholly inside, so both are.
7434 let base_mi = ((sb_r & !1) as usize * SB_MI as usize, (sb_c & !1) as usize * SB_MI as usize);
7435 let (w, h) = if horz { (128usize, 64usize) } else { (64, 128) };
7436 for (i, half) in halves.iter().enumerate() {
7437 let at_mi = if horz {
7438 (base_mi.0 + i * 16, base_mi.1)
7439 } else {
7440 (base_mi.0, base_mi.1 + i * 16)
7441 };
7442 write_inter_block_128_rect(
7443 &mut enc,
7444 &mut cdfs,
7445 &mut neighbours,
7446 &mut grid,
7447 at_mi,
7448 (w, h),
7449 half,
7450 mi_cols,
7451 mi_rows,
7452 tx_select,
7453 )?;
7454 }
7455 sb128_none = true;
7456 continue;
7457 }
7458 if let Some((symbol, pieces)) = root_ab {
7459 // libaom `decode_partition` at BLOCK_128X128, AB arm: two
7460 // 64x64 blocks and one 128x64 / 64x128 half, in the order
7461 // decode.rs' `sb128_ab` reads them
7462 // ([`crate::encode::ab128_pieces`]). An AB shape only comes
7463 // from the full alphabet symbol (both halves in frame), so
7464 // there is no edge break to mirror -- the search offers one
7465 // only at a root wholly inside.
7466 let base_mi = (
7467 (sb_r & !1) as usize * SB_MI as usize,
7468 (sb_c & !1) as usize * SB_MI as usize,
7469 );
7470 for (((mi_r, mi_c), (w, h)), piece) in
7471 crate::encode::ab128_pieces(symbol, base_mi).iter().zip(pieces)
7472 {
7473 write_inter_block_128_rect(
7474 &mut enc,
7475 &mut cdfs,
7476 &mut neighbours,
7477 &mut grid,
7478 (*mi_r, *mi_c),
7479 (*w, *h),
7480 piece,
7481 mi_cols,
7482 mi_rows,
7483 tx_select,
7484 )?;
7485 }
7486 SB128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7487 sb128_none = true;
7488 continue;
7489 }
7490 }
7491 {
7492 if !sb128 {
7493 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W);
7494 }
7495 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
7496 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
7497 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
7498 // whose bottom or right half falls outside the true frame cannot
7499 // be left whole, so the only question there is which of the three
7500 // partition symbols the split takes — same three-way signaling as
7501 // `sb_coeff_key_frame_tile`'s superblock level.
7502 let (has_cols, has_rows) = (
7503 sb_c * SB_MI + SB_MI / 2 < mi_cols,
7504 sb_r * SB_MI + SB_MI / 2 < mi_rows,
7505 );
7506 // lane-b64: a superblock the search left WHOLE — one 64x64 block
7507 // at `PARTITION_NONE`, carried by its top-left quadrant's entry
7508 // ([`Quadrant::Whole64`]). Single-reference; skipped, or with a
7509 // real residual through `TxbSet::Luma64` + two `Chroma32`
7510 // (lane-tx64).
7511 let sb64 = ((sb_r * 2) < rows && (sb_c * 2) < cols)
7512 .then(|| &blocks[((sb_r * 2) * cols + sb_c * 2) as usize])
7513 .and_then(|q| match q {
7514 Quadrant::Whole64(block) => Some(block),
7515 _ => None,
7516 });
7517 if let Some(block) = sb64 {
7518 if !has_cols || !has_rows {
7519 return Err(Error::unsupported(
7520 "AV1 tile",
7521 "a superblock that is half outside the true frame cannot be left whole",
7522 ));
7523 }
7524 let info = block.inter.ok_or_else(|| {
7525 Error::unsupported("AV1 tile", "a 64x64 root block is coded inter")
7526 })?;
7527 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[sb_ctx]);
7528 let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
7529 let has_above = neighbours.has_above(mi_r);
7530 let has_left = neighbours.has_left(mi_c);
7531 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
7532 + usize::from(neighbours.left_skip[mi_r]);
7533 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
7534 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
7535 write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), !sb128_armed(), block.skip);
7536 let ii_ctx = intra_inter_ctx(
7537 has_above,
7538 has_left,
7539 neighbours.above_inter[mi_c],
7540 neighbours.left_inter[mi_r],
7541 );
7542 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
7543 write_comp_mode(
7544 &mut enc,
7545 &mut cdfs,
7546 &neighbours,
7547 (mi_r, mi_c),
7548 (has_above, has_left),
7549 info.ref1.is_some(),
7550 );
7551 // lane-b64b: a COMPOUND 64x64 root takes the same mode chain
7552 // every other compound block does, at this superblock's own
7553 // 16x16-mi window.
7554 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
7555 write_compound_block(
7556 &mut enc,
7557 &mut cdfs,
7558 &neighbours,
7559 &grid,
7560 (mi_r, mi_c),
7561 (SB_MI as usize, SB_MI as usize),
7562 (has_above, has_left),
7563 info,
7564 (mi_cols as usize, mi_rows as usize),
7565 )?
7566 } else {
7567 write_single_ref(
7568 &mut enc,
7569 &mut cdfs,
7570 info.ref_frame,
7571 neighbours.above_ref[mi_c],
7572 neighbours.above_ref1[mi_c],
7573 neighbours.left_ref[mi_r],
7574 neighbours.left_ref1[mi_r],
7575 );
7576 let stack = find_mv_stack(
7577 &grid,
7578 mi_r,
7579 mi_c,
7580 SB_MI as usize,
7581 SB_MI as usize,
7582 info.ref_frame,
7583 mi_cols as usize,
7584 mi_rows as usize,
7585 );
7586 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
7587 if crate::msac::symtrace::dir().is_some() {
7588 crate::msac::symtrace::note(&format!(
7589 " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
7590 info.mode, info.ref_mv_idx, info.mv
7591 ));
7592 }
7593 (mv, (0, 0), is_new_mv)
7594 };
7595 for dr in 0..SB_MI as usize {
7596 for dc in 0..SB_MI as usize {
7597 grid.set(
7598 mi_r + dr,
7599 mi_c + dc,
7600 MiInfo {
7601 is_inter: true,
7602 ref_frame: info.ref_frame,
7603 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7604 mv1: mv16(mv1),
7605 mv: mv16(mv),
7606 is_new_mv,
7607 size: SB_MI as u8,
7608 size_h: SB_MI as u8,
7609 is_global_mv0: false,
7610 is_global_mv1: false,
7611 },
7612 );
7613 }
7614 }
7615 if info.ref1.is_none() {
7616 // libaom's `motion_mode_allowed` fails on a compound
7617 // block, so the decoder reads no symbol for one.
7618 write_motion_mode(
7619 &mut enc,
7620 &mut cdfs,
7621 &grid,
7622 (mi_r, mi_c),
7623 (SB_MI as usize, SB_MI as usize),
7624 (SB, SB),
7625 (mi_cols as usize, mi_rows as usize),
7626 info.ref_frame,
7627 block.motion_mode,
7628 )?;
7629 }
7630 if tx_select {
7631 // A skipped inter block writes no `txfm_split` at all --
7632 // that call only publishes the max transform size the
7633 // reader infers for it; an unskipped one writes the
7634 // `txfm_split` flag: 0 when the root's luma is one whole
7635 // TX_64X64, 1 when it is the four TX_32X32 units
7636 // lane-b64b's var-tx arm chose.
7637 write_tx_syntax_inter(
7638 &mut enc,
7639 &mut cdfs,
7640 &mut neighbours,
7641 (mi_r, mi_c),
7642 SB,
7643 true,
7644 block.skip,
7645 usize::from(block.tx_depth),
7646 );
7647 }
7648 if block.skip {
7649 neighbours.record(sb_at, SB, 0, &zero_grids);
7650 } else {
7651 // lane-tx64: the 64x64 root's real residual. Luma is one
7652 // TX_64X64 whose coded quarter is a 32x32 level grid
7653 // (`TxbSet::Luma64`, `TX32`'s own scan -- the same pair
7654 // `sb_coeff_key_frame_tile`'s `Superblock::Whole` writes),
7655 // chroma one whole TX_32X32 per plane, and `split` is
7656 // false because the luma transform covers the block.
7657 // lane-b64b: at `txfm_split = 1` the luma levels arrive in
7658 // 64x64 block coordinates and are written as the four
7659 // TX_32X32 units `write_luma_tus` slices out, each
7660 // publishing its own coefficient context before the next
7661 // one reads it; chroma is one TX_32X32 per plane either
7662 // way.
7663 let split = block.tx_depth == 1;
7664 let grids = [
7665 level_grid(&block.luma, if split { SB } else { TX32 })?,
7666 level_grid(&block.u, TX32)?,
7667 level_grid(&block.v, TX32)?,
7668 ];
7669 if split {
7670 write_luma_tus(
7671 &mut enc,
7672 &mut cdfs,
7673 &mut neighbours,
7674 (mi_r, mi_c),
7675 SB,
7676 TX32,
7677 &grids[0],
7678 0,
7679 &all_scans,
7680 true,
7681 &block.luma_tx_types,
7682 )?;
7683 }
7684 write_block_planes(
7685 &mut enc,
7686 &mut cdfs,
7687 &sb64_planes,
7688 &grids,
7689 &[&scan32, &scan32, &scan32],
7690 &neighbours.around(sb_at, SB),
7691 0,
7692 split,
7693 block_tx_type(block),
7694 true,
7695 );
7696 neighbours.record_planes(sb_at, SB, 0, &grids, !split);
7697 }
7698 neighbours.record_inter(sb_at, SB, block.skip, true, block_ref(block));
7699 record_block_compound(&mut neighbours, (mi_r, mi_c), SB, block);
7700 continue;
7701 }
7702 match (has_cols, has_rows) {
7703 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]),
7704 (true, false) => {
7705 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
7706 }
7707 (false, true) => {
7708 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
7709 }
7710 (false, false) => {}
7711 }
7712
7713 for quadrant in 0..4 {
7714 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
7715 // Only a quadrant whose own mi origin is inside the true
7716 // frame is coded at all (spec `decode_partition`'s
7717 // `r >= MiRows || c >= MiCols` early return), same filter as
7718 // `sb_coeff_key_frame_tile`'s `quadrant_positions`.
7719 if r32 >= rows || c32 >= cols {
7720 continue;
7721 }
7722 let site = &blocks[(r32 * cols + c32) as usize];
7723 let at = (r32 as usize * 2, c32 as usize * 2);
7724 let ctx32 = neighbours.partition_ctx(at, BLOCK);
7725 // spec `decode_partition`'s hasRows/hasCols recomputed at this
7726 // quadrant's own half: a whole 32x32 block cannot be left
7727 // whole once its own half straddles the true edge, mirroring
7728 // `sb_coeff_key_frame_tile`'s "cannot be left whole" refusal.
7729 let (has_cols32, has_rows32) = (
7730 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
7731 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
7732 );
7733 let block = match site {
7734 // Already coded by the `Whole64` above -- but only inside
7735 // a superblock that really carried one.
7736 Quadrant::Whole64(_)
7737 | Quadrant::Whole128(_)
7738 | Quadrant::Rect128(..)
7739 | Quadrant::Ab128(..)
7740 | Quadrant::Covered => {
7741 return Err(Error::unsupported(
7742 "AV1 tile",
7743 "a `Whole64`/`Covered` quadrant needs its superblock's \
7744 top-left entry to be the `Whole64`",
7745 ));
7746 }
7747 Quadrant::Whole(block) => {
7748 if !has_cols32 || !has_rows32 {
7749 return Err(Error::unsupported(
7750 "AV1 tile",
7751 "a 32x32 block that is half outside the true frame \
7752 cannot be left whole",
7753 ));
7754 }
7755 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]);
7756 block
7757 }
7758 Quadrant::Split(sub_blocks) => {
7759 // Same filter as `sb_coeff_key_frame_tile`'s
7760 // `sub_positions`: only the 16x16 leaves whose own mi
7761 // origin is inside the true frame are coded.
7762 let sub_positions: Vec<(usize, usize)> = (0..4)
7763 .map(|i| (r32 as usize * 2 + i / 2, c32 as usize * 2 + i % 2))
7764 .filter(|&(sr, sc)| {
7765 (sr as u32) * SUB_MI < mi_rows && (sc as u32) * SUB_MI < mi_cols
7766 })
7767 .collect();
7768 if sub_blocks.len() != sub_positions.len() {
7769 return Err(Error::unsupported(
7770 "AV1 tile",
7771 "a split 32x32 inter-frame block needs one 16x16 entry \
7772 per sub-block inside the true frame",
7773 ));
7774 }
7775 // Same three-way spec signaling as the superblock
7776 // level above, recomputed at this quadrant's own half.
7777 match (has_cols32, has_rows32) {
7778 (true, true) => {
7779 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx32]);
7780 }
7781 (true, false) => {
7782 enc.symbol_fixed(
7783 1,
7784 &gather(&cdfs.partition_w32[ctx32], VERT_ALIKE),
7785 );
7786 }
7787 (false, true) => {
7788 enc.symbol_fixed(
7789 1,
7790 &gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE),
7791 );
7792 }
7793 (false, false) => {}
7794 }
7795 for (leaf, (sr, sc)) in sub_blocks.iter().zip(sub_positions) {
7796 // A 16x16 leaf whose own half straddles the true
7797 // frame edge splits into the 8x8 leaves that are
7798 // inside it (lane-av1inter8), same split the key
7799 // frame search takes at this geometry -- on both
7800 // axes too, where `decode_partition` infers the
7801 // split and reads no symbol at all
7802 // (lane-av1rect).
7803 let (has_cols16, has_rows16) = (
7804 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
7805 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
7806 );
7807 let at16 = (sr, sc);
7808 if has_cols16 && has_rows16 {
7809 let ctx16 = neighbours.partition_ctx(at16, SUB);
7810 // A 16x16 leaf wholly inside the frame that
7811 // carries `eight` split itself further, on
7812 // cost rather than on geometry (lane-av1rd2):
7813 // spec PARTITION_SPLIT at BLOCK_16X16, then
7814 // the same four 8x8 leaves the straddling
7815 // branch below writes -- all four inside, so
7816 // the partition symbol is a real one rather
7817 // than the edge's gathered flag.
7818 if let Some(leaves) = &leaf.eight {
7819 if leaves.len() != 4 {
7820 return Err(Error::unsupported(
7821 "AV1 tile",
7822 "a 16x16 inter-frame block inside the frame that splits needs all four 8x8 leaves",
7823 ));
7824 }
7825 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w16[ctx16]);
7826 let (mi_row0, mi_col0) =
7827 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
7828 for (i, leaf8) in leaves.iter().enumerate() {
7829 let leaf_mi = (
7830 (mi_row0 + (i as u32 / 2) * 2) as usize,
7831 (mi_col0 + (i as u32 % 2) * 2) as usize,
7832 );
7833 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
7834 enc.symbol(
7835 PARTITION_NONE,
7836 &mut cdfs.partition_w8[leaf_ctx],
7837 );
7838 let (skip, is_inter) = write_inter_frame_leaf8(
7839 &mut enc,
7840 &mut cdfs,
7841 &mut neighbours,
7842 &mut grid,
7843 mi_cols,
7844 mi_rows,
7845 leaf8,
7846 leaf_mi,
7847 &scan8,
7848 &scan4,
7849 tx_select,
7850 &all_scans,
7851 )?;
7852 let _ = (skip, is_inter);
7853 }
7854 continue;
7855 }
7856 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]);
7857 write_inter_frame_leaf(
7858 &mut enc,
7859 &mut cdfs,
7860 &mut neighbours,
7861 &mut grid,
7862 mi_cols,
7863 mi_rows,
7864 leaf,
7865 at16,
7866 &scan16,
7867 &scan8,
7868 tx_select,
7869 &all_scans,
7870 )?;
7871 } else {
7872 let ctx16 = neighbours.partition_ctx(at16, SUB);
7873 match (has_cols16, has_rows16) {
7874 (true, false) => enc.symbol_fixed(
7875 1,
7876 &gather(&cdfs.partition_w16[ctx16], VERT_ALIKE),
7877 ),
7878 (false, true) => enc.symbol_fixed(
7879 1,
7880 &gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE),
7881 ),
7882 // Both halves outside: SPLIT is inferred.
7883 _ => {}
7884 }
7885 let leaves = leaf.eight.as_ref().ok_or_else(|| {
7886 Error::unsupported(
7887 "AV1 tile",
7888 "a 16x16 inter-frame block the true frame edge cuts \
7889 through needs its `eight` leaves populated",
7890 )
7891 })?;
7892 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
7893 let leaf_positions: Vec<(u32, u32)> = (0..4)
7894 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
7895 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
7896 .collect();
7897 if leaves.len() != leaf_positions.len() {
7898 return Err(Error::unsupported(
7899 "AV1 tile",
7900 "a straddling 16x16 inter-frame block needs one \
7901 `eight` entry per 8x8 leaf inside the true frame",
7902 ));
7903 }
7904 for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) {
7905 let leaf_mi = (mr as usize, mc as usize);
7906 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
7907 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w8[leaf_ctx]);
7908 let (skip, is_inter) = write_inter_frame_leaf8(
7909 &mut enc,
7910 &mut cdfs,
7911 &mut neighbours,
7912 &mut grid,
7913 mi_cols,
7914 mi_rows,
7915 leaf8,
7916 leaf_mi,
7917 &scan8,
7918 &scan4,
7919 tx_select,
7920 &all_scans,
7921 )?;
7922 let _ = (skip, is_inter);
7923 }
7924 // Same write-back-once-from-the-last-leaf rule
7925 // as the key frame search's `write_leaf8`
7926 // caller (r15): the SUB-grid skip/inter arrays
7927 // are otherwise left stale for the next
7928 // 16x16 slot.
7929
7930 }
7931 }
7932 continue;
7933 }
7934 };
7935
7936 let (r, c) = at;
7937 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
7938 let has_above = neighbours.has_above(mi_r);
7939 let has_left = neighbours.has_left(mi_c);
7940 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
7941 + usize::from(neighbours.left_skip[mi_r]);
7942 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
7943 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
7944 write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), false, block.skip);
7945
7946 let is_inter = block.inter.is_some();
7947 let (above_inter, left_inter) =
7948 (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
7949 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
7950 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
7951
7952 let mode_for_tx;
7953 if let Some(info) = block.inter {
7954 write_comp_mode(&mut enc, &mut cdfs, &neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some());
7955 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
7956 if info.ref1.is_some() {
7957 let (mv, mv1, is_new_mv) = write_compound_block(
7958 &mut enc, &mut cdfs, &neighbours, &grid, (mi_row, mi_col), (8, 8),
7959 (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
7960 )?;
7961 for dr in 0..8 {
7962 for dc in 0..8 {
7963 grid.set(mi_row + dr, mi_col + dc, MiInfo {
7964 is_inter: true,
7965 ref_frame: info.ref_frame,
7966 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7967 mv1: mv16(mv1),
7968 mv: mv16(mv),
7969 is_new_mv,
7970 size: 8,
7971 size_h: 8,
7972 is_global_mv0: false,
7973 is_global_mv1: false,
7974 });
7975 }
7976 }
7977 mode_for_tx = 0;
7978 } else {
7979 write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.above_ref1[mi_c], neighbours.left_ref[mi_r], neighbours.left_ref1[mi_r]);
7980
7981 let stack = find_mv_stack(
7982 &grid,
7983 mi_row,
7984 mi_col,
7985 8,
7986 8,
7987 info.ref_frame,
7988 mi_cols as usize,
7989 mi_rows as usize,
7990 );
7991
7992 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
7993 if crate::msac::symtrace::dir().is_some() {
7994 crate::msac::symtrace::note(&format!(
7995 " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
7996 info.mode, info.ref_mv_idx, info.mv
7997 ));
7998 }
7999 grid.set(
8000 mi_row,
8001 mi_col,
8002 MiInfo {
8003 is_inter: true,
8004 ref_frame: info.ref_frame,
8005 ref_frame1: NO_REF1,
8006 mv1: (0, 0),
8007 mv: mv16(mv),
8008 is_new_mv,
8009 size: 8,
8010 size_h: 8,
8011 is_global_mv0: false,
8012 is_global_mv1: false,
8013 },
8014 );
8015 for dr in 0..8 {
8016 for dc in 0..8 {
8017 if dr == 0 && dc == 0 {
8018 continue;
8019 }
8020 grid.set(
8021 mi_row + dr,
8022 mi_col + dc,
8023 MiInfo {
8024 is_inter: true,
8025 ref_frame: info.ref_frame,
8026 ref_frame1: NO_REF1,
8027 mv1: (0, 0),
8028 mv: mv16(mv),
8029 is_new_mv,
8030 size: 8,
8031 size_h: 8,
8032 is_global_mv0: false,
8033 is_global_mv1: false,
8034 },
8035 );
8036 }
8037 }
8038 write_motion_mode(
8039 &mut enc,
8040 &mut cdfs,
8041 &grid,
8042 (mi_row, mi_col),
8043 (8, 8),
8044 (BLOCK, BLOCK),
8045 (mi_cols as usize, mi_rows as usize),
8046 info.ref_frame,
8047 block.motion_mode,
8048 )?;
8049 mode_for_tx = 0;
8050 }
8051 } else {
8052 let mode = usize::from(block.mode);
8053 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
8054 if (V_PRED..=D67_PRED).contains(&mode) {
8055 enc.symbol(
8056 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8057 &mut cdfs.angle_delta[mode - V_PRED],
8058 );
8059 }
8060 let uv_mode = usize::from(block.uv_mode);
8061 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8062 if uv_mode == UV_CFL_PRED {
8063 write_cfl_alphas(&mut enc, &mut cdfs, block.cfl_alphas.expect("cfl"));
8064 }
8065 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8066 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8067 }
8068 mode_for_tx = tx_row(mode, block.filter_intra);
8069 // Intra: no vote, but still a coded cell -- mvstack's
8070 // extended-scan coverage must see it (module doc).
8071 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
8072 write_palette_syntax(
8073 &mut enc,
8074 &mut cdfs,
8075 &mut neighbours,
8076 block.palette.as_ref(),
8077 block.palette_uv.as_ref(),
8078 block.filter_intra,
8079 mode,
8080 uv_mode,
8081 (mi_row, mi_col),
8082 BLOCK,
8083 );
8084 for dr in 0..8 {
8085 for dc in 0..8 {
8086 grid.set(
8087 mi_row + dr,
8088 mi_col + dc,
8089 MiInfo {
8090 is_inter: false,
8091 ref_frame: -1,
8092 ref_frame1: NO_REF1,
8093 mv1: (0, 0),
8094 mv: (0, 0),
8095 is_new_mv: false,
8096 size: 8,
8097 size_h: 8,
8098 is_global_mv0: false,
8099 is_global_mv1: false,
8100 },
8101 );
8102 }
8103 }
8104 }
8105
8106 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
8107 let tx = if tx_select {
8108 write_tx_syntax_inter(
8109 &mut enc,
8110 &mut cdfs,
8111 &mut neighbours,
8112 at_mi,
8113 BLOCK,
8114 is_inter,
8115 block.skip,
8116 usize::from(block.tx_depth),
8117 )
8118 } else {
8119 BLOCK
8120 };
8121 let split = tx < BLOCK;
8122 if block.skip {
8123 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
8124 } else {
8125 let grids = [
8126 level_grid(&block.luma, TX32)?,
8127 level_grid(&block.u, TX16)?,
8128 level_grid(&block.v, TX16)?,
8129 ];
8130 if split {
8131 write_luma_tus(
8132 &mut enc,
8133 &mut cdfs,
8134 &mut neighbours,
8135 at_mi,
8136 BLOCK,
8137 tx,
8138 &grids[0],
8139 mode_for_tx,
8140 &all_scans,
8141 is_inter,
8142 &block.luma_tx_types,
8143 )?;
8144 }
8145 write_block_planes(
8146 &mut enc,
8147 &mut cdfs,
8148 if is_inter {
8149 &inter_planes
8150 } else {
8151 &intra_planes
8152 },
8153 &grids,
8154 &[&scan32, &scan16, &scan16],
8155 &neighbours.around(at, BLOCK),
8156 mode_for_tx,
8157 split,
8158 block_tx_type(block),
8159 is_inter,
8160 );
8161 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
8162 }
8163 neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));
8164 record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block);
8165 }
8166 }
8167 }
8168 Ok(enc.finish())
8169}
8170
8171/// Writes one 16x16 leaf a straddling 32x32 quadrant's [`Quadrant::Split`]
8172/// splits into: intra (spec `inter_frame_mode_info`'s intra branch, the only
8173/// one this writer used to code here) or real inter (`is_inter` coded
8174/// `true`), `NEARESTMV` only -- `NEWMV` at this size is this function's
8175/// caller's to never build (`Quadrant::Split`'s `BlockCoeffs.inter`) -- same
8176/// `single_ref`/mv-stack/DRL symbol chain as the whole-32x32 branch above,
8177/// just at this leaf's own 4x4-mi window (`bw4`/`bh4` of 4, not 8) and coded
8178/// through [`TxbSet::Luma16Inter`] rather than [`TxbSet::Luma32Inter`]. Its
8179/// own `PARTITION_NONE` symbol is already written, same contract as
8180/// [`write_block`].
8181#[allow(clippy::too_many_arguments)]
8182fn write_inter_frame_leaf(
8183 enc: &mut SymbolEncoder,
8184 cdfs: &mut Cdfs,
8185 neighbours: &mut Neighbours,
8186 grid: &mut MiGrid,
8187 mi_cols: u32,
8188 mi_rows: u32,
8189 block: &BlockCoeffs,
8190 at: (usize, usize),
8191 scan16: &Vec<u16>,
8192 scan8: &Vec<u16>,
8193 tx_select: bool,
8194 all_scans: &[Vec<u16>; 4],
8195) -> Result<()> {
8196 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
8197 return Err(Error::unsupported(
8198 "AV1 tile",
8199 format!(
8200 "intra mode {} is not one of the thirteen this writer codes",
8201 block.mode
8202 ),
8203 ));
8204 }
8205 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
8206 /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size.
8207 const SIZE_GROUP_16: usize = 2;
8208
8209 let (r, c) = at;
8210 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8211 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
8212 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
8213 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
8214 write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
8215
8216 let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c));
8217 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
8218 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8219 let is_inter = block.inter.is_some();
8220 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
8221
8222 let mode_for_tx;
8223 if let Some(info) = block.inter {
8224 write_comp_mode(enc, cdfs, neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some());
8225 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8226 if info.ref1.is_some() {
8227 let n = SUB_MI as usize;
8228 let (mv, mv1, is_new_mv) = write_compound_block(
8229 enc, cdfs, neighbours, grid, (mi_row, mi_col), (n, n),
8230 (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
8231 )?;
8232 for dr in 0..n {
8233 for dc in 0..n {
8234 grid.set(mi_row + dr, mi_col + dc, MiInfo {
8235 is_inter: true,
8236 ref_frame: info.ref_frame,
8237 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8238 mv1: mv16(mv1),
8239 mv: mv16(mv),
8240 is_new_mv,
8241 size: n as u8,
8242 size_h: n as u8,
8243 is_global_mv0: false,
8244 is_global_mv1: false,
8245 });
8246 }
8247 }
8248 mode_for_tx = 0;
8249 } else {
8250 write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.above_ref1[mi_c], neighbours.left_ref[mi_r], neighbours.left_ref1[mi_r]);
8251
8252 let stack = find_mv_stack(
8253 grid,
8254 mi_row,
8255 mi_col,
8256 SUB_MI as usize,
8257 SUB_MI as usize,
8258 info.ref_frame,
8259 mi_cols as usize,
8260 mi_rows as usize,
8261 );
8262
8263 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
8264 for dr in 0..SUB_MI as usize {
8265 for dc in 0..SUB_MI as usize {
8266 grid.set(
8267 mi_row + dr,
8268 mi_col + dc,
8269 MiInfo {
8270 is_inter: true,
8271 ref_frame: info.ref_frame,
8272 ref_frame1: NO_REF1,
8273 mv1: (0, 0),
8274 mv: mv16(mv),
8275 is_new_mv,
8276 size: SUB_MI as usize as u8,
8277 size_h: SUB_MI as usize as u8,
8278 is_global_mv0: false,
8279 is_global_mv1: false,
8280 },
8281 );
8282 }
8283 }
8284 write_motion_mode(
8285 enc,
8286 cdfs,
8287 grid,
8288 (mi_row, mi_col),
8289 (SUB_MI as usize, SUB_MI as usize),
8290 (SUB, SUB),
8291 (mi_cols as usize, mi_rows as usize),
8292 info.ref_frame,
8293 block.motion_mode,
8294 )?;
8295 mode_for_tx = 0;
8296 }
8297 } else {
8298 let mode = usize::from(block.mode);
8299 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);
8300 if (V_PRED..=D67_PRED).contains(&mode) {
8301 enc.symbol(
8302 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8303 &mut cdfs.angle_delta[mode - V_PRED],
8304 );
8305 }
8306 let uv_mode = usize::from(block.uv_mode);
8307 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8308 if uv_mode == UV_CFL_PRED {
8309 write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
8310 }
8311 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8312 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8313 }
8314 mode_for_tx = tx_row(mode, block.filter_intra);
8315 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
8316 // coverage must see it (module doc).
8317 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
8318 write_palette_syntax(
8319 enc,
8320 cdfs,
8321 neighbours,
8322 block.palette.as_ref(),
8323 block.palette_uv.as_ref(),
8324 block.filter_intra,
8325 mode,
8326 uv_mode,
8327 (mi_row, mi_col),
8328 SUB,
8329 );
8330 for dr in 0..SUB_MI as usize {
8331 for dc in 0..SUB_MI as usize {
8332 grid.set(
8333 mi_row + dr,
8334 mi_col + dc,
8335 MiInfo {
8336 is_inter: false,
8337 ref_frame: -1,
8338 ref_frame1: NO_REF1,
8339 mv1: (0, 0),
8340 mv: (0, 0),
8341 is_new_mv: false,
8342 size: SUB_MI as usize as u8,
8343 size_h: SUB_MI as usize as u8,
8344 is_global_mv0: false,
8345 is_global_mv1: false,
8346 },
8347 );
8348 }
8349 }
8350 }
8351
8352 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
8353 let tx = if tx_select {
8354 write_tx_syntax_inter(
8355 enc,
8356 cdfs,
8357 neighbours,
8358 at_mi,
8359 SUB,
8360 is_inter,
8361 block.skip,
8362 usize::from(block.tx_depth),
8363 )
8364 } else {
8365 SUB
8366 };
8367 let split = tx < SUB;
8368 if block.skip {
8369 let zero_grids = [
8370 vec![0i32; TX16 * TX16],
8371 vec![0i32; TX8 * TX8],
8372 vec![0i32; TX8 * TX8],
8373 ];
8374 neighbours.record(at, SUB, mode_for_tx, &zero_grids);
8375 } else {
8376 let grids = [
8377 level_grid(&block.luma, TX16)?,
8378 level_grid(&block.u, TX8)?,
8379 level_grid(&block.v, TX8)?,
8380 ];
8381 if split {
8382 write_luma_tus(
8383 enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, is_inter,
8384 &block.luma_tx_types,
8385 )?;
8386 }
8387 write_block_planes(
8388 enc,
8389 cdfs,
8390 if is_inter {
8391 &[TxbSet::Luma16Inter, TxbSet::Chroma8, TxbSet::Chroma8]
8392 } else {
8393 &[TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8]
8394 },
8395 &grids,
8396 &[scan16, scan8, scan8],
8397 &neighbours.around(at, SUB),
8398 mode_for_tx,
8399 split,
8400 block_tx_type(block),
8401 is_inter,
8402 );
8403 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
8404 }
8405 neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block));
8406 record_block_compound(neighbours, (mi_r, mi_c), SUB, block);
8407 Ok(())
8408}
8409
8410/// Writes one 8x8 leaf of a straddling 16x16 inter-frame block
8411/// (lane-av1inter8): its own skip flag, intra/inter choice and (when inter)
8412/// `NEARESTMV`/`NEWMV` chain, or (when intra) `Y_MODE`, then its own luma and
8413/// two chroma transform blocks -- coded exactly like
8414/// [`write_inter_frame_leaf`] but through [`TxbSet::Luma8Inter`]/
8415/// [`TxbSet::Chroma4`] and at this leaf's own 2x2-mi mv-stack window, reading
8416/// its skip/intra-inter context from the *enclosing* 16x16 slot's
8417/// [`Neighbours`] arrays (`outer_at`, in [`SUB`]-grid units) unless
8418/// `prev_leaf` names this straddling block's own first leaf as the true
8419/// mi-adjacent neighbour -- the same override [`write_leaf8`] applies to its
8420/// mode context, needed for the same reason: `Neighbours`' above/left arrays
8421/// only resolve to [`SUB`] granularity, too coarse for the second leaf of a
8422/// straddling 16x16 to see the first. `Y_MODE`'s own context (`Size_Group`)
8423/// is not neighbour-dependent, unlike the key frame path's `kf_y_mode`, so no
8424/// override is needed there. Hands back this leaf's own skip flag and
8425/// intra/inter choice, which is what the next leaf (or the caller's final
8426/// write-back, mirroring `write_leaf8`'s caller) reads.
8427#[allow(clippy::too_many_arguments)]
8428fn write_inter_frame_leaf8(
8429 enc: &mut SymbolEncoder,
8430 cdfs: &mut Cdfs,
8431 neighbours: &mut Neighbours,
8432 grid: &mut MiGrid,
8433 mi_cols: u32,
8434 mi_rows: u32,
8435 block: &BlockCoeffs,
8436 leaf_mi: (usize, usize),
8437 scan8: &Vec<u16>,
8438 scan4: &Vec<u16>,
8439 tx_select: bool,
8440 all_scans: &[Vec<u16>; 4],
8441) -> Result<(bool, bool)> {
8442 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
8443 return Err(Error::unsupported(
8444 "AV1 tile",
8445 format!(
8446 "intra mode {} is not one of the thirteen this writer codes",
8447 block.mode
8448 ),
8449 ));
8450 }
8451 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
8452 /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size.
8453 const SIZE_GROUP_8: usize = 1;
8454
8455 // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's:
8456 // under a real PARTITION_SPLIT all four leaves are coded, so the
8457 // bottom-left leaf's true above neighbour is the FIRST leaf and the
8458 // bottom-right's above and left are two DIFFERENT ones (lane-av1rd2 --
8459 // reading the coarse slot desynced the stream, and so did an override
8460 // that remembered only the previous leaf).
8461 let above_skip = neighbours.above_skip[leaf_mi.1];
8462 let left_skip = neighbours.left_skip[leaf_mi.0];
8463 let above_inter = neighbours.above_inter[leaf_mi.1];
8464 let left_inter = neighbours.left_inter[leaf_mi.0];
8465 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
8466 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
8467 write_cdef_idx(enc, leaf_mi, block.skip);
8468 write_delta_q(enc, cdfs, leaf_mi, false, block.skip);
8469
8470 let (has_above, has_left) = (neighbours.has_above(leaf_mi.0), neighbours.has_left(leaf_mi.1));
8471 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8472 let is_inter = block.inter.is_some();
8473 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
8474
8475 let mode_for_tx;
8476 if let Some(info) = block.inter {
8477 write_comp_mode(enc, cdfs, neighbours, leaf_mi, (has_above, has_left), info.ref1.is_some());
8478 let (mi_row, mi_col) = leaf_mi;
8479 if info.ref1.is_some() {
8480 let (mv, mv1, is_new_mv) = write_compound_block(
8481 enc, cdfs, neighbours, grid, (mi_row, mi_col), (2, 2),
8482 (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
8483 )?;
8484 for dr in 0..2 {
8485 for dc in 0..2 {
8486 grid.set(mi_row + dr, mi_col + dc, MiInfo {
8487 is_inter: true,
8488 ref_frame: info.ref_frame,
8489 ref_frame1: info.ref1.unwrap_or(NO_REF1),
8490 mv1: mv16(mv1),
8491 mv: mv16(mv),
8492 is_new_mv,
8493 size: 2,
8494 size_h: 2,
8495 is_global_mv0: false,
8496 is_global_mv1: false,
8497 });
8498 }
8499 }
8500 mode_for_tx = 0;
8501 } else {
8502 write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.above_ref1[leaf_mi.1], neighbours.left_ref[leaf_mi.0], neighbours.left_ref1[leaf_mi.0]);
8503
8504 let stack = find_mv_stack(
8505 grid,
8506 mi_row,
8507 mi_col,
8508 2,
8509 2,
8510 info.ref_frame,
8511 mi_cols as usize,
8512 mi_rows as usize,
8513 );
8514
8515 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
8516 for dr in 0..2 {
8517 for dc in 0..2 {
8518 grid.set(
8519 mi_row + dr,
8520 mi_col + dc,
8521 MiInfo {
8522 is_inter: true,
8523 ref_frame: info.ref_frame,
8524 ref_frame1: NO_REF1,
8525 mv1: (0, 0),
8526 mv: mv16(mv),
8527 is_new_mv,
8528 size: 2,
8529 size_h: 2,
8530 is_global_mv0: false,
8531 is_global_mv1: false,
8532 },
8533 );
8534 }
8535 }
8536 write_motion_mode(
8537 enc,
8538 cdfs,
8539 grid,
8540 (mi_row, mi_col),
8541 (2, 2),
8542 (8, 8),
8543 (mi_cols as usize, mi_rows as usize),
8544 info.ref_frame,
8545 block.motion_mode,
8546 )?;
8547 mode_for_tx = 0;
8548 }
8549 } else {
8550 let mode = usize::from(block.mode);
8551 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);
8552 if (V_PRED..=D67_PRED).contains(&mode) {
8553 enc.symbol(
8554 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
8555 &mut cdfs.angle_delta[mode - V_PRED],
8556 );
8557 }
8558 let uv_mode = usize::from(block.uv_mode);
8559 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
8560 if uv_mode == UV_CFL_PRED {
8561 write_cfl_alphas(enc, cdfs, block.cfl_alphas.expect("cfl"));
8562 }
8563 if (V_PRED..=D67_PRED).contains(&uv_mode) {
8564 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
8565 }
8566 mode_for_tx = tx_row(mode, block.filter_intra);
8567 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
8568 // coverage must see it (module doc).
8569 let (mi_row, mi_col) = leaf_mi;
8570 write_palette_syntax(
8571 enc,
8572 cdfs,
8573 neighbours,
8574 block.palette.as_ref(),
8575 block.palette_uv.as_ref(),
8576 block.filter_intra,
8577 mode,
8578 uv_mode,
8579 leaf_mi,
8580 8,
8581 );
8582 for dr in 0..2 {
8583 for dc in 0..2 {
8584 grid.set(
8585 mi_row + dr,
8586 mi_col + dc,
8587 MiInfo {
8588 is_inter: false,
8589 ref_frame: -1,
8590 ref_frame1: NO_REF1,
8591 mv1: (0, 0),
8592 mv: (0, 0),
8593 is_new_mv: false,
8594 size: 2,
8595 size_h: 2,
8596 is_global_mv0: false,
8597 is_global_mv1: false,
8598 },
8599 );
8600 }
8601 }
8602 }
8603
8604 let planes = if is_inter {
8605 [TxbSet::Luma8Inter, TxbSet::Chroma4, TxbSet::Chroma4]
8606 } else {
8607 [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]
8608 };
8609 let tx = if tx_select {
8610 write_tx_syntax_inter(
8611 enc,
8612 cdfs,
8613 neighbours,
8614 leaf_mi,
8615 8,
8616 is_inter,
8617 block.skip,
8618 usize::from(block.tx_depth),
8619 )
8620 } else {
8621 8
8622 };
8623 let split = tx < 8;
8624 if block.skip {
8625 let zero_grids = [
8626 vec![0i32; TX8 * TX8],
8627 vec![0i32; TX4 * TX4],
8628 vec![0i32; TX4 * TX4],
8629 ];
8630 neighbours.record_mi(leaf_mi, 8, &zero_grids);
8631 neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block));
8632 record_block_compound(neighbours, leaf_mi, 8, block);
8633 } else {
8634 let grids = [
8635 level_grid(&block.luma, TX8)?,
8636 level_grid(&block.u, TX4)?,
8637 level_grid(&block.v, TX4)?,
8638 ];
8639 if split {
8640 write_luma_tus(
8641 enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, is_inter,
8642 &block.luma_tx_types,
8643 )?;
8644 }
8645 write_block_planes(
8646 enc,
8647 cdfs,
8648 &planes,
8649 &grids,
8650 &[scan8, scan4, scan4],
8651 &neighbours.around_mi(leaf_mi, 8),
8652 mode_for_tx,
8653 split,
8654 block_tx_type(block),
8655 is_inter,
8656 );
8657 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
8658 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));
8659 record_block_compound(neighbours, leaf_mi, 8, block);
8660 }
8661 Ok((block.skip, is_inter))
8662}
8663
8664#[cfg(test)]
8665mod tests {
8666 use super::*;
8667 use crate::frame::frame_obu;
8668 use crate::obu::temporal_delimiter;
8669 use crate::sequence::sequence_header_obu;
8670 use ec_av1_syntax::sequence::SequenceHeader;
8671 use ec_av1_syntax::{
8672 FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
8673 TxMode,
8674 };
8675 use std::io::Write;
8676 use std::process::{Command, Stdio};
8677
8678 /// A 64x64 sequence with every tool this writer does not code turned off:
8679 /// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter
8680 /// intra, and no screen content tools (which is what keeps intra block copy
8681 /// and palette out of the block syntax).
8682 fn sequence_64() -> SequenceHeader {
8683 let mut seq = crate::sequence::tests::sample_1080p();
8684 seq.frame_width_bits = 7;
8685 seq.frame_height_bits = 7;
8686 seq.max_frame_width = 64;
8687 seq.max_frame_height = 64;
8688 seq.use_128x128_superblock = false;
8689 seq.enable_filter_intra = false;
8690 seq.enable_cdef = false;
8691 seq.enable_restoration = false;
8692 seq.enable_superres = false;
8693 seq.seq_force_screen_content_tools = 0;
8694 seq.seq_force_integer_mv = 0;
8695 seq
8696 }
8697
8698 /// The key frame the tile above belongs to: one tile, quantised so nothing
8699 /// is lossless, one transform size per block, no in-loop filtering, and no
8700 /// CDF adaptation (the writer codes against the defaults).
8701 fn flat_key_frame() -> FrameHeader {
8702 FrameHeader {
8703 frame_type: FrameType::Key,
8704 frame_is_intra: true,
8705 show_frame: true,
8706 error_resilient_mode: true,
8707 disable_cdf_update: true,
8708 allow_screen_content_tools: false,
8709 force_integer_mv: true,
8710 refresh_frame_flags: 0xFF,
8711 primary_ref_frame: PRIMARY_REF_NONE,
8712 frame_width: 64,
8713 frame_height: 64,
8714 upscaled_width: 64,
8715 render_width: 64,
8716 render_height: 64,
8717 mi_cols: 16,
8718 mi_rows: 16,
8719 tile_info: TileInfo {
8720 uniform_spacing: true,
8721 cols: 1,
8722 rows: 1,
8723 cols_log2: 0,
8724 rows_log2: 0,
8725 mi_col_starts: vec![0, 16],
8726 mi_row_starts: vec![0, 16],
8727 context_update_tile_id: 0,
8728 tile_size_bytes: 1,
8729 },
8730 quantization: QuantizationParams {
8731 base_q_idx: 100,
8732 ..QuantizationParams::default()
8733 },
8734 loop_filter: LoopFilterParams::default(),
8735 tx_mode: TxMode::Largest,
8736 reduced_tx_set: false,
8737 ..FrameHeader::default()
8738 }
8739 }
8740
8741 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
8742 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
8743 /// aomenc gate decodes its stream through ffmpeg and is meaningless
8744 /// without it -- turns it into a hard failure. Without this the require
8745 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
8746 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
8747 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
8748 fn have_ffmpeg() -> bool {
8749 let present = Command::new("ffmpeg")
8750 .arg("-version")
8751 .stdout(Stdio::null())
8752 .stderr(Stdio::null())
8753 .status()
8754 .is_ok_and(|s| s.success());
8755 assert!(
8756 present
8757 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
8758 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
8759 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
8760 );
8761 present
8762 }
8763
8764 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
8765 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
8766 let mut child = Command::new("ffmpeg")
8767 .args([
8768 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
8769 ])
8770 .stdin(Stdio::piped())
8771 .stdout(Stdio::piped())
8772 .stderr(Stdio::piped())
8773 .spawn()
8774 .expect("ffmpeg failed to start");
8775 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
8776 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
8777 // fills before the last input byte is written -- which is exactly what
8778 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
8779 // (measured: 45 min, both processes at 0% CPU). A write error here is
8780 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
8781 // below, are the real diagnosis.
8782 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
8783 let payload = stream.to_vec();
8784 let writer = std::thread::spawn(move || {
8785 let _ = stdin.write_all(&payload);
8786 });
8787 let out = child.wait_with_output().expect("ffmpeg failed to run");
8788 writer.join().expect("ffmpeg stdin writer thread");
8789 assert!(
8790 out.status.success(),
8791 "ffmpeg refused the stream: {}",
8792 String::from_utf8_lossy(&out.stderr)
8793 );
8794 assert_eq!(
8795 out.stdout.len(),
8796 w * h * 3 / 2,
8797 "expected one 4:2:0 frame, ffmpeg said: {}",
8798 String::from_utf8_lossy(&out.stderr)
8799 );
8800 out.stdout
8801 }
8802
8803 #[test]
8804 fn flat_key_frame_decodes_to_mid_grey() {
8805 if !have_ffmpeg() {
8806 eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH");
8807 return;
8808 }
8809 let seq = sequence_64();
8810 let header = flat_key_frame();
8811 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();
8812
8813 let mut stream = temporal_delimiter();
8814 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
8815 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
8816
8817 let planes = ffmpeg_decode(&stream, 64, 64);
8818 // A DC prediction with no neighbour to average is the middle of the
8819 // range, and a skipped block adds no residual, so every sample of every
8820 // plane is 128 — one wrong symbol anywhere in the tile shows up here.
8821 for (i, &s) in planes.iter().enumerate() {
8822 assert_eq!(s, 128, "sample {i} of the decoded frame");
8823 }
8824 }
8825
8826 /// The one q-context whose CDFs this crate carries; the decoded table
8827 /// below is pinned at this quantiser and nowhere else.
8828 const Q_IDX: u8 = 100;
8829
8830 /// Encode a 64x64 key frame carrying `dc_level` and hand back its planes.
8831 fn decode_dc_frame(dc_level: i32) -> Vec<u8> {
8832 let seq = sequence_64();
8833 let mut header = flat_key_frame();
8834 header.quantization.base_q_idx = Q_IDX;
8835 let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap();
8836 let mut stream = temporal_delimiter();
8837 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
8838 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
8839 ffmpeg_decode(&stream, 64, 64)
8840 }
8841
8842 /// What a reference decoder makes of each DC level at `base_q_idx` 100:
8843 /// the level times the DC quantiser, inverse-transformed over a whole
8844 /// 64x64 block — which spreads one coefficient over 4096 samples, so a
8845 /// level moves the picture by a sample or two, not by tens. These numbers
8846 /// are pinned from the decoder rather than derived: this crate has no
8847 /// inverse transform of its own yet to derive them with. What the test
8848 /// asserts around them — flat planes, untouched chroma, monotone in the
8849 /// level, and the sign going the right way — is derived, and it is what a
8850 /// desync in the coefficient syntax breaks first.
8851 const DECODED_AT_Q100: [(i32, u8); 28] = [
8852 (1, 128),
8853 (2, 128),
8854 (3, 129),
8855 (4, 129),
8856 (5, 129),
8857 (6, 129),
8858 (7, 129),
8859 (8, 129),
8860 (9, 130),
8861 (10, 130),
8862 (11, 130),
8863 (12, 130),
8864 (13, 130),
8865 (14, 131),
8866 (-1, 128),
8867 (-2, 128),
8868 (-3, 128),
8869 (-4, 127),
8870 (-5, 127),
8871 (-6, 127),
8872 (-7, 127),
8873 (-8, 127),
8874 (-9, 126),
8875 (-10, 126),
8876 (-11, 126),
8877 (-12, 126),
8878 (-13, 126),
8879 (-14, 126),
8880 ];
8881
8882 #[test]
8883 fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
8884 if !have_ffmpeg() {
8885 eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
8886 return;
8887 }
8888 let mut seen = Vec::new();
8889 for (level, want) in DECODED_AT_Q100 {
8890 let planes = decode_dc_frame(level);
8891 let (luma, chroma) = planes.split_at(64 * 64);
8892 for (i, &sample) in luma.iter().enumerate() {
8893 assert_eq!(sample, want, "luma sample {i} at dc level {level}");
8894 }
8895 // The chroma transform blocks are all-zero, so both planes stay at
8896 // the prediction. A desync in the luma coefficient syntax lands
8897 // here first: the chroma flags are the next symbols after it.
8898 for (i, &sample) in chroma.iter().enumerate() {
8899 assert_eq!(sample, 128, "chroma sample {i} at dc level {level}");
8900 }
8901 seen.push((level, want));
8902 }
8903 // The picture moves off mid-grey the way the level says: up for a
8904 // positive level, down for a negative one, and never back towards it
8905 // as the level grows.
8906 for w in seen.windows(2) {
8907 let ((prev_level, prev), (level, value)) = (w[0], w[1]);
8908 if prev_level.signum() != level.signum() {
8909 continue;
8910 }
8911 if level > 0 {
8912 assert!(
8913 value >= prev,
8914 "level {level} decoded below level {prev_level}"
8915 );
8916 assert!(value >= 128, "a positive level darkened the picture");
8917 } else {
8918 assert!(
8919 value <= prev,
8920 "level {level} decoded above level {prev_level}"
8921 );
8922 assert!(value <= 128, "a negative level brightened the picture");
8923 }
8924 }
8925 assert!(
8926 DECODED_AT_Q100.iter().any(|&(_, v)| v > 128)
8927 && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128),
8928 "the pinned table has to move the picture both ways"
8929 );
8930 }
8931
8932 /// Encode a grid of 64x64 superblocks, each carrying its own DC level, and
8933 /// hand back the decoded planes.
8934 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
8935 let (w, h) = (64 * sb_cols, 64 * sb_rows);
8936 let (seq, mut header) = frame_of(w, h);
8937 // The DC fixture writers code against the default CDFs and never
8938 // update them, so their frames say so.
8939 header.disable_cdf_update = true;
8940 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
8941 let mut stream = temporal_delimiter();
8942 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
8943 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
8944 ffmpeg_decode(&stream, w as usize, h as usize)
8945 }
8946
8947 /// A sequence and key frame header for a `w` by `h` frame of whole
8948 /// superblocks.
8949 fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) {
8950 let mut seq = sequence_64();
8951 seq.max_frame_width = w;
8952 seq.max_frame_height = h;
8953 let mut header = flat_key_frame();
8954 // Every tile these headers carry is written by the adapting writer.
8955 header.disable_cdf_update = false;
8956 header.frame_width = w;
8957 header.frame_height = h;
8958 header.upscaled_width = w;
8959 header.render_width = w;
8960 header.render_height = h;
8961 header.mi_cols = w / 4;
8962 header.mi_rows = h / 4;
8963 header.tile_info.mi_col_starts = vec![0, header.mi_cols];
8964 header.tile_info.mi_row_starts = vec![0, header.mi_rows];
8965 header.quantization.base_q_idx = Q_IDX;
8966 (seq, header)
8967 }
8968
8969 fn decoded_value(level: i32) -> u8 {
8970 DECODED_AT_Q100
8971 .iter()
8972 .find(|&&(l, _)| l == level)
8973 .map(|&(_, v)| v)
8974 .expect("the level is in the pinned table")
8975 }
8976
8977 /// `dc_predict` (spec 7.11.2) for the flat case: a block whose neighbours
8978 /// are themselves flat predicts their average, and predicts mid-grey with
8979 /// no neighbour at all. Every block here is a whole 64x64 superblock, so
8980 /// the above row and the left column weigh the same.
8981 fn dc_prediction(above: Option<u8>, left: Option<u8>) -> u8 {
8982 match (above, left) {
8983 (None, None) => 128,
8984 (Some(a), None) => a,
8985 (None, Some(l)) => l,
8986 (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8,
8987 }
8988 }
8989
8990 /// What a DC level adds to the prediction: the pinned table is that sum
8991 /// against a mid-grey prediction, and the residual does not depend on what
8992 /// it is added to.
8993 fn dc_residual(level: i32) -> i32 {
8994 i32::from(decoded_value(level)) - 128
8995 }
8996
8997 /// Every block reads its DC sign context off the coded blocks above and to
8998 /// its left, and the three ways that can land — no coded neighbour, the
8999 /// neighbours leaning one way, the neighbours cancelling — are only
9000 /// reachable in a frame whose levels differ in sign. Getting the context
9001 /// wrong desyncs the arithmetic decoder, so the check is that every block
9002 /// still decodes to the grey its own level asks for.
9003 #[test]
9004 fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {
9005 if !have_ffmpeg() {
9006 eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg");
9007 return;
9008 }
9009 // Read in raster order the two grids put a positive, a negative and a
9010 // cancelling sign context in front of the bottom-right block, and a
9011 // leaning-down one in front of the second grid's right and bottom
9012 // blocks.
9013 for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] {
9014 let planes = decode_level_grid(&levels, 2, 2);
9015 let (luma, chroma) = planes.split_at(128 * 128);
9016 // The blocks are not independent: a DC prediction reads the
9017 // reconstructed neighbours, so each block's grey is its
9018 // neighbours' average plus its own residual.
9019 let mut recon = [0u8; 4];
9020 for (block, level) in levels.iter().enumerate() {
9021 let (br, bc) = (block / 2, block % 2);
9022 let above = (br > 0).then(|| recon[block - 2]);
9023 let left = (bc > 0).then(|| recon[block - 1]);
9024 let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level))
9025 .clamp(0, 255) as u8;
9026 recon[block] = want;
9027 for y in 0..64 {
9028 for x in 0..64 {
9029 let i = (br * 64 + y) * 128 + bc * 64 + x;
9030 assert_eq!(
9031 luma[i], want,
9032 "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}"
9033 );
9034 }
9035 }
9036 }
9037 for (i, &sample) in chroma.iter().enumerate() {
9038 assert_eq!(sample, 128, "chroma sample {i} of {levels:?}");
9039 }
9040 }
9041 }
9042
9043 /// What a DC level adds to a 32x32 block's prediction at `base_q_idx` 100,
9044 /// pinned from the decoder the way [`DECODED_AT_Q100`] is. A 32x32
9045 /// transform spreads its DC over a quarter of the samples a 64x64 one
9046 /// does, so the same level moves the picture further: level 14 is five
9047 /// sample values here against three there.
9048 const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [
9049 (1, 0),
9050 (2, 1),
9051 (3, 1),
9052 (4, 1),
9053 (5, 2),
9054 (6, 2),
9055 (7, 3),
9056 (8, 3),
9057 (9, 3),
9058 (10, 4),
9059 (11, 4),
9060 (12, 4),
9061 (13, 5),
9062 (14, 5),
9063 (-1, 0),
9064 (-2, -1),
9065 (-3, -1),
9066 (-4, -1),
9067 (-5, -2),
9068 (-6, -2),
9069 (-7, -2),
9070 (-8, -3),
9071 (-9, -3),
9072 (-10, -4),
9073 (-11, -4),
9074 (-12, -4),
9075 (-13, -5),
9076 (-14, -5),
9077 ];
9078
9079 fn split_residual(level: i32) -> i32 {
9080 SPLIT_RESIDUAL_AT_Q100
9081 .iter()
9082 .find(|&&(l, _)| l == level)
9083 .map(|&(_, r)| r)
9084 .expect("the level is in the pinned table")
9085 }
9086
9087 /// Splitting a superblock puts three more syntax elements in front of every
9088 /// block — the split partition itself, the 32x32 partition below it and a
9089 /// chroma mode from the wider table CFL-capable blocks read — and moves the
9090 /// coefficients onto the 32x32 CDFs. Getting any of them wrong desyncs the
9091 /// arithmetic decoder, and the check is that all sixteen blocks still land
9092 /// on the grey their own level and their neighbours ask for.
9093 #[test]
9094 fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
9095 if !have_ffmpeg() {
9096 eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
9097 return;
9098 }
9099 // Four by four 32x32 blocks over two by two superblocks, so the walk
9100 // crosses superblock boundaries in both directions, and signs that
9101 // alternate so the DC sign context lands on all three of its values.
9102 let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1];
9103 let planes = decode_split_grid(&levels, 2, 2);
9104 let (luma, chroma) = planes.split_at(128 * 128);
9105
9106 let mut recon = [0i32; 16];
9107 for (block, level) in levels.iter().enumerate() {
9108 let (br, bc) = (block / 4, block % 4);
9109 let above = (br > 0).then(|| recon[block - 4] as u8);
9110 let left = (bc > 0).then(|| recon[block - 1] as u8);
9111 let want =
9112 (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255);
9113 recon[block] = want;
9114 for y in 0..32 {
9115 for x in 0..32 {
9116 let i = (br * 32 + y) * 128 + bc * 32 + x;
9117 assert_eq!(
9118 i32::from(luma[i]),
9119 want,
9120 "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \
9121 column {bc}"
9122 );
9123 }
9124 }
9125 }
9126 for (i, &sample) in chroma.iter().enumerate() {
9127 assert_eq!(sample, 128, "chroma sample {i}");
9128 }
9129 }
9130
9131 /// Encode a grid of 32x32 blocks, each carrying its own DC level.
9132 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
9133 let (w, h) = (64 * sb_cols, 64 * sb_rows);
9134 let (seq, mut header) = frame_of(w, h);
9135 // The DC fixture writers code against the default CDFs and never
9136 // update them, so their frames say so.
9137 header.disable_cdf_update = true;
9138 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
9139 let mut stream = temporal_delimiter();
9140 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9141 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9142 ffmpeg_decode(&stream, w as usize, h as usize)
9143 }
9144
9145 #[test]
9146 fn a_level_grid_that_does_not_cover_the_frame_is_refused() {
9147 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err());
9148 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err());
9149 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());
9150 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());
9151 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());
9152 }
9153
9154 #[test]
9155 fn dc_levels_the_base_syntax_cannot_carry_are_refused() {
9156 assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());
9157 assert!(dc_key_frame_tile(16, 16, 100, 15).is_err());
9158 assert!(dc_key_frame_tile(16, 16, 100, -15).is_err());
9159 }
9160
9161 #[test]
9162 fn partial_superblocks_are_refused() {
9163 assert!(flat_key_frame_tile(16, 20).is_err());
9164 assert!(flat_key_frame_tile(0, 16).is_err());
9165 }
9166
9167 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
9168 /// hands back the luma plane as rows of samples.
9169 fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {
9170 let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect();
9171 let [luma, u, v] = decode_coeff_planes(&blocks);
9172 for (name, plane) in [("U", &u), ("V", &v)] {
9173 for (y, row) in plane.iter().enumerate() {
9174 for (x, &s) in row.iter().enumerate() {
9175 assert_eq!(
9176 s, 128,
9177 "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \
9178 DC prediction with no coded neighbour is mid-grey"
9179 );
9180 }
9181 }
9182 }
9183 luma
9184 }
9185
9186 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
9187 /// hands back its three planes as rows of samples: 64 rows of luma and, at
9188 /// 4:2:0, 32 rows of each chroma plane.
9189 fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] {
9190 let (seq, header) = frame_of(64, 64);
9191 let tile =
9192 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
9193 let mut stream = temporal_delimiter();
9194 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9195 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9196 let planes = ffmpeg_decode(&stream, 64, 64);
9197 let (luma, chroma) = planes.split_at(64 * 64);
9198 let (u, v) = chroma.split_at(32 * 32);
9199 [
9200 luma.chunks_exact(64).map(<[u8]>::to_vec).collect(),
9201 u.chunks_exact(32).map(<[u8]>::to_vec).collect(),
9202 v.chunks_exact(32).map(<[u8]>::to_vec).collect(),
9203 ]
9204 }
9205
9206 /// The top-left 32x32 block of a decoded frame, which is the only one whose
9207 /// prediction has no neighbour to lean on.
9208 fn top_left_block(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
9209 rows[..32].iter().map(|r| r[..32].to_vec()).collect()
9210 }
9211
9212 /// A transform's basis functions all average to zero except the DC's, so a
9213 /// block carrying no DC decodes to samples that average to its prediction —
9214 /// mid-grey for the block with no neighbours. Rounding of the inverse
9215 /// transform moves the average by less than a sample.
9216 fn assert_mean_is_mid_grey(block: &[Vec<u8>]) {
9217 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
9218 let mean = f64::from(sum) / (32.0 * 32.0);
9219 assert!(
9220 (mean - 128.0).abs() <= 1.0,
9221 "a block with no DC coefficient averages to its mid-grey prediction, got {mean}"
9222 );
9223 }
9224
9225 /// A coefficient at row 0, column 1 selects the basis function that is flat
9226 /// down the block and a half-cycle of a cosine across it. Nothing about
9227 /// that shape is pinned here: every row of the block must be the same row,
9228 /// the samples must fall from left to right and actually move, and the
9229 /// block must still average to its prediction. A desync in the scan, the
9230 /// end-of-block position or the level contexts breaks one of those.
9231 #[test]
9232 fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
9233 if !have_ffmpeg() {
9234 eprintln!(
9235 "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg"
9236 );
9237 return;
9238 }
9239 let blocks = vec![
9240 vec![Coeff {
9241 row: 0,
9242 col: 1,
9243 level: 12,
9244 }],
9245 Vec::new(),
9246 Vec::new(),
9247 Vec::new(),
9248 ];
9249 let rows = decode_coeff_quadrants(&blocks);
9250 let block = top_left_block(&rows);
9251
9252 for (y, row) in block.iter().enumerate() {
9253 assert_eq!(row, &block[0], "row {y} of a horizontal basis function");
9254 }
9255 assert!(
9256 block[0][0] > block[0][31],
9257 "a positive coefficient leans the block towards its left edge: {:?}",
9258 block[0]
9259 );
9260 for x in 1..32 {
9261 assert!(
9262 block[0][x] <= block[0][x - 1],
9263 "the half-cycle falls from left to right, broke at column {x}: {:?}",
9264 block[0]
9265 );
9266 }
9267 assert_mean_is_mid_grey(&block);
9268
9269 // The same coefficient transposed selects the basis function that is
9270 // flat across the block and a half-cycle down it.
9271 let blocks = vec![
9272 vec![Coeff {
9273 row: 1,
9274 col: 0,
9275 level: 12,
9276 }],
9277 Vec::new(),
9278 Vec::new(),
9279 Vec::new(),
9280 ];
9281 let rows = decode_coeff_quadrants(&blocks);
9282 let block = top_left_block(&rows);
9283 for (y, row) in block.iter().enumerate() {
9284 for (x, &s) in row.iter().enumerate() {
9285 assert_eq!(s, row[0], "sample ({y},{x}) of a vertical basis function");
9286 }
9287 }
9288 assert!(
9289 block[0][0] > block[31][0],
9290 "a positive coefficient leans the block up"
9291 );
9292 for y in 1..32 {
9293 assert!(
9294 block[y][0] <= block[y - 1][0],
9295 "the half-cycle falls from top to bottom, broke at row {y}"
9296 );
9297 }
9298 assert_mean_is_mid_grey(&block);
9299 }
9300
9301 /// A coefficient late in the scan pushes the end-of-block position into a
9302 /// group that carries an offset — the far corner of a 32x32 transform is
9303 /// the last of the eleven groups, whose offset is nine bits wide, one of
9304 /// them from a CDF and the rest raw. Every coefficient before it is coded
9305 /// too, so this also walks the base and base-range contexts over a block
9306 /// with neighbours that carry levels rather than zeros.
9307 #[test]
9308 fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {
9309 if !have_ffmpeg() {
9310 eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group");
9311 return;
9312 }
9313 let block = vec![
9314 Coeff {
9315 row: 31,
9316 col: 31,
9317 level: 5,
9318 },
9319 Coeff {
9320 row: 5,
9321 col: 7,
9322 level: -9,
9323 },
9324 Coeff {
9325 row: 1,
9326 col: 1,
9327 level: 14,
9328 },
9329 Coeff {
9330 row: 0,
9331 col: 2,
9332 level: -3,
9333 },
9334 Coeff {
9335 row: 2,
9336 col: 0,
9337 level: 2,
9338 },
9339 Coeff {
9340 row: 1,
9341 col: 2,
9342 level: -1,
9343 },
9344 ];
9345 let rows = decode_coeff_quadrants(&[block, Vec::new(), Vec::new(), Vec::new()]);
9346 let block = top_left_block(&rows);
9347 assert_mean_is_mid_grey(&block);
9348 assert!(
9349 block.iter().flatten().any(|&s| s != block[0][0]),
9350 "six coefficients do not decode to a flat block"
9351 );
9352 // The blocks that carry nothing are flat: their prediction is whatever
9353 // their neighbours left, and they add no residual to it.
9354 for (name, ys, xs) in [("top right", 0..32, 32..64), ("bottom left", 32..64, 0..32)] {
9355 let first = rows[ys.start][xs.start];
9356 for y in ys {
9357 for x in xs.clone() {
9358 assert_eq!(rows[y][x], first, "the {name} block carries no coefficient");
9359 }
9360 }
9361 }
9362 }
9363
9364 /// The price the mode search pays for a block's levels has to be the price
9365 /// the writer charges for them, or the search is ranking modes by a
9366 /// fiction. Both halves are asked for the same grids under the same
9367 /// neutral contexts, and the priced bits are compared against the bytes
9368 /// the writer really spends.
9369 #[test]
9370 fn the_priced_coefficient_bits_match_the_bytes_written() {
9371 let scan = default_scan(TX32);
9372 // Three grids that reach different parts of the syntax: a lone DC, a
9373 // sparse spread of small levels with both signs, and levels past the
9374 // base-range alphabet so the Golomb tail runs.
9375 let mut grids = vec![vec![0i32; TX32 * TX32]; 3];
9376 grids[0][0] = -7;
9377 for (i, &pos) in scan.iter().enumerate().take(400) {
9378 if i % 7 == 0 {
9379 grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 };
9380 }
9381 }
9382 grids[2][0] = 40;
9383 for (i, &pos) in scan.iter().enumerate().take(64) {
9384 grids[2][pos as usize] += i as i32 % 23 - 11;
9385 }
9386
9387 // A single block is too short for the coder's own flush to average
9388 // out, so all three go through one encoder and one flush.
9389 let mut enc = SymbolEncoder::new();
9390 let mut priced = 0.0;
9391 for grid in &grids {
9392 write_coeffs(
9393 &mut enc,
9394 &mut Cdfs::new(2).txb(TxbSet::Luma32, 0),
9395 grid,
9396 &scan,
9397 0,
9398 0,
9399 None,
9400 TxType::DctDct,
9401 );
9402 priced += luma_32_coeff_bits(grid);
9403 }
9404 let spent = enc.finish().len() as f64 * 8.0;
9405 assert!(
9406 (priced - spent).abs() / spent < 0.02,
9407 "priced {priced} bits, wrote {spent}"
9408 );
9409 }
9410
9411 /// A rate term the search can read as constant is a rate term that ranks
9412 /// nothing, so the price is checked to move the way the levels move: an
9413 /// empty block is the cheapest thing there is, one coefficient costs more
9414 /// than none, and both spreading the coefficients and growing them costs
9415 /// more again.
9416 #[test]
9417 fn the_price_grows_with_the_levels() {
9418 let grid = |f: &dyn Fn(&mut Vec<i32>)| {
9419 let mut g = vec![0i32; TX32 * TX32];
9420 f(&mut g);
9421 luma_32_coeff_bits(&g)
9422 };
9423 let empty = grid(&|_| {});
9424 let one = grid(&|g| g[0] = 1);
9425 let bigger = grid(&|g| g[0] = 30);
9426 let spread = grid(&|g| {
9427 for i in 0..TX32 {
9428 g[i * TX32 + i] = 1;
9429 }
9430 });
9431 assert!(empty < one, "{empty} {one}");
9432 assert!(one < bigger, "{one} {bigger}");
9433 assert!(one < spread, "{one} {spread}");
9434 // An empty block is one symbol -- an expensive one, because a block
9435 // with no coefficients at all is the rarer of the two under the
9436 // neutral context -- and nothing else.
9437 assert!(
9438 empty < 6.0,
9439 "an empty block is one skip symbol, not {empty}"
9440 );
9441 }
9442
9443 /// Neighbouring blocks that each carry coefficients read their DC sign
9444 /// context, their prediction and their own contexts off each other, so a
9445 /// frame whose four blocks all carry mixed-sign coefficients exercises what
9446 /// a single coded block cannot. The check is that it decodes at all — a
9447 /// desync anywhere fails the decode or the frame size — and that the block
9448 /// with no neighbours still averages to mid-grey.
9449 #[test]
9450 fn every_quadrant_carries_its_own_coefficients() {
9451 if !have_ffmpeg() {
9452 eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg");
9453 return;
9454 }
9455 let blocks = vec![
9456 vec![
9457 Coeff {
9458 row: 0,
9459 col: 1,
9460 level: 7,
9461 },
9462 Coeff {
9463 row: 3,
9464 col: 4,
9465 level: -14,
9466 },
9467 ],
9468 vec![
9469 Coeff {
9470 row: 0,
9471 col: 0,
9472 level: -6,
9473 },
9474 Coeff {
9475 row: 2,
9476 col: 2,
9477 level: 9,
9478 },
9479 ],
9480 vec![
9481 Coeff {
9482 row: 0,
9483 col: 0,
9484 level: 6,
9485 },
9486 Coeff {
9487 row: 1,
9488 col: 0,
9489 level: -2,
9490 },
9491 Coeff {
9492 row: 8,
9493 col: 9,
9494 level: 3,
9495 },
9496 ],
9497 vec![
9498 Coeff {
9499 row: 0,
9500 col: 0,
9501 level: 11,
9502 },
9503 Coeff {
9504 row: 16,
9505 col: 1,
9506 level: -4,
9507 },
9508 ],
9509 ];
9510 let rows = decode_coeff_quadrants(&blocks);
9511 assert_mean_is_mid_grey(&top_left_block(&rows));
9512 for (name, ys, xs) in [
9513 ("top right", 0..32, 32..64),
9514 ("bottom left", 32..64, 0..32),
9515 ("bottom right", 32..64, 32..64),
9516 ] {
9517 let block: Vec<Vec<u8>> = rows[ys].iter().map(|r| r[xs.clone()].to_vec()).collect();
9518 assert!(
9519 block.iter().flatten().any(|&s| s != block[0][0]),
9520 "the {name} block carries coefficients, so it is not flat"
9521 );
9522 }
9523 }
9524
9525 /// The top-left 16x16 block of a decoded chroma plane, which is the only
9526 /// one whose prediction has no neighbour to lean on.
9527 fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
9528 rows[..16].iter().map(|r| r[..16].to_vec()).collect()
9529 }
9530
9531 /// The mean of a decoded block, which every basis function but the DC's
9532 /// leaves at the block's prediction.
9533 fn mean(block: &[Vec<u8>]) -> f64 {
9534 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
9535 let count = block.iter().map(Vec::len).sum::<usize>() as f64;
9536 f64::from(sum) / count
9537 }
9538
9539 /// A chroma plane's coefficients ride their own transform, their own CDFs
9540 /// and their own end-of-block alphabet, so a chroma basis function is the
9541 /// gate on all three: U carries the coefficient that is flat down the block
9542 /// and a half-cycle across it, V the one turned a quarter turn, and neither
9543 /// may reach the other plane or luma.
9544 #[test]
9545 fn each_chroma_plane_codes_its_own_basis_function() {
9546 if !have_ffmpeg() {
9547 eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
9548 return;
9549 }
9550 let mut blocks = vec![BlockCoeffs::default(); 4];
9551 blocks[0].u = vec![Coeff {
9552 row: 0,
9553 col: 1,
9554 level: 12,
9555 }];
9556 blocks[0].v = vec![Coeff {
9557 row: 1,
9558 col: 0,
9559 level: 12,
9560 }];
9561 let [luma, u, v] = decode_coeff_planes(&blocks);
9562
9563 for (y, row) in luma.iter().enumerate() {
9564 for (x, &s) in row.iter().enumerate() {
9565 assert_eq!(
9566 s, 128,
9567 "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \
9568 stays at its mid-grey prediction"
9569 );
9570 }
9571 }
9572
9573 let u_block = top_left_chroma(&u);
9574 for (y, row) in u_block.iter().enumerate() {
9575 assert_eq!(
9576 row, &u_block[0],
9577 "row {y} of a horizontal chroma basis function"
9578 );
9579 }
9580 assert!(
9581 u_block[0][0] > u_block[0][15],
9582 "a positive coefficient leans the U block towards its left edge: {:?}",
9583 u_block[0]
9584 );
9585
9586 let v_block = top_left_chroma(&v);
9587 for (x, &top) in v_block[0].iter().enumerate() {
9588 assert_eq!(
9589 top, v_block[0][0],
9590 "column {x} of a vertical chroma basis function"
9591 );
9592 let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect();
9593 assert!(
9594 column[0] > column[15],
9595 "a positive coefficient leans the V column towards its top edge: {column:?}"
9596 );
9597 }
9598
9599 for (name, block) in [("U", &u_block), ("V", &v_block)] {
9600 let mean = mean(block);
9601 assert!(
9602 (mean - 128.0).abs() <= 1.0,
9603 "the {name} block carries no DC, so it averages to its mid-grey prediction, \
9604 got {mean}"
9605 );
9606 }
9607 }
9608
9609 /// Every block coding chroma puts the chroma all-zero flag on the contexts
9610 /// a coded neighbour above and to the left select, and the DC sign on the
9611 /// contexts their signs select. A frame whose four blocks all carry chroma
9612 /// DCs of mixed sign walks those contexts; the picture that comes back must
9613 /// still lean the way each block's own DC asks.
9614 #[test]
9615 fn chroma_dc_signs_read_their_neighbours() {
9616 if !have_ffmpeg() {
9617 eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
9618 return;
9619 }
9620 let dc = |level| {
9621 vec![Coeff {
9622 row: 0,
9623 col: 0,
9624 level,
9625 }]
9626 };
9627 let signs = [8, -8, -8, 8];
9628 let blocks: Vec<BlockCoeffs> = signs
9629 .iter()
9630 .map(|&level| BlockCoeffs {
9631 luma: Vec::new(),
9632 u: dc(level),
9633 v: dc(-level),
9634 ..BlockCoeffs::default()
9635 })
9636 .collect();
9637 let [luma, u, v] = decode_coeff_planes(&blocks);
9638
9639 for (y, row) in luma.iter().enumerate() {
9640 for (x, &s) in row.iter().enumerate() {
9641 assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient");
9642 }
9643 }
9644
9645 // A DC prediction leans on the neighbours a block has, so each block is
9646 // measured against the prediction it was given rather than mid-grey:
9647 // the only block with no neighbour is the first, and the rest are read
9648 // as a step away from the block above them and to their left.
9649 for (i, &level) in signs.iter().enumerate() {
9650 let (r, c) = (i / 2, i % 2);
9651 let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> {
9652 plane[r * 16..r * 16 + 16]
9653 .iter()
9654 .map(|row| row[c * 16..c * 16 + 16].to_vec())
9655 .collect()
9656 };
9657 for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] {
9658 let block = block(plane);
9659 let mean = mean(&block);
9660 for (y, row) in block.iter().enumerate() {
9661 assert_eq!(
9662 row.iter().collect::<std::collections::HashSet<_>>().len(),
9663 1,
9664 "row {y} of a DC-only {name} block is flat"
9665 );
9666 }
9667 if i == 0 {
9668 assert!(
9669 (want > 0) == (mean > 128.0),
9670 "{name} block {i} carries a DC of {want}, so it must lean off its \
9671 mid-grey prediction that way, got {mean}"
9672 );
9673 }
9674 }
9675 }
9676 assert_ne!(u, v, "the two chroma planes carry opposite DCs");
9677 }
9678
9679 /// The coefficient writer refuses what it cannot code rather than writing a
9680 /// stream a decoder walks off the end of.
9681 /// The 32x32 block at the given block row and column of a decoded plane.
9682 fn block_at(rows: &[Vec<u8>], block_row: usize, block_col: usize) -> Vec<Vec<u8>> {
9683 rows[block_row * 32..block_row * 32 + 32]
9684 .iter()
9685 .map(|r| r[block_col * 32..block_col * 32 + 32].to_vec())
9686 .collect()
9687 }
9688
9689 /// Encodes a key frame of the given size, whose 32x32 blocks carry
9690 /// `blocks` in raster order, and hands back its luma plane as rows of
9691 /// The neighbour context a block reads is gathered across every cell it
9692 /// spans, not taken from the first one: a 32x32 block whose left-hand
9693 /// neighbour cells disagree still sees the coded one. Reading a single
9694 /// cell agreed with the decoder only while every block was the same size,
9695 /// and desynchronised the arithmetic decoder the moment a 16x16 one
9696 /// appeared beside a 32x32 one.
9697 #[test]
9698 fn a_block_gathers_the_cells_its_neighbours_cover() {
9699 let mut neighbours = Neighbours::new(4, 4, 64, 64);
9700 let quiet = [
9701 vec![0i32; TX16 * TX16],
9702 vec![0; TX8 * TX8],
9703 vec![0; TX8 * TX8],
9704 ];
9705 let mut loud = quiet.clone();
9706 loud[1][0] = -3;
9707 // Two 16x16 blocks above the right-hand 32x32 block of the row, of
9708 // which only the second codes anything.
9709 neighbours.record((0, 2), SUB, DC_PRED, &quiet);
9710 neighbours.record((0, 3), SUB, DC_PRED, &loud);
9711 let around = neighbours.around((2, 2), BLOCK);
9712 assert!(
9713 around[1].above_coded,
9714 "the coded cell has to reach the block below it"
9715 );
9716 assert_eq!(
9717 dc_sign_ctx(around[1].dc_vote),
9718 1,
9719 "the one negative DC above the block is what it votes"
9720 );
9721 // The same read one cell at a time misses it, which is the bug this
9722 // gate is here for. `above[8]` is the first 4x4 unit the quiet block
9723 // at `(0, 2)` wrote (2 SUB units * 4 4x4-units-per-SUB).
9724 assert!(!neighbours.above[8][1].coded);
9725 }
9726
9727 /// samples.
9728 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
9729 let (seq, header) = frame_of(width as u32, height as u32);
9730 let tile =
9731 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
9732 let mut stream = temporal_delimiter();
9733 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9734 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9735 let planes = ffmpeg_decode(&stream, width, height);
9736 planes[..width * height]
9737 .chunks_exact(width)
9738 .map(<[u8]>::to_vec)
9739 .collect()
9740 }
9741
9742 /// Every row of a block is the same row, and that row falls from left to
9743 /// right — the shape of a coefficient at row 0, column 1.
9744 fn assert_falls_across(block: &[Vec<u8>], name: &str) {
9745 for row in block {
9746 assert_eq!(
9747 row, &block[0],
9748 "{name}: every row of the block is the same row"
9749 );
9750 }
9751 assert!(
9752 block[0][0] > block[0][31],
9753 "{name}: the row falls from left to right, got {} then {}",
9754 block[0][0],
9755 block[0][31]
9756 );
9757 }
9758
9759 /// Every column of a block is constant across it and falls down it — the
9760 /// shape of a coefficient at row 1, column 0.
9761 fn assert_falls_down(block: &[Vec<u8>], name: &str) {
9762 for (y, row) in block.iter().enumerate() {
9763 assert!(
9764 row.iter().all(|&s| s == row[0]),
9765 "{name}: row {y} of the block is one constant"
9766 );
9767 }
9768 assert!(
9769 block[0][0] > block[31][0],
9770 "{name}: the column falls down the block, got {} then {}",
9771 block[0][0],
9772 block[31][0]
9773 );
9774 }
9775
9776 /// The mean sample of a decoded block.
9777 fn mean_of(block: &[Vec<u8>]) -> f64 {
9778 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
9779 f64::from(sum) / (block.len() * block[0].len()) as f64
9780 }
9781
9782 /// The top-left block of a frame whose only coefficient is a luma DC of
9783 /// `level`.
9784 fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> {
9785 let blocks = vec![
9786 vec![Coeff {
9787 row: 0,
9788 col: 0,
9789 level,
9790 }],
9791 Vec::new(),
9792 Vec::new(),
9793 Vec::new(),
9794 ];
9795 top_left_block(&decode_coeff_quadrants(&blocks))
9796 }
9797
9798 /// `read_golomb` (spec 5.11.40), written from the specification's
9799 /// pseudocode, and the level its caller builds from it: a level above the
9800 /// base-range tail is fifteen plus what the tail carries.
9801 fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 {
9802 let mut length = 0;
9803 while dec.literal(1) == 0 {
9804 length += 1;
9805 assert!(
9806 length < 20,
9807 "the tail's length prefix runs past twenty bits"
9808 );
9809 }
9810 let mut x = 1;
9811 for _ in 0..length {
9812 x = (x << 1) | dec.literal(1);
9813 }
9814 (MAX_BR_LEVEL + 1) as u32 + (x - 1)
9815 }
9816
9817 /// The tail says how much of the level the base and base-range syntax could
9818 /// not carry, and the spec's own reader must hand back the level that was
9819 /// asked for — not one either side of it. A tail written a bit long, a bit
9820 /// short, or against the wrong base fails this at the first level it
9821 /// reaches.
9822 #[test]
9823 fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
9824 for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300)
9825 .chain([MAX_LEVEL - 1, MAX_LEVEL])
9826 .map(|l| l as u32)
9827 {
9828 let mut enc = SymbolEncoder::new();
9829 write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32);
9830 // The tail is raw bits, so it needs no padding beyond what the
9831 // encoder's own flush writes.
9832 let data = enc.finish();
9833 let mut dec = crate::msac::tests::SymbolDecoder::new(&data);
9834 assert_eq!(
9835 read_golomb_level(&mut dec),
9836 level,
9837 "the tail of level {level}"
9838 );
9839 }
9840 }
9841
9842 /// The base and base-range syntax reach level fourteen between them;
9843 /// anything above that carries the rest of itself as a Golomb tail, written
9844 /// after its own sign. A DC level moves the whole block off its mid-grey
9845 /// prediction by an amount that grows with the level, so a run of levels
9846 /// either side of the tail's threshold — spaced wide enough that the
9847 /// quantiser separates them — must decode to a run of steadily
9848 /// brighter blocks — and the negatives of the same levels to steadily
9849 /// darker ones. A tail written with the wrong length, in the wrong place in
9850 /// the syntax, or off by one desyncs the decoder outright.
9851 #[test]
9852 fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
9853 if !have_ffmpeg() {
9854 eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
9855 return;
9856 }
9857 let mut brighter = Vec::new();
9858 let mut darker = Vec::new();
9859 for level in [10, 14, 18, 31, 60, 400] {
9860 brighter.push((level, mean_of(&decode_dc_level_block(level))));
9861 darker.push((level, mean_of(&decode_dc_level_block(-level))));
9862 }
9863 for pair in brighter.windows(2) {
9864 let [(low, dim), (high, bright)] = [pair[0], pair[1]];
9865 assert!(
9866 bright > dim,
9867 "level {high} decodes brighter than level {low}, got {bright} against {dim}"
9868 );
9869 }
9870 for pair in darker.windows(2) {
9871 let [(low, bright), (high, dim)] = [pair[0], pair[1]];
9872 assert!(
9873 dim < bright,
9874 "level -{high} decodes darker than level -{low}, got {dim} against {bright}"
9875 );
9876 }
9877 let (_, mid) = brighter[0];
9878 assert!(
9879 mid > 128.0 && darker[0].1 < 128.0,
9880 "a positive level brightens its block and a negative one darkens it, got {mid} and {}",
9881 darker[0].1
9882 );
9883 }
9884
9885 /// A frame need not be a whole number of superblocks. A 96x64 frame is a
9886 /// superblock and a half across: the second superblock has no right-hand
9887 /// half, so its partition is a gathered flag rather than the full symbol,
9888 /// and the two blocks that would sit in that half are never coded at all.
9889 /// Each of the six blocks that do exist carries one of two basis functions,
9890 /// alternating, so a block written into the wrong place or a flag the
9891 /// decoder reads as a different number of bits shows up as a block with the
9892 /// other block's shape — or as a decode failure.
9893 fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8>> {
9894 let (seq, header) = frame_of(width as u32, height as u32);
9895 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap();
9896 let mut stream = temporal_delimiter();
9897 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
9898 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
9899 let planes = ffmpeg_decode(&stream, width, height);
9900 planes[..width * height]
9901 .chunks_exact(width)
9902 .map(<[u8]>::to_vec)
9903 .collect()
9904 }
9905
9906 /// A superblock left whole carries one 64x64 transform, whose lowest
9907 /// horizontal basis function falls across the whole sixty-four samples in
9908 /// one stroke. Were the same superblock split, each half would restart the
9909 /// gradient at its own left edge and the picture would rise again in the
9910 /// middle, so the walk across the row is what tells the two apart — and
9911 /// the split superblock beside it proves the two partitions still agree on
9912 /// where the next one begins.
9913 #[test]
9914 fn a_whole_superblock_covers_all_four_of_its_quadrants() {
9915 if !have_ffmpeg() {
9916 eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg");
9917 return;
9918 }
9919 let across = BlockCoeffs::from(vec![Coeff {
9920 row: 0,
9921 col: 1,
9922 level: 20,
9923 }]);
9924 let down = BlockCoeffs::from(vec![Coeff {
9925 row: 1,
9926 col: 0,
9927 level: 20,
9928 }]);
9929 let sbs = [
9930 Superblock::Whole(across),
9931 Superblock::Split(vec![
9932 Quadrant::Whole(down.clone()),
9933 Quadrant::Whole(down.clone()),
9934 Quadrant::Whole(down.clone()),
9935 Quadrant::Whole(down),
9936 ]),
9937 ];
9938 let rows = decode_luma_sb(128, 64, &sbs);
9939
9940 for (y, row) in rows.iter().enumerate() {
9941 assert_eq!(
9942 &row[..64],
9943 &rows[0][..64],
9944 "row {y} of the whole superblock repeats its first row"
9945 );
9946 }
9947 let first = &rows[0][..64];
9948 assert!(
9949 first.windows(2).all(|w| w[0] >= w[1]),
9950 "the whole superblock falls across its sixty-four samples without \
9951 restarting: {first:?}"
9952 );
9953 assert!(
9954 first[0] > first[63],
9955 "the whole superblock falls from left to right, got {} then {}",
9956 first[0],
9957 first[63]
9958 );
9959 for block_row in 0..2 {
9960 for block_col in 2..4 {
9961 let block = block_at(&rows, block_row, block_col);
9962 assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})"));
9963 }
9964 }
9965 }
9966
9967 /// A quadrant may be split again into four 16x16 blocks, each carrying its
9968 /// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block
9969 /// makes each of the four a flat grey of its own, so the quadrant reads as
9970 /// four squares rather than one — which is what tells the extra split from
9971 /// a 32x32 block that merely carries the same coefficients.
9972 #[test]
9973 fn a_quadrant_splits_into_four_sixteens() {
9974 if !have_ffmpeg() {
9975 eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
9976 return;
9977 }
9978 let dc = |level: i32| {
9979 BlockCoeffs::from(vec![Coeff {
9980 row: 0,
9981 col: 0,
9982 level,
9983 }])
9984 };
9985 let levels = [14, 8, -8, -14];
9986 let flat = BlockCoeffs::from(Vec::new());
9987 let sbs = [Superblock::Split(vec![
9988 Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()),
9989 Quadrant::Whole(flat.clone()),
9990 Quadrant::Whole(flat.clone()),
9991 Quadrant::Whole(flat),
9992 ])];
9993 let rows = decode_luma_sb(64, 64, &sbs);
9994
9995 let mut greys = Vec::new();
9996 for i in 0..levels.len() {
9997 let (y0, x0) = ((i / 2) * 16, (i % 2) * 16);
9998 let grey = rows[y0][x0];
9999 for (y, row) in rows.iter().enumerate().skip(y0).take(16) {
10000 for (x, &sample) in row.iter().enumerate().skip(x0).take(16) {
10001 assert_eq!(
10002 sample, grey,
10003 "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not"
10004 );
10005 }
10006 }
10007 greys.push(grey);
10008 }
10009
10010 // Each block is predicted DC from the blocks the decoder has already
10011 // rebuilt, so what its own level does is move it off that prediction,
10012 // in the level's own direction.
10013 let g = |i: usize| i32::from(greys[i]);
10014 let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2];
10015 for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() {
10016 assert_eq!(
10017 (g(i) - prediction).signum(),
10018 level.signum(),
10019 "the 16x16 block {i} carries level {level}, so it sits on the \
10020 {} side of the {prediction} its neighbours predict, not at {}",
10021 if level > 0 { "bright" } else { "dark" },
10022 g(i)
10023 );
10024 }
10025 assert_eq!(
10026 greys.iter().collect::<std::collections::HashSet<_>>().len(),
10027 4,
10028 "the four blocks are four different greys, not one: {greys:?}"
10029 );
10030 }
10031
10032 /// A superblock half outside the frame has no partition that keeps a block
10033 /// outside it, so it cannot be left whole.
10034 #[test]
10035 fn a_whole_superblock_at_the_frame_edge_is_refused() {
10036 let block = BlockCoeffs::from(vec![Coeff {
10037 row: 0,
10038 col: 0,
10039 level: 4,
10040 }]);
10041 let sbs = [
10042 Superblock::Split(vec![
10043 Quadrant::Whole(block.clone()),
10044 Quadrant::Whole(block.clone()),
10045 Quadrant::Whole(block.clone()),
10046 Quadrant::Whole(block.clone()),
10047 ]),
10048 Superblock::Whole(block.clone()),
10049 ];
10050 // Ninety-six samples across is three 32x32 blocks, so the second
10051 // superblock hangs half outside the frame.
10052 let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err();
10053 assert!(
10054 format!("{err}").contains("half outside the frame"),
10055 "got {err}"
10056 );
10057 }
10058
10059 #[test]
10060 fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
10061 if !have_ffmpeg() {
10062 eprintln!(
10063 "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \
10064 ffmpeg"
10065 );
10066 return;
10067 }
10068 let blocks: Vec<BlockCoeffs> = (0..6)
10069 .map(|i| {
10070 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
10071 BlockCoeffs::from(vec![Coeff {
10072 row,
10073 col,
10074 level: 12,
10075 }])
10076 })
10077 .collect();
10078 let rows = decode_luma_at(96, 64, &blocks);
10079 for block_row in 0..2 {
10080 for block_col in 0..3 {
10081 let name = format!("block ({block_row},{block_col})");
10082 let block = block_at(&rows, block_row, block_col);
10083 if (block_row * 3 + block_col) % 2 == 0 {
10084 assert_falls_across(&block, &name);
10085 } else {
10086 assert_falls_down(&block, &name);
10087 }
10088 }
10089 }
10090 }
10091
10092 /// The transpose of [`a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block`]:
10093 /// an odd number of 32x32 block *rows* (superblock hangs off the
10094 /// *bottom*, `has_cols=true, has_rows=false`) rather than an odd number of
10095 /// columns (hangs off the *right*, `has_cols=false, has_rows=true`) --
10096 /// the two halves of the `(has_cols, has_rows)` match in
10097 /// `sb_coeff_key_frame_tile` gather from different tables
10098 /// (`VERT_ALIKE`/`HORZ_ALIKE`), and only the right-hand-edge direction had
10099 /// a real-decoder test before this one.
10100 #[test]
10101 fn a_frame_that_hangs_off_the_bottom_codes_every_block() {
10102 if !have_ffmpeg() {
10103 eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg");
10104 return;
10105 }
10106 let blocks: Vec<BlockCoeffs> = (0..6)
10107 .map(|i| {
10108 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
10109 BlockCoeffs::from(vec![Coeff {
10110 row,
10111 col,
10112 level: 12,
10113 }])
10114 })
10115 .collect();
10116 let rows = decode_luma_at(64, 96, &blocks);
10117 for block_row in 0..3 {
10118 for block_col in 0..2 {
10119 let name = format!("block ({block_row},{block_col})");
10120 let block = block_at(&rows, block_row, block_col);
10121 if (block_row * 2 + block_col) % 2 == 0 {
10122 assert_falls_across(&block, &name);
10123 } else {
10124 assert_falls_down(&block, &name);
10125 }
10126 }
10127 }
10128 }
10129
10130 /// A frame whose blocks do not tile it is refused rather than written as a
10131 /// stream a decoder walks off the end of.
10132 #[test]
10133 fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() {
10134 let (_, header) = frame_of(80, 64);
10135 let blocks = vec![BlockCoeffs::default(); 4];
10136 let err = split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, &blocks)
10137 .expect_err("80 is not a whole number of 32x32 blocks");
10138 assert!(
10139 format!("{err}").contains("32x32"),
10140 "the refusal names the block size, got {err}"
10141 );
10142 }
10143
10144 /// A directional intra mode says where its prediction comes from, and with
10145 /// no residual of its own a block must be exactly that prediction. The
10146 /// top-left block is given a basis function that is flat across it and
10147 /// falls down it; the block to its right is coded `H_PRED`, so every one of
10148 /// its rows must be the constant its left neighbour's rightmost column
10149 /// hands it, and the block below is coded `V_PRED`, so every one of its
10150 /// columns must be the constant the row above it ends on — a single flat
10151 /// value for the whole block. Nothing here pins the transform's shape or
10152 /// the mode's CDF: a mode written with the wrong context, an angle delta
10153 /// left out or a mode index off by one desyncs the symbol decoder and the
10154 /// two empty blocks stop mirroring their neighbours.
10155 #[test]
10156 fn directional_modes_predict_from_the_neighbours_they_name() {
10157 if !have_ffmpeg() {
10158 eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg");
10159 return;
10160 }
10161 let gradient = BlockCoeffs {
10162 luma: vec![Coeff {
10163 row: 1,
10164 col: 0,
10165 level: 12,
10166 }],
10167 ..BlockCoeffs::default()
10168 };
10169 let blocks = [
10170 gradient,
10171 BlockCoeffs {
10172 mode: H_PRED as u8,
10173 ..BlockCoeffs::default()
10174 },
10175 BlockCoeffs {
10176 mode: V_PRED as u8,
10177 ..BlockCoeffs::default()
10178 },
10179 BlockCoeffs::default(),
10180 ];
10181 let [luma, ..] = decode_coeff_planes(&blocks);
10182
10183 let source = block_at(&luma, 0, 0);
10184 for (r, row) in source.iter().enumerate() {
10185 assert!(
10186 row.iter().all(|&s| s == row[0]),
10187 "the basis function at row 1, column 0 is flat across the block, row {r} is not: {row:?}"
10188 );
10189 }
10190 let profile: Vec<u8> = source.iter().map(|r| r[0]).collect();
10191 assert!(
10192 profile.windows(2).all(|w| w[0] >= w[1]) && profile[0] > profile[31],
10193 "the block must fall from top to bottom, got {profile:?}"
10194 );
10195
10196 let horizontal = block_at(&luma, 0, 1);
10197 for (r, row) in horizontal.iter().enumerate() {
10198 assert!(
10199 row.iter().all(|&s| s == profile[r]),
10200 "an H_PRED block repeats the column to its left, row {r} should be all {} but is {row:?}",
10201 profile[r]
10202 );
10203 }
10204
10205 let vertical = block_at(&luma, 1, 0);
10206 let bottom = profile[31];
10207 assert!(
10208 vertical.iter().flatten().all(|&s| s == bottom),
10209 "a V_PRED block repeats the row above it, which is all {bottom} here, got rows \
10210 {:?} and {:?}",
10211 vertical[0],
10212 vertical[31]
10213 );
10214 }
10215
10216 /// The mode index is checked before anything is written.
10217 #[test]
10218 fn an_intra_mode_outside_the_key_frame_set_is_refused() {
10219 let mut blocks = vec![BlockCoeffs::default(); 4];
10220 blocks[2].mode = INTRA_MODES as u8;
10221 let message = split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks)
10222 .unwrap_err()
10223 .to_string();
10224 assert!(
10225 message.contains("intra mode 13"),
10226 "the refusal must name the mode, got {message}"
10227 );
10228 }
10229
10230 #[test]
10231 fn coefficients_the_writer_cannot_code_are_refused() {
10232 let empty = || vec![BlockCoeffs::default(); 4];
10233 let cases: [(&str, Vec<BlockCoeffs>); 6] = [
10234 ("one set short", vec![BlockCoeffs::default(); 3]),
10235 ("off the transform", {
10236 let mut b = empty();
10237 b[0].luma = vec![Coeff {
10238 row: 32,
10239 col: 0,
10240 level: 1,
10241 }];
10242 b
10243 }),
10244 ("a zero level", {
10245 let mut b = empty();
10246 b[1].luma = vec![Coeff {
10247 row: 0,
10248 col: 0,
10249 level: 0,
10250 }];
10251 b
10252 }),
10253 ("a level past the Golomb tail's reach", {
10254 let mut b = empty();
10255 b[2].luma = vec![Coeff {
10256 row: 0,
10257 col: 0,
10258 level: MAX_LEVEL + 1,
10259 }];
10260 b
10261 }),
10262 ("two coefficients at one position", {
10263 let mut b = empty();
10264 b[3].luma = vec![
10265 Coeff {
10266 row: 4,
10267 col: 4,
10268 level: 1,
10269 },
10270 Coeff {
10271 row: 4,
10272 col: 4,
10273 level: 2,
10274 },
10275 ];
10276 b
10277 }),
10278 ("off the chroma transform", {
10279 let mut b = empty();
10280 b[0].u = vec![Coeff {
10281 row: 0,
10282 col: 16,
10283 level: 1,
10284 }];
10285 b
10286 }),
10287 ];
10288 for (name, blocks) in cases {
10289 assert!(
10290 split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks).is_err(),
10291 "{name} must be refused"
10292 );
10293 }
10294 }
10295
10296 /// The default scan is written as the rule that generates it rather than a
10297 /// thousand pinned numbers, so the rule is checked against what a scan must
10298 /// be: every position exactly once, the origin first, and never a position
10299 /// before one it sits diagonally behind — which is what lets a decoder read
10300 /// a coefficient's context off the coefficients it has already decoded.
10301 /// lane-rdoq's two contracts, on a block shaped like the ones the pass
10302 /// exists for (a strong DC, two mid levels and a tail of barely-rounded
10303 /// +-1s): it may only move a block to a LOWER `D + lambda * R`, and the
10304 /// bits it hands back must be the price of the grid it leaves behind --
10305 /// the search takes that number as the block's rate, so a stale one
10306 /// would price a tile nobody writes.
10307 #[test]
10308 fn rdoq_only_lowers_the_cost_and_reports_its_own_grid() {
10309 let (side, set, q, lambda) = (16usize, TxbSet::Luma16, 150u8, 0.0275);
10310 let mut scaled = vec![0f32; side * side];
10311 for (i, v) in [
10312 (0usize, 7.4f32),
10313 (1, 2.6),
10314 (side, -1.55),
10315 // The tail the pass exists for: coefficients the deadzone only
10316 // just rounded up to +-1, which give a whole level back for a
10317 // fraction of one step of squared error.
10318 (2, 0.55),
10319 (2 * side + 1, -0.52),
10320 (3 * side + 3, 0.51),
10321 ] {
10322 scaled[i] = v;
10323 }
10324 // The deadzone quantiser this pass runs after, at the shipped 0.5.
10325 let mut levels: Vec<i32> = scaled
10326 .iter()
10327 .map(|&v| {
10328 let m = f64::from(v).abs() + 0.5;
10329 let l = if m < 1.0 { 0 } else { m.floor() as i32 };
10330 if v < 0.0 { -l } else { l }
10331 })
10332 .collect();
10333 let before = levels.clone();
10334 let dc = f64::from(crate::quant::dc_q(8, i32::from(q)));
10335 let ac = f64::from(crate::quant::ac_q(8, i32::from(q)));
10336 let dc_weight = (dc / ac) * (dc / ac);
10337 let cost = |grid: &[i32]| -> f64 {
10338 let d: f64 = grid
10339 .iter()
10340 .zip(&scaled)
10341 .enumerate()
10342 .map(|(i, (&l, &s))| {
10343 (if i == 0 { dc_weight } else { 1.0 })
10344 * (f64::from(s) - f64::from(l)).powi(2)
10345 })
10346 .sum();
10347 d + lambda * coeff_bits(grid, set, crate::decode::q_ctx_of(q), 0, 0)
10348 };
10349 let bits = rdoq(&mut levels, &scaled, side, q, set, 0, 0, lambda, TxType::DctDct);
10350 assert_eq!(bits, coeff_bits(&levels, set, crate::decode::q_ctx_of(q), 0, 0));
10351 assert!(cost(&levels) <= cost(&before), "{:?} vs {:?}", cost(&levels), cost(&before));
10352 // The tail is what it is for: the last coded position moves earlier.
10353 let last = |g: &[i32]| scan_of(side).iter().rposition(|&p| g[usize::from(p)] != 0);
10354 assert!(last(&levels) < last(&before), "eob {:?} -> {:?}", last(&before), last(&levels));
10355 // A 64-point transform is priced on its top-left 32x32 corner, and
10356 // the pass has to hand back THAT price (the dense path).
10357 let (side, set) = (64usize, TxbSet::Luma64);
10358 let mut scaled = vec![0f32; side * side];
10359 for (i, v) in [(0usize, 6.1f32), (1, 0.55), (side + 1, -0.53)] {
10360 scaled[i] = v;
10361 }
10362 let mut levels: Vec<i32> = scaled
10363 .iter()
10364 .map(|&v| {
10365 let m = f64::from(v).abs() + 0.5;
10366 let l = if m < 1.0 { 0 } else { m.floor() as i32 };
10367 if v < 0.0 { -l } else { l }
10368 })
10369 .collect();
10370 let bits = rdoq(&mut levels, &scaled, side, q, set, 0, 0, lambda, TxType::DctDct);
10371 let corner: Vec<i32> = (0..32)
10372 .flat_map(|row| levels[row * side..][..32].to_vec())
10373 .collect();
10374 assert_eq!(bits, coeff_bits(&corner, set, crate::decode::q_ctx_of(q), 0, 0));
10375 }
10376
10377 #[test]
10378 fn the_default_scan_walks_every_position_outwards() {
10379 for side in [TX16, TX32] {
10380 let area = side * side;
10381 let scan = default_scan(side);
10382 assert_eq!(scan.len(), area);
10383 let mut seen = vec![false; area];
10384 for &pos in &scan {
10385 assert!(
10386 !seen[pos as usize],
10387 "position {pos} is scanned twice in {side}x{side}"
10388 );
10389 seen[pos as usize] = true;
10390 }
10391 assert_eq!(scan[0], 0, "the scan starts at the DC");
10392
10393 let mut order = vec![0usize; area];
10394 for (i, &pos) in scan.iter().enumerate() {
10395 order[pos as usize] = i;
10396 }
10397 for row in 0..side {
10398 for col in 0..side {
10399 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
10400 let (nr, nc) = (row + dr, col + dc);
10401 if nr < side && nc < side {
10402 assert!(
10403 order[nr * side + nc] > order[row * side + col],
10404 "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
10405 be scanned after it"
10406 );
10407 }
10408 }
10409 }
10410 }
10411 }
10412 }
10413
10414 /// The whole point of the inverse transform living in the encoder is that
10415 /// it predicts the decoder without asking one. The residual a DC-only
10416 /// 64x64 transform produces has already been pinned from a real decoder in
10417 /// [`DECODED_AT_Q100`], so that table is the gate: every level in it, both
10418 /// signs, has to come back out of `dequant_and_inverse` exactly.
10419 #[test]
10420 fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() {
10421 for (level, _) in DECODED_AT_Q100 {
10422 let mut levels = vec![0i32; 64 * 64];
10423 levels[0] = level;
10424 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
10425 let want = dc_residual(level);
10426 assert!(
10427 residual.iter().all(|&r| r == want),
10428 "level {level}: want a flat {want}, got {}..{} (first {})",
10429 residual.iter().min().unwrap(),
10430 residual.iter().max().unwrap(),
10431 residual[0]
10432 );
10433 }
10434 }
10435
10436 /// The same gate at the other transform size the encoder codes: a split
10437 /// superblock's 32x32 blocks, whose residuals are pinned in
10438 /// [`SPLIT_RESIDUAL_AT_Q100`]. The two sizes divide the dequantized
10439 /// coefficient by different denominators, so a size-blind dequantizer
10440 /// passes one table and fails the other.
10441 #[test]
10442 fn the_inverse_transform_reproduces_the_pinned_split_residuals() {
10443 for (level, want) in SPLIT_RESIDUAL_AT_Q100 {
10444 let mut levels = vec![0i32; 32 * 32];
10445 levels[0] = level;
10446 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
10447 assert!(
10448 residual.iter().all(|&r| r == want),
10449 "level {level}: want a flat {want}, got {}..{} (first {})",
10450 residual.iter().min().unwrap(),
10451 residual.iter().max().unwrap(),
10452 residual[0]
10453 );
10454 }
10455 }
10456
10457 /// A DC-only transform is flat, which is exactly the case that cannot tell
10458 /// a transposed or mis-permuted butterfly network from a correct one. An AC
10459 /// coefficient in the first row must vary along the row and stay constant
10460 /// down each column, and the one in the first column the other way round;
10461 /// a transposed network swaps the two.
10462 #[test]
10463 fn a_single_ac_coefficient_varies_along_its_own_axis() {
10464 for side in [4, 8, 16, 32, 64] {
10465 let mut horizontal = vec![0i32; side * side];
10466 horizontal[1] = 100;
10467 let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX));
10468 let mut vertical = vec![0i32; side * side];
10469 vertical[side] = 100;
10470 let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX));
10471 for row in 0..side {
10472 for col in 0..side {
10473 assert_eq!(
10474 h[row * side + col],
10475 h[col],
10476 "{side}: a first-row coefficient is constant down column {col}"
10477 );
10478 assert_eq!(
10479 v[row * side + col],
10480 v[row * side],
10481 "{side}: a first-column coefficient is constant along row {row}"
10482 );
10483 }
10484 }
10485 // The two are each other's transpose. Only to within a rounding
10486 // step: the spec rounds halves up rather than away from zero, so a
10487 // basis function and its transpose can land a count apart where
10488 // the row and column passes round opposite ways.
10489 assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies");
10490 for row in 0..side {
10491 for col in 0..side {
10492 let (a, b) = (h[row * side + col], v[col * side + row]);
10493 assert!(
10494 (a - b).abs() <= 1,
10495 "{side}: transpose at ({row},{col}): {a} vs {b}"
10496 );
10497 }
10498 }
10499 }
10500 }
10501
10502 /// Negating every level negates every residual, to within the one count
10503 /// the spec's round-halves-up leaves behind. A dequantizer that rounded a
10504 /// negative coefficient away from zero instead of toward it would shift a
10505 /// whole basis function, not a count of it, so the bound is what makes
10506 /// this a test rather than a restatement.
10507 #[test]
10508 fn negating_the_levels_negates_the_residual() {
10509 for side in [32, 64] {
10510 for level in [1, 2, 3, 5, 9, 14, 40, 100] {
10511 let mut levels = vec![0i32; side * side];
10512 levels[0] = level;
10513 levels[1] = -level;
10514 levels[side + 1] = level * 2;
10515 let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
10516 let negated: Vec<i32> = levels.iter().map(|&l| -l).collect();
10517 let neg =
10518 crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX));
10519 let worst = pos
10520 .iter()
10521 .zip(&neg)
10522 .map(|(&p, &n)| (p + n).abs())
10523 .max()
10524 .expect("the block is not empty");
10525 assert!(worst <= 1, "side {side} level {level}: off by {worst}");
10526 }
10527 }
10528 }
10529
10530 /// The pinned tables above are DC-only, and a flat residual cannot tell a
10531 /// correct butterfly network from one that is merely correct at DC. This
10532 /// is the same claim against a real decoder and with real AC content: the
10533 /// top-left block of a key frame predicts a flat mid-grey with no
10534 /// neighbours to read, so what ffmpeg shows there is exactly 128 plus the
10535 /// residual the encoder's own inverse transform computes. Every sample has
10536 /// to agree, not most of them.
10537 #[test]
10538 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
10539 if !have_ffmpeg() {
10540 eprintln!(
10541 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg"
10542 );
10543 return;
10544 }
10545 // A DC, two low-frequency terms of each orientation, a diagonal and a
10546 // far corner, with both signs among them.
10547 let coeffs = [
10548 (0u8, 0u8, 9i32),
10549 (0, 1, -14),
10550 (1, 0, 7),
10551 (0, 3, 5),
10552 (3, 0, -3),
10553 (2, 2, 11),
10554 (7, 5, -6),
10555 (31, 31, 4),
10556 ];
10557 let block: BlockCoeffs = coeffs
10558 .iter()
10559 .map(|&(row, col, level)| Coeff { row, col, level })
10560 .collect::<Vec<_>>()
10561 .into();
10562 let rows = decode_luma_at(
10563 64,
10564 64,
10565 &[
10566 block,
10567 BlockCoeffs::default(),
10568 BlockCoeffs::default(),
10569 BlockCoeffs::default(),
10570 ],
10571 );
10572
10573 let mut levels = vec![0i32; 32 * 32];
10574 for &(row, col, level) in &coeffs {
10575 levels[usize::from(row) * 32 + usize::from(col)] = level;
10576 }
10577 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
10578 for row in 0..32 {
10579 for col in 0..32 {
10580 let want = (128 + residual[row * 32 + col]).clamp(0, 255);
10581 assert_eq!(
10582 i32::from(rows[row][col]),
10583 want,
10584 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
10585 rows[row][col]
10586 );
10587 }
10588 }
10589 // The block is not flat, so the agreement is about the transform and
10590 // not about a prediction both sides got trivially right.
10591 let (lo, hi) = (
10592 rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(),
10593 rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(),
10594 );
10595 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
10596 }
10597
10598 /// The same against the smallest transform the writer codes, the 16x16 one
10599 /// a split quadrant carries. Its rounding is the one the split path rests
10600 /// on, and nothing else in the crate exercises it against a decoder.
10601 #[test]
10602 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
10603 if !have_ffmpeg() {
10604 eprintln!(
10605 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
10606 );
10607 return;
10608 }
10609 let coeffs = [
10610 (0u8, 0u8, 9i32),
10611 (0, 1, -14),
10612 (1, 0, 7),
10613 (0, 3, 5),
10614 (3, 0, -3),
10615 (2, 2, 11),
10616 (7, 5, -6),
10617 (15, 15, 4),
10618 ];
10619 let block: BlockCoeffs = coeffs
10620 .iter()
10621 .map(|&(row, col, level)| Coeff { row, col, level })
10622 .collect::<Vec<_>>()
10623 .into();
10624 let (seq, header) = frame_of(64, 64);
10625 let quadrants = vec![
10626 Quadrant::Split(vec![
10627 block,
10628 BlockCoeffs::default(),
10629 BlockCoeffs::default(),
10630 BlockCoeffs::default(),
10631 ]),
10632 Quadrant::Whole(BlockCoeffs::default()),
10633 Quadrant::Whole(BlockCoeffs::default()),
10634 Quadrant::Whole(BlockCoeffs::default()),
10635 ];
10636 let tile = sb_coeff_key_frame_tile(
10637 header.mi_cols,
10638 header.mi_rows,
10639 Q_IDX,
10640 &[Superblock::Split(quadrants)],
10641 )
10642 .unwrap();
10643 let mut stream = temporal_delimiter();
10644 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
10645 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
10646 let planes = ffmpeg_decode(&stream, 64, 64);
10647
10648 let mut levels = vec![0i32; TX16 * TX16];
10649 for &(row, col, level) in &coeffs {
10650 levels[usize::from(row) * TX16 + usize::from(col)] = level;
10651 }
10652 let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX));
10653 for row in 0..TX16 {
10654 for col in 0..TX16 {
10655 let want = (128 + residual[row * TX16 + col]).clamp(0, 255);
10656 assert_eq!(
10657 i32::from(planes[row * 64 + col]),
10658 want,
10659 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
10660 planes[row * 64 + col]
10661 );
10662 }
10663 }
10664 }
10665
10666 /// The same against the other transform size, the 64x64 one a whole
10667 /// superblock carries. Only its top-left 32x32 can hold coefficients, and
10668 /// the spec zeroes the rest before the row transform — a 64-point network
10669 /// that read the missing half as anything else would disagree here.
10670 #[test]
10671 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {
10672 if !have_ffmpeg() {
10673 eprintln!(
10674 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg"
10675 );
10676 return;
10677 }
10678 let coeffs = [
10679 (0u8, 0u8, 12i32),
10680 (0, 2, -9),
10681 (2, 0, 6),
10682 (1, 1, -5),
10683 (5, 9, 8),
10684 (31, 0, -4),
10685 (0, 31, 3),
10686 ];
10687 let block: BlockCoeffs = coeffs
10688 .iter()
10689 .map(|&(row, col, level)| Coeff { row, col, level })
10690 .collect::<Vec<_>>()
10691 .into();
10692 let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]);
10693
10694 let mut levels = vec![0i32; 64 * 64];
10695 for &(row, col, level) in &coeffs {
10696 levels[usize::from(row) * 64 + usize::from(col)] = level;
10697 }
10698 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
10699 for row in 0..64 {
10700 for col in 0..64 {
10701 let want = (128 + residual[row * 64 + col]).clamp(0, 255);
10702 assert_eq!(
10703 i32::from(rows[row][col]),
10704 want,
10705 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
10706 rows[row][col]
10707 );
10708 }
10709 }
10710 }
10711
10712 /// The AV1 transforms are normalized so that a quantized level means the
10713 /// same thing at every size: doubling the transform's side halves what a
10714 /// DC level is worth, which is the job the per-size row shift and the
10715 /// dequantizer's denominator split between them. The frame syntax only
10716 /// codes 32x32 and 64x64 transforms, so this is what holds the four
10717 /// smaller sizes' shifts to the spec's table — a shift wrong by one at any
10718 /// size doubles or halves that size's step alone.
10719 #[test]
10720 fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() {
10721 let mut previous: Option<i32> = None;
10722 for side in [4usize, 8, 16, 32, 64] {
10723 let mut levels = vec![0i32; side * side];
10724 levels[0] = 100;
10725 let residual =
10726 crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
10727 let dc = residual[0];
10728 assert!(
10729 residual.iter().all(|&r| r == dc),
10730 "side {side}: a DC coefficient reconstructs flat"
10731 );
10732 if let Some(previous) = previous {
10733 assert!(
10734 (dc * 2 - previous).abs() <= 1,
10735 "side {side}: {dc} is not half of the previous size's {previous}"
10736 );
10737 }
10738 previous = Some(dc);
10739 }
10740 }
10741
10742 /// The encoder's own round trip, through a real bitstream.
10743 ///
10744 /// A picture is chosen, its residual against the DC prediction of 128 is
10745 /// forward-transformed and quantized, the levels are written into a tile,
10746 /// and ffmpeg decodes it. Two things have to hold: what comes back is
10747 /// exactly what the encoder's own inverse said it would be — sample for
10748 /// sample, which is what lets a rate-distortion loop trust its
10749 /// reconstruction — and it is within a quantizer step of the picture that
10750 /// was asked for, which is what makes the forward transform an encoder
10751 /// rather than a scrambler.
10752 #[test]
10753 fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {
10754 if !have_ffmpeg() {
10755 eprintln!(
10756 "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
10757 );
10758 return;
10759 }
10760 // A gradient, a ripple and a corner patch: low frequencies, a mid one
10761 // and an edge, none of them a basis function of the transform.
10762 let mut residual = vec![0i32; 32 * 32];
10763 for row in 0..32usize {
10764 for col in 0..32usize {
10765 let gradient = row as f64 * 2.0 - 32.0;
10766 let ripple = 25.0
10767 * (col as f64 * std::f64::consts::PI / 6.0).sin()
10768 * (row as f64 * std::f64::consts::PI / 11.0).cos();
10769 let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 };
10770 residual[row * 32 + col] = (gradient + ripple + patch).round() as i32;
10771 }
10772 }
10773
10774 let levels =
10775 crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5);
10776 assert!(
10777 levels.iter().any(|&l| l != 0),
10778 "the picture quantized away entirely"
10779 );
10780 let coded: Vec<Coeff> = levels
10781 .iter()
10782 .enumerate()
10783 .filter(|&(_, &level)| level != 0)
10784 .map(|(i, &level)| Coeff {
10785 row: (i / 32) as u8,
10786 col: (i % 32) as u8,
10787 level,
10788 })
10789 .collect();
10790
10791 let rows = decode_luma_at(
10792 64,
10793 64,
10794 &[
10795 coded.into(),
10796 BlockCoeffs::default(),
10797 BlockCoeffs::default(),
10798 BlockCoeffs::default(),
10799 ],
10800 );
10801 let reconstruction =
10802 crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
10803
10804 let mut squared = 0.0f64;
10805 for row in 0..32 {
10806 for col in 0..32 {
10807 let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255);
10808 assert_eq!(
10809 i32::from(rows[row][col]),
10810 want,
10811 "sample ({row},{col}): the decoder and the encoder disagree"
10812 );
10813 let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]);
10814 squared += error * error;
10815 }
10816 }
10817 let rmse = (squared / 1024.0).sqrt();
10818 // A quantizer step is q/8 in residual units. Rounding to nearest
10819 // spreads the error over a step, and a quarter of one is a bound this
10820 // picture clears with room to spare (2.2 of 14 as written) while a
10821 // forward transform that is merely energy-preserving does not: a
10822 // transposed column pass measures 13.3 here.
10823 let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0;
10824 assert!(
10825 rmse < step / 4.0,
10826 "the decoded picture is {rmse} off, a step being {step}"
10827 );
10828 }
10829
10830 /// The inverse of [`write_mv_component`], mirroring [`SymbolDecoder`]
10831 /// against the spec's own `read_mv_component` pseudocode.
10832 fn decode_mv_component(
10833 dec: &mut crate::msac::tests::SymbolDecoder,
10834 c: &mut MvComponentCdfs,
10835 ) -> i32 {
10836 let sign = dec.symbol(&mut c.sign);
10837 let class = dec.symbol(&mut c.class);
10838 let local = if class == 0 {
10839 let bit = dec.symbol(&mut c.class0_bit);
10840 let fr = dec.symbol(&mut c.class0_fr[bit]);
10841 (bit << 3) | (fr << 1) | 1
10842 } else {
10843 let mut d = 0;
10844 for i in 0..class {
10845 d |= dec.symbol(&mut c.bit[i]) << i;
10846 }
10847 let fr = dec.symbol(&mut c.fr);
10848 (d << 3) | (fr << 1) | 1
10849 };
10850 let mag = mv_class_base(class) + local as i32 + 1;
10851 if sign == 1 { -mag } else { mag }
10852 }
10853
10854 /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,
10855 /// mirroring the writer's own context tracking (partition, skip,
10856 /// is_inter, and the MV stack) symbol for symbol against a fresh
10857 /// [`Cdfs`], so a desync between the two shows up as a wrong decoded
10858 /// value rather than a silent pass. Every block here is skipped, so no
10859 /// coefficient symbols are read. `wrong_y_mode` swaps in `KF_Y_MODE`'s
10860 /// (0, 0) row for an intra block's mode read, to show that reading the
10861 /// wrong table decodes the wrong mode rather than the one that was
10862 /// written.
10863 ///
10864 /// One decoded block's `(skip, is_inter, mode, mv)` — `mode` is `None`
10865 /// for an inter block, `mv` is `(0, 0)` for an intra one.
10866 type DecodedBlock = (bool, bool, Option<usize>, (i32, i32));
10867
10868 /// Returns the number of symbols and literals read, and each block's
10869 /// decoded state.
10870 fn decode_inter_sb(
10871 data: &[u8],
10872 mi_cols: u32,
10873 mi_rows: u32,
10874 wrong_y_mode: bool,
10875 ) -> (usize, Vec<DecodedBlock>) {
10876 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
10877 let mut cdfs = Cdfs::new(2);
10878 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
10879 let mut above_skip = [false; 2];
10880 let mut left_skip = [false; 2];
10881 let mut above_inter = [false; 2];
10882 let mut left_inter = [false; 2];
10883 let mut count = 0usize;
10884
10885 count += 1;
10886 dec.symbol(&mut cdfs.partition_w64[0]);
10887
10888 let mut results = Vec::new();
10889 for quadrant in 0..4usize {
10890 let (r32, c32) = (quadrant / 2, quadrant % 2);
10891 count += 1;
10892 dec.symbol(&mut cdfs.partition_w32[0]);
10893
10894 let (has_above, has_left) = (r32 > 0, c32 > 0);
10895 let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]);
10896 count += 1;
10897 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
10898
10899 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]);
10900 count += 1;
10901 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
10902
10903 let (mode, mv) = if is_inter {
10904 let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]);
10905 count += 3;
10906 assert_eq!(
10907 dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
10908 0,
10909 "single_ref p1"
10910 );
10911 assert_eq!(
10912 dec.symbol(&mut cdfs.single_ref[sr_ctx][2]),
10913 0,
10914 "single_ref p3"
10915 );
10916 assert_eq!(
10917 dec.symbol(&mut cdfs.single_ref[sr_ctx][3]),
10918 0,
10919 "single_ref p4"
10920 );
10921
10922 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
10923 let stack = find_mv_stack(
10924 &grid,
10925 mi_row,
10926 mi_col,
10927 8,
10928 8,
10929 1,
10930 mi_cols as usize,
10931 mi_rows as usize,
10932 );
10933
10934 count += 1;
10935 let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0;
10936 let (mv, is_new_mv) = if new_mv {
10937 if stack.entries.len() > 1 {
10938 count += 1;
10939 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
10940 }
10941 count += 1;
10942 let joint = dec.symbol(&mut cdfs.mv_joint);
10943 let mut diff = (0, 0);
10944 if joint == 2 || joint == 3 {
10945 // sign, class, class0_bit, class0_fr for this test's
10946 // small (class 0) components.
10947 count += 4;
10948 diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]);
10949 }
10950 if joint == 1 || joint == 3 {
10951 count += 4;
10952 diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]);
10953 }
10954 ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true)
10955 } else {
10956 count += 2;
10957 assert_eq!(
10958 dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]),
10959 1,
10960 "zero_mv"
10961 );
10962 assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv");
10963 (stack.nearest_mv, false)
10964 };
10965 for dr in 0..8 {
10966 for dc in 0..8 {
10967 grid.set(
10968 mi_row + dr,
10969 mi_col + dc,
10970 MiInfo {
10971 is_inter: true,
10972 ref_frame: 1,
10973 ref_frame1: NO_REF1,
10974 mv1: (0, 0),
10975 mv: mv16(mv),
10976 is_new_mv,
10977 size: 8,
10978 size_h: 8,
10979 is_global_mv0: false,
10980 is_global_mv1: false,
10981 },
10982 );
10983 }
10984 }
10985 (None, mv)
10986 } else {
10987 count += 1;
10988 let m = if wrong_y_mode {
10989 dec.symbol(&mut cdfs.kf_y_mode[0][0])
10990 } else {
10991 dec.symbol(&mut cdfs.y_mode[3])
10992 };
10993 if (V_PRED..=D67_PRED).contains(&m) {
10994 count += 1;
10995 dec.symbol(&mut cdfs.angle_delta[m - V_PRED]);
10996 }
10997 count += 1;
10998 dec.symbol(&mut cdfs.uv_mode_cfl[m]);
10999 (Some(m), (0, 0))
11000 };
11001
11002 above_skip[c32] = skip;
11003 left_skip[r32] = skip;
11004 above_inter[c32] = is_inter;
11005 left_inter[r32] = is_inter;
11006 results.push((skip, is_inter, mode, mv));
11007 }
11008 (count, results)
11009 }
11010
11011 /// Every superblock here skips: no residual, so the only symbols are the
11012 /// mode chain, and the byte count and the symbol count both come out
11013 /// small enough to hand-check.
11014 #[test]
11015 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
11016 let block = BlockCoeffs {
11017 inter: Some(InterInfo {
11018 ref1: None,
11019 mv1: (0, 0),
11020 ref_frame: crate::mvstack::LAST_FRAME,
11021 mode: InterMode::NearestMv,
11022 mv: (0, 0),
11023 ref_mv_idx: 0,
11024 }),
11025 skip: true,
11026 ..BlockCoeffs::default()
11027 };
11028 let blocks = vec![
11029 Quadrant::Whole(block.clone()),
11030 Quadrant::Whole(block.clone()),
11031 Quadrant::Whole(block.clone()),
11032 Quadrant::Whole(block),
11033 ];
11034 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11035 // Hand count: one partition_w64, then per block partition_w32 + skip +
11036 // is_inter + 3 single_ref + new_mv + zero_mv + ref_mv = 9, times four.
11037 assert!(
11038 data.len() <= 16,
11039 "an all-skip NEARESTMV superblock took {} bytes",
11040 data.len()
11041 );
11042
11043 let (count, results) = decode_inter_sb(&data, 16, 16, false);
11044 assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count");
11045 for (skip, is_inter, mode, mv) in results {
11046 assert!(skip);
11047 assert!(is_inter);
11048 assert_eq!(mode, None);
11049 // Every block's only inter neighbours carry (0, 0), so the stack's
11050 // nearest candidate is (0, 0) throughout.
11051 assert_eq!(mv, (0, 0));
11052 }
11053 }
11054
11055 /// The fourth block codes NEWMV against a (0, 0) predictor with a coded
11056 /// column component: the symbol sequence a decoder reads back has to be
11057 /// exactly what [`write_mv`] wrote, not a residual that merely decodes
11058 /// to *some* valid vector.
11059 #[test]
11060 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
11061 let nearest = BlockCoeffs {
11062 inter: Some(InterInfo {
11063 ref1: None,
11064 mv1: (0, 0),
11065 ref_frame: crate::mvstack::LAST_FRAME,
11066 mode: InterMode::NearestMv,
11067 mv: (0, 0),
11068 ref_mv_idx: 0,
11069 }),
11070 skip: true,
11071 ..BlockCoeffs::default()
11072 };
11073 let newmv = BlockCoeffs {
11074 inter: Some(InterInfo {
11075 ref1: None,
11076 mv1: (0, 0),
11077 ref_frame: crate::mvstack::LAST_FRAME,
11078 mode: InterMode::NewMv,
11079 mv: (0, 2),
11080 ref_mv_idx: 0,
11081 }),
11082 skip: true,
11083 ..BlockCoeffs::default()
11084 };
11085 let blocks = vec![
11086 Quadrant::Whole(nearest.clone()),
11087 Quadrant::Whole(nearest.clone()),
11088 Quadrant::Whole(nearest),
11089 Quadrant::Whole(newmv),
11090 ];
11091 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11092
11093 let (count, results) = decode_inter_sb(&data, 16, 16, false);
11094 // Three NEARESTMV blocks at 9 symbols each, one NEWMV block at
11095 // partition + skip + is_inter + 3 single_ref + new_mv + mv_joint +
11096 // (sign, class, class0_bit, class0_fr for the one nonzero component)
11097 // = 12, plus the superblock's partition_w64.
11098 assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count");
11099 let (skip, is_inter, mode, mv) = results[3];
11100 assert!(skip);
11101 assert!(is_inter);
11102 assert_eq!(mode, None);
11103 assert_eq!(
11104 mv,
11105 (0, 2),
11106 "the decoded motion vector must be exactly what was written"
11107 );
11108 }
11109
11110 /// Decodes only the first 32x32 block's mode symbol of a superblock: the
11111 /// tile's own first block always reads partition, skip and is_inter at
11112 /// context zero, so this needs none of [`decode_inter_sb`]'s neighbour
11113 /// bookkeeping — which matters here because the mutation this feeds
11114 /// desyncs everything after the one symbol it is testing, and a decoder
11115 /// that kept reading past it would be asserting on garbage.
11116 fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize {
11117 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
11118 let mut cdfs = Cdfs::new(2);
11119 dec.symbol(&mut cdfs.partition_w64[0]);
11120 dec.symbol(&mut cdfs.partition_w32[0]);
11121 dec.symbol(&mut cdfs.skip[0]);
11122 dec.symbol(&mut cdfs.intra_inter[0]);
11123 if wrong_y_mode {
11124 dec.symbol(&mut cdfs.kf_y_mode[0][0])
11125 } else {
11126 dec.symbol(&mut cdfs.y_mode[3])
11127 }
11128 }
11129
11130 /// An inter frame's intra block reads its mode against `Y_MODE`'s size
11131 /// group, not `KF_Y_MODE`'s neighbour-context table a key frame's block
11132 /// reads. Reading the wrong table back — `KF_Y_MODE`'s `(0, 0)` row —
11133 /// decodes a different mode than the one [`sb_coeff_inter_frame_tile`]
11134 /// wrote, because the two tables carry different default probabilities
11135 /// even though a row of each is the same fourteen-entry width. (The swap
11136 /// this test's name warns of does not typecheck as a one-line
11137 /// substitution at the write site either — `cdfs.kf_y_mode[3]` is a
11138 /// `[[u16; 14]; 5]` row, not the single `[u16; 14]` `Y_MODE` indexing
11139 /// needs — so a mutation that got the *outer* shape wrong would be
11140 /// caught by `cargo check` before it ever reached a test; this test is
11141 /// what catches getting the *right* leaf shape from the *wrong* table.)
11142 #[test]
11143 fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() {
11144 let block = BlockCoeffs {
11145 mode: H_PRED as u8,
11146 skip: true,
11147 ..BlockCoeffs::default()
11148 };
11149 let blocks = vec![Quadrant::Whole(block); 4];
11150 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
11151
11152 assert_eq!(
11153 decode_first_block_mode(&data, false),
11154 H_PRED,
11155 "the right table reads the mode back exactly"
11156 );
11157 assert_ne!(
11158 decode_first_block_mode(&data, true),
11159 H_PRED,
11160 "KF_Y_MODE's different probabilities must decode a different mode"
11161 );
11162 }
11163
11164 /// lane-rectdq witness: [`crate::encode::delta_q_bits`] prices exactly
11165 /// what [`write_delta_q`] writes, over the whole `delta_q_abs` domain
11166 /// (0..=20 steps, both signs -- the escape literal pair starts at 3 and
11167 /// its `rem_bits` widens at 4, 5, 9 and 17). The writer is run into a
11168 /// PRICING coder whose account (`SymbolEncoder::bits`) is the same
11169 /// arithmetic-coder cost the pricer's `symbol_bits` sums, so the two
11170 /// agree to floating-point noise, not to a tolerance band.
11171 ///
11172 /// Both sides read the DEFAULT `delta_q` row: the writer's `cdfs` is
11173 /// rebuilt per case, exactly as every tile's is armed before its first
11174 /// superblock.
11175 #[test]
11176 fn the_delta_q_pricer_matches_the_writer_over_the_whole_domain() {
11177 const RES: i32 = 4;
11178 const CUR: i32 = 128;
11179 for steps in -20i32..=20 {
11180 let target = CUR + steps * RES;
11181 arm_delta_q(RES, 1, vec![u8::try_from(target).expect("in range")], 128);
11182 let mut cdfs = Cdfs::new(2);
11183 let mut enc = SymbolEncoder::pricer();
11184 enc.reset_bits();
11185 // `is_whole_sb = false`: the rect half / 64-superblock shape,
11186 // the one whose pricer this witnesses.
11187 write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
11188 let written = enc.bits();
11189 let priced = crate::encode::delta_q_bits(target, CUR, RES);
11190 assert!(
11191 (written - priced).abs() < 1e-9,
11192 "steps {steps}: writer {written} bits, pricer {priced}"
11193 );
11194 }
11195 // Disarmed plan: the writer codes nothing and the pricer charges
11196 // nothing.
11197 arm_delta_q(0, 1, Vec::new(), 128);
11198 let mut cdfs = Cdfs::new(2);
11199 let mut enc = SymbolEncoder::pricer();
11200 enc.reset_bits();
11201 write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
11202 assert!(enc.bits().abs() < 1e-9, "a disarmed plan writes no symbol");
11203 assert!((crate::encode::delta_q_bits(200, 128, 0)).abs() < 1e-9);
11204 }
11205}