forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs2503 lines, 103.1 KiBHistoryRawDownload
1//! Tile payload writer (spec 5.11), for the one block coding the encoder can
2//! produce today: a key frame whose every superblock is a single 64x64
3//! DC-predicted block with no residual.
4//!
5//! That frame decodes to a flat mid-grey picture — every sample is the value a
6//! DC prediction with no neighbours produces — which is what makes it a usable
7//! gate: any desync between this writer and a real decoder shows up as a
8//! decode failure or a sample that is not mid-grey, with no metric in the way.
9//! It is the skeleton the block modes, transform sizes and coefficients hang
10//! off as they arrive.
11
12use std::cell::RefCell;
13#[cfg(test)]
14use std::collections::BTreeMap;
15use std::sync::LazyLock;
16use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
17
18use ec_core::{Error, Result};
19
20use crate::cdf;
21use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
22use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
23use crate::msac::SymbolEncoder;
24use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};
25use crate::transform::TxType;
26
27// ---------------------------------------------------------------------------
28// lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder
29// reads ONE `cdef_idx` literal per 64x64 superblock, at that superblock's
30// first non-skip block, and only when the frame header's `cdef_bits > 0`
31// (`crate::decode::maybe_read_cdef_idx`). The writers below mirror that from
32// a plan the filter search hands over, kept in a thread-local rather than
33// threaded through every `write_*` signature -- the same shape the decoder's
34// own `FrameCtx::cdef_transmitted` uses, and the encoder codes one tile at a
35// time on one thread. The plan is CONSUMED by the tile writer that runs next
36// ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame
37// that arms nothing writes no literals.
38
39// ---------------------------------------------------------------------------
40// lane-av1lr: per-restoration-unit loop restoration syntax (spec 5.11.57,
41// `read_lr`), armed by the encoder's restoration search the same way
42// [`arm_cdef_idx`] arms the CDEF indices. LUMA ONLY and Wiener only: the
43// frame header this encoder writes sets `FrameRestorationType[0] = WIENER`
44// and leaves both chroma planes at `RESTORE_NONE`, so a unit codes one
45// `restore_wiener` symbol and, when it takes the filter, its two directions
46// against the running per-tile reference (`crate::restoration::
47// write_wiener_filter`, the exact inverse of the reader's own
48// `read_wiener_filter`).
49
50/// One frame's per-unit restoration plan (see [`arm_lr`]).
51struct LrPlan {
52 /// `LoopRestorationSize[0]`, in luma samples.
53 unit_size: u32,
54 /// `horz_units`/`vert_units` for the luma plane.
55 horz_units: u32,
56 vert_units: u32,
57 /// One entry per unit, `rcol + rrow * horz_units`: the filter it takes,
58 /// or `None` for `RESTORE_NONE`.
59 units: Vec<Option<crate::restoration::WienerInfo>>,
60 /// `ref_wiener_info`: the running reference the taps are coded against,
61 /// reset to the midpoint filter at the start of each tile (this writer
62 /// codes one tile per frame).
63 reference: crate::restoration::WienerInfo,
64}
65
66thread_local! {
67 static LR_PLAN: std::cell::RefCell<Option<LrPlan>> = const { std::cell::RefCell::new(None) };
68}
69
70/// Arms the next tile write with one Wiener decision per luma restoration
71/// unit. An empty `units` disarms (the frame codes no restoration at all).
72pub(crate) fn arm_lr(
73 unit_size: u32,
74 horz_units: u32,
75 vert_units: u32,
76 units: Vec<Option<crate::restoration::WienerInfo>>,
77) {
78 LR_PLAN.with(|c| {
79 *c.borrow_mut() = (!units.is_empty()).then(|| LrPlan {
80 unit_size,
81 horz_units,
82 vert_units,
83 units,
84 reference: crate::restoration::WienerInfo::default(),
85 });
86 });
87}
88
89// ---------------------------------------------------------------------------
90// lane-sb128: the sequence's `use_128x128_superblock`. Armed per tile write
91// like [`arm_lr`] (the encoder codes one tile at a time per thread) rather
92// than threaded through every writer signature. When set, the two tile
93// writers walk 128x128 superblocks -- loop restoration and one
94// `partition_w128` symbol at the 128 root, then the four 64x64 quadrants in
95// libaom `decode_partition`'s own TL, TR, BL, BR order -- which is exactly
96// what `crate::decode::read_sb128_root` reads.
97
98thread_local! {
99 static SB128: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
100}
101
102/// Arms the next tile write with the sequence's 128x128 superblock size.
103pub(crate) fn arm_sb128(on: bool) {
104 SB128.with(|c| c.set(on));
105}
106
107/// How many 128x128 superblock roots the writers have coded since the last
108/// [`take_sb128_root_hits`] -- a gate reports how often the root fires rather
109/// than assuming it does (class `gate-blind-to-feature`). Process-global
110/// rather than thread-local because the tiles of one frame are written on
111/// worker threads.
112static SB128_ROOT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
113
114/// The 128x128-root count since the last call, and zero it.
115pub fn take_sb128_root_hits() -> usize {
116 SB128_ROOT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
117}
118
119/// Whether the next tile write codes 128x128 superblocks ([`arm_sb128`]).
120fn sb128_armed() -> bool {
121 SB128.with(std::cell::Cell::get)
122}
123
124/// The order a tile's 64x64 superblock cells are written in, mirroring
125/// `crate::decode::sb_visit_order` exactly: plain raster at a 64 superblock,
126/// and TL/TR/BL/BR inside each 128x128 superblock (in raster order over the
127/// 128 grid) at a 128 one. The two flags mark the first cell of a superblock
128/// ROW (where the left neighbour context resets) and the first cell of a
129/// superblock (where the 128 root's own restoration units and partition
130/// symbol are written).
131fn sb_write_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
132 let mut out = Vec::new();
133 if !sb128 {
134 for r in r0..r1 {
135 for c in c0..c1 {
136 out.push((r, c, c == c0, true));
137 }
138 }
139 return out;
140 }
141 let mut r = r0;
142 while r < r1 {
143 let mut first_in_row = true;
144 let mut c = c0;
145 while c < c1 {
146 let mut first_in_sb = true;
147 for qr in 0..2 {
148 for qc in 0..2 {
149 let (rr, cc) = (r + qr, c + qc);
150 if rr >= r1 || cc >= c1 {
151 continue;
152 }
153 out.push((rr, cc, first_in_row, first_in_sb));
154 first_in_row = false;
155 first_in_sb = false;
156 }
157 }
158 c += 2;
159 }
160 r += 2;
161 }
162 out
163}
164
165/// The 128x128 superblock root ([`sb_write_order`]'s `sb_start` cells): the
166/// units its own 128-sample span covers, then the partition symbol. Only
167/// `PARTITION_SPLIT` is written -- the four 64x64 quadrants below are today's
168/// superblocks -- and at a root the true frame edge cuts, the DECIDING
169/// gathered bit the decoder reads instead (`read_sb128_root`).
170// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
171#[allow(clippy::too_many_arguments)]
172fn write_sb128_root(
173 enc: &mut SymbolEncoder,
174 cdfs: &mut Cdfs,
175 neighbours: &Neighbours,
176 sb_r: u32,
177 sb_c: u32,
178 mi_cols: u32,
179 mi_rows: u32,
180 // lane-b128: the partition the root's own search chose --
181 // `PARTITION_SPLIT` (the four 64x64 quadrants below, which is every root
182 // this writer coded before) or `PARTITION_NONE` (one 128x128 block,
183 // written by the caller right after this). Only offered at a root wholly
184 // inside the frame, so the gathered edge arms below still code SPLIT.
185 part: usize,
186) {
187 SB128_ROOT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
188 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
189 write_lr(enc, cdfs, mi_r128, mi_c128, SB_MI * 2);
190 let at128 = ((mi_r128 / 4) as usize, (mi_c128 / 4) as usize);
191 let ctx128 = neighbours.partition_ctx(at128, 128);
192 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
193 if crate::envflags::env_flag!("EC_AV1_TRACE") {
194 eprintln!("WTRACE partition_w128 ctx={ctx128} cols={has_cols128} rows={has_rows128}");
195 }
196 match (has_cols128, has_rows128) {
197 (true, true) => enc.symbol(part, &mut cdfs.partition_w128[ctx128]),
198 // As at the 64 root: the gathered CDF is built for the read and
199 // thrown away, so nothing adapts here. Value 1 is SPLIT.
200 (true, false) => enc.symbol_fixed(
201 1,
202 &crate::decode::gather_of(&cdfs.partition_w128[ctx128], &crate::decode::VERT_ALIKE128),
203 ),
204 (false, true) => enc.symbol_fixed(
205 1,
206 &crate::decode::gather_of(&cdfs.partition_w128[ctx128], &crate::decode::HORZ_ALIKE128),
207 ),
208 // Both halves outside: the split is the only partition left and the
209 // decoder reads nothing.
210 (false, false) => {}
211 }
212}
213
214/// lane-b128: one 128x128 inter block at a `PARTITION_NONE` 128 superblock
215/// root -- the syntax `decode_inter_block` reads for `sb128_none` (decode.rs
216/// ~35110): `skip`, `is_inter`, the reference/mode chain at the block's own
217/// 32x32-mi window, the motion mode, and the transform syntax, with the mi
218/// grid and every neighbour band published over all thirty-two mi cells.
219///
220/// lane-b128r: a block that carries a RESIDUAL codes it as the four 64x64 mu
221/// chunks libaom's `decode_token_recon_block` walks -- per chunk one
222/// TX_64X64 luma unit (its coded 32x32 corner, `TxbSet::Luma64`, DCT-only at
223/// this size) then one TX_32X32 unit per chroma plane on the offset-10
224/// `txb_skip` rows, each publishing its own coefficient context before the
225/// next unit reads it. Its transform syntax is the var-tx tree's four
226/// depth-0 `txfm_partition` symbols, one per chunk. The levels arrive packed
227/// per plane into a 64-wide grid, chunk (cr, cc) at (cr * 32, cc * 32)
228/// ([`crate::encode::search_root_128`]). A skipped block writes no
229/// `cdef_idx` and no `delta_q`, exactly as the 64 root's skip arm does.
230///
231/// # Errors
232/// A block that is intra, that is compound with a residual, or whose var-tx
233/// depth is not 0, at this size.
234#[allow(clippy::too_many_arguments)]
235fn write_inter_block_128(
236 enc: &mut SymbolEncoder,
237 cdfs: &mut Cdfs,
238 neighbours: &mut Neighbours,
239 grid: &mut MiGrid,
240 // The root's top-left position in [`SUB`] (16x16) units.
241 sb_at: (usize, usize),
242 block: &BlockCoeffs,
243 mi_cols: u32,
244 mi_rows: u32,
245 tx_select: bool,
246) -> Result<()> {
247 /// The block's side in samples and in 4x4 mode-info units.
248 const SIDE: usize = 128;
249 const SIDE_MI: usize = SIDE / MI;
250 /// The four 64x64 "mu" chunks, in the order libaom's
251 /// `decode_token_recon_block` walks them (raster).
252 const CHUNKS: [(usize, usize); 4] = [(0, 0), (0, 1), (1, 0), (1, 1)];
253 let info = block.inter.ok_or_else(|| {
254 Error::unsupported("AV1 tile", "a 128x128 superblock root block is coded inter")
255 })?;
256 if !block.skip && block.tx_depth != 0 {
257 return Err(Error::unsupported(
258 "AV1 tile",
259 "a 128x128 superblock root block splits its var-tx tree below TX_64X64",
260 ));
261 }
262 let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
263 let has_above = neighbours.has_above(mi_r);
264 let has_left = neighbours.has_left(mi_c);
265 let skip_ctx =
266 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
267 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
268 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
269 write_delta_q(enc, cdfs, (mi_r, mi_c), true, block.skip);
270 let ii_ctx = intra_inter_ctx(
271 has_above,
272 has_left,
273 neighbours.above_inter[mi_c],
274 neighbours.left_inter[mi_r],
275 );
276 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
277 write_comp_mode(
278 enc,
279 cdfs,
280 neighbours,
281 (mi_r, mi_c),
282 (has_above, has_left),
283 info.ref1.is_some(),
284 );
285 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
286 write_compound_block(
287 enc,
288 cdfs,
289 neighbours,
290 grid,
291 (mi_r, mi_c),
292 (SIDE_MI, SIDE_MI),
293 (has_above, has_left),
294 info,
295 (mi_cols as usize, mi_rows as usize),
296 )?
297 } else {
298 write_single_ref(
299 enc,
300 cdfs,
301 info.ref_frame,
302 neighbours.above_ref[mi_c],
303 neighbours.above_ref1[mi_c],
304 neighbours.left_ref[mi_r],
305 neighbours.left_ref1[mi_r],
306 );
307 let stack = find_mv_stack(
308 grid,
309 mi_r,
310 mi_c,
311 SIDE_MI,
312 SIDE_MI,
313 info.ref_frame,
314 mi_cols as usize,
315 mi_rows as usize,
316 );
317 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
318 (mv, (0, 0), is_new_mv)
319 };
320 for dr in 0..SIDE_MI {
321 for dc in 0..SIDE_MI {
322 grid.set(
323 mi_r + dr,
324 mi_c + dc,
325 MiInfo {
326 is_inter: true,
327 ref_frame: info.ref_frame,
328 ref_frame1: info.ref1.unwrap_or(NO_REF1),
329 mv1: mv16(mv1),
330 mv: mv16(mv),
331 is_new_mv,
332 size: SIDE_MI as u8,
333 size_h: SIDE_MI as u8,
334 is_global_mv0: false,
335 is_global_mv1: false,
336 },
337 );
338 }
339 }
340 if info.ref1.is_none() {
341 write_motion_mode(
342 enc,
343 cdfs,
344 grid,
345 (mi_r, mi_c),
346 (SIDE_MI, SIDE_MI),
347 (SIDE, SIDE),
348 (mi_cols as usize, mi_rows as usize),
349 info.ref_frame,
350 block.motion_mode,
351 )?;
352 }
353 if tx_select {
354 if block.skip {
355 write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SIDE, true, true, 0);
356 } else {
357 // The var-tx tree of a 128x128 block enters at TX_64X64 once per
358 // mu chunk (`read_block_tx_size`'s `max_tx = side.min(64)` loop),
359 // so it is four depth-0 `txfm_split` flags of zero, each read
360 // against the bands the chunks before it published.
361 for (cr, cc) in CHUNKS {
362 let unit = (mi_r + cr * 16, mi_c + cc * 16);
363 let ctx = txfm_partition_ctx_rect(
364 neighbours.above_txfm[unit.1],
365 neighbours.left_txfm[unit.0],
366 SIDE,
367 64,
368 64,
369 );
370 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
371 neighbours.record_txfm(unit, 64, 64, 64);
372 }
373 }
374 }
375 let zero_grids = [
376 vec![0i32; TX32 * TX32],
377 vec![0i32; TX32 * TX32],
378 vec![0i32; TX32 * TX32],
379 ];
380 if !block.skip {
381 // The packed 64-wide level grids the search hands over, one plane
382 // each (see this function's doc).
383 let packed = [
384 level_grid(&block.luma, 64)?,
385 level_grid(&block.u, 64)?,
386 level_grid(&block.v, 64)?,
387 ];
388 let scan32 = default_scan(TX32);
389 let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec<i32> {
390 (0..32)
391 .flat_map(|row| packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec())
392 .collect()
393 };
394 let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
395 for (cr, cc) in CHUNKS {
396 let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
397 // The luma unit: its own `txb_skip_ctx` is the neighbour
398 // magnitude table (the unit is smaller than its block), and it
399 // publishes its context before the next chunk reads it.
400 let luma = unit_of(0, cr, cc);
401 let skip_ctx = neighbours.luma_skip_ctx(unit_mi, 64 / MI);
402 let around = neighbours.around_mi(unit_mi, 64);
403 write_coeffs(
404 enc,
405 &mut cdfs.txb(TxbSet::Luma64, 0),
406 &luma,
407 &scan32,
408 skip_ctx,
409 dc_sign_ctx(around[0].dc_vote),
410 Some(0),
411 TxType::DctDct,
412 );
413 neighbours.record_mi_luma(unit_mi, 64, &luma);
414 // Then this chunk's chroma pair, before the next chunk's luma:
415 // libaom codes every plane of a mu chunk before moving on. The
416 // chroma `txb_skip_ctx` takes `get_txb_ctx`'s offset-10 rows
417 // (+3 here) because the uv plane block is bigger than the unit.
418 // lane-av1-128rectspan: SQUARE per-axis geometry -- one TX_32X32
419 // per 64x64 mu chunk, stamped at span 64 on BOTH axes. That is
420 // 4:2:0/4:4:4 only: at 4:2:2 the chunk's chroma plane block is
421 // 32x64 (two stacked units) with a (64, 32) luma footprint per
422 // unit, so `unit_mi`, the `64`-spans and the whole `CHUNKS`
423 // raster need the same per-axis treatment before 4:2:2 could be
424 // written here. This is a PORT note, not a live defect, because
425 // nothing feeds this writer 4:2:2: every non-test `ColorConfig`
426 // the encoder names is (1,1), pinned by arm 2 of
427 // `the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_
428 // else_reaches_it`. lane-av1422lift lifted the decoder's
429 // sequence-header refusal, so the reason this is not live is the
430 // writer's 4:2:0-only source, not a refusal.
431 let mut pair = [Vec::new(), Vec::new()];
432 for plane in 1..3usize {
433 let grid = unit_of(plane, cr, cc);
434 let around = neighbours.around_mi(unit_mi, 64)[plane];
435 write_coeffs(
436 enc,
437 &mut cdfs.txb(TxbSet::Chroma32, 0),
438 &grid,
439 &scan32,
440 usize::from(around.above_coded) + usize::from(around.left_coded) + 3,
441 dc_sign_ctx(around.dc_vote),
442 Some(plane),
443 TxType::DctDct,
444 );
445 neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
446 pair[plane - 1] = grid;
447 }
448 chroma_units.push((unit_mi, pair));
449 }
450 // decode.rs' own tail (`record_split_luma_rect_mi` then the
451 // `mu_chroma_units` re-stamp): the block-level write off the WHOLE
452 // assembled chroma plane grid, luma kept because each unit already
453 // published its own, and then the per-unit chroma writes replayed
454 // over it -- last writer wins, so the next block reads the units.
455 let block_grids = [
456 vec![0i32; TX32 * TX32],
457 packed[1].clone(),
458 packed[2].clone(),
459 ];
460 neighbours.record_planes(sb_at, SIDE, 0, &block_grids, false);
461 for (unit_mi, pair) in &chroma_units {
462 neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
463 neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
464 }
465 } else {
466 neighbours.record(sb_at, SIDE, 0, &zero_grids);
467 }
468 neighbours.record_inter(sb_at, SIDE, block.skip, true, block_ref(block));
469 record_block_compound(neighbours, (mi_r, mi_c), SIDE, block);
470 SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
471 if !block.skip {
472 SB128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
473 }
474 if info.ref1.is_some() {
475 SB128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
476 }
477 Ok(())
478}
479
480/// lane-b128hv: one 128x64 (HORZ) or 64x128 (VERT) inter block, the two
481/// halves a `PARTITION_HORZ`/`PARTITION_VERT` 128 superblock root carries --
482/// the syntax `decode_inter_block` reads for `sb128_rect` (decode.rs ~35343):
483/// the same chain [`write_inter_block_128`] writes, at the block's own
484/// rectangular window. Every CDF/context decision is taken at the enclosing
485/// square `side` of 128 (what the decoder's `inter_piece!` passes), and the
486/// block's true footprint governs only its mv-stack window, its mi/grid stamp
487/// and its neighbour bands (decode.rs' own `write_w`/`write_h` split).
488///
489/// lane-ab128: also the two 64x64 squares an AB shape codes (the `w == h`
490/// arm below) and its 128x64 / 64x128 half.
491///
492/// lane-rectres: a piece may CARRY A RESIDUAL -- the search only ever hands
493/// one over under `EC_AV1_RECTRES` ([`crate::encode::rectres`]), and then it
494/// is coded here exactly as `decode_inter_block` reads it: one TX_64X64 luma
495/// unit plus a TX_32X32 chroma pair per 64x64 mu chunk (two chunks for a
496/// half, one for a square), each depth-0 in the var-tx tree (a half codes
497/// two `txfm_partition` flags under `TxMode::Select`, a square one).
498///
499/// # Errors
500/// A block that is intra.
501#[allow(clippy::too_many_arguments)]
502fn write_inter_block_128_rect(
503 enc: &mut SymbolEncoder,
504 cdfs: &mut Cdfs,
505 neighbours: &mut Neighbours,
506 grid: &mut MiGrid,
507 // The half's own top-left position in mode-info (4x4) units.
508 at_mi: (usize, usize),
509 // Its true footprint in samples: (128, 64) at HORZ, (64, 128) at VERT.
510 (w, h): (usize, usize),
511 block: &BlockCoeffs,
512 mi_cols: u32,
513 mi_rows: u32,
514 tx_select: bool,
515) -> Result<()> {
516 let info = block.inter.ok_or_else(|| {
517 Error::unsupported("AV1 tile", "a 128-root rectangular half is coded inter")
518 })?;
519 let (mi_r, mi_c) = at_mi;
520 let (w_mi, h_mi) = (w / MI, h / MI);
521 let has_above = neighbours.has_above(mi_r);
522 let has_left = neighbours.has_left(mi_c);
523 let skip_ctx =
524 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
525 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
526 write_cdef_idx(enc, (mi_r, mi_c), block.skip);
527 // NOT a whole superblock: decode.rs' `whole_sb` is `write_w == write_h ==
528 // sb_px`, so a rect half reads its `delta_q` group even when skipped.
529 write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
530 let ii_ctx = intra_inter_ctx(
531 has_above,
532 has_left,
533 neighbours.above_inter[mi_c],
534 neighbours.left_inter[mi_r],
535 );
536 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
537 write_comp_mode(
538 enc,
539 cdfs,
540 neighbours,
541 (mi_r, mi_c),
542 (has_above, has_left),
543 info.ref1.is_some(),
544 );
545 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
546 write_compound_block(
547 enc,
548 cdfs,
549 neighbours,
550 grid,
551 (mi_r, mi_c),
552 (w_mi, h_mi),
553 (has_above, has_left),
554 info,
555 (mi_cols as usize, mi_rows as usize),
556 )?
557 } else {
558 write_single_ref(
559 enc,
560 cdfs,
561 info.ref_frame,
562 neighbours.above_ref[mi_c],
563 neighbours.above_ref1[mi_c],
564 neighbours.left_ref[mi_r],
565 neighbours.left_ref1[mi_r],
566 );
567 let stack = find_mv_stack(
568 grid,
569 mi_r,
570 mi_c,
571 w_mi,
572 h_mi,
573 info.ref_frame,
574 mi_cols as usize,
575 mi_rows as usize,
576 );
577 let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
578 (mv, (0, 0), is_new_mv)
579 };
580 for dr in 0..h_mi {
581 for dc in 0..w_mi {
582 grid.set(
583 mi_r + dr,
584 mi_c + dc,
585 MiInfo {
586 is_inter: true,
587 ref_frame: info.ref_frame,
588 ref_frame1: info.ref1.unwrap_or(NO_REF1),
589 mv1: mv16(mv1),
590 mv: mv16(mv),
591 is_new_mv,
592 size: w_mi as u8,
593 size_h: h_mi as u8,
594 is_global_mv0: false,
595 is_global_mv1: false,
596 },
597 );
598 }
599 }
600 if info.ref1.is_none() {
601 write_motion_mode(
602 enc,
603 cdfs,
604 grid,
605 (mi_r, mi_c),
606 (w_mi, h_mi),
607 (w, h),
608 (mi_cols as usize, mi_rows as usize),
609 info.ref_frame,
610 block.motion_mode,
611 )?;
612 }
613 // The 64x64 mu chunks the residual is coded in, raster order -- the
614 // decoder's own walk: two for a half, one for a square piece.
615 let chunks: &[(usize, usize)] = match (w, h) {
616 (128, 64) => &[(0, 0), (0, 1)],
617 (64, 128) => &[(0, 0), (1, 0)],
618 _ => &[(0, 0)],
619 };
620 // A half's uv plane block (64x32 / 32x64) is wider or taller than its
621 // 32x32 unit, so the unit's `txb_skip_ctx` takes `get_txb_ctx`'s
622 // offset-10 rows (+3 here); a 64x64 piece's uv block IS the unit and
623 // takes none. The half is also the only shape whose chroma is re-stamped
624 // per mu chunk at the end (decode.rs' `mu_chroma`).
625 let is_half = w.max(h) > 64;
626 if tx_select {
627 if block.skip {
628 // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect`
629 // with the BLOCK's own size in both bands, no symbol.
630 neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h));
631 } else if is_half {
632 // The var-tx tree of a 128x64 / 64x128 block enters at TX_64X64
633 // once per mu chunk (`read_block_tx_size_rect`'s `max_tx = 64`
634 // loop), so it is two depth-0 `txfm_split` flags of zero, each
635 // read against the bands the chunks before it published.
636 for &(cr, cc) in chunks {
637 let unit = (mi_r + cr * 16, mi_c + cc * 16);
638 let ctx = txfm_partition_ctx_rect(
639 neighbours.above_txfm[unit.1],
640 neighbours.left_txfm[unit.0],
641 w.max(h),
642 64,
643 64,
644 );
645 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
646 neighbours.record_txfm(unit, 64, 64, 64);
647 }
648 } else {
649 // A 64x64 piece is one whole TX_64X64: the single depth-0 flag
650 // the 64 root's own writer codes (`write_tx_syntax_inter`).
651 write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SB, true, false, 0);
652 }
653 }
654 let zero_grids = [
655 vec![0i32; TX32 * TX32],
656 vec![0i32; TX32 * TX32],
657 vec![0i32; TX32 * TX32],
658 ];
659 // A 128 root's half is always SUB (16 px) aligned, so the coarse mode /
660 // side bands are named by the same SUB-grid origin every square block
661 // uses.
662 let at_sub = (mi_r / (SUB / MI), mi_c / (SUB / MI));
663 if !block.skip {
664 // lane-rectres: the packed 64-wide level grids the search hands over,
665 // one plane each (the same layout `write_inter_block_128` slices for
666 // the whole block, here with the piece's own chunk list).
667 let packed = [
668 level_grid(&block.luma, 64)?,
669 level_grid(&block.u, 64)?,
670 level_grid(&block.v, 64)?,
671 ];
672 let scan32 = default_scan(TX32);
673 let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec<i32> {
674 (0..32)
675 .flat_map(|row| packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec())
676 .collect()
677 };
678 let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
679 for &(cr, cc) in chunks {
680 let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
681 // The luma unit, and the context its all-zero flag reads: a
682 // HALF's unit is smaller than its block (neighbour magnitude
683 // table), a square's IS the whole plane block (fixed zero --
684 // `read_inter_plane`'s `luma_skip_ctx.unwrap_or(0)`, the 64
685 // root's own writer rule). It publishes its context before the
686 // next chunk reads it.
687 let luma = unit_of(0, cr, cc);
688 let skip_ctx = if is_half {
689 neighbours.luma_skip_ctx(unit_mi, 64 / MI)
690 } else {
691 0
692 };
693 let around = neighbours.around_mi(unit_mi, 64);
694 write_coeffs(
695 enc,
696 &mut cdfs.txb(TxbSet::Luma64, 0),
697 &luma,
698 &scan32,
699 skip_ctx,
700 dc_sign_ctx(around[0].dc_vote),
701 Some(0),
702 TxType::DctDct,
703 );
704 neighbours.record_mi_luma(unit_mi, 64, &luma);
705 // Then this chunk's chroma pair, before the next chunk's luma:
706 // libaom codes every plane of a mu chunk before moving on.
707 let mut pair = [Vec::new(), Vec::new()];
708 for plane in 1..3usize {
709 let grid = unit_of(plane, cr, cc);
710 let around = neighbours.around_mi(unit_mi, 64)[plane];
711 write_coeffs(
712 enc,
713 &mut cdfs.txb(TxbSet::Chroma32, 0),
714 &grid,
715 &scan32,
716 usize::from(around.above_coded)
717 + usize::from(around.left_coded)
718 + 3 * usize::from(is_half),
719 dc_sign_ctx(around.dc_vote),
720 Some(plane),
721 TxType::DctDct,
722 );
723 neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
724 pair[plane - 1] = grid;
725 }
726 chroma_units.push((unit_mi, pair));
727 }
728 // decode.rs' own tail (`record_split_luma_rect_mi` then, on a half,
729 // the per-chunk chroma re-stamp): the block-level write off the
730 // whole assembled chroma plane grid, luma kept because each unit
731 // already published its own, and then the per-unit chroma writes
732 // replayed over it -- last writer wins, so the next block reads the
733 // units.
734 let block_grids = [
735 vec![0i32; TX32 * TX32],
736 packed[1].clone(),
737 packed[2].clone(),
738 ];
739 neighbours.record_planes_rect(at_sub, (w, h), 0, &block_grids, false);
740 if is_half {
741 for (unit_mi, pair) in &chroma_units {
742 neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
743 neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
744 }
745 }
746 SB128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
747 } else {
748 neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
749 }
750 neighbours.record_inter_rect_mi((mi_r, mi_c), (w, h), block.skip, true, block_ref(block));
751 if let Some(r1) = info.ref1 {
752 neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1);
753 }
754 // lane-ab128: an AB shape codes its two 64x64 pieces through this same
755 // function, and they are neither a 128x64 nor a 64x128 half -- the
756 // witness reads these two counters for the HORZ/VERT shape alone.
757 if w > h {
758 SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
759 } else if h > w {
760 SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
761 }
762 Ok(())
763}
764
765/// lane-b128hv: how many 128x64 / 64x128 halves the inter writer has coded
766/// since the last [`take_sb128_horz_hits`] / [`take_sb128_vert_hits`] (class
767/// `gate-blind-to-feature`).
768static SB128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
769/// The VERT twin of [`SB128_HORZ_HITS`].
770static SB128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
771
772/// The 128x64-half count since the last call, and zero it.
773pub fn take_sb128_horz_hits() -> usize {
774 SB128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
775}
776
777/// The 64x128-half count since the last call, and zero it.
778pub fn take_sb128_vert_hits() -> usize {
779 SB128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
780}
781
782/// lane-ab128: how many AB-shape roots the inter writer has coded since the
783/// last [`take_sb128_ab_hits`], in `PARTITION_HORZ_A` .. `_VERT_B` order
784/// (class `gate-blind-to-feature`).
785static SB128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
786 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
787
788/// The four per-shape AB-root counts since the last call, and zero them.
789pub fn take_sb128_ab_hits() -> [usize; 4] {
790 std::array::from_fn(|i| SB128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
791}
792
793/// lane-b128r: how many of those blocks carried a REAL residual (four
794/// TX_64X64 luma units plus their per-chunk chroma pair) rather than being
795/// skipped, since the last [`take_sb128_residual_hits`].
796static SB128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
797
798/// The 128x128-with-residual count since the last call, and zero it.
799pub fn take_sb128_residual_hits() -> usize {
800 SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
801}
802/// lane-rectres: how many RECT/AB pieces (the halves and 64x64 squares
803/// [`write_inter_block_128_rect`] codes) carried a REAL residual rather than
804/// being skipped, since the last [`take_sb128_rectres_hits`] -- the writer
805/// side of [`crate::encode::take_b128_rectres_hits`]'s search count.
806static SB128_RECTRES_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
807
808/// The rect/AB-piece-with-residual count since the last call, and zero it.
809pub fn take_sb128_rectres_hits() -> usize {
810 SB128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
811}
812
813/// lane-b128r: how many of those blocks named a SECOND reference (the
814/// compound arm at the 128 root), since the last
815/// [`take_sb128_compound_hits`].
816static SB128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
817
818/// The compound-128 count since the last call, and zero it.
819pub fn take_sb128_compound_hits() -> usize {
820 SB128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
821}
822
823/// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since
824/// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).
825static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
826
827/// The 128x128-block count since the last call, and zero it.
828pub fn take_sb128_none_hits() -> usize {
829 SB128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
830}
831
832/// `read_lr`'s write side, called once at the top of every superblock,
833/// before its partition symbol: writes the units this superblock's own
834/// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
835/// column scaling is the plain mi one).
836fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32, span: u32) {
837 LR_PLAN.with(|c| {
838 let mut plan = c.borrow_mut();
839 let Some(plan) = plan.as_mut() else { return };
840 let unit = plan.unit_size;
841 let rcol0 = (mi_col * 4).div_ceil(unit);
842 let rcol1 = ((mi_col + span) * 4).div_ceil(unit).min(plan.horz_units);
843 let rrow0 = (mi_row * 4).div_ceil(unit);
844 let rrow1 = ((mi_row + span) * 4).div_ceil(unit).min(plan.vert_units);
845 for rrow in rrow0..rrow1 {
846 for rcol in rcol0..rcol1 {
847 let info = plan.units[(rcol + rrow * plan.horz_units) as usize];
848 enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener);
849 if let Some(info) = info {
850 crate::restoration::write_wiener_filter(enc, false, &mut plan.reference, &info);
851 }
852 }
853 }
854 });
855}
856
857/// A 64x64 superblock's width in 4x4 mode-info units (`SB_MI` in
858/// `crate::decode`), the span [`write_lr`] resolves its units over.
859const SB_MI_W: u32 = 16;
860
861/// One tile's own superblock and mode-info span (spec 5.11.1's tile loop
862/// bounds): `MiColStarts[i]..MiColStarts[i+1]` and the same down the rows,
863/// with the superblock indices those mi bounds fall on. The writers walk
864/// exactly this rect, and everything a block reads outside it -- the
865/// neighbour bands, the MV grid -- is left at the "unavailable" state a
866/// tile's own first row and column see, which is how the decoder clips them
867/// (`MiGrid::set_tile_bounds`, `PlaneBuf::set_tile_origin`).
868#[derive(Clone, Copy, Debug, PartialEq, Eq)]
869pub(crate) struct TileRect {
870 pub(crate) sb_col0: u32,
871 pub(crate) sb_col1: u32,
872 pub(crate) sb_row0: u32,
873 pub(crate) sb_row1: u32,
874 pub(crate) mi_col0: u32,
875 pub(crate) mi_col1: u32,
876 pub(crate) mi_row0: u32,
877 pub(crate) mi_row1: u32,
878}
879
880impl TileRect {
881 /// The whole frame as one tile -- what every single-tile caller writes.
882 pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self {
883 let (cols, rows) = block_grid(mi_cols, mi_rows);
884 Self {
885 sb_col0: 0,
886 sb_col1: cols.div_ceil(2),
887 sb_row0: 0,
888 sb_row1: rows.div_ceil(2),
889 mi_col0: 0,
890 mi_col1: mi_cols,
891 mi_row0: 0,
892 mi_row1: mi_rows,
893 }
894 }
895}
896
897/// A frame's uniform tile grid (spec 5.9.15's `uniform_tile_spacing_flag`
898/// arm, mirrored from `ec_av1_syntax::frame::read_tile_info` so that what
899/// this encoder writes and what a decoder derives from the same two log2
900/// fields are the same rects). 64x64 superblocks only, which is the only
901/// size this encoder's sequence header signals.
902#[derive(Clone, Debug)]
903pub(crate) struct TileLayout {
904 pub(crate) cols_log2: u32,
905 pub(crate) rows_log2: u32,
906 /// Tile column starts in superblocks, `cols + 1` entries.
907 col_starts_sb: Vec<u32>,
908 /// Tile row starts in superblocks, `rows + 1` entries.
909 row_starts_sb: Vec<u32>,
910 mi_cols: u32,
911 mi_rows: u32,
912}
913
914impl TileLayout {
915 /// The layout `cols_log2`/`rows_log2` name for this frame's mi grid.
916 pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self {
917 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
918 let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2));
919 // lane-sb128: a tile boundary is a SUPERBLOCK boundary, so under a
920 // 128 superblock the starts are laid out on the 128 grid and then
921 // doubled back into the 64-cell units the writers walk.
922 let unit = u32::from(crate::encode::sb128_on()) + 1;
923 let starts = |total: u32, log2: u32| {
924 let total128 = total.div_ceil(unit);
925 let step = total128.div_ceil(1 << log2).max(1);
926 let mut v: Vec<u32> = (0..total128)
927 .step_by(step as usize)
928 .map(|s| s * unit)
929 .collect();
930 v.push(total);
931 v
932 };
933 Self {
934 cols_log2,
935 rows_log2,
936 col_starts_sb: starts(sb_cols, cols_log2),
937 row_starts_sb: starts(sb_rows, rows_log2),
938 mi_cols,
939 mi_rows,
940 }
941 }
942
943 pub(crate) fn cols(&self) -> u32 {
944 self.col_starts_sb.len() as u32 - 1
945 }
946
947 pub(crate) fn rows(&self) -> u32 {
948 self.row_starts_sb.len() as u32 - 1
949 }
950
951 pub(crate) fn count(&self) -> usize {
952 (self.cols() * self.rows()) as usize
953 }
954
955 /// `MiColStarts`/`MiRowStarts` as the frame header carries them.
956 pub(crate) fn mi_col_starts(&self) -> Vec<u32> {
957 let mut v: Vec<u32> = self.col_starts_sb[..self.cols() as usize]
958 .iter()
959 .map(|sb| sb * SB_MI_W)
960 .collect();
961 v.push(self.mi_cols);
962 v
963 }
964
965 pub(crate) fn mi_row_starts(&self) -> Vec<u32> {
966 let mut v: Vec<u32> = self.row_starts_sb[..self.rows() as usize]
967 .iter()
968 .map(|sb| sb * SB_MI_W)
969 .collect();
970 v.push(self.mi_rows);
971 v
972 }
973
974 /// Tile `index` (row major, `TileNum`) as a rect.
975 pub(crate) fn rect(&self, index: usize) -> TileRect {
976 let (r, c) = (index / self.cols() as usize, index % self.cols() as usize);
977 let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]);
978 let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]);
979 TileRect {
980 sb_col0,
981 sb_col1,
982 sb_row0,
983 sb_row1,
984 mi_col0: sb_col0 * SB_MI_W,
985 mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols),
986 mi_row0: sb_row0 * SB_MI_W,
987 mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows),
988 }
989 }
990
991 /// The largest tile by mi area, `context_update_tile_id`'s own rule
992 /// (spec 6.8.14 leaves the choice to the encoder; libaom and rav1e both
993 /// name the biggest tile, whose end-of-tile tables the frame stores).
994 pub(crate) fn largest_tile(&self) -> usize {
995 (0..self.count())
996 .max_by_key(|&i| {
997 let t = self.rect(i);
998 ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64)
999 })
1000 .unwrap_or(0)
1001 }
1002}
1003
1004/// lane-edge128: which 64x64 CDEF unit's `cdef_idx` literal covers each unit
1005/// of this frame, in the same raster order [`arm_cdef_idx`]'s grid is in.
1006///
1007/// `read_cdef` (spec 5.11.56) codes ONE literal for the block that first
1008/// reaches a unit and copies it over every unit that block SPANS, so a whole
1009/// 128x128 root block puts one literal in the stream for all four of its
1010/// units -- the encoder's CDEF search, which prices a preset per unit, may
1011/// not hand those four units different presets: only the first would be
1012/// coded, and every decoder (ours and ffmpeg's alike) would apply it to all
1013/// four while the encoder's own filter replay applied four different ones.
1014/// That is the shape this map exists to collapse
1015/// ([`crate::filter_search::pick_filters`]).
1016///
1017/// lane-rectres: the same holds for a Rect128 half or an Ab128 half that
1018/// carries a residual (`EC_AV1_RECTRES`) -- it codes one literal at its own
1019/// origin and the decoder stamps BOTH units it spans with it, so its pair is
1020/// collapsed onto the origin unit too. Its 64x64 squares cover exactly one
1021/// unit each, and a SKIP-ONLY rect/AB piece codes no literal at all (the
1022/// decoder's per-piece `cdef_transmitted` reset never fires), so neither
1023/// touches this map -- only pieces the writer really codes a residual for.
1024pub(crate) fn cdef_unit_owner(blocks: &[Quadrant], mi_cols: u32, mi_rows: u32) -> Vec<u32> {
1025 let (cols, rows) = block_grid(mi_cols, mi_rows);
1026 let (sb_cols, sb_rows) = (cols.div_ceil(2) as usize, rows.div_ceil(2) as usize);
1027 let mut owner: Vec<u32> = (0..(sb_cols * sb_rows) as u32).collect();
1028 // Collapses every 64x64 unit `(ur, uc) ..` a residual piece at unit
1029 // `(ur, uc)` with footprint `(w, h)` spans onto the piece's origin --
1030 // [`crate::encode::write_inter_block_128_rect`]'s one `write_cdef_idx`
1031 // is what the decoder copies over all of them.
1032 let collapse = |owner: &mut Vec<u32>, (ur, uc): (usize, usize), (w, h): (usize, usize)| {
1033 let origin = (ur * sb_cols + uc) as u32;
1034 for r in ur..(ur + (h / 64).max(1)).min(sb_rows) {
1035 for c in uc..(uc + (w / 64).max(1)).min(sb_cols) {
1036 owner[r * sb_cols + c] = origin;
1037 }
1038 }
1039 };
1040 for sb_r in (0..sb_rows).step_by(2) {
1041 for sb_c in (0..sb_cols).step_by(2) {
1042 let Some(root) = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize)
1043 .then(|| &blocks[(sb_r * 2) * cols as usize + sb_c * 2])
1044 else {
1045 continue;
1046 };
1047 match root {
1048 Quadrant::Whole128(_) => {
1049 let origin = (sb_r * sb_cols + sb_c) as u32;
1050 for r in sb_r..(sb_r + 2).min(sb_rows) {
1051 for c in sb_c..(sb_c + 2).min(sb_cols) {
1052 owner[r * sb_cols + c] = origin;
1053 }
1054 }
1055 }
1056 // lane-rectres: the two halves of a HORZ/VERT root sit in
1057 // different unit rows (HORZ) / columns (VERT); each
1058 // non-skip half collapses its own pair.
1059 Quadrant::Rect128(horz, halves) => {
1060 for (i, half) in halves.iter().enumerate() {
1061 if half.skip {
1062 continue;
1063 }
1064 let (ur, uc) = if *horz {
1065 (sb_r + i, sb_c)
1066 } else {
1067 (sb_r, sb_c + i)
1068 };
1069 let (w, h) = if *horz { (128, 64) } else { (64, 128) };
1070 collapse(&mut owner, (ur, uc), (w, h));
1071 }
1072 }
1073 // lane-rectres: the AB half is the only multi-unit piece
1074 // (its two squares are one unit each); only a non-skip one
1075 // codes a literal, so only it fires.
1076 Quadrant::Ab128(symbol, pieces) => {
1077 for (piece, ((mi_r, mi_c), (w, h))) in pieces
1078 .iter()
1079 .zip(crate::encode::ab128_pieces(usize::from(*symbol), (0, 0)))
1080 {
1081 if piece.skip {
1082 continue;
1083 }
1084 let (ur, uc) = (sb_r + mi_r / 16, sb_c + mi_c / 16);
1085 collapse(&mut owner, (ur, uc), (w, h));
1086 }
1087 }
1088 _ => {}
1089 }
1090 }
1091 }
1092 owner
1093}
1094
1095/// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]).
1096struct CdefIdxPlan {
1097 /// The header's `cdef_bits`; never 0 while armed.
1098 bits: u8,
1099 /// Superblocks per row, the stride of `grid`.
1100 sb_cols: usize,
1101 /// One index per 64x64 superblock, in raster order.
1102 grid: Vec<u8>,
1103 /// The superblock whose literal was already written -- the decoder's
1104 /// `cdef_transmitted`, which resets at every superblock and which coding
1105 /// order (each superblock's blocks are contiguous) makes a single slot.
1106 last: Option<usize>,
1107}
1108
1109thread_local! {
1110 static CDEF_IDX: std::cell::RefCell<Option<CdefIdxPlan>> =
1111 const { std::cell::RefCell::new(None) };
1112}
1113
1114/// Arms the next tile write with one `cdef_idx` per 64x64 superblock.
1115/// `bits == 0` disarms (the header codes a single strength pair, so the tile
1116/// carries no literal at all).
1117pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) {
1118 CDEF_IDX.with(|c| {
1119 *c.borrow_mut() = (bits > 0).then_some(CdefIdxPlan {
1120 bits,
1121 sb_cols,
1122 grid,
1123 last: None,
1124 });
1125 });
1126}
1127
1128/// One frame's per-superblock quantizer plan (lane-deltaq, see
1129/// [`arm_delta_q`]): the writer side of decode.rs `maybe_read_delta_q`.
1130struct DeltaQPlan {
1131 /// `1 << delta_q_res`, the multiplier the coded symbol is scaled by --
1132 /// every `grid` entry is congruent to `base` modulo it, so the delta the
1133 /// writer codes is always a whole number of steps.
1134 res: i32,
1135 /// Superblocks per row, the stride of `grid`.
1136 sb_cols: usize,
1137 /// The absolute `qindex` each 64x64 superblock is coded at, raster order.
1138 grid: Vec<u8>,
1139 /// The spec's `CurrentQIndex`, carried across the superblocks of THIS
1140 /// tile -- armed at the frame's `base_q_idx` because a tile writer is
1141 /// armed once per tile (`encode_inter_frame`'s `code_tiles`), which is
1142 /// exactly the spec's own per-tile reset.
1143 cur: i32,
1144}
1145
1146thread_local! {
1147 static DELTA_Q: std::cell::RefCell<Option<DeltaQPlan>> =
1148 const { std::cell::RefCell::new(None) };
1149}
1150
1151/// Arms the next tile write with one absolute `qindex` per 64x64 superblock.
1152/// Disarmed (a plain no-op writer, byte for byte what this crate wrote before
1153/// lane-deltaq) when `res == 0`.
1154pub(crate) fn arm_delta_q(res: i32, sb_cols: usize, grid: Vec<u8>, base: u8) {
1155 DELTA_Q.with(|c| {
1156 *c.borrow_mut() = (res > 0).then(|| DeltaQPlan {
1157 res,
1158 sb_cols,
1159 grid,
1160 cur: i32::from(base),
1161 });
1162 });
1163}
1164
1165thread_local! {
1166 static SIGN_BIAS: std::cell::Cell<crate::mvstack::SignBiasTable> =
1167 const { std::cell::Cell::new(crate::mvstack::NO_SIGN_BIAS) };
1168}
1169
1170/// Arms the next tile write with this frame's `ref_frame_sign_bias` (spec
1171/// 5.9.2), the table its MV-stack scans run under. Armed the same way
1172/// [`arm_cdef_idx`]/[`arm_lr`] are -- and disarmed by the same guard -- so
1173/// that a frame with a backward reference needs no new parameter on the four
1174/// nested writer helpers between here and `find_mv_stack`. A frame that never
1175/// names a future reference leaves this alone: all-`false` is what every
1176/// stream this crate wrote before pyramids existed codes under.
1177pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
1178 SIGN_BIAS.with(|c| c.set(sign_bias));
1179}
1180
1181thread_local! {
1182 static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1183}
1184
1185/// Arms the next tile write with this frame's `allow_screen_content_tools`
1186/// (spec 5.9.2), which is what makes every intra block carry the
1187/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46
1188/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/
1189/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that
1190/// never detected screen content writes exactly the stream it wrote before
1191/// this lane.
1192pub(crate) fn arm_screen(on: bool) {
1193 SCREEN.with(|c| c.set(on));
1194}
1195
1196thread_local! {
1197 /// This frame's `(mi_rows, mi_cols)` (spec `compute_image_size`), armed
1198 /// beside [`SCREEN`] by both frame encoders: a palette block cut by the
1199 /// frame's right/bottom mi edge codes its colour-index map over the
1200 /// ON-SCREEN part only, so the writer needs the same dims the decoder's
1201 /// `palette_onscreen` reads off its `FrameCtx` (lane-palw). `(0, 0)`
1202 /// -- an unarmed writer, i.e. a unit test coding one block -- clamps
1203 /// nothing, which is what every stream without a cut palette block codes.
1204 static FRAME_MI_DIMS: std::cell::Cell<(usize, usize)> =
1205 const { std::cell::Cell::new((0, 0)) };
1206}
1207
1208/// Arms the next tile write with this frame's `(mi_rows, mi_cols)`.
1209pub(crate) fn arm_frame_mi_dims(dims: (usize, usize)) {
1210 FRAME_MI_DIMS.with(|c| c.set(dims));
1211}
1212
1213/// The armed `(mi_rows, mi_cols)`, or a grid big enough to clamp nothing.
1214fn frame_mi_dims() -> (usize, usize) {
1215 match FRAME_MI_DIMS.with(std::cell::Cell::get) {
1216 (0, 0) => (usize::MAX / 8, usize::MAX / 8),
1217 dims => dims,
1218 }
1219}
1220
1221fn screen_armed() -> bool {
1222 SCREEN.with(std::cell::Cell::get)
1223}
1224
1225thread_local! {
1226 /// This frame header's `allow_intrabc` (spec 5.9.2), armed exactly like
1227 /// [`SCREEN`]: with it every intra block of the tile carries a
1228 /// `use_intrabc` symbol right after `skip`/`cdef`/`delta_q` (decode.rs
1229 /// `read_intra_mode`), so a tile written without it and read with it
1230 /// desyncs at the first block.
1231 static INTRABC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1232 /// The mi grid the DV predictor is built off (decode.rs
1233 /// `INTRABC_MI_GRID`/`record_intrabc_mi`): every coded block publishes
1234 /// its own footprint into it, an intrabc one also its DV as an
1235 /// `INTRA_FRAME` candidate. `Some` only while an `allow_intrabc` tile is
1236 /// being written.
1237 static INTRABC_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1238 const { std::cell::RefCell::new(None) };
1239}
1240
1241/// Arms the frame's `allow_intrabc` bit for the next tile written on this
1242/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
1243pub(crate) fn arm_intrabc(on: bool) {
1244 INTRABC.with(|c| c.set(on));
1245}
1246
1247fn intrabc_armed() -> bool {
1248 INTRABC.with(std::cell::Cell::get)
1249}
1250
1251thread_local! {
1252 /// This SEQUENCE header's `enable_filter_intra` (spec 5.5.2), armed
1253 /// exactly like [`SCREEN`]: with it every DC_PRED intra block of at most
1254 /// 32x32 that took no luma palette carries a `use_filter_intra` symbol
1255 /// after the palette colours and before the colour-index maps (decode.rs
1256 /// `read_intra_mode`), so a tile written without it and read with it
1257 /// desyncs at the first such block.
1258 static FILTER_INTRA: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1259}
1260
1261/// Arms the sequence's `enable_filter_intra` bit for the next tile written on
1262/// this thread; cleared by [`CdefIdxGuard`] when that writer returns.
1263pub(crate) fn arm_filter_intra(on: bool) {
1264 FILTER_INTRA.with(|c| c.set(on));
1265}
1266
1267fn filter_intra_armed() -> bool {
1268 FILTER_INTRA.with(std::cell::Cell::get)
1269}
1270
1271/// How many blocks this writer coded `use_filter_intra == 1`, and the
1272/// histogram of the five `filter_intra_mode`s (index 1..=5) -- the fire count
1273/// a gate prints so that "filter intra is on" is a measurement rather than a
1274/// claim (class `gate-blind-to-feature`). Index 0 is the block count.
1275static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] =
1276 [const { std::sync::atomic::AtomicUsize::new(0) }; 6];
1277
1278/// Reads [`FILTER_INTRA_HITS`] and zeroes it, so a gate can attribute the
1279/// counts to its own encode.
1280#[cfg(test)]
1281pub(crate) fn take_filter_intra_hits() -> [usize; 6] {
1282 std::array::from_fn(|i| FILTER_INTRA_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1283}
1284
1285/// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for
1286/// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every
1287/// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <=
1288/// 32, [`crate::decode::filter_intra_size_class`]) and that took no luma
1289/// palette (`av1_filter_intra_allowed`, reconintra.h:77), then the chosen mode
1290/// of five. Sits between the palette COLOUR lists and the colour-index maps,
1291/// where libaom reads it (`av1_visit_palette` runs after
1292/// `read_filter_intra_mode_info`).
1293fn write_filter_intra(
1294 enc: &mut SymbolEncoder,
1295 cdfs: &mut Cdfs,
1296 mode: usize,
1297 side: usize,
1298 has_palette_y: bool,
1299 filter_intra: Option<u8>,
1300) {
1301 if !filter_intra_armed() || mode != DC_PRED || has_palette_y {
1302 debug_assert!(
1303 filter_intra.is_none(),
1304 "no `use_filter_intra` symbol exists here"
1305 );
1306 return;
1307 }
1308 let Some(class) = crate::decode::filter_intra_size_class(side) else {
1309 debug_assert!(
1310 filter_intra.is_none(),
1311 "past av1_filter_intra_allowed_bsize"
1312 );
1313 return;
1314 };
1315 enc.symbol(
1316 usize::from(filter_intra.is_some()),
1317 &mut cdfs.filter_intra[class],
1318 );
1319 if let Some(fi) = filter_intra {
1320 enc.symbol(usize::from(fi), &mut cdfs.filter_intra_mode);
1321 FILTER_INTRA_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1322 FILTER_INTRA_HITS[usize::from(fi) + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1323 }
1324}
1325
1326/// The coefficient-table row a block's luma transform types are coded from:
1327/// `fimode_to_intradir[filter_intra_mode]` for a filter-intra block, its own
1328/// luma mode otherwise (class `filter-intra tx_type row`, decode.rs
1329/// [`crate::decode::fi_tx_row`]). The block still PUBLISHES `DC_PRED` as its
1330/// neighbour mode -- libaom's `mbmi->mode` is unchanged by filter intra.
1331fn tx_row(mode: usize, filter_intra: Option<u8>) -> usize {
1332 crate::decode::fi_tx_row(mode, filter_intra.map(usize::from))
1333}
1334
1335/// How many blocks this writer coded `use_intrabc == 1`, and the histogram of
1336/// their DV magnitudes in full pels (index 1..=6 = 1, 2, 4, 8, 16, 32 pels
1337/// and up, by the larger component) -- the fire count a gate prints so that
1338/// "intrabc is on" is a measurement rather than a claim (class
1339/// `gate-blind-to-feature`). Index 0 is the block count.
1340static INTRABC_HITS: [std::sync::atomic::AtomicUsize; 7] =
1341 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1342
1343fn note_intrabc(dv: (i32, i32)) {
1344 INTRABC_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1345 let px = (dv.0.abs() / 8).max(dv.1.abs() / 8).max(1) as usize;
1346 let bucket = (usize::BITS - px.leading_zeros()) as usize;
1347 INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1348}
1349
1350/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts
1351/// to its own encode.
1352#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1353pub(crate) fn take_intrabc_hits() -> [usize; 7] {
1354 std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1355}
1356
1357thread_local! {
1358 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
1359 /// the same way `arm_sign_bias` arms the sign-bias table rather than
1360 /// threaded through the five nested writer helpers between here and the
1361 /// per-block mode syntax. `true` makes every inter block of size at least
1362 /// 8x8 code a `comp_mode` symbol, exactly where decode.rs `read_comp_mode`
1363 /// reads one.
1364 static REFERENCE_SELECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1365}
1366
1367/// Arms the frame's `reference_select` bit for the next tile written on this
1368/// thread; cleared by [`CdefIdxGuard`] when that writer returns.
1369pub(crate) fn arm_reference_select(on: bool) {
1370 REFERENCE_SELECT.with(|c| c.set(on));
1371}
1372
1373thread_local! {
1374 /// This frame header's own `is_motion_mode_switchable` bit (spec 5.9.2),
1375 /// armed exactly like [`REFERENCE_SELECT`]. `true` makes every
1376 /// single-reference inter block that libaom's `motion_mode_allowed`
1377 /// accepts carry a `motion_mode`/`obmc` symbol right after its MV syntax,
1378 /// exactly where decode.rs' `read_motion_mode` reads one.
1379 static MOTION_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1380}
1381
1382thread_local! {
1383 /// This frame header's own `allow_warped_motion` bit (spec 5.9.2): with
1384 /// it set, every block libaom's `motion_mode_allowed` accepts AND that
1385 /// has at least one warp sample (`num_proj_ref >= 1`) reads the 3-symbol
1386 /// `motion_mode_cdf` alphabet instead of the 2-symbol `obmc_cdf` one.
1387 /// lane-av1obmc2.
1388 static WARPED_MOTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1389 /// The frame geometry the warp-sample walk needs (`num_proj_ref` ->
1390 /// `has_top_right`), which is only ever this writer's own superblock
1391 /// size. Every stream this crate writes uses a 64 superblock, which is
1392 /// `FrameCtx::new`'s default.
1393 /// corner-cut: ceiling is a 128-superblock WRITER -- it must arm the real
1394 /// frame context here (or take one as a parameter) or the warp-sample
1395 /// walk reads the wrong `has_top_right` geometry.
1396 static WRITER_FCTX: crate::decode::FrameCtx = crate::decode::FrameCtx::new();
1397}
1398
1399/// Arms [`WARPED_MOTION`] for the next tile written on this thread.
1400pub(crate) fn arm_warped_motion(on: bool) {
1401 WARPED_MOTION.with(|c| c.set(on));
1402}
1403
1404/// Arms the frame's `is_motion_mode_switchable` bit for the next tile written
1405/// on this thread; cleared by [`CdefIdxGuard`] when that writer returns.
1406pub(crate) fn arm_motion_mode(on: bool) {
1407 MOTION_MODE.with(|c| c.set(on));
1408}
1409
1410/// How many single-reference inter blocks this writer coded a `motion_mode`
1411/// symbol for, split by the value it coded and by the block's own footprint
1412/// -- the histogram a gate prints so that "OBMC is on" is a measurement, not
1413/// a claim (class `gate-blind-to-feature`). Index: `0 + 2 * bucket` for
1414/// SIMPLE, `1 + 2 * bucket` for OBMC, bucket 0/1/2 = 32x32/16x16/8x8.
1415static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] =
1416 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
1417
1418/// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the
1419/// counts to its own encode.
1420#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1421pub(crate) fn take_motion_mode_hits() -> [usize; 9] {
1422 std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1423}
1424
1425/// What the 3-symbol `motion_mode` symbol costs, in bits, against the same
1426/// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off --
1427/// which alphabet a block reads is `motion_mode_allowed`'s own choice
1428/// ([`write_motion_mode`]).
1429pub(crate) fn motion_mode_symbol_bits(row: usize, motion: u8) -> f64 {
1430 PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
1431 Some(s) => crate::encode::symbol_bits(&s.0.motion_mode[row], usize::from(motion)),
1432 None => crate::encode::symbol_bits(&crate::cdf::MOTION_MODE[row], usize::from(motion)),
1433 })
1434}
1435
1436/// What the `motion_mode`/`obmc` symbol costs, in bits, against the tables
1437/// this frame's writer really starts from ([`arm_pricing_cdfs`]) -- the same
1438/// tables the coefficients are priced off since lane-av1price2, rather than
1439/// the static defaults the symbol used to be estimated with. Falls back to
1440/// the default table whenever the search is armed with the defaults (a key
1441/// frame, or a screen frame the gate turned off).
1442pub(crate) fn obmc_symbol_bits(row: usize, obmc: bool) -> f64 {
1443 PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
1444 Some(s) => crate::encode::symbol_bits(&s.0.obmc[row], usize::from(obmc)),
1445 None => crate::encode::symbol_bits(&crate::cdf::OBMC[row], usize::from(obmc)),
1446 })
1447}
1448
1449/// `read_motion_mode`'s write side (spec 5.11.24), called on a
1450/// single-reference inter block right after its MV syntax and before the
1451/// (never switchable here) interpolation filter -- libaom's own sequential
1452/// order in `read_inter_block_mode_info`.
1453///
1454/// Eligibility is decode.rs' own `motion_mode_eligible`, term for term, with
1455/// the terms this writer settles statically dropped: no block it codes is
1456/// `skip_mode`, interintra or a non-IDENTITY-global `GLOBALMV` one, so what
1457/// is left is the footprint floor and the overlappable-neighbour walk
1458/// ([`crate::decode::has_overlappable_neighbour`], shared with the decoder so
1459/// the two cannot drift). The frame header keeps `allow_warped_motion == 0`,
1460/// so the alphabet is always the 2-symbol `obmc_cdf`, never the 3-symbol
1461/// `motion_mode_cdf`.
1462// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1463#[allow(clippy::too_many_arguments)]
1464fn write_motion_mode(
1465 enc: &mut SymbolEncoder,
1466 cdfs: &mut Cdfs,
1467 grid: &MiGrid,
1468 (mi_row, mi_col): (usize, usize),
1469 (bw4, bh4): (usize, usize),
1470 (write_w, write_h): (usize, usize),
1471 (mi_cols, mi_rows): (usize, usize),
1472 // This block's own reference, for the warp-sample walk that picks the
1473 // alphabet (`num_proj_ref`).
1474 ref_frame: i8,
1475 // 0 SIMPLE_TRANSLATION, 1 OBMC_CAUSAL, 2 WARPED_CAUSAL -- what the
1476 // encoder's search committed for this block.
1477 motion: u8,
1478) -> Result<()> {
1479 let eligible = MOTION_MODE.with(std::cell::Cell::get)
1480 && write_w.min(write_h) >= 8
1481 && crate::decode::has_overlappable_neighbour(
1482 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows,
1483 );
1484 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
1485 let proj = WRITER_FCTX.with(|fctx| {
1486 crate::decode::num_proj_ref(
1487 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1488 )
1489 });
1490 eprintln!(
1491 "EC_MMW mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} proj={proj} warp_armed={} motion={motion}",
1492 eligible as u8,
1493 WARPED_MOTION.with(std::cell::Cell::get) as u8,
1494 );
1495 }
1496 if !eligible {
1497 // The encoder trialled an OBMC prediction for a block this writer
1498 // codes as SIMPLE_TRANSLATION: its reconstruction is not the
1499 // decoder's (class encoder-grid-drift), which is exactly what the
1500 // `EC_COMP_MISMATCH` rung exists to catch.
1501 if motion != 0 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
1502 eprintln!(
1503 "EC_COMP_MISMATCH motion_mode enc=OBMC wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
1504 );
1505 }
1506 return Ok(());
1507 }
1508 let row = crate::decode::motion_mode_cdf_row(write_w, write_h).ok_or_else(|| {
1509 Error::unsupported(
1510 "AV1 tile",
1511 format!("a {write_w}x{write_h} block has no motion_mode CDF row"),
1512 )
1513 })?;
1514 // libaom `motion_mode_allowed`: the 3-symbol `motion_mode_cdf` alphabet
1515 // exactly when `allow_warped_motion` is on and the block has at least one
1516 // warp sample. The other two vetoes libaom applies there cannot fire for
1517 // a stream this encoder writes -- it codes no scaled reference and no
1518 // inter frame with `force_integer_mv` -- and the decoder checks all three
1519 // (`decode.rs`'s `warp_eligible`), so the two sides agree term for term.
1520 let warp_alphabet = WARPED_MOTION.with(std::cell::Cell::get)
1521 && WRITER_FCTX.with(|fctx| {
1522 crate::decode::num_proj_ref(
1523 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1524 )
1525 }) >= 1;
1526 if warp_alphabet {
1527 enc.symbol(usize::from(motion), &mut cdfs.motion_mode[row]);
1528 } else {
1529 // A warp winner whose block the writer resolves to the 2-symbol
1530 // alphabet would reconstruct as SIMPLE at the decoder: the same
1531 // encoder-grid-drift rung the OBMC case above prints.
1532 if motion == 2 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
1533 eprintln!(
1534 "EC_COMP_MISMATCH motion_mode enc=WARP wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
1535 );
1536 }
1537 enc.symbol(usize::from(motion == 1), &mut cdfs.obmc[row]);
1538 }
1539 let bucket = match write_w.min(write_h) {
1540 32.. => 0,
1541 16 => 1,
1542 _ => 2,
1543 };
1544 MOTION_MODE_HITS[usize::from(motion.min(2)) + 3 * bucket]
1545 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1546 Ok(())
1547}
1548
1549/// The compound half of a block's end-of-block neighbour record: nothing for
1550/// a single-reference or intra block, and `record_compound_mi`'s overwrite of
1551/// the ALTREF default for a compound one (this writer only codes
1552/// `comp_group_idx == 0`, `compound_idx == 1`).
1553fn record_block_compound(
1554 neighbours: &mut Neighbours,
1555 at_mi: (usize, usize),
1556 side: usize,
1557 block: &BlockCoeffs,
1558) {
1559 if let Some(r1) = block.inter.and_then(|i| i.ref1) {
1560 neighbours.record_compound_mi(at_mi, side, r1, 0, 1);
1561 }
1562}
1563
1564/// decode.rs' own `is_uni_comp_ref`: a pair is `UNIDIR_COMP_REFERENCE`
1565/// exactly when both references sit on the same temporal side.
1566use crate::mvstack::is_uni_comp_ref;
1567
1568thread_local! {
1569 /// `(order_hint_bits, this frame's order hint, each reference's order
1570 /// hint)` -- what `get_comp_index_context` (decode.rs) needs to context
1571 /// the `compound_idx` symbol, armed the same way the sign-bias table is.
1572 static ORDER_HINTS: std::cell::Cell<(u32, u32, [u32; 7])> =
1573 const { std::cell::Cell::new((7, 0, [0; 7])) };
1574}
1575
1576/// Arms this frame's order hints for the next tile written on this thread.
1577pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) {
1578 ORDER_HINTS.with(|c| c.set((bits, order_hint, hints)));
1579}
1580
1581/// What [`arm_order_hints`] last armed: `(order_hint_bits, order_hint,
1582/// ref_order_hints)`, for the encoder's own per-reference distance.
1583pub(crate) fn order_hints() -> (u32, u32, [u32; 7]) {
1584 ORDER_HINTS.with(std::cell::Cell::get)
1585}
1586
1587thread_local! {
1588 /// lane-hpmv: this frame's `allow_high_precision_mv`, armed per worker
1589 /// beside [`arm_order_hints`] -- the writer's eighth-pel symbol, the
1590 /// pricer's mv bits and the motion search's finest step all read it.
1591 static HIGH_PRECISION_MV: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1592}
1593
1594/// Arms this frame's `allow_high_precision_mv` for the next tile written --
1595/// or searched -- on this thread.
1596pub(crate) fn arm_high_precision_mv(on: bool) {
1597 HIGH_PRECISION_MV.with(|c| c.set(on));
1598}
1599
1600/// What [`arm_high_precision_mv`] last armed on this thread.
1601pub(crate) fn high_precision_mv() -> bool {
1602 HIGH_PRECISION_MV.with(std::cell::Cell::get)
1603}
1604
1605/// lane-hpmv's witness counters: `[0]` counts every `mv_hp`/`mv_class0_hp`
1606/// symbol this process's writers coded (zero without
1607/// `allow_high_precision_mv`, one per non-zero mv component with it), `[1]`
1608/// counts the ones that came out ZERO -- an eighth-pel vector, i.e. one a
1609/// frame without the flag cannot name at all.
1610static HP_SYMBOLS: [std::sync::atomic::AtomicU64; 2] = [
1611 std::sync::atomic::AtomicU64::new(0),
1612 std::sync::atomic::AtomicU64::new(0),
1613];
1614
1615/// Reads and clears [`HP_SYMBOLS`]: `(hp symbols coded, eighth-pel ones)`.
1616#[allow(dead_code)] // read only from the `#[cfg(test)]` witness
1617pub(crate) fn take_hp_symbols() -> (u64, u64) {
1618 let all = HP_SYMBOLS[0].swap(0, std::sync::atomic::Ordering::Relaxed);
1619 (
1620 all,
1621 HP_SYMBOLS[1].swap(0, std::sync::atomic::Ordering::Relaxed),
1622 )
1623}
1624
1625/// [`take_hp_symbols`] without clearing -- what the NEWMV census prints.
1626pub(crate) fn hp_symbols() -> (u64, u64) {
1627 use std::sync::atomic::Ordering::Relaxed;
1628 (HP_SYMBOLS[0].load(Relaxed), HP_SYMBOLS[1].load(Relaxed))
1629}
1630
1631/// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec
1632/// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref`
1633/// trees), symbol for symbol at the same contexts -- which are, as that
1634/// function's own doc records, `single_ref_p1_ctx`..`single_ref_p6_ctx`/
1635/// `uni_comp_ref_p1_ctx` under libaom's compound names.
1636///
1637/// # Errors
1638/// A pair this writer never forms (its `ref0` is not `LAST_FRAME`).
1639fn write_compound_ref_frames(
1640 enc: &mut SymbolEncoder,
1641 cdfs: &mut Cdfs,
1642 above: Option<crate::mvstack::NeighbourRef>,
1643 left: Option<crate::mvstack::NeighbourRef>,
1644 above_ref: i8,
1645 left_ref: i8,
1646 (ref0, ref1): (i8, i8),
1647) -> Result<()> {
1648 use crate::mvstack::{
1649 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
1650 LAST3_FRAME, comp_reference_type_ctx, single_ref_p1_ctx, single_ref_p2_ctx,
1651 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
1652 uni_comp_ref_p1_ctx,
1653 };
1654 let a = (above_ref > 0).then_some(above_ref);
1655 let l = (left_ref > 0).then_some(left_ref);
1656 let a1 = above.and_then(|n| n.ref1);
1657 let l1 = left.and_then(|n| n.ref1);
1658 let unidir = is_uni_comp_ref(ref0, ref1);
1659 enc.symbol(
1660 usize::from(!unidir),
1661 &mut cdfs.comp_ref_type[comp_reference_type_ctx(above, left)],
1662 );
1663 if unidir {
1664 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
1665 enc.symbol(
1666 usize::from(both_backward),
1667 &mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0],
1668 );
1669 if both_backward {
1670 return Ok(());
1671 }
1672 if ref0 != LAST_FRAME {
1673 return Err(Error::unsupported(
1674 "AV1 tile",
1675 "a unidirectional compound pair this writer does not form",
1676 ));
1677 }
1678 let past_last2 = ref1 != LAST2_FRAME;
1679 enc.symbol(
1680 usize::from(past_last2),
1681 &mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
1682 );
1683 if past_last2 {
1684 enc.symbol(
1685 usize::from(ref1 == GOLDEN_FRAME),
1686 &mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
1687 );
1688 }
1689 return Ok(());
1690 }
1691 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
1692 enc.symbol(
1693 usize::from(far),
1694 &mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0],
1695 );
1696 if far {
1697 enc.symbol(
1698 usize::from(ref0 == GOLDEN_FRAME),
1699 &mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
1700 );
1701 } else {
1702 enc.symbol(
1703 usize::from(ref0 == LAST2_FRAME),
1704 &mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1],
1705 );
1706 }
1707 let is_altref = ref1 == ALTREF_FRAME;
1708 enc.symbol(
1709 usize::from(is_altref),
1710 &mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0],
1711 );
1712 if !is_altref {
1713 enc.symbol(
1714 usize::from(ref1 == ALTREF2_FRAME),
1715 &mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1],
1716 );
1717 }
1718 Ok(())
1719}
1720
1721/// Per-mode and per-pair fire counts of [`write_compound_block`], for the
1722/// gate's own census (gate-blind-to-feature): modes indexed by the spec's
1723/// `INTER_COMPOUND_MODES`, pairs by `ref1` (`LAST`..`ALTREF`).
1724static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1725 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1726static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =
1727 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1728
1729/// Takes and clears the compound mode histogram.
1730#[cfg(test)]
1731pub(crate) fn take_compound_mode_hits() -> [usize; 8] {
1732 std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1733}
1734
1735/// Takes and clears the compound pair histogram, indexed by the SECOND
1736/// reference (`LAST` = 0 .. `ALTREF` = 6).
1737#[cfg(test)]
1738pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
1739 std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1740}
1741
1742/// Per-SIZE fire counts of [`write_compound_block`], indexed by
1743/// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
1744/// 32x32-only tool, so the share by size is what says whether the leaf
1745/// candidates fire at all (gate-blind-to-feature).
1746static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
1747 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
1748
1749/// Takes and clears the compound size histogram.
1750#[cfg(test)]
1751pub(crate) fn take_compound_size_hits() -> [usize; 4] {
1752 std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1753}
1754
1755/// The compound mode histogram of the LEAVES alone (`bw4 <= 4`, so 16x16 and
1756/// below). The frame-wide histogram above cannot say whether a mode reaches
1757/// the leaves at all, which is exactly the question every leaf compound step
1758/// asks (gate-blind-to-feature): before lane-av1comp4 gave a leaf its second
1759/// reference search, the two half-new modes were structurally impossible
1760/// there and screen capture's leaf compound was 100% `NEAREST_NEARESTMV`.
1761static COMPOUND_LEAF_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1762 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1763
1764/// Takes and clears the leaf-only compound mode histogram.
1765#[cfg(test)]
1766pub(crate) fn take_compound_leaf_mode_hits() -> [usize; 8] {
1767 std::array::from_fn(|i| {
1768 COMPOUND_LEAF_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)
1769 })
1770}
1771
1772/// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
1773/// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
1774/// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
1775/// order. Returns the two motion vectors the decoder derives (what the MI
1776/// grid must record) and whether the mode was a `NEW*` one.
1777///
1778/// Only the modes [`InterMode::compound_index`] names are written, and
1779/// only the `comp_group_idx == 0`, `compound_idx == 1` blend (spec
1780/// `COMPOUND_AVERAGE`) -- masked compound and the distance-weighted blend are
1781/// not searched.
1782///
1783/// # Errors
1784/// As [`write_mv`], or a pair/mode this writer does not form.
1785#[allow(clippy::too_many_arguments)]
1786fn write_compound_block(
1787 enc: &mut SymbolEncoder,
1788 cdfs: &mut Cdfs,
1789 neighbours: &Neighbours,
1790 grid: &crate::mvstack::MiGrid,
1791 (mi_row, mi_col): (usize, usize),
1792 (bw4, bh4): (usize, usize),
1793 (has_above, has_left): (bool, bool),
1794 info: InterInfo,
1795 (mi_cols, mi_rows): (usize, usize),
1796) -> Result<((i32, i32), (i32, i32), bool)> {
1797 let (Some(ref1), Some(mode)) = (info.ref1, info.mode.compound_index()) else {
1798 return Err(Error::unsupported(
1799 "AV1 tile",
1800 "a compound block needs a second reference and a compound mode",
1801 ));
1802 };
1803 let above = has_above.then(|| neighbours.above_nbr(mi_col));
1804 let left = has_left.then(|| neighbours.left_nbr(mi_row));
1805 write_compound_ref_frames(
1806 enc,
1807 cdfs,
1808 above,
1809 left,
1810 neighbours.above_ref[mi_col],
1811 neighbours.left_ref[mi_row],
1812 (info.ref_frame, ref1),
1813 )?;
1814 let stack = crate::mvstack::find_mv_stack_compound(
1815 grid,
1816 mi_row,
1817 mi_col,
1818 bw4,
1819 bh4,
1820 (info.ref_frame, ref1),
1821 mi_cols,
1822 mi_rows,
1823 grid.sign_bias_table(),
1824 &[(0, 0); 7],
1825 None,
1826 );
1827 let ctx = crate::cdf::COMPOUND_MODE_CTX_MAP[stack.ref_mv_ctx >> 1][stack.new_mv_ctx.min(4)];
1828 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1829 eprintln!(
1830 "EC_WCOMP mi_row={mi_row} mi_col={mi_col} mode={mode} ref0={} ref1={ref1} ctx={ctx} new_mv_ctx={} ref_mv_ctx={} stack={}",
1831 info.ref_frame,
1832 stack.new_mv_ctx,
1833 stack.ref_mv_ctx,
1834 stack.entries.len()
1835 );
1836 }
1837 enc.symbol(mode, &mut cdfs.inter_compound_mode[ctx]);
1838 // `assign_compound_mv`'s own DRL half: `NEW_NEWMV` walks from index 0,
1839 // the two derived modes code no index at all.
1840 let mvs = match info.mode {
1841 InterMode::NearestNearestMv => stack.nearest_mv,
1842 InterMode::GlobalGlobalMv => ((0, 0), (0, 0)),
1843 InterMode::NearNearMv => {
1844 // decode.rs `assign_compound_mv`'s second DRL loop: the index
1845 // starts at 1 and the mode's own `ref_mv_idx` is `idx - 1`, so
1846 // this walk starts at 1 too and reads entry `ref_mv_idx + 1`.
1847 let idx = usize::from(info.ref_mv_idx) + 1;
1848 let mut walk = 1usize;
1849 while walk < 3 && stack.entries.len() > walk + 1 {
1850 let advance = walk < idx;
1851 enc.symbol(
1852 usize::from(advance),
1853 &mut cdfs.drl_mode[stack.drl_ctx[walk]],
1854 );
1855 if !advance {
1856 break;
1857 }
1858 walk += 1;
1859 }
1860 let near = |i: usize| {
1861 stack
1862 .entries
1863 .get(i)
1864 .map_or(stack.near_mv, |e| (e.mv0, e.mv1))
1865 };
1866 if walk != idx && near(walk) != near(idx) {
1867 note_drl_clamp(idx, walk, stack.entries.len());
1868 }
1869 near(walk)
1870 }
1871 InterMode::NearestNewMv | InterMode::NewNearestMv => {
1872 // Neither mode codes a DRL index (the decoder leaves `ref_mv_idx`
1873 // at 0): the NEAREST half is derived, the NEW half codes a
1874 // residual against stack entry 0.
1875 let base = stack
1876 .entries
1877 .first()
1878 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
1879 if matches!(info.mode, InterMode::NearestNewMv) {
1880 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
1881 (stack.nearest_mv.0, info.mv1)
1882 } else {
1883 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
1884 (info.mv, stack.nearest_mv.1)
1885 }
1886 }
1887 _ => {
1888 let idx = usize::from(info.ref_mv_idx);
1889 let mut walk = 0usize;
1890 while walk < 2 && stack.entries.len() > walk + 1 {
1891 let advance = walk < idx;
1892 enc.symbol(
1893 usize::from(advance),
1894 &mut cdfs.drl_mode[stack.drl_ctx[walk]],
1895 );
1896 if !advance {
1897 break;
1898 }
1899 walk += 1;
1900 }
1901 let nearest = |i: usize| {
1902 stack
1903 .entries
1904 .get(i)
1905 .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1))
1906 };
1907 if walk != idx && nearest(walk) != nearest(idx) {
1908 note_drl_clamp(idx, walk, stack.entries.len());
1909 }
1910 let base = nearest(walk);
1911 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
1912 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
1913 (info.mv, info.mv1)
1914 }
1915 };
1916 // spec 5.11.25's `comp_group_idx`/`compound_idx` are NOT coded: this
1917 // crate's sequence header carries `enable_masked_compound = false` and
1918 // `enable_jnt_comp = false` (encode.rs), and decode.rs reads neither
1919 // symbol under those bits -- it infers `comp_group_idx = 0`,
1920 // `compound_idx = 1` (the simple average), which is the only blend this
1921 // writer forms anyway. A lane that turns either sequence bit on has to
1922 // write the matching symbol here, at
1923 // `get_comp_group_idx_context`/`get_comp_index_context`'s contexts (which
1924 // is what `Neighbours::above_comp_group_idx`/`above_compound_idx` and the
1925 // armed order hints below are already kept for).
1926 let _ = ORDER_HINTS.with(std::cell::Cell::get);
1927 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1928 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
1929 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1930 COMPOUND_SIZE_HITS[(bw4.max(1).trailing_zeros() as usize).min(3)]
1931 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1932 if bw4 <= 4 {
1933 COMPOUND_LEAF_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1934 }
1935 if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {
1936 eprintln!(
1937 "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",
1938 info.mv, info.mv1, mvs.0, mvs.1
1939 );
1940 }
1941 // decode.rs' own `is_new_mv` for a compound block: modes 2, 3, 4, 5, 7.
1942 Ok((
1943 mvs.0,
1944 mvs.1,
1945 matches!(
1946 info.mode,
1947 InterMode::NewNewMv | InterMode::NearestNewMv | InterMode::NewNearestMv
1948 ),
1949 ))
1950}
1951
1952/// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's
1953/// `comp_mode`): on a `reference_select` frame every inter block whose size
1954/// allows compound (`is_comp_ref_allowed`, always true here -- this writer's
1955/// smallest leaf is 8x8) names SINGLE or COMPOUND, at
1956/// `mvstack::reference_mode_ctx`'s own context off the same two neighbour
1957/// bands decode.rs builds its `NeighbourRef` pair from.
1958fn write_comp_mode(
1959 enc: &mut SymbolEncoder,
1960 cdfs: &mut Cdfs,
1961 neighbours: &Neighbours,
1962 (mi_r, mi_c): (usize, usize),
1963 (has_above, has_left): (bool, bool),
1964 compound: bool,
1965) {
1966 if !REFERENCE_SELECT.with(std::cell::Cell::get) {
1967 return;
1968 }
1969 let above = has_above.then(|| neighbours.above_nbr(mi_c));
1970 let left = has_left.then(|| neighbours.left_nbr(mi_r));
1971 let ctx = crate::mvstack::reference_mode_ctx(above, left);
1972 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1973 eprintln!(
1974 "EC_WCM mi=({mi_r},{mi_c}) ctx={ctx} val={} a={:?} l={:?}",
1975 usize::from(compound),
1976 above.map(|n| (n.is_inter, n.ref0, n.ref1)),
1977 left.map(|n| (n.is_inter, n.ref0, n.ref1))
1978 );
1979 }
1980 enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]);
1981}
1982
1983/// Clears the armed plan when the tile writer that consumed it returns.
1984struct CdefIdxGuard;
1985
1986impl Drop for CdefIdxGuard {
1987 fn drop(&mut self) {
1988 CDEF_IDX.with(|c| *c.borrow_mut() = None);
1989 DELTA_Q.with(|c| *c.borrow_mut() = None);
1990 LR_PLAN.with(|c| *c.borrow_mut() = None);
1991 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
1992 SCREEN.with(|c| c.set(false));
1993 REFERENCE_SELECT.with(|c| c.set(false));
1994 MOTION_MODE.with(|c| c.set(false));
1995 INTRABC.with(|c| c.set(false));
1996 FILTER_INTRA.with(|c| c.set(false));
1997 INTRABC_GRID.with(|c| *c.borrow_mut() = None);
1998 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
1999 }
2000}
2001
2002/// `read_cdef`'s write side, called right after every block's `skip` symbol:
2003/// writes this superblock's `cdef_idx` literal the first time a non-skip
2004/// block of it is coded. `mi` is the block's own position in 4x4 mode-info
2005/// units.
2006fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) {
2007 if skip {
2008 return;
2009 }
2010 CDEF_IDX.with(|c| {
2011 let mut plan = c.borrow_mut();
2012 let Some(plan) = plan.as_mut() else { return };
2013 let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16);
2014 if plan.last == Some(sb) {
2015 return;
2016 }
2017 plan.last = Some(sb);
2018 enc.literal(
2019 u32::from(plan.grid.get(sb).copied().unwrap_or(0)),
2020 u32::from(plan.bits),
2021 );
2022 });
2023}
2024
2025/// `read_delta_qindex`'s write side (spec 5.11.10), called right after every
2026/// block's [`write_cdef_idx`] -- the spec's own `skip -> cdef -> delta_q`
2027/// order, and decode.rs `maybe_read_delta_q` is the reader this mirrors
2028/// symbol for symbol. A no-op unless this block sits at its superblock's own
2029/// top-left mode-info position, and (the one case the reader skips too) when
2030/// that block IS the whole superblock and is skipped, in which case
2031/// `CurrentQIndex` carries over unchanged on both sides.
2032fn write_delta_q(
2033 enc: &mut SymbolEncoder,
2034 cdfs: &mut Cdfs,
2035 mi: (usize, usize),
2036 is_whole_sb: bool,
2037 skip: bool,
2038) {
2039 DELTA_Q.with(|c| {
2040 let mut plan = c.borrow_mut();
2041 let Some(plan) = plan.as_mut() else { return };
2042 // lane-b128m: the delta_q unit is the SUPERBLOCK, so it is 128 wide
2043 // under `EC_AV1_SB128` -- decode.rs `maybe_read_delta_q` gates on
2044 // `sb_mi_cur`, and a writer gating on a hardcoded 64 codes three
2045 // symbol groups per 128 root the reader never reads.
2046 let sb_mi = if sb128_armed() {
2047 SB_MI as usize * 2
2048 } else {
2049 SB_MI as usize
2050 };
2051 if !mi.0.is_multiple_of(sb_mi) || !mi.1.is_multiple_of(sb_mi) {
2052 return;
2053 }
2054 if is_whole_sb && skip {
2055 return;
2056 }
2057 let sb = (mi.0 / SB_MI as usize) * plan.sb_cols + (mi.1 / SB_MI as usize);
2058 let target = i32::from(plan.grid.get(sb).copied().unwrap_or(0));
2059 // `reduced` is the spec's `delta_q_abs`/`delta_q_sign_bit` pair: the
2060 // step count, not the qindex difference.
2061 let reduced = (target - plan.cur) / plan.res;
2062 let abs = reduced.unsigned_abs() as usize;
2063 /// spec `DELTA_Q_SMALL`: the largest `delta_q_abs` symbol that is not
2064 /// an escape into the literal pair below.
2065 const DELTA_Q_SMALL: usize = 3;
2066 enc.symbol(abs.min(DELTA_Q_SMALL), &mut cdfs.delta_q);
2067 if abs >= DELTA_Q_SMALL {
2068 // libaom `write_delta_qindex`: `rem_bits = get_msb(abs - 1)`,
2069 // written one less in three bits, and the value offset by the
2070 // threshold `(1 << rem_bits) + 1` the reader adds back.
2071 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
2072 let thr = (1u32 << rem_bits) + 1;
2073 enc.literal(rem_bits - 1, 3);
2074 enc.literal(abs as u32 - thr, rem_bits);
2075 }
2076 if abs != 0 {
2077 enc.literal(u32::from(reduced < 0), 1);
2078 }
2079 plan.cur = (plan.cur + reduced * plan.res).clamp(1, 255);
2080 });
2081}
2082
2083/// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the
2084/// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK`
2085/// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the
2086/// same variable, so the two traces line up symbol for symbol. Checked once
2087/// per process, so unset (the default) costs one atomic load per call and no
2088/// allocation. Only the real tile writer below calls this -- the mode/rate
2089/// search's own trial encoders never do -- so the trace does not need the
2090/// throwaway-encoder gating a whole-encoder trace would.
2091fn ec_rng_trace(msg: impl FnOnce() -> String) {
2092 use std::sync::atomic::{AtomicU8, Ordering};
2093 static ON: AtomicU8 = AtomicU8::new(2); // 2 = unknown, 1 = on, 0 = off
2094 let on = match ON.load(Ordering::Relaxed) {
2095 2 => {
2096 let on = u8::from(std::env::var_os("EC_RNG").is_some());
2097 ON.store(on, Ordering::Relaxed);
2098 on
2099 }
2100 v => v,
2101 };
2102 if on == 1 {
2103 eprintln!("{}", msg());
2104 }
2105}
2106
2107/// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
2108const PARTITION_NONE: usize = 0;
2109/// `PARTITION_HORZ` (spec 6.10.4): the block cut into a top and a bottom half.
2110const PARTITION_HORZ: usize = 1;
2111/// `PARTITION_VERT` (spec 6.10.4): the block cut into a left and a right half.
2112const PARTITION_VERT: usize = 2;
2113/// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants.
2114const PARTITION_SPLIT: usize = 3;
2115
2116/// The partition types whose probability mass the split-or-horizontal flag of
2117/// a superblock hanging off the bottom of the frame gathers (spec 9.3,
2118/// `partition_gather_vert_alike`): the flag says split, so everything vertical
2119/// or split lands on it.
2120const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2121
2122/// The same for a superblock hanging off the right-hand edge
2123/// (`partition_gather_horz_alike`).
2124const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2125
2126/// Mode-info units across a 32x32 block.
2127pub(crate) const BLOCK_MI: u32 = SB_MI / 2;
2128
2129/// Mode-info units across a 16x16 block, the smallest this crate's key-frame
2130/// writer codes.
2131pub(crate) const SUB_MI: u32 = BLOCK_MI / 2;
2132
2133/// spec `decode_partition`'s `hasRows`/`hasCols` (5.11.4), recomputed at
2134/// whichever block size is asking: a block of `side_mi` mode-info units at mi
2135/// position `pos` may be coded unsplit (its own `PARTITION_NONE`) only when
2136/// this is true in both directions -- the frame's *true* size can put the
2137/// boundary inside a superblock, a 32x32 quadrant or (since this writer's
2138/// smallest block is 16x16) even a leaf, and each level must ask again with
2139/// its own half, not just once at the superblock.
2140pub(crate) fn has_half(pos: u32, side_mi: u32, bound: u32) -> bool {
2141 pos + side_mi / 2 < bound
2142}
2143
2144/// The number of 32x32 block columns/rows a frame whose *true* (unpadded)
2145/// size gives `mi_cols`/`mi_rows` is coded over: every block whose mi origin
2146/// (`col * BLOCK_MI`) is inside the true bound is coded, so this is a
2147/// ceiling, not the exact division a block-aligned frame would give. Shared
2148/// by the tile writer's own iteration and by [`crate::encode`]'s block/
2149/// superblock generation, which must agree with it exactly.
2150pub(crate) fn block_grid(mi_cols: u32, mi_rows: u32) -> (u32, u32) {
2151 (mi_cols.div_ceil(BLOCK_MI), mi_rows.div_ceil(BLOCK_MI))
2152}
2153/// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode.
2154const DC_PRED: usize = 0;
2155
2156/// `V_PRED` (spec 6.10.2), the first of the eight directional intra modes and
2157/// so the first mode that carries an angle delta.
2158const V_PRED: usize = 1;
2159
2160/// `H_PRED`, which predicts every row from the column to the block's left.
2161#[cfg(test)]
2162const H_PRED: usize = 2;
2163
2164/// The last directional mode, `D67_PRED`.
2165const D67_PRED: usize = 8;
2166
2167/// The number of intra modes a key frame's luma block chooses from,
2168/// `INTRA_MODES` (spec 3).
2169const INTRA_MODES: usize = 13;
2170
2171/// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts
2172/// its neighbours in when they pick the CDF for the next block's mode.
2173pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0];
2174
2175/// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
2176/// +3, so `MAX_ANGLE_DELTA` is the middle of it.
2177pub(crate) const ANGLE_DELTA_ZERO: usize = 3;
2178/// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
2179pub(crate) const SB_MI: u32 = 16;
2180
2181/// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
2182const NUM_BASE_LEVELS: i32 = 2;
2183/// Where DCT_DCT sits in the spec's `Tx_Type_Intra_Inv_Set2`, the set a 16x16
2184/// intra luma transform picks its type from.
2185const TX_TYPE_DCT_DCT_SET2: usize = 1;
2186/// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
2187/// Golomb tail takes over.
2188const COEFF_BASE_RANGE: i32 = 12;
2189/// `BR_CDF_SIZE - 1` (spec 3): the largest increment one base-range symbol
2190/// carries.
2191const BR_STEP: i32 = 3;
2192/// The largest level the base and base-range syntax carry between them.
2193/// Anything above it is written as a Golomb tail on top of this.
2194const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2195/// The largest level this writer codes. The Golomb tail is a length in unary
2196/// followed by that many bits, and the spec's decoder reads at most twenty of
2197/// each, so a level a decoder cannot read back is refused rather than written.
2198const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
2199
2200/// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s
2201/// leading index) a frame's `base_q_idx` picks its default CDFs from.
2202/// [`crate::cdf`] carries all four, one constant set per context.
2203pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
2204 match base_q_idx {
2205 0..=20 => 0,
2206 21..=60 => 1,
2207 61..=120 => 2,
2208 _ => 3,
2209 }
2210}
2211
2212/// Both writers here code whole superblocks only: a partial one forces the
2213/// partition syntax down the block tree, which they do not code yet.
2214/// The probability the CDF gives one symbol on its own.
2215fn element_prob(cdf: &[u16], element: usize) -> u16 {
2216 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2217}
2218
2219/// The two-symbol CDF a partial superblock's partition flag is coded with: the
2220/// mass of the listed partition types becomes the probability of a split, and
2221/// the rest is the one partition the frame edge still allows.
2222fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
2223 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
2224 [32768 - split, 32768, 0]
2225}
2226
2227fn check_superblocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
2228 if mi_cols == 0
2229 || mi_rows == 0
2230 || !mi_cols.is_multiple_of(SB_MI)
2231 || !mi_rows.is_multiple_of(SB_MI)
2232 {
2233 return Err(Error::unsupported(
2234 "AV1 tile",
2235 "a key frame is written only for frames that are a whole number \
2236 of 64x64 superblocks",
2237 ));
2238 }
2239 Ok(())
2240}
2241
2242/// Writes the payload of a one-tile key frame in which every superblock is a
2243/// skipped 64x64 DC-predicted block.
2244///
2245/// `mi_cols` and `mi_rows` are the frame's dimensions in 4x4 mode-info units,
2246/// as the frame header carries them.
2247///
2248/// # Errors
2249/// Returns an error when the frame is not a whole number of 64x64 superblocks:
2250/// a partial superblock forces the partition syntax down the block tree, which
2251/// this writer does not code yet.
2252pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {
2253 check_superblocks(mi_cols, mi_rows)?;
2254 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2255
2256 let mut enc = SymbolEncoder::new();
2257 for r in 0..sb_rows {
2258 for c in 0..sb_cols {
2259 // decode_partition (spec 5.11.4). Every neighbour is a 64x64 block,
2260 // whose stored partition context has a zero bit at this block
2261 // size, so the context is 0 wherever the block sits.
2262 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
2263
2264 // intra_frame_mode_info (spec 5.11.16). Segmentation, delta q,
2265 // delta lf, palette, filter intra and intrabc are all off in the
2266 // frame header, and a skipped block codes no CDEF index, so the
2267 // block is three symbols: the skip flag and the two modes.
2268 let skip_ctx = usize::from(r > 0) + usize::from(c > 0);
2269 enc.symbol_fixed(1, &cdf::SKIP[skip_ctx]);
2270 // Both neighbours are DC-predicted, and an unavailable neighbour
2271 // counts as DC too, so both mode contexts are 0.
2272 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2273 // Chroma from luma is only offered up to 32x32, so the CFL-free
2274 // table is the one a 64x64 block reads.
2275 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
2276
2277 // read_block_tx_size codes nothing while the frame's tx_mode is
2278 // TX_MODE_LARGEST, and a skipped block has no residual, so the
2279 // block ends here.
2280 }
2281 }
2282 Ok(enc.finish())
2283}
2284
2285/// Writes the payload of a one-tile key frame in which every superblock is a
2286/// 64x64 DC-predicted block carrying one luma DC coefficient of `dc_level` and
2287/// no chroma residual.
2288///
2289/// `dc_level` is a quantised level, not a sample value: the decoder multiplies
2290/// it by the frame's DC quantiser and inverse-transforms it over the whole
2291/// block, so the picture it makes is a flat grey some distance either side of
2292/// the mid-grey a zero level gives. `base_q_idx` is the frame header's, and
2293/// picks the coefficient CDFs.
2294///
2295/// # Errors
2296/// As [`dc_key_frame_tile_levels`], which this is the one-level case of.
2297pub fn dc_key_frame_tile(
2298 mi_cols: u32,
2299 mi_rows: u32,
2300 base_q_idx: u8,
2301 dc_level: i32,
2302) -> Result<Vec<u8>> {
2303 check_superblocks(mi_cols, mi_rows)?;
2304 let blocks = ((mi_cols / SB_MI) * (mi_rows / SB_MI)) as usize;
2305 dc_key_frame_tile_levels(mi_cols, mi_rows, base_q_idx, &vec![dc_level; blocks])
2306}
2307
2308/// Writes the payload of a one-tile key frame carrying one luma DC coefficient
2309/// per superblock, `levels` giving them in the raster order the superblocks are
2310/// coded in.
2311///
2312/// Each superblock decodes to a flat block of its own grey, so a frame written
2313/// here is a grid of greys the caller chooses — which is what makes the sign
2314/// context observable: a block's sign context is read off its coded neighbours,
2315/// and a frame whose levels differ in sign exercises the three-way split that a
2316/// single-sign frame cannot reach.
2317///
2318/// # Errors
2319/// Returns an error when the frame is not a whole number of 64x64 superblocks,
2320/// when `levels` does not carry exactly one level per superblock, when a level
2321/// is outside the range the base and base-range syntax carry (`-14..=14`
2322/// without zero).
2323pub fn dc_key_frame_tile_levels(
2324 mi_cols: u32,
2325 mi_rows: u32,
2326 base_q_idx: u8,
2327 levels: &[i32],
2328) -> Result<Vec<u8>> {
2329 check_superblocks(mi_cols, mi_rows)?;
2330 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2331 check_levels(levels, (sb_cols * sb_rows) as usize)?;
2332 let q_ctx = q_ctx_of(base_q_idx);
2333 let txb_skip_luma_64 = crate::cdf_state::pick(
2334 q_ctx,
2335 cdf::TXB_SKIP_LUMA_64_Q0,
2336 cdf::TXB_SKIP_LUMA_64_Q1,
2337 cdf::TXB_SKIP_LUMA_64,
2338 cdf::TXB_SKIP_LUMA_64_Q3,
2339 );
2340 let base_eob_luma_64_dc = crate::cdf_state::pick(
2341 q_ctx,
2342 cdf::COEFF_BASE_EOB_LUMA_64_Q0[0],
2343 cdf::COEFF_BASE_EOB_LUMA_64_Q1[0],
2344 cdf::COEFF_BASE_EOB_LUMA_64[0],
2345 cdf::COEFF_BASE_EOB_LUMA_64_Q3[0],
2346 );
2347 let txb_skip_chroma_32_none = crate::cdf_state::pick(
2348 q_ctx,
2349 cdf::TXB_SKIP_CHROMA_32_Q0[0],
2350 cdf::TXB_SKIP_CHROMA_32_Q1[0],
2351 cdf::TXB_SKIP_CHROMA_32[0],
2352 cdf::TXB_SKIP_CHROMA_32_Q3[0],
2353 );
2354
2355 // The sign of the DC each coded block left behind, for the two neighbours
2356 // the sign context is read from: one row of them above, and the block to
2357 // the left, which is dropped at the start of every superblock row the way a
2358 // decoder clears its left context there.
2359 let mut above: Vec<Option<bool>> = vec![None; sb_cols as usize];
2360 let mut enc = SymbolEncoder::new();
2361 for r in 0..sb_rows {
2362 let mut left: Option<bool> = None;
2363 for c in 0..sb_cols {
2364 let dc_level = levels[(r * sb_cols + c) as usize];
2365 let negative = dc_level < 0;
2366
2367 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
2368
2369 // Nothing is skipped now, so every neighbour's skip flag is 0 and
2370 // the skip context stays 0 across the frame.
2371 enc.symbol_fixed(0, &cdf::SKIP[0]);
2372 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2373 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
2374
2375 write_dc_coeffs(
2376 &mut enc,
2377 dc_level,
2378 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)),
2379 q_ctx,
2380 &txb_skip_luma_64,
2381 &base_eob_luma_64_dc,
2382 );
2383
2384 // Both chroma transform blocks are all-zero. Their planes carry no
2385 // coded coefficient anywhere in the frame, so the neighbour halves
2386 // of their context stay 0 and only the offset for a transform block
2387 // that covers its whole plane block is left: context 7.
2388 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
2389 enc.symbol_fixed(1, &txb_skip_chroma_32_none);
2390
2391 above[c as usize] = Some(negative);
2392 left = Some(negative);
2393 }
2394 }
2395 Ok(enc.finish())
2396}
2397
2398/// Writes the payload of a one-tile key frame in which every superblock is
2399/// split into four 32x32 DC-predicted blocks, each carrying one luma DC
2400/// coefficient and no chroma residual.
2401///
2402/// `levels` gives one level per 32x32 block in raster order across the frame,
2403/// so the grid is twice as wide and twice as tall as the superblock grid. The
2404/// blocks are coded in the z-order a superblock's split walks, but every
2405/// block's neighbours above and to its left are coded before it either way, so
2406/// the picture reads in raster order.
2407///
2408/// # Errors
2409/// As [`dc_key_frame_tile_levels`], with `levels` sized for the 32x32 grid.
2410pub fn split_dc_key_frame_tile(
2411 mi_cols: u32,
2412 mi_rows: u32,
2413 base_q_idx: u8,
2414 levels: &[i32],
2415) -> Result<Vec<u8>> {
2416 check_superblocks(mi_cols, mi_rows)?;
2417 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
2418 let (cols, rows) = (sb_cols * 2, sb_rows * 2);
2419 check_levels(levels, (cols * rows) as usize)?;
2420 let q_ctx = q_ctx_of(base_q_idx);
2421 let txb_skip_luma_32 = crate::cdf_state::pick(
2422 q_ctx,
2423 cdf::TXB_SKIP_LUMA_32_Q0,
2424 cdf::TXB_SKIP_LUMA_32_Q1,
2425 cdf::TXB_SKIP_LUMA_32,
2426 cdf::TXB_SKIP_LUMA_32_Q3,
2427 );
2428 let base_eob_luma_32 = crate::cdf_state::pick(
2429 q_ctx,
2430 cdf::COEFF_BASE_EOB_LUMA_32_Q0[0],
2431 cdf::COEFF_BASE_EOB_LUMA_32_Q1[0],
2432 cdf::COEFF_BASE_EOB_LUMA_32[0],
2433 cdf::COEFF_BASE_EOB_LUMA_32_Q3[0],
2434 );
2435 let txb_skip_chroma_16_0 = crate::cdf_state::pick(
2436 q_ctx,
2437 cdf::TXB_SKIP_CHROMA_16_Q0[0],
2438 cdf::TXB_SKIP_CHROMA_16_Q1[0],
2439 cdf::TXB_SKIP_CHROMA_16[0],
2440 cdf::TXB_SKIP_CHROMA_16_Q3[0],
2441 );
2442
2443 let mut above: Vec<Option<bool>> = vec![None; cols as usize];
2444 let mut left: Vec<Option<bool>> = vec![None; rows as usize];
2445
2446 let mut enc = SymbolEncoder::new();
2447 for sb_r in 0..sb_rows {
2448 // A decoder clears its left context at the start of every superblock
2449 // row, and so does the partition context the 64x64 symbol reads.
2450 left.iter_mut().for_each(|l| *l = None);
2451 for sb_c in 0..sb_cols {
2452 // The partition context of a 64x64 block reads the bit its
2453 // neighbours' block size sets at this depth: a 32x32 neighbour sets
2454 // it, and an uncoded one leaves it clear, so the context is just
2455 // which neighbours exist. The 32x32 blocks below read a bit their
2456 // own size leaves clear, so their context is 0 throughout.
2457 // Every superblock here is split, so an existing neighbour always
2458 // sets that bit.
2459 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
2460 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
2461
2462 for quadrant in 0..4 {
2463 let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
2464 let dc_level = levels[(r * cols + c) as usize];
2465 let negative = dc_level < 0;
2466
2467 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
2468 enc.symbol_fixed(0, &cdf::SKIP[0]);
2469 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
2470 // Chroma from luma is offered up to 32x32, so the block reads
2471 // the wider table even though it does not take the mode.
2472 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL[DC_PRED]);
2473
2474 write_dc_coeffs(
2475 &mut enc,
2476 dc_level,
2477 dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])),
2478 q_ctx,
2479 &txb_skip_luma_32,
2480 &base_eob_luma_32,
2481 );
2482 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
2483 enc.symbol_fixed(1, &txb_skip_chroma_16_0);
2484
2485 above[c as usize] = Some(negative);
2486 left[r as usize] = Some(negative);
2487 }
2488 }
2489 }
2490 Ok(enc.finish())
2491}
2492
2493mod syntax;
2494pub use self::syntax::*;
2495
2496
2497mod blocks;
2498pub use self::blocks::*;
2499mod leaf;
2500use self::leaf::*;
2501
2502#[cfg(test)]
2503mod tests;