forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

tile.rs8204 lines, 337.5 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;
13use std::sync::LazyLock;
14
15use ec_core::{Error, Result};
16
17use crate::cdf;
18use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
19use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
20use crate::msac::SymbolEncoder;
21use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};
22
23// ---------------------------------------------------------------------------
24// lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder
25// reads ONE `cdef_idx` literal per 64x64 superblock, at that superblock's
26// first non-skip block, and only when the frame header's `cdef_bits > 0`
27// (`crate::decode::maybe_read_cdef_idx`). The writers below mirror that from
28// a plan the filter search hands over, kept in a thread-local rather than
29// threaded through every `write_*` signature -- the same shape the decoder's
30// own `FrameCtx::cdef_transmitted` uses, and the encoder codes one tile at a
31// time on one thread. The plan is CONSUMED by the tile writer that runs next
32// ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame
33// that arms nothing writes no literals.
34
35// ---------------------------------------------------------------------------
36// lane-av1lr: per-restoration-unit loop restoration syntax (spec 5.11.57,
37// `read_lr`), armed by the encoder's restoration search the same way
38// [`arm_cdef_idx`] arms the CDEF indices. LUMA ONLY and Wiener only: the
39// frame header this encoder writes sets `FrameRestorationType[0] = WIENER`
40// and leaves both chroma planes at `RESTORE_NONE`, so a unit codes one
41// `restore_wiener` symbol and, when it takes the filter, its two directions
42// against the running per-tile reference (`crate::restoration::
43// write_wiener_filter`, the exact inverse of the reader's own
44// `read_wiener_filter`).
45
46/// One frame's per-unit restoration plan (see [`arm_lr`]).
47struct LrPlan {
48 /// `LoopRestorationSize[0]`, in luma samples.
49 unit_size: u32,
50 /// `horz_units`/`vert_units` for the luma plane.
51 horz_units: u32,
52 vert_units: u32,
53 /// One entry per unit, `rcol + rrow * horz_units`: the filter it takes,
54 /// or `None` for `RESTORE_NONE`.
55 units: Vec<Option<crate::restoration::WienerInfo>>,
56 /// `ref_wiener_info`: the running reference the taps are coded against,
57 /// reset to the midpoint filter at the start of each tile (this writer
58 /// codes one tile per frame).
59 reference: crate::restoration::WienerInfo,
60}
61
62thread_local! {
63 static LR_PLAN: std::cell::RefCell<Option<LrPlan>> = const { std::cell::RefCell::new(None) };
64}
65
66/// Arms the next tile write with one Wiener decision per luma restoration
67/// unit. An empty `units` disarms (the frame codes no restoration at all).
68pub(crate) fn arm_lr(
69 unit_size: u32,
70 horz_units: u32,
71 vert_units: u32,
72 units: Vec<Option<crate::restoration::WienerInfo>>,
73) {
74 LR_PLAN.with(|c| {
75 *c.borrow_mut() = (!units.is_empty()).then(|| LrPlan {
76 unit_size,
77 horz_units,
78 vert_units,
79 units,
80 reference: crate::restoration::WienerInfo::default(),
81 });
82 });
83}
84
85/// `read_lr`'s write side, called once at the top of every superblock,
86/// before its partition symbol: writes the units this superblock's own
87/// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
88/// column scaling is the plain mi one).
89fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32) {
90 LR_PLAN.with(|c| {
91 let mut plan = c.borrow_mut();
92 let Some(plan) = plan.as_mut() else { return };
93 let unit = plan.unit_size;
94 let rcol0 = (mi_col * 4).div_ceil(unit);
95 let rcol1 = ((mi_col + SB_MI_W) * 4).div_ceil(unit).min(plan.horz_units);
96 let rrow0 = (mi_row * 4).div_ceil(unit);
97 let rrow1 = ((mi_row + SB_MI_W) * 4).div_ceil(unit).min(plan.vert_units);
98 for rrow in rrow0..rrow1 {
99 for rcol in rcol0..rcol1 {
100 let info = plan.units[(rcol + rrow * plan.horz_units) as usize];
101 enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener);
102 if let Some(info) = info {
103 crate::restoration::write_wiener_filter(
104 enc,
105 false,
106 &mut plan.reference,
107 &info,
108 );
109 }
110 }
111 }
112 });
113}
114
115/// A 64x64 superblock's width in 4x4 mode-info units (`SB_MI` in
116/// `crate::decode`), the span [`write_lr`] resolves its units over.
117const SB_MI_W: u32 = 16;
118
119/// One tile's own superblock and mode-info span (spec 5.11.1's tile loop
120/// bounds): `MiColStarts[i]..MiColStarts[i+1]` and the same down the rows,
121/// with the superblock indices those mi bounds fall on. The writers walk
122/// exactly this rect, and everything a block reads outside it -- the
123/// neighbour bands, the MV grid -- is left at the "unavailable" state a
124/// tile's own first row and column see, which is how the decoder clips them
125/// (`MiGrid::set_tile_bounds`, `PlaneBuf::set_tile_origin`).
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub(crate) struct TileRect {
128 pub(crate) sb_col0: u32,
129 pub(crate) sb_col1: u32,
130 pub(crate) sb_row0: u32,
131 pub(crate) sb_row1: u32,
132 pub(crate) mi_col0: u32,
133 pub(crate) mi_col1: u32,
134 pub(crate) mi_row0: u32,
135 pub(crate) mi_row1: u32,
136}
137
138impl TileRect {
139 /// The whole frame as one tile -- what every single-tile caller writes.
140 pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self {
141 let (cols, rows) = block_grid(mi_cols, mi_rows);
142 Self {
143 sb_col0: 0,
144 sb_col1: cols.div_ceil(2),
145 sb_row0: 0,
146 sb_row1: rows.div_ceil(2),
147 mi_col0: 0,
148 mi_col1: mi_cols,
149 mi_row0: 0,
150 mi_row1: mi_rows,
151 }
152 }
153}
154
155/// A frame's uniform tile grid (spec 5.9.15's `uniform_tile_spacing_flag`
156/// arm, mirrored from `ec_av1_syntax::frame::read_tile_info` so that what
157/// this encoder writes and what a decoder derives from the same two log2
158/// fields are the same rects). 64x64 superblocks only, which is the only
159/// size this encoder's sequence header signals.
160#[derive(Clone, Debug)]
161pub(crate) struct TileLayout {
162 pub(crate) cols_log2: u32,
163 pub(crate) rows_log2: u32,
164 /// Tile column starts in superblocks, `cols + 1` entries.
165 col_starts_sb: Vec<u32>,
166 /// Tile row starts in superblocks, `rows + 1` entries.
167 row_starts_sb: Vec<u32>,
168 mi_cols: u32,
169 mi_rows: u32,
170}
171
172impl TileLayout {
173 /// The layout `cols_log2`/`rows_log2` name for this frame's mi grid.
174 pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self {
175 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
176 let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2));
177 let starts = |total: u32, log2: u32| {
178 let step = total.div_ceil(1 << log2).max(1);
179 let mut v: Vec<u32> = (0..total).step_by(step as usize).collect();
180 v.push(total);
181 v
182 };
183 Self {
184 cols_log2,
185 rows_log2,
186 col_starts_sb: starts(sb_cols, cols_log2),
187 row_starts_sb: starts(sb_rows, rows_log2),
188 mi_cols,
189 mi_rows,
190 }
191 }
192
193 pub(crate) fn cols(&self) -> u32 {
194 self.col_starts_sb.len() as u32 - 1
195 }
196
197 pub(crate) fn rows(&self) -> u32 {
198 self.row_starts_sb.len() as u32 - 1
199 }
200
201 pub(crate) fn count(&self) -> usize {
202 (self.cols() * self.rows()) as usize
203 }
204
205 /// `MiColStarts`/`MiRowStarts` as the frame header carries them.
206 pub(crate) fn mi_col_starts(&self) -> Vec<u32> {
207 let mut v: Vec<u32> = self.col_starts_sb[..self.cols() as usize]
208 .iter()
209 .map(|sb| sb * SB_MI_W)
210 .collect();
211 v.push(self.mi_cols);
212 v
213 }
214
215 pub(crate) fn mi_row_starts(&self) -> Vec<u32> {
216 let mut v: Vec<u32> = self.row_starts_sb[..self.rows() as usize]
217 .iter()
218 .map(|sb| sb * SB_MI_W)
219 .collect();
220 v.push(self.mi_rows);
221 v
222 }
223
224 /// Tile `index` (row major, `TileNum`) as a rect.
225 pub(crate) fn rect(&self, index: usize) -> TileRect {
226 let (r, c) = (index / self.cols() as usize, index % self.cols() as usize);
227 let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]);
228 let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]);
229 TileRect {
230 sb_col0,
231 sb_col1,
232 sb_row0,
233 sb_row1,
234 mi_col0: sb_col0 * SB_MI_W,
235 mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols),
236 mi_row0: sb_row0 * SB_MI_W,
237 mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows),
238 }
239 }
240
241 /// The largest tile by mi area, `context_update_tile_id`'s own rule
242 /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both
243 /// name the biggest tile, whose end-of-tile tables the frame stores).
244 pub(crate) fn largest_tile(&self) -> usize {
245 (0..self.count())
246 .max_by_key(|&i| {
247 let t = self.rect(i);
248 ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64)
249 })
250 .unwrap_or(0)
251 }
252}
253
254/// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
255struct CdefIdxPlan {
256 /// The header's `cdef_bits`; never 0 while armed.
257 bits: u8,
258 /// Superblocks per row, the stride of `grid`.
259 sb_cols: usize,
260 /// One index per 64x64 superblock, in raster order.
261 grid: Vec<u8>,
262 /// The superblock whose literal was already written -- the decoder's
263 /// `cdef_transmitted`, which resets at every superblock and which coding
264 /// order (each superblock's blocks are contiguous) makes a single slot.
265 last: Option<usize>,
266}
267
268thread_local! {
269 static CDEF_IDX: std::cell::RefCell<Option<CdefIdxPlan>> =
270 const { std::cell::RefCell::new(None) };
271}
272
273/// Arms the next tile write with one `cdef_idx` per 64x64 superblock.
274/// `bits == 0` disarms (the header codes a single strength pair, so the tile
275/// carries no literal at all).
276pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
277 CDEF_IDX.with(|c| {
278 *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan { bits, sb_cols, grid, last: None });
279 });
280}
281
282thread_local! {
283 static SIGN_BIAS: std::cell::Cell<crate::mvstack::SignBiasTable> =
284 const { std::cell::Cell::new(crate::mvstack::NO_SIGN_BIAS) };
285}
286
287/// Arms the next tile write with this frame's `ref_frame_sign_bias` (spec
288/// 5.9.2), the table its MV-stack scans run under. Armed the same way
289/// [`arm_cdef_idx`]/[`arm_lr`] are -- and disarmed by the same guard -- so
290/// that a frame with a backward reference needs no new parameter on the four
291/// nested writer helpers between here and `find_mv_stack`. A frame that never
292/// names a future reference leaves this alone: all-`false` is what every
293/// stream this crate wrote before pyramids existed codes under.
294pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
295 SIGN_BIAS.with(|c| c.set(sign_bias));
296}
297
298thread_local! {
299 static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
300}
301
302/// Arms the next tile write with this frame's `allow_screen_content_tools`
303/// (spec 5.9.2), which is what makes every intra block carry the
304/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46
305/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/
306/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that
307/// never detected screen content writes exactly the stream it wrote before
308/// this lane.
309pub(crate) fn arm_screen(on: bool) {
310 SCREEN.with(|c| c.set(on));
311}
312
313fn screen_armed() -> bool {
314 SCREEN.with(std::cell::Cell::get)
315}
316
317thread_local! {
318 /// This frame header's `allow_intrabc` (spec 5.9.2), armed exactly like
319 /// [`SCREEN`]: with it every intra block of the tile carries a
320 /// `use_intrabc` symbol right after `skip`/`cdef`/`delta_q` (decode.rs
321 /// `read_intra_mode`), so a tile written without it and read with it
322 /// desyncs at the first block.
323 static INTRABC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
324 /// The mi grid the DV predictor is built off (decode.rs
325 /// `INTRABC_MI_GRID`/`record_intrabc_mi`): every coded block publishes
326 /// its own footprint into it, an intrabc one also its DV as an
327 /// `INTRA_FRAME` candidate. `Some` only while an `allow_intrabc` tile is
328 /// being written.
329 static INTRABC_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
330 const { std::cell::RefCell::new(None) };
331}
332
333/// Arms the frame's `allow_intrabc` bit for the next tile written on this
334/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
335pub(crate) fn arm_intrabc(on: bool) {
336 INTRABC.with(|c| c.set(on));
337}
338
339fn intrabc_armed() -> bool {
340 INTRABC.with(std::cell::Cell::get)
341}
342
343/// How many blocks this writer coded `use_intrabc == 1`, and the histogram of
344/// their DV magnitudes in full pels (index 1..=6 = 1, 2, 4, 8, 16, 32 pels
345/// and up, by the larger component) -- the fire count a gate prints so that
346/// "intrabc is on" is a measurement rather than a claim (class
347/// `gate-blind-to-feature`). Index 0 is the block count.
348static INTRABC_HITS: [std::sync::atomic::AtomicUsize; 7] =
349 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
350
351fn note_intrabc(dv: (i32, i32)) {
352 INTRABC_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
353 let px = (dv.0.abs() / 8).max(dv.1.abs() / 8).max(1) as usize;
354 let bucket = (usize::BITS - px.leading_zeros()) as usize;
355 INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
356}
357
358/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts
359/// to its own encode.
360#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
361pub(crate) fn take_intrabc_hits() -> [usize; 7] {
362 std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
363}
364
365thread_local! {
366 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
367 /// the same way `arm_sign_bias` arms the sign-bias table rather than
368 /// threaded through the five nested writer helpers between here and the
369 /// per-block mode syntax. `true` makes every inter block of size at least
370 /// 8x8 code a `comp_mode` symbol, exactly where decode.rs `read_comp_mode`
371 /// reads one.
372 static REFERENCE_SELECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
373}
374
375/// Arms the frame's `reference_select` bit for the next tile written on this
376/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
377pub(crate) fn arm_reference_select(on: bool) {
378 REFERENCE_SELECT.with(|c| c.set(on));
379}
380
381/// The compound half of a block's end-of-block neighbour record: nothing for
382/// a single-reference or intra block, and `record_compound_mi`'s overwrite of
383/// the ALTREF default for a compound one (this writer only codes
384/// `comp_group_idx == 0`, `compound_idx == 1`).
385fn record_block_compound(neighbours: &mut Neighbours, at_mi: (usize, usize), side: usize, block: &BlockCoeffs) {
386 if let Some(r1) = block.inter.and_then(|i| i.ref1) {
387 neighbours.record_compound_mi(at_mi, side, r1, 0, 1);
388 }
389}
390
391/// decode.rs' own `is_uni_comp_ref`: a pair is `UNIDIR_COMP_REFERENCE`
392/// exactly when both references sit on the same temporal side.
393fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
394 let backward =
395 |r: i8| (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&r);
396 backward(ref0) == backward(ref1)
397}
398
399thread_local! {
400 /// `(order_hint_bits, this frame's order hint, each reference's order
401 /// hint)` -- what `get_comp_index_context` (decode.rs) needs to context
402 /// the `compound_idx` symbol, armed the same way the sign-bias table is.
403 static ORDER_HINTS: std::cell::Cell<(u32, u32, [u32; 7])> =
404 const { std::cell::Cell::new((7, 0, [0; 7])) };
405}
406
407/// Arms this frame's order hints for the next tile written on this thread.
408pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) {
409 ORDER_HINTS.with(|c| c.set((bits, order_hint, hints)));
410}
411
412/// What [`arm_order_hints`] last armed: `(order_hint_bits, order_hint,
413/// ref_order_hints)`, for the encoder's own per-reference distance.
414pub(crate) fn order_hints() -> (u32, u32, [u32; 7]) {
415 ORDER_HINTS.with(std::cell::Cell::get)
416}
417
418/// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec
419/// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref`
420/// trees), symbol for symbol at the same contexts -- which are, as that
421/// function's own doc records, `single_ref_p1_ctx`..`single_ref_p6_ctx`/
422/// `uni_comp_ref_p1_ctx` under libaom's compound names.
423///
424/// # Errors
425/// A pair this writer never forms (its `ref0` is not `LAST_FRAME`).
426fn write_compound_ref_frames(
427 enc: &mut SymbolEncoder,
428 cdfs: &mut Cdfs,
429 above: Option<crate::mvstack::NeighbourRef>,
430 left: Option<crate::mvstack::NeighbourRef>,
431 above_ref: i8,
432 left_ref: i8,
433 (ref0, ref1): (i8, i8),
434) -> Result<()> {
435 use crate::mvstack::{
436 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
437 LAST_FRAME, comp_reference_type_ctx, single_ref_p1_ctx, single_ref_p2_ctx,
438 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
439 uni_comp_ref_p1_ctx,
440 };
441 let a = (above_ref > 0).then_some(above_ref);
442 let l = (left_ref > 0).then_some(left_ref);
443 let a1 = above.and_then(|n| n.ref1);
444 let l1 = left.and_then(|n| n.ref1);
445 let unidir = is_uni_comp_ref(ref0, ref1);
446 enc.symbol(
447 usize::from(!unidir),
448 &mut cdfs.comp_ref_type[comp_reference_type_ctx(above, left)],
449 );
450 if unidir {
451 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
452 enc.symbol(
453 usize::from(both_backward),
454 &mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0],
455 );
456 if both_backward {
457 return Ok(());
458 }
459 if ref0 != LAST_FRAME {
460 return Err(Error::unsupported(
461 "AV1 tile",
462 "a unidirectional compound pair this writer does not form",
463 ));
464 }
465 let past_last2 = ref1 != LAST2_FRAME;
466 enc.symbol(
467 usize::from(past_last2),
468 &mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
469 );
470 if past_last2 {
471 enc.symbol(
472 usize::from(ref1 == GOLDEN_FRAME),
473 &mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
474 );
475 }
476 return Ok(());
477 }
478 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
479 enc.symbol(
480 usize::from(far),
481 &mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0],
482 );
483 if far {
484 enc.symbol(
485 usize::from(ref0 == GOLDEN_FRAME),
486 &mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
487 );
488 } else {
489 enc.symbol(
490 usize::from(ref0 == LAST2_FRAME),
491 &mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1],
492 );
493 }
494 let is_altref = ref1 == ALTREF_FRAME;
495 enc.symbol(
496 usize::from(is_altref),
497 &mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0],
498 );
499 if !is_altref {
500 enc.symbol(
501 usize::from(ref1 == ALTREF2_FRAME),
502 &mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1],
503 );
504 }
505 Ok(())
506}
507
508/// Per-mode and per-pair fire counts of [`write_compound_block`], for the
509/// gate's own census (gate-blind-to-feature): modes indexed by the spec's
510/// `INTER_COMPOUND_MODES`, pairs by `ref1` (`LAST`..`ALTREF`).
511static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
512 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
513static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =
514 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
515
516/// Takes and clears the compound mode histogram.
517#[cfg(test)]
518pub(crate) fn take_compound_mode_hits() -> [usize; 8] {
519 std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
520}
521
522/// Takes and clears the compound pair histogram, indexed by the SECOND
523/// reference (`LAST` = 0 .. `ALTREF` = 6).
524#[cfg(test)]
525pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
526 std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
527}
528
529/// Per-SIZE fire counts of [`write_compound_block`], indexed by
530/// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
531/// 32x32-only tool, so the share by size is what says whether the leaf
532/// candidates fire at all (gate-blind-to-feature).
533static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
534 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
535
536/// Takes and clears the compound size histogram.
537#[cfg(test)]
538pub(crate) fn take_compound_size_hits() -> [usize; 4] {
539 std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
540}
541
542/// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
543/// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
544/// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
545/// order. Returns the two motion vectors the decoder derives (what the MI
546/// grid must record) and whether the mode was a `NEW*` one.
547///
548/// Only the modes [`InterMode::compound_index`] names are written, and
549/// only the `comp_group_idx == 0`, `compound_idx == 1` blend (spec
550/// `COMPOUND_AVERAGE`) -- masked compound and the distance-weighted blend are
551/// not searched.
552///
553/// # Errors
554/// As [`write_mv`], or a pair/mode this writer does not form.
555#[allow(clippy::too_many_arguments)]
556fn write_compound_block(
557 enc: &mut SymbolEncoder,
558 cdfs: &mut Cdfs,
559 neighbours: &Neighbours,
560 grid: &crate::mvstack::MiGrid,
561 (mi_row, mi_col): (usize, usize),
562 (bw4, bh4): (usize, usize),
563 (has_above, has_left): (bool, bool),
564 info: InterInfo,
565 (mi_cols, mi_rows): (usize, usize),
566) -> Result<((i32, i32), (i32, i32), bool)> {
567 let (Some(ref1), Some(mode)) = (info.ref1, info.mode.compound_index()) else {
568 return Err(Error::unsupported(
569 "AV1 tile",
570 "a compound block needs a second reference and a compound mode",
571 ));
572 };
573 let above = has_above.then(|| neighbours.above_nbr(mi_col));
574 let left = has_left.then(|| neighbours.left_nbr(mi_row));
575 write_compound_ref_frames(
576 enc,
577 cdfs,
578 above,
579 left,
580 neighbours.above_ref[mi_col],
581 neighbours.left_ref[mi_row],
582 (info.ref_frame, ref1),
583 )?;
584 let stack = crate::mvstack::find_mv_stack_compound(
585 grid,
586 mi_row,
587 mi_col,
588 bw4,
589 bh4,
590 (info.ref_frame, ref1),
591 mi_cols,
592 mi_rows,
593 grid.sign_bias_table(),
594 &[(0, 0); 7],
595 None,
596 );
597 let ctx = crate::cdf::COMPOUND_MODE_CTX_MAP[stack.ref_mv_ctx >> 1][stack.new_mv_ctx.min(4)];
598 if crate::envflags::env_flag!("EC_TRACE_MODE") {
599 eprintln!(
600 "EC_WCOMP mi_row={mi_row} mi_col={mi_col} mode={mode} ref0={} ref1={ref1} ctx={ctx} new_mv_ctx={} ref_mv_ctx={} stack={}",
601 info.ref_frame, stack.new_mv_ctx, stack.ref_mv_ctx, stack.entries.len()
602 );
603 }
604 enc.symbol(mode, &mut cdfs.inter_compound_mode[ctx]);
605 // `assign_compound_mv`'s own DRL half: `NEW_NEWMV` walks from index 0,
606 // the two derived modes code no index at all.
607 let mvs = match info.mode {
608 InterMode::NearestNearestMv => stack.nearest_mv,
609 InterMode::GlobalGlobalMv => ((0, 0), (0, 0)),
610 InterMode::NearNearMv => {
611 // decode.rs `assign_compound_mv`'s second DRL loop: the index
612 // starts at 1 and the mode's own `ref_mv_idx` is `idx - 1`, so
613 // this walk starts at 1 too and reads entry `ref_mv_idx + 1`.
614 let idx = usize::from(info.ref_mv_idx) + 1;
615 let mut walk = 1usize;
616 while walk < 3 && stack.entries.len() > walk + 1 {
617 let advance = walk < idx;
618 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]);
619 if !advance {
620 break;
621 }
622 walk += 1;
623 }
624 stack
625 .entries
626 .get(idx)
627 .map_or(stack.near_mv, |e| (e.mv0, e.mv1))
628 }
629 InterMode::NearestNewMv | InterMode::NewNearestMv => {
630 // Neither mode codes a DRL index (the decoder leaves `ref_mv_idx`
631 // at 0): the NEAREST half is derived, the NEW half codes a
632 // residual against stack entry 0.
633 let base = stack
634 .entries
635 .first()
636 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
637 if matches!(info.mode, InterMode::NearestNewMv) {
638 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
639 (stack.nearest_mv.0, info.mv1)
640 } else {
641 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
642 (info.mv, stack.nearest_mv.1)
643 }
644 }
645 _ => {
646 let idx = usize::from(info.ref_mv_idx);
647 let mut walk = 0usize;
648 while walk < 2 && stack.entries.len() > walk + 1 {
649 let advance = walk < idx;
650 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]);
651 if !advance {
652 break;
653 }
654 walk += 1;
655 }
656 let base = stack
657 .entries
658 .get(idx)
659 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
660 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
661 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
662 (info.mv, info.mv1)
663 }
664 };
665 // spec 5.11.25's `comp_group_idx`/`compound_idx` are NOT coded: this
666 // crate's sequence header carries `enable_masked_compound = false` and
667 // `enable_jnt_comp = false` (encode.rs), and decode.rs reads neither
668 // symbol under those bits -- it infers `comp_group_idx = 0`,
669 // `compound_idx = 1` (the simple average), which is the only blend this
670 // writer forms anyway. A lane that turns either sequence bit on has to
671 // write the matching symbol here, at
672 // `get_comp_group_idx_context`/`get_comp_index_context`'s contexts (which
673 // is what `Neighbours::above_comp_group_idx`/`above_compound_idx` and the
674 // armed order hints below are already kept for).
675 let _ = ORDER_HINTS.with(std::cell::Cell::get);
676 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
677 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
678 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
679 COMPOUND_SIZE_HITS[(bw4.max(1).trailing_zeros() as usize).min(3)]
680 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
681 if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {
682 eprintln!(
683 "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",
684 info.mv, info.mv1, mvs.0, mvs.1
685 );
686 }
687 // decode.rs' own `is_new_mv` for a compound block: modes 2, 3, 4, 5, 7.
688 Ok((
689 mvs.0,
690 mvs.1,
691 matches!(
692 info.mode,
693 InterMode::NewNewMv | InterMode::NearestNewMv | InterMode::NewNearestMv
694 ),
695 ))
696}
697
698/// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's
699/// `comp_mode`): on a `reference_select` frame every inter block whose size
700/// allows compound (`is_comp_ref_allowed`, always true here -- this writer's
701/// smallest leaf is 8x8) names SINGLE or COMPOUND, at
702/// `mvstack::reference_mode_ctx`'s own context off the same two neighbour
703/// bands decode.rs builds its `NeighbourRef` pair from.
704fn write_comp_mode(
705 enc: &mut SymbolEncoder,
706 cdfs: &mut Cdfs,
707 neighbours: &Neighbours,
708 (mi_r, mi_c): (usize, usize),
709 (has_above, has_left): (bool, bool),
710 compound: bool,
711) {
712 if !REFERENCE_SELECT.with(std::cell::Cell::get) {
713 return;
714 }
715 let above = has_above.then(|| neighbours.above_nbr(mi_c));
716 let left = has_left.then(|| neighbours.left_nbr(mi_r));
717 let ctx = crate::mvstack::reference_mode_ctx(above, left);
718 if crate::envflags::env_flag!("EC_TRACE_MODE") {
719 eprintln!(
720 "EC_WCM mi=({mi_r},{mi_c}) ctx={ctx} val={} a={:?} l={:?}",
721 usize::from(compound),
722 above.map(|n| (n.is_inter, n.ref0, n.ref1)),
723 left.map(|n| (n.is_inter, n.ref0, n.ref1))
724 );
725 }
726 enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]);
727}
728
729/// Clears the armed plan when the tile writer that consumed it returns.
730struct CdefIdxGuard;
731
732impl Drop for CdefIdxGuard {
733 fn drop(&mut self) {
734 CDEF_IDX.with(|c| *c.borrow_mut() = None);
735 LR_PLAN.with(|c| *c.borrow_mut() = None);
736 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
737 SCREEN.with(|c| c.set(false));
738 REFERENCE_SELECT.with(|c| c.set(false));
739 INTRABC.with(|c| c.set(false));
740 INTRABC_GRID.with(|c| *c.borrow_mut() = None);
741 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
742 }
743}
744
745/// `read_cdef`'s write side, called right after every block's `skip` symbol:
746/// writes this superblock's `cdef_idx` literal the first time a non-skip
747/// block of it is coded. `mi` is the block's own position in 4x4 mode-info
748/// units.
749fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) {
750 if skip {
751 return;
752 }
753 CDEF_IDX.with(|c| {
754 let mut plan = c.borrow_mut();
755 let Some(plan) = plan.as_mut() else { return };
756 let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16);
757 if plan.last == Some(sb) {
758 return;
759 }
760 plan.last = Some(sb);
761 enc.literal(
762 u32::from(plan.grid.get(sb).copied().unwrap_or(0)),
763 u32::from(plan.bits),
764 );
765 });
766}
767
768/// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
769/// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
770/// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
771/// same variable, so the two traces line up symbol for symbol. Checked once
772/// per process, so unset (the default) costs one atomic load per call and no
773/// allocation. Only the real tile writer below calls this -- the mode/rate
774/// search's own trial encoders never do -- so the trace does not need the
775/// throwaway-encoder gating a whole-encoder trace would.
776fn ec_rng_trace(msg: impl FnOnce() -> String) {
777 use std::sync::atomic::{AtomicU8, Ordering};
778 static ON: AtomicU8 = AtomicU8::new(2); // 2 = unknown, 1 = on, 0 = off
779 let on = match ON.load(Ordering::Relaxed) {
780 2 => {
781 let on = u8::from(std::env::var_os("EC_RNG").is_some());
782 ON.store(on, Ordering::Relaxed);
783 on
784 }
785 v => v,
786 };
787 if on == 1 {
788 eprintln!("{}", msg());
789 }
790}
791
792/// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
793const PARTITION_NONE: usize = 0;
794/// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants.
795const PARTITION_SPLIT: usize = 3;
796
797/// The partition types whose probability mass the split-or-horizontal flag of
798/// a superblock hanging off the bottom of the frame gathers (spec 9.3,
799/// `partition_gather_vert_alike`): the flag says split, so everything vertical
800/// or split lands on it.
801const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
802
803/// The same for a superblock hanging off the right-hand edge
804/// (`partition_gather_horz_alike`).
805const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
806
807/// Mode-info units across a 32x32 block.
808pub(crate) const BLOCK_MI: u32 = SB_MI / 2;
809
810/// Mode-info units across a 16x16 block, the smallest this crate's key-frame
811/// writer codes.
812pub(crate) const SUB_MI: u32 = BLOCK_MI / 2;
813
814/// spec `decode_partition`'s `hasRows`/`hasCols` (5.11.4), recomputed at
815/// whichever block size is asking: a block of `side_mi` mode-info units at mi
816/// position `pos` may be coded unsplit (its own `PARTITION_NONE`) only when
817/// this is true in both directions -- the frame's *true* size can put the
818/// boundary inside a superblock, a 32x32 quadrant or (since this writer's
819/// smallest block is 16x16) even a leaf, and each level must ask again with
820/// its own half, not just once at the superblock.
821pub(crate) fn has_half(pos: u32, side_mi: u32, bound: u32) -> bool {
822 pos + side_mi / 2 < bound
823}
824
825/// The number of 32x32 block columns/rows a frame whose *true* (unpadded)
826/// size gives `mi_cols`/`mi_rows` is coded over: every block whose mi origin
827/// (`col * BLOCK_MI`) is inside the true bound is coded, so this is a
828/// ceiling, not the exact division a block-aligned frame would give. Shared
829/// by the tile writer's own iteration and by [`crate::encode`]'s block/
830/// superblock generation, which must agree with it exactly.
831pub(crate) fn block_grid(mi_cols: u32, mi_rows: u32) -> (u32, u32) {
832 (mi_cols.div_ceil(BLOCK_MI), mi_rows.div_ceil(BLOCK_MI))
833}
834/// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode.
835const DC_PRED: usize = 0;
836
837/// `V_PRED` (spec 6.10.2), the first of the eight directional intra modes and
838/// so the first mode that carries an angle delta.
839const V_PRED: usize = 1;
840
841/// `H_PRED`, which predicts every row from the column to the block's left.
842#[cfg(test)]
843const H_PRED: usize = 2;
844
845/// The last directional mode, `D67_PRED`.
846const D67_PRED: usize = 8;
847
848/// The number of intra modes a key frame's luma block chooses from,
849/// `INTRA_MODES` (spec 3).
850const INTRA_MODES: usize = 13;
851
852/// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts
853/// its neighbours in when they pick the CDF for the next block's mode.
854pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0];
855
856/// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
857/// +3, so `MAX_ANGLE_DELTA` is the middle of it.
858const ANGLE_DELTA_ZERO: usize = 3;
859/// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
860const SB_MI: u32 = 16;
861
862/// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
863const NUM_BASE_LEVELS: i32 = 2;
864/// Where DCT_DCT sits in the spec's `Tx_Type_Intra_Inv_Set2`, the set a 16x16
865/// intra luma transform picks its type from.
866const TX_TYPE_DCT_DCT_SET2: usize = 1;
867/// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
868/// Golomb tail takes over.
869const COEFF_BASE_RANGE: i32 = 12;
870/// `BR_CDF_SIZE - 1` (spec 3): the largest increment one base-range symbol
871/// carries.
872const BR_STEP: i32 = 3;
873/// The largest level the base and base-range syntax carry between them.
874/// Anything above it is written as a Golomb tail on top of this.
875const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
876/// The largest level this writer codes. The Golomb tail is a length in unary
877/// followed by that many bits, and the spec's decoder reads at most twenty of
878/// each, so a level a decoder cannot read back is refused rather than written.
879const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
880
881/// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s
882/// leading index) a frame's `base_q_idx` picks its default CDFs from.
883/// [`crate::cdf`] carries all four, one constant set per context.
884pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
885 match base_q_idx {
886 0..=20 => 0,
887 21..=60 => 1,
888 61..=120 => 2,
889 _ => 3,
890 }
891}
892
893/// Both writers here code whole superblocks only: a partial one forces the
894/// partition syntax down the block tree, which they do not code yet.
895/// The probability the CDF gives one symbol on its own.
896fn element_prob(cdf: &[u16], element: usize) -> u16 {
897 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
898}
899
900/// The two-symbol CDF a partial superblock's partition flag is coded with: the
901/// mass of the listed partition types becomes the probability of a split, and
902/// the rest is the one partition the frame edge still allows.
903fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
904 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
905 [32768 - split, 32768, 0]
906}
907
908fn check_superblocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
909 if mi_cols == 0
910 || mi_rows == 0
911 || !mi_cols.is_multiple_of(SB_MI)
912 || !mi_rows.is_multiple_of(SB_MI)
913 {
914 return Err(Error::unsupported(
915 "AV1 tile",
916 "a key frame is written only for frames that are a whole number \
917 of 64x64 superblocks",
918 ));
919 }
920 Ok(())
921}
922
923/// Writes the payload of a one-tile key frame in which every superblock is a
924/// skipped 64x64 DC-predicted block.
925///
926/// `mi_cols` and `mi_rows` are the frame's dimensions in 4x4 mode-info units,
927/// as the frame header carries them.
928///
929/// # Errors
930/// Returns an error when the frame is not a whole number of 64x64 superblocks:
931/// a partial superblock forces the partition syntax down the block tree, which
932/// this writer does not code yet.
933pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {
934 check_superblocks(mi_cols, mi_rows)?;
935 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
936
937 let mut enc = SymbolEncoder::new();
938 for r in 0..sb_rows {
939 for c in 0..sb_cols {
940 // decode_partition (spec 5.11.4). Every neighbour is a 64x64 block,
941 // whose stored partition context has a zero bit at this block
942 // size, so the context is 0 wherever the block sits.
943 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
944
945 // intra_frame_mode_info (spec 5.11.16). Segmentation, delta q,
946 // delta lf, palette, filter intra and intrabc are all off in the
947 // frame header, and a skipped block codes no CDEF index, so the
948 // block is three symbols: the skip flag and the two modes.
949 let skip_ctx = usize::from(r > 0) + usize::from(c > 0);
950 enc.symbol_fixed(1, &cdf::SKIP[skip_ctx]);
951 // Both neighbours are DC-predicted, and an unavailable neighbour
952 // counts as DC too, so both mode contexts are 0.
953 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
954 // Chroma from luma is only offered up to 32x32, so the CFL-free
955 // table is the one a 64x64 block reads.
956 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
957
958 // read_block_tx_size codes nothing while the frame's tx_mode is
959 // TX_MODE_LARGEST, and a skipped block has no residual, so the
960 // block ends here.
961 }
962 }
963 Ok(enc.finish())
964}
965
966/// Writes the payload of a one-tile key frame in which every superblock is a
967/// 64x64 DC-predicted block carrying one luma DC coefficient of `dc_level` and
968/// no chroma residual.
969///
970/// `dc_level` is a quantised level, not a sample value: the decoder multiplies
971/// it by the frame's DC quantiser and inverse-transforms it over the whole
972/// block, so the picture it makes is a flat grey some distance either side of
973/// the mid-grey a zero level gives. `base_q_idx` is the frame header's, and
974/// picks the coefficient CDFs.
975///
976/// # Errors
977/// As [`dc_key_frame_tile_levels`], which this is the one-level case of.
978pub fn dc_key_frame_tile(
979 mi_cols: u32,
980 mi_rows: u32,
981 base_q_idx: u8,
982 dc_level: i32,
983) -> Result<Vec<u8>> {
984 check_superblocks(mi_cols, mi_rows)?;
985 let blocks = ((mi_cols / SB_MI) * (mi_rows / SB_MI)) as usize;
986 dc_key_frame_tile_levels(mi_cols, mi_rows, base_q_idx, &vec![dc_level; blocks])
987}
988
989/// Writes the payload of a one-tile key frame carrying one luma DC coefficient
990/// per superblock, `levels` giving them in the raster order the superblocks are
991/// coded in.
992///
993/// Each superblock decodes to a flat block of its own grey, so a frame written
994/// here is a grid of greys the caller chooses — which is what makes the sign
995/// context observable: a block's sign context is read off its coded neighbours,
996/// and a frame whose levels differ in sign exercises the three-way split that a
997/// single-sign frame cannot reach.
998///
999/// # Errors
1000/// Returns an error when the frame is not a whole number of 64x64 superblocks,
1001/// when `levels` does not carry exactly one level per superblock, when a level
1002/// is outside the range the base and base-range syntax carry (`-14..=14`
1003/// without zero).
1004pub fn dc_key_frame_tile_levels(
1005 mi_cols: u32,
1006 mi_rows: u32,
1007 base_q_idx: u8,
1008 levels: &[i32],
1009) -> Result<Vec<u8>> {
1010 check_superblocks(mi_cols, mi_rows)?;
1011 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
1012 check_levels(levels, (sb_cols * sb_rows) as usize)?;
1013 let q_ctx = q_ctx_of(base_q_idx);
1014 let txb_skip_luma_64 = crate::cdf_state::pick(
1015 q_ctx,
1016 cdf::TXB_SKIP_LUMA_64_Q0,
1017 cdf::TXB_SKIP_LUMA_64_Q1,
1018 cdf::TXB_SKIP_LUMA_64,
1019 cdf::TXB_SKIP_LUMA_64_Q3,
1020 );
1021 let base_eob_luma_64_dc = crate::cdf_state::pick(
1022 q_ctx,
1023 cdf::COEFF_BASE_EOB_LUMA_64_Q0[0],
1024 cdf::COEFF_BASE_EOB_LUMA_64_Q1[0],
1025 cdf::COEFF_BASE_EOB_LUMA_64[0],
1026 cdf::COEFF_BASE_EOB_LUMA_64_Q3[0],
1027 );
1028 let txb_skip_chroma_32_none = crate::cdf_state::pick(
1029 q_ctx,
1030 cdf::TXB_SKIP_CHROMA_32_Q0[0],
1031 cdf::TXB_SKIP_CHROMA_32_Q1[0],
1032 cdf::TXB_SKIP_CHROMA_32[0],
1033 cdf::TXB_SKIP_CHROMA_32_Q3[0],
1034 );
1035
1036 // The sign of the DC each coded block left behind, for the two neighbours
1037 // the sign context is read from: one row of them above, and the block to
1038 // the left, which is dropped at the start of every superblock row the way a
1039 // decoder clears its left context there.
1040 let mut above: Vec<Option<bool>> = vec![None; sb_cols as usize];
1041 let mut enc = SymbolEncoder::new();
1042 for r in 0..sb_rows {
1043 let mut left: Option<bool> = None;
1044 for c in 0..sb_cols {
1045 let dc_level = levels[(r * sb_cols + c) as usize];
1046 let negative = dc_level < 0;
1047
1048 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
1049
1050 // Nothing is skipped now, so every neighbour's skip flag is 0 and
1051 // the skip context stays 0 across the frame.
1052 enc.symbol_fixed(0, &cdf::SKIP[0]);
1053 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
1054 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
1055
1056 write_dc_coeffs(
1057 &mut enc,
1058 dc_level,
1059 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)),
1060 q_ctx,
1061 &txb_skip_luma_64,
1062 &base_eob_luma_64_dc,
1063 );
1064
1065 // Both chroma transform blocks are all-zero. Their planes carry no
1066 // coded coefficient anywhere in the frame, so the neighbour halves
1067 // of their context stay 0 and only the offset for a transform block
1068 // that covers its whole plane block is left: context 7.
1069 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
1070 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
1071
1072 above[c as usize] = Some(negative);
1073 left = Some(negative);
1074 }
1075 }
1076 Ok(enc.finish())
1077}
1078
1079/// Writes the payload of a one-tile key frame in which every superblock is
1080/// split into four 32x32 DC-predicted blocks, each carrying one luma DC
1081/// coefficient and no chroma residual.
1082///
1083/// `levels` gives one level per 32x32 block in raster order across the frame,
1084/// so the grid is twice as wide and twice as tall as the superblock grid. The
1085/// blocks are coded in the z-order a superblock's split walks, but every
1086/// block's neighbours above and to its left are coded before it either way, so
1087/// the picture reads in raster order.
1088///
1089/// # Errors
1090/// As [`dc_key_frame_tile_levels`], with `levels` sized for the 32x32 grid.
1091pub fn split_dc_key_frame_tile(
1092 mi_cols: u32,
1093 mi_rows: u32,
1094 base_q_idx: u8,
1095 levels: &[i32],
1096) -> Result<Vec<u8>> {
1097 check_superblocks(mi_cols, mi_rows)?;
1098 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
1099 let (cols, rows) = (sb_cols * 2, sb_rows * 2);
1100 check_levels(levels, (cols * rows) as usize)?;
1101 let q_ctx = q_ctx_of(base_q_idx);
1102 let txb_skip_luma_32 = crate::cdf_state::pick(
1103 q_ctx,
1104 cdf::TXB_SKIP_LUMA_32_Q0,
1105 cdf::TXB_SKIP_LUMA_32_Q1,
1106 cdf::TXB_SKIP_LUMA_32,
1107 cdf::TXB_SKIP_LUMA_32_Q3,
1108 );
1109 let base_eob_luma_32 = crate::cdf_state::pick(
1110 q_ctx,
1111 cdf::COEFF_BASE_EOB_LUMA_32_Q0[0],
1112 cdf::COEFF_BASE_EOB_LUMA_32_Q1[0],
1113 cdf::COEFF_BASE_EOB_LUMA_32[0],
1114 cdf::COEFF_BASE_EOB_LUMA_32_Q3[0],
1115 );
1116 let txb_skip_chroma_16_0 = crate::cdf_state::pick(
1117 q_ctx,
1118 cdf::TXB_SKIP_CHROMA_16_Q0[0],
1119 cdf::TXB_SKIP_CHROMA_16_Q1[0],
1120 cdf::TXB_SKIP_CHROMA_16[0],
1121 cdf::TXB_SKIP_CHROMA_16_Q3[0],
1122 );
1123
1124 let mut above: Vec<Option<bool>> = vec![None; cols as usize];
1125 let mut left: Vec<Option<bool>> = vec![None; rows as usize];
1126
1127 let mut enc = SymbolEncoder::new();
1128 for sb_r in 0..sb_rows {
1129 // A decoder clears its left context at the start of every superblock
1130 // row, and so does the partition context the 64x64 symbol reads.
1131 left.iter_mut().for_each(|l| *l = None);
1132 for sb_c in 0..sb_cols {
1133 // The partition context of a 64x64 block reads the bit its
1134 // neighbours' block size sets at this depth: a 32x32 neighbour sets
1135 // it, and an uncoded one leaves it clear, so the context is just
1136 // which neighbours exist. The 32x32 blocks below read a bit their
1137 // own size leaves clear, so their context is 0 throughout.
1138 // Every superblock here is split, so an existing neighbour always
1139 // sets that bit.
1140 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
1141 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
1142
1143 for quadrant in 0..4 {
1144 let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
1145 let dc_level = levels[(r * cols + c) as usize];
1146 let negative = dc_level < 0;
1147
1148 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
1149 enc.symbol_fixed(0, &cdf::SKIP[0]);
1150 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
1151 // Chroma from luma is offered up to 32x32, so the block reads
1152 // the wider table even though it does not take the mode.
1153 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL[DC_PRED]);
1154
1155 write_dc_coeffs(
1156 &mut enc,
1157 dc_level,
1158 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])),
1159 q_ctx,
1160 &txb_skip_luma_32,
1161 &base_eob_luma_32,
1162 );
1163 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
1164 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
1165
1166 above[c as usize] = Some(negative);
1167 left[r as usize] = Some(negative);
1168 }
1169 }
1170 }
1171 Ok(enc.finish())
1172}
1173
1174/// One quantised coefficient of a transform block.
1175///
1176/// `row` and `col` are its position in the transform it belongs to — 32x32 for
1177/// luma, 16x16 for each chroma plane — not in the picture: a coefficient at
1178/// row 0 varies along the picture's width and one at column 0 along its
1179/// height, and the coefficient at the origin is the DC the block's average
1180/// sample value rides on.
1181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1182pub struct Coeff {
1183 /// The coefficient's row in the transform.
1184 pub row: u8,
1185 /// The coefficient's column in the transform.
1186 pub col: u8,
1187 /// Its quantised level, which the base and base-range syntax carry for
1188 /// magnitudes up to [`MAX_LEVEL`].
1189 pub level: i32,
1190}
1191
1192/// The coefficients of one coded block: a 32x32 luma transform and, at 4:2:0,
1193/// the 16x16 transform each chroma plane covers the same area with.
1194#[derive(Clone, Debug, Default, PartialEq, Eq)]
1195pub struct BlockCoeffs {
1196 /// The luma transform's coefficients.
1197 pub luma: Vec<Coeff>,
1198 /// The U plane's.
1199 pub u: Vec<Coeff>,
1200 /// The V plane's.
1201 pub v: Vec<Coeff>,
1202 /// The luma intra mode the block is predicted with, one of the thirteen
1203 /// modes a key frame codes (`DC_PRED` is zero, which is what
1204 /// [`Default`] and a plain coefficient list give).
1205 pub mode: u8,
1206 /// The chroma intra mode both chroma planes are predicted with (spec
1207 /// `uv_mode`, one symbol for the pair). `DC_PRED` is zero, which is what
1208 /// [`Default`] gives; a non-`DC_PRED` mode also changes the transform
1209 /// type the decoder derives for chroma (`Intra_Mode_To_Tx_Type`, spec
1210 /// 9.3), which is never coded as a symbol.
1211 pub uv_mode: u8,
1212 /// Whether the block carries no residual at all (spec `skip`). An intra
1213 /// block may still be skipped; `false` (the [`Default`]) codes whatever
1214 /// `luma`/`u`/`v` carry.
1215 pub skip: bool,
1216 /// The block's inter mode and motion vector, or `None` for an intra
1217 /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key
1218 /// frame writers never read this field.
1219 pub inter: Option<InterInfo>,
1220 /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect),
1221 /// each with its own 8x8 luma transform and 4x4 chroma transforms, in
1222 /// raster order among the leaves that are inside the true frame. `Some`
1223 /// overrides this `BlockCoeffs`'s own `luma`/`u`/`v`/`mode`, which are left
1224 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
1225 /// per-quadrant fields are unused.
1226 pub eight: Option<Vec<BlockCoeffs>>,
1227 /// The luma palette this block is predicted with (spec 5.11.46
1228 /// `palette_mode_info`), or `None` for an ordinary intra block. Only a
1229 /// `DC_PRED` block on a frame whose header set
1230 /// `allow_screen_content_tools` may carry one, and it forces
1231 /// `tx_depth` to zero (the whole block is one transform over the
1232 /// palette's own prediction).
1233 pub palette: Option<PaletteY>,
1234 /// The chroma palette this block's two chroma planes are predicted with
1235 /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a
1236 /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry
1237 /// one; it is independent of [`Self::palette`] (either, both or neither).
1238 pub palette_uv: Option<PaletteUv>,
1239 /// How many times this block's luma transform is halved under
1240 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
1241 /// block). Read only by the writers a `tx_select` frame calls; a
1242 /// `TxMode::Largest` frame codes no symbol and leaves this at zero.
1243 /// `luma` then carries the whole block's levels in BLOCK coordinates,
1244 /// which the writer slices per transform unit.
1245 pub tx_depth: u8,
1246 /// This block's intra block-copy vector (spec 5.11.13 `use_intrabc` ->
1247 /// `assign_dv`), in the spec's 1/8-pel `(row, col)` units, or `None` for
1248 /// an ordinary intra block. Only a key frame whose header set
1249 /// `allow_intrabc` ([`arm_intrabc`]) may carry one; the block is then
1250 /// coded `skip` with no residual, no mode, no palette -- exactly what
1251 /// decode.rs `read_intra_mode` reads back and returns early on.
1252 ///
1253 /// lane-av1ibc corner-cut, ceiling named: a residual-carrying intrabc
1254 /// block needs the INTER coefficient tables plus the var-tx tree
1255 /// decode.rs `decode_block`'s `intrabc_vartx` arm reads; the upgrade path
1256 /// is to route the block through [`write_tx_syntax_inter`] instead of
1257 /// returning early here.
1258 pub dv: Option<(i32, i32)>,
1259}
1260
1261/// A block's luma palette: its base colours (ascending, only the first
1262/// `size` entries are real) and the per-pixel colour-index map, `side*side`
1263/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back
1264/// out of the stream.
1265#[derive(Clone, Debug, Default, PartialEq, Eq)]
1266pub struct PaletteY {
1267 /// How many base colours, 2..=8 (spec `PaletteSizeY`).
1268 pub size: u8,
1269 /// The base colours, ascending.
1270 pub colors: [u16; 8],
1271 /// Which colour each pixel takes, row-major over the block's own side.
1272 pub map: Vec<u8>,
1273}
1274
1275/// As [`PaletteY`], for a block's chroma palette -- one colour-index map
1276/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes
1277/// are co-located after 4:2:0 subsampling) plus each plane's own base
1278/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of
1279/// the stream.
1280#[derive(Clone, Debug, Default, PartialEq, Eq)]
1281pub struct PaletteUv {
1282 /// How many base colours, 2..=8 (spec `PaletteSizeUV`).
1283 pub size: u8,
1284 /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv`
1285 /// merges the cached and transmitted lists as two ascending runs, and its
1286 /// delta form only ever steps upwards.
1287 pub u_colors: [u16; 8],
1288 /// V's base colours, in the same cluster order as [`Self::u_colors`] --
1289 /// the shared map indexes both, and V's own coding needs no ordering.
1290 pub v_colors: [u16; 8],
1291 /// Which colour each chroma pixel takes, row-major over the subsampled
1292 /// block's own `(side / 2).max(4)` side.
1293 pub map: Vec<u8>,
1294}
1295
1296/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
1297/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
1298/// [`write_inter_mode`] with the decoder's own contexts.
1299#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1300pub enum InterMode {
1301 /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
1302 NearestMv,
1303 /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names
1304 /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode).
1305 NearMv,
1306 /// `GLOBALMV`: the identity global model's zero vector, two symbols and
1307 /// no MV at all.
1308 GlobalMv,
1309 /// `NEWMV`: codes `mv` as a residual against the stack entry
1310 /// [`InterInfo::ref_mv_idx`] names.
1311 NewMv,
1312 /// `NEAREST_NEARESTMV`: both sides take the compound stack's own nearest
1313 /// pair, no residual, no DRL.
1314 NearestNearestMv,
1315 /// `NEAR_NEARMV`: both sides take compound stack entry
1316 /// [`InterInfo::ref_mv_idx`]` + 1` (decode.rs `assign_compound_mv`'s own
1317 /// `ref_mv_idx + 1`), reached by a DRL walk that starts at index 1.
1318 NearNearMv,
1319 /// `NEAREST_NEWMV`: the first side takes the stack's nearest vector, the
1320 /// second codes a residual against stack entry 0.
1321 NearestNewMv,
1322 /// `NEW_NEARESTMV`: the first side codes a residual against stack entry 0,
1323 /// the second takes the stack's nearest vector.
1324 NewNearestMv,
1325 /// `GLOBAL_GLOBALMV`: both sides take the identity global model's zero
1326 /// vector.
1327 GlobalGlobalMv,
1328 /// `NEW_NEWMV`: both sides code a residual against the compound stack
1329 /// entry [`InterInfo::ref_mv_idx`] names.
1330 NewNewMv,
1331}
1332
1333impl InterMode {
1334 /// The spec's `INTER_COMPOUND_MODES` index (libaom `enums.h` order,
1335 /// `NEAREST_NEARESTMV = 0`..`NEW_NEWMV = 7`) for a compound mode, `None`
1336 /// for a single-reference one.
1337 fn compound_index(self) -> Option<usize> {
1338 match self {
1339 InterMode::NearestNearestMv => Some(0),
1340 InterMode::NearNearMv => Some(1),
1341 InterMode::NearestNewMv => Some(2),
1342 InterMode::NewNearestMv => Some(3),
1343 InterMode::GlobalGlobalMv => Some(6),
1344 InterMode::NewNewMv => Some(7),
1345 _ => None,
1346 }
1347 }
1348}
1349
1350/// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
1351/// `(row, col)` units. For [`InterMode::NearestMv`] this writer ignores `mv`
1352/// and codes the stack's own candidate instead — the decoder derives it, so
1353/// nothing here can disagree with it.
1354#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1355pub struct InterInfo {
1356 /// The mode this block is coded with.
1357 pub mode: InterMode,
1358 /// The motion vector a [`InterMode::NewMv`] block's residual targets.
1359 pub mv: (i32, i32),
1360 /// The reference this block predicts from (`LAST_FRAME`..=`ALTREF_FRAME`,
1361 /// spec 6.10.24's alphabet), written by [`write_single_ref`].
1362 pub ref_frame: i8,
1363 /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which
1364 /// `MvStack::entries` slot `NEWMV` codes its residual against, or
1365 /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
1366 /// index (`NEARESTMV`, `GLOBALMV`).
1367 pub ref_mv_idx: u8,
1368 /// The block's second reference (spec `RefFrames[1]`), `None` for a
1369 /// single-reference block. `Some` only on a `reference_select` frame, and
1370 /// only beside one of [`InterMode`]'s compound modes.
1371 pub ref1: Option<i8>,
1372 /// The motion vector into `ref1`, for the compound modes that code one
1373 /// (`NEW_NEWMV`); the other two derive both sides.
1374 pub mv1: (i32, i32),
1375}
1376
1377impl From<Vec<Coeff>> for BlockCoeffs {
1378 /// A block that codes luma only.
1379 fn from(luma: Vec<Coeff>) -> Self {
1380 Self {
1381 luma,
1382 ..Self::default()
1383 }
1384 }
1385}
1386
1387/// Side of the luma transform the coefficient writer codes.
1388const TX32: usize = 32;
1389/// Side of the larger of the two blocks a superblock splits into, in samples.
1390const BLOCK: usize = 32;
1391/// Side of the chroma transform beside it at 4:2:0, and of the luma transform
1392/// of a 16x16 block.
1393const TX16: usize = 16;
1394/// Side of the chroma transform of a 16x16 block at 4:2:0, and of the luma
1395/// transform of an 8x8 leaf under a straddling 16x16 (lane-av1-rect).
1396const TX8: usize = 8;
1397/// Side of the chroma transform of an 8x8 leaf at 4:2:0 (lane-av1-rect).
1398const TX4: usize = 4;
1399/// Side of a superblock, in samples, which is the size a block outside the
1400/// tile reads as.
1401const SB: usize = 64;
1402/// Side of the smallest block the writer codes, in samples, which is the grid
1403/// the neighbour bookkeeping is kept on.
1404const SUB: usize = 16;
1405/// Side of a 4x4 mode-info unit, in samples: the granularity libaom's above
1406/// and left entropy-context arrays are actually kept on (spec
1407/// `get_txb_ctx`/`av1_set_entropy_contexts`), finer than [`SUB`].
1408const MI: usize = 4;
1409
1410/// What one coded block leaves behind for the blocks that read it as a
1411/// neighbour: whether it coded anything at all, and the sign of its DC.
1412#[derive(Clone, Copy, Default)]
1413struct Neighbour {
1414 /// Whether the plane's transform block carried a coefficient.
1415 coded: bool,
1416 /// Its cumulative coefficient level (spec `cul_level`, clamped to 7) --
1417 /// what the *luma* `txb_skip_ctx` of a transform unit smaller than its
1418 /// own block reads (`get_txb_ctx_general`, decode.rs `luma_skip_ctx`),
1419 /// where "coded or not" is not enough.
1420 level: u8,
1421 /// The sign of its DC, absent when the DC itself is zero.
1422 dc: Option<bool>,
1423}
1424
1425/// Rejects a frame with no mode-info grid at all.
1426///
1427/// `mi_cols`/`mi_rows` are the frame's *true* (unpadded) size in 4x4 units
1428/// (spec `compute_image_size`), not necessarily a multiple of the 32x32 block
1429/// grid: a block whose origin sits at or past this bound is not coded (spec's
1430/// `decode_partition` never visits it), and one that straddles the bound is
1431/// coded whole, its samples coming from the padded planes.
1432fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
1433 if mi_cols == 0 || mi_rows == 0 {
1434 return Err(Error::unsupported(
1435 "AV1 tile",
1436 "a coefficient key frame needs a nonzero mode-info grid",
1437 ));
1438 }
1439 Ok(())
1440}
1441
1442/// The coefficients of one superblock: either one 64x64 block covering it, or
1443/// the four 32x32 blocks it is split into.
1444///
1445/// A superblock at the right-hand or bottom edge of the frame may be half
1446/// outside it, and such a superblock cannot be left whole — the spec has no
1447/// partition that keeps a block outside the frame — so it must be
1448/// [`Split`](Superblock::Split), and carries only the quadrants that are
1449/// inside, in raster order among themselves.
1450#[derive(Clone, Debug, PartialEq, Eq)]
1451pub enum Superblock {
1452 /// One 64x64 block, whose luma transform is 64x64 — of which only the
1453 /// top-left 32x32 carries coefficients — and whose chroma transforms are
1454 /// 32x32 each at 4:2:0.
1455 Whole(BlockCoeffs),
1456 /// The 32x32 quadrants the superblock is split into, each either one
1457 /// block or four 16x16 blocks of its own.
1458 Split(Vec<Quadrant>),
1459}
1460
1461/// One 32x32 quadrant of a split superblock.
1462#[derive(Clone, Debug, PartialEq, Eq)]
1463pub enum Quadrant {
1464 /// One 32x32 block, with a 32x32 luma transform and a 16x16 transform per
1465 /// chroma plane.
1466 Whole(BlockCoeffs),
1467 /// The four 16x16 blocks it is split into, in raster order, each with a
1468 /// 16x16 luma transform and an 8x8 transform per chroma plane.
1469 Split(Vec<BlockCoeffs>),
1470}
1471
1472impl Quadrant {
1473 /// The blocks it carries, in the order they are coded.
1474 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {
1475 match self {
1476 Quadrant::Whole(block) => std::slice::from_ref(block),
1477 Quadrant::Split(blocks) => blocks.as_slice(),
1478 }
1479 }
1480}
1481
1482/// What the blocks above and to the left of the one being coded left behind,
1483/// kept on the 16x16 grid the smallest block sits on.
1484struct Neighbours {
1485 /// This tile's own top-left mode-info origin (spec 5.11.1's `MiRowStart`/
1486 /// `MiColStart`): every "is there a neighbour above/left of me" answer is
1487 /// TILE-relative, not frame-relative -- the decoder's own
1488 /// `Neighbours::start_tile` sets the same pair, and a writer that asked
1489 /// `mi_row > 0` instead coded a tile's own first row against a neighbour
1490 /// the decoder does not have (class: new map ignores tile edge).
1491 tile_row0_mi: usize,
1492 tile_col0_mi: usize,
1493 /// Per plane, whether the neighbour coded anything and the sign of its DC.
1494 above: Vec<[Neighbour; 3]>,
1495 /// The same, down the left edge.
1496 left: Vec<[Neighbour; 3]>,
1497 /// The neighbour's luma intra mode, which picks the CDF the next block's
1498 /// mode is coded with.
1499 above_mode: Vec<usize>,
1500 /// The same, down the left edge.
1501 left_mode: Vec<usize>,
1502 /// The side of the neighbour block, in samples, which is what the
1503 /// partition symbol's context reads.
1504 above_side: Vec<usize>,
1505 /// The same, down the left edge.
1506 left_side: Vec<usize>,
1507 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
1508 /// granularity [`Self::above`]/[`Self::left`] are, rather than [`SUB`]:
1509 /// two 8x8 leaves of one straddling 16x16 block (lane-av1-rect) share a
1510 /// single [`SUB`]-grid cell, so a coarse array cannot tell the second
1511 /// leaf's partition symbol that the first one was coded at 8x8 (finer
1512 /// than the 16x16 it sits in) -- exactly what its `above`/`left` context
1513 /// needs to read (spec 9.3's `AbovePartitionContext`/`LeftPartitionContext`,
1514 /// which libaom keeps per mi unit for this reason).
1515 above_side_mi: Vec<usize>,
1516 /// The same, down the left edge.
1517 left_side_mi: Vec<usize>,
1518 /// Whether the neighbour carried no residual, for [`sb_coeff_inter_frame_tile`]'s
1519 /// skip context. Unused (and left at its default) by the key frame writers.
1520 /// Kept per 4x4 mode-info unit, like [`Self::above_side_mi`] and for the
1521 /// same reason: under a real PARTITION_SPLIT to 8x8 the four leaves of a
1522 /// 16x16 read (and leave) different contexts inside one [`SUB`] slot.
1523 above_skip: Vec<bool>,
1524 /// The same, down the left edge.
1525 left_skip: Vec<bool>,
1526 /// The side, in pixels, of the transform last written in this 4x4
1527 /// mode-info column -- the deblock `tx_grid` a key frame's
1528 /// `get_tx_size_context` reads (decode.rs `tx_size_context`/`tx_px_at`),
1529 /// which is what picks the CDF row of a `TxMode::Select` block's
1530 /// `tx_depth` symbol.
1531 above_tx: Vec<u8>,
1532 /// The same, down the left edge (the transform's HEIGHT, `tx_h_px_at`;
1533 /// every transform this writer codes is square, so one value serves).
1534 left_tx: Vec<u8>,
1535 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), per
1536 /// 4x4 mode-info unit: what an INTER frame's `txfm_split` and `tx_depth`
1537 /// symbols read their context from (decode.rs `txfm_partition_ctx_rect`/
1538 /// `tx_size_context_txfm_rect`). Initialised to the widest transform, not
1539 /// zero (decode.rs `TXFM_CTX_INIT`).
1540 above_txfm: Vec<u8>,
1541 /// The same, down the left edge (transform HEIGHT).
1542 left_txfm: Vec<u8>,
1543 /// The palette size each 4x4 mode-info column last left behind, and its
1544 /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and
1545 /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's
1546 /// own `above_palette_size`/`above_palette_colors` bands (decode.rs
1547 /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content
1548 /// frame writes them, `0` when it took no palette, so a stale size never
1549 /// survives into the next block's context.
1550 above_palette_size: Vec<u8>,
1551 /// The same, down the left edge.
1552 left_palette_size: Vec<u8>,
1553 /// What the block being written right now will leave in the two palette
1554 /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY
1555 /// block of either frame type passes through, so an inter block (or an
1556 /// intra block that took no palette) clears the bands rather than letting
1557 /// an earlier palette block's size stand (the neighbour-band hazard
1558 /// lane-t900 r23 hit on the decoder side).
1559 pending_palette: Option<(u8, [u16; 8])>,
1560 /// The colours beside [`Self::above_palette_size`].
1561 above_palette_colors: Vec<[u16; 8]>,
1562 /// The chroma (U-channel) halves of the three bands above --
1563 /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the
1564 /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`.
1565 above_palette_uv_size: Vec<u8>,
1566 left_palette_uv_size: Vec<u8>,
1567 above_palette_uv_colors: Vec<[u16; 8]>,
1568 left_palette_uv_colors: Vec<[u16; 8]>,
1569 /// [`Self::pending_palette`] for the chroma palette.
1570 pending_palette_uv: Option<(u8, [u16; 8])>,
1571 /// The same, down the left edge.
1572 left_palette_colors: Vec<[u16; 8]>,
1573 /// Whether the neighbour was coded inter, for the `is_inter` context.
1574 /// Unused by the key frame writers.
1575 above_inter: Vec<bool>,
1576 /// The same, down the left edge.
1577 left_inter: Vec<bool>,
1578 /// The reference each neighbour named, `-1` for an intra or unavailable
1579 /// one -- what the decoder keeps in its own `Neighbours::above_ref`
1580 /// (decode.rs) and feeds `read_single_ref`'s context functions.
1581 above_ref: Vec<i8>,
1582 /// The same, down the left edge.
1583 left_ref: Vec<i8>,
1584 /// Each neighbour's SECOND reference, `None` for a single-reference or
1585 /// intra one -- decode.rs `Neighbours::above_ref1`, read by every compound
1586 /// context function (`reference_mode_ctx`, `comp_reference_type_ctx`, the
1587 /// `comp_ref`/`comp_bwdref` votes).
1588 above_ref1: Vec<Option<i8>>,
1589 /// The same, down the left edge.
1590 left_ref1: Vec<Option<i8>>,
1591 /// What decode.rs `Neighbours::above_comp_group_idx` holds: a compound
1592 /// neighbour's own `comp_group_idx`, or libaom's single-reference special
1593 /// case (`3` for an ALTREF block, `0` otherwise).
1594 above_comp_group_idx: Vec<u8>,
1595 /// The same, down the left edge.
1596 left_comp_group_idx: Vec<u8>,
1597 /// The same for `compound_idx` (`1` for a single-ref ALTREF block).
1598 above_compound_idx: Vec<u8>,
1599 /// The same, down the left edge.
1600 left_compound_idx: Vec<u8>,
1601 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
1602 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
1603 /// `av1_set_entropy_contexts`): a block whose row or column run spills
1604 /// past this bound leaves its trailing 4x4 units at their default,
1605 /// mid-cell if need be.
1606 mi_cols: usize,
1607 mi_rows: usize,
1608}
1609
1610/// What one plane's neighbours leave for a block, gathered across every cell
1611/// the block spans -- which is what the decoder's own derivation reads
1612/// (spec 5.11.39), and what a single cell only stands in for while every block
1613/// is the same size.
1614#[derive(Clone, Copy, Default)]
1615struct Around {
1616 /// Whether any transform block above this one carried a coefficient.
1617 above_coded: bool,
1618 /// The same, to the left.
1619 left_coded: bool,
1620 /// The running vote of the neighbours' DC signs: negative DCs count down,
1621 /// positive ones up, and a neighbour with no DC does not count.
1622 dc_vote: i32,
1623}
1624
1625impl Neighbours {
1626 /// The state a tile starts from: a block outside it reads as `DC_PRED`,
1627 /// as having coded nothing, and as unsplit. `cols`/`rows` are in [`SUB`]
1628 /// units; `mi_cols`/`mi_rows` are the frame's true (unpadded) size in 4x4
1629 /// mode-info units.
1630 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
1631 Self {
1632 tile_row0_mi: 0,
1633 tile_col0_mi: 0,
1634 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1635 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1636 above_mode: vec![DC_PRED; cols],
1637 left_mode: vec![DC_PRED; rows],
1638 above_side: vec![SB; cols],
1639 left_side: vec![SB; rows],
1640 above_side_mi: vec![SB; cols * (SUB / MI)],
1641 left_side_mi: vec![SB; rows * (SUB / MI)],
1642 above_skip: vec![false; cols * (SUB / MI)],
1643 left_skip: vec![false; rows * (SUB / MI)],
1644 above_inter: vec![false; cols * (SUB / MI)],
1645 left_inter: vec![false; rows * (SUB / MI)],
1646 above_ref: vec![-1; cols * (SUB / MI)],
1647 left_ref: vec![-1; rows * (SUB / MI)],
1648 above_ref1: vec![None; cols * (SUB / MI)],
1649 left_ref1: vec![None; rows * (SUB / MI)],
1650 above_comp_group_idx: vec![0; cols * (SUB / MI)],
1651 left_comp_group_idx: vec![0; rows * (SUB / MI)],
1652 above_compound_idx: vec![0; cols * (SUB / MI)],
1653 left_compound_idx: vec![0; rows * (SUB / MI)],
1654 above_tx: vec![0; cols * (SUB / MI)],
1655 left_tx: vec![0; rows * (SUB / MI)],
1656 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
1657 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
1658 above_palette_size: vec![0; cols * (SUB / MI)],
1659 left_palette_size: vec![0; rows * (SUB / MI)],
1660 pending_palette: None,
1661 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
1662 above_palette_uv_size: vec![0; cols * (SUB / MI)],
1663 left_palette_uv_size: vec![0; rows * (SUB / MI)],
1664 above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)],
1665 left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)],
1666 pending_palette_uv: None,
1667 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
1668 mi_cols,
1669 mi_rows,
1670 }
1671 }
1672
1673 /// Clears the left edge, which a tile starts every superblock row with.
1674 /// Points this writer's availability answers at one tile
1675 /// ([`Self::tile_row0_mi`]).
1676 fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) {
1677 self.tile_row0_mi = row0_mi;
1678 self.tile_col0_mi = col0_mi;
1679 }
1680
1681 /// Whether the block at mode-info row `mi_r` has a neighbour above it
1682 /// INSIDE its own tile, and the same to the left.
1683 fn has_above(&self, mi_r: usize) -> bool {
1684 mi_r > self.tile_row0_mi
1685 }
1686
1687 fn has_left(&self, mi_c: usize) -> bool {
1688 mi_c > self.tile_col0_mi
1689 }
1690
1691 fn start_row(&mut self) {
1692 self.left.iter_mut().for_each(|l| *l = Default::default());
1693 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
1694 self.left_side.iter_mut().for_each(|s| *s = SB);
1695 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
1696 self.left_skip.iter_mut().for_each(|s| *s = false);
1697 self.left_inter.iter_mut().for_each(|i| *i = false);
1698 self.left_ref.iter_mut().for_each(|r| *r = -1);
1699 self.left_ref1.iter_mut().for_each(|r| *r = None);
1700 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
1701 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
1702 self.left_tx.iter_mut().for_each(|t| *t = 0);
1703 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
1704 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
1705 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
1706 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
1707 }
1708
1709 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
1710 /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the
1711 /// `palette_y_mode` context (how many of the two neighbours took a
1712 /// palette) and the ascending, deduplicated colour cache the neighbours
1713 /// offer. `mi` is the block's own position in 4x4 units; this writer
1714 /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0`
1715 /// availability terms read against.
1716 fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) {
1717 // `av1_get_palette_cache` drops the above neighbour on a 64-px
1718 // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does
1719 // not, which is why the two terms below are asked separately.
1720 let above_ok = r % 16 != 0;
1721 let above_is_palette = r > 0 && self.above_palette_size[c] > 0;
1722 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
1723 (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
1724 } else {
1725 (0, [0u16; 8])
1726 };
1727 let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 {
1728 (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
1729 } else {
1730 (0, [0u16; 8])
1731 };
1732 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
1733 let mut cache = Vec::with_capacity(16);
1734 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1735 if cache.last() != Some(&v) {
1736 cache.push(v);
1737 }
1738 };
1739 let (mut ai, mut li) = (0usize, 0usize);
1740 while ai < above_n && li < left_n {
1741 let (va, vl) = (above_colors[ai], left_colors[li]);
1742 if vl < va {
1743 push_dedup(&mut cache, vl);
1744 li += 1;
1745 } else {
1746 push_dedup(&mut cache, va);
1747 ai += 1;
1748 if vl == va {
1749 li += 1;
1750 }
1751 }
1752 }
1753 while ai < above_n {
1754 push_dedup(&mut cache, above_colors[ai]);
1755 ai += 1;
1756 }
1757 while li < left_n {
1758 push_dedup(&mut cache, left_colors[li]);
1759 li += 1;
1760 }
1761 (ctx, cache)
1762 }
1763
1764 /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel
1765 /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's
1766 /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no
1767 /// neighbour lookup at all (it is this block's own just-decided Y palette
1768 /// use), so only the cache is wanted here.
1769 fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> {
1770 let above_ok = r % 16 != 0;
1771 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
1772 (
1773 usize::from(self.above_palette_uv_size[c]),
1774 self.above_palette_uv_colors[c],
1775 )
1776 } else {
1777 (0, [0u16; 8])
1778 };
1779 let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 {
1780 (
1781 usize::from(self.left_palette_uv_size[r]),
1782 self.left_palette_uv_colors[r],
1783 )
1784 } else {
1785 (0, [0u16; 8])
1786 };
1787 let mut cache = Vec::with_capacity(16);
1788 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1789 if cache.last() != Some(&v) {
1790 cache.push(v);
1791 }
1792 };
1793 let (mut ai, mut li) = (0usize, 0usize);
1794 while ai < above_n && li < left_n {
1795 let (va, vl) = (above_colors[ai], left_colors[li]);
1796 if vl < va {
1797 push_dedup(&mut cache, vl);
1798 li += 1;
1799 } else {
1800 push_dedup(&mut cache, va);
1801 ai += 1;
1802 if vl == va {
1803 li += 1;
1804 }
1805 }
1806 }
1807 while ai < above_n {
1808 push_dedup(&mut cache, above_colors[ai]);
1809 ai += 1;
1810 }
1811 while li < left_n {
1812 push_dedup(&mut cache, left_colors[li]);
1813 li += 1;
1814 }
1815 cache
1816 }
1817
1818 /// [`Self::record_palette_y`] for the chroma bands (decode.rs
1819 /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same
1820 /// way, and the span is in LUMA pixels for both planes' bands alike.
1821 fn record_palette_uv(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) {
1822 for cell in 0..(side / MI).max(1) {
1823 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
1824 *e = size;
1825 if size > 0 {
1826 self.above_palette_uv_colors[c + cell] = colors;
1827 }
1828 }
1829 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
1830 *e = size;
1831 if size > 0 {
1832 self.left_palette_uv_colors[r + cell] = colors;
1833 }
1834 }
1835 }
1836 }
1837
1838 /// What a just-written block leaves in the palette bands (decode.rs
1839 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
1840 /// spans, `0` for a block that took no palette.
1841 fn record_palette_y(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) {
1842 for cell in 0..(side / MI).max(1) {
1843 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
1844 *e = size;
1845 if size > 0 {
1846 self.above_palette_colors[c + cell] = colors;
1847 }
1848 }
1849 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
1850 *e = size;
1851 if size > 0 {
1852 self.left_palette_colors[r + cell] = colors;
1853 }
1854 }
1855 }
1856 }
1857
1858 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block
1859 /// of an INTER frame leaves in the two `TXFM_CONTEXT` bands -- its
1860 /// resolved transform size over the span `(w_px, h_px)`, which for a
1861 /// SKIPPED inter block is its own block size instead.
1862 fn record_txfm(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, w_px: usize, h_px: usize) {
1863 for i in 0..h_px / MI {
1864 if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
1865 *cell = tx_px as u8;
1866 }
1867 }
1868 for i in 0..w_px / MI {
1869 if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
1870 *cell = tx_px as u8;
1871 }
1872 }
1873 }
1874
1875 /// `get_tx_size_context` as libaom writes it for a block inside an INTER
1876 /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT`
1877 /// bands, except that an *inter* neighbour contributes its own BLOCK size.
1878 ///
1879 /// lane-av1tx2 r1: a neighbour OUTSIDE the tile contributes nothing at all
1880 /// -- the decoder's `tx_size_context_txfm` drops the whole term when
1881 /// `has_above`/`has_left` is false, where this counted the band's
1882 /// [`TXFM_CTX_INIT`] (64, the widest transform) as a real neighbour. Every
1883 /// intra block on a tile's top row or left column then took its `tx_depth`
1884 /// off a CDF row one higher than the decoder's, which is the first
1885 /// divergence of the inter `TxMode::Select` stream.
1886 fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
1887 let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c));
1888 let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
1889 let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
1890 if has_above && self.above_inter[mi_c] {
1891 above = self.above_side_mi[mi_c] >= own_side;
1892 }
1893 if has_left && self.left_inter[mi_r] {
1894 left = self.left_side_mi[mi_r] >= own_side;
1895 }
1896 usize::from(has_above && above) + usize::from(has_left && left)
1897 }
1898
1899 /// `get_tx_size_context` (decode.rs [`crate::decode::tx_size_context`]):
1900 /// whether the transform above is at least as wide as this block's own
1901 /// largest transform, plus whether the one to the left is at least as
1902 /// tall. A neighbour outside the tile contributes nothing.
1903 fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
1904 usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx)
1905 + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx)
1906 }
1907
1908 /// Publishes one block's resolved transform side over every 4x4 unit it
1909 /// covers, the way the decoder's `fill_lf_grid` does at the end of every
1910 /// block.
1911 fn record_tx(&mut self, (mi_r, mi_c): (usize, usize), side: usize, tx_px: usize) {
1912 for cell in 0..side / MI {
1913 if mi_r + cell < self.left_tx.len() {
1914 self.left_tx[mi_r + cell] = tx_px as u8;
1915 }
1916 if mi_c + cell < self.above_tx.len() {
1917 self.above_tx[mi_c + cell] = tx_px as u8;
1918 }
1919 }
1920 }
1921
1922 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
1923 /// (decode.rs `Neighbours::luma_skip_ctx`): the above and left magnitude
1924 /// tiers, each ORed over the unit's own span and clamped to 4.
1925 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
1926 let mut top = 0u8;
1927 let mut left = 0u8;
1928 for cell in 0..side_mi {
1929 top |= self.above[mi_c + cell][0].level;
1930 left |= self.left[mi_r + cell][0].level;
1931 }
1932 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
1933 }
1934
1935 /// Publishes ONE luma transform unit's coefficient context, the way the
1936 /// decoder's `record_mi_luma` does between the units of a split block.
1937 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
1938 let state = neighbour_state(grid);
1939 for cell in 0..tx_px / MI {
1940 if mi_r + cell < self.mi_rows {
1941 self.left[mi_r + cell][0] = state;
1942 }
1943 if mi_c + cell < self.mi_cols {
1944 self.above[mi_c + cell][0] = state;
1945 }
1946 }
1947 }
1948
1949 /// Writes one coded block into every 16x16 column and row it covers, and,
1950 /// on the finer 4x4 grid libaom's entropy context arrays are actually
1951 /// kept on, into every unit up to the true frame edge -- the units past
1952 /// it are left at their default (uncoded), even mid-16x16-cell (spec
1953 /// `av1_set_entropy_contexts`, which clamps to `blocks_wide`/`blocks_high`
1954 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own
1955 /// side).
1956 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
1957 self.record_planes(at, side, mode, grids, true);
1958 }
1959
1960 /// [`Self::record`] with a switch for plane 0: a block whose luma was
1961 /// written as several transform units published each unit's own context
1962 /// as it went ([`Self::record_mi_luma`]), so the whole-block write here
1963 /// would clobber what the next block reads (decode.rs
1964 /// `record_split_luma`).
1965 fn record_planes(
1966 &mut self,
1967 at: (usize, usize),
1968 side: usize,
1969 mode: usize,
1970 grids: &[Vec<i32>; 3],
1971 luma: bool,
1972 ) {
1973 let (r, c) = at;
1974 for cell in 0..side / SUB {
1975 self.above_mode[c + cell] = mode;
1976 self.left_mode[r + cell] = mode;
1977 self.above_side[c + cell] = side;
1978 self.left_side[r + cell] = side;
1979 }
1980 self.record_mi_planes((r * (SUB / MI), c * (SUB / MI)), side, grids, luma);
1981 }
1982
1983 /// The coefficient-context half of [`Self::record`], taking the block's
1984 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
1985 /// (r, c): an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at a
1986 /// mi offset [`Self::record`]'s SUB-unit `at` cannot name, but the
1987 /// `above`/`left` arrays it writes into are already sized to the full mi
1988 /// grid, so no resizing is needed to write into them at this
1989 /// finer-than-SUB granularity.
1990 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
1991 self.record_mi_planes(at_mi, side, grids, true);
1992 }
1993
1994 /// [`Self::record_mi`] with [`Self::record_planes`]'s plane-0 switch.
1995 fn record_mi_planes(
1996 &mut self,
1997 at_mi: (usize, usize),
1998 side: usize,
1999 grids: &[Vec<i32>; 3],
2000 luma: bool,
2001 ) {
2002 let (mi_r, mi_c) = at_mi;
2003 if screen_armed() {
2004 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
2005 self.record_palette_y(at_mi, side, size, colors);
2006 let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8]));
2007 self.record_palette_uv(at_mi, side, uv_size, uv_colors);
2008 }
2009 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
2010 let side_mi = side / MI;
2011 for cell in 0..side_mi {
2012 self.left_side_mi[mi_r + cell] = side;
2013 self.above_side_mi[mi_c + cell] = side;
2014 }
2015 // libaom rounds the luma edge up to the plane's own 4x4 unit before
2016 // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high,
2017 // subsampling_y)` in av1_write_intra_coeffs_mb, encodetxb.c:456-459):
2018 // a chroma 4x4 unit straddling the true luma edge is still whole in
2019 // chroma's own halved grid, so it stays valid one luma-mi row/col
2020 // past where luma's own edge falls when that edge is odd.
2021 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2022 let bound_h = [
2023 self.mi_rows,
2024 round_up_even(self.mi_rows),
2025 round_up_even(self.mi_rows),
2026 ];
2027 let bound_w = [
2028 self.mi_cols,
2029 round_up_even(self.mi_cols),
2030 round_up_even(self.mi_cols),
2031 ];
2032 for cell in 0..side_mi {
2033 let keep_left = self.left[mi_r + cell][0];
2034 let keep_above = self.above[mi_c + cell][0];
2035 self.left[mi_r + cell] = std::array::from_fn(|plane| {
2036 if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {
2037 states[plane]
2038 } else {
2039 Default::default()
2040 }
2041 });
2042 self.above[mi_c + cell] = std::array::from_fn(|plane| {
2043 if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) {
2044 states[plane]
2045 } else {
2046 Default::default()
2047 }
2048 });
2049 if !luma {
2050 self.left[mi_r + cell][0] = keep_left;
2051 self.above[mi_c + cell][0] = keep_above;
2052 }
2053 }
2054 }
2055
2056 /// Writes one inter-frame block's skip flag and inter/intra state into
2057 /// every 16x16 column and row it covers, the same span [`Self::record`]
2058 /// fills for the coefficient and mode state.
2059 fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) {
2060 let (r, c) = at;
2061 self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame);
2062 }
2063
2064 /// [`Self::record_inter_mi`]'s compound half (decode.rs
2065 /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF
2066 /// single-reference default with a real compound block's own second
2067 /// reference and `comp_group_idx`/`compound_idx` bits, called right after
2068 /// it for every compound-coded block.
2069 fn record_compound_mi(
2070 &mut self,
2071 (mi_r, mi_c): (usize, usize),
2072 side: usize,
2073 ref1: i8,
2074 comp_group_idx: u8,
2075 compound_idx: u8,
2076 ) {
2077 for cell in 0..side / MI {
2078 self.above_ref1[mi_c + cell] = Some(ref1);
2079 self.left_ref1[mi_r + cell] = Some(ref1);
2080 self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
2081 self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
2082 self.above_compound_idx[mi_c + cell] = compound_idx;
2083 self.left_compound_idx[mi_r + cell] = compound_idx;
2084 }
2085 }
2086
2087 /// [`Self::record_inter`] taking the block's position directly in 4x4
2088 /// mode-info units, for a block finer than one [`SUB`] slot.
2089 fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) {
2090 for cell in 0..side / MI {
2091 self.above_skip[mi_c + cell] = skip;
2092 self.left_skip[mi_r + cell] = skip;
2093 self.above_inter[mi_c + cell] = is_inter;
2094 self.left_inter[mi_r + cell] = is_inter;
2095 self.above_ref[mi_c + cell] = ref_frame;
2096 self.left_ref[mi_r + cell] = ref_frame;
2097 // decode.rs `record_inter`'s single-reference default: no second
2098 // reference, and libaom's ALTREF special case in the two compound
2099 // context bands. `record_compound_mi` overwrites both for a real
2100 // compound block.
2101 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
2102 self.above_ref1[mi_c + cell] = None;
2103 self.left_ref1[mi_r + cell] = None;
2104 self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
2105 self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
2106 self.above_compound_idx[mi_c + cell] = u8::from(altref);
2107 self.left_compound_idx[mi_r + cell] = u8::from(altref);
2108 }
2109 }
2110
2111 /// The above neighbour as decode.rs' own `NeighbourRef`, for every
2112 /// compound context function (`reference_mode_ctx`,
2113 /// `comp_reference_type_ctx`, the `comp_ref`/`comp_bwdref` votes).
2114 fn above_nbr(&self, mi_c: usize) -> crate::mvstack::NeighbourRef {
2115 let is_inter = self.above_inter[mi_c];
2116 let ref0 = if is_inter { self.above_ref[mi_c] } else { 0 };
2117 let ref1 = self.above_ref1[mi_c];
2118 crate::mvstack::NeighbourRef {
2119 is_inter,
2120 ref0,
2121 ref1,
2122 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
2123 }
2124 }
2125
2126 /// [`Self::above_nbr`], down the left edge.
2127 fn left_nbr(&self, mi_r: usize) -> crate::mvstack::NeighbourRef {
2128 let is_inter = self.left_inter[mi_r];
2129 let ref0 = if is_inter { self.left_ref[mi_r] } else { 0 };
2130 let ref1 = self.left_ref1[mi_r];
2131 crate::mvstack::NeighbourRef {
2132 is_inter,
2133 ref0,
2134 ref1,
2135 uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
2136 }
2137 }
2138
2139 /// The context of a block's partition symbol (spec 9.3): whether the
2140 /// blocks above it and to its left were split finer than it is.
2141 /// The gathered state of the blocks above and to the left of one block,
2142 /// per plane.
2143 fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] {
2144 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
2145 }
2146
2147 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
2148 /// units, for the same reason [`Self::record_mi`] does.
2149 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [Around; 3] {
2150 let side_mi = side / MI;
2151 std::array::from_fn(|plane| {
2152 let mut around = Around::default();
2153 for cell in 0..side_mi {
2154 let (above, left) = (
2155 &self.above[mi_c + cell][plane],
2156 &self.left[mi_r + cell][plane],
2157 );
2158 around.above_coded |= above.coded;
2159 around.left_coded |= left.coded;
2160 around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc);
2161 }
2162 around
2163 })
2164 }
2165
2166 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
2167 // Delegates to the mi-precise reader (same pattern as `around` /
2168 // `around_mi`): `above_side`/`left_side` are only ever advanced in
2169 // whole-[`SUB`] steps by [`Self::record`], so a leaf8's `record_mi`
2170 // (lane-av1-rect) -- which only touches the finer mi arrays -- leaves
2171 // them stale for the *next* sibling's own partition symbol, reading a
2172 // 16x16-slot side that already split into 8x8s underneath it.
2173 let (r, c) = at;
2174 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
2175 }
2176
2177 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
2178 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
2179 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
2180 /// than the enclosing 16x16 slot's stale, shared state.
2181 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
2182 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
2183 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
2184 }
2185}
2186
2187/// Writes the payload of a one-tile key frame built from `superblocks`, each
2188/// either one 64x64 block or the 32x32 blocks it splits into.
2189///
2190/// `superblocks` gives one entry per superblock in raster order across the
2191/// frame. Every block is DC-predicted unless its [`BlockCoeffs::mode`] says
2192/// otherwise, and carries the coefficients its lists give; the coefficients
2193/// may sit anywhere in their transform, so a block is a picture rather than a
2194/// flat grey.
2195///
2196/// # Errors
2197/// Returns an error when the frame is not a whole number of 32x32 blocks, when
2198/// `superblocks` does not carry exactly one entry per superblock or an entry
2199/// does not carry one block per quadrant inside the frame, when a superblock
2200/// that is half outside the frame is left whole, when a block names an intra
2201/// mode a key frame does not code, when a coefficient sits outside its
2202/// transform, repeats a position, carries a zero level or one wider than the
2203/// Golomb tail reaches.
2204pub fn sb_coeff_key_frame_tile(
2205 mi_cols: u32,
2206 mi_rows: u32,
2207 base_q_idx: u8,
2208 superblocks: &[Superblock],
2209) -> Result<Vec<u8>> {
2210 sb_coeff_key_frame_tile_tx(mi_cols, mi_rows, base_q_idx, superblocks, false)
2211}
2212
2213/// [`sb_coeff_key_frame_tile`] for a frame header carrying
2214/// `tx_mode == TxMode::Select` (`tx_select`): every block then codes a
2215/// `tx_depth` symbol and, where that depth is nonzero, its luma residual as
2216/// several transform units ([`write_luma_select`]). With `tx_select` false
2217/// this writes exactly the stream it always did.
2218///
2219/// # Errors
2220/// As [`sb_coeff_key_frame_tile`], plus a 64x64 block whose `tx_depth` is
2221/// nonzero (not written yet).
2222pub fn sb_coeff_key_frame_tile_tx(
2223 mi_cols: u32,
2224 mi_rows: u32,
2225 base_q_idx: u8,
2226 superblocks: &[Superblock],
2227 tx_select: bool,
2228) -> Result<Vec<u8>> {
2229 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
2230 sb_coeff_key_frame_tile_cdfs(
2231 mi_cols,
2232 mi_rows,
2233 base_q_idx,
2234 superblocks,
2235 tx_select,
2236 &mut cdfs,
2237 TileRect::whole(mi_cols, mi_rows),
2238 )
2239}
2240
2241/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
2242/// caller's own CDF state, which is what a frame whose
2243/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must
2244/// start where this tile ended (spec 7.20, mirrored by
2245/// `crate::stream::stored_cdfs_for`).
2246///
2247/// # Errors
2248/// As [`sb_coeff_key_frame_tile_tx`].
2249pub(crate) fn sb_coeff_key_frame_tile_cdfs(
2250 mi_cols: u32,
2251 mi_rows: u32,
2252 _base_q_idx: u8,
2253 superblocks: &[Superblock],
2254 tx_select: bool,
2255 cdfs: &mut Cdfs,
2256 // This tile's own span (spec 5.11.1): the writer walks only these
2257 // superblocks, and its neighbour bands start blank, so everything
2258 // outside reads as unavailable exactly as the decoder's own per-tile
2259 // reset makes it.
2260 tile: TileRect,
2261) -> Result<Vec<u8>> {
2262 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
2263 let _cdef_idx = CdefIdxGuard;
2264 check_blocks(mi_cols, mi_rows)?;
2265 // The DV predictor's own mi grid, per tile exactly as decode.rs builds it
2266 // per frame (`decode_key_frame_tile_lr`'s `intrabc_mi_grid`): a tile that
2267 // allows no intrabc arms none and every `record_intrabc_mi` below is a
2268 // no-op.
2269 if intrabc_armed() {
2270 // No `set_tile_bounds`: decode.rs builds this grid for the WHOLE
2271 // frame with the default (whole-grid) bounds, so the writer must
2272 // too. `encode_key_frame_inner` only allows intrabc on a
2273 // single-tile frame, where the two grids are the same grid.
2274 let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize);
2275 INTRABC_GRID.with(|g| {
2276 *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize));
2277 });
2278 }
2279 let (cols, rows) = block_grid(mi_cols, mi_rows);
2280 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
2281 if superblocks.len() != (sb_cols * sb_rows) as usize {
2282 return Err(Error::unsupported(
2283 "AV1 tile",
2284 "a coefficient key frame needs one entry per superblock",
2285 ));
2286 }
2287 let mut coded: Vec<&BlockCoeffs> = Vec::new();
2288 for superblock in superblocks {
2289 match superblock {
2290 Superblock::Whole(block) => coded.push(block),
2291 Superblock::Split(quadrants) => {
2292 for block in quadrants.iter().flat_map(Quadrant::blocks) {
2293 match &block.eight {
2294 Some(leaves) => coded.extend(leaves.iter()),
2295 None => coded.push(block),
2296 }
2297 }
2298 }
2299 }
2300 }
2301 if let Some(bad) = coded
2302 .into_iter()
2303 .find(|b| usize::from(b.mode) >= INTRA_MODES)
2304 {
2305 return Err(Error::unsupported(
2306 "AV1 tile",
2307 format!(
2308 "intra mode {} is not one of the thirteen a key frame codes",
2309 bad.mode
2310 ),
2311 ));
2312 }
2313
2314 let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8];
2315 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
2316 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
2317 let scans = [
2318 default_scan(TX32),
2319 default_scan(TX16),
2320 default_scan(TX8),
2321 default_scan(TX4),
2322 ];
2323 // The blocks above and to the left, on the 16x16 grid. The left edge is
2324 // reset at every superblock row because a tile starts each row with no
2325 // left neighbour.
2326 let mut neighbours = Neighbours::new(
2327 cols as usize * 2,
2328 rows as usize * 2,
2329 mi_cols as usize,
2330 mi_rows as usize,
2331 );
2332 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
2333
2334 // The tile adapts every non-literal CDF it writes, exactly as the decoder
2335 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
2336 // off.
2337 let mut cdfs = cdfs;
2338 let mut enc = SymbolEncoder::new();
2339 for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
2340 neighbours.start_row();
2341 for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
2342 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
2343 let at = (sb_r as usize * 4, sb_c as usize * 4);
2344 let ctx = neighbours.partition_ctx(at, SB);
2345 ec_rng_trace(|| {
2346 format!(
2347 "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={}",
2348 at.0 * 4,
2349 at.1 * 4,
2350 ctx,
2351 enc.tell()
2352 )
2353 });
2354 // A superblock whose bottom or right half is outside the frame
2355 // cannot be left unsplit, so the decoder reads a flag instead of
2356 // the partition symbol — and reads nothing at all when both halves
2357 // are outside, where the split is the only partition left.
2358 let (has_cols, has_rows) = (
2359 sb_c * SB_MI + SB_MI / 2 < mi_cols,
2360 sb_r * SB_MI + SB_MI / 2 < mi_rows,
2361 );
2362 // The quadrants of this superblock that are inside the frame, as
2363 // positions in the 32x32 block grid.
2364 let quadrant_positions: Vec<(usize, usize)> = (0..4)
2365 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
2366 .filter(|&(r, c)| r < rows && c < cols)
2367 .map(|(r, c)| (r as usize, c as usize))
2368 .collect();
2369
2370 match &superblocks[(sb_r * sb_cols + sb_c) as usize] {
2371 Superblock::Whole(block) => {
2372 if !has_cols || !has_rows {
2373 return Err(Error::unsupported(
2374 "AV1 tile",
2375 "a superblock that is half outside the frame cannot be left whole",
2376 ));
2377 }
2378 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
2379 let grids = [
2380 level_grid(&block.luma, TX32)?,
2381 level_grid(&block.u, TX32)?,
2382 level_grid(&block.v, TX32)?,
2383 ];
2384 write_block(
2385 &mut enc,
2386 &mut cdfs,
2387 &mut neighbours,
2388 block,
2389 at,
2390 SB,
2391 &whole_planes,
2392 &grids,
2393 [&scans[0], &scans[0], &scans[0]],
2394 // A 64x64 block is too big to be offered chroma from
2395 // luma, so its chroma mode reads the table without it.
2396 false,
2397 tx_select,
2398 &scans,
2399 )?;
2400 ec_rng_trace(|| {
2401 format!(
2402 "EC_TOK mi_row={} mi_col={} tell={}",
2403 at.0 * 4,
2404 at.1 * 4,
2405 enc.tell()
2406 )
2407 });
2408 }
2409 Superblock::Split(quadrants) => {
2410 match (has_cols, has_rows) {
2411 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
2412 // The gathered CDF an edge superblock reads is built
2413 // for the read and thrown away: the decoder never
2414 // stores it back, so nothing adapts here.
2415 (true, false) => {
2416 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
2417 }
2418 (false, true) => {
2419 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
2420 }
2421 (false, false) => {}
2422 }
2423 if quadrants.len() != quadrant_positions.len() {
2424 return Err(Error::unsupported(
2425 "AV1 tile",
2426 "a split superblock needs one block per quadrant inside the frame",
2427 ));
2428 }
2429 for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) {
2430 let at = (r * 2, c * 2);
2431 let ctx = neighbours.partition_ctx(at, BLOCK);
2432 // Recomputed at this 32x32 block's own half (spec
2433 // `decode_partition`, called again at every size, not
2434 // just once for the superblock): the true frame edge
2435 // can fall inside this quadrant even when the
2436 // superblock it sits in was itself whole or safely
2437 // split above.
2438 let (has_cols32, has_rows32) = (
2439 has_half(c as u32 * BLOCK_MI, BLOCK_MI, mi_cols),
2440 has_half(r as u32 * BLOCK_MI, BLOCK_MI, mi_rows),
2441 );
2442 ec_rng_trace(|| {
2443 format!(
2444 "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={}",
2445 at.0 * 4,
2446 at.1 * 4,
2447 ctx,
2448 enc.tell()
2449 )
2450 });
2451 match quadrant {
2452 Quadrant::Whole(block) => {
2453 if !has_cols32 || !has_rows32 {
2454 return Err(Error::unsupported(
2455 "AV1 tile",
2456 "a 32x32 block that is half outside the true frame \
2457 cannot be left whole",
2458 ));
2459 }
2460 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]);
2461 let grids = [
2462 level_grid(&block.luma, TX32)?,
2463 level_grid(&block.u, TX16)?,
2464 level_grid(&block.v, TX16)?,
2465 ];
2466 write_block(
2467 &mut enc,
2468 &mut cdfs,
2469 &mut neighbours,
2470 block,
2471 at,
2472 BLOCK,
2473 &split_planes,
2474 &grids,
2475 [&scans[0], &scans[1], &scans[1]],
2476 true,
2477 tx_select,
2478 &scans,
2479 )?;
2480 ec_rng_trace(|| {
2481 format!(
2482 "EC_TOK mi_row={} mi_col={} tell={}",
2483 at.0 * 4,
2484 at.1 * 4,
2485 enc.tell()
2486 )
2487 });
2488 }
2489 Quadrant::Split(blocks) => {
2490 // The 16x16 sub-blocks this quadrant's split
2491 // carries: only those whose own mi origin is
2492 // inside the true frame (spec `decode_partition`'s
2493 // `r >= MiRows || c >= MiCols` early return),
2494 // which need not be all four when the true
2495 // edge falls inside this quadrant.
2496 let sub_positions: Vec<(usize, usize)> = (0..4)
2497 .map(|i| (r * 2 + i / 2, c * 2 + i % 2))
2498 .filter(|&(sr, sc)| {
2499 (sr as u32) * SUB_MI < mi_rows
2500 && (sc as u32) * SUB_MI < mi_cols
2501 })
2502 .collect();
2503 if blocks.len() != sub_positions.len() {
2504 return Err(Error::unsupported(
2505 "AV1 tile",
2506 "a split 32x32 block needs one 16x16 entry per \
2507 sub-block inside the true frame",
2508 ));
2509 }
2510 // Same three-way spec signaling as the
2511 // superblock level above, recomputed at this
2512 // block's own half: a full alphabet symbol
2513 // only when both halves are inside, a single
2514 // gathered bit when just one is, and nothing
2515 // at all (SPLIT is inferred) when neither is.
2516 match (has_cols32, has_rows32) {
2517 (true, true) => {
2518 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]);
2519 }
2520 (true, false) => {
2521 enc.symbol_fixed(
2522 1,
2523 &gather(&cdfs.partition_w32[ctx], VERT_ALIKE),
2524 );
2525 }
2526 (false, true) => {
2527 enc.symbol_fixed(
2528 1,
2529 &gather(&cdfs.partition_w32[ctx], HORZ_ALIKE),
2530 );
2531 }
2532 (false, false) => {}
2533 }
2534 for (block, (sr, sc)) in blocks.iter().zip(sub_positions) {
2535 // A 16x16 leaf's own hasRows/hasCols,
2536 // recomputed at this leaf's own half
2537 // (same three-way signaling as the 32x32
2538 // and 64x64 levels above).
2539 let (has_cols16, has_rows16) = (
2540 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
2541 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
2542 );
2543 let at = (sr, sc);
2544 let ctx = neighbours.partition_ctx(at, SUB);
2545 ec_rng_trace(|| {
2546 format!(
2547 "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={}",
2548 at.0 * 4,
2549 at.1 * 4,
2550 ctx,
2551 enc.tell()
2552 )
2553 });
2554 if has_cols16 && has_rows16 {
2555 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]);
2556 let grids = [
2557 level_grid(&block.luma, TX16)?,
2558 level_grid(&block.u, TX8)?,
2559 level_grid(&block.v, TX8)?,
2560 ];
2561 write_block(
2562 &mut enc,
2563 &mut cdfs,
2564 &mut neighbours,
2565 block,
2566 at,
2567 SUB,
2568 &sub_planes,
2569 &grids,
2570 [&scans[1], &scans[2], &scans[2]],
2571 true,
2572 tx_select,
2573 &scans,
2574 )?;
2575 ec_rng_trace(|| {
2576 format!(
2577 "EC_TOK mi_row={} mi_col={} tell={}",
2578 at.0 * 4,
2579 at.1 * 4,
2580 enc.tell()
2581 )
2582 });
2583 continue;
2584 }
2585 // The true edge falls inside this 16x16
2586 // leaf itself (mod-32==8 target sizes):
2587 // one axis only, per r6's charter -- an
2588 // 8x8 leaf never itself straddles, so the
2589 // block splits cleanly along whichever
2590 // axis is short and only the in-frame
2591 // 8x8s are coded, each its own leaf.
2592 if !has_cols16 && !has_rows16 {
2593 return Err(Error::unsupported(
2594 "AV1 tile",
2595 "a 16x16 block whose true edge cuts through both \
2596 axes needs a rectangular transform this writer \
2597 does not code yet",
2598 ));
2599 }
2600 if has_cols16 {
2601 enc.symbol_fixed(
2602 1,
2603 &gather(&cdfs.partition_w16[ctx], VERT_ALIKE),
2604 );
2605 } else {
2606 enc.symbol_fixed(
2607 1,
2608 &gather(&cdfs.partition_w16[ctx], HORZ_ALIKE),
2609 );
2610 }
2611 let leaves = block.eight.as_ref().ok_or_else(|| {
2612 Error::unsupported(
2613 "AV1 tile",
2614 "a 16x16 block the true frame edge cuts through \
2615 needs its `eight` leaves populated",
2616 )
2617 })?;
2618 let (mi_row0, mi_col0) =
2619 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
2620 let leaf_positions: Vec<(u32, u32)> = (0..4)
2621 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
2622 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
2623 .collect();
2624 if leaves.len() != leaf_positions.len() {
2625 return Err(Error::unsupported(
2626 "AV1 tile",
2627 "a straddling 16x16 block needs one `eight` entry \
2628 per 8x8 leaf inside the true frame",
2629 ));
2630 }
2631 // r11: the enclosing 16x16 slot's
2632 // above_mode/left_mode arrays are too
2633 // coarse for a second leaf whose true
2634 // above (or left) neighbour is the FIRST
2635 // leaf -- track it here and hand it to
2636 // write_leaf8 as a context override.
2637 let mut prev_leaf: Option<((usize, usize), usize)> = None;
2638 for (leaf, (mr, mc)) in leaves.iter().zip(leaf_positions) {
2639 let leaf_mi = (mr as usize, mc as usize);
2640 // r8: read at mi granularity, not the
2641 // enclosing 16x16 slot -- the first
2642 // leaf's `record_mi` call below
2643 // updates `above_side_mi`/
2644 // `left_side_mi` at this leaf's own
2645 // mi position, which the second
2646 // leaf's ctx lookup then sees.
2647 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
2648 ec_rng_trace(|| {
2649 format!(
2650 "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={}",
2651 leaf_mi.0,
2652 leaf_mi.1,
2653 leaf_ctx,
2654 enc.tell()
2655 )
2656 });
2657 enc.symbol(
2658 PARTITION_NONE,
2659 &mut cdfs.partition_w8[leaf_ctx],
2660 );
2661 let grids = [
2662 level_grid(&leaf.luma, TX8)?,
2663 level_grid(&leaf.u, TX4)?,
2664 level_grid(&leaf.v, TX4)?,
2665 ];
2666 let leaf_mode = write_leaf8(
2667 &mut enc,
2668 &mut cdfs,
2669 &mut neighbours,
2670 leaf,
2671 at,
2672 leaf_mi,
2673 &grids,
2674 [&scans[2], &scans[3], &scans[3]],
2675 prev_leaf,
2676 tx_select,
2677 &scans,
2678 )?;
2679 prev_leaf = Some((leaf_mi, leaf_mode));
2680 ec_rng_trace(|| {
2681 format!(
2682 "EC_TOK mi_row={} mi_col={} tell={}",
2683 leaf_mi.0,
2684 leaf_mi.1,
2685 enc.tell()
2686 )
2687 });
2688 }
2689 // `record()`'s `above_mode`/`left_mode`
2690 // write is a no-op at an 8x8 leaf's own
2691 // side (`side / SUB == 0`), so the next
2692 // 16x16 quadrant beyond this straddling
2693 // one would otherwise see whatever stale
2694 // mode sat here before it: force the
2695 // write once the whole quadrant's leaves
2696 // are done, from the last (bottom/right-
2697 // most) leaf -- lane-av1-rect r15: doing
2698 // this *inside* `write_leaf8`, once per
2699 // leaf, let the first leaf's write
2700 // clobber the true external neighbour a
2701 // second leaf of the *same* quadrant
2702 // still needed to read on its
2703 // non-adjacency axis.
2704 if let Some((_, mode)) = prev_leaf {
2705 neighbours.above_mode[at.1] = mode;
2706 neighbours.left_mode[at.0] = mode;
2707 }
2708 }
2709 }
2710 }
2711 }
2712 }
2713 }
2714 }
2715 }
2716 Ok(enc.finish())
2717}
2718
2719/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`,
2720/// which the palette colour-index map's first (context-free) symbol is coded
2721/// with.
2722fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) {
2723 let l = crate::decode::ceil_log2(n as u32);
2724 let m = (1usize << l) - n;
2725 if value < m {
2726 enc.literal(value as u32, l - 1);
2727 } else {
2728 enc.literal(((value + m) >> 1) as u32, l - 1);
2729 enc.literal(((value + m) & 1) as u32, 1);
2730 }
2731}
2732
2733/// `write_palette_colors_y` (bitstream.c:1178), the write side of
2734/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache
2735/// entry (taken when this palette holds that colour, in cache order, stopping
2736/// once `n` are cached), then the colours the cache did not supply -- the
2737/// first raw, the rest as deltas off a bit width that shrinks with the range
2738/// left. `colors` is ascending and distinct, so the decoder's `merge_colors`
2739/// of the two ascending lists puts it back exactly.
2740fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) {
2741 let n = colors.len();
2742 let mut cached: Vec<u16> = Vec::with_capacity(n);
2743 for &c in cache {
2744 if cached.len() >= n {
2745 break;
2746 }
2747 let take = colors.contains(&c);
2748 enc.literal(u32::from(take), 1);
2749 if take {
2750 cached.push(c);
2751 }
2752 }
2753 let transmitted: Vec<u16> = colors
2754 .iter()
2755 .copied()
2756 .filter(|c| !cached.contains(c))
2757 .collect();
2758 if transmitted.is_empty() {
2759 return;
2760 }
2761 enc.literal(u32::from(transmitted[0]), 8);
2762 if transmitted.len() == 1 {
2763 return;
2764 }
2765 // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one
2766 // under which every delta still fits its (shrinking) width. `extra == 3`
2767 // always works -- a delta can never exceed the range left -- so the
2768 // search below always finds one.
2769 let fits = |extra: u32| -> bool {
2770 let mut bits = 5 + extra;
2771 let mut range = 255i32 - i32::from(transmitted[0]);
2772 for w in transmitted.windows(2) {
2773 let delta = i32::from(w[1]) - i32::from(w[0]);
2774 if delta - 1 >= (1i32 << bits) {
2775 return false;
2776 }
2777 range -= delta;
2778 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2779 }
2780 true
2781 };
2782 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
2783 enc.literal(extra, 2);
2784 let mut bits = 5 + extra;
2785 let mut range = 255i32 - i32::from(transmitted[0]);
2786 for w in transmitted.windows(2) {
2787 let delta = i32::from(w[1]) - i32::from(w[0]);
2788 enc.literal((delta - 1) as u32, bits);
2789 range -= delta;
2790 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2791 }
2792}
2793
2794/// `write_palette_colors_uv` (bitstream.c:1236), the write side of
2795/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is
2796/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two
2797/// documented differences -- the shrinking range starts at `256 - first`
2798/// (not `255 - first`) and each delta is written unbiased (no `-1`).
2799///
2800/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n`
2801/// 8-bit literals) rather than its first-value-plus-signed-deltas form.
2802/// Ceiling: about `n` bits per chroma-palette block more than the delta form
2803/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer
2804/// below sees, so it only ever makes the encoder take FEWER chroma palettes
2805/// than it should -- never a wrong stream. Upgrade path: price both forms
2806/// here and write the cheaper one under its own leading bit.
2807fn write_palette_colors_uv(enc: &mut SymbolEncoder, u_colors: &[u16], v_colors: &[u16], cache: &[u16]) {
2808 let n = u_colors.len();
2809 let mut cached: Vec<u16> = Vec::with_capacity(n);
2810 for &c in cache {
2811 if cached.len() >= n {
2812 break;
2813 }
2814 let take = u_colors.contains(&c);
2815 enc.literal(u32::from(take), 1);
2816 if take {
2817 PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2818 cached.push(c);
2819 }
2820 }
2821 let transmitted: Vec<u16> = u_colors
2822 .iter()
2823 .copied()
2824 .filter(|c| !cached.contains(c))
2825 .collect();
2826 if !transmitted.is_empty() {
2827 enc.literal(u32::from(transmitted[0]), 8);
2828 if transmitted.len() > 1 {
2829 let fits = |extra: u32| -> bool {
2830 let mut bits = 5 + extra;
2831 let mut range = 256i32 - i32::from(transmitted[0]);
2832 for w in transmitted.windows(2) {
2833 let delta = i32::from(w[1]) - i32::from(w[0]);
2834 if delta >= (1i32 << bits) {
2835 return false;
2836 }
2837 range -= delta;
2838 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2839 }
2840 true
2841 };
2842 let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
2843 enc.literal(extra, 2);
2844 let mut bits = 5 + extra;
2845 let mut range = 256i32 - i32::from(transmitted[0]);
2846 for w in transmitted.windows(2) {
2847 let delta = i32::from(w[1]) - i32::from(w[0]);
2848 enc.literal(delta as u32, bits);
2849 range -= delta;
2850 bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2851 }
2852 }
2853 }
2854 enc.literal(0, 1);
2855 for &v in v_colors {
2856 enc.literal(u32::from(v), 8);
2857 }
2858}
2859
2860/// `write_palette_color_map` (bitstream.c), the write side of
2861/// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
2862/// each symbol written as the position its colour takes in the neighbour
2863/// ordering `av1_get_palette_color_index_context` hands back.
2864fn write_color_index_map(
2865 enc: &mut SymbolEncoder,
2866 idx_cdfs: &mut [[u16; 9]; 5],
2867 map: &[u8],
2868 side: usize,
2869 n: usize,
2870) {
2871 write_uniform(enc, usize::from(map[0]), n);
2872 for i in 1..(2 * side - 1) {
2873 for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() {
2874 let (row, col) = (i - j, j);
2875 let (ctx, color_order) =
2876 crate::decode::palette_color_index_context(map, side, row, col, n);
2877 let want = map[row * side + col];
2878 let symbol = color_order[..n]
2879 .iter()
2880 .position(|&c| c == want)
2881 .expect("every colour index is in the block\'s own palette");
2882 enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]);
2883 }
2884 }
2885}
2886
2887/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag,
2888/// the size symbol, the colours and the whole colour-index map, priced
2889/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the
2890/// search reads the rate the tile will really spend, not an estimate of it.
2891/// The neighbour cache is taken as empty (the search runs before the tile
2892/// knows what its neighbours will be), which only ever over-prices.
2893pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 {
2894 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
2895 return f64::INFINITY;
2896 };
2897 let n = usize::from(pal.size);
2898 let mut enc = SymbolEncoder::pricer();
2899 let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0];
2900 enc.symbol(1, &mut mode_cdf);
2901 let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx];
2902 enc.symbol(n - 2, &mut size_cdf);
2903 write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
2904 let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];
2905 write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n);
2906 enc.bits()
2907}
2908
2909/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
2910/// size symbol, both colour lists and the shared colour-index map, priced
2911/// through the very writers above (empty cache, which only over-prices).
2912pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 {
2913 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
2914 return f64::INFINITY;
2915 };
2916 let n = usize::from(pal.size);
2917 let mut enc = SymbolEncoder::pricer();
2918 let mut mode_cdf = cdf::PALETTE_UV_MODE[0];
2919 enc.symbol(1, &mut mode_cdf);
2920 let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx];
2921 enc.symbol(n - 2, &mut size_cdf);
2922 write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
2923 let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];
2924 write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n);
2925 enc.bits()
2926}
2927
2928/// Writes everything a key frame's block carries before its coefficients: the
2929/// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
2930/// the angle a directional mode is steered by, and its chroma mode. Hands back
2931/// the luma mode, which is what the blocks beside it read.
2932/// The DV predictor decode.rs `read_intrabc_dv` derives, mirrored line for
2933/// line off the writer's own copy of the intrabc mi grid: the `INTRA_FRAME`
2934/// stack's `nearest_mv` (or `near_mv` when that is zero), or -- when both are
2935/// -- `av1_find_ref_dv`'s fallback one superblock up, or 256 pixels plus one
2936/// superblock to the left on the tile's first superblock row, then floored to
2937/// full pel. Returns `(0, 0)` when no grid is armed, which no `allow_intrabc`
2938/// tile ever reaches.
2939fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) {
2940 const INTRABC_DELAY_PIXELS: i32 = 256;
2941 let n4 = side / MI;
2942 let stack_pred = INTRABC_GRID.with(|g| {
2943 let g = g.borrow();
2944 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
2945 let stack = crate::mvstack::find_mv_stack(
2946 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
2947 *mi_cols, *mi_rows,
2948 );
2949 if stack.nearest_mv == (0, 0) {
2950 stack.near_mv
2951 } else {
2952 stack.nearest_mv
2953 }
2954 })
2955 });
2956 let mut pred = stack_pred.unwrap_or((0, 0));
2957 if pred == (0, 0) {
2958 // 64x64 superblocks: the only size this encoder's sequence header
2959 // signals (`use_128x128_superblock: false`), so `mib_size` is 16 mi.
2960 // The tile row start is 0, exactly as decode.rs `read_intrabc_dv`
2961 // takes it -- both are written for the single-tile-row streams this
2962 // encoder produces.
2963 let sb_mi = 16i32;
2964 let sb_px = sb_mi * MI as i32;
2965 pred = if (mi_r as i32) < sb_mi {
2966 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
2967 } else {
2968 (-sb_px * 8, 0)
2969 };
2970 }
2971 ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8)
2972}
2973
2974/// Publishes one coded block into [`INTRABC_GRID`], mirroring decode.rs
2975/// `record_intrabc_mi`: every block contributes its size, an intrabc one also
2976/// its DV as an `INTRA_FRAME` candidate.
2977fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
2978 INTRABC_GRID.with(|g| {
2979 let mut g = g.borrow_mut();
2980 let Some((grid, _, _)) = g.as_mut() else {
2981 return;
2982 };
2983 let info = crate::mvstack::MiInfo {
2984 is_inter: dv.is_some(),
2985 ref_frame: 0,
2986 ref_frame1: crate::mvstack::NO_REF1,
2987 mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))),
2988 mv1: (0, 0),
2989 is_new_mv: dv.is_some(),
2990 is_global_mv0: false,
2991 is_global_mv1: false,
2992 size: n4 as u8,
2993 size_h: n4 as u8,
2994 };
2995 for r in mi_r..mi_r + n4 {
2996 for c in mi_c..mi_c + n4 {
2997 grid.set(r, c, info);
2998 }
2999 }
3000 });
3001}
3002
3003/// One full-pel block-vector component, [`write_mv_component`]'s
3004/// `force_integer_mv` twin: decode.rs `read_mv_component` infers `mv_fr`/
3005/// `mv_class0_fr` as 3 and the high-precision bit as 1 under
3006/// `force_integer_mv`, so neither symbol is written here -- writing them
3007/// would leave the decoder two symbols behind from this block on.
3008fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
3009 let mag = diff.unsigned_abs() as i32;
3010 if mag % 8 != 0 {
3011 return Err(Error::unsupported(
3012 "AV1 tile",
3013 "a block vector is coded at full-pel precision only",
3014 ));
3015 }
3016 enc.symbol(usize::from(diff < 0), &mut c.sign);
3017 let z = mag - 1;
3018 let class = mv_class_of(z);
3019 enc.symbol(class, &mut c.class);
3020 let local = z - mv_class_base(class);
3021 if class == 0 {
3022 enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit);
3023 } else {
3024 let d = local >> 3;
3025 for i in 0..class {
3026 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
3027 }
3028 }
3029 Ok(())
3030}
3031
3032/// One intrabc block's DV as a residual against [`intrabc_dv_pred`], off the
3033/// `dv` nmv context (decode.rs `read_intrabc_dv` -> `read_mv`).
3034fn write_dv(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, dv: (i32, i32), pred: (i32, i32)) -> Result<()> {
3035 let diff = (dv.0 - pred.0, dv.1 - pred.1);
3036 let joint = match (diff.0 != 0, diff.1 != 0) {
3037 (false, false) => 0,
3038 (false, true) => 1,
3039 (true, false) => 2,
3040 (true, true) => 3,
3041 };
3042 enc.symbol(joint, &mut cdfs.dv_joint);
3043 if diff.0 != 0 {
3044 write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?;
3045 }
3046 if diff.1 != 0 {
3047 write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?;
3048 }
3049 Ok(())
3050}
3051
3052/// The mode-info half of an intrabc block (decode.rs `read_intra_mode`'s
3053/// early return): `skip`, `cdef_idx`, `use_intrabc` and the DV, then nothing
3054/// -- no y/uv mode, no angle delta, no palette, and (because it is skipped)
3055/// no transform size and no residual. Publishes the block into every
3056/// neighbour band an ordinary block leaves behind, at the DC_PRED/uncoded/
3057/// skipped state a decoder reads back for it.
3058fn write_intrabc_block(
3059 enc: &mut SymbolEncoder,
3060 cdfs: &mut Cdfs,
3061 neighbours: &mut Neighbours,
3062 dv: (i32, i32),
3063 mi: (usize, usize),
3064 side: usize,
3065) -> Result<()> {
3066 let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
3067 enc.symbol(1, &mut cdfs.skip[skip_ctx]);
3068 write_cdef_idx(enc, mi, true);
3069 enc.symbol(1, &mut cdfs.intrabc);
3070 write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?;
3071 note_intrabc(dv);
3072 // The bands: DC_PRED mode (what the decoder forces), no coefficients
3073 // anywhere (skip), the block's own side for the partition context, the
3074 // largest transform (`side.min(64)`, decode.rs's `intrabc_skip_tx` arm)
3075 // for the deblock grid, and `skip` itself for the next block's skip
3076 // context.
3077 // One zero level per plane: `neighbour_state` reads `grid[0]` for the DC
3078 // sign vote, and a skipped block leaves every context cleared.
3079 let empty: [Vec<i32>; 3] = [vec![0], vec![0], vec![0]];
3080 for cell in 0..(side / SUB).max(1) {
3081 let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI));
3082 neighbours.above_mode[c + cell] = DC_PRED;
3083 neighbours.left_mode[r + cell] = DC_PRED;
3084 neighbours.above_side[c + cell] = side;
3085 neighbours.left_side[r + cell] = side;
3086 }
3087 neighbours.record_mi_planes(mi, side, &empty, true);
3088 neighbours.record_tx(mi, side, side.min(64));
3089 for cell in 0..side / MI {
3090 neighbours.above_skip[mi.1 + cell] = true;
3091 neighbours.left_skip[mi.0 + cell] = true;
3092 }
3093 Ok(())
3094}
3095
3096fn write_intra_mode(
3097 enc: &mut SymbolEncoder,
3098 cdfs: &mut Cdfs,
3099 neighbours: &mut Neighbours,
3100 block: &BlockCoeffs,
3101 above_mode: usize,
3102 left_mode: usize,
3103 cfl: bool,
3104 // This block's own position in 4x4 mode-info units, for the `cdef_idx`
3105 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
3106 mi: (usize, usize),
3107 // The block's side in samples, which gates the palette syntax below
3108 // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]).
3109 side: usize,
3110) -> usize {
3111 let mode = usize::from(block.mode);
3112 // `av1_get_skip_txfm_context` (decode.rs `Neighbours::skip_txfm_ctx`):
3113 // above + left. Every block this writer codes outside an `allow_intrabc`
3114 // frame is unskipped, so both bands stay false and this stays 0 -- the
3115 // literal every stream before this lane was written with.
3116 let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]);
3117 enc.symbol(0, &mut cdfs.skip[skip_ctx]);
3118 write_cdef_idx(enc, mi, false);
3119 // `read_intrabc_info` (spec 5.11.13): the flag is read for EVERY intra
3120 // block of an `allow_intrabc` frame, not only the ones that use it.
3121 if intrabc_armed() {
3122 enc.symbol(0, &mut cdfs.intrabc);
3123 }
3124 enc.symbol(
3125 mode,
3126 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
3127 );
3128 ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng()));
3129 if (V_PRED..=D67_PRED).contains(&mode) {
3130 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
3131 }
3132 // A block small enough to be offered chroma from luma reads the wider
3133 // table even when it does not take the mode.
3134 let uv_mode = usize::from(block.uv_mode);
3135 if cfl {
3136 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
3137 } else {
3138 enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]);
3139 }
3140 // `angle_delta_uv` (spec `read_intra_angle_info`) off the same CDF array
3141 // the luma delta reads, indexed by the chroma mode.
3142 if (V_PRED..=D67_PRED).contains(&uv_mode) {
3143 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
3144 }
3145 // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from
3146 // the decoder's own read in `read_intra_mode`: on a frame whose header set
3147 // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED`
3148 // chroma pair each carry a use-palette flag. Both contexts are 0 here --
3149 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
3150 // codes none -- exactly the ctx-0 read the decoder does under the same
3151 // condition.
3152 write_palette_syntax(
3153 enc,
3154 cdfs,
3155 neighbours,
3156 block.palette.as_ref(),
3157 block.palette_uv.as_ref(),
3158 mode,
3159 uv_mode,
3160 mi,
3161 side,
3162 );
3163 mode
3164}
3165
3166/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for
3167/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose
3168/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a
3169/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette
3170/// then codes its size, its colours (against the neighbour colour cache) and
3171/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs
3172/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and
3173/// by the three intra arms of the inter-frame writers, which read the same
3174/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`.
3175///
3176/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the
3177/// one point every block passes through), so a block that takes no palette
3178/// still clears what the column held.
3179#[allow(clippy::too_many_arguments)]
3180fn write_palette_syntax(
3181 enc: &mut SymbolEncoder,
3182 cdfs: &mut Cdfs,
3183 neighbours: &mut Neighbours,
3184 palette: Option<&PaletteY>,
3185 palette_uv: Option<&PaletteUv>,
3186 mode: usize,
3187 uv_mode: usize,
3188 mi: (usize, usize),
3189 side: usize,
3190) {
3191 if !screen_armed() {
3192 return;
3193 }
3194 let palette = palette.filter(|_| mode == DC_PRED);
3195 let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
3196 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
3197 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
3198 let uv_cache = neighbours.palette_uv_cache(mi);
3199 if mode == DC_PRED {
3200 enc.symbol(
3201 usize::from(palette.is_some()),
3202 &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],
3203 );
3204 }
3205 if let Some(pal) = palette {
3206 let n = usize::from(pal.size);
3207 enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);
3208 write_palette_colors_y(enc, &pal.colors[..n], &cache);
3209 }
3210 if uv_mode == DC_PRED {
3211 enc.symbol(
3212 usize::from(palette_uv.is_some()),
3213 &mut cdfs.palette_uv_mode[usize::from(palette.is_some())],
3214 );
3215 }
3216 if let Some(pal) = palette_uv {
3217 let n = usize::from(pal.size);
3218 enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]);
3219 write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache);
3220 }
3221 // Both colour-index maps come after BOTH colour lists, in plane order
3222 // (`av1_visit_palette` runs from the caller, past `filter_intra`).
3223 if let Some(pal) = palette {
3224 let n = usize::from(pal.size);
3225 write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);
3226 note_palette(n);
3227 }
3228 if let Some(pal) = palette_uv {
3229 let n = usize::from(pal.size);
3230 write_color_index_map(
3231 enc,
3232 &mut cdfs.palette_uv_color_index[n - 2],
3233 &pal.map,
3234 palette_uv_side(side),
3235 n,
3236 );
3237 note_palette_uv(n);
3238 }
3239 }
3240 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
3241 neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors));
3242}
3243
3244/// The side of a chroma palette's shared colour-index map for a square luma
3245/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at
3246/// the 4-px transform, NOT a plain halving (decode.rs reads the map at
3247/// exactly this size).
3248pub(crate) fn palette_uv_side(side: usize) -> usize {
3249 (side / 2).max(4)
3250}
3251
3252/// How many blocks took a palette, and of what size -- the fire count a gate
3253/// prints so that "palette is on" is a measurement rather than a claim
3254/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the
3255/// per-size histogram.
3256static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
3257 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
3258
3259fn note_palette(n: usize) {
3260 PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3261 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3262}
3263
3264/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can
3265/// print the share of each plane's palette separately.
3266static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] =
3267 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
3268
3269fn note_palette_uv(n: usize) {
3270 PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3271 PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3272}
3273
3274/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than
3275/// the stream -- the half of `write_palette_colors_uv` a test cannot see from
3276/// the block counts alone, and the one that desyncs the tile if this writer's
3277/// cache ever disagrees with the decoder's (`gate-blind-to-feature`).
3278static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize =
3279 std::sync::atomic::AtomicUsize::new(0);
3280
3281/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it.
3282#[cfg(test)]
3283pub(crate) fn take_palette_uv_cache_hits() -> usize {
3284 PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
3285}
3286
3287/// [`take_palette_hits`] for the chroma palette.
3288#[cfg(test)]
3289pub(crate) fn take_palette_uv_hits() -> [usize; 9] {
3290 std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
3291}
3292
3293/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
3294/// its own encode.
3295#[cfg(test)]
3296pub(crate) fn take_palette_hits() -> [usize; 9] {
3297 std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
3298}
3299
3300/// Writes one coded block: its mode, its three transform blocks, and what it
3301/// leaves behind for the blocks beside it. Its partition symbol is already
3302/// written, because only the caller knows what tree led here.
3303#[allow(clippy::too_many_arguments)]
3304fn write_block(
3305 enc: &mut SymbolEncoder,
3306 cdfs: &mut Cdfs,
3307 neighbours: &mut Neighbours,
3308 block: &BlockCoeffs,
3309 at: (usize, usize),
3310 side: usize,
3311 planes: &[TxbSet; 3],
3312 grids: &[Vec<i32>; 3],
3313 scans: [&Vec<u16>; 3],
3314 cfl: bool,
3315 // The frame's `tx_mode == TxMode::Select`, and the block's own chosen
3316 // depth: with it the luma residual goes through [`write_luma_select`]
3317 // (one `tx_depth` symbol, then one transform unit per tile of the block)
3318 // instead of the single whole-block transform below.
3319 tx_select: bool,
3320 all_scans: &[Vec<u16>; 4],
3321) -> Result<()> {
3322 let (r, c) = at;
3323 let at_mi = (r * (SUB / MI), c * (SUB / MI));
3324 if let Some(dv) = block.dv {
3325 write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?;
3326 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv));
3327 return Ok(());
3328 }
3329 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
3330 let mode = write_intra_mode(
3331 enc,
3332 cdfs,
3333 neighbours,
3334 block,
3335 above_mode,
3336 left_mode,
3337 cfl,
3338 at_mi,
3339 side,
3340 );
3341 let split = if tx_select {
3342 let tx = write_luma_select(
3343 enc,
3344 cdfs,
3345 neighbours,
3346 at_mi,
3347 side,
3348 usize::from(block.tx_depth),
3349 &grids[0],
3350 mode,
3351 all_scans,
3352 )?;
3353 tx < side
3354 } else {
3355 false
3356 };
3357 write_block_planes(
3358 enc,
3359 cdfs,
3360 planes,
3361 grids,
3362 &scans,
3363 &neighbours.around(at, side),
3364 mode,
3365 tx_select,
3366 );
3367 neighbours.record_planes(at, side, mode, grids, !split);
3368 clear_skip_band(neighbours, at_mi, side);
3369 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None);
3370 Ok(())
3371}
3372
3373/// An unskipped block's own `skip` publication: only an `allow_intrabc`
3374/// frame ever sets these bands, so a frame without one leaves them exactly
3375/// as they were before this lane (all false).
3376fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) {
3377 if !intrabc_armed() {
3378 return;
3379 }
3380 for cell in 0..side / MI {
3381 neighbours.above_skip[mi.1 + cell] = false;
3382 neighbours.left_skip[mi.0 + cell] = false;
3383 }
3384}
3385
3386/// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
3387/// luma transform and 4x4 chroma transforms, coded exactly like
3388/// [`write_block`] but reading its intra-mode context from the *enclosing*
3389/// 16x16 slot -- `outer_at`, in [`SUB`]-grid units -- rather than from its own
3390/// finer position, since [`Neighbours`]'s `above_mode`/`left_mode` arrays stay
3391/// at [`SUB`] (16-sample) granularity. `leaf_mi` is this leaf's own position
3392/// in 4x4 mode-info units, which is what its coefficient context (finer than
3393/// [`SUB`]) is kept and read at.
3394#[allow(clippy::too_many_arguments)]
3395fn write_leaf8(
3396 enc: &mut SymbolEncoder,
3397 cdfs: &mut Cdfs,
3398 neighbours: &mut Neighbours,
3399 block: &BlockCoeffs,
3400 outer_at: (usize, usize),
3401 leaf_mi: (usize, usize),
3402 grids: &[Vec<i32>; 3],
3403 scans: [&Vec<u16>; 3],
3404 prev_leaf: Option<((usize, usize), usize)>,
3405 tx_select: bool,
3406 all_scans: &[Vec<u16>; 4],
3407) -> Result<usize> {
3408 let (r, c) = outer_at;
3409 if let Some(dv) = block.dv {
3410 write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?;
3411 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv));
3412 return Ok(DC_PRED);
3413 }
3414 let mut above_mode = neighbours.above_mode[c];
3415 let mut left_mode = neighbours.left_mode[r];
3416 // The previous leaf sits directly above (same column, two mi rows up)
3417 // or directly to the left (same row, two mi cols over) of this one --
3418 // in either case its just-written mode, not the enclosing 16x16 slot's
3419 // stale neighbour, is what a decoder reads as this leaf's context.
3420 if let Some(((pr, pc), pmode)) = prev_leaf {
3421 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
3422 above_mode = pmode;
3423 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
3424 left_mode = pmode;
3425 }
3426 }
3427 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
3428 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF -- like every
3429 // other `write_block` caller at 16x16 and up -- not the narrower
3430 // no-CFL one: r12 lane-av1-rect, this leaf's own `cfl: false` was the
3431 // true first divergence (a differently-sized alphabet under the same
3432 // DC_PRED decision desyncs the coder even though the decoded mode is
3433 // unchanged).
3434 let mode = write_intra_mode(enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8);
3435 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
3436 let split = if tx_select {
3437 let tx = write_luma_select(
3438 enc,
3439 cdfs,
3440 neighbours,
3441 leaf_mi,
3442 8,
3443 usize::from(block.tx_depth),
3444 &grids[0],
3445 mode,
3446 all_scans,
3447 )?;
3448 tx < 8
3449 } else {
3450 false
3451 };
3452 write_block_planes(
3453 enc,
3454 cdfs,
3455 &planes,
3456 grids,
3457 &scans,
3458 &neighbours.around_mi(leaf_mi, 8),
3459 mode,
3460 tx_select,
3461 );
3462 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
3463 clear_skip_band(neighbours, leaf_mi, 8);
3464 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None);
3465 Ok(mode)
3466}
3467
3468/// Writes the three transform blocks of one coded block, in the order a
3469/// decoder reads them.
3470#[allow(clippy::too_many_arguments)]
3471fn write_block_planes(
3472 enc: &mut SymbolEncoder,
3473 cdfs: &mut Cdfs,
3474 planes: &[TxbSet; 3],
3475 grids: &[Vec<i32>; 3],
3476 scans: &[&Vec<u16>; 3],
3477 around: &[Around; 3],
3478 mode: usize,
3479 // A block whose luma was already written as several transform units
3480 // ([`write_luma_select`]) has only its chroma planes left here.
3481 skip_luma: bool,
3482) {
3483 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
3484 if plane == 0 && skip_luma {
3485 continue;
3486 }
3487 // Luma's transform covers its whole block, which fixes the all-zero
3488 // flag's context at zero; a chroma transform reads whether its
3489 // neighbours coded anything, on top of the offset the chroma tables
3490 // start at.
3491 let skip_ctx = if plane == 0 {
3492 0
3493 } else {
3494 usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
3495 };
3496 write_coeffs(
3497 enc,
3498 &mut cdfs.txb(planes[plane], mode),
3499 grid,
3500 scan,
3501 skip_ctx,
3502 dc_sign_ctx(around[plane].dc_vote),
3503 Some(plane),
3504 );
3505 ec_rng_trace(|| {
3506 format!(
3507 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
3508 grid.iter().filter(|&&l| l != 0).count(),
3509 enc.tell()
3510 )
3511 });
3512 }
3513}
3514
3515/// The `(side / tx)^2` transform units of one block's luma residual, raster
3516/// order, each with its own coefficient context and each published before the
3517/// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch).
3518/// `grid` is the block's levels in BLOCK coordinates when the transform
3519/// splits, and the single transform's own coefficient grid when it does not.
3520#[allow(clippy::too_many_arguments)]
3521fn write_luma_tus(
3522 enc: &mut SymbolEncoder,
3523 cdfs: &mut Cdfs,
3524 neighbours: &mut Neighbours,
3525 at_mi: (usize, usize),
3526 side: usize,
3527 tx: usize,
3528 grid: &[i32],
3529 mode: usize,
3530 scans: &[Vec<u16>; 4],
3531 // lane-av1tx2 r2: an INTER block's split units read the inter coefficient
3532 // tables, not the intra ones (`TxbSet::Luma*Inter`).
3533 inter: bool,
3534) -> Result<()> {
3535 if tx < side && side > 32 {
3536 // A 64x64 block's own levels reach the writer as the 32x32 corner a
3537 // 64-point transform codes, not as a 64x64 block grid, so there is
3538 // nothing to slice per unit here.
3539 return Err(Error::unsupported(
3540 "AV1 tile",
3541 "a 64x64 block's split luma transform is not written yet",
3542 ));
3543 }
3544 let coeff_side = tx.min(32);
3545 let n = side / tx;
3546 let set = match (tx, inter) {
3547 (32, false) => TxbSet::Luma32,
3548 (16, false) => TxbSet::Luma16,
3549 (8, false) => TxbSet::Luma8,
3550 (4, false) => TxbSet::Luma4,
3551 (32, true) => TxbSet::Luma32Inter,
3552 (16, true) => TxbSet::Luma16Inter,
3553 (8, true) => TxbSet::Luma8Inter,
3554 (4, true) => TxbSet::Luma4Inter,
3555 _ => TxbSet::Luma64,
3556 };
3557 let scan = match coeff_side {
3558 32 => &scans[0],
3559 16 => &scans[1],
3560 8 => &scans[2],
3561 _ => &scans[3],
3562 };
3563 let (mi_r, mi_c) = at_mi;
3564 for tu_row in 0..n {
3565 for tu_col in 0..n {
3566 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
3567 let unit = if n == 1 {
3568 grid.to_vec()
3569 } else {
3570 (0..tx)
3571 .flat_map(|row| {
3572 grid[(tu_row * tx + row) * side + tu_col * tx..][..tx].to_vec()
3573 })
3574 .collect()
3575 };
3576 // spec `get_txb_ctx_general`: a lone transform unit covering its
3577 // whole block reads context 0, a smaller one the neighbour
3578 // magnitude table.
3579 let skip_ctx = if n == 1 {
3580 0
3581 } else {
3582 neighbours.luma_skip_ctx(tu_mi, tx / MI)
3583 };
3584 let around = neighbours.around_mi(tu_mi, tx)[0];
3585 write_coeffs(
3586 enc,
3587 &mut cdfs.txb(set, mode),
3588 &unit,
3589 scan,
3590 skip_ctx,
3591 dc_sign_ctx(around.dc_vote),
3592 Some(0),
3593 );
3594 if n > 1 {
3595 neighbours.record_mi_luma(tu_mi, tx, &unit);
3596 }
3597 }
3598 }
3599 Ok(())
3600}
3601
3602/// Writes one intra block's luma residual under `TxMode::Select`: the
3603/// `tx_depth` symbol (spec 5.11.16 `read_selected_tx_size`, off the size
3604/// category's own CDF at [`Neighbours::tx_size_ctx`]'s row), then the
3605/// `(side / tx)^2` transform units in raster order -- each predicted and
3606/// coded against what the units before it already left behind, which is why
3607/// every unit publishes its own coefficient context before the next one reads
3608/// it (decode.rs `decode_block`'s multi-transform-unit branch).
3609///
3610/// `grid` is the block's levels in BLOCK coordinates (`side` by `side`) when
3611/// the transform splits, and the single transform's own coefficient grid when
3612/// it does not. Hands back the resolved transform side in pixels.
3613#[allow(clippy::too_many_arguments)]
3614fn write_luma_select(
3615 enc: &mut SymbolEncoder,
3616 cdfs: &mut Cdfs,
3617 neighbours: &mut Neighbours,
3618 at_mi: (usize, usize),
3619 side: usize,
3620 depth: usize,
3621 grid: &[i32],
3622 mode: usize,
3623 scans: &[Vec<u16>; 4],
3624) -> Result<usize> {
3625 let max_tx = side.min(64);
3626 let ctx = neighbours.tx_size_ctx(at_mi, max_tx);
3627 match max_tx {
3628 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
3629 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
3630 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
3631 64 => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
3632 _ => {
3633 return Err(Error::unsupported(
3634 "AV1 tile",
3635 "a tx_depth symbol is only coded at 8/16/32/64",
3636 ));
3637 }
3638 }
3639 let tx = max_tx >> depth;
3640 write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false)?;
3641 neighbours.record_tx(at_mi, side, tx);
3642 Ok(tx)
3643}
3644
3645/// The transform syntax one block of an INTER frame coded with
3646/// `tx_mode == TxMode::Select` carries, in the place spec 5.11.16's
3647/// `read_block_tx_size` reads it -- after the modes and the motion vector,
3648/// before the residual:
3649/// * an inter block that codes a residual walks a var-tx tree; this writer
3650/// keeps it at its own largest transform, so that is one `txfm_split` flag
3651/// of zero, off `txfm_partition_ctx_rect`'s row, publishing the bands per
3652/// unit the way `read_var_tx_size` does.
3653/// * a skipped inter block codes nothing and records its own BLOCK size
3654/// (`set_txfm_ctxs`'s `skip_inter` term).
3655/// * an intra block codes `tx_depth` like a key frame's, but off the
3656/// `TXFM_CONTEXT` bands rather than the deblock grid.
3657///
3658/// Hands back the block's resolved luma transform side.
3659#[allow(clippy::too_many_arguments)]
3660fn write_tx_syntax_inter(
3661 enc: &mut SymbolEncoder,
3662 cdfs: &mut Cdfs,
3663 neighbours: &mut Neighbours,
3664 at_mi: (usize, usize),
3665 side: usize,
3666 is_inter: bool,
3667 skip: bool,
3668 depth: usize,
3669) -> usize {
3670 let max_tx = side.min(64);
3671 let (mi_r, mi_c) = at_mi;
3672 if is_inter {
3673 if !skip {
3674 let ctx = txfm_partition_ctx_rect(
3675 neighbours.above_txfm[mi_c],
3676 neighbours.left_txfm[mi_r],
3677 side,
3678 max_tx,
3679 max_tx,
3680 );
3681 enc.symbol(usize::from(depth != 0), &mut cdfs.txfm_partition[ctx]);
3682 if depth == 0 {
3683 neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx);
3684 return max_tx;
3685 }
3686 // lane-av1tx2 r2: one halving of the var-tx tree. Each child of a
3687 // split root codes its own `txfm_split` (decode.rs
3688 // `read_var_tx_size` only stops symbol-free at `MAX_VARTX_DEPTH`
3689 // or at a 4x4 sub-size), off the bands the children before it
3690 // published -- so the context read and the update interleave per
3691 // unit, exactly as the reader's recursion does.
3692 let tx = max_tx / 2;
3693 for row in (0..max_tx / MI).step_by(tx / MI) {
3694 for col in (0..max_tx / MI).step_by(tx / MI) {
3695 let unit = (mi_r + row, mi_c + col);
3696 // The encoder only picks depth 1 for a block wholly
3697 // inside the frame; the reader skips a unit past the true
3698 // edge, which would leave the residual units unpaired.
3699 debug_assert!(
3700 unit.0 < neighbours.mi_rows && unit.1 < neighbours.mi_cols,
3701 "a split inter transform unit past the frame edge"
3702 );
3703 let ctx = txfm_partition_ctx_rect(
3704 neighbours.above_txfm[unit.1],
3705 neighbours.left_txfm[unit.0],
3706 side,
3707 tx,
3708 tx,
3709 );
3710 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
3711 neighbours.record_txfm(unit, tx, tx, tx);
3712 }
3713 }
3714 return tx;
3715 }
3716 neighbours.record_txfm(at_mi, side, side, side);
3717 return max_tx;
3718 }
3719 let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx);
3720 match max_tx {
3721 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
3722 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
3723 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
3724 _ => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
3725 }
3726 let tx = max_tx >> depth;
3727 neighbours.record_txfm(at_mi, tx, side, side);
3728 tx
3729}
3730
3731/// What a coded transform block leaves behind for the blocks that read it as a
3732/// neighbour.
3733fn neighbour_state(grid: &[i32]) -> Neighbour {
3734 Neighbour {
3735 coded: grid.iter().any(|&l| l != 0),
3736 level: grid.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8,
3737 dc: (grid[0] != 0).then_some(grid[0] < 0),
3738 }
3739}
3740
3741/// Writes the payload of a one-tile key frame in which every superblock is
3742/// split into 32x32 blocks, each carrying the coefficients `blocks` gives it.
3743///
3744/// `blocks` gives one coefficient set per 32x32 block in raster order across
3745/// the frame. This is [`sb_coeff_key_frame_tile`] with every superblock split.
3746///
3747/// # Errors
3748/// As [`sb_coeff_key_frame_tile`], with `blocks` sized for the 32x32 grid.
3749pub fn split_coeff_key_frame_tile(
3750 mi_cols: u32,
3751 mi_rows: u32,
3752 base_q_idx: u8,
3753 blocks: &[BlockCoeffs],
3754) -> Result<Vec<u8>> {
3755 check_blocks(mi_cols, mi_rows)?;
3756 let (cols, rows) = block_grid(mi_cols, mi_rows);
3757 if blocks.len() != (cols * rows) as usize {
3758 return Err(Error::unsupported(
3759 "AV1 tile",
3760 "a coefficient key frame needs one coefficient set per 32x32 block",
3761 ));
3762 }
3763 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
3764 let superblocks: Vec<Superblock> = (0..sb_rows)
3765 .flat_map(|sb_r| (0..sb_cols).map(move |sb_c| (sb_r, sb_c)))
3766 .map(|(sb_r, sb_c)| {
3767 Superblock::Split(
3768 (0..4)
3769 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
3770 .filter(|&(r, c)| r < rows && c < cols)
3771 .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone()))
3772 .collect(),
3773 )
3774 })
3775 .collect();
3776 sb_coeff_key_frame_tile(mi_cols, mi_rows, base_q_idx, &superblocks)
3777}
3778
3779/// Lays one plane's coefficient list out over its transform, rejecting the
3780/// positions and levels the writer does not code.
3781fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
3782 let mut grid = vec![0i32; side * side];
3783 for coeff in coeffs {
3784 if usize::from(coeff.row) >= side || usize::from(coeff.col) >= side {
3785 return Err(Error::unsupported(
3786 "AV1 tile",
3787 "a coefficient sits outside the transform of its plane",
3788 ));
3789 }
3790 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
3791 return Err(Error::unsupported(
3792 "AV1 tile",
3793 format!(
3794 "coefficients are written for levels -{MAX_LEVEL}..={MAX_LEVEL} without zero"
3795 ),
3796 ));
3797 }
3798 let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
3799 if grid[pos] != 0 {
3800 return Err(Error::unsupported(
3801 "AV1 tile",
3802 "two coefficients of one block share a position",
3803 ));
3804 }
3805 grid[pos] = coeff.level;
3806 }
3807 Ok(grid)
3808}
3809
3810/// The default scan of a square transform (spec 8.4.2's `Default_Scan_NxN`),
3811/// as raster positions in the order they are coded.
3812///
3813/// The table is a rule rather than hundreds of pinned numbers: the scan walks
3814/// the anti-diagonals of the transform outwards from the origin, each diagonal
3815/// from its top-right end on odd diagonals and from its bottom-left end on
3816/// even ones.
3817fn default_scan(side: usize) -> Vec<u16> {
3818 let mut scan = Vec::with_capacity(side * side);
3819 for d in 0..(2 * side - 1) {
3820 let lo = d.saturating_sub(side - 1);
3821 let hi = d.min(side - 1);
3822 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
3823 if d % 2 == 0 {
3824 scan.extend(diagonal.rev());
3825 } else {
3826 scan.extend(diagonal);
3827 }
3828 }
3829 scan
3830}
3831
3832/// What one 32x32 luma transform block's levels cost, in bits, priced through
3833/// the very CDFs [`write_coeffs`] will write them with -- end-of-block
3834/// position, base levels, base range, signs and the Golomb tail all included.
3835///
3836/// The mode search calls this before the block's neighbours exist, so the two
3837/// neighbour-derived contexts (the block-skip context and the DC sign context)
3838/// are taken as zero. Every other context inside the block is exact, because
3839/// those are read from the block's own levels.
3840///
3841/// The encoder codes 32x32 luma only -- every superblock it emits is split --
3842/// so one table is all the search needs; a second block size would need its
3843/// own entry point rather than a size argument, because the table and the scan
3844/// have to agree.
3845/// What the search paid for every coefficient of `blocks`, in bits: the same
3846/// [`coeff_bits`] price the mode search ranked those blocks by, summed over
3847/// the blocks that were actually kept.
3848///
3849/// The instrument behind `predicted_coeff_bits_track_the_tile_the_writer_wrote`
3850/// (lane-av1rd1): the writer codes these levels against a state that has
3851/// adapted away from the defaults `coeff_bits` prices with, and against real
3852/// neighbour contexts instead of the empty ones, so the sum here and the tile
3853/// the writer produced differ by exactly that drift plus the non-coefficient
3854/// syntax (partition/mode/skip/mv symbols) the sum leaves out.
3855#[cfg(test)]
3856fn dense(coeffs: &[Coeff], side: usize) -> Vec<i32> {
3857 let mut grid = vec![0i32; side * side];
3858 for c in coeffs {
3859 grid[usize::from(c.row) * side + usize::from(c.col)] = c.level;
3860 }
3861 grid
3862}
3863
3864#[cfg(test)]
3865pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8) -> f64 {
3866 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
3867 superblocks
3868 .iter()
3869 .map(|sb| match sb {
3870 // A whole 64x64 codes its luma through `TxbSet::Luma64` (only the
3871 // top-left 32x32 carries coefficients) and each chroma plane at
3872 // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here.
3873 Superblock::Whole(block) if !block.skip => {
3874 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx)
3875 + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx)
3876 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx)
3877 }
3878 Superblock::Whole(_) => 0.0,
3879 Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx),
3880 })
3881 .sum()
3882}
3883
3884#[cfg(test)]
3885pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
3886 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
3887 fn block_bits(block: &BlockCoeffs, side: usize, q_ctx: usize) -> f64 {
3888 if let Some(leaves) = &block.eight {
3889 return leaves.iter().map(|l| block_bits(l, 8, q_ctx)).sum();
3890 }
3891 if block.skip {
3892 return 0.0;
3893 }
3894 let inter = block.inter.is_some();
3895 let (luma, chroma) = match (side, inter) {
3896 (32, false) => (TxbSet::Luma32, TxbSet::Chroma16),
3897 (32, true) => (TxbSet::Luma32Inter, TxbSet::Chroma16),
3898 (16, false) => (TxbSet::Luma16, TxbSet::Chroma8),
3899 (16, true) => (TxbSet::Luma16Inter, TxbSet::Chroma8),
3900 (_, false) => (TxbSet::Luma8, TxbSet::Chroma4),
3901 (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4),
3902 };
3903 coeff_bits(&dense(&block.luma, side), luma, q_ctx)
3904 + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx)
3905 + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx)
3906 }
3907 blocks
3908 .iter()
3909 .map(|q| {
3910 let side = match q {
3911 Quadrant::Whole(_) => 32,
3912 Quadrant::Split(_) => 16,
3913 };
3914 q.blocks().iter().map(|b| block_bits(b, side, q_ctx)).sum::<f64>()
3915 })
3916 .sum()
3917}
3918
3919#[cfg(test)]
3920pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
3921 coeff_bits(grid, TxbSet::Luma32, 2)
3922}
3923
3924/// What one transform block's levels cost through the CDFs of `set`, in bits.
3925///
3926/// The search runs before the tile is written, so the adapted state the block
3927/// will really be coded against does not exist yet: the price is taken against
3928/// the defaults every tile starts from, at the frame's own coefficient
3929/// q-context (`q_ctx_of(base_q_idx)`, what `Cdfs::new` is given at
3930/// `sb_coeff_*_tile` -- lane-av1rd1: this used to be pinned at 2, so two of
3931/// the four points of the BD ladder were priced against another quantizer's
3932/// tables), and against the contexts a block whose neighbours coded nothing
3933/// reads.
3934pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
3935 /// Built once per size: the search prices thirteen modes for every block,
3936 /// and the scan is the same table every time.
3937 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {
3938 [
3939 default_scan(TX4),
3940 default_scan(TX8),
3941 default_scan(TX16),
3942 default_scan(TX32),
3943 ]
3944 });
3945 // `Cdfs::new` builds every table a tile writer adapts -- tens of
3946 // kilobytes -- and this function is called once per priced candidate:
3947 // together with the copy behind it that was 9% of the encoder's profile
3948 // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the
3949 // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per
3950 // q-context per thread beside a pristine one and restore just those from
3951 // it. The state the price is taken against is identical to a fresh
3952 // `Cdfs::new(q_ctx)`, so every price is bit-identical.
3953 thread_local! {
3954 static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
3955 const { RefCell::new([None, None, None, None]) };
3956 }
3957 PRICING.with_borrow_mut(|slots| {
3958 let slot = slots[q_ctx.min(3)]
3959 .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
3960 let (pristine, scratch) = (&mut slot.0, &mut slot.1);
3961 let src = pristine.txb(set, DC_PRED);
3962 let mut coding = scratch.txb(set, DC_PRED);
3963 coding.txb_skip.copy_from_slice(src.txb_skip);
3964 coding.eob_pt.copy_from_slice(src.eob_pt);
3965 if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) {
3966 dst.copy_from_slice(src);
3967 }
3968 *coding.eob_extra = *src.eob_extra;
3969 *coding.base = *src.base;
3970 *coding.base_eob = *src.base_eob;
3971 *coding.br = *src.br;
3972 *coding.dc_sign = *src.dc_sign;
3973 if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) {
3974 dst.copy_from_slice(src);
3975 }
3976 let scan = match coding.side {
3977 TX4 => &SCANS[0],
3978 TX8 => &SCANS[1],
3979 TX16 => &SCANS[2],
3980 _ => &SCANS[3],
3981 };
3982 let mut enc = SymbolEncoder::pricer();
3983 write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);
3984 enc.bits()
3985 })
3986}
3987
3988/// What the partition symbol of a block of `side` samples costs, in bits, when
3989/// it says the block is split (or that it is not).
3990///
3991/// The price is taken at context zero — a block whose neighbours are no finer
3992/// than it is — because the search that reads it runs before the tile knows
3993/// what its neighbours will be.
3994pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
3995 // Read-only, and the same tables every call: built once (see
3996 // [`coeff_bits`] for why that matters here).
3997 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
3998 let cdfs = &*CDFS;
3999 let cdf: &[u16] = match side {
4000 SB => &cdfs.partition_w64[0],
4001 BLOCK => &cdfs.partition_w32[0],
4002 TX8 => &cdfs.partition_w8[0],
4003 _ => &cdfs.partition_w16[0],
4004 };
4005 let symbol = if split {
4006 PARTITION_SPLIT
4007 } else {
4008 PARTITION_NONE
4009 };
4010 crate::encode::symbol_bits(cdf, symbol)
4011}
4012
4013/// coeffs() for one plane's transform block of any coefficients the base and
4014/// base-range syntax reach (spec 5.11.39).
4015///
4016/// A 16x16 luma transform codes which transform type it is, because its set
4017/// holds more than one; 32x32 and 64x64 are DCT-only by spec 5.11.40. The
4018/// levels the contexts below are read from are the levels of
4019/// coefficients later in the scan, which a decoder walking the scan backwards
4020/// already has.
4021#[allow(clippy::too_many_arguments)]
4022fn write_coeffs(
4023 enc: &mut SymbolEncoder,
4024 coding: &mut TxbTables,
4025 grid: &[i32],
4026 scan: &[u16],
4027 skip_ctx: usize,
4028 sign_ctx: usize,
4029 plane: Option<usize>,
4030) {
4031 if let Some(plane) = plane {
4032 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));
4033 }
4034 let side = coding.side;
4035 // The scan-order search reads the grid in scan order, one dependent load
4036 // per position, and an all-zero block makes it walk every one of them --
4037 // which the pricer does for candidate after candidate. A straight-line
4038 // pass settles that case first: it vectorises, and a block that codes
4039 // anything at all almost always codes its DC, so it stops at the first
4040 // element.
4041 let eob = if grid.iter().all(|&level| level == 0) {
4042 0
4043 } else {
4044 scan.iter()
4045 .rposition(|&pos| grid[pos as usize] != 0)
4046 .map_or(0, |i| i + 1)
4047 };
4048 enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]);
4049 if plane.is_some() {
4050 ec_rng_trace(|| {
4051 format!(
4052 "EC_TXBSKIP ctx={skip_ctx} eob0={} tell={} rng={}",
4053 usize::from(eob == 0),
4054 enc.tell(),
4055 enc.rng()
4056 )
4057 });
4058 }
4059 if eob == 0 {
4060 return;
4061 }
4062 // A luma transform whose type set holds more than one type codes which it
4063 // is, right after the all-zero flag (spec 5.11.39). The writer only ever
4064 // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.
4065 if let Some(tx_type) = coding.tx_type.as_deref_mut() {
4066 enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type);
4067 if plane.is_some() {
4068 ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng()));
4069 }
4070 }
4071
4072 write_eob(enc, coding, eob, plane);
4073
4074 for scan_idx in (0..eob).rev() {
4075 let pos = scan[scan_idx] as usize;
4076 let (row, col) = (pos / side, pos % side);
4077 let level = grid[pos].abs();
4078 if scan_idx == eob - 1 {
4079 let ctx = eob_coeff_ctx(scan_idx, side * side);
4080 let sym = (level.min(NUM_BASE_LEVELS + 1) - 1) as usize;
4081 enc.symbol(sym, &mut coding.base_eob[ctx]);
4082 if plane.is_some() {
4083 ec_rng_trace(|| {
4084 format!(
4085 "EC_BASEEOB scan_idx={scan_idx} ctx={ctx} level={} tell={}",
4086 sym + 1,
4087 enc.tell()
4088 )
4089 });
4090 }
4091 } else {
4092 let ctx = base_ctx(grid, side, row, col);
4093 let sym = level.min(NUM_BASE_LEVELS + 1) as usize;
4094 enc.symbol(sym, &mut coding.base[ctx]);
4095 if plane.is_some() {
4096 ec_rng_trace(|| {
4097 format!(
4098 "EC_BASE scan_idx={scan_idx} ctx={ctx} level={sym} tell={}",
4099 enc.tell()
4100 )
4101 });
4102 }
4103 }
4104 if level > NUM_BASE_LEVELS {
4105 let ctx = br_ctx(grid, side, row, col);
4106 let mut remaining = level - (NUM_BASE_LEVELS + 1);
4107 let mut sent = 0;
4108 while sent < COEFF_BASE_RANGE {
4109 let k = remaining.min(BR_STEP);
4110 enc.symbol(k as usize, &mut coding.br[ctx]);
4111 if plane.is_some() {
4112 ec_rng_trace(|| {
4113 format!(
4114 "EC_BR scan_idx={scan_idx} ctx={ctx} k={k} tell={}",
4115 enc.tell()
4116 )
4117 });
4118 }
4119 if k < BR_STEP {
4120 break;
4121 }
4122 remaining -= k;
4123 sent += BR_STEP;
4124 }
4125 }
4126 }
4127
4128 // The signs come after the levels, in scan order, the DC's from a CDF and
4129 // the rest as raw bits (spec 5.11.39).
4130 for &pos in &scan[..eob] {
4131 let level = grid[pos as usize];
4132 if level == 0 {
4133 continue;
4134 }
4135 if pos == 0 {
4136 enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]);
4137 if plane.is_some() {
4138 ec_rng_trace(|| {
4139 format!(
4140 "EC_DCSIGN ctx={sign_ctx} neg={} tell={}",
4141 usize::from(level < 0),
4142 enc.tell()
4143 )
4144 });
4145 }
4146 } else {
4147 enc.literal(u32::from(level < 0), 1);
4148 }
4149 // A level the base and base-range syntax cannot reach carries the rest
4150 // of itself here, after its own sign (spec 5.11.39).
4151 if level.abs() > MAX_BR_LEVEL {
4152 write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32);
4153 if plane.is_some() {
4154 ec_rng_trace(|| format!("EC_GOLOMB tell={}", enc.tell()));
4155 }
4156 }
4157 }
4158 if let Some(plane) = plane {
4159 ec_rng_trace(|| format!("EC_PLANE plane={plane} eob={eob} tell_after={}", enc.tell()));
4160 }
4161}
4162
4163/// The end-of-block position (spec 5.11.39): which group of scan positions the
4164/// last coded coefficient falls in, then its offset inside that group — the
4165/// offset's top bit from a CDF and the rest as raw bits.
4166fn write_eob(enc: &mut SymbolEncoder, coding: &mut TxbTables, eob: usize, plane: Option<usize>) {
4167 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
4168 /// end-of-block positions covers, indexed by the group's own number.
4169 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
4170 /// `Eob_Offset_Bits` (spec 5.11.39): how wide each group's offset is.
4171 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
4172
4173 let group = GROUP_START
4174 .iter()
4175 .rposition(|&start| start <= eob)
4176 .expect("the first group starts at zero");
4177 // The groups are numbered from one, and how many of them the transform
4178 // reaches is the size of its own end-of-block alphabet.
4179 enc.symbol(group - 1, coding.eob_pt);
4180 if let Some(plane) = plane {
4181 ec_rng_trace(|| {
4182 format!(
4183 "EC_EOBPT plane={plane} eob_pt={group} tell={} rng={}",
4184 enc.tell(),
4185 enc.rng()
4186 )
4187 });
4188 }
4189
4190 let bits = OFFSET_BITS[group];
4191 if bits > 0 {
4192 let offset = (eob - GROUP_START[group]) as u32;
4193 let top = (offset >> (bits - 1)) & 1;
4194 enc.symbol(top as usize, &mut coding.eob_extra[group - 3]);
4195 if let Some(plane) = plane {
4196 ec_rng_trace(|| {
4197 format!(
4198 "EC_EOBEXTRA plane={plane} eob_ctx={} top={top} tell={}",
4199 group - 3,
4200 enc.tell()
4201 )
4202 });
4203 }
4204 if bits > 1 {
4205 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
4206 if let Some(plane) = plane {
4207 ec_rng_trace(|| {
4208 format!(
4209 "EC_EOBBITS plane={plane} eob_extra={offset} tell={}",
4210 enc.tell()
4211 )
4212 });
4213 }
4214 }
4215 }
4216}
4217
4218/// Writes the remainder of a level the base and base-range syntax could not
4219/// reach (spec 5.11.40): the value plus one, as its bit length in unary
4220/// followed by the value's own bits, most significant first.
4221pub(crate) fn write_golomb(enc: &mut SymbolEncoder, value: u32) {
4222 let x = value + 1;
4223 let length = 32 - x.leading_zeros();
4224 for _ in 0..length - 1 {
4225 enc.literal(0, 1);
4226 }
4227 for i in (0..length).rev() {
4228 enc.literal((x >> i) & 1, 1);
4229 }
4230}
4231
4232/// The context of the level of the last coded coefficient (spec 8.3.2): how
4233/// far into the scan it sits, in quarters and eighths of the transform.
4234fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
4235 match scan_idx {
4236 0 => 0,
4237 i if i <= area / 8 => 1,
4238 i if i <= area / 4 => 2,
4239 _ => 3,
4240 }
4241}
4242
4243/// The context of a coefficient's level (spec 8.3.2): the magnitudes of the
4244/// five neighbours below and to the right of it — the ones a decoder walking
4245/// the scan backwards already has — plus a term for where in the transform it
4246/// sits. The DC reads context 0 whatever its neighbours carry.
4247fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
4248 if row == 0 && col == 0 {
4249 return 0;
4250 }
4251 // A coefficient two rows and two columns clear of the far edges reaches
4252 // all five neighbours, so the gather is five loads off one index with no
4253 // per-neighbour edge test -- which is where this writer spends a third of
4254 // its coefficient loop.
4255 let p = row * side + col;
4256 let mag: i32 = if row + 2 < side && col + 2 < side {
4257 [p + side, p + 1, p + side + 1, p + 2 * side, p + 2]
4258 .iter()
4259 .map(|&i| grid[i].abs().min(3))
4260 .sum()
4261 } else {
4262 [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
4263 .iter()
4264 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
4265 .sum()
4266 };
4267 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
4268 (((mag + 1) >> 1).min(4) as usize) + offset
4269}
4270
4271/// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes
4272/// of its three closest neighbours below and to the right, uncapped, and a
4273/// term separating the DC, the corner of the transform, and the rest.
4274fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
4275 let p = row * side + col;
4276 let mag: i32 = if row + 1 < side && col + 1 < side {
4277 grid[p + side].abs() + grid[p + 1].abs() + grid[p + side + 1].abs()
4278 } else {
4279 [(1, 0), (0, 1), (1, 1)]
4280 .iter()
4281 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
4282 .sum()
4283 };
4284 let mag = (((mag + 1) >> 1).min(6)) as usize;
4285 if row == 0 && col == 0 {
4286 mag
4287 } else if row < 2 && col < 2 {
4288 mag + 7
4289 } else {
4290 mag + 14
4291 }
4292}
4293
4294/// A level at a position that may fall off the transform, where the levels a
4295/// context reads are zero.
4296fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
4297 if row >= side || col >= side {
4298 0
4299 } else {
4300 grid[row * side + col]
4301 }
4302}
4303
4304/// Shared by both DC writers: one level per block, none of them zero.
4305fn check_levels(levels: &[i32], blocks: usize) -> Result<()> {
4306 if levels.len() != blocks {
4307 return Err(Error::unsupported(
4308 "AV1 tile",
4309 "a DC-only key frame needs one level per coded block",
4310 ));
4311 }
4312 if levels.iter().any(|&l| l == 0 || l.abs() > MAX_BR_LEVEL) {
4313 return Err(Error::unsupported(
4314 "AV1 tile",
4315 "a DC-only key frame is written for levels -14..=14 without zero; \
4316 wider levels need the Golomb tail",
4317 ));
4318 }
4319 Ok(())
4320}
4321
4322/// coeffs() for a luma transform block whose only coefficient is the DC (spec
4323/// 5.11.39). The block size is the transform size, so the all-zero flag's
4324/// context is 0; an end-of-block of one is token 0 of the position alphabet
4325/// with no extra bits; the transform sizes here are all DCT-only, so no
4326/// transform type is coded; and the DC's own neighbours are zero, so its
4327/// magnitude contexts are 0 throughout.
4328fn write_dc_coeffs(
4329 enc: &mut SymbolEncoder,
4330 dc_level: i32,
4331 sign_ctx: usize,
4332 q_ctx: usize,
4333 txb_skip: &[u16],
4334 base_eob: &[u16],
4335) {
4336 use crate::cdf_state::pick;
4337 let level = dc_level.abs();
4338 let eob_pt = pick(
4339 q_ctx,
4340 cdf::EOB_PT_1024_LUMA_Q0,
4341 cdf::EOB_PT_1024_LUMA_Q1,
4342 cdf::EOB_PT_1024_LUMA,
4343 cdf::EOB_PT_1024_LUMA_Q3,
4344 );
4345 let br = pick(
4346 q_ctx,
4347 cdf::COEFF_BR_LUMA_32_Q0,
4348 cdf::COEFF_BR_LUMA_32_Q1,
4349 cdf::COEFF_BR_LUMA_32,
4350 cdf::COEFF_BR_LUMA_32_Q3,
4351 );
4352 enc.symbol_fixed(0, txb_skip);
4353 enc.symbol_fixed(0, &eob_pt);
4354 enc.symbol_fixed((level.min(NUM_BASE_LEVELS + 1) - 1) as usize, base_eob);
4355 if level > NUM_BASE_LEVELS {
4356 let mut remaining = level - (NUM_BASE_LEVELS + 1);
4357 let mut sent = 0;
4358 while sent < COEFF_BASE_RANGE {
4359 let k = remaining.min(BR_STEP);
4360 enc.symbol_fixed(k as usize, &br[0]);
4361 if k < BR_STEP {
4362 break;
4363 }
4364 remaining -= k;
4365 sent += BR_STEP;
4366 }
4367 }
4368 // The signs come after the levels, DC first (spec 5.11.39).
4369 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
4370}
4371
4372/// One 4x4 unit's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for a
4373/// positive DC, minus one for a negative one, nothing for a unit whose block
4374/// carried no DC or that sits past the frame's true edge (spec
4375/// `av1_set_entropy_contexts`), which is why the vote is gathered per 4x4
4376/// unit and not per coded cell -- a unit past the edge does not vote even
4377/// when the rest of its cell does.
4378fn dc_vote(dc: Option<bool>) -> i32 {
4379 match dc {
4380 None => 0,
4381 Some(true) => -1,
4382 Some(false) => 1,
4383 }
4384}
4385
4386/// Which of the three DC sign contexts a gathered vote picks.
4387fn dc_sign_ctx(vote: i32) -> usize {
4388 match vote.signum() {
4389 0 => 0,
4390 -1 => 1,
4391 _ => 2,
4392 }
4393}
4394
4395/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`,
4396/// `pred_common.c`): both neighbours' intra/inter state when both are
4397/// available, one neighbour's when only one is, and zero at a tile's own
4398/// top-left corner.
4399fn intra_inter_ctx(has_above: bool, has_left: bool, above_inter: bool, left_inter: bool) -> usize {
4400 match (has_above, has_left) {
4401 (true, true) => {
4402 let (above_intra, left_intra) = (!above_inter, !left_inter);
4403 if above_intra && left_intra {
4404 3
4405 } else {
4406 usize::from(above_intra || left_intra)
4407 }
4408 }
4409 (true, false) => 2 * usize::from(!above_inter),
4410 (false, true) => 2 * usize::from(!left_inter),
4411 (false, false) => 0,
4412 }
4413}
4414
4415/// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`
4416/// component's own bits start counting from; class zero starts at zero.
4417fn mv_class_base(class: usize) -> i32 {
4418 if class == 0 { 0 } else { 2i32 << (class + 2) }
4419}
4420
4421/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse
4422/// of `mv_class_base`'s doubling ranges, ported from libaom's
4423/// `av1_get_mv_class` (`mv.h`).
4424fn mv_class_of(z: i32) -> usize {
4425 let mut class = 0;
4426 while class < 10 && mv_class_base(class + 1) <= z {
4427 class += 1;
4428 }
4429 class
4430}
4431
4432/// Writes one motion vector component's non-zero diff (spec 5.11.32
4433/// `read_mv_component`, run backwards): sign, class, then the class's own
4434/// bits. `allow_high_precision_mv` is off in every frame this writer codes,
4435/// so the eighth-pel bit is always inferred as one rather than coded — which
4436/// means only diffs whose eighth-pel bit really is one are representable;
4437/// anything else is refused rather than rounded, since rounding would silently
4438/// code a different vector than the caller asked for.
4439///
4440/// # Errors
4441/// Returns an error when `diff` needs the eighth-pel precision this writer's
4442/// frames do not carry.
4443fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
4444 debug_assert_ne!(diff, 0);
4445 let sign = diff < 0;
4446 enc.symbol(usize::from(sign), &mut c.sign);
4447 let mag = diff.unsigned_abs() as i32;
4448 let z = mag - 1;
4449 if z & 1 == 0 {
4450 return Err(Error::unsupported(
4451 "AV1 tile",
4452 "a motion vector component needs eighth-pel precision, which \
4453 allow_high_precision_mv off does not carry",
4454 ));
4455 }
4456 let class = mv_class_of(z);
4457 enc.symbol(class, &mut c.class);
4458 let local = z - mv_class_base(class);
4459 if class == 0 {
4460 let bit = (local >> 3) & 1;
4461 let fr = (local >> 1) & 3;
4462 enc.symbol(bit as usize, &mut c.class0_bit);
4463 enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]);
4464 } else {
4465 let d = local >> 3;
4466 let fr = (local >> 1) & 3;
4467 for i in 0..class {
4468 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
4469 }
4470 enc.symbol(fr as usize, &mut c.fr);
4471 }
4472 // The eighth-pel bit itself is inferred, not coded (spec 5.11.32: "if
4473 // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
4474 Ok(())
4475}
4476
4477/// Writes a motion vector as a residual against `pred` (spec 5.11.32
4478/// `read_mv`): the joint symbol naming which components differ, then each
4479/// differing component.
4480fn write_mv(
4481 enc: &mut SymbolEncoder,
4482 mv_comp: &mut [MvComponentCdfs; 2],
4483 mv_joint: &mut [u16; 5],
4484 mv: (i32, i32),
4485 pred: (i32, i32),
4486) -> Result<()> {
4487 let diff = (mv.0 - pred.0, mv.1 - pred.1);
4488 let joint = match (diff.0 != 0, diff.1 != 0) {
4489 (false, false) => 0, // MV_JOINT_ZERO
4490 (false, true) => 1, // MV_JOINT_HNZVZ: column only
4491 (true, false) => 2, // MV_JOINT_HZVNZ: row only
4492 (true, true) => 3, // MV_JOINT_HNZVNZ
4493 };
4494 enc.symbol(joint, mv_joint);
4495 if diff.0 != 0 {
4496 write_mv_component(enc, &mut mv_comp[0], diff.0)?;
4497 }
4498 if diff.1 != 0 {
4499 write_mv_component(enc, &mut mv_comp[1], diff.1)?;
4500 }
4501 Ok(())
4502}
4503
4504/// What a block leaves in the neighbour reference bands: its own reference,
4505/// or `-1` when it is intra (decode.rs `Neighbours::above_ref`'s convention).
4506fn block_ref(block: &BlockCoeffs) -> i8 {
4507 block.inter.map_or(-1, |i| i.ref_frame)
4508}
4509
4510/// Writer-side counterpart of decode.rs `read_single_ref` (spec 5.11.25's
4511/// `single_ref_p1`..`p6` tree): codes `ref_frame` bit by bit, each symbol at
4512/// the context its own `single_ref_p*_ctx` derives from the immediate
4513/// above/left neighbours' references -- the same functions the decoder calls,
4514/// with `-1` standing for an intra or unavailable neighbour and no second
4515/// reference (this writer codes no compound block).
4516fn write_single_ref(
4517 enc: &mut SymbolEncoder,
4518 cdfs: &mut Cdfs,
4519 ref_frame: i8,
4520 above_ref: i8,
4521 above_ref1: Option<i8>,
4522 left_ref: i8,
4523 left_ref1: Option<i8>,
4524) {
4525 REF_HITS[(ref_frame.max(1) - 1) as usize % 7].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4526 use crate::mvstack::{
4527 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4528 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4529 single_ref_p5_ctx, single_ref_p6_ctx,
4530 };
4531 let above = (above_ref > 0).then_some(above_ref);
4532 let left = (left_ref > 0).then_some(left_ref);
4533 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
4534 // neighbour's references (decode.rs `read_single_ref`'s own
4535 // `above_ref1`/`left_ref1`): dropping the second one reads a different
4536 // context row for every block sitting under a compound neighbour, and so
4537 // decodes a different reference NAME.
4538 let backward = ref_frame >= BWDREF_FRAME;
4539 enc.symbol(
4540 usize::from(backward),
4541 &mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0],
4542 );
4543 if backward {
4544 let is_altref = ref_frame == ALTREF_FRAME;
4545 enc.symbol(
4546 usize::from(is_altref),
4547 &mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1],
4548 );
4549 if !is_altref {
4550 enc.symbol(
4551 usize::from(ref_frame == ALTREF2_FRAME),
4552 &mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5],
4553 );
4554 }
4555 return;
4556 }
4557 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4558 enc.symbol(
4559 usize::from(far),
4560 &mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2],
4561 );
4562 if far {
4563 enc.symbol(
4564 usize::from(ref_frame == GOLDEN_FRAME),
4565 &mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4],
4566 );
4567 } else {
4568 enc.symbol(
4569 usize::from(ref_frame == LAST2_FRAME),
4570 &mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3],
4571 );
4572 }
4573}
4574
4575/// Per-mode fire counts of [`write_inter_mode`], indexed
4576/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block
4577/// coded (bucket 3 collects any index past 2). Read by the BD gate, which
4578/// is the only thing that proves a newly added mode ever fires
4579/// (gate-blind-to-feature).
4580static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [
4581 std::sync::atomic::AtomicUsize::new(0),
4582 std::sync::atomic::AtomicUsize::new(0),
4583 std::sync::atomic::AtomicUsize::new(0),
4584 std::sync::atomic::AtomicUsize::new(0),
4585];
4586static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [
4587 std::sync::atomic::AtomicUsize::new(0),
4588 std::sync::atomic::AtomicUsize::new(0),
4589 std::sync::atomic::AtomicUsize::new(0),
4590 std::sync::atomic::AtomicUsize::new(0),
4591];
4592
4593/// One counter per reference name (`LAST`..`ALTREF`), for the gate's own
4594/// census of what the encoder actually picks.
4595static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [
4596 std::sync::atomic::AtomicUsize::new(0),
4597 std::sync::atomic::AtomicUsize::new(0),
4598 std::sync::atomic::AtomicUsize::new(0),
4599 std::sync::atomic::AtomicUsize::new(0),
4600 std::sync::atomic::AtomicUsize::new(0),
4601 std::sync::atomic::AtomicUsize::new(0),
4602 std::sync::atomic::AtomicUsize::new(0),
4603];
4604
4605/// Takes and clears the per-reference histogram.
4606#[cfg(test)]
4607pub(crate) fn take_ref_hits() -> [usize; 7] {
4608 std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4609}
4610
4611/// Bumps the two histograms for one coded inter block.
4612fn note_inter_mode(mode: usize, drl: usize) {
4613 INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4614 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4615}
4616
4617/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW).
4618#[cfg(test)]
4619pub(crate) fn take_inter_mode_hits() -> [usize; 4] {
4620 [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4621}
4622
4623/// Takes and clears the DRL-index histogram (0, 1, 2, 3+).
4624#[cfg(test)]
4625pub(crate) fn take_drl_hits() -> [usize; 4] {
4626 [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4627}
4628
4629/// Writes the DRL index of one block: the loop the decoder runs (spec
4630/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
4631/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
4632/// stop, at most two bits. `drl_ctx[idx]` is the context between
4633/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses
4634/// between.
4635fn write_drl_idx(
4636 enc: &mut SymbolEncoder,
4637 cdfs: &mut Cdfs,
4638 stack: &crate::mvstack::MvStack,
4639 start: usize,
4640 target: usize,
4641) {
4642 let mut idx = start;
4643 while idx < start + 2 && stack.entries.len() > idx + 1 {
4644 let advance = idx < target;
4645 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]);
4646 if !advance {
4647 return;
4648 }
4649 idx += 1;
4650 }
4651}
4652
4653/// Writer-side counterpart of the decoder's single-reference
4654/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s
4655/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV
4656/// residual against the DRL-selected predictor. Returns the motion vector
4657/// the decoder will derive for the block (what the MI grid must record) and
4658/// whether it is `NEWMV`.
4659///
4660/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global
4661/// motion parameters at all, so every `gm_get_motion_vector` the decoder
4662/// runs is the identity model's zero vector; a lane that starts writing
4663/// real `gm_params` has to feed the same vector in here.
4664///
4665/// # Errors
4666/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision.
4667fn write_inter_mode(
4668 enc: &mut SymbolEncoder,
4669 cdfs: &mut Cdfs,
4670 info: InterInfo,
4671 stack: &crate::mvstack::MvStack,
4672) -> Result<((i32, i32), bool)> {
4673 let idx = usize::from(info.ref_mv_idx);
4674 if info.mode.compound_index().is_some() {
4675 return Err(Error::unsupported(
4676 "AV1 tile",
4677 "a compound mode is written by `write_compound_block`, not here",
4678 ));
4679 }
4680 match info.mode {
4681 InterMode::NewMv => {
4682 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
4683 write_drl_idx(enc, cdfs, stack, 0, idx);
4684 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
4685 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?;
4686 note_inter_mode(3, idx);
4687 Ok((info.mv, true))
4688 }
4689 InterMode::GlobalMv => {
4690 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
4691 enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV
4692 note_inter_mode(2, 0);
4693 Ok(((0, 0), false))
4694 }
4695 InterMode::NearestMv => {
4696 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
4697 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
4698 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
4699 note_inter_mode(0, 0);
4700 Ok((stack.nearest_mv, false))
4701 }
4702 InterMode::NearMv => {
4703 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
4704 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
4705 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV
4706 // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24).
4707 let idx = idx.max(1);
4708 write_drl_idx(enc, cdfs, stack, 1, idx);
4709 let mv = stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv);
4710 note_inter_mode(1, idx);
4711 Ok((mv, false))
4712 }
4713 _ => unreachable!("compound modes are refused above"),
4714 }
4715}
4716
4717/// Writes the payload of a one-tile inter frame built from `blocks`, one
4718/// 32x32 block per entry in raster order across the frame — every superblock
4719/// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
4720/// codes a key frame, because a mixed-size partition tree buys this writer's
4721/// gate nothing a flat grid does not already prove: the CDF state, the
4722/// neighbour contexts and the single-reference/MV-stack machinery below are
4723/// exactly as size-sensitive whether the tree recurses or not, and recursing
4724/// it would be undirected scaffolding — see `sb_coeff_key_frame_tile` for
4725/// where that tree already lives, ready to graft this block's mode reads
4726/// onto once a real partition search needs it.
4727///
4728/// A block whose [`BlockCoeffs::inter`] is `Some` is coded inter: `skip`,
4729/// then `is_inter`, then a single-reference chain that always names `LAST`
4730/// (spec 5.11.25 `single_ref_p1`/`p3`/`p4`, this crate's only reference so
4731/// far), then the two-mode `read_inter_mode` chain (spec 5.11.24) and, for
4732/// [`InterMode::NewMv`], a DRL index (always zero) and a coded motion vector
4733/// residual. A block whose `inter` is `None` codes intra, through the
4734/// *inter*-frame intra path (spec 5.11.16's `intra_frame_mode_info` is the
4735/// key frame writers' path; this is `inter_frame_mode_info`'s intra branch):
4736/// `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour context, since
4737/// an inter frame's intra blocks do not read their neighbours' modes.
4738///
4739/// # Errors
4740/// Returns an error when the frame is not a whole number of 64x64
4741/// superblocks, when `blocks` does not carry exactly one entry per 32x32
4742/// block, when an intra block names a mode a key frame does not code, when a
4743/// coefficient sits outside its transform or is one the writer cannot code,
4744/// when a `NEWMV` block's motion vector needs eighth-pel precision.
4745pub fn sb_coeff_inter_frame_tile(
4746 mi_cols: u32,
4747 mi_rows: u32,
4748 base_q_idx: u8,
4749 blocks: &[Quadrant],
4750) -> Result<Vec<u8>> {
4751 sb_coeff_inter_frame_tile_tx(mi_cols, mi_rows, base_q_idx, blocks, false)
4752}
4753
4754/// [`sb_coeff_inter_frame_tile`] for a frame header carrying
4755/// `tx_mode == TxMode::Select`: every block then codes the transform syntax
4756/// [`write_tx_syntax_inter`] writes -- one `txfm_split` flag on an inter
4757/// block that carries a residual, a `tx_depth` symbol on an intra one -- and
4758/// an intra block whose depth is nonzero codes its luma as several transform
4759/// units. With `tx_select` false this writes exactly the stream it always did.
4760///
4761/// # Errors
4762/// As [`sb_coeff_inter_frame_tile`].
4763pub fn sb_coeff_inter_frame_tile_tx(
4764 mi_cols: u32,
4765 mi_rows: u32,
4766 base_q_idx: u8,
4767 blocks: &[Quadrant],
4768 tx_select: bool,
4769) -> Result<Vec<u8>> {
4770 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
4771 sb_coeff_inter_frame_tile_cdfs(
4772 mi_cols,
4773 mi_rows,
4774 base_q_idx,
4775 blocks,
4776 tx_select,
4777 &mut cdfs,
4778 TileRect::whole(mi_cols, mi_rows),
4779 &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
4780 )
4781}
4782
4783/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
4784/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`].
4785///
4786/// # Errors
4787/// As [`sb_coeff_inter_frame_tile_tx`].
4788pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
4789 mi_cols: u32,
4790 mi_rows: u32,
4791 _base_q_idx: u8,
4792 blocks: &[Quadrant],
4793 tx_select: bool,
4794 cdfs: &mut Cdfs,
4795 // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
4796 tile: TileRect,
4797 // The frame's MV grid, carried across the frame's tiles by the caller
4798 // (see the comment at `set_tile_bounds` below).
4799 grid: &mut MiGrid,
4800) -> Result<Vec<u8>> {
4801 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
4802 let _cdef_idx = CdefIdxGuard;
4803 check_blocks(mi_cols, mi_rows)?;
4804 // `block_grid`'s ceiling, not a plain division: a true frame size that is
4805 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has
4806 // one more block/superblock whose own origin is inside the true frame,
4807 // same as `sb_coeff_key_frame_tile`.
4808 let (cols, rows) = block_grid(mi_cols, mi_rows);
4809 if blocks.len() != (cols * rows) as usize {
4810 return Err(Error::unsupported(
4811 "AV1 tile",
4812 "an inter frame needs one entry per 32x32 block inside the true frame",
4813 ));
4814 }
4815 let coded: Vec<&BlockCoeffs> = blocks.iter().flat_map(Quadrant::blocks).collect();
4816 if let Some(bad) = coded
4817 .into_iter()
4818 .find(|b| b.inter.is_none() && usize::from(b.mode) >= INTRA_MODES)
4819 {
4820 return Err(Error::unsupported(
4821 "AV1 tile",
4822 format!(
4823 "intra mode {} is not one of the thirteen this writer codes",
4824 bad.mode
4825 ),
4826 ));
4827 }
4828
4829 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only
4830 /// size this writer's inter branch codes.
4831 const SIZE_GROUP_32: usize = 3;
4832
4833 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
4834 let mut neighbours = Neighbours::new(
4835 cols as usize * 2,
4836 rows as usize * 2,
4837 mi_cols as usize,
4838 mi_rows as usize,
4839 );
4840 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
4841 // The MV grid spans the FRAME and carries every tile written before this
4842 // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
4843 // keeps one grid for the whole frame and narrows its read window per
4844 // tile): the tile bounds below are what stops a candidate scan reaching
4845 // across the boundary, and a grid that was merely empty out there would
4846 // not read the same as the decoder's wherever a scan reads the array
4847 // without asking `MiGrid::get` first.
4848 let mut grid = &mut *grid;
4849 grid.set_tile_bounds(
4850 tile.mi_row0 as usize,
4851 tile.mi_col0 as usize,
4852 tile.mi_row1 as usize,
4853 tile.mi_col1 as usize,
4854 );
4855 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
4856 let mut cdfs = cdfs;
4857 let mut enc = SymbolEncoder::new();
4858 // An `is_inter` block's 32x32 luma transform reads a different
4859 // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see
4860 // `TxbSet::Luma32Inter`'s doc comment); chroma's transform type is
4861 // derived from luma's, not coded, so it never differs between the two.
4862 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
4863 let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16];
4864 let scan32 = default_scan(TX32);
4865 let scan16 = default_scan(TX16);
4866 let scan8 = default_scan(TX8);
4867 let scan4 = default_scan(TX4);
4868 // The same four tables again as one array, which is what the per-unit
4869 // luma writer indexes by transform side.
4870 let all_scans = [
4871 scan32.clone(),
4872 scan16.clone(),
4873 scan8.clone(),
4874 scan4.clone(),
4875 ];
4876 let zero_grids = [
4877 vec![0i32; TX32 * TX32],
4878 vec![0i32; TX16 * TX16],
4879 vec![0i32; TX16 * TX16],
4880 ];
4881
4882 for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) {
4883 neighbours.start_row();
4884 for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) {
4885 write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W);
4886 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
4887 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
4888 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
4889 // whose bottom or right half falls outside the true frame cannot
4890 // be left whole, but this writer only ever splits a superblock
4891 // into its four 32x32 quadrants (never `PARTITION_NONE` at 64x64),
4892 // so the only question is which of the three partition symbols
4893 // that split takes — same three-way signaling as
4894 // `sb_coeff_key_frame_tile`'s superblock level.
4895 let (has_cols, has_rows) = (
4896 sb_c * SB_MI + SB_MI / 2 < mi_cols,
4897 sb_r * SB_MI + SB_MI / 2 < mi_rows,
4898 );
4899 match (has_cols, has_rows) {
4900 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]),
4901 (true, false) => {
4902 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
4903 }
4904 (false, true) => {
4905 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
4906 }
4907 (false, false) => {}
4908 }
4909
4910 for quadrant in 0..4 {
4911 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
4912 // Only a quadrant whose own mi origin is inside the true
4913 // frame is coded at all (spec `decode_partition`'s
4914 // `r >= MiRows || c >= MiCols` early return), same filter as
4915 // `sb_coeff_key_frame_tile`'s `quadrant_positions`.
4916 if r32 >= rows || c32 >= cols {
4917 continue;
4918 }
4919 let site = &blocks[(r32 * cols + c32) as usize];
4920 let at = (r32 as usize * 2, c32 as usize * 2);
4921 let ctx32 = neighbours.partition_ctx(at, BLOCK);
4922 // spec `decode_partition`'s hasRows/hasCols recomputed at this
4923 // quadrant's own half: a whole 32x32 block cannot be left
4924 // whole once its own half straddles the true edge, mirroring
4925 // `sb_coeff_key_frame_tile`'s "cannot be left whole" refusal.
4926 let (has_cols32, has_rows32) = (
4927 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
4928 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
4929 );
4930 let block = match site {
4931 Quadrant::Whole(block) => {
4932 if !has_cols32 || !has_rows32 {
4933 return Err(Error::unsupported(
4934 "AV1 tile",
4935 "a 32x32 block that is half outside the true frame \
4936 cannot be left whole",
4937 ));
4938 }
4939 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]);
4940 block
4941 }
4942 Quadrant::Split(sub_blocks) => {
4943 // Same filter as `sb_coeff_key_frame_tile`'s
4944 // `sub_positions`: only the 16x16 leaves whose own mi
4945 // origin is inside the true frame are coded.
4946 let sub_positions: Vec<(usize, usize)> = (0..4)
4947 .map(|i| (r32 as usize * 2 + i / 2, c32 as usize * 2 + i % 2))
4948 .filter(|&(sr, sc)| {
4949 (sr as u32) * SUB_MI < mi_rows && (sc as u32) * SUB_MI < mi_cols
4950 })
4951 .collect();
4952 if sub_blocks.len() != sub_positions.len() {
4953 return Err(Error::unsupported(
4954 "AV1 tile",
4955 "a split 32x32 inter-frame block needs one 16x16 entry \
4956 per sub-block inside the true frame",
4957 ));
4958 }
4959 // Same three-way spec signaling as the superblock
4960 // level above, recomputed at this quadrant's own half.
4961 match (has_cols32, has_rows32) {
4962 (true, true) => {
4963 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx32]);
4964 }
4965 (true, false) => {
4966 enc.symbol_fixed(
4967 1,
4968 &gather(&cdfs.partition_w32[ctx32], VERT_ALIKE),
4969 );
4970 }
4971 (false, true) => {
4972 enc.symbol_fixed(
4973 1,
4974 &gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE),
4975 );
4976 }
4977 (false, false) => {}
4978 }
4979 for (leaf, (sr, sc)) in sub_blocks.iter().zip(sub_positions) {
4980 // A 16x16 leaf whose own half straddles the true
4981 // frame edge on both axes needs a rectangular
4982 // transform this writer does not code yet; one
4983 // axis only is two (or, at a true corner, one)
4984 // 8x8 leaves (lane-av1inter8), same split the key
4985 // frame search takes at this geometry.
4986 let (has_cols16, has_rows16) = (
4987 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
4988 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
4989 );
4990 if !has_cols16 && !has_rows16 {
4991 return Err(Error::unsupported(
4992 "AV1 tile",
4993 "a 16x16 inter-frame block whose true edge cuts through \
4994 both axes needs a rectangular transform this writer \
4995 does not code yet",
4996 ));
4997 }
4998 let at16 = (sr, sc);
4999 if has_cols16 && has_rows16 {
5000 let ctx16 = neighbours.partition_ctx(at16, SUB);
5001 // A 16x16 leaf wholly inside the frame that
5002 // carries `eight` split itself further, on
5003 // cost rather than on geometry (lane-av1rd2):
5004 // spec PARTITION_SPLIT at BLOCK_16X16, then
5005 // the same four 8x8 leaves the straddling
5006 // branch below writes -- all four inside, so
5007 // the partition symbol is a real one rather
5008 // than the edge's gathered flag.
5009 if let Some(leaves) = &leaf.eight {
5010 if leaves.len() != 4 {
5011 return Err(Error::unsupported(
5012 "AV1 tile",
5013 "a 16x16 inter-frame block inside the frame that splits needs all four 8x8 leaves",
5014 ));
5015 }
5016 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w16[ctx16]);
5017 let (mi_row0, mi_col0) =
5018 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
5019 for (i, leaf8) in leaves.iter().enumerate() {
5020 let leaf_mi = (
5021 (mi_row0 + (i as u32 / 2) * 2) as usize,
5022 (mi_col0 + (i as u32 % 2) * 2) as usize,
5023 );
5024 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
5025 enc.symbol(
5026 PARTITION_NONE,
5027 &mut cdfs.partition_w8[leaf_ctx],
5028 );
5029 let (skip, is_inter) = write_inter_frame_leaf8(
5030 &mut enc,
5031 &mut cdfs,
5032 &mut neighbours,
5033 &mut grid,
5034 mi_cols,
5035 mi_rows,
5036 leaf8,
5037 leaf_mi,
5038 &scan8,
5039 &scan4,
5040 tx_select,
5041 &all_scans,
5042 )?;
5043 let _ = (skip, is_inter);
5044 }
5045 continue;
5046 }
5047 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]);
5048 write_inter_frame_leaf(
5049 &mut enc,
5050 &mut cdfs,
5051 &mut neighbours,
5052 &mut grid,
5053 mi_cols,
5054 mi_rows,
5055 leaf,
5056 at16,
5057 &scan16,
5058 &scan8,
5059 tx_select,
5060 &all_scans,
5061 )?;
5062 } else {
5063 let ctx16 = neighbours.partition_ctx(at16, SUB);
5064 if has_cols16 {
5065 enc.symbol_fixed(
5066 1,
5067 &gather(&cdfs.partition_w16[ctx16], VERT_ALIKE),
5068 );
5069 } else {
5070 enc.symbol_fixed(
5071 1,
5072 &gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE),
5073 );
5074 }
5075 let leaves = leaf.eight.as_ref().ok_or_else(|| {
5076 Error::unsupported(
5077 "AV1 tile",
5078 "a 16x16 inter-frame block the true frame edge cuts \
5079 through needs its `eight` leaves populated",
5080 )
5081 })?;
5082 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
5083 let leaf_positions: Vec<(u32, u32)> = (0..4)
5084 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
5085 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
5086 .collect();
5087 if leaves.len() != leaf_positions.len() {
5088 return Err(Error::unsupported(
5089 "AV1 tile",
5090 "a straddling 16x16 inter-frame block needs one \
5091 `eight` entry per 8x8 leaf inside the true frame",
5092 ));
5093 }
5094 for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) {
5095 let leaf_mi = (mr as usize, mc as usize);
5096 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
5097 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w8[leaf_ctx]);
5098 let (skip, is_inter) = write_inter_frame_leaf8(
5099 &mut enc,
5100 &mut cdfs,
5101 &mut neighbours,
5102 &mut grid,
5103 mi_cols,
5104 mi_rows,
5105 leaf8,
5106 leaf_mi,
5107 &scan8,
5108 &scan4,
5109 tx_select,
5110 &all_scans,
5111 )?;
5112 let _ = (skip, is_inter);
5113 }
5114 // Same write-back-once-from-the-last-leaf rule
5115 // as the key frame search's `write_leaf8`
5116 // caller (r15): the SUB-grid skip/inter arrays
5117 // are otherwise left stale for the next
5118 // 16x16 slot.
5119
5120 }
5121 }
5122 continue;
5123 }
5124 };
5125
5126 let (r, c) = at;
5127 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5128 let has_above = neighbours.has_above(mi_r);
5129 let has_left = neighbours.has_left(mi_c);
5130 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
5131 + usize::from(neighbours.left_skip[mi_r]);
5132 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
5133 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
5134
5135 let is_inter = block.inter.is_some();
5136 let (above_inter, left_inter) =
5137 (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
5138 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
5139 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
5140
5141 let mode_for_tx;
5142 if let Some(info) = block.inter {
5143 write_comp_mode(&mut enc, &mut cdfs, &neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some());
5144 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
5145 if info.ref1.is_some() {
5146 let (mv, mv1, is_new_mv) = write_compound_block(
5147 &mut enc, &mut cdfs, &neighbours, &grid, (mi_row, mi_col), (8, 8),
5148 (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
5149 )?;
5150 for dr in 0..8 {
5151 for dc in 0..8 {
5152 grid.set(mi_row + dr, mi_col + dc, MiInfo {
5153 is_inter: true,
5154 ref_frame: info.ref_frame,
5155 ref_frame1: info.ref1.unwrap_or(NO_REF1),
5156 mv1: mv16(mv1),
5157 mv: mv16(mv),
5158 is_new_mv,
5159 size: 8,
5160 size_h: 8,
5161 is_global_mv0: false,
5162 is_global_mv1: false,
5163 });
5164 }
5165 }
5166 mode_for_tx = 0;
5167 } else {
5168 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]);
5169
5170 let stack = find_mv_stack(
5171 &grid,
5172 mi_row,
5173 mi_col,
5174 8,
5175 8,
5176 info.ref_frame,
5177 mi_cols as usize,
5178 mi_rows as usize,
5179 );
5180
5181 let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
5182 grid.set(
5183 mi_row,
5184 mi_col,
5185 MiInfo {
5186 is_inter: true,
5187 ref_frame: info.ref_frame,
5188 ref_frame1: NO_REF1,
5189 mv1: (0, 0),
5190 mv: mv16(mv),
5191 is_new_mv,
5192 size: 8,
5193 size_h: 8,
5194 is_global_mv0: false,
5195 is_global_mv1: false,
5196 },
5197 );
5198 for dr in 0..8 {
5199 for dc in 0..8 {
5200 if dr == 0 && dc == 0 {
5201 continue;
5202 }
5203 grid.set(
5204 mi_row + dr,
5205 mi_col + dc,
5206 MiInfo {
5207 is_inter: true,
5208 ref_frame: info.ref_frame,
5209 ref_frame1: NO_REF1,
5210 mv1: (0, 0),
5211 mv: mv16(mv),
5212 is_new_mv,
5213 size: 8,
5214 size_h: 8,
5215 is_global_mv0: false,
5216 is_global_mv1: false,
5217 },
5218 );
5219 }
5220 }
5221 mode_for_tx = 0;
5222 }
5223 } else {
5224 let mode = usize::from(block.mode);
5225 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
5226 if (V_PRED..=D67_PRED).contains(&mode) {
5227 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
5228 }
5229 let uv_mode = usize::from(block.uv_mode);
5230 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
5231 if (V_PRED..=D67_PRED).contains(&uv_mode) {
5232 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
5233 }
5234 mode_for_tx = mode;
5235 // Intra: no vote, but still a coded cell -- mvstack's
5236 // extended-scan coverage must see it (module doc).
5237 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
5238 write_palette_syntax(
5239 &mut enc,
5240 &mut cdfs,
5241 &mut neighbours,
5242 block.palette.as_ref(),
5243 block.palette_uv.as_ref(),
5244 mode,
5245 uv_mode,
5246 (mi_row, mi_col),
5247 BLOCK,
5248 );
5249 for dr in 0..8 {
5250 for dc in 0..8 {
5251 grid.set(
5252 mi_row + dr,
5253 mi_col + dc,
5254 MiInfo {
5255 is_inter: false,
5256 ref_frame: -1,
5257 ref_frame1: NO_REF1,
5258 mv1: (0, 0),
5259 mv: (0, 0),
5260 is_new_mv: false,
5261 size: 8,
5262 size_h: 8,
5263 is_global_mv0: false,
5264 is_global_mv1: false,
5265 },
5266 );
5267 }
5268 }
5269 }
5270
5271 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
5272 let tx = if tx_select {
5273 write_tx_syntax_inter(
5274 &mut enc,
5275 &mut cdfs,
5276 &mut neighbours,
5277 at_mi,
5278 BLOCK,
5279 is_inter,
5280 block.skip,
5281 usize::from(block.tx_depth),
5282 )
5283 } else {
5284 BLOCK
5285 };
5286 let split = tx < BLOCK;
5287 if block.skip {
5288 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
5289 } else {
5290 let grids = [
5291 level_grid(&block.luma, TX32)?,
5292 level_grid(&block.u, TX16)?,
5293 level_grid(&block.v, TX16)?,
5294 ];
5295 if split {
5296 write_luma_tus(
5297 &mut enc,
5298 &mut cdfs,
5299 &mut neighbours,
5300 at_mi,
5301 BLOCK,
5302 tx,
5303 &grids[0],
5304 mode_for_tx,
5305 &all_scans,
5306 is_inter,
5307 )?;
5308 }
5309 write_block_planes(
5310 &mut enc,
5311 &mut cdfs,
5312 if is_inter {
5313 &inter_planes
5314 } else {
5315 &intra_planes
5316 },
5317 &grids,
5318 &[&scan32, &scan16, &scan16],
5319 &neighbours.around(at, BLOCK),
5320 mode_for_tx,
5321 split,
5322 );
5323 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
5324 }
5325 neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));
5326 record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block);
5327 }
5328 }
5329 }
5330 Ok(enc.finish())
5331}
5332
5333/// Writes one 16x16 leaf a straddling 32x32 quadrant's [`Quadrant::Split`]
5334/// splits into: intra (spec `inter_frame_mode_info`'s intra branch, the only
5335/// one this writer used to code here) or real inter (`is_inter` coded
5336/// `true`), `NEARESTMV` only -- `NEWMV` at this size is this function's
5337/// caller's to never build (`Quadrant::Split`'s `BlockCoeffs.inter`) -- same
5338/// `single_ref`/mv-stack/DRL symbol chain as the whole-32x32 branch above,
5339/// just at this leaf's own 4x4-mi window (`bw4`/`bh4` of 4, not 8) and coded
5340/// through [`TxbSet::Luma16Inter`] rather than [`TxbSet::Luma32Inter`]. Its
5341/// own `PARTITION_NONE` symbol is already written, same contract as
5342/// [`write_block`].
5343#[allow(clippy::too_many_arguments)]
5344fn write_inter_frame_leaf(
5345 enc: &mut SymbolEncoder,
5346 cdfs: &mut Cdfs,
5347 neighbours: &mut Neighbours,
5348 grid: &mut MiGrid,
5349 mi_cols: u32,
5350 mi_rows: u32,
5351 block: &BlockCoeffs,
5352 at: (usize, usize),
5353 scan16: &Vec<u16>,
5354 scan8: &Vec<u16>,
5355 tx_select: bool,
5356 all_scans: &[Vec<u16>; 4],
5357) -> Result<()> {
5358 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
5359 return Err(Error::unsupported(
5360 "AV1 tile",
5361 format!(
5362 "intra mode {} is not one of the thirteen this writer codes",
5363 block.mode
5364 ),
5365 ));
5366 }
5367 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
5368 /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size.
5369 const SIZE_GROUP_16: usize = 2;
5370
5371 let (r, c) = at;
5372 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5373 let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
5374 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
5375 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
5376
5377 let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c));
5378 let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
5379 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
5380 let is_inter = block.inter.is_some();
5381 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
5382
5383 let mode_for_tx;
5384 if let Some(info) = block.inter {
5385 write_comp_mode(enc, cdfs, neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some());
5386 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
5387 if info.ref1.is_some() {
5388 let n = SUB_MI as usize;
5389 let (mv, mv1, is_new_mv) = write_compound_block(
5390 enc, cdfs, neighbours, grid, (mi_row, mi_col), (n, n),
5391 (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
5392 )?;
5393 for dr in 0..n {
5394 for dc in 0..n {
5395 grid.set(mi_row + dr, mi_col + dc, MiInfo {
5396 is_inter: true,
5397 ref_frame: info.ref_frame,
5398 ref_frame1: info.ref1.unwrap_or(NO_REF1),
5399 mv1: mv16(mv1),
5400 mv: mv16(mv),
5401 is_new_mv,
5402 size: n as u8,
5403 size_h: n as u8,
5404 is_global_mv0: false,
5405 is_global_mv1: false,
5406 });
5407 }
5408 }
5409 mode_for_tx = 0;
5410 } else {
5411 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]);
5412
5413 let stack = find_mv_stack(
5414 grid,
5415 mi_row,
5416 mi_col,
5417 SUB_MI as usize,
5418 SUB_MI as usize,
5419 info.ref_frame,
5420 mi_cols as usize,
5421 mi_rows as usize,
5422 );
5423
5424 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
5425 for dr in 0..SUB_MI as usize {
5426 for dc in 0..SUB_MI as usize {
5427 grid.set(
5428 mi_row + dr,
5429 mi_col + dc,
5430 MiInfo {
5431 is_inter: true,
5432 ref_frame: info.ref_frame,
5433 ref_frame1: NO_REF1,
5434 mv1: (0, 0),
5435 mv: mv16(mv),
5436 is_new_mv,
5437 size: SUB_MI as usize as u8,
5438 size_h: SUB_MI as usize as u8,
5439 is_global_mv0: false,
5440 is_global_mv1: false,
5441 },
5442 );
5443 }
5444 }
5445 mode_for_tx = 0;
5446 }
5447 } else {
5448 let mode = usize::from(block.mode);
5449 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);
5450 if (V_PRED..=D67_PRED).contains(&mode) {
5451 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
5452 }
5453 let uv_mode = usize::from(block.uv_mode);
5454 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
5455 if (V_PRED..=D67_PRED).contains(&uv_mode) {
5456 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
5457 }
5458 mode_for_tx = mode;
5459 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
5460 // coverage must see it (module doc).
5461 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
5462 write_palette_syntax(
5463 enc,
5464 cdfs,
5465 neighbours,
5466 block.palette.as_ref(),
5467 block.palette_uv.as_ref(),
5468 mode,
5469 uv_mode,
5470 (mi_row, mi_col),
5471 SUB,
5472 );
5473 for dr in 0..SUB_MI as usize {
5474 for dc in 0..SUB_MI as usize {
5475 grid.set(
5476 mi_row + dr,
5477 mi_col + dc,
5478 MiInfo {
5479 is_inter: false,
5480 ref_frame: -1,
5481 ref_frame1: NO_REF1,
5482 mv1: (0, 0),
5483 mv: (0, 0),
5484 is_new_mv: false,
5485 size: SUB_MI as usize as u8,
5486 size_h: SUB_MI as usize as u8,
5487 is_global_mv0: false,
5488 is_global_mv1: false,
5489 },
5490 );
5491 }
5492 }
5493 }
5494
5495 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
5496 let tx = if tx_select {
5497 write_tx_syntax_inter(
5498 enc,
5499 cdfs,
5500 neighbours,
5501 at_mi,
5502 SUB,
5503 is_inter,
5504 block.skip,
5505 usize::from(block.tx_depth),
5506 )
5507 } else {
5508 SUB
5509 };
5510 let split = tx < SUB;
5511 if block.skip {
5512 let zero_grids = [
5513 vec![0i32; TX16 * TX16],
5514 vec![0i32; TX8 * TX8],
5515 vec![0i32; TX8 * TX8],
5516 ];
5517 neighbours.record(at, SUB, mode_for_tx, &zero_grids);
5518 } else {
5519 let grids = [
5520 level_grid(&block.luma, TX16)?,
5521 level_grid(&block.u, TX8)?,
5522 level_grid(&block.v, TX8)?,
5523 ];
5524 if split {
5525 write_luma_tus(
5526 enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, is_inter,
5527 )?;
5528 }
5529 write_block_planes(
5530 enc,
5531 cdfs,
5532 if is_inter {
5533 &[TxbSet::Luma16Inter, TxbSet::Chroma8, TxbSet::Chroma8]
5534 } else {
5535 &[TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8]
5536 },
5537 &grids,
5538 &[scan16, scan8, scan8],
5539 &neighbours.around(at, SUB),
5540 mode_for_tx,
5541 split,
5542 );
5543 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
5544 }
5545 neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block));
5546 record_block_compound(neighbours, (mi_r, mi_c), SUB, block);
5547 Ok(())
5548}
5549
5550/// Writes one 8x8 leaf of a straddling 16x16 inter-frame block
5551/// (lane-av1inter8): its own skip flag, intra/inter choice and (when inter)
5552/// `NEARESTMV`/`NEWMV` chain, or (when intra) `Y_MODE`, then its own luma and
5553/// two chroma transform blocks -- coded exactly like
5554/// [`write_inter_frame_leaf`] but through [`TxbSet::Luma8Inter`]/
5555/// [`TxbSet::Chroma4`] and at this leaf's own 2x2-mi mv-stack window, reading
5556/// its skip/intra-inter context from the *enclosing* 16x16 slot's
5557/// [`Neighbours`] arrays (`outer_at`, in [`SUB`]-grid units) unless
5558/// `prev_leaf` names this straddling block's own first leaf as the true
5559/// mi-adjacent neighbour -- the same override [`write_leaf8`] applies to its
5560/// mode context, needed for the same reason: `Neighbours`' above/left arrays
5561/// only resolve to [`SUB`] granularity, too coarse for the second leaf of a
5562/// straddling 16x16 to see the first. `Y_MODE`'s own context (`Size_Group`)
5563/// is not neighbour-dependent, unlike the key frame path's `kf_y_mode`, so no
5564/// override is needed there. Hands back this leaf's own skip flag and
5565/// intra/inter choice, which is what the next leaf (or the caller's final
5566/// write-back, mirroring `write_leaf8`'s caller) reads.
5567#[allow(clippy::too_many_arguments)]
5568fn write_inter_frame_leaf8(
5569 enc: &mut SymbolEncoder,
5570 cdfs: &mut Cdfs,
5571 neighbours: &mut Neighbours,
5572 grid: &mut MiGrid,
5573 mi_cols: u32,
5574 mi_rows: u32,
5575 block: &BlockCoeffs,
5576 leaf_mi: (usize, usize),
5577 scan8: &Vec<u16>,
5578 scan4: &Vec<u16>,
5579 tx_select: bool,
5580 all_scans: &[Vec<u16>; 4],
5581) -> Result<(bool, bool)> {
5582 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
5583 return Err(Error::unsupported(
5584 "AV1 tile",
5585 format!(
5586 "intra mode {} is not one of the thirteen this writer codes",
5587 block.mode
5588 ),
5589 ));
5590 }
5591 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
5592 /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size.
5593 const SIZE_GROUP_8: usize = 1;
5594
5595 // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's:
5596 // under a real PARTITION_SPLIT all four leaves are coded, so the
5597 // bottom-left leaf's true above neighbour is the FIRST leaf and the
5598 // bottom-right's above and left are two DIFFERENT ones (lane-av1rd2 --
5599 // reading the coarse slot desynced the stream, and so did an override
5600 // that remembered only the previous leaf).
5601 let above_skip = neighbours.above_skip[leaf_mi.1];
5602 let left_skip = neighbours.left_skip[leaf_mi.0];
5603 let above_inter = neighbours.above_inter[leaf_mi.1];
5604 let left_inter = neighbours.left_inter[leaf_mi.0];
5605 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
5606 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
5607 write_cdef_idx(enc, leaf_mi, block.skip);
5608
5609 let (has_above, has_left) = (neighbours.has_above(leaf_mi.0), neighbours.has_left(leaf_mi.1));
5610 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
5611 let is_inter = block.inter.is_some();
5612 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
5613
5614 let mode_for_tx;
5615 if let Some(info) = block.inter {
5616 write_comp_mode(enc, cdfs, neighbours, leaf_mi, (has_above, has_left), info.ref1.is_some());
5617 let (mi_row, mi_col) = leaf_mi;
5618 if info.ref1.is_some() {
5619 let (mv, mv1, is_new_mv) = write_compound_block(
5620 enc, cdfs, neighbours, grid, (mi_row, mi_col), (2, 2),
5621 (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
5622 )?;
5623 for dr in 0..2 {
5624 for dc in 0..2 {
5625 grid.set(mi_row + dr, mi_col + dc, MiInfo {
5626 is_inter: true,
5627 ref_frame: info.ref_frame,
5628 ref_frame1: info.ref1.unwrap_or(NO_REF1),
5629 mv1: mv16(mv1),
5630 mv: mv16(mv),
5631 is_new_mv,
5632 size: 2,
5633 size_h: 2,
5634 is_global_mv0: false,
5635 is_global_mv1: false,
5636 });
5637 }
5638 }
5639 mode_for_tx = 0;
5640 } else {
5641 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]);
5642
5643 let stack = find_mv_stack(
5644 grid,
5645 mi_row,
5646 mi_col,
5647 2,
5648 2,
5649 info.ref_frame,
5650 mi_cols as usize,
5651 mi_rows as usize,
5652 );
5653
5654 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
5655 for dr in 0..2 {
5656 for dc in 0..2 {
5657 grid.set(
5658 mi_row + dr,
5659 mi_col + dc,
5660 MiInfo {
5661 is_inter: true,
5662 ref_frame: info.ref_frame,
5663 ref_frame1: NO_REF1,
5664 mv1: (0, 0),
5665 mv: mv16(mv),
5666 is_new_mv,
5667 size: 2,
5668 size_h: 2,
5669 is_global_mv0: false,
5670 is_global_mv1: false,
5671 },
5672 );
5673 }
5674 }
5675 mode_for_tx = 0;
5676 }
5677 } else {
5678 let mode = usize::from(block.mode);
5679 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);
5680 if (V_PRED..=D67_PRED).contains(&mode) {
5681 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
5682 }
5683 let uv_mode = usize::from(block.uv_mode);
5684 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
5685 if (V_PRED..=D67_PRED).contains(&uv_mode) {
5686 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
5687 }
5688 mode_for_tx = mode;
5689 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
5690 // coverage must see it (module doc).
5691 let (mi_row, mi_col) = leaf_mi;
5692 write_palette_syntax(
5693 enc,
5694 cdfs,
5695 neighbours,
5696 block.palette.as_ref(),
5697 block.palette_uv.as_ref(),
5698 mode,
5699 uv_mode,
5700 leaf_mi,
5701 8,
5702 );
5703 for dr in 0..2 {
5704 for dc in 0..2 {
5705 grid.set(
5706 mi_row + dr,
5707 mi_col + dc,
5708 MiInfo {
5709 is_inter: false,
5710 ref_frame: -1,
5711 ref_frame1: NO_REF1,
5712 mv1: (0, 0),
5713 mv: (0, 0),
5714 is_new_mv: false,
5715 size: 2,
5716 size_h: 2,
5717 is_global_mv0: false,
5718 is_global_mv1: false,
5719 },
5720 );
5721 }
5722 }
5723 }
5724
5725 let planes = if is_inter {
5726 [TxbSet::Luma8Inter, TxbSet::Chroma4, TxbSet::Chroma4]
5727 } else {
5728 [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]
5729 };
5730 let tx = if tx_select {
5731 write_tx_syntax_inter(
5732 enc,
5733 cdfs,
5734 neighbours,
5735 leaf_mi,
5736 8,
5737 is_inter,
5738 block.skip,
5739 usize::from(block.tx_depth),
5740 )
5741 } else {
5742 8
5743 };
5744 let split = tx < 8;
5745 if block.skip {
5746 let zero_grids = [
5747 vec![0i32; TX8 * TX8],
5748 vec![0i32; TX4 * TX4],
5749 vec![0i32; TX4 * TX4],
5750 ];
5751 neighbours.record_mi(leaf_mi, 8, &zero_grids);
5752 neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block));
5753 record_block_compound(neighbours, leaf_mi, 8, block);
5754 } else {
5755 let grids = [
5756 level_grid(&block.luma, TX8)?,
5757 level_grid(&block.u, TX4)?,
5758 level_grid(&block.v, TX4)?,
5759 ];
5760 if split {
5761 write_luma_tus(
5762 enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, is_inter,
5763 )?;
5764 }
5765 write_block_planes(
5766 enc,
5767 cdfs,
5768 &planes,
5769 &grids,
5770 &[scan8, scan4, scan4],
5771 &neighbours.around_mi(leaf_mi, 8),
5772 mode_for_tx,
5773 split,
5774 );
5775 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
5776 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));
5777 record_block_compound(neighbours, leaf_mi, 8, block);
5778 }
5779 Ok((block.skip, is_inter))
5780}
5781
5782#[cfg(test)]
5783mod tests {
5784 use super::*;
5785 use crate::frame::frame_obu;
5786 use crate::obu::temporal_delimiter;
5787 use crate::sequence::sequence_header_obu;
5788 use ec_av1_syntax::sequence::SequenceHeader;
5789 use ec_av1_syntax::{
5790 FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
5791 TxMode,
5792 };
5793 use std::io::Write;
5794 use std::process::{Command, Stdio};
5795
5796 /// A 64x64 sequence with every tool this writer does not code turned off:
5797 /// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter
5798 /// intra, and no screen content tools (which is what keeps intra block copy
5799 /// and palette out of the block syntax).
5800 fn sequence_64() -> SequenceHeader {
5801 let mut seq = crate::sequence::tests::sample_1080p();
5802 seq.frame_width_bits = 7;
5803 seq.frame_height_bits = 7;
5804 seq.max_frame_width = 64;
5805 seq.max_frame_height = 64;
5806 seq.use_128x128_superblock = false;
5807 seq.enable_filter_intra = false;
5808 seq.enable_cdef = false;
5809 seq.enable_restoration = false;
5810 seq.enable_superres = false;
5811 seq.seq_force_screen_content_tools = 0;
5812 seq.seq_force_integer_mv = 0;
5813 seq
5814 }
5815
5816 /// The key frame the tile above belongs to: one tile, quantised so nothing
5817 /// is lossless, one transform size per block, no in-loop filtering, and no
5818 /// CDF adaptation (the writer codes against the defaults).
5819 fn flat_key_frame() -> FrameHeader {
5820 FrameHeader {
5821 frame_type: FrameType::Key,
5822 frame_is_intra: true,
5823 show_frame: true,
5824 error_resilient_mode: true,
5825 disable_cdf_update: true,
5826 allow_screen_content_tools: false,
5827 force_integer_mv: true,
5828 refresh_frame_flags: 0xFF,
5829 primary_ref_frame: PRIMARY_REF_NONE,
5830 frame_width: 64,
5831 frame_height: 64,
5832 upscaled_width: 64,
5833 render_width: 64,
5834 render_height: 64,
5835 mi_cols: 16,
5836 mi_rows: 16,
5837 tile_info: TileInfo {
5838 uniform_spacing: true,
5839 cols: 1,
5840 rows: 1,
5841 cols_log2: 0,
5842 rows_log2: 0,
5843 mi_col_starts: vec![0, 16],
5844 mi_row_starts: vec![0, 16],
5845 context_update_tile_id: 0,
5846 tile_size_bytes: 1,
5847 },
5848 quantization: QuantizationParams {
5849 base_q_idx: 100,
5850 ..QuantizationParams::default()
5851 },
5852 loop_filter: LoopFilterParams::default(),
5853 tx_mode: TxMode::Largest,
5854 reduced_tx_set: false,
5855 ..FrameHeader::default()
5856 }
5857 }
5858
5859 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
5860 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
5861 /// aomenc gate decodes its stream through ffmpeg and is meaningless
5862 /// without it -- turns it into a hard failure. Without this the require
5863 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
5864 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
5865 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
5866 fn have_ffmpeg() -> bool {
5867 let present = Command::new("ffmpeg")
5868 .arg("-version")
5869 .stdout(Stdio::null())
5870 .stderr(Stdio::null())
5871 .status()
5872 .is_ok_and(|s| s.success());
5873 assert!(
5874 present
5875 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
5876 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
5877 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
5878 );
5879 present
5880 }
5881
5882 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
5883 fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
5884 let mut child = Command::new("ffmpeg")
5885 .args([
5886 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
5887 ])
5888 .stdin(Stdio::piped())
5889 .stdout(Stdio::piped())
5890 .stderr(Stdio::piped())
5891 .spawn()
5892 .expect("ffmpeg failed to start");
5893 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
5894 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
5895 // fills before the last input byte is written -- which is exactly what
5896 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
5897 // (measured: 45 min, both processes at 0% CPU). A write error here is
5898 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
5899 // below, are the real diagnosis.
5900 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
5901 let payload = stream.to_vec();
5902 let writer = std::thread::spawn(move || {
5903 let _ = stdin.write_all(&payload);
5904 });
5905 let out = child.wait_with_output().expect("ffmpeg failed to run");
5906 writer.join().expect("ffmpeg stdin writer thread");
5907 assert!(
5908 out.status.success(),
5909 "ffmpeg refused the stream: {}",
5910 String::from_utf8_lossy(&out.stderr)
5911 );
5912 assert_eq!(
5913 out.stdout.len(),
5914 w * h * 3 / 2,
5915 "expected one 4:2:0 frame, ffmpeg said: {}",
5916 String::from_utf8_lossy(&out.stderr)
5917 );
5918 out.stdout
5919 }
5920
5921 #[test]
5922 fn flat_key_frame_decodes_to_mid_grey() {
5923 if !have_ffmpeg() {
5924 eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH");
5925 return;
5926 }
5927 let seq = sequence_64();
5928 let header = flat_key_frame();
5929 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();
5930
5931 let mut stream = temporal_delimiter();
5932 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
5933 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
5934
5935 let planes = ffmpeg_decode(&stream, 64, 64);
5936 // A DC prediction with no neighbour to average is the middle of the
5937 // range, and a skipped block adds no residual, so every sample of every
5938 // plane is 128 — one wrong symbol anywhere in the tile shows up here.
5939 for (i, &s) in planes.iter().enumerate() {
5940 assert_eq!(s, 128, "sample {i} of the decoded frame");
5941 }
5942 }
5943
5944 /// The one q-context whose CDFs this crate carries; the decoded table
5945 /// below is pinned at this quantiser and nowhere else.
5946 const Q_IDX: u8 = 100;
5947
5948 /// Encode a 64x64 key frame carrying `dc_level` and hand back its planes.
5949 fn decode_dc_frame(dc_level: i32) -> Vec<u8> {
5950 let seq = sequence_64();
5951 let mut header = flat_key_frame();
5952 header.quantization.base_q_idx = Q_IDX;
5953 let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap();
5954 let mut stream = temporal_delimiter();
5955 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
5956 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
5957 ffmpeg_decode(&stream, 64, 64)
5958 }
5959
5960 /// What a reference decoder makes of each DC level at `base_q_idx` 100:
5961 /// the level times the DC quantiser, inverse-transformed over a whole
5962 /// 64x64 block — which spreads one coefficient over 4096 samples, so a
5963 /// level moves the picture by a sample or two, not by tens. These numbers
5964 /// are pinned from the decoder rather than derived: this crate has no
5965 /// inverse transform of its own yet to derive them with. What the test
5966 /// asserts around them — flat planes, untouched chroma, monotone in the
5967 /// level, and the sign going the right way — is derived, and it is what a
5968 /// desync in the coefficient syntax breaks first.
5969 const DECODED_AT_Q100: [(i32, u8); 28] = [
5970 (1, 128),
5971 (2, 128),
5972 (3, 129),
5973 (4, 129),
5974 (5, 129),
5975 (6, 129),
5976 (7, 129),
5977 (8, 129),
5978 (9, 130),
5979 (10, 130),
5980 (11, 130),
5981 (12, 130),
5982 (13, 130),
5983 (14, 131),
5984 (-1, 128),
5985 (-2, 128),
5986 (-3, 128),
5987 (-4, 127),
5988 (-5, 127),
5989 (-6, 127),
5990 (-7, 127),
5991 (-8, 127),
5992 (-9, 126),
5993 (-10, 126),
5994 (-11, 126),
5995 (-12, 126),
5996 (-13, 126),
5997 (-14, 126),
5998 ];
5999
6000 #[test]
6001 fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
6002 if !have_ffmpeg() {
6003 eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
6004 return;
6005 }
6006 let mut seen = Vec::new();
6007 for (level, want) in DECODED_AT_Q100 {
6008 let planes = decode_dc_frame(level);
6009 let (luma, chroma) = planes.split_at(64 * 64);
6010 for (i, &sample) in luma.iter().enumerate() {
6011 assert_eq!(sample, want, "luma sample {i} at dc level {level}");
6012 }
6013 // The chroma transform blocks are all-zero, so both planes stay at
6014 // the prediction. A desync in the luma coefficient syntax lands
6015 // here first: the chroma flags are the next symbols after it.
6016 for (i, &sample) in chroma.iter().enumerate() {
6017 assert_eq!(sample, 128, "chroma sample {i} at dc level {level}");
6018 }
6019 seen.push((level, want));
6020 }
6021 // The picture moves off mid-grey the way the level says: up for a
6022 // positive level, down for a negative one, and never back towards it
6023 // as the level grows.
6024 for w in seen.windows(2) {
6025 let ((prev_level, prev), (level, value)) = (w[0], w[1]);
6026 if prev_level.signum() != level.signum() {
6027 continue;
6028 }
6029 if level > 0 {
6030 assert!(
6031 value >= prev,
6032 "level {level} decoded below level {prev_level}"
6033 );
6034 assert!(value >= 128, "a positive level darkened the picture");
6035 } else {
6036 assert!(
6037 value <= prev,
6038 "level {level} decoded above level {prev_level}"
6039 );
6040 assert!(value <= 128, "a negative level brightened the picture");
6041 }
6042 }
6043 assert!(
6044 DECODED_AT_Q100.iter().any(|&(_, v)| v > 128)
6045 && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128),
6046 "the pinned table has to move the picture both ways"
6047 );
6048 }
6049
6050 /// Encode a grid of 64x64 superblocks, each carrying its own DC level, and
6051 /// hand back the decoded planes.
6052 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
6053 let (w, h) = (64 * sb_cols, 64 * sb_rows);
6054 let (seq, mut header) = frame_of(w, h);
6055 // The DC fixture writers code against the default CDFs and never
6056 // update them, so their frames say so.
6057 header.disable_cdf_update = true;
6058 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
6059 let mut stream = temporal_delimiter();
6060 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
6061 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
6062 ffmpeg_decode(&stream, w as usize, h as usize)
6063 }
6064
6065 /// A sequence and key frame header for a `w` by `h` frame of whole
6066 /// superblocks.
6067 fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) {
6068 let mut seq = sequence_64();
6069 seq.max_frame_width = w;
6070 seq.max_frame_height = h;
6071 let mut header = flat_key_frame();
6072 // Every tile these headers carry is written by the adapting writer.
6073 header.disable_cdf_update = false;
6074 header.frame_width = w;
6075 header.frame_height = h;
6076 header.upscaled_width = w;
6077 header.render_width = w;
6078 header.render_height = h;
6079 header.mi_cols = w / 4;
6080 header.mi_rows = h / 4;
6081 header.tile_info.mi_col_starts = vec![0, header.mi_cols];
6082 header.tile_info.mi_row_starts = vec![0, header.mi_rows];
6083 header.quantization.base_q_idx = Q_IDX;
6084 (seq, header)
6085 }
6086
6087 fn decoded_value(level: i32) -> u8 {
6088 DECODED_AT_Q100
6089 .iter()
6090 .find(|&&(l, _)| l == level)
6091 .map(|&(_, v)| v)
6092 .expect("the level is in the pinned table")
6093 }
6094
6095 /// `dc_predict` (spec 7.11.2) for the flat case: a block whose neighbours
6096 /// are themselves flat predicts their average, and predicts mid-grey with
6097 /// no neighbour at all. Every block here is a whole 64x64 superblock, so
6098 /// the above row and the left column weigh the same.
6099 fn dc_prediction(above: Option<u8>, left: Option<u8>) -> u8 {
6100 match (above, left) {
6101 (None, None) => 128,
6102 (Some(a), None) => a,
6103 (None, Some(l)) => l,
6104 (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8,
6105 }
6106 }
6107
6108 /// What a DC level adds to the prediction: the pinned table is that sum
6109 /// against a mid-grey prediction, and the residual does not depend on what
6110 /// it is added to.
6111 fn dc_residual(level: i32) -> i32 {
6112 i32::from(decoded_value(level)) - 128
6113 }
6114
6115 /// Every block reads its DC sign context off the coded blocks above and to
6116 /// its left, and the three ways that can land — no coded neighbour, the
6117 /// neighbours leaning one way, the neighbours cancelling — are only
6118 /// reachable in a frame whose levels differ in sign. Getting the context
6119 /// wrong desyncs the arithmetic decoder, so the check is that every block
6120 /// still decodes to the grey its own level asks for.
6121 #[test]
6122 fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {
6123 if !have_ffmpeg() {
6124 eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg");
6125 return;
6126 }
6127 // Read in raster order the two grids put a positive, a negative and a
6128 // cancelling sign context in front of the bottom-right block, and a
6129 // leaning-down one in front of the second grid's right and bottom
6130 // blocks.
6131 for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] {
6132 let planes = decode_level_grid(&levels, 2, 2);
6133 let (luma, chroma) = planes.split_at(128 * 128);
6134 // The blocks are not independent: a DC prediction reads the
6135 // reconstructed neighbours, so each block's grey is its
6136 // neighbours' average plus its own residual.
6137 let mut recon = [0u8; 4];
6138 for (block, level) in levels.iter().enumerate() {
6139 let (br, bc) = (block / 2, block % 2);
6140 let above = (br > 0).then(|| recon[block - 2]);
6141 let left = (bc > 0).then(|| recon[block - 1]);
6142 let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level))
6143 .clamp(0, 255) as u8;
6144 recon[block] = want;
6145 for y in 0..64 {
6146 for x in 0..64 {
6147 let i = (br * 64 + y) * 128 + bc * 64 + x;
6148 assert_eq!(
6149 luma[i], want,
6150 "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}"
6151 );
6152 }
6153 }
6154 }
6155 for (i, &sample) in chroma.iter().enumerate() {
6156 assert_eq!(sample, 128, "chroma sample {i} of {levels:?}");
6157 }
6158 }
6159 }
6160
6161 /// What a DC level adds to a 32x32 block's prediction at `base_q_idx` 100,
6162 /// pinned from the decoder the way [`DECODED_AT_Q100`] is. A 32x32
6163 /// transform spreads its DC over a quarter of the samples a 64x64 one
6164 /// does, so the same level moves the picture further: level 14 is five
6165 /// sample values here against three there.
6166 const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [
6167 (1, 0),
6168 (2, 1),
6169 (3, 1),
6170 (4, 1),
6171 (5, 2),
6172 (6, 2),
6173 (7, 3),
6174 (8, 3),
6175 (9, 3),
6176 (10, 4),
6177 (11, 4),
6178 (12, 4),
6179 (13, 5),
6180 (14, 5),
6181 (-1, 0),
6182 (-2, -1),
6183 (-3, -1),
6184 (-4, -1),
6185 (-5, -2),
6186 (-6, -2),
6187 (-7, -2),
6188 (-8, -3),
6189 (-9, -3),
6190 (-10, -4),
6191 (-11, -4),
6192 (-12, -4),
6193 (-13, -5),
6194 (-14, -5),
6195 ];
6196
6197 fn split_residual(level: i32) -> i32 {
6198 SPLIT_RESIDUAL_AT_Q100
6199 .iter()
6200 .find(|&&(l, _)| l == level)
6201 .map(|&(_, r)| r)
6202 .expect("the level is in the pinned table")
6203 }
6204
6205 /// Splitting a superblock puts three more syntax elements in front of every
6206 /// block — the split partition itself, the 32x32 partition below it and a
6207 /// chroma mode from the wider table CFL-capable blocks read — and moves the
6208 /// coefficients onto the 32x32 CDFs. Getting any of them wrong desyncs the
6209 /// arithmetic decoder, and the check is that all sixteen blocks still land
6210 /// on the grey their own level and their neighbours ask for.
6211 #[test]
6212 fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
6213 if !have_ffmpeg() {
6214 eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
6215 return;
6216 }
6217 // Four by four 32x32 blocks over two by two superblocks, so the walk
6218 // crosses superblock boundaries in both directions, and signs that
6219 // alternate so the DC sign context lands on all three of its values.
6220 let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1];
6221 let planes = decode_split_grid(&levels, 2, 2);
6222 let (luma, chroma) = planes.split_at(128 * 128);
6223
6224 let mut recon = [0i32; 16];
6225 for (block, level) in levels.iter().enumerate() {
6226 let (br, bc) = (block / 4, block % 4);
6227 let above = (br > 0).then(|| recon[block - 4] as u8);
6228 let left = (bc > 0).then(|| recon[block - 1] as u8);
6229 let want =
6230 (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255);
6231 recon[block] = want;
6232 for y in 0..32 {
6233 for x in 0..32 {
6234 let i = (br * 32 + y) * 128 + bc * 32 + x;
6235 assert_eq!(
6236 i32::from(luma[i]),
6237 want,
6238 "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \
6239 column {bc}"
6240 );
6241 }
6242 }
6243 }
6244 for (i, &sample) in chroma.iter().enumerate() {
6245 assert_eq!(sample, 128, "chroma sample {i}");
6246 }
6247 }
6248
6249 /// Encode a grid of 32x32 blocks, each carrying its own DC level.
6250 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
6251 let (w, h) = (64 * sb_cols, 64 * sb_rows);
6252 let (seq, mut header) = frame_of(w, h);
6253 // The DC fixture writers code against the default CDFs and never
6254 // update them, so their frames say so.
6255 header.disable_cdf_update = true;
6256 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
6257 let mut stream = temporal_delimiter();
6258 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
6259 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
6260 ffmpeg_decode(&stream, w as usize, h as usize)
6261 }
6262
6263 #[test]
6264 fn a_level_grid_that_does_not_cover_the_frame_is_refused() {
6265 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err());
6266 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err());
6267 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());
6268 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());
6269 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());
6270 }
6271
6272 #[test]
6273 fn dc_levels_the_base_syntax_cannot_carry_are_refused() {
6274 assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());
6275 assert!(dc_key_frame_tile(16, 16, 100, 15).is_err());
6276 assert!(dc_key_frame_tile(16, 16, 100, -15).is_err());
6277 }
6278
6279 #[test]
6280 fn partial_superblocks_are_refused() {
6281 assert!(flat_key_frame_tile(16, 20).is_err());
6282 assert!(flat_key_frame_tile(0, 16).is_err());
6283 }
6284
6285 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
6286 /// hands back the luma plane as rows of samples.
6287 fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {
6288 let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect();
6289 let [luma, u, v] = decode_coeff_planes(&blocks);
6290 for (name, plane) in [("U", &u), ("V", &v)] {
6291 for (y, row) in plane.iter().enumerate() {
6292 for (x, &s) in row.iter().enumerate() {
6293 assert_eq!(
6294 s, 128,
6295 "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \
6296 DC prediction with no coded neighbour is mid-grey"
6297 );
6298 }
6299 }
6300 }
6301 luma
6302 }
6303
6304 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
6305 /// hands back its three planes as rows of samples: 64 rows of luma and, at
6306 /// 4:2:0, 32 rows of each chroma plane.
6307 fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] {
6308 let (seq, header) = frame_of(64, 64);
6309 let tile =
6310 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
6311 let mut stream = temporal_delimiter();
6312 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
6313 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
6314 let planes = ffmpeg_decode(&stream, 64, 64);
6315 let (luma, chroma) = planes.split_at(64 * 64);
6316 let (u, v) = chroma.split_at(32 * 32);
6317 [
6318 luma.chunks_exact(64).map(<[u8]>::to_vec).collect(),
6319 u.chunks_exact(32).map(<[u8]>::to_vec).collect(),
6320 v.chunks_exact(32).map(<[u8]>::to_vec).collect(),
6321 ]
6322 }
6323
6324 /// The top-left 32x32 block of a decoded frame, which is the only one whose
6325 /// prediction has no neighbour to lean on.
6326 fn top_left_block(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
6327 rows[..32].iter().map(|r| r[..32].to_vec()).collect()
6328 }
6329
6330 /// A transform's basis functions all average to zero except the DC's, so a
6331 /// block carrying no DC decodes to samples that average to its prediction —
6332 /// mid-grey for the block with no neighbours. Rounding of the inverse
6333 /// transform moves the average by less than a sample.
6334 fn assert_mean_is_mid_grey(block: &[Vec<u8>]) {
6335 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
6336 let mean = f64::from(sum) / (32.0 * 32.0);
6337 assert!(
6338 (mean - 128.0).abs() <= 1.0,
6339 "a block with no DC coefficient averages to its mid-grey prediction, got {mean}"
6340 );
6341 }
6342
6343 /// A coefficient at row 0, column 1 selects the basis function that is flat
6344 /// down the block and a half-cycle of a cosine across it. Nothing about
6345 /// that shape is pinned here: every row of the block must be the same row,
6346 /// the samples must fall from left to right and actually move, and the
6347 /// block must still average to its prediction. A desync in the scan, the
6348 /// end-of-block position or the level contexts breaks one of those.
6349 #[test]
6350 fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
6351 if !have_ffmpeg() {
6352 eprintln!(
6353 "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg"
6354 );
6355 return;
6356 }
6357 let blocks = vec![
6358 vec![Coeff {
6359 row: 0,
6360 col: 1,
6361 level: 12,
6362 }],
6363 Vec::new(),
6364 Vec::new(),
6365 Vec::new(),
6366 ];
6367 let rows = decode_coeff_quadrants(&blocks);
6368 let block = top_left_block(&rows);
6369
6370 for (y, row) in block.iter().enumerate() {
6371 assert_eq!(row, &block[0], "row {y} of a horizontal basis function");
6372 }
6373 assert!(
6374 block[0][0] > block[0][31],
6375 "a positive coefficient leans the block towards its left edge: {:?}",
6376 block[0]
6377 );
6378 for x in 1..32 {
6379 assert!(
6380 block[0][x] <= block[0][x - 1],
6381 "the half-cycle falls from left to right, broke at column {x}: {:?}",
6382 block[0]
6383 );
6384 }
6385 assert_mean_is_mid_grey(&block);
6386
6387 // The same coefficient transposed selects the basis function that is
6388 // flat across the block and a half-cycle down it.
6389 let blocks = vec![
6390 vec![Coeff {
6391 row: 1,
6392 col: 0,
6393 level: 12,
6394 }],
6395 Vec::new(),
6396 Vec::new(),
6397 Vec::new(),
6398 ];
6399 let rows = decode_coeff_quadrants(&blocks);
6400 let block = top_left_block(&rows);
6401 for (y, row) in block.iter().enumerate() {
6402 for (x, &s) in row.iter().enumerate() {
6403 assert_eq!(s, row[0], "sample ({y},{x}) of a vertical basis function");
6404 }
6405 }
6406 assert!(
6407 block[0][0] > block[31][0],
6408 "a positive coefficient leans the block up"
6409 );
6410 for y in 1..32 {
6411 assert!(
6412 block[y][0] <= block[y - 1][0],
6413 "the half-cycle falls from top to bottom, broke at row {y}"
6414 );
6415 }
6416 assert_mean_is_mid_grey(&block);
6417 }
6418
6419 /// A coefficient late in the scan pushes the end-of-block position into a
6420 /// group that carries an offset — the far corner of a 32x32 transform is
6421 /// the last of the eleven groups, whose offset is nine bits wide, one of
6422 /// them from a CDF and the rest raw. Every coefficient before it is coded
6423 /// too, so this also walks the base and base-range contexts over a block
6424 /// with neighbours that carry levels rather than zeros.
6425 #[test]
6426 fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {
6427 if !have_ffmpeg() {
6428 eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group");
6429 return;
6430 }
6431 let block = vec![
6432 Coeff {
6433 row: 31,
6434 col: 31,
6435 level: 5,
6436 },
6437 Coeff {
6438 row: 5,
6439 col: 7,
6440 level: -9,
6441 },
6442 Coeff {
6443 row: 1,
6444 col: 1,
6445 level: 14,
6446 },
6447 Coeff {
6448 row: 0,
6449 col: 2,
6450 level: -3,
6451 },
6452 Coeff {
6453 row: 2,
6454 col: 0,
6455 level: 2,
6456 },
6457 Coeff {
6458 row: 1,
6459 col: 2,
6460 level: -1,
6461 },
6462 ];
6463 let rows = decode_coeff_quadrants(&[block, Vec::new(), Vec::new(), Vec::new()]);
6464 let block = top_left_block(&rows);
6465 assert_mean_is_mid_grey(&block);
6466 assert!(
6467 block.iter().flatten().any(|&s| s != block[0][0]),
6468 "six coefficients do not decode to a flat block"
6469 );
6470 // The blocks that carry nothing are flat: their prediction is whatever
6471 // their neighbours left, and they add no residual to it.
6472 for (name, ys, xs) in [("top right", 0..32, 32..64), ("bottom left", 32..64, 0..32)] {
6473 let first = rows[ys.start][xs.start];
6474 for y in ys {
6475 for x in xs.clone() {
6476 assert_eq!(rows[y][x], first, "the {name} block carries no coefficient");
6477 }
6478 }
6479 }
6480 }
6481
6482 /// The price the mode search pays for a block's levels has to be the price
6483 /// the writer charges for them, or the search is ranking modes by a
6484 /// fiction. Both halves are asked for the same grids under the same
6485 /// neutral contexts, and the priced bits are compared against the bytes
6486 /// the writer really spends.
6487 #[test]
6488 fn the_priced_coefficient_bits_match_the_bytes_written() {
6489 let scan = default_scan(TX32);
6490 // Three grids that reach different parts of the syntax: a lone DC, a
6491 // sparse spread of small levels with both signs, and levels past the
6492 // base-range alphabet so the Golomb tail runs.
6493 let mut grids = vec![vec![0i32; TX32 * TX32]; 3];
6494 grids[0][0] = -7;
6495 for (i, &pos) in scan.iter().enumerate().take(400) {
6496 if i % 7 == 0 {
6497 grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 };
6498 }
6499 }
6500 grids[2][0] = 40;
6501 for (i, &pos) in scan.iter().enumerate().take(64) {
6502 grids[2][pos as usize] += i as i32 % 23 - 11;
6503 }
6504
6505 // A single block is too short for the coder's own flush to average
6506 // out, so all three go through one encoder and one flush.
6507 let mut enc = SymbolEncoder::new();
6508 let mut priced = 0.0;
6509 for grid in &grids {
6510 write_coeffs(
6511 &mut enc,
6512 &mut Cdfs::new(2).txb(TxbSet::Luma32, 0),
6513 grid,
6514 &scan,
6515 0,
6516 0,
6517 None,
6518 );
6519 priced += luma_32_coeff_bits(grid);
6520 }
6521 let spent = enc.finish().len() as f64 * 8.0;
6522 assert!(
6523 (priced - spent).abs() / spent < 0.02,
6524 "priced {priced} bits, wrote {spent}"
6525 );
6526 }
6527
6528 /// A rate term the search can read as constant is a rate term that ranks
6529 /// nothing, so the price is checked to move the way the levels move: an
6530 /// empty block is the cheapest thing there is, one coefficient costs more
6531 /// than none, and both spreading the coefficients and growing them costs
6532 /// more again.
6533 #[test]
6534 fn the_price_grows_with_the_levels() {
6535 let grid = |f: &dyn Fn(&mut Vec<i32>)| {
6536 let mut g = vec![0i32; TX32 * TX32];
6537 f(&mut g);
6538 luma_32_coeff_bits(&g)
6539 };
6540 let empty = grid(&|_| {});
6541 let one = grid(&|g| g[0] = 1);
6542 let bigger = grid(&|g| g[0] = 30);
6543 let spread = grid(&|g| {
6544 for i in 0..TX32 {
6545 g[i * TX32 + i] = 1;
6546 }
6547 });
6548 assert!(empty < one, "{empty} {one}");
6549 assert!(one < bigger, "{one} {bigger}");
6550 assert!(one < spread, "{one} {spread}");
6551 // An empty block is one symbol -- an expensive one, because a block
6552 // with no coefficients at all is the rarer of the two under the
6553 // neutral context -- and nothing else.
6554 assert!(
6555 empty < 6.0,
6556 "an empty block is one skip symbol, not {empty}"
6557 );
6558 }
6559
6560 /// Neighbouring blocks that each carry coefficients read their DC sign
6561 /// context, their prediction and their own contexts off each other, so a
6562 /// frame whose four blocks all carry mixed-sign coefficients exercises what
6563 /// a single coded block cannot. The check is that it decodes at all — a
6564 /// desync anywhere fails the decode or the frame size — and that the block
6565 /// with no neighbours still averages to mid-grey.
6566 #[test]
6567 fn every_quadrant_carries_its_own_coefficients() {
6568 if !have_ffmpeg() {
6569 eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg");
6570 return;
6571 }
6572 let blocks = vec![
6573 vec![
6574 Coeff {
6575 row: 0,
6576 col: 1,
6577 level: 7,
6578 },
6579 Coeff {
6580 row: 3,
6581 col: 4,
6582 level: -14,
6583 },
6584 ],
6585 vec![
6586 Coeff {
6587 row: 0,
6588 col: 0,
6589 level: -6,
6590 },
6591 Coeff {
6592 row: 2,
6593 col: 2,
6594 level: 9,
6595 },
6596 ],
6597 vec![
6598 Coeff {
6599 row: 0,
6600 col: 0,
6601 level: 6,
6602 },
6603 Coeff {
6604 row: 1,
6605 col: 0,
6606 level: -2,
6607 },
6608 Coeff {
6609 row: 8,
6610 col: 9,
6611 level: 3,
6612 },
6613 ],
6614 vec![
6615 Coeff {
6616 row: 0,
6617 col: 0,
6618 level: 11,
6619 },
6620 Coeff {
6621 row: 16,
6622 col: 1,
6623 level: -4,
6624 },
6625 ],
6626 ];
6627 let rows = decode_coeff_quadrants(&blocks);
6628 assert_mean_is_mid_grey(&top_left_block(&rows));
6629 for (name, ys, xs) in [
6630 ("top right", 0..32, 32..64),
6631 ("bottom left", 32..64, 0..32),
6632 ("bottom right", 32..64, 32..64),
6633 ] {
6634 let block: Vec<Vec<u8>> = rows[ys].iter().map(|r| r[xs.clone()].to_vec()).collect();
6635 assert!(
6636 block.iter().flatten().any(|&s| s != block[0][0]),
6637 "the {name} block carries coefficients, so it is not flat"
6638 );
6639 }
6640 }
6641
6642 /// The top-left 16x16 block of a decoded chroma plane, which is the only
6643 /// one whose prediction has no neighbour to lean on.
6644 fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
6645 rows[..16].iter().map(|r| r[..16].to_vec()).collect()
6646 }
6647
6648 /// The mean of a decoded block, which every basis function but the DC's
6649 /// leaves at the block's prediction.
6650 fn mean(block: &[Vec<u8>]) -> f64 {
6651 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
6652 let count = block.iter().map(Vec::len).sum::<usize>() as f64;
6653 f64::from(sum) / count
6654 }
6655
6656 /// A chroma plane's coefficients ride their own transform, their own CDFs
6657 /// and their own end-of-block alphabet, so a chroma basis function is the
6658 /// gate on all three: U carries the coefficient that is flat down the block
6659 /// and a half-cycle across it, V the one turned a quarter turn, and neither
6660 /// may reach the other plane or luma.
6661 #[test]
6662 fn each_chroma_plane_codes_its_own_basis_function() {
6663 if !have_ffmpeg() {
6664 eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
6665 return;
6666 }
6667 let mut blocks = vec![BlockCoeffs::default(); 4];
6668 blocks[0].u = vec![Coeff {
6669 row: 0,
6670 col: 1,
6671 level: 12,
6672 }];
6673 blocks[0].v = vec![Coeff {
6674 row: 1,
6675 col: 0,
6676 level: 12,
6677 }];
6678 let [luma, u, v] = decode_coeff_planes(&blocks);
6679
6680 for (y, row) in luma.iter().enumerate() {
6681 for (x, &s) in row.iter().enumerate() {
6682 assert_eq!(
6683 s, 128,
6684 "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \
6685 stays at its mid-grey prediction"
6686 );
6687 }
6688 }
6689
6690 let u_block = top_left_chroma(&u);
6691 for (y, row) in u_block.iter().enumerate() {
6692 assert_eq!(
6693 row, &u_block[0],
6694 "row {y} of a horizontal chroma basis function"
6695 );
6696 }
6697 assert!(
6698 u_block[0][0] > u_block[0][15],
6699 "a positive coefficient leans the U block towards its left edge: {:?}",
6700 u_block[0]
6701 );
6702
6703 let v_block = top_left_chroma(&v);
6704 for (x, &top) in v_block[0].iter().enumerate() {
6705 assert_eq!(
6706 top, v_block[0][0],
6707 "column {x} of a vertical chroma basis function"
6708 );
6709 let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect();
6710 assert!(
6711 column[0] > column[15],
6712 "a positive coefficient leans the V column towards its top edge: {column:?}"
6713 );
6714 }
6715
6716 for (name, block) in [("U", &u_block), ("V", &v_block)] {
6717 let mean = mean(block);
6718 assert!(
6719 (mean - 128.0).abs() <= 1.0,
6720 "the {name} block carries no DC, so it averages to its mid-grey prediction, \
6721 got {mean}"
6722 );
6723 }
6724 }
6725
6726 /// Every block coding chroma puts the chroma all-zero flag on the contexts
6727 /// a coded neighbour above and to the left select, and the DC sign on the
6728 /// contexts their signs select. A frame whose four blocks all carry chroma
6729 /// DCs of mixed sign walks those contexts; the picture that comes back must
6730 /// still lean the way each block's own DC asks.
6731 #[test]
6732 fn chroma_dc_signs_read_their_neighbours() {
6733 if !have_ffmpeg() {
6734 eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
6735 return;
6736 }
6737 let dc = |level| {
6738 vec![Coeff {
6739 row: 0,
6740 col: 0,
6741 level,
6742 }]
6743 };
6744 let signs = [8, -8, -8, 8];
6745 let blocks: Vec<BlockCoeffs> = signs
6746 .iter()
6747 .map(|&level| BlockCoeffs {
6748 luma: Vec::new(),
6749 u: dc(level),
6750 v: dc(-level),
6751 ..BlockCoeffs::default()
6752 })
6753 .collect();
6754 let [luma, u, v] = decode_coeff_planes(&blocks);
6755
6756 for (y, row) in luma.iter().enumerate() {
6757 for (x, &s) in row.iter().enumerate() {
6758 assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient");
6759 }
6760 }
6761
6762 // A DC prediction leans on the neighbours a block has, so each block is
6763 // measured against the prediction it was given rather than mid-grey:
6764 // the only block with no neighbour is the first, and the rest are read
6765 // as a step away from the block above them and to their left.
6766 for (i, &level) in signs.iter().enumerate() {
6767 let (r, c) = (i / 2, i % 2);
6768 let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> {
6769 plane[r * 16..r * 16 + 16]
6770 .iter()
6771 .map(|row| row[c * 16..c * 16 + 16].to_vec())
6772 .collect()
6773 };
6774 for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] {
6775 let block = block(plane);
6776 let mean = mean(&block);
6777 for (y, row) in block.iter().enumerate() {
6778 assert_eq!(
6779 row.iter().collect::<std::collections::HashSet<_>>().len(),
6780 1,
6781 "row {y} of a DC-only {name} block is flat"
6782 );
6783 }
6784 if i == 0 {
6785 assert!(
6786 (want > 0) == (mean > 128.0),
6787 "{name} block {i} carries a DC of {want}, so it must lean off its \
6788 mid-grey prediction that way, got {mean}"
6789 );
6790 }
6791 }
6792 }
6793 assert_ne!(u, v, "the two chroma planes carry opposite DCs");
6794 }
6795
6796 /// The coefficient writer refuses what it cannot code rather than writing a
6797 /// stream a decoder walks off the end of.
6798 /// The 32x32 block at the given block row and column of a decoded plane.
6799 fn block_at(rows: &[Vec<u8>], block_row: usize, block_col: usize) -> Vec<Vec<u8>> {
6800 rows[block_row * 32..block_row * 32 + 32]
6801 .iter()
6802 .map(|r| r[block_col * 32..block_col * 32 + 32].to_vec())
6803 .collect()
6804 }
6805
6806 /// Encodes a key frame of the given size, whose 32x32 blocks carry
6807 /// `blocks` in raster order, and hands back its luma plane as rows of
6808 /// The neighbour context a block reads is gathered across every cell it
6809 /// spans, not taken from the first one: a 32x32 block whose left-hand
6810 /// neighbour cells disagree still sees the coded one. Reading a single
6811 /// cell agreed with the decoder only while every block was the same size,
6812 /// and desynchronised the arithmetic decoder the moment a 16x16 one
6813 /// appeared beside a 32x32 one.
6814 #[test]
6815 fn a_block_gathers_the_cells_its_neighbours_cover() {
6816 let mut neighbours = Neighbours::new(4, 4, 64, 64);
6817 let quiet = [
6818 vec![0i32; TX16 * TX16],
6819 vec![0; TX8 * TX8],
6820 vec![0; TX8 * TX8],
6821 ];
6822 let mut loud = quiet.clone();
6823 loud[1][0] = -3;
6824 // Two 16x16 blocks above the right-hand 32x32 block of the row, of
6825 // which only the second codes anything.
6826 neighbours.record((0, 2), SUB, DC_PRED, &quiet);
6827 neighbours.record((0, 3), SUB, DC_PRED, &loud);
6828 let around = neighbours.around((2, 2), BLOCK);
6829 assert!(
6830 around[1].above_coded,
6831 "the coded cell has to reach the block below it"
6832 );
6833 assert_eq!(
6834 dc_sign_ctx(around[1].dc_vote),
6835 1,
6836 "the one negative DC above the block is what it votes"
6837 );
6838 // The same read one cell at a time misses it, which is the bug this
6839 // gate is here for. `above[8]` is the first 4x4 unit the quiet block
6840 // at `(0, 2)` wrote (2 SUB units * 4 4x4-units-per-SUB).
6841 assert!(!neighbours.above[8][1].coded);
6842 }
6843
6844 /// samples.
6845 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
6846 let (seq, header) = frame_of(width as u32, height as u32);
6847 let tile =
6848 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
6849 let mut stream = temporal_delimiter();
6850 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
6851 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
6852 let planes = ffmpeg_decode(&stream, width, height);
6853 planes[..width * height]
6854 .chunks_exact(width)
6855 .map(<[u8]>::to_vec)
6856 .collect()
6857 }
6858
6859 /// Every row of a block is the same row, and that row falls from left to
6860 /// right — the shape of a coefficient at row 0, column 1.
6861 fn assert_falls_across(block: &[Vec<u8>], name: &str) {
6862 for row in block {
6863 assert_eq!(
6864 row, &block[0],
6865 "{name}: every row of the block is the same row"
6866 );
6867 }
6868 assert!(
6869 block[0][0] > block[0][31],
6870 "{name}: the row falls from left to right, got {} then {}",
6871 block[0][0],
6872 block[0][31]
6873 );
6874 }
6875
6876 /// Every column of a block is constant across it and falls down it — the
6877 /// shape of a coefficient at row 1, column 0.
6878 fn assert_falls_down(block: &[Vec<u8>], name: &str) {
6879 for (y, row) in block.iter().enumerate() {
6880 assert!(
6881 row.iter().all(|&s| s == row[0]),
6882 "{name}: row {y} of the block is one constant"
6883 );
6884 }
6885 assert!(
6886 block[0][0] > block[31][0],
6887 "{name}: the column falls down the block, got {} then {}",
6888 block[0][0],
6889 block[31][0]
6890 );
6891 }
6892
6893 /// The mean sample of a decoded block.
6894 fn mean_of(block: &[Vec<u8>]) -> f64 {
6895 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
6896 f64::from(sum) / (block.len() * block[0].len()) as f64
6897 }
6898
6899 /// The top-left block of a frame whose only coefficient is a luma DC of
6900 /// `level`.
6901 fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> {
6902 let blocks = vec![
6903 vec![Coeff {
6904 row: 0,
6905 col: 0,
6906 level,
6907 }],
6908 Vec::new(),
6909 Vec::new(),
6910 Vec::new(),
6911 ];
6912 top_left_block(&decode_coeff_quadrants(&blocks))
6913 }
6914
6915 /// `read_golomb` (spec 5.11.40), written from the specification's
6916 /// pseudocode, and the level its caller builds from it: a level above the
6917 /// base-range tail is fifteen plus what the tail carries.
6918 fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 {
6919 let mut length = 0;
6920 while dec.literal(1) == 0 {
6921 length += 1;
6922 assert!(
6923 length < 20,
6924 "the tail's length prefix runs past twenty bits"
6925 );
6926 }
6927 let mut x = 1;
6928 for _ in 0..length {
6929 x = (x << 1) | dec.literal(1);
6930 }
6931 (MAX_BR_LEVEL + 1) as u32 + (x - 1)
6932 }
6933
6934 /// The tail says how much of the level the base and base-range syntax could
6935 /// not carry, and the spec's own reader must hand back the level that was
6936 /// asked for — not one either side of it. A tail written a bit long, a bit
6937 /// short, or against the wrong base fails this at the first level it
6938 /// reaches.
6939 #[test]
6940 fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
6941 for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300)
6942 .chain([MAX_LEVEL - 1, MAX_LEVEL])
6943 .map(|l| l as u32)
6944 {
6945 let mut enc = SymbolEncoder::new();
6946 write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32);
6947 // The tail is raw bits, so it needs no padding beyond what the
6948 // encoder's own flush writes.
6949 let data = enc.finish();
6950 let mut dec = crate::msac::tests::SymbolDecoder::new(&data);
6951 assert_eq!(
6952 read_golomb_level(&mut dec),
6953 level,
6954 "the tail of level {level}"
6955 );
6956 }
6957 }
6958
6959 /// The base and base-range syntax reach level fourteen between them;
6960 /// anything above that carries the rest of itself as a Golomb tail, written
6961 /// after its own sign. A DC level moves the whole block off its mid-grey
6962 /// prediction by an amount that grows with the level, so a run of levels
6963 /// either side of the tail's threshold — spaced wide enough that the
6964 /// quantiser separates them — must decode to a run of steadily
6965 /// brighter blocks — and the negatives of the same levels to steadily
6966 /// darker ones. A tail written with the wrong length, in the wrong place in
6967 /// the syntax, or off by one desyncs the decoder outright.
6968 #[test]
6969 fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
6970 if !have_ffmpeg() {
6971 eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
6972 return;
6973 }
6974 let mut brighter = Vec::new();
6975 let mut darker = Vec::new();
6976 for level in [10, 14, 18, 31, 60, 400] {
6977 brighter.push((level, mean_of(&decode_dc_level_block(level))));
6978 darker.push((level, mean_of(&decode_dc_level_block(-level))));
6979 }
6980 for pair in brighter.windows(2) {
6981 let [(low, dim), (high, bright)] = [pair[0], pair[1]];
6982 assert!(
6983 bright > dim,
6984 "level {high} decodes brighter than level {low}, got {bright} against {dim}"
6985 );
6986 }
6987 for pair in darker.windows(2) {
6988 let [(low, bright), (high, dim)] = [pair[0], pair[1]];
6989 assert!(
6990 dim < bright,
6991 "level -{high} decodes darker than level -{low}, got {dim} against {bright}"
6992 );
6993 }
6994 let (_, mid) = brighter[0];
6995 assert!(
6996 mid > 128.0 && darker[0].1 < 128.0,
6997 "a positive level brightens its block and a negative one darkens it, got {mid} and {}",
6998 darker[0].1
6999 );
7000 }
7001
7002 /// A frame need not be a whole number of superblocks. A 96x64 frame is a
7003 /// superblock and a half across: the second superblock has no right-hand
7004 /// half, so its partition is a gathered flag rather than the full symbol,
7005 /// and the two blocks that would sit in that half are never coded at all.
7006 /// Each of the six blocks that do exist carries one of two basis functions,
7007 /// alternating, so a block written into the wrong place or a flag the
7008 /// decoder reads as a different number of bits shows up as a block with the
7009 /// other block's shape — or as a decode failure.
7010 fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8>> {
7011 let (seq, header) = frame_of(width as u32, height as u32);
7012 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap();
7013 let mut stream = temporal_delimiter();
7014 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
7015 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
7016 let planes = ffmpeg_decode(&stream, width, height);
7017 planes[..width * height]
7018 .chunks_exact(width)
7019 .map(<[u8]>::to_vec)
7020 .collect()
7021 }
7022
7023 /// A superblock left whole carries one 64x64 transform, whose lowest
7024 /// horizontal basis function falls across the whole sixty-four samples in
7025 /// one stroke. Were the same superblock split, each half would restart the
7026 /// gradient at its own left edge and the picture would rise again in the
7027 /// middle, so the walk across the row is what tells the two apart — and
7028 /// the split superblock beside it proves the two partitions still agree on
7029 /// where the next one begins.
7030 #[test]
7031 fn a_whole_superblock_covers_all_four_of_its_quadrants() {
7032 if !have_ffmpeg() {
7033 eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg");
7034 return;
7035 }
7036 let across = BlockCoeffs::from(vec![Coeff {
7037 row: 0,
7038 col: 1,
7039 level: 20,
7040 }]);
7041 let down = BlockCoeffs::from(vec![Coeff {
7042 row: 1,
7043 col: 0,
7044 level: 20,
7045 }]);
7046 let sbs = [
7047 Superblock::Whole(across),
7048 Superblock::Split(vec![
7049 Quadrant::Whole(down.clone()),
7050 Quadrant::Whole(down.clone()),
7051 Quadrant::Whole(down.clone()),
7052 Quadrant::Whole(down),
7053 ]),
7054 ];
7055 let rows = decode_luma_sb(128, 64, &sbs);
7056
7057 for (y, row) in rows.iter().enumerate() {
7058 assert_eq!(
7059 &row[..64],
7060 &rows[0][..64],
7061 "row {y} of the whole superblock repeats its first row"
7062 );
7063 }
7064 let first = &rows[0][..64];
7065 assert!(
7066 first.windows(2).all(|w| w[0] >= w[1]),
7067 "the whole superblock falls across its sixty-four samples without \
7068 restarting: {first:?}"
7069 );
7070 assert!(
7071 first[0] > first[63],
7072 "the whole superblock falls from left to right, got {} then {}",
7073 first[0],
7074 first[63]
7075 );
7076 for block_row in 0..2 {
7077 for block_col in 2..4 {
7078 let block = block_at(&rows, block_row, block_col);
7079 assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})"));
7080 }
7081 }
7082 }
7083
7084 /// A quadrant may be split again into four 16x16 blocks, each carrying its
7085 /// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block
7086 /// makes each of the four a flat grey of its own, so the quadrant reads as
7087 /// four squares rather than one — which is what tells the extra split from
7088 /// a 32x32 block that merely carries the same coefficients.
7089 #[test]
7090 fn a_quadrant_splits_into_four_sixteens() {
7091 if !have_ffmpeg() {
7092 eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
7093 return;
7094 }
7095 let dc = |level: i32| {
7096 BlockCoeffs::from(vec![Coeff {
7097 row: 0,
7098 col: 0,
7099 level,
7100 }])
7101 };
7102 let levels = [14, 8, -8, -14];
7103 let flat = BlockCoeffs::from(Vec::new());
7104 let sbs = [Superblock::Split(vec![
7105 Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()),
7106 Quadrant::Whole(flat.clone()),
7107 Quadrant::Whole(flat.clone()),
7108 Quadrant::Whole(flat),
7109 ])];
7110 let rows = decode_luma_sb(64, 64, &sbs);
7111
7112 let mut greys = Vec::new();
7113 for i in 0..levels.len() {
7114 let (y0, x0) = ((i / 2) * 16, (i % 2) * 16);
7115 let grey = rows[y0][x0];
7116 for (y, row) in rows.iter().enumerate().skip(y0).take(16) {
7117 for (x, &sample) in row.iter().enumerate().skip(x0).take(16) {
7118 assert_eq!(
7119 sample, grey,
7120 "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not"
7121 );
7122 }
7123 }
7124 greys.push(grey);
7125 }
7126
7127 // Each block is predicted DC from the blocks the decoder has already
7128 // rebuilt, so what its own level does is move it off that prediction,
7129 // in the level's own direction.
7130 let g = |i: usize| i32::from(greys[i]);
7131 let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2];
7132 for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() {
7133 assert_eq!(
7134 (g(i) - prediction).signum(),
7135 level.signum(),
7136 "the 16x16 block {i} carries level {level}, so it sits on the \
7137 {} side of the {prediction} its neighbours predict, not at {}",
7138 if level > 0 { "bright" } else { "dark" },
7139 g(i)
7140 );
7141 }
7142 assert_eq!(
7143 greys.iter().collect::<std::collections::HashSet<_>>().len(),
7144 4,
7145 "the four blocks are four different greys, not one: {greys:?}"
7146 );
7147 }
7148
7149 /// A superblock half outside the frame has no partition that keeps a block
7150 /// outside it, so it cannot be left whole.
7151 #[test]
7152 fn a_whole_superblock_at_the_frame_edge_is_refused() {
7153 let block = BlockCoeffs::from(vec![Coeff {
7154 row: 0,
7155 col: 0,
7156 level: 4,
7157 }]);
7158 let sbs = [
7159 Superblock::Split(vec![
7160 Quadrant::Whole(block.clone()),
7161 Quadrant::Whole(block.clone()),
7162 Quadrant::Whole(block.clone()),
7163 Quadrant::Whole(block.clone()),
7164 ]),
7165 Superblock::Whole(block.clone()),
7166 ];
7167 // Ninety-six samples across is three 32x32 blocks, so the second
7168 // superblock hangs half outside the frame.
7169 let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err();
7170 assert!(
7171 format!("{err}").contains("half outside the frame"),
7172 "got {err}"
7173 );
7174 }
7175
7176 #[test]
7177 fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
7178 if !have_ffmpeg() {
7179 eprintln!(
7180 "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \
7181 ffmpeg"
7182 );
7183 return;
7184 }
7185 let blocks: Vec<BlockCoeffs> = (0..6)
7186 .map(|i| {
7187 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
7188 BlockCoeffs::from(vec![Coeff {
7189 row,
7190 col,
7191 level: 12,
7192 }])
7193 })
7194 .collect();
7195 let rows = decode_luma_at(96, 64, &blocks);
7196 for block_row in 0..2 {
7197 for block_col in 0..3 {
7198 let name = format!("block ({block_row},{block_col})");
7199 let block = block_at(&rows, block_row, block_col);
7200 if (block_row * 3 + block_col) % 2 == 0 {
7201 assert_falls_across(&block, &name);
7202 } else {
7203 assert_falls_down(&block, &name);
7204 }
7205 }
7206 }
7207 }
7208
7209 /// The transpose of [`a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block`]:
7210 /// an odd number of 32x32 block *rows* (superblock hangs off the
7211 /// *bottom*, `has_cols=true, has_rows=false`) rather than an odd number of
7212 /// columns (hangs off the *right*, `has_cols=false, has_rows=true`) --
7213 /// the two halves of the `(has_cols, has_rows)` match in
7214 /// `sb_coeff_key_frame_tile` gather from different tables
7215 /// (`VERT_ALIKE`/`HORZ_ALIKE`), and only the right-hand-edge direction had
7216 /// a real-decoder test before this one.
7217 #[test]
7218 fn a_frame_that_hangs_off_the_bottom_codes_every_block() {
7219 if !have_ffmpeg() {
7220 eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg");
7221 return;
7222 }
7223 let blocks: Vec<BlockCoeffs> = (0..6)
7224 .map(|i| {
7225 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
7226 BlockCoeffs::from(vec![Coeff {
7227 row,
7228 col,
7229 level: 12,
7230 }])
7231 })
7232 .collect();
7233 let rows = decode_luma_at(64, 96, &blocks);
7234 for block_row in 0..3 {
7235 for block_col in 0..2 {
7236 let name = format!("block ({block_row},{block_col})");
7237 let block = block_at(&rows, block_row, block_col);
7238 if (block_row * 2 + block_col) % 2 == 0 {
7239 assert_falls_across(&block, &name);
7240 } else {
7241 assert_falls_down(&block, &name);
7242 }
7243 }
7244 }
7245 }
7246
7247 /// A frame whose blocks do not tile it is refused rather than written as a
7248 /// stream a decoder walks off the end of.
7249 #[test]
7250 fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() {
7251 let (_, header) = frame_of(80, 64);
7252 let blocks = vec![BlockCoeffs::default(); 4];
7253 let err = split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, &blocks)
7254 .expect_err("80 is not a whole number of 32x32 blocks");
7255 assert!(
7256 format!("{err}").contains("32x32"),
7257 "the refusal names the block size, got {err}"
7258 );
7259 }
7260
7261 /// A directional intra mode says where its prediction comes from, and with
7262 /// no residual of its own a block must be exactly that prediction. The
7263 /// top-left block is given a basis function that is flat across it and
7264 /// falls down it; the block to its right is coded `H_PRED`, so every one of
7265 /// its rows must be the constant its left neighbour's rightmost column
7266 /// hands it, and the block below is coded `V_PRED`, so every one of its
7267 /// columns must be the constant the row above it ends on — a single flat
7268 /// value for the whole block. Nothing here pins the transform's shape or
7269 /// the mode's CDF: a mode written with the wrong context, an angle delta
7270 /// left out or a mode index off by one desyncs the symbol decoder and the
7271 /// two empty blocks stop mirroring their neighbours.
7272 #[test]
7273 fn directional_modes_predict_from_the_neighbours_they_name() {
7274 if !have_ffmpeg() {
7275 eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg");
7276 return;
7277 }
7278 let gradient = BlockCoeffs {
7279 luma: vec![Coeff {
7280 row: 1,
7281 col: 0,
7282 level: 12,
7283 }],
7284 ..BlockCoeffs::default()
7285 };
7286 let blocks = [
7287 gradient,
7288 BlockCoeffs {
7289 mode: H_PRED as u8,
7290 ..BlockCoeffs::default()
7291 },
7292 BlockCoeffs {
7293 mode: V_PRED as u8,
7294 ..BlockCoeffs::default()
7295 },
7296 BlockCoeffs::default(),
7297 ];
7298 let [luma, ..] = decode_coeff_planes(&blocks);
7299
7300 let source = block_at(&luma, 0, 0);
7301 for (r, row) in source.iter().enumerate() {
7302 assert!(
7303 row.iter().all(|&s| s == row[0]),
7304 "the basis function at row 1, column 0 is flat across the block, row {r} is not: {row:?}"
7305 );
7306 }
7307 let profile: Vec<u8> = source.iter().map(|r| r[0]).collect();
7308 assert!(
7309 profile.windows(2).all(|w| w[0] >= w[1]) && profile[0] > profile[31],
7310 "the block must fall from top to bottom, got {profile:?}"
7311 );
7312
7313 let horizontal = block_at(&luma, 0, 1);
7314 for (r, row) in horizontal.iter().enumerate() {
7315 assert!(
7316 row.iter().all(|&s| s == profile[r]),
7317 "an H_PRED block repeats the column to its left, row {r} should be all {} but is {row:?}",
7318 profile[r]
7319 );
7320 }
7321
7322 let vertical = block_at(&luma, 1, 0);
7323 let bottom = profile[31];
7324 assert!(
7325 vertical.iter().flatten().all(|&s| s == bottom),
7326 "a V_PRED block repeats the row above it, which is all {bottom} here, got rows \
7327 {:?} and {:?}",
7328 vertical[0],
7329 vertical[31]
7330 );
7331 }
7332
7333 /// The mode index is checked before anything is written.
7334 #[test]
7335 fn an_intra_mode_outside_the_key_frame_set_is_refused() {
7336 let mut blocks = vec![BlockCoeffs::default(); 4];
7337 blocks[2].mode = INTRA_MODES as u8;
7338 let message = split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks)
7339 .unwrap_err()
7340 .to_string();
7341 assert!(
7342 message.contains("intra mode 13"),
7343 "the refusal must name the mode, got {message}"
7344 );
7345 }
7346
7347 #[test]
7348 fn coefficients_the_writer_cannot_code_are_refused() {
7349 let empty = || vec![BlockCoeffs::default(); 4];
7350 let cases: [(&str, Vec<BlockCoeffs>); 6] = [
7351 ("one set short", vec![BlockCoeffs::default(); 3]),
7352 ("off the transform", {
7353 let mut b = empty();
7354 b[0].luma = vec![Coeff {
7355 row: 32,
7356 col: 0,
7357 level: 1,
7358 }];
7359 b
7360 }),
7361 ("a zero level", {
7362 let mut b = empty();
7363 b[1].luma = vec![Coeff {
7364 row: 0,
7365 col: 0,
7366 level: 0,
7367 }];
7368 b
7369 }),
7370 ("a level past the Golomb tail's reach", {
7371 let mut b = empty();
7372 b[2].luma = vec![Coeff {
7373 row: 0,
7374 col: 0,
7375 level: MAX_LEVEL + 1,
7376 }];
7377 b
7378 }),
7379 ("two coefficients at one position", {
7380 let mut b = empty();
7381 b[3].luma = vec![
7382 Coeff {
7383 row: 4,
7384 col: 4,
7385 level: 1,
7386 },
7387 Coeff {
7388 row: 4,
7389 col: 4,
7390 level: 2,
7391 },
7392 ];
7393 b
7394 }),
7395 ("off the chroma transform", {
7396 let mut b = empty();
7397 b[0].u = vec![Coeff {
7398 row: 0,
7399 col: 16,
7400 level: 1,
7401 }];
7402 b
7403 }),
7404 ];
7405 for (name, blocks) in cases {
7406 assert!(
7407 split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks).is_err(),
7408 "{name} must be refused"
7409 );
7410 }
7411 }
7412
7413 /// The default scan is written as the rule that generates it rather than a
7414 /// thousand pinned numbers, so the rule is checked against what a scan must
7415 /// be: every position exactly once, the origin first, and never a position
7416 /// before one it sits diagonally behind — which is what lets a decoder read
7417 /// a coefficient's context off the coefficients it has already decoded.
7418 #[test]
7419 fn the_default_scan_walks_every_position_outwards() {
7420 for side in [TX16, TX32] {
7421 let area = side * side;
7422 let scan = default_scan(side);
7423 assert_eq!(scan.len(), area);
7424 let mut seen = vec![false; area];
7425 for &pos in &scan {
7426 assert!(
7427 !seen[pos as usize],
7428 "position {pos} is scanned twice in {side}x{side}"
7429 );
7430 seen[pos as usize] = true;
7431 }
7432 assert_eq!(scan[0], 0, "the scan starts at the DC");
7433
7434 let mut order = vec![0usize; area];
7435 for (i, &pos) in scan.iter().enumerate() {
7436 order[pos as usize] = i;
7437 }
7438 for row in 0..side {
7439 for col in 0..side {
7440 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
7441 let (nr, nc) = (row + dr, col + dc);
7442 if nr < side && nc < side {
7443 assert!(
7444 order[nr * side + nc] > order[row * side + col],
7445 "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
7446 be scanned after it"
7447 );
7448 }
7449 }
7450 }
7451 }
7452 }
7453 }
7454
7455 /// The whole point of the inverse transform living in the encoder is that
7456 /// it predicts the decoder without asking one. The residual a DC-only
7457 /// 64x64 transform produces has already been pinned from a real decoder in
7458 /// [`DECODED_AT_Q100`], so that table is the gate: every level in it, both
7459 /// signs, has to come back out of `dequant_and_inverse` exactly.
7460 #[test]
7461 fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() {
7462 for (level, _) in DECODED_AT_Q100 {
7463 let mut levels = vec![0i32; 64 * 64];
7464 levels[0] = level;
7465 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
7466 let want = dc_residual(level);
7467 assert!(
7468 residual.iter().all(|&r| r == want),
7469 "level {level}: want a flat {want}, got {}..{} (first {})",
7470 residual.iter().min().unwrap(),
7471 residual.iter().max().unwrap(),
7472 residual[0]
7473 );
7474 }
7475 }
7476
7477 /// The same gate at the other transform size the encoder codes: a split
7478 /// superblock's 32x32 blocks, whose residuals are pinned in
7479 /// [`SPLIT_RESIDUAL_AT_Q100`]. The two sizes divide the dequantized
7480 /// coefficient by different denominators, so a size-blind dequantizer
7481 /// passes one table and fails the other.
7482 #[test]
7483 fn the_inverse_transform_reproduces_the_pinned_split_residuals() {
7484 for (level, want) in SPLIT_RESIDUAL_AT_Q100 {
7485 let mut levels = vec![0i32; 32 * 32];
7486 levels[0] = level;
7487 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
7488 assert!(
7489 residual.iter().all(|&r| r == want),
7490 "level {level}: want a flat {want}, got {}..{} (first {})",
7491 residual.iter().min().unwrap(),
7492 residual.iter().max().unwrap(),
7493 residual[0]
7494 );
7495 }
7496 }
7497
7498 /// A DC-only transform is flat, which is exactly the case that cannot tell
7499 /// a transposed or mis-permuted butterfly network from a correct one. An AC
7500 /// coefficient in the first row must vary along the row and stay constant
7501 /// down each column, and the one in the first column the other way round;
7502 /// a transposed network swaps the two.
7503 #[test]
7504 fn a_single_ac_coefficient_varies_along_its_own_axis() {
7505 for side in [4, 8, 16, 32, 64] {
7506 let mut horizontal = vec![0i32; side * side];
7507 horizontal[1] = 100;
7508 let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX));
7509 let mut vertical = vec![0i32; side * side];
7510 vertical[side] = 100;
7511 let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX));
7512 for row in 0..side {
7513 for col in 0..side {
7514 assert_eq!(
7515 h[row * side + col],
7516 h[col],
7517 "{side}: a first-row coefficient is constant down column {col}"
7518 );
7519 assert_eq!(
7520 v[row * side + col],
7521 v[row * side],
7522 "{side}: a first-column coefficient is constant along row {row}"
7523 );
7524 }
7525 }
7526 // The two are each other's transpose. Only to within a rounding
7527 // step: the spec rounds halves up rather than away from zero, so a
7528 // basis function and its transpose can land a count apart where
7529 // the row and column passes round opposite ways.
7530 assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies");
7531 for row in 0..side {
7532 for col in 0..side {
7533 let (a, b) = (h[row * side + col], v[col * side + row]);
7534 assert!(
7535 (a - b).abs() <= 1,
7536 "{side}: transpose at ({row},{col}): {a} vs {b}"
7537 );
7538 }
7539 }
7540 }
7541 }
7542
7543 /// Negating every level negates every residual, to within the one count
7544 /// the spec's round-halves-up leaves behind. A dequantizer that rounded a
7545 /// negative coefficient away from zero instead of toward it would shift a
7546 /// whole basis function, not a count of it, so the bound is what makes
7547 /// this a test rather than a restatement.
7548 #[test]
7549 fn negating_the_levels_negates_the_residual() {
7550 for side in [32, 64] {
7551 for level in [1, 2, 3, 5, 9, 14, 40, 100] {
7552 let mut levels = vec![0i32; side * side];
7553 levels[0] = level;
7554 levels[1] = -level;
7555 levels[side + 1] = level * 2;
7556 let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
7557 let negated: Vec<i32> = levels.iter().map(|&l| -l).collect();
7558 let neg =
7559 crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX));
7560 let worst = pos
7561 .iter()
7562 .zip(&neg)
7563 .map(|(&p, &n)| (p + n).abs())
7564 .max()
7565 .expect("the block is not empty");
7566 assert!(worst <= 1, "side {side} level {level}: off by {worst}");
7567 }
7568 }
7569 }
7570
7571 /// The pinned tables above are DC-only, and a flat residual cannot tell a
7572 /// correct butterfly network from one that is merely correct at DC. This
7573 /// is the same claim against a real decoder and with real AC content: the
7574 /// top-left block of a key frame predicts a flat mid-grey with no
7575 /// neighbours to read, so what ffmpeg shows there is exactly 128 plus the
7576 /// residual the encoder's own inverse transform computes. Every sample has
7577 /// to agree, not most of them.
7578 #[test]
7579 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
7580 if !have_ffmpeg() {
7581 eprintln!(
7582 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg"
7583 );
7584 return;
7585 }
7586 // A DC, two low-frequency terms of each orientation, a diagonal and a
7587 // far corner, with both signs among them.
7588 let coeffs = [
7589 (0u8, 0u8, 9i32),
7590 (0, 1, -14),
7591 (1, 0, 7),
7592 (0, 3, 5),
7593 (3, 0, -3),
7594 (2, 2, 11),
7595 (7, 5, -6),
7596 (31, 31, 4),
7597 ];
7598 let block: BlockCoeffs = coeffs
7599 .iter()
7600 .map(|&(row, col, level)| Coeff { row, col, level })
7601 .collect::<Vec<_>>()
7602 .into();
7603 let rows = decode_luma_at(
7604 64,
7605 64,
7606 &[
7607 block,
7608 BlockCoeffs::default(),
7609 BlockCoeffs::default(),
7610 BlockCoeffs::default(),
7611 ],
7612 );
7613
7614 let mut levels = vec![0i32; 32 * 32];
7615 for &(row, col, level) in &coeffs {
7616 levels[usize::from(row) * 32 + usize::from(col)] = level;
7617 }
7618 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
7619 for row in 0..32 {
7620 for col in 0..32 {
7621 let want = (128 + residual[row * 32 + col]).clamp(0, 255);
7622 assert_eq!(
7623 i32::from(rows[row][col]),
7624 want,
7625 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
7626 rows[row][col]
7627 );
7628 }
7629 }
7630 // The block is not flat, so the agreement is about the transform and
7631 // not about a prediction both sides got trivially right.
7632 let (lo, hi) = (
7633 rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(),
7634 rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(),
7635 );
7636 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
7637 }
7638
7639 /// The same against the smallest transform the writer codes, the 16x16 one
7640 /// a split quadrant carries. Its rounding is the one the split path rests
7641 /// on, and nothing else in the crate exercises it against a decoder.
7642 #[test]
7643 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
7644 if !have_ffmpeg() {
7645 eprintln!(
7646 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
7647 );
7648 return;
7649 }
7650 let coeffs = [
7651 (0u8, 0u8, 9i32),
7652 (0, 1, -14),
7653 (1, 0, 7),
7654 (0, 3, 5),
7655 (3, 0, -3),
7656 (2, 2, 11),
7657 (7, 5, -6),
7658 (15, 15, 4),
7659 ];
7660 let block: BlockCoeffs = coeffs
7661 .iter()
7662 .map(|&(row, col, level)| Coeff { row, col, level })
7663 .collect::<Vec<_>>()
7664 .into();
7665 let (seq, header) = frame_of(64, 64);
7666 let quadrants = vec![
7667 Quadrant::Split(vec![
7668 block,
7669 BlockCoeffs::default(),
7670 BlockCoeffs::default(),
7671 BlockCoeffs::default(),
7672 ]),
7673 Quadrant::Whole(BlockCoeffs::default()),
7674 Quadrant::Whole(BlockCoeffs::default()),
7675 Quadrant::Whole(BlockCoeffs::default()),
7676 ];
7677 let tile = sb_coeff_key_frame_tile(
7678 header.mi_cols,
7679 header.mi_rows,
7680 Q_IDX,
7681 &[Superblock::Split(quadrants)],
7682 )
7683 .unwrap();
7684 let mut stream = temporal_delimiter();
7685 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
7686 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
7687 let planes = ffmpeg_decode(&stream, 64, 64);
7688
7689 let mut levels = vec![0i32; TX16 * TX16];
7690 for &(row, col, level) in &coeffs {
7691 levels[usize::from(row) * TX16 + usize::from(col)] = level;
7692 }
7693 let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX));
7694 for row in 0..TX16 {
7695 for col in 0..TX16 {
7696 let want = (128 + residual[row * TX16 + col]).clamp(0, 255);
7697 assert_eq!(
7698 i32::from(planes[row * 64 + col]),
7699 want,
7700 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
7701 planes[row * 64 + col]
7702 );
7703 }
7704 }
7705 }
7706
7707 /// The same against the other transform size, the 64x64 one a whole
7708 /// superblock carries. Only its top-left 32x32 can hold coefficients, and
7709 /// the spec zeroes the rest before the row transform — a 64-point network
7710 /// that read the missing half as anything else would disagree here.
7711 #[test]
7712 fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {
7713 if !have_ffmpeg() {
7714 eprintln!(
7715 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg"
7716 );
7717 return;
7718 }
7719 let coeffs = [
7720 (0u8, 0u8, 12i32),
7721 (0, 2, -9),
7722 (2, 0, 6),
7723 (1, 1, -5),
7724 (5, 9, 8),
7725 (31, 0, -4),
7726 (0, 31, 3),
7727 ];
7728 let block: BlockCoeffs = coeffs
7729 .iter()
7730 .map(|&(row, col, level)| Coeff { row, col, level })
7731 .collect::<Vec<_>>()
7732 .into();
7733 let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]);
7734
7735 let mut levels = vec![0i32; 64 * 64];
7736 for &(row, col, level) in &coeffs {
7737 levels[usize::from(row) * 64 + usize::from(col)] = level;
7738 }
7739 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
7740 for row in 0..64 {
7741 for col in 0..64 {
7742 let want = (128 + residual[row * 64 + col]).clamp(0, 255);
7743 assert_eq!(
7744 i32::from(rows[row][col]),
7745 want,
7746 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
7747 rows[row][col]
7748 );
7749 }
7750 }
7751 }
7752
7753 /// The AV1 transforms are normalized so that a quantized level means the
7754 /// same thing at every size: doubling the transform's side halves what a
7755 /// DC level is worth, which is the job the per-size row shift and the
7756 /// dequantizer's denominator split between them. The frame syntax only
7757 /// codes 32x32 and 64x64 transforms, so this is what holds the four
7758 /// smaller sizes' shifts to the spec's table — a shift wrong by one at any
7759 /// size doubles or halves that size's step alone.
7760 #[test]
7761 fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() {
7762 let mut previous: Option<i32> = None;
7763 for side in [4usize, 8, 16, 32, 64] {
7764 let mut levels = vec![0i32; side * side];
7765 levels[0] = 100;
7766 let residual =
7767 crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
7768 let dc = residual[0];
7769 assert!(
7770 residual.iter().all(|&r| r == dc),
7771 "side {side}: a DC coefficient reconstructs flat"
7772 );
7773 if let Some(previous) = previous {
7774 assert!(
7775 (dc * 2 - previous).abs() <= 1,
7776 "side {side}: {dc} is not half of the previous size's {previous}"
7777 );
7778 }
7779 previous = Some(dc);
7780 }
7781 }
7782
7783 /// The encoder's own round trip, through a real bitstream.
7784 ///
7785 /// A picture is chosen, its residual against the DC prediction of 128 is
7786 /// forward-transformed and quantized, the levels are written into a tile,
7787 /// and ffmpeg decodes it. Two things have to hold: what comes back is
7788 /// exactly what the encoder's own inverse said it would be — sample for
7789 /// sample, which is what lets a rate-distortion loop trust its
7790 /// reconstruction — and it is within a quantizer step of the picture that
7791 /// was asked for, which is what makes the forward transform an encoder
7792 /// rather than a scrambler.
7793 #[test]
7794 fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {
7795 if !have_ffmpeg() {
7796 eprintln!(
7797 "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
7798 );
7799 return;
7800 }
7801 // A gradient, a ripple and a corner patch: low frequencies, a mid one
7802 // and an edge, none of them a basis function of the transform.
7803 let mut residual = vec![0i32; 32 * 32];
7804 for row in 0..32usize {
7805 for col in 0..32usize {
7806 let gradient = row as f64 * 2.0 - 32.0;
7807 let ripple = 25.0
7808 * (col as f64 * std::f64::consts::PI / 6.0).sin()
7809 * (row as f64 * std::f64::consts::PI / 11.0).cos();
7810 let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 };
7811 residual[row * 32 + col] = (gradient + ripple + patch).round() as i32;
7812 }
7813 }
7814
7815 let levels =
7816 crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5);
7817 assert!(
7818 levels.iter().any(|&l| l != 0),
7819 "the picture quantized away entirely"
7820 );
7821 let coded: Vec<Coeff> = levels
7822 .iter()
7823 .enumerate()
7824 .filter(|&(_, &level)| level != 0)
7825 .map(|(i, &level)| Coeff {
7826 row: (i / 32) as u8,
7827 col: (i % 32) as u8,
7828 level,
7829 })
7830 .collect();
7831
7832 let rows = decode_luma_at(
7833 64,
7834 64,
7835 &[
7836 coded.into(),
7837 BlockCoeffs::default(),
7838 BlockCoeffs::default(),
7839 BlockCoeffs::default(),
7840 ],
7841 );
7842 let reconstruction =
7843 crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
7844
7845 let mut squared = 0.0f64;
7846 for row in 0..32 {
7847 for col in 0..32 {
7848 let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255);
7849 assert_eq!(
7850 i32::from(rows[row][col]),
7851 want,
7852 "sample ({row},{col}): the decoder and the encoder disagree"
7853 );
7854 let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]);
7855 squared += error * error;
7856 }
7857 }
7858 let rmse = (squared / 1024.0).sqrt();
7859 // A quantizer step is q/8 in residual units. Rounding to nearest
7860 // spreads the error over a step, and a quarter of one is a bound this
7861 // picture clears with room to spare (2.2 of 14 as written) while a
7862 // forward transform that is merely energy-preserving does not: a
7863 // transposed column pass measures 13.3 here.
7864 let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0;
7865 assert!(
7866 rmse < step / 4.0,
7867 "the decoded picture is {rmse} off, a step being {step}"
7868 );
7869 }
7870
7871 /// The inverse of [`write_mv_component`], mirroring [`SymbolDecoder`]
7872 /// against the spec's own `read_mv_component` pseudocode.
7873 fn decode_mv_component(
7874 dec: &mut crate::msac::tests::SymbolDecoder,
7875 c: &mut MvComponentCdfs,
7876 ) -> i32 {
7877 let sign = dec.symbol(&mut c.sign);
7878 let class = dec.symbol(&mut c.class);
7879 let local = if class == 0 {
7880 let bit = dec.symbol(&mut c.class0_bit);
7881 let fr = dec.symbol(&mut c.class0_fr[bit]);
7882 (bit << 3) | (fr << 1) | 1
7883 } else {
7884 let mut d = 0;
7885 for i in 0..class {
7886 d |= dec.symbol(&mut c.bit[i]) << i;
7887 }
7888 let fr = dec.symbol(&mut c.fr);
7889 (d << 3) | (fr << 1) | 1
7890 };
7891 let mag = mv_class_base(class) + local as i32 + 1;
7892 if sign == 1 { -mag } else { mag }
7893 }
7894
7895 /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,
7896 /// mirroring the writer's own context tracking (partition, skip,
7897 /// is_inter, and the MV stack) symbol for symbol against a fresh
7898 /// [`Cdfs`], so a desync between the two shows up as a wrong decoded
7899 /// value rather than a silent pass. Every block here is skipped, so no
7900 /// coefficient symbols are read. `wrong_y_mode` swaps in `KF_Y_MODE`'s
7901 /// (0, 0) row for an intra block's mode read, to show that reading the
7902 /// wrong table decodes the wrong mode rather than the one that was
7903 /// written.
7904 ///
7905 /// One decoded block's `(skip, is_inter, mode, mv)` — `mode` is `None`
7906 /// for an inter block, `mv` is `(0, 0)` for an intra one.
7907 type DecodedBlock = (bool, bool, Option<usize>, (i32, i32));
7908
7909 /// Returns the number of symbols and literals read, and each block's
7910 /// decoded state.
7911 fn decode_inter_sb(
7912 data: &[u8],
7913 mi_cols: u32,
7914 mi_rows: u32,
7915 wrong_y_mode: bool,
7916 ) -> (usize, Vec<DecodedBlock>) {
7917 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
7918 let mut cdfs = Cdfs::new(2);
7919 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
7920 let mut above_skip = [false; 2];
7921 let mut left_skip = [false; 2];
7922 let mut above_inter = [false; 2];
7923 let mut left_inter = [false; 2];
7924 let mut count = 0usize;
7925
7926 count += 1;
7927 dec.symbol(&mut cdfs.partition_w64[0]);
7928
7929 let mut results = Vec::new();
7930 for quadrant in 0..4usize {
7931 let (r32, c32) = (quadrant / 2, quadrant % 2);
7932 count += 1;
7933 dec.symbol(&mut cdfs.partition_w32[0]);
7934
7935 let (has_above, has_left) = (r32 > 0, c32 > 0);
7936 let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]);
7937 count += 1;
7938 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
7939
7940 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]);
7941 count += 1;
7942 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
7943
7944 let (mode, mv) = if is_inter {
7945 let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]);
7946 count += 3;
7947 assert_eq!(
7948 dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
7949 0,
7950 "single_ref p1"
7951 );
7952 assert_eq!(
7953 dec.symbol(&mut cdfs.single_ref[sr_ctx][2]),
7954 0,
7955 "single_ref p3"
7956 );
7957 assert_eq!(
7958 dec.symbol(&mut cdfs.single_ref[sr_ctx][3]),
7959 0,
7960 "single_ref p4"
7961 );
7962
7963 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
7964 let stack = find_mv_stack(
7965 &grid,
7966 mi_row,
7967 mi_col,
7968 8,
7969 8,
7970 1,
7971 mi_cols as usize,
7972 mi_rows as usize,
7973 );
7974
7975 count += 1;
7976 let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0;
7977 let (mv, is_new_mv) = if new_mv {
7978 if stack.entries.len() > 1 {
7979 count += 1;
7980 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
7981 }
7982 count += 1;
7983 let joint = dec.symbol(&mut cdfs.mv_joint);
7984 let mut diff = (0, 0);
7985 if joint == 2 || joint == 3 {
7986 // sign, class, class0_bit, class0_fr for this test's
7987 // small (class 0) components.
7988 count += 4;
7989 diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]);
7990 }
7991 if joint == 1 || joint == 3 {
7992 count += 4;
7993 diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]);
7994 }
7995 ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true)
7996 } else {
7997 count += 2;
7998 assert_eq!(
7999 dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]),
8000 1,
8001 "zero_mv"
8002 );
8003 assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv");
8004 (stack.nearest_mv, false)
8005 };
8006 for dr in 0..8 {
8007 for dc in 0..8 {
8008 grid.set(
8009 mi_row + dr,
8010 mi_col + dc,
8011 MiInfo {
8012 is_inter: true,
8013 ref_frame: 1,
8014 ref_frame1: NO_REF1,
8015 mv1: (0, 0),
8016 mv: mv16(mv),
8017 is_new_mv,
8018 size: 8,
8019 size_h: 8,
8020 is_global_mv0: false,
8021 is_global_mv1: false,
8022 },
8023 );
8024 }
8025 }
8026 (None, mv)
8027 } else {
8028 count += 1;
8029 let m = if wrong_y_mode {
8030 dec.symbol(&mut cdfs.kf_y_mode[0][0])
8031 } else {
8032 dec.symbol(&mut cdfs.y_mode[3])
8033 };
8034 if (V_PRED..=D67_PRED).contains(&m) {
8035 count += 1;
8036 dec.symbol(&mut cdfs.angle_delta[m - V_PRED]);
8037 }
8038 count += 1;
8039 dec.symbol(&mut cdfs.uv_mode_cfl[m]);
8040 (Some(m), (0, 0))
8041 };
8042
8043 above_skip[c32] = skip;
8044 left_skip[r32] = skip;
8045 above_inter[c32] = is_inter;
8046 left_inter[r32] = is_inter;
8047 results.push((skip, is_inter, mode, mv));
8048 }
8049 (count, results)
8050 }
8051
8052 /// Every superblock here skips: no residual, so the only symbols are the
8053 /// mode chain, and the byte count and the symbol count both come out
8054 /// small enough to hand-check.
8055 #[test]
8056 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
8057 let block = BlockCoeffs {
8058 inter: Some(InterInfo {
8059 ref1: None,
8060 mv1: (0, 0),
8061 ref_frame: crate::mvstack::LAST_FRAME,
8062 mode: InterMode::NearestMv,
8063 mv: (0, 0),
8064 ref_mv_idx: 0,
8065 }),
8066 skip: true,
8067 ..BlockCoeffs::default()
8068 };
8069 let blocks = vec![
8070 Quadrant::Whole(block.clone()),
8071 Quadrant::Whole(block.clone()),
8072 Quadrant::Whole(block.clone()),
8073 Quadrant::Whole(block),
8074 ];
8075 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
8076 // Hand count: one partition_w64, then per block partition_w32 + skip +
8077 // is_inter + 3 single_ref + new_mv + zero_mv + ref_mv = 9, times four.
8078 assert!(
8079 data.len() <= 16,
8080 "an all-skip NEARESTMV superblock took {} bytes",
8081 data.len()
8082 );
8083
8084 let (count, results) = decode_inter_sb(&data, 16, 16, false);
8085 assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count");
8086 for (skip, is_inter, mode, mv) in results {
8087 assert!(skip);
8088 assert!(is_inter);
8089 assert_eq!(mode, None);
8090 // Every block's only inter neighbours carry (0, 0), so the stack's
8091 // nearest candidate is (0, 0) throughout.
8092 assert_eq!(mv, (0, 0));
8093 }
8094 }
8095
8096 /// The fourth block codes NEWMV against a (0, 0) predictor with a coded
8097 /// column component: the symbol sequence a decoder reads back has to be
8098 /// exactly what [`write_mv`] wrote, not a residual that merely decodes
8099 /// to *some* valid vector.
8100 #[test]
8101 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
8102 let nearest = BlockCoeffs {
8103 inter: Some(InterInfo {
8104 ref1: None,
8105 mv1: (0, 0),
8106 ref_frame: crate::mvstack::LAST_FRAME,
8107 mode: InterMode::NearestMv,
8108 mv: (0, 0),
8109 ref_mv_idx: 0,
8110 }),
8111 skip: true,
8112 ..BlockCoeffs::default()
8113 };
8114 let newmv = BlockCoeffs {
8115 inter: Some(InterInfo {
8116 ref1: None,
8117 mv1: (0, 0),
8118 ref_frame: crate::mvstack::LAST_FRAME,
8119 mode: InterMode::NewMv,
8120 mv: (0, 2),
8121 ref_mv_idx: 0,
8122 }),
8123 skip: true,
8124 ..BlockCoeffs::default()
8125 };
8126 let blocks = vec![
8127 Quadrant::Whole(nearest.clone()),
8128 Quadrant::Whole(nearest.clone()),
8129 Quadrant::Whole(nearest),
8130 Quadrant::Whole(newmv),
8131 ];
8132 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
8133
8134 let (count, results) = decode_inter_sb(&data, 16, 16, false);
8135 // Three NEARESTMV blocks at 9 symbols each, one NEWMV block at
8136 // partition + skip + is_inter + 3 single_ref + new_mv + mv_joint +
8137 // (sign, class, class0_bit, class0_fr for the one nonzero component)
8138 // = 12, plus the superblock's partition_w64.
8139 assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count");
8140 let (skip, is_inter, mode, mv) = results[3];
8141 assert!(skip);
8142 assert!(is_inter);
8143 assert_eq!(mode, None);
8144 assert_eq!(
8145 mv,
8146 (0, 2),
8147 "the decoded motion vector must be exactly what was written"
8148 );
8149 }
8150
8151 /// Decodes only the first 32x32 block's mode symbol of a superblock: the
8152 /// tile's own first block always reads partition, skip and is_inter at
8153 /// context zero, so this needs none of [`decode_inter_sb`]'s neighbour
8154 /// bookkeeping — which matters here because the mutation this feeds
8155 /// desyncs everything after the one symbol it is testing, and a decoder
8156 /// that kept reading past it would be asserting on garbage.
8157 fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize {
8158 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
8159 let mut cdfs = Cdfs::new(2);
8160 dec.symbol(&mut cdfs.partition_w64[0]);
8161 dec.symbol(&mut cdfs.partition_w32[0]);
8162 dec.symbol(&mut cdfs.skip[0]);
8163 dec.symbol(&mut cdfs.intra_inter[0]);
8164 if wrong_y_mode {
8165 dec.symbol(&mut cdfs.kf_y_mode[0][0])
8166 } else {
8167 dec.symbol(&mut cdfs.y_mode[3])
8168 }
8169 }
8170
8171 /// An inter frame's intra block reads its mode against `Y_MODE`'s size
8172 /// group, not `KF_Y_MODE`'s neighbour-context table a key frame's block
8173 /// reads. Reading the wrong table back — `KF_Y_MODE`'s `(0, 0)` row —
8174 /// decodes a different mode than the one [`sb_coeff_inter_frame_tile`]
8175 /// wrote, because the two tables carry different default probabilities
8176 /// even though a row of each is the same fourteen-entry width. (The swap
8177 /// this test's name warns of does not typecheck as a one-line
8178 /// substitution at the write site either — `cdfs.kf_y_mode[3]` is a
8179 /// `[[u16; 14]; 5]` row, not the single `[u16; 14]` `Y_MODE` indexing
8180 /// needs — so a mutation that got the *outer* shape wrong would be
8181 /// caught by `cargo check` before it ever reached a test; this test is
8182 /// what catches getting the *right* leaf shape from the *wrong* table.)
8183 #[test]
8184 fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() {
8185 let block = BlockCoeffs {
8186 mode: H_PRED as u8,
8187 skip: true,
8188 ..BlockCoeffs::default()
8189 };
8190 let blocks = vec![Quadrant::Whole(block); 4];
8191 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
8192
8193 assert_eq!(
8194 decode_first_block_mode(&data, false),
8195 H_PRED,
8196 "the right table reads the mode back exactly"
8197 );
8198 assert_ne!(
8199 decode_first_block_mode(&data, true),
8200 H_PRED,
8201 "KF_Y_MODE's different probabilities must decode a different mode"
8202 );
8203 }
8204}