forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

blocks.rs3381 lines, 141.5 KiBHistoryRawDownload
1use super::*;
2
3/// The side of a chroma palette's shared colour-index map for a square luma
4/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at
5/// the 4-px transform, NOT a plain halving (decode.rs reads the map at
6/// exactly this size).
7pub(crate) fn palette_uv_side(side: usize) -> usize {
8 (side / 2).max(4)
9}
10
11/// How many blocks took a palette, and of what size -- the fire count a gate
12/// prints so that "palette is on" is a measurement rather than a claim
13/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the
14/// per-size histogram.
15pub(super) static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
16 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
17
18/// lane-palw: colour-index maps written over the ON-SCREEN corner only,
19/// i.e. palette blocks this writer cut at the frame's right/bottom mi edge.
20/// A gate asserts it non-zero so it cannot pass on a stream that never cuts
21/// one (class `gate-blind-to-feature`).
22pub(super) static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
23
24/// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps).
25pub fn palette_cut_maps_written() -> usize {
26 PALETTE_CUT_MAPS.load(std::sync::atomic::Ordering::Relaxed)
27}
28
29/// Zeroes [`PALETTE_CUT_MAPS`] before a gate's own encode.
30pub fn reset_palette_cut_maps_written() {
31 PALETTE_CUT_MAPS.store(0, std::sync::atomic::Ordering::Relaxed);
32}
33
34pub(super) fn note_palette(n: usize) {
35 PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
36 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
37}
38
39/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can
40/// print the share of each plane's palette separately.
41pub(super) static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] =
42 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
43
44pub(super) fn note_palette_uv(n: usize) {
45 PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
46 PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
47}
48
49/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than
50/// the stream -- the half of `write_palette_colors_uv` a test cannot see from
51/// the block counts alone, and the one that desyncs the tile if this writer's
52/// cache ever disagrees with the decoder's (`gate-blind-to-feature`).
53pub(super) static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize =
54 std::sync::atomic::AtomicUsize::new(0);
55
56/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it.
57#[cfg(test)]
58pub(crate) fn take_palette_uv_cache_hits() -> usize {
59 PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
60}
61
62/// [`take_palette_hits`] for the chroma palette.
63#[cfg(test)]
64pub(crate) fn take_palette_uv_hits() -> [usize; 9] {
65 std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
66}
67
68/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
69/// its own encode.
70#[cfg(test)]
71pub(crate) fn take_palette_hits() -> [usize; 9] {
72 std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
73}
74
75/// Writes one coded block: its mode, its three transform blocks, and what it
76/// leaves behind for the blocks beside it. Its partition symbol is already
77/// written, because only the caller knows what tree led here.
78#[allow(clippy::too_many_arguments)]
79pub(super) fn write_block(
80 enc: &mut SymbolEncoder,
81 cdfs: &mut Cdfs,
82 neighbours: &mut Neighbours,
83 block: &BlockCoeffs,
84 at: (usize, usize),
85 side: usize,
86 planes: &[TxbSet; 3],
87 grids: &[Vec<i32>; 3],
88 scans: [&Vec<u16>; 3],
89 cfl: bool,
90 // The frame's `tx_mode == TxMode::Select`, and the block's own chosen
91 // depth: with it the luma residual goes through [`write_luma_select`]
92 // (one `tx_depth` symbol, then one transform unit per tile of the block)
93 // instead of the single whole-block transform below.
94 tx_select: bool,
95 all_scans: &[Vec<u16>; 4],
96) -> Result<()> {
97 let (r, c) = at;
98 let at_mi = (r * (SUB / MI), c * (SUB / MI));
99 if let Some(dv) = block.dv {
100 write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?;
101 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv));
102 return Ok(());
103 }
104 let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
105 let mode = write_intra_mode(
106 enc, cdfs, neighbours, block, above_mode, left_mode, cfl, at_mi, side,
107 );
108 // The coefficient tables read `fimode_to_intradir[filter_intra_mode]`'s
109 // row on a filter-intra block; the neighbour publication below still gets
110 // the block's own `DC_PRED` ([`tx_row`]).
111 let tx_mode = tx_row(mode, block.filter_intra);
112 let split = if tx_select {
113 let tx = write_luma_select(
114 enc,
115 cdfs,
116 neighbours,
117 at_mi,
118 side,
119 usize::from(block.tx_depth),
120 &grids[0],
121 tx_mode,
122 all_scans,
123 &block.luma_tx_types,
124 )?;
125 tx < side
126 } else {
127 false
128 };
129 write_block_planes(
130 enc,
131 cdfs,
132 planes,
133 grids,
134 &scans,
135 &neighbours.around(at, side),
136 tx_mode,
137 tx_select,
138 block_tx_type(block),
139 false,
140 );
141 neighbours.record_planes(at, side, mode, grids, !split);
142 clear_skip_band(neighbours, at_mi, side);
143 record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None);
144 Ok(())
145}
146
147/// An unskipped block's own `skip` publication: only an `allow_intrabc`
148/// frame ever sets these bands, so a frame without one leaves them exactly
149/// as they were before this lane (all false).
150pub(super) fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) {
151 if !intrabc_armed() {
152 return;
153 }
154 for cell in 0..side / MI {
155 neighbours.above_skip[mi.1 + cell] = false;
156 neighbours.left_skip[mi.0 + cell] = false;
157 }
158}
159
160/// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
161/// luma transform and 4x4 chroma transforms, coded exactly like
162/// [`write_block`] but reading its intra-mode context from the *enclosing*
163/// 16x16 slot -- `outer_at`, in [`SUB`]-grid units -- rather than from its own
164/// finer position, since [`Neighbours`]'s `above_mode`/`left_mode` arrays stay
165/// at [`SUB`] (16-sample) granularity. `leaf_mi` is this leaf's own position
166/// in 4x4 mode-info units, which is what its coefficient context (finer than
167/// [`SUB`]) is kept and read at.
168#[allow(clippy::too_many_arguments)]
169pub(super) fn write_leaf8(
170 enc: &mut SymbolEncoder,
171 cdfs: &mut Cdfs,
172 neighbours: &mut Neighbours,
173 block: &BlockCoeffs,
174 outer_at: (usize, usize),
175 leaf_mi: (usize, usize),
176 grids: &[Vec<i32>; 3],
177 scans: [&Vec<u16>; 3],
178 prev_leaf: Option<((usize, usize), usize)>,
179 tx_select: bool,
180 all_scans: &[Vec<u16>; 4],
181) -> Result<usize> {
182 let (r, c) = outer_at;
183 if let Some(dv) = block.dv {
184 write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?;
185 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv));
186 return Ok(DC_PRED);
187 }
188 let mut above_mode = neighbours.above_mode[c];
189 let mut left_mode = neighbours.left_mode[r];
190 // The previous leaf sits directly above (same column, two mi rows up)
191 // or directly to the left (same row, two mi cols over) of this one --
192 // in either case its just-written mode, not the enclosing 16x16 slot's
193 // stale neighbour, is what a decoder reads as this leaf's context.
194 if let Some(((pr, pc), pmode)) = prev_leaf {
195 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
196 above_mode = pmode;
197 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
198 left_mode = pmode;
199 }
200 }
201 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
202 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF -- like every
203 // other `write_block` caller at 16x16 and up -- not the narrower
204 // no-CFL one: r12 lane-av1-rect, this leaf's own `cfl: false` was the
205 // true first divergence (a differently-sized alphabet under the same
206 // DC_PRED decision desyncs the coder even though the decoded mode is
207 // unchanged).
208 let mode = write_intra_mode(
209 enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8,
210 );
211 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
212 // As [`write_block`]: the coefficient row follows the filter-intra mode,
213 // the mode this leaf publishes (and returns to the next leaf) does not.
214 let tx_mode = tx_row(mode, block.filter_intra);
215 let split = if tx_select {
216 let tx = write_luma_select(
217 enc,
218 cdfs,
219 neighbours,
220 leaf_mi,
221 8,
222 usize::from(block.tx_depth),
223 &grids[0],
224 tx_mode,
225 all_scans,
226 &block.luma_tx_types,
227 )?;
228 tx < 8
229 } else {
230 false
231 };
232 write_block_planes(
233 enc,
234 cdfs,
235 &planes,
236 grids,
237 &scans,
238 &neighbours.around_mi(leaf_mi, 8),
239 tx_mode,
240 tx_select,
241 block_tx_type(block),
242 false,
243 );
244 neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
245 clear_skip_band(neighbours, leaf_mi, 8);
246 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None);
247 Ok(mode)
248}
249
250/// Writes the three transform blocks of one coded block, in the order a
251/// decoder reads them.
252#[allow(clippy::too_many_arguments)]
253pub(super) fn write_block_planes(
254 enc: &mut SymbolEncoder,
255 cdfs: &mut Cdfs,
256 planes: &[TxbSet; 3],
257 grids: &[Vec<i32>; 3],
258 scans: &[&Vec<u16>; 3],
259 around: &[Around; 3],
260 mode: usize,
261 // A block whose luma was already written as several transform units
262 // ([`write_luma_select`]) has only its chroma planes left here.
263 skip_luma: bool,
264 // This block's single luma transform type (lane-txset); chroma's is
265 // derived from its mode by the decoder and codes no symbol.
266 luma_tx_type: TxType,
267 // lane-intertx: an INTER block's chroma transforms INHERIT the luma
268 // type (reduced to the chroma set against this frame's own
269 // `reduced_tx_set` bit); an intra block's comes off its UV mode and
270 // rides `DCT_DCT`'s 2D class exactly as before.
271 inter: bool,
272) {
273 // lane-intertx, desync (b): the writer used to code every chroma plane
274 // `DCT_DCT`. Chroma codes no `tx_type` symbol, but the type names the
275 // transform class, and the class picks the scan, the `eob_pt` row and
276 // the context offsets (the lane-txw note in `write_coeffs`) -- so an
277 // inherited 1-D luma type desynced the chroma exactly as luma itself
278 // once did. The reduced bit read here is the frame's own header bit,
279 // the ONE the writer's `Cdfs` is armed with (`Cdfs::reduced_tx_set`).
280 let reduced = cdfs.reduced_tx_set;
281 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
282 if plane == 0 && skip_luma {
283 continue;
284 }
285 // Luma's transform covers its whole block, which fixes the all-zero
286 // flag's context at zero; a chroma transform reads whether its
287 // neighbours coded anything, on top of the offset the chroma tables
288 // start at.
289 let skip_ctx = if plane == 0 {
290 0
291 } else {
292 usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
293 };
294 #[cfg(test)]
295 let before = enc.tell();
296 #[cfg(test)]
297 let q_ctx = cdfs.q_ctx;
298 let mut coding = cdfs.txb(planes[plane], mode);
299 let tx_type = if plane == 0 {
300 luma_tx_type
301 } else if inter {
302 crate::decode::reduce_inherited_chroma_tx_type_flagged(
303 luma_tx_type,
304 coding.side.min(32),
305 coding.side.min(32),
306 reduced,
307 )
308 } else {
309 TxType::DctDct
310 };
311 write_coeffs(
312 enc,
313 &mut coding,
314 grid,
315 scan,
316 skip_ctx,
317 dc_sign_ctx(around[plane].dc_vote),
318 Some(plane),
319 tx_type,
320 );
321 #[cfg(test)]
322 census_record(
323 planes[plane],
324 q_ctx,
325 grid,
326 f64::from(enc.tell() - before),
327 skip_ctx,
328 dc_sign_ctx(around[plane].dc_vote),
329 );
330 ec_rng_trace(|| {
331 format!(
332 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
333 grid.iter().filter(|&&l| l != 0).count(),
334 enc.tell()
335 )
336 });
337 }
338}
339
340/// The single luma transform type a block carries, `DCT_DCT` for one that
341/// never searched one (lane-txset).
342pub(super) fn block_tx_type(block: &BlockCoeffs) -> TxType {
343 block
344 .luma_tx_types
345 .first()
346 .copied()
347 .unwrap_or(TxType::DctDct)
348}
349
350/// The `(side / tx)^2` transform units of one block's luma residual, raster
351/// order, each with its own coefficient context and each published before the
352/// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch).
353/// `grid` is the block's levels in BLOCK coordinates when the transform
354/// splits, and the single transform's own coefficient grid when it does not.
355#[allow(clippy::too_many_arguments)]
356pub(super) fn write_luma_tus(
357 enc: &mut SymbolEncoder,
358 cdfs: &mut Cdfs,
359 neighbours: &mut Neighbours,
360 at_mi: (usize, usize),
361 side: usize,
362 tx: usize,
363 grid: &[i32],
364 mode: usize,
365 scans: &[Vec<u16>; 4],
366 // lane-av1tx2 r2: an INTER block's split units read the inter coefficient
367 // tables, not the intra ones (`TxbSet::Luma*Inter`).
368 inter: bool,
369 // One transform type per unit in this same raster order (lane-txset).
370 // Empty -- what every caller that never searched a type passes -- is
371 // `DCT_DCT` throughout, the one type this writer used to code.
372 tx_types: &[TxType],
373) -> Result<()> {
374 if tx < side && side > 32 && tx < 32 {
375 // A 64x64 block's own levels reach the writer as the 32x32 corner a
376 // 64-point transform codes unless the whole block was SPLIT into
377 // TX_32X32 units (lane-b64b), so any finer split has nothing to slice.
378 return Err(Error::unsupported(
379 "AV1 tile",
380 "a 64x64 block's luma transform splits no finer than TX_32X32",
381 ));
382 }
383 let coeff_side = tx.min(32);
384 let n = side / tx;
385 let set = match (tx, inter) {
386 (32, false) => TxbSet::Luma32,
387 (16, false) => TxbSet::Luma16,
388 (8, false) => TxbSet::Luma8,
389 (4, false) => TxbSet::Luma4,
390 (32, true) => TxbSet::Luma32Inter,
391 (16, true) => TxbSet::Luma16Inter,
392 (8, true) => TxbSet::Luma8Inter,
393 (4, true) => TxbSet::Luma4Inter,
394 _ => TxbSet::Luma64,
395 };
396 let scan = match coeff_side {
397 32 => &scans[0],
398 16 => &scans[1],
399 8 => &scans[2],
400 _ => &scans[3],
401 };
402 let (mi_r, mi_c) = at_mi;
403 for tu_row in 0..n {
404 for tu_col in 0..n {
405 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
406 // lane-av1straddle: libaom clips the transform loop to
407 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
408 // off the frame's true `mi_cols`/`mi_rows`), and decode.rs does
409 // the same (`tu_px >= y.true_width` there): a unit whose TOP-LEFT
410 // sample is outside the frame is NEVER coded. Writing one -- as
411 // this loop did for the phantom right-hand column of a 32x32 at
412 // x=192 in a 216-wide frame -- desyncs the tile at the very next
413 // symbol, which is what made an odd-size GOP's last block
414 // reconstruct differently and both ffmpeg decoders (libdav1d and
415 // libaom) refuse the whole key frame.
416 if tu_mi.0 >= neighbours.mi_rows || tu_mi.1 >= neighbours.mi_cols {
417 continue;
418 }
419 let unit = if n == 1 {
420 grid.to_vec()
421 } else {
422 (0..tx)
423 .flat_map(|row| grid[(tu_row * tx + row) * side + tu_col * tx..][..tx].to_vec())
424 .collect()
425 };
426 // spec `get_txb_ctx_general`: a lone transform unit covering its
427 // whole block reads context 0, a smaller one the neighbour
428 // magnitude table.
429 let skip_ctx = if n == 1 {
430 0
431 } else {
432 neighbours.luma_skip_ctx(tu_mi, tx / MI)
433 };
434 let around = neighbours.around_mi(tu_mi, tx)[0];
435 #[cfg(test)]
436 let before = enc.tell();
437 #[cfg(test)]
438 let q_ctx = cdfs.q_ctx;
439 write_coeffs(
440 enc,
441 &mut cdfs.txb(set, mode),
442 &unit,
443 scan,
444 skip_ctx,
445 dc_sign_ctx(around.dc_vote),
446 Some(0),
447 tx_types
448 .get(tu_row * n + tu_col)
449 .copied()
450 .unwrap_or(TxType::DctDct),
451 );
452 #[cfg(test)]
453 census_record(
454 set,
455 q_ctx,
456 &unit,
457 f64::from(enc.tell() - before),
458 skip_ctx,
459 dc_sign_ctx(around.dc_vote),
460 );
461 if n > 1 {
462 neighbours.record_mi_luma(tu_mi, tx, &unit);
463 }
464 }
465 }
466 Ok(())
467}
468
469/// Writes one intra block's luma residual under `TxMode::Select`: the
470/// `tx_depth` symbol (spec 5.11.16 `read_selected_tx_size`, off the size
471/// category's own CDF at [`Neighbours::tx_size_ctx`]'s row), then the
472/// `(side / tx)^2` transform units in raster order -- each predicted and
473/// coded against what the units before it already left behind, which is why
474/// every unit publishes its own coefficient context before the next one reads
475/// it (decode.rs `decode_block`'s multi-transform-unit branch).
476///
477/// `grid` is the block's levels in BLOCK coordinates (`side` by `side`) when
478/// the transform splits, and the single transform's own coefficient grid when
479/// it does not. Hands back the resolved transform side in pixels.
480#[allow(clippy::too_many_arguments)]
481pub(super) fn write_luma_select(
482 enc: &mut SymbolEncoder,
483 cdfs: &mut Cdfs,
484 neighbours: &mut Neighbours,
485 at_mi: (usize, usize),
486 side: usize,
487 depth: usize,
488 grid: &[i32],
489 mode: usize,
490 scans: &[Vec<u16>; 4],
491 tx_types: &[TxType],
492) -> Result<usize> {
493 let max_tx = side.min(64);
494 let ctx = neighbours.tx_size_ctx(at_mi, max_tx);
495 match max_tx {
496 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
497 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
498 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
499 64 => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
500 _ => {
501 return Err(Error::unsupported(
502 "AV1 tile",
503 "a tx_depth symbol is only coded at 8/16/32/64",
504 ));
505 }
506 }
507 let tx = max_tx >> depth;
508 write_luma_tus(
509 enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false, tx_types,
510 )?;
511 neighbours.record_tx(at_mi, side, tx);
512 Ok(tx)
513}
514
515/// The transform syntax one block of an INTER frame coded with
516/// `tx_mode == TxMode::Select` carries, in the place spec 5.11.16's
517/// `read_block_tx_size` reads it -- after the modes and the motion vector,
518/// before the residual:
519/// * an inter block that codes a residual walks a var-tx tree; this writer
520/// keeps it at its own largest transform, so that is one `txfm_split` flag
521/// of zero, off `txfm_partition_ctx_rect`'s row, publishing the bands per
522/// unit the way `read_var_tx_size` does.
523/// * a skipped inter block codes nothing and records its own BLOCK size
524/// (`set_txfm_ctxs`'s `skip_inter` term).
525/// * an intra block codes `tx_depth` like a key frame's, but off the
526/// `TXFM_CONTEXT` bands rather than the deblock grid.
527///
528/// Hands back the block's resolved luma transform side.
529#[allow(clippy::too_many_arguments)]
530pub(super) fn write_tx_syntax_inter(
531 enc: &mut SymbolEncoder,
532 cdfs: &mut Cdfs,
533 neighbours: &mut Neighbours,
534 at_mi: (usize, usize),
535 side: usize,
536 is_inter: bool,
537 skip: bool,
538 depth: usize,
539) -> usize {
540 let max_tx = side.min(64);
541 let (mi_r, mi_c) = at_mi;
542 if is_inter {
543 if !skip {
544 let ctx = txfm_partition_ctx_rect(
545 neighbours.above_txfm[mi_c],
546 neighbours.left_txfm[mi_r],
547 side,
548 max_tx,
549 max_tx,
550 );
551 enc.symbol(usize::from(depth != 0), &mut cdfs.txfm_partition[ctx]);
552 if depth == 0 {
553 neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx);
554 return max_tx;
555 }
556 // lane-av1tx2 r2: one halving of the var-tx tree. Each child of a
557 // split root codes its own `txfm_split` (decode.rs
558 // `read_var_tx_size` only stops symbol-free at `MAX_VARTX_DEPTH`
559 // or at a 4x4 sub-size), off the bands the children before it
560 // published -- so the context read and the update interleave per
561 // unit, exactly as the reader's recursion does.
562 let tx = max_tx / 2;
563 for row in (0..max_tx / MI).step_by(tx / MI) {
564 for col in (0..max_tx / MI).step_by(tx / MI) {
565 let unit = (mi_r + row, mi_c + col);
566 // The encoder only picks depth 1 for a block wholly
567 // inside the frame; the reader skips a unit past the true
568 // edge, which would leave the residual units unpaired.
569 debug_assert!(
570 unit.0 < neighbours.mi_rows && unit.1 < neighbours.mi_cols,
571 "a split inter transform unit past the frame edge"
572 );
573 let ctx = txfm_partition_ctx_rect(
574 neighbours.above_txfm[unit.1],
575 neighbours.left_txfm[unit.0],
576 side,
577 tx,
578 tx,
579 );
580 enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
581 neighbours.record_txfm(unit, tx, tx, tx);
582 }
583 }
584 return tx;
585 }
586 neighbours.record_txfm(at_mi, side, side, side);
587 return max_tx;
588 }
589 let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx);
590 match max_tx {
591 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
592 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
593 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
594 _ => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
595 }
596 let tx = max_tx >> depth;
597 neighbours.record_txfm(at_mi, tx, side, side);
598 tx
599}
600
601/// What a coded transform block leaves behind for the blocks that read it as a
602/// neighbour.
603pub(super) fn neighbour_state(grid: &[i32]) -> Neighbour {
604 Neighbour {
605 coded: grid.iter().any(|&l| l != 0),
606 level: grid.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8,
607 dc: (grid[0] != 0).then_some(grid[0] < 0),
608 }
609}
610
611/// Writes the payload of a one-tile key frame in which every superblock is
612/// split into 32x32 blocks, each carrying the coefficients `blocks` gives it.
613///
614/// `blocks` gives one coefficient set per 32x32 block in raster order across
615/// the frame. This is [`sb_coeff_key_frame_tile`] with every superblock split.
616///
617/// # Errors
618/// As [`sb_coeff_key_frame_tile`], with `blocks` sized for the 32x32 grid.
619pub fn split_coeff_key_frame_tile(
620 mi_cols: u32,
621 mi_rows: u32,
622 base_q_idx: u8,
623 blocks: &[BlockCoeffs],
624) -> Result<Vec<u8>> {
625 check_blocks(mi_cols, mi_rows)?;
626 let (cols, rows) = block_grid(mi_cols, mi_rows);
627 if blocks.len() != (cols * rows) as usize {
628 return Err(Error::unsupported(
629 "AV1 tile",
630 "a coefficient key frame needs one coefficient set per 32x32 block",
631 ));
632 }
633 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
634 let superblocks: Vec<Superblock> = (0..sb_rows)
635 .flat_map(|sb_r| (0..sb_cols).map(move |sb_c| (sb_r, sb_c)))
636 .map(|(sb_r, sb_c)| {
637 Superblock::Split(
638 (0..4)
639 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
640 .filter(|&(r, c)| r < rows && c < cols)
641 .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone()))
642 .collect(),
643 )
644 })
645 .collect();
646 sb_coeff_key_frame_tile(mi_cols, mi_rows, base_q_idx, &superblocks)
647}
648
649/// Lays one plane's coefficient list out over its transform, rejecting the
650/// positions and levels the writer does not code.
651pub(super) fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
652 let mut grid = vec![0i32; side * side];
653 for coeff in coeffs {
654 if usize::from(coeff.row) >= side || usize::from(coeff.col) >= side {
655 return Err(Error::unsupported(
656 "AV1 tile",
657 "a coefficient sits outside the transform of its plane",
658 ));
659 }
660 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
661 return Err(Error::unsupported(
662 "AV1 tile",
663 format!(
664 "coefficients are written for levels -{MAX_LEVEL}..={MAX_LEVEL} without zero"
665 ),
666 ));
667 }
668 let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
669 if grid[pos] != 0 {
670 return Err(Error::unsupported(
671 "AV1 tile",
672 "two coefficients of one block share a position",
673 ));
674 }
675 grid[pos] = coeff.level;
676 }
677 Ok(grid)
678}
679
680/// The default scan of a square transform (spec 8.4.2's `Default_Scan_NxN`),
681/// as raster positions in the order they are coded.
682///
683/// The table is a rule rather than hundreds of pinned numbers: the scan walks
684/// the anti-diagonals of the transform outwards from the origin, each diagonal
685/// from its top-right end on odd diagonals and from its bottom-left end on
686/// even ones.
687pub(super) fn default_scan(side: usize) -> Vec<u16> {
688 let mut scan = Vec::with_capacity(side * side);
689 for d in 0..(2 * side - 1) {
690 let lo = d.saturating_sub(side - 1);
691 let hi = d.min(side - 1);
692 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
693 if d % 2 == 0 {
694 scan.extend(diagonal.rev());
695 } else {
696 scan.extend(diagonal);
697 }
698 }
699 scan
700}
701
702/// What one 32x32 luma transform block's levels cost, in bits, priced through
703/// the very CDFs [`write_coeffs`] will write them with -- end-of-block
704/// position, base levels, base range, signs and the Golomb tail all included.
705///
706/// The mode search calls this before the block's neighbours exist, so the two
707/// neighbour-derived contexts (the block-skip context and the DC sign context)
708/// are taken as zero. Every other context inside the block is exact, because
709/// those are read from the block's own levels.
710///
711/// The encoder codes 32x32 luma only -- every superblock it emits is split --
712/// so one table is all the search needs; a second block size would need its
713/// own entry point rather than a size argument, because the table and the scan
714/// have to agree.
715/// What the search paid for every coefficient of `blocks`, in bits: the same
716/// [`coeff_bits`] price the mode search ranked those blocks by, summed over
717/// the blocks that were actually kept.
718///
719/// The instrument behind `predicted_coeff_bits_track_the_tile_the_writer_wrote`
720/// (lane-av1rd1): the writer codes these levels against a state that has
721/// adapted away from the defaults `coeff_bits` prices with, and against real
722/// neighbour contexts instead of the empty ones, so the sum here and the tile
723/// the writer produced differ by exactly that drift plus the non-coefficient
724/// syntax (partition/mode/skip/mv symbols) the sum leaves out.
725#[cfg(test)]
726pub(super) fn dense(coeffs: &[Coeff], side: usize) -> Vec<i32> {
727 let mut grid = vec![0i32; side * side];
728 for c in coeffs {
729 grid[usize::from(c.row) * side + usize::from(c.col)] = c.level;
730 }
731 grid
732}
733
734#[cfg(test)]
735pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8) -> f64 {
736 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
737 superblocks
738 .iter()
739 .map(|sb| match sb {
740 // A whole 64x64 codes its luma through `TxbSet::Luma64` (only the
741 // top-left 32x32 carries coefficients) and each chroma plane at
742 // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here.
743 Superblock::Whole(block) if !block.skip => {
744 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
745 + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
746 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
747 }
748 Superblock::Whole(_) => 0.0,
749 Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx),
750 })
751 .sum()
752}
753
754#[cfg(test)]
755pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
756 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
757 fn block_bits(block: &BlockCoeffs, side: usize, q_ctx: usize) -> f64 {
758 if let Some(leaves) = &block.eight {
759 return leaves.iter().map(|l| block_bits(l, 8, q_ctx)).sum();
760 }
761 if block.skip {
762 return 0.0;
763 }
764 let inter = block.inter.is_some();
765 let (luma, chroma) = match (side, inter) {
766 (32, false) => (TxbSet::Luma32, TxbSet::Chroma16),
767 (32, true) => (TxbSet::Luma32Inter, TxbSet::Chroma16),
768 (16, false) => (TxbSet::Luma16, TxbSet::Chroma8),
769 (16, true) => (TxbSet::Luma16Inter, TxbSet::Chroma8),
770 (_, false) => (TxbSet::Luma8, TxbSet::Chroma4),
771 (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4),
772 };
773 coeff_bits(&dense(&block.luma, side), luma, q_ctx, 0, 0)
774 + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx, 0, 0)
775 + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx, 0, 0)
776 }
777 blocks
778 .iter()
779 .map(|q| {
780 let side = match q {
781 // lane-b128: a 128x128 root is SKIP by construction (the
782 // writer refuses a residual at that size), so it names no
783 // coefficients on any plane.
784 Quadrant::Whole128(_) | Quadrant::Rect128(..) | Quadrant::Ab128(..) => {
785 return 0.0;
786 }
787 Quadrant::Whole(_) => 32,
788 Quadrant::Split(_) => 16,
789 // lane-tx64: a 64x64 root that codes a residual pays for one
790 // TX_64X64 luma transform (only the top-left 32x32 carries
791 // coefficients) and one TX_32X32 per chroma plane -- the same
792 // three prices `predicted_coeff_bits_sb` takes for a key
793 // frame's whole superblock, and the same sets the writer's
794 // `Whole64` arm codes. `block_bits`'s table has no 64 row, so
795 // it is spelled out here.
796 Quadrant::Whole64(block) => {
797 return match block.skip {
798 true => 0.0,
799 false => {
800 // lane-b64b: at `tx_depth = 1` the luma levels are
801 // the whole 64-sided block, written as four
802 // TX_32X32 units, so the pricer slices them the
803 // same way the writer does.
804 let luma = if block.tx_depth == 1 {
805 let g = dense(&block.luma, 64);
806 (0..4)
807 .map(|tu| {
808 let (r0, c0) = ((tu / 2) * 32, (tu % 2) * 32);
809 let unit: Vec<i32> = (0..32)
810 .flat_map(|row| {
811 g[(r0 + row) * 64 + c0..][..32].to_vec()
812 })
813 .collect();
814 coeff_bits(&unit, TxbSet::Luma32Inter, q_ctx, 0, 0)
815 })
816 .sum::<f64>()
817 } else {
818 coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
819 };
820 luma + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
821 + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
822 }
823 };
824 }
825 Quadrant::Covered => return 0.0,
826 };
827 q.blocks()
828 .iter()
829 .map(|b| block_bits(b, side, q_ctx))
830 .sum::<f64>()
831 })
832 .sum()
833}
834
835#[cfg(test)]
836pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
837 coeff_bits(grid, TxbSet::Luma32, 2, 0, 0)
838}
839
840/// What one transform block's levels cost through the CDFs of `set`, in bits.
841///
842/// The search runs before the tile is written, so the adapted state the block
843/// will really be coded against does not exist yet: the price is taken against
844/// the defaults every tile starts from, at the frame's own coefficient
845/// q-context (`q_ctx_of(base_q_idx)`, what `Cdfs::new` is given at
846/// `sb_coeff_*_tile` -- lane-av1rd1: this used to be pinned at 2, so two of
847/// the four points of the BD ladder were priced against another quantizer's
848/// tables), and against the contexts a block whose neighbours coded nothing
849/// reads.
850///
851/// lane-av1skipctx CLOSED that row: `skip_ctx`/`sign_ctx` are the caller's
852/// now, and [`crate::encode::CoefCtxMap`] -- a per-plane, per-4x4-cell map
853/// committed in coding order and undone with a losing partition trial's
854/// pixels -- is the per-trial neighbour state the previous lane said the
855/// search did not have. The census (6 frames of each clip at 640x384, q=100,
856/// `pricer_error_census_on_clips`) moved:
857///
858/// | row | before | after |
859/// |---|---|---|
860/// | screen total | +10.3% | +9.5% |
861/// | screen Chroma8 nz=0 | -73.0% | -1.9% |
862/// | screen Chroma16 nz=0 | -48% | -23.4% |
863/// | screen Chroma4 nz=0 | -74% | -6.7% |
864/// | screen Chroma8 nz=1 / nz=2 | +32.2% / +26.2% | +4.9% / +7.9% |
865/// | screen Luma4 nz=0 | +464% | +89.5% |
866/// | film total | +5.3% | +1.5% |
867///
868/// What is left in the all-zero rows is table ADAPTATION, not context: the
869/// price is taken against the frame's starting tables, and a frame whose
870/// blocks mostly code nothing narrows `txb_skip` far below where it started.
871/// A whole-block luma transform still reads context 0 -- that is what the
872/// writer codes (`write_luma_tus`, `n == 1`), not an approximation.
873/// The default scan of one transform size, built once per size: the search
874/// prices thirteen modes for every block, and the scan is the same table
875/// every time.
876pub(super) fn scan_of(side: usize) -> &'static Vec<u16> {
877 pub(super) static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {
878 [
879 default_scan(TX4),
880 default_scan(TX8),
881 default_scan(TX16),
882 default_scan(TX32),
883 ]
884 });
885 match side {
886 TX4 => &SCANS[0],
887 TX8 => &SCANS[1],
888 TX16 => &SCANS[2],
889 _ => &SCANS[3],
890 }
891}
892
893/// [`scan_of`]'s `TX_CLASS_HORIZ`/`TX_CLASS_VERT` sibling (lane-txw): the
894/// `Mrow_Scan`/`Mcol_Scan` a `V_DCT`/`H_DCT` unit is coded in, built off the
895/// DECODER's own table so the two cannot drift, cached per size and class.
896pub(super) fn class_scan_of(side: usize, class: crate::decode::TxClass) -> &'static [u16] {
897 pub(super) static SCANS: LazyLock<[[Vec<u16>; 2]; 4]> = LazyLock::new(|| {
898 use crate::decode::{TxClass, class_scan_table};
899 [TX4, TX8, TX16, TX32].map(|side| {
900 [
901 class_scan_table(side, TxClass::Horiz),
902 class_scan_table(side, TxClass::Vert),
903 ]
904 })
905 });
906 let size = match side {
907 TX4 => 0,
908 TX8 => 1,
909 TX16 => 2,
910 _ => 3,
911 };
912 let idx = usize::from(class == crate::decode::TxClass::Vert);
913 &SCANS[size][idx]
914}
915
916/// [`coeff_bits_typed`] at `DCT_DCT`, the only type the test-only pricers
917/// ([`predicted_coeff_bits`]) model.
918#[cfg(test)]
919pub(crate) fn coeff_bits(
920 grid: &[i32],
921 set: TxbSet,
922 q_ctx: usize,
923 skip_ctx: usize,
924 sign_ctx: usize,
925) -> f64 {
926 coeff_bits_typed(grid, set, q_ctx, skip_ctx, sign_ctx, TxType::DctDct)
927}
928
929/// What levels a named transform type produced cost: the `tx_type`
930/// symbol is part of what the block spends, so a search comparing types has
931/// to see each one's own symbol priced (lane-txset).
932pub(crate) fn coeff_bits_typed(
933 grid: &[i32],
934 set: TxbSet,
935 q_ctx: usize,
936 // lane-av1skipctx: the two neighbour-derived contexts, mirrored from the
937 // writer's own (`write_block_planes`/`write_luma_tus`) off the search's
938 // coding-order-committed map ([`crate::encode::CoefCtxMap`]). `(0, 0)` is
939 // what every caller passed before the map existed -- exact for a luma
940 // transform covering its whole block, and the census row that was the
941 // largest remaining pricer error for every other block.
942 skip_ctx: usize,
943 sign_ctx: usize,
944 tx_type: TxType,
945) -> f64 {
946 // `Cdfs::new` builds every table a tile writer adapts -- tens of
947 // kilobytes -- and this function is called once per priced candidate:
948 // together with the copy behind it that was 9% of the encoder's profile
949 // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the
950 // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per
951 // q-context per thread beside a pristine one and restore just those from
952 // it. The state the price is taken against is identical to a fresh
953 // `Cdfs::new(q_ctx)`, so every price is bit-identical.
954 // lane-av1txbits: an inter frame's writer does NOT start from the
955 // defaults -- it starts from the tables the previous frame stored (spec
956 // 7.20, `start_cdfs` in `encode_inter_frame`) -- so pricing against the
957 // defaults charged the search for a narrowing the writer no longer pays.
958 // The census measured that at +31% on the one-coefficient inter blocks
959 // the search lives on. `arm_pricing_cdfs` puts the frame's own starting
960 // tables under the price; nothing armed keeps the old default behaviour.
961 let price = |slot: &mut (Cdfs, Cdfs)| {
962 let (pristine, scratch) = (&mut slot.0, &mut slot.1);
963 let src = pristine.txb(set, DC_PRED);
964 let mut coding = scratch.txb(set, DC_PRED);
965 coding.txb_skip.copy_from_slice(src.txb_skip);
966 coding.eob_pt.copy_from_slice(src.eob_pt);
967 if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) {
968 dst.copy_from_slice(src);
969 }
970 *coding.eob_extra = *src.eob_extra;
971 *coding.base = *src.base;
972 *coding.base_eob = *src.base_eob;
973 *coding.br = *src.br;
974 *coding.dc_sign = *src.dc_sign;
975 if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) {
976 dst.copy_from_slice(src);
977 }
978 let scan = scan_of(coding.side);
979 let mut enc = SymbolEncoder::pricer();
980 write_coeffs(
981 &mut enc,
982 &mut coding,
983 grid,
984 scan,
985 skip_ctx,
986 sign_ctx,
987 None,
988 tx_type,
989 );
990 enc.bits()
991 };
992 // lane-av1speed2: 60% of the transform units of an inter stream hold no
993 // coefficient, and for those `write_coeffs` codes ONE symbol -- the
994 // all-zero flag -- and returns. Restoring the eight tables it might have
995 // touched (~800 bytes of `copy_from_slice`, the largest `memmove` in the
996 // encoder's profile) buys nothing there, so price that symbol straight
997 // off the pristine table on a copy of its own row. Identical bits: the
998 // scratch's `txb_skip[skip_ctx]` was restored from exactly this row, and
999 // nothing after the flag runs.
1000 let zero_price = |slot: &mut (Cdfs, Cdfs)| {
1001 let mut row = slot.0.txb(set, DC_PRED).txb_skip[skip_ctx];
1002 let mut enc = SymbolEncoder::pricer();
1003 enc.symbol(1, &mut row);
1004 enc.bits()
1005 };
1006 let all_zero = grid.iter().all(|&level| level == 0);
1007 PRICING_BASE.with_borrow_mut(|base| {
1008 if let Some(slot) = base.as_deref_mut().filter(|s| s.0.q_ctx == q_ctx) {
1009 return if all_zero {
1010 zero_price(slot)
1011 } else {
1012 price(slot)
1013 };
1014 }
1015 PRICING.with_borrow_mut(|slots| {
1016 let slot = slots[q_ctx.min(3)]
1017 .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
1018 if all_zero {
1019 zero_price(slot)
1020 } else {
1021 price(slot)
1022 }
1023 })
1024 })
1025}
1026
1027/// The largest level [`rdoq`] offers a candidate for, and the most prices it
1028/// may spend on one block. `EC_AV1_RDOQ_MAXLEVEL` / `EC_AV1_RDOQ_BUDGET`
1029/// sweep them; see [`rdoq`] for why both exist.
1030pub(super) const RDOQ_MAX_LEVEL: u32 = 2;
1031pub(super) const RDOQ_BUDGET: u32 = 24;
1032
1033pub(super) fn rdoq_max_level() -> u32 {
1034 pub(super) static ENV: LazyLock<u32> = LazyLock::new(|| {
1035 crate::envflags::var("EC_AV1_RDOQ_MAXLEVEL")
1036 .ok()
1037 .and_then(|v| v.parse().ok())
1038 .unwrap_or(RDOQ_MAX_LEVEL)
1039 });
1040 *ENV
1041}
1042
1043pub(super) fn rdoq_budget() -> u32 {
1044 pub(super) static ENV: LazyLock<u32> = LazyLock::new(|| {
1045 crate::envflags::var("EC_AV1_RDOQ_BUDGET")
1046 .ok()
1047 .and_then(|v| v.parse().ok())
1048 .unwrap_or(RDOQ_BUDGET)
1049 });
1050 *ENV
1051}
1052
1053/// Rate-distortion optimised quantisation (lane-rdoq): the pass every
1054/// reference encoder runs after the quantiser and this one did not have.
1055///
1056/// The deadzone quantiser rounds each coefficient on its own, blind to what
1057/// the coded level costs. Every reference decides that per coefficient
1058/// against the entropy coder (libaom `av1_optimize_txb`, rav1e
1059/// `optimize_txb`): a level is lowered toward zero when the bits it gives
1060/// back are worth more than the squared error it adds, which also shortens
1061/// the eob when the tail levels go to zero.
1062///
1063/// Mirroring rav1e's shape without its incremental cost model: the candidate
1064/// set per coefficient is `{level, level - 1, .., 0}` walked one step at a
1065/// time in REVERSE scan order (the tail first, so a dropped tail is retried
1066/// against the shorter eob it leaves), and each candidate is priced by
1067/// re-coding the whole block through [`coeff_bits`] -- the same CDFs, the
1068/// same neighbour contexts and the same writer the search already prices
1069/// with, so no second cost model can drift from the writer (class
1070/// `table-and-reader-move-together`). That costs one `write_coeffs` per
1071/// candidate instead of rav1e's table lookup, which is why this is a preset
1072/// lever (`crate::speed::RDOQ`) and not unconditional.
1073///
1074/// `levels` is the side-strided grid the inverse transform and the writer
1075/// will read, `scaled` the pre-rounding `coeff / q` of each position
1076/// (`crate::transform::forward_and_quantize_scaled`). `lambda` is the rate
1077/// weight in units of ONE SQUARED AC QUANTISER STEP: the search's own
1078/// `sse + lambda * bits` is `step^2 * (sum (scaled - level)^2 + LAMBDA_SCALE
1079/// * bits)` once the pixel-domain error of a level is written through the
1080/// orthonormal transform (`(coeff - level * q) / 8`, `INVERSE_GAIN_RECIPROCAL`),
1081/// so `step^2` divides out of every comparison here and the DC's different
1082/// quantiser is the only per-position weight left.
1083///
1084/// Returns what the block's levels cost after the pass, so the caller prices
1085/// the tile it will actually write and never the pre-RDOQ grid.
1086#[allow(clippy::too_many_arguments)]
1087pub(crate) fn rdoq(
1088 levels: &mut [i32],
1089 scaled: &[f32],
1090 side: usize,
1091 base_q_idx: u8,
1092 set: TxbSet,
1093 skip_ctx: usize,
1094 sign_ctx: usize,
1095 lambda: f64,
1096 tx_type: TxType,
1097) -> f64 {
1098 // A 64-point transform carries its top-left 32x32 alone, and that corner
1099 // is what the writer and the pricer take (`coded_corner`).
1100 let coded = side.min(TX32);
1101 let q_ctx = crate::decode::q_ctx_of(base_q_idx);
1102 let mut dense = if coded == side {
1103 Vec::new()
1104 } else {
1105 vec![0i32; coded * coded]
1106 };
1107 fn price(
1108 levels: &[i32],
1109 dense: &mut [i32],
1110 side: usize,
1111 coded: usize,
1112 set: TxbSet,
1113 q_ctx: usize,
1114 skip_ctx: usize,
1115 sign_ctx: usize,
1116 tx_type: TxType,
1117 ) -> f64 {
1118 if dense.is_empty() {
1119 return coeff_bits_typed(levels, set, q_ctx, skip_ctx, sign_ctx, tx_type);
1120 }
1121 for row in 0..coded {
1122 dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]);
1123 }
1124 coeff_bits_typed(dense, set, q_ctx, skip_ctx, sign_ctx, tx_type)
1125 }
1126 let mut bits = price(
1127 levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type,
1128 );
1129 // The DC has its own quantiser, so its squared error per unit of level is
1130 // `(dc_q / ac_q)^2` of an AC coefficient's.
1131 let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx)));
1132 let ac = f64::from(crate::quant::ac_q(8, i32::from(base_q_idx)));
1133 let dc_weight = (dc / ac) * (dc / ac);
1134 let census = crate::envflags::env_flag!("EC_AV1_RDOQ_CENSUS");
1135 if census {
1136 census_block(levels, scaled, side, coded, bits);
1137 }
1138 // Where the pass may spend its prices. Every candidate here costs a whole
1139 // `write_coeffs`, where rav1e's incremental model costs a table lookup,
1140 // so both bounds exist to keep that affordable -- and both cut where the
1141 // decisions do not pay anyway:
1142 // * a level above [`RDOQ_MAX_LEVEL`] is never a candidate: one step off
1143 // a big level gives back a fraction of a bit for a whole quantiser
1144 // step of squared error. What pays is `1 -> 0` and `2 -> 1`.
1145 // * at most [`RDOQ_BUDGET`] prices per block, spent from the TAIL
1146 // backwards -- the eob end, where dropping a level also shortens the
1147 // eob -- so a fine-quantizer block carrying two hundred coefficients
1148 // cannot cost two hundred re-codings.
1149 let mut budget = rdoq_budget();
1150 let max_level = rdoq_max_level();
1151 // lane-txw: the tail this walks back from is the tail of the unit's OWN
1152 // scan -- a `V_DCT`/`H_DCT` unit is coded in `Mrow_Scan`/`Mcol_Scan`, so
1153 // the 2D zigzag's last positions are not the ones whose removal shortens
1154 // its eob. Every candidate is still priced through the class-aware writer
1155 // ([`write_coeffs`]), so this changes which positions the budget reaches,
1156 // never whether a decision is right.
1157 let class = crate::decode::TxClass::of(tx_type);
1158 let order: &[u16] = if class == crate::decode::TxClass::TwoD {
1159 scan_of(coded)
1160 } else {
1161 class_scan_of(coded, class)
1162 };
1163 for &position in order.iter().rev() {
1164 if budget == 0 {
1165 break;
1166 }
1167 let (row, col) = (usize::from(position) / coded, usize::from(position) % coded);
1168 let i = row * side + col;
1169 if levels[i] == 0 || levels[i].unsigned_abs() > max_level {
1170 continue;
1171 }
1172 let s = f64::from(scaled[i]);
1173 let weight = if i == 0 { dc_weight } else { 1.0 };
1174 while budget > 0 {
1175 let level = levels[i];
1176 let candidate = level - level.signum();
1177 levels[i] = candidate;
1178 budget -= 1;
1179 let after = price(
1180 levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type,
1181 );
1182 let distortion =
1183 weight * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2));
1184 if distortion + lambda * (after - bits) < 0.0 {
1185 bits = after;
1186 if census {
1187 RDOQ_STATS[if candidate == 0 { 4 } else { 5 }].fetch_add(1, Ordering::Relaxed);
1188 }
1189 if candidate == 0 {
1190 break;
1191 }
1192 } else {
1193 levels[i] = level;
1194 break;
1195 }
1196 }
1197 }
1198 if census {
1199 RDOQ_STATS[6].fetch_add((bits * 64.0) as u64, Ordering::Relaxed);
1200 }
1201 bits
1202}
1203
1204/// blocks, coded coefficients, +-1 levels, trailing +-1 levels (a run of them
1205/// at the end of the scan), zeroed coefficients, lowered coefficients, bits
1206/// after the pass * 64, bits before the pass * 64.
1207pub(crate) static RDOQ_STATS: [AtomicU64; 8] = [
1208 AtomicU64::new(0),
1209 AtomicU64::new(0),
1210 AtomicU64::new(0),
1211 AtomicU64::new(0),
1212 AtomicU64::new(0),
1213 AtomicU64::new(0),
1214 AtomicU64::new(0),
1215 AtomicU64::new(0),
1216];
1217
1218/// The pre-pass half of [`RDOQ_STATS`] (`EC_AV1_RDOQ_CENSUS`): what the
1219/// quantiser handed the pass, which is the instrument for how much is at
1220/// stake before any decision is taken.
1221pub(super) fn census_block(levels: &[i32], _scaled: &[f32], side: usize, coded: usize, bits: f64) {
1222 let scan = scan_of(coded);
1223 let at = |p: u16| levels[usize::from(p) / coded * side + usize::from(p) % coded];
1224 let nonzero = scan.iter().filter(|&&p| at(p) != 0).count();
1225 let ones = scan.iter().filter(|&&p| at(p).abs() == 1).count();
1226 let trailing = scan
1227 .iter()
1228 .rev()
1229 .skip_while(|&&p| at(p) == 0)
1230 .take_while(|&&p| at(p).abs() == 1)
1231 .count();
1232 RDOQ_STATS[0].fetch_add(1, Ordering::Relaxed);
1233 RDOQ_STATS[1].fetch_add(nonzero as u64, Ordering::Relaxed);
1234 RDOQ_STATS[2].fetch_add(ones as u64, Ordering::Relaxed);
1235 RDOQ_STATS[3].fetch_add(trailing as u64, Ordering::Relaxed);
1236 RDOQ_STATS[7].fetch_add((bits * 64.0) as u64, Ordering::Relaxed);
1237}
1238
1239/// Reads and clears [`RDOQ_STATS`].
1240pub fn take_rdoq_stats() -> [u64; 8] {
1241 std::array::from_fn(|i| RDOQ_STATS[i].swap(0, Ordering::Relaxed))
1242}
1243
1244thread_local! {
1245 /// The default tables every price falls back to, one pristine/scratch
1246 /// pair per q-context (see [`coeff_bits`] for why the pair is kept).
1247 pub(super) static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
1248 const { RefCell::new([None, None, None, None]) };
1249 /// The tables the frame being searched will really be written against,
1250 /// armed per frame by the encoder ([`arm_pricing_cdfs`]) on every thread
1251 /// that prices -- the search jobs re-arm their own worker, exactly like
1252 /// the other tile thread-locals.
1253 pub(super) static PRICING_BASE: RefCell<Option<Box<(Cdfs, Cdfs)>>> = const { RefCell::new(None) };
1254}
1255
1256/// Arms the tables [`coeff_bits`] prices against on this thread: the state
1257/// this frame's tile writer starts from. `None` goes back to the per-q-context
1258/// defaults (a key frame, whose writer really does start there), and so does
1259/// any frame the screen detector said yes to (`screen`).
1260///
1261/// ON by default for non-screen frames since lane-av1price2;
1262/// `EC_AV1_PRICE_FRAME_CDFS` selects 0 = never (the pre-lane behaviour),
1263/// 1 = always, unset/2 = the screen-gated default.
1264///
1265/// Pricing against the frame's REAL starting tables is the more accurate
1266/// estimate by measurement -- the pricer census
1267/// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every
1268/// transform block, and the one- and two-coefficient inter blocks the search
1269/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy only
1270/// converts into ladder bytes on camera content. Measured on ONE build
1271/// (lane-av1price2, mode 0 vs mode 2), BD-rate vs libaom / vs rav1e:
1272///
1273/// | clip | 640x384 base | 640x384 gated | native base | native gated |
1274/// |---|---|---|---|---|
1275/// | film 1080p | +79.9 / +37.3 | +78.8 / +36.1 | +18.7 / +1.4 | +18.0 / +0.7 |
1276/// | film 2160p | +94.6 / +55.7 | +95.1 / +56.4 | +48.1 / +19.8 | +47.3 / +19.2 |
1277/// | screen | +54.5 / +1.1 | +54.5 / +1.1 | +59.4 / -10.0 | +59.4 / -10.0 |
1278///
1279/// The screen rows are not merely close, they are byte-identical (the ladders
1280/// print 8832/13507/18772/24754 and 39312/52829/70719/92134 in both modes):
1281/// the gate is per frame and the detector fires on 48 of 48 screen frames, so
1282/// no screen frame is ever armed with anything but the defaults. At native
1283/// resolution -- the resolution his library is in -- both films come down
1284/// against both references and the screen capture is flat, which is this
1285/// lane's keep rule. At the downscaled 640x384 gate the 2160p film goes the
1286/// other way (+0.5/+0.7) while the 1080p one comes down further (-1.1/-1.2);
1287/// the downscale is the same recipe that exaggerated the frame pyramid's loss
1288/// sixfold, so the native table decides and the 640x384 2160p regression is
1289/// recorded here rather than argued away.
1290///
1291/// Why the screen capture needs the gate at all is in the census
1292/// (`pricer_error_census_on_clips`, 6 frames of each clip at 640x384, q=100).
1293/// Real tables take the film clip's total pricer error from +7.8% to +5.3%
1294/// and flatten its inter classes outright (Luma8Inter/Luma16Inter/Luma32Inter
1295/// 1-coefficient rows from +11.7%/+17.4%/+24.9% to -0.3%/-5.5%/+8.8%). On the
1296/// screen capture the total only moves +12.8% -> +10.3%, because the classes
1297/// that dominate a screen frame are not the ones the tables fix: its chroma
1298/// stays over-priced (Chroma8 nz=1 +32.2% -> +31.8%, nz=2 +26.2% -> +26.2%,
1299/// unmoved) and its all-zero blocks stay hugely UNDER-priced (Chroma8 nz=0
1300/// -73.0% -> -73.0%, Luma4 nz=0 +464% -> +467% -- both a pricer that assumes
1301/// `skip_ctx` 0, not a table set). So on screen the change makes the inter
1302/// luma price accurate while leaving the bigger chroma and all-zero errors
1303/// exactly where they were, which SKEWS the search's tradeoffs between them
1304/// instead of correcting them -- and the bytes get worse. The fix for that
1305/// row was the neighbour skip context, not another table set, and
1306/// lane-av1skipctx landed it (see [`coeff_bits`]): with the real contexts
1307/// under every price the screen capture comes down +59.4 -> +58.3 vs libaom
1308/// at native, still with every one of its frames armed with the defaults.
1309pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {
1310 pub(super) static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
1311 let mode = *MODE.get_or_init(
1312 || match std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() {
1313 Ok("0") => 0,
1314 Ok("1") => 1,
1315 _ => 2,
1316 },
1317 );
1318 let on = match mode {
1319 0 => false,
1320 1 => true,
1321 _ => !screen,
1322 };
1323 PRICING_HITS[usize::from(on && base.is_some())].fetch_add(1, Ordering::Relaxed);
1324 PRICING_BASE.with_borrow_mut(|slot| {
1325 *slot = base
1326 .filter(|_| on)
1327 .map(|c| Box::new((c.clone(), c.clone())));
1328 });
1329}
1330
1331/// How many times a frame's search was armed with the DEFAULT tables and how
1332/// many with the frame's REAL starting tables ([`arm_pricing_cdfs`]), so a
1333/// gate can print which side of the screen gate every frame landed on. Counts
1334/// arming calls, not frames: a multi-tile frame arms one worker per tile.
1335pub(crate) static PRICING_HITS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)];
1336
1337/// Reads and clears [`PRICING_HITS`]: (default-table armings, real-table
1338/// armings).
1339#[cfg(test)]
1340pub(crate) fn take_pricing_hits() -> (usize, usize) {
1341 (
1342 PRICING_HITS[0].swap(0, Ordering::Relaxed),
1343 PRICING_HITS[1].swap(0, Ordering::Relaxed),
1344 )
1345}
1346
1347/// The pricer census (`pricer_census_on`): for every transform block the tile
1348/// writer really codes, the bits it spent against the bits [`coeff_bits`]
1349/// prices those very levels at -- the search's rate term measured against the
1350/// rate it is meant to predict. Keyed by (table set, non-zero bucket) so a
1351/// class that is systematically mispriced (all-zero blocks' `txb_skip`, the
1352/// eob of a one-coefficient block, a whole size) shows up on its own row
1353/// rather than inside one average.
1354/// Thread-local, so a census cannot pick up the blocks of another test's
1355/// encode running beside it; a multi-tile, multi-threaded encode would
1356/// therefore only census the tiles this thread wrote, which is every tile of
1357/// the one-tile-one-thread encodes the gates print it from.
1358#[cfg(test)]
1359pub(super) type CensusRows = BTreeMap<(String, usize), (u64, f64, f64)>;
1360#[cfg(test)]
1361thread_local! {
1362 pub(super) static CENSUS: RefCell<Option<CensusRows>> = const { RefCell::new(None) };
1363}
1364
1365/// Starts a census on this thread, discarding anything a previous one left.
1366#[cfg(test)]
1367pub(crate) fn pricer_census_on() {
1368 CENSUS.with_borrow_mut(|c| *c = Some(BTreeMap::new()));
1369}
1370
1371/// Stops the census and hands back its rows: (set, non-zero bucket) ->
1372/// (blocks, priced bits, written bits).
1373#[cfg(test)]
1374pub(crate) fn take_pricer_census() -> CensusRows {
1375 CENSUS.with_borrow_mut(|c| c.take()).unwrap_or_default()
1376}
1377
1378/// The label of a non-zero bucket, for the tables the gates print.
1379#[cfg(test)]
1380pub(crate) fn census_bucket_label(bucket: usize) -> &'static str {
1381 ["0", "1", "2", "3-4", "5-8", "9-16", "17+"][bucket]
1382}
1383
1384#[cfg(test)]
1385pub(super) fn census_record(
1386 set: TxbSet,
1387 q_ctx: usize,
1388 grid: &[i32],
1389 written: f64,
1390 // The writer's own neighbour contexts for this very transform block: the
1391 // census prices the search's estimate the way the search now takes it
1392 // (lane-av1skipctx), so a row's error is the table/adaptation drift that
1393 // is left once the context is right.
1394 skip_ctx: usize,
1395 sign_ctx: usize,
1396) {
1397 if CENSUS.with_borrow(|c| c.is_none()) {
1398 return;
1399 }
1400 let nz = grid.iter().filter(|&&l| l != 0).count();
1401 let bucket = match nz {
1402 0 => 0,
1403 1 => 1,
1404 2 => 2,
1405 3..=4 => 3,
1406 5..=8 => 4,
1407 9..=16 => 5,
1408 _ => 6,
1409 };
1410 let priced = coeff_bits(grid, set, q_ctx, skip_ctx, sign_ctx);
1411 CENSUS.with_borrow_mut(|rows| {
1412 let rows = rows.as_mut().expect("the census is on");
1413 let row = rows.entry((format!("{set:?}"), bucket)).or_default();
1414 row.0 += 1;
1415 row.1 += priced;
1416 row.2 += written;
1417 });
1418}
1419
1420/// What the partition symbol of a block of `side` samples costs, in bits, when
1421/// it says the block is split (or that it is not).
1422///
1423/// The price is taken at context zero — a block whose neighbours are no finer
1424/// than it is — because the search that reads it runs before the tile knows
1425/// what its neighbours will be.
1426pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
1427 // Read-only, and the same tables every call: built once (see
1428 // [`coeff_bits`] for why that matters here).
1429 pub(super) static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
1430 let cdfs = &*CDFS;
1431 let cdf: &[u16] = match side {
1432 // lane-b128: the 128 superblock root's own eight-symbol alphabet.
1433 128 => &cdfs.partition_w128[0],
1434 SB => &cdfs.partition_w64[0],
1435 BLOCK => &cdfs.partition_w32[0],
1436 TX8 => &cdfs.partition_w8[0],
1437 _ => &cdfs.partition_w16[0],
1438 };
1439 let symbol = if split {
1440 PARTITION_SPLIT
1441 } else {
1442 PARTITION_NONE
1443 };
1444 crate::encode::symbol_bits(cdf, symbol)
1445}
1446
1447/// lane-b128hv: [`partition_bits`] for any partition symbol, at the same
1448/// fixed (round-2) tables -- what the 128 root's HORZ/VERT candidate is priced
1449/// with (`PARTITION_HORZ` = 1, `PARTITION_VERT` = 2).
1450pub(crate) fn partition_bits_sym(side: usize, symbol: usize) -> f64 {
1451 pub(super) static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
1452 let cdfs = &*CDFS;
1453 let cdf: &[u16] = match side {
1454 128 => &cdfs.partition_w128[0],
1455 SB => &cdfs.partition_w64[0],
1456 BLOCK => &cdfs.partition_w32[0],
1457 TX8 => &cdfs.partition_w8[0],
1458 _ => &cdfs.partition_w16[0],
1459 };
1460 crate::encode::symbol_bits(cdf, symbol)
1461}
1462
1463/// coeffs() for one plane's transform block of any coefficients the base and
1464/// base-range syntax reach (spec 5.11.39).
1465///
1466/// A 16x16 luma transform codes which transform type it is, because its set
1467/// holds more than one; 32x32 and 64x64 are DCT-only by spec 5.11.40. The
1468/// levels the contexts below are read from are the levels of
1469/// coefficients later in the scan, which a decoder walking the scan backwards
1470/// already has.
1471#[allow(clippy::too_many_arguments)]
1472pub(super) fn write_coeffs(
1473 enc: &mut SymbolEncoder,
1474 coding: &mut TxbTables,
1475 grid: &[i32],
1476 scan: &[u16],
1477 skip_ctx: usize,
1478 sign_ctx: usize,
1479 plane: Option<usize>,
1480 // Which transform type these levels were produced with (lane-txset).
1481 // Only a luma set whose alphabet holds more than one type codes it;
1482 // chroma never codes a `tx_type` symbol at all.
1483 tx_type: TxType,
1484) {
1485 if let Some(plane) = plane {
1486 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));
1487 }
1488 let side = coding.side;
1489 // lane-txw ROOT CAUSE: this writer used to code every transform unit as
1490 // `TX_CLASS_2D` -- default zigzag scan, the 2D `eob_pt` table and the 2D
1491 // neighbour taps -- while the decoder resolves `V_DCT`/`H_DCT` to
1492 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`decode::TxClass::of`), which read
1493 // their own scan (`class_scan_table`), their own `eob_pt` row
1494 // (`eob_pt_class1`) and their own context offsets. So the first 1-D type
1495 // the search ever offered (the wider `reduced_tx_set == 0` alphabets)
1496 // desynced the tile from its own trial decode. The class is a property of
1497 // the type alone, so it is resolved here, once per unit, exactly as the
1498 // reader does it.
1499 let class = crate::decode::TxClass::of(tx_type);
1500 let scan: &[u16] = if class == crate::decode::TxClass::TwoD {
1501 scan
1502 } else {
1503 class_scan_of(side, class)
1504 };
1505 // The scan-order search reads the grid in scan order, one dependent load
1506 // per position, and an all-zero block makes it walk every one of them --
1507 // which the pricer does for candidate after candidate. A straight-line
1508 // pass settles that case first: it vectorises, and a block that codes
1509 // anything at all almost always codes its DC, so it stops at the first
1510 // element.
1511 let eob = if grid.iter().all(|&level| level == 0) {
1512 0
1513 } else {
1514 scan.iter()
1515 .rposition(|&pos| grid[pos as usize] != 0)
1516 .map_or(0, |i| i + 1)
1517 };
1518 enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]);
1519 if plane.is_some() {
1520 ec_rng_trace(|| {
1521 format!(
1522 "EC_TXBSKIP ctx={skip_ctx} eob0={} tell={} rng={}",
1523 usize::from(eob == 0),
1524 enc.tell(),
1525 enc.rng()
1526 )
1527 });
1528 }
1529 if eob == 0 {
1530 return;
1531 }
1532 // A luma transform whose type set holds more than one type codes which it
1533 // is, right after the all-zero flag (spec 5.11.39). The writer only ever
1534 // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.
1535 if let Some(cdf) = coding.tx_type.as_deref_mut() {
1536 // The symbol comes from the DECODER's own map, keyed by this set's
1537 // alphabet width, so a type this set cannot express is caught here
1538 // rather than desyncing the tile. The search only ever offers types
1539 // the set holds ([`crate::encode::tx_type_candidates`]).
1540 let symbol = crate::decode::tx_type_symbol(cdf.len(), tx_type);
1541 debug_assert!(
1542 symbol.is_some(),
1543 "{tx_type:?} is not in the {}-symbol tx_type set",
1544 cdf.len() - 1
1545 );
1546 enc.symbol(symbol.unwrap_or(TX_TYPE_DCT_DCT_SET2), cdf);
1547 if plane.is_some() {
1548 ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng()));
1549 }
1550 }
1551
1552 write_eob(enc, coding, eob, plane, class);
1553
1554 // lane-av1speed3: `side` is 4, 8, 16 or 32, but it is a runtime value --
1555 // `pos / side` compiles to a real integer division, once per coefficient,
1556 // in the encoder's largest self-time symbol. Same row and column.
1557 debug_assert!(
1558 side.is_power_of_two(),
1559 "the scan splits a position by shifting"
1560 );
1561 let (shift, mask) = (side.trailing_zeros(), side - 1);
1562 for scan_idx in (0..eob).rev() {
1563 let pos = scan[scan_idx] as usize;
1564 let (row, col) = (pos >> shift, pos & mask);
1565 let level = grid[pos].abs();
1566 if scan_idx == eob - 1 {
1567 let ctx = eob_coeff_ctx(scan_idx, side * side);
1568 let sym = (level.min(NUM_BASE_LEVELS + 1) - 1) as usize;
1569 enc.symbol(sym, &mut coding.base_eob[ctx]);
1570 if plane.is_some() {
1571 ec_rng_trace(|| {
1572 format!(
1573 "EC_BASEEOB scan_idx={scan_idx} ctx={ctx} level={} tell={}",
1574 sym + 1,
1575 enc.tell()
1576 )
1577 });
1578 }
1579 } else {
1580 let ctx = base_ctx(grid, side, row, col, class);
1581 let sym = level.min(NUM_BASE_LEVELS + 1) as usize;
1582 enc.symbol(sym, &mut coding.base[ctx]);
1583 if plane.is_some() {
1584 ec_rng_trace(|| {
1585 format!(
1586 "EC_BASE scan_idx={scan_idx} ctx={ctx} level={sym} tell={}",
1587 enc.tell()
1588 )
1589 });
1590 }
1591 }
1592 if level > NUM_BASE_LEVELS {
1593 let ctx = br_ctx(grid, side, row, col, class);
1594 let mut remaining = level - (NUM_BASE_LEVELS + 1);
1595 let mut sent = 0;
1596 while sent < COEFF_BASE_RANGE {
1597 let k = remaining.min(BR_STEP);
1598 enc.symbol(k as usize, &mut coding.br[ctx]);
1599 if plane.is_some() {
1600 ec_rng_trace(|| {
1601 format!(
1602 "EC_BR scan_idx={scan_idx} ctx={ctx} k={k} tell={}",
1603 enc.tell()
1604 )
1605 });
1606 }
1607 if k < BR_STEP {
1608 break;
1609 }
1610 remaining -= k;
1611 sent += BR_STEP;
1612 }
1613 }
1614 }
1615
1616 // The signs come after the levels, in scan order, the DC's from a CDF and
1617 // the rest as raw bits (spec 5.11.39).
1618 for &pos in &scan[..eob] {
1619 let level = grid[pos as usize];
1620 if level == 0 {
1621 continue;
1622 }
1623 if pos == 0 {
1624 enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]);
1625 if plane.is_some() {
1626 ec_rng_trace(|| {
1627 format!(
1628 "EC_DCSIGN ctx={sign_ctx} neg={} tell={}",
1629 usize::from(level < 0),
1630 enc.tell()
1631 )
1632 });
1633 }
1634 } else {
1635 enc.literal(u32::from(level < 0), 1);
1636 }
1637 // A level the base and base-range syntax cannot reach carries the rest
1638 // of itself here, after its own sign (spec 5.11.39).
1639 if level.abs() > MAX_BR_LEVEL {
1640 write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32);
1641 if plane.is_some() {
1642 ec_rng_trace(|| format!("EC_GOLOMB tell={}", enc.tell()));
1643 }
1644 }
1645 }
1646 if let Some(plane) = plane {
1647 ec_rng_trace(|| format!("EC_PLANE plane={plane} eob={eob} tell_after={}", enc.tell()));
1648 }
1649}
1650
1651/// The end-of-block position (spec 5.11.39): which group of scan positions the
1652/// last coded coefficient falls in, then its offset inside that group — the
1653/// offset's top bit from a CDF and the rest as raw bits.
1654pub(super) fn write_eob(
1655 enc: &mut SymbolEncoder,
1656 coding: &mut TxbTables,
1657 eob: usize,
1658 plane: Option<usize>,
1659 class: crate::decode::TxClass,
1660) {
1661 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
1662 /// end-of-block positions covers, indexed by the group's own number.
1663 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
1664 /// `Eob_Offset_Bits` (spec 5.11.39): how wide each group's offset is.
1665 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1666
1667 let group = GROUP_START
1668 .iter()
1669 .rposition(|&start| start <= eob)
1670 .expect("the first group starts at zero");
1671 // The groups are numbered from one, and how many of them the transform
1672 // reaches is the size of its own end-of-block alphabet. A
1673 // `TX_CLASS_HORIZ`/`TX_CLASS_VERT` unit adapts a wholly separate row
1674 // (libaom's `eob_multi_ctx`), which is what `decode::read_eob` reads.
1675 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
1676 (crate::decode::TxClass::TwoD, _) | (_, None) => coding.eob_pt,
1677 (_, Some(class1)) => class1,
1678 };
1679 enc.symbol(group - 1, eob_pt);
1680 if let Some(plane) = plane {
1681 ec_rng_trace(|| {
1682 format!(
1683 "EC_EOBPT plane={plane} eob_pt={group} tell={} rng={}",
1684 enc.tell(),
1685 enc.rng()
1686 )
1687 });
1688 }
1689
1690 let bits = OFFSET_BITS[group];
1691 if bits > 0 {
1692 let offset = (eob - GROUP_START[group]) as u32;
1693 let top = (offset >> (bits - 1)) & 1;
1694 enc.symbol(top as usize, &mut coding.eob_extra[group - 3]);
1695 if let Some(plane) = plane {
1696 ec_rng_trace(|| {
1697 format!(
1698 "EC_EOBEXTRA plane={plane} eob_ctx={} top={top} tell={}",
1699 group - 3,
1700 enc.tell()
1701 )
1702 });
1703 }
1704 if bits > 1 {
1705 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
1706 if let Some(plane) = plane {
1707 ec_rng_trace(|| {
1708 format!(
1709 "EC_EOBBITS plane={plane} eob_extra={offset} tell={}",
1710 enc.tell()
1711 )
1712 });
1713 }
1714 }
1715 }
1716}
1717
1718/// Writes the remainder of a level the base and base-range syntax could not
1719/// reach (spec 5.11.40): the value plus one, as its bit length in unary
1720/// followed by the value's own bits, most significant first.
1721pub(crate) fn write_golomb(enc: &mut SymbolEncoder, value: u32) {
1722 let x = value + 1;
1723 let length = 32 - x.leading_zeros();
1724 for _ in 0..length - 1 {
1725 enc.literal(0, 1);
1726 }
1727 for i in (0..length).rev() {
1728 enc.literal((x >> i) & 1, 1);
1729 }
1730}
1731
1732/// The context of the level of the last coded coefficient (spec 8.3.2): how
1733/// far into the scan it sits, in quarters and eighths of the transform.
1734pub(super) fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
1735 match scan_idx {
1736 0 => 0,
1737 i if i <= area / 8 => 1,
1738 i if i <= area / 4 => 2,
1739 _ => 3,
1740 }
1741}
1742
1743/// The context of a coefficient's level (spec 8.3.2): the magnitudes of the
1744/// five neighbours below and to the right of it — the ones a decoder walking
1745/// the scan backwards already has — plus a term for where in the transform it
1746/// sits. The DC reads context 0 whatever its neighbours carry.
1747pub(super) fn base_ctx(
1748 grid: &[i32],
1749 side: usize,
1750 row: usize,
1751 col: usize,
1752 class: crate::decode::TxClass,
1753) -> usize {
1754 use crate::decode::TxClass;
1755 // Only `TX_CLASS_2D` short-circuits its DC to context 0
1756 // (`get_nz_map_ctx_from_stats`'s `(tx_class | coeff_idx) == 0`); a 1-D
1757 // class runs the DC through the same neighbour sum as every other
1758 // position.
1759 if class == TxClass::TwoD && row == 0 && col == 0 {
1760 return 0;
1761 }
1762 if class != TxClass::TwoD {
1763 let offsets: [(usize, usize); 5] = if class == TxClass::Horiz {
1764 [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)]
1765 } else {
1766 [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)]
1767 };
1768 let mag: i32 = offsets
1769 .iter()
1770 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
1771 .sum();
1772 let along = if class == TxClass::Horiz { col } else { row };
1773 return (((mag + 1) >> 1).min(4) as usize)
1774 + crate::decode::nz_map_ctx_offset_1d(along.min(31));
1775 }
1776 // A coefficient two rows and two columns clear of the far edges reaches
1777 // all five neighbours, so the gather is five loads off one index with no
1778 // per-neighbour edge test -- which is where this writer spends a third of
1779 // its coefficient loop.
1780 let p = row * side + col;
1781 let mag: i32 = if row + 2 < side && col + 2 < side {
1782 [p + side, p + 1, p + side + 1, p + 2 * side, p + 2]
1783 .iter()
1784 .map(|&i| grid[i].abs().min(3))
1785 .sum()
1786 } else {
1787 [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
1788 .iter()
1789 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
1790 .sum()
1791 };
1792 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
1793 (((mag + 1) >> 1).min(4) as usize) + offset
1794}
1795
1796/// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes
1797/// of its three closest neighbours below and to the right, uncapped, and a
1798/// term separating the DC, the corner of the transform, and the rest.
1799pub(super) fn br_ctx(
1800 grid: &[i32],
1801 side: usize,
1802 row: usize,
1803 col: usize,
1804 class: crate::decode::TxClass,
1805) -> usize {
1806 use crate::decode::TxClass;
1807 if class != TxClass::TwoD {
1808 let extra = if class == TxClass::Horiz {
1809 neighbour(grid, side, row, col + 2)
1810 } else {
1811 neighbour(grid, side, row + 2, col)
1812 };
1813 let mag = neighbour(grid, side, row + 1, col).abs()
1814 + neighbour(grid, side, row, col + 1).abs()
1815 + extra.abs();
1816 let mag = (((mag + 1) >> 1).min(6)) as usize;
1817 if row == 0 && col == 0 {
1818 return mag;
1819 }
1820 let near_origin = if class == TxClass::Horiz {
1821 col == 0
1822 } else {
1823 row == 0
1824 };
1825 return if near_origin { mag + 7 } else { mag + 14 };
1826 }
1827 let p = row * side + col;
1828 let mag: i32 = if row + 1 < side && col + 1 < side {
1829 grid[p + side].abs() + grid[p + 1].abs() + grid[p + side + 1].abs()
1830 } else {
1831 [(1, 0), (0, 1), (1, 1)]
1832 .iter()
1833 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
1834 .sum()
1835 };
1836 let mag = (((mag + 1) >> 1).min(6)) as usize;
1837 if row == 0 && col == 0 {
1838 mag
1839 } else if row < 2 && col < 2 {
1840 mag + 7
1841 } else {
1842 mag + 14
1843 }
1844}
1845
1846/// A level at a position that may fall off the transform, where the levels a
1847/// context reads are zero.
1848pub(super) fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
1849 if row >= side || col >= side {
1850 0
1851 } else {
1852 grid[row * side + col]
1853 }
1854}
1855
1856/// Shared by both DC writers: one level per block, none of them zero.
1857pub(super) fn check_levels(levels: &[i32], blocks: usize) -> Result<()> {
1858 if levels.len() != blocks {
1859 return Err(Error::unsupported(
1860 "AV1 tile",
1861 "a DC-only key frame needs one level per coded block",
1862 ));
1863 }
1864 if levels.iter().any(|&l| l == 0 || l.abs() > MAX_BR_LEVEL) {
1865 return Err(Error::unsupported(
1866 "AV1 tile",
1867 "a DC-only key frame is written for levels -14..=14 without zero; \
1868 wider levels need the Golomb tail",
1869 ));
1870 }
1871 Ok(())
1872}
1873
1874/// coeffs() for a luma transform block whose only coefficient is the DC (spec
1875/// 5.11.39). The block size is the transform size, so the all-zero flag's
1876/// context is 0; an end-of-block of one is token 0 of the position alphabet
1877/// with no extra bits; the transform sizes here are all DCT-only, so no
1878/// transform type is coded; and the DC's own neighbours are zero, so its
1879/// magnitude contexts are 0 throughout.
1880pub(super) fn write_dc_coeffs(
1881 enc: &mut SymbolEncoder,
1882 dc_level: i32,
1883 sign_ctx: usize,
1884 q_ctx: usize,
1885 txb_skip: &[u16],
1886 base_eob: &[u16],
1887) {
1888 use crate::cdf_state::pick;
1889 let level = dc_level.abs();
1890 let eob_pt = pick(
1891 q_ctx,
1892 cdf::EOB_PT_1024_LUMA_Q0,
1893 cdf::EOB_PT_1024_LUMA_Q1,
1894 cdf::EOB_PT_1024_LUMA,
1895 cdf::EOB_PT_1024_LUMA_Q3,
1896 );
1897 let br = pick(
1898 q_ctx,
1899 cdf::COEFF_BR_LUMA_32_Q0,
1900 cdf::COEFF_BR_LUMA_32_Q1,
1901 cdf::COEFF_BR_LUMA_32,
1902 cdf::COEFF_BR_LUMA_32_Q3,
1903 );
1904 enc.symbol_fixed(0, txb_skip);
1905 enc.symbol_fixed(0, &eob_pt);
1906 enc.symbol_fixed((level.min(NUM_BASE_LEVELS + 1) - 1) as usize, base_eob);
1907 if level > NUM_BASE_LEVELS {
1908 let mut remaining = level - (NUM_BASE_LEVELS + 1);
1909 let mut sent = 0;
1910 while sent < COEFF_BASE_RANGE {
1911 let k = remaining.min(BR_STEP);
1912 enc.symbol_fixed(k as usize, &br[0]);
1913 if k < BR_STEP {
1914 break;
1915 }
1916 remaining -= k;
1917 sent += BR_STEP;
1918 }
1919 }
1920 // The signs come after the levels, DC first (spec 5.11.39).
1921 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
1922}
1923
1924/// One 4x4 unit's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for a
1925/// positive DC, minus one for a negative one, nothing for a unit whose block
1926/// carried no DC or that sits past the frame's true edge (spec
1927/// `av1_set_entropy_contexts`), which is why the vote is gathered per 4x4
1928/// unit and not per coded cell -- a unit past the edge does not vote even
1929/// when the rest of its cell does.
1930pub(super) fn dc_vote(dc: Option<bool>) -> i32 {
1931 match dc {
1932 None => 0,
1933 Some(true) => -1,
1934 Some(false) => 1,
1935 }
1936}
1937
1938/// Which of the three DC sign contexts a gathered vote picks.
1939pub(super) fn dc_sign_ctx(vote: i32) -> usize {
1940 match vote.signum() {
1941 0 => 0,
1942 -1 => 1,
1943 _ => 2,
1944 }
1945}
1946
1947/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`,
1948/// `pred_common.c`): both neighbours' intra/inter state when both are
1949/// available, one neighbour's when only one is, and zero at a tile's own
1950/// top-left corner.
1951pub(crate) fn intra_inter_ctx(
1952 has_above: bool,
1953 has_left: bool,
1954 above_inter: bool,
1955 left_inter: bool,
1956) -> usize {
1957 match (has_above, has_left) {
1958 (true, true) => {
1959 let (above_intra, left_intra) = (!above_inter, !left_inter);
1960 if above_intra && left_intra {
1961 3
1962 } else {
1963 usize::from(above_intra || left_intra)
1964 }
1965 }
1966 (true, false) => 2 * usize::from(!above_inter),
1967 (false, true) => 2 * usize::from(!left_inter),
1968 (false, false) => 0,
1969 }
1970}
1971
1972/// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`
1973/// component's own bits start counting from; class zero starts at zero.
1974pub(super) fn mv_class_base(class: usize) -> i32 {
1975 if class == 0 { 0 } else { 2i32 << (class + 2) }
1976}
1977
1978/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse
1979/// of `mv_class_base`'s doubling ranges, ported from libaom's
1980/// `av1_get_mv_class` (`mv.h`).
1981pub(super) fn mv_class_of(z: i32) -> usize {
1982 let mut class = 0;
1983 while class < 10 && mv_class_base(class + 1) <= z {
1984 class += 1;
1985 }
1986 class
1987}
1988
1989/// Writes one motion vector component's non-zero diff (spec 5.11.32
1990/// `read_mv_component`, run backwards): sign, class, then the class's own
1991/// bits, and (lane-hpmv) the eighth-pel bit when the frame armed through
1992/// [`arm_high_precision_mv`] carries `allow_high_precision_mv`. Without that
1993/// flag the eighth-pel bit is inferred as one rather than coded, so only
1994/// diffs whose eighth-pel bit really is one are representable; anything else
1995/// is refused rather than rounded, since rounding would silently code a
1996/// different vector than the caller asked for.
1997///
1998/// # Errors
1999/// Returns an error when `diff` needs eighth-pel precision in a frame coded
2000/// without `allow_high_precision_mv`.
2001pub(super) fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
2002 debug_assert_ne!(diff, 0);
2003 let hp_frame = high_precision_mv();
2004 let sign = diff < 0;
2005 enc.symbol(usize::from(sign), &mut c.sign);
2006 let mag = diff.unsigned_abs() as i32;
2007 let z = mag - 1;
2008 if !hp_frame && z & 1 == 0 {
2009 return Err(Error::unsupported(
2010 "AV1 tile",
2011 "a motion vector component needs eighth-pel precision, which \
2012 allow_high_precision_mv off does not carry",
2013 ));
2014 }
2015 let class = mv_class_of(z);
2016 enc.symbol(class, &mut c.class);
2017 let local = z - mv_class_base(class);
2018 let hp = (local & 1) as usize;
2019 if class == 0 {
2020 let bit = (local >> 3) & 1;
2021 let fr = (local >> 1) & 3;
2022 enc.symbol(bit as usize, &mut c.class0_bit);
2023 enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]);
2024 // spec 5.11.32: the eighth-pel bit is CODED when the frame allows
2025 // high-precision motion vectors, and inferred as one otherwise ("if
2026 // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
2027 if hp_frame {
2028 enc.symbol(hp, &mut c.class0_hp);
2029 }
2030 } else {
2031 let d = local >> 3;
2032 let fr = (local >> 1) & 3;
2033 for i in 0..class {
2034 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
2035 }
2036 enc.symbol(fr as usize, &mut c.fr);
2037 if hp_frame {
2038 enc.symbol(hp, &mut c.hp);
2039 }
2040 }
2041 if hp_frame {
2042 HP_SYMBOLS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2043 if hp == 0 {
2044 HP_SYMBOLS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2045 }
2046 }
2047 Ok(())
2048}
2049
2050/// Writes a motion vector as a residual against `pred` (spec 5.11.32
2051/// `read_mv`): the joint symbol naming which components differ, then each
2052/// differing component.
2053pub(super) fn write_mv(
2054 enc: &mut SymbolEncoder,
2055 mv_comp: &mut [MvComponentCdfs; 2],
2056 mv_joint: &mut [u16; 5],
2057 mv: (i32, i32),
2058 pred: (i32, i32),
2059) -> Result<()> {
2060 let diff = (mv.0 - pred.0, mv.1 - pred.1);
2061 let joint = match (diff.0 != 0, diff.1 != 0) {
2062 (false, false) => 0, // MV_JOINT_ZERO
2063 (false, true) => 1, // MV_JOINT_HNZVZ: column only
2064 (true, false) => 2, // MV_JOINT_HZVNZ: row only
2065 (true, true) => 3, // MV_JOINT_HNZVNZ
2066 };
2067 enc.symbol(joint, mv_joint);
2068 if diff.0 != 0 {
2069 write_mv_component(enc, &mut mv_comp[0], diff.0)?;
2070 }
2071 if diff.1 != 0 {
2072 write_mv_component(enc, &mut mv_comp[1], diff.1)?;
2073 }
2074 Ok(())
2075}
2076
2077/// What a block leaves in the neighbour reference bands: its own reference,
2078/// or `-1` when it is intra (decode.rs `Neighbours::above_ref`'s convention).
2079pub(super) fn block_ref(block: &BlockCoeffs) -> i8 {
2080 block.inter.map_or(-1, |i| i.ref_frame)
2081}
2082
2083/// Writer-side counterpart of decode.rs `read_single_ref` (spec 5.11.25's
2084/// `single_ref_p1`..`p6` tree): codes `ref_frame` bit by bit, each symbol at
2085/// the context its own `single_ref_p*_ctx` derives from the immediate
2086/// above/left neighbours' references -- the same functions the decoder calls,
2087/// with `-1` standing for an intra or unavailable neighbour and no second
2088/// reference (this writer codes no compound block).
2089pub(super) fn write_single_ref(
2090 enc: &mut SymbolEncoder,
2091 cdfs: &mut Cdfs,
2092 ref_frame: i8,
2093 above_ref: i8,
2094 above_ref1: Option<i8>,
2095 left_ref: i8,
2096 left_ref1: Option<i8>,
2097) {
2098 REF_HITS[(ref_frame.max(1) - 1) as usize % 7]
2099 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2100 use crate::mvstack::{
2101 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
2102 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
2103 single_ref_p5_ctx, single_ref_p6_ctx,
2104 };
2105 let above = (above_ref > 0).then_some(above_ref);
2106 let left = (left_ref > 0).then_some(left_ref);
2107 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
2108 // neighbour's references (decode.rs `read_single_ref`'s own
2109 // `above_ref1`/`left_ref1`): dropping the second one reads a different
2110 // context row for every block sitting under a compound neighbour, and so
2111 // decodes a different reference NAME.
2112 let backward = ref_frame >= BWDREF_FRAME;
2113 enc.symbol(
2114 usize::from(backward),
2115 &mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0],
2116 );
2117 if backward {
2118 let is_altref = ref_frame == ALTREF_FRAME;
2119 enc.symbol(
2120 usize::from(is_altref),
2121 &mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1],
2122 );
2123 if !is_altref {
2124 enc.symbol(
2125 usize::from(ref_frame == ALTREF2_FRAME),
2126 &mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5],
2127 );
2128 }
2129 return;
2130 }
2131 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
2132 enc.symbol(
2133 usize::from(far),
2134 &mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2],
2135 );
2136 if far {
2137 enc.symbol(
2138 usize::from(ref_frame == GOLDEN_FRAME),
2139 &mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4],
2140 );
2141 } else {
2142 enc.symbol(
2143 usize::from(ref_frame == LAST2_FRAME),
2144 &mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3],
2145 );
2146 }
2147}
2148
2149/// Per-mode fire counts of [`write_inter_mode`], indexed
2150/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block
2151/// coded (bucket 3 collects any index past 2). Read by the BD gate, which
2152/// is the only thing that proves a newly added mode ever fires
2153/// (gate-blind-to-feature).
2154pub(super) static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [
2155 std::sync::atomic::AtomicUsize::new(0),
2156 std::sync::atomic::AtomicUsize::new(0),
2157 std::sync::atomic::AtomicUsize::new(0),
2158 std::sync::atomic::AtomicUsize::new(0),
2159];
2160pub(super) static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [
2161 std::sync::atomic::AtomicUsize::new(0),
2162 std::sync::atomic::AtomicUsize::new(0),
2163 std::sync::atomic::AtomicUsize::new(0),
2164 std::sync::atomic::AtomicUsize::new(0),
2165];
2166
2167/// One counter per reference name (`LAST`..`ALTREF`), for the gate's own
2168/// census of what the encoder actually picks.
2169pub(super) static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [
2170 std::sync::atomic::AtomicUsize::new(0),
2171 std::sync::atomic::AtomicUsize::new(0),
2172 std::sync::atomic::AtomicUsize::new(0),
2173 std::sync::atomic::AtomicUsize::new(0),
2174 std::sync::atomic::AtomicUsize::new(0),
2175 std::sync::atomic::AtomicUsize::new(0),
2176 std::sync::atomic::AtomicUsize::new(0),
2177];
2178
2179/// Takes and clears the per-reference histogram.
2180#[cfg(test)]
2181pub(crate) fn take_ref_hits() -> [usize; 7] {
2182 std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2183}
2184
2185/// Bumps the two histograms for one coded inter block.
2186/// How many blocks this process wrote whose search-chosen `ref_mv_idx` the
2187/// write-time stack could not carry, so the writer signalled a SMALLER index
2188/// (lane-sb128b). Every one of these used to price its residual against a
2189/// predictor the decoder never derives.
2190pub(super) static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2191
2192/// Counts one clamped DRL index whose predictor differs from the one the
2193/// search asked for -- the harmful case, and the only one a witness can see.
2194pub(super) fn note_drl_clamp(target: usize, signalled: usize, entries: usize) {
2195 DRL_CLAMP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2196 if crate::envflags::env_flag!("EC_AV1_TRACE") {
2197 eprintln!("DRL_CLAMP target={target} signalled={signalled} entries={entries}");
2198 }
2199}
2200
2201/// Reads [`DRL_CLAMP_HITS`] -- the tripwire for the DRL owner's fix. It is
2202/// provably zero while `every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`
2203/// (encode.rs) holds: the pricer never offers an index this walk cannot signal,
2204/// so no clip can move it (lane-av1recipehunt, 153 attempts, plus a mutation
2205/// proof that widening the pricer's offer set does). The clip gate that used
2206/// to wait on it is deleted; this counter stays so that widening the pricer
2207/// is loud instead of silent. `EC_AV1_TRACE=1` prints each hit.
2208pub fn drl_clamp_hits() -> usize {
2209 DRL_CLAMP_HITS.load(std::sync::atomic::Ordering::Relaxed)
2210}
2211
2212pub(super) fn note_inter_mode(mode: usize, drl: usize) {
2213 INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2214 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2215}
2216
2217/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW).
2218#[cfg(test)]
2219pub(crate) fn take_inter_mode_hits() -> [usize; 4] {
2220 [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2221}
2222
2223/// Takes and clears the DRL-index histogram (0, 1, 2, 3+).
2224#[cfg(test)]
2225pub(crate) fn take_drl_hits() -> [usize; 4] {
2226 [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2227}
2228
2229/// Writes the DRL index of one block: the loop the decoder runs (spec
2230/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
2231/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
2232/// stop, at most two bits. `drl_ctx[idx]` is the context between
2233/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses
2234/// between. Returns the index the symbols actually SIGNAL, which is `target`
2235/// clamped by the stack (`min(target, start + 2, entries.len() - 1)`): the
2236/// decoder derives its predictor from THAT index, so every caller must take
2237/// its own base MV from the returned value and not from `target` (lane-sb128b:
2238/// a search-chosen `ref_mv_idx` of 2 against a two-entry write-time stack
2239/// signalled index 1 and priced the residual against `pred_mv`, and the
2240/// decoder's MV silently drifted a whole frame before the drl symbols
2241/// desynced).
2242/// The DRL index [`write_drl_idx`]'s walk can actually SIGNAL against a stack
2243/// of `entries` candidates: at most two `drl_mode` symbols past `start`, and
2244/// each one needs a further entry to advance into (spec 5.11.24's
2245/// `for (idx = 0; idx < 2; idx++) if (NumMvFound > idx + 1)`).
2246///
2247/// A search that offers an index this clamps prices its residual against a
2248/// predictor the decoder never derives (lane-sb128b's silent MV drift); the
2249/// pricer's own offer set is enumerated against this rule by
2250/// `crate::encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`.
2251pub(crate) fn signalled_drl_idx(entries: usize, start: usize, target: usize) -> usize {
2252 target
2253 .min(start + 2)
2254 .min(entries.saturating_sub(1))
2255 .max(start)
2256}
2257
2258pub(super) fn write_drl_idx(
2259 enc: &mut SymbolEncoder,
2260 cdfs: &mut Cdfs,
2261 stack: &crate::mvstack::MvStack,
2262 start: usize,
2263 target: usize,
2264) -> usize {
2265 debug_assert_eq!(
2266 signalled_drl_idx(stack.entries.len(), start, target),
2267 {
2268 let mut i = start;
2269 while i < start + 2 && stack.entries.len() > i + 1 && i < target {
2270 i += 1;
2271 }
2272 i
2273 },
2274 "the drl clamp rule and the writer's own walk disagree",
2275 );
2276 let mut idx = start;
2277 while idx < start + 2 && stack.entries.len() > idx + 1 {
2278 let advance = idx < target;
2279 enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]);
2280 if !advance {
2281 return idx;
2282 }
2283 idx += 1;
2284 }
2285 idx
2286}
2287
2288/// Writer-side counterpart of the decoder's single-reference
2289/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s
2290/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV
2291/// residual against the DRL-selected predictor. Returns the motion vector
2292/// the decoder will derive for the block (what the MI grid must record) and
2293/// whether it is `NEWMV`.
2294///
2295/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global
2296/// motion parameters at all, so every `gm_get_motion_vector` the decoder
2297/// runs is the identity model's zero vector; a lane that starts writing
2298/// real `gm_params` has to feed the same vector in here.
2299///
2300/// # Errors
2301/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision.
2302pub(super) fn write_inter_mode(
2303 enc: &mut SymbolEncoder,
2304 cdfs: &mut Cdfs,
2305 info: InterInfo,
2306 stack: &crate::mvstack::MvStack,
2307) -> Result<((i32, i32), bool)> {
2308 let idx = usize::from(info.ref_mv_idx);
2309 if info.mode.compound_index().is_some() {
2310 return Err(Error::unsupported(
2311 "AV1 tile",
2312 "a compound mode is written by `write_compound_block`, not here",
2313 ));
2314 }
2315 match info.mode {
2316 InterMode::NewMv => {
2317 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
2318 let signalled = write_drl_idx(enc, cdfs, stack, 0, idx);
2319 let base = stack.entries.get(signalled).map_or(stack.pred_mv, |e| e.mv);
2320 if signalled != idx && base != stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv) {
2321 note_drl_clamp(idx, signalled, stack.entries.len());
2322 }
2323 let idx = signalled;
2324 write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?;
2325 note_inter_mode(3, idx);
2326 Ok((info.mv, true))
2327 }
2328 InterMode::GlobalMv => {
2329 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
2330 enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV
2331 note_inter_mode(2, 0);
2332 Ok(((0, 0), false))
2333 }
2334 InterMode::NearestMv => {
2335 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
2336 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
2337 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
2338 note_inter_mode(0, 0);
2339 Ok((stack.nearest_mv, false))
2340 }
2341 InterMode::NearMv => {
2342 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
2343 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
2344 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV
2345 // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24).
2346 let idx = idx.max(1);
2347 let signalled = write_drl_idx(enc, cdfs, stack, 1, idx);
2348 let mv = stack.entries.get(signalled).map_or(stack.near_mv, |e| e.mv);
2349 if signalled != idx && mv != stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) {
2350 note_drl_clamp(idx, signalled, stack.entries.len());
2351 }
2352 let idx = signalled;
2353 note_inter_mode(1, idx);
2354 Ok((mv, false))
2355 }
2356 _ => unreachable!("compound modes are refused above"),
2357 }
2358}
2359
2360/// Writes the payload of a one-tile inter frame built from `blocks`, one
2361/// 32x32 block per entry in raster order across the frame — every superblock
2362/// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
2363/// codes a key frame, because a mixed-size partition tree buys this writer's
2364/// gate nothing a flat grid does not already prove: the CDF state, the
2365/// neighbour contexts and the single-reference/MV-stack machinery below are
2366/// exactly as size-sensitive whether the tree recurses or not, and recursing
2367/// it would be undirected scaffolding — see `sb_coeff_key_frame_tile` for
2368/// where that tree already lives, ready to graft this block's mode reads
2369/// onto once a real partition search needs it.
2370///
2371/// A block whose [`BlockCoeffs::inter`] is `Some` is coded inter: `skip`,
2372/// then `is_inter`, then a single-reference chain that always names `LAST`
2373/// (spec 5.11.25 `single_ref_p1`/`p3`/`p4`, this crate's only reference so
2374/// far), then the two-mode `read_inter_mode` chain (spec 5.11.24) and, for
2375/// [`InterMode::NewMv`], a DRL index (always zero) and a coded motion vector
2376/// residual. A block whose `inter` is `None` codes intra, through the
2377/// *inter*-frame intra path (spec 5.11.16's `intra_frame_mode_info` is the
2378/// key frame writers' path; this is `inter_frame_mode_info`'s intra branch):
2379/// `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour context, since
2380/// an inter frame's intra blocks do not read their neighbours' modes.
2381///
2382/// # Errors
2383/// Returns an error when the frame is not a whole number of 64x64
2384/// superblocks, when `blocks` does not carry exactly one entry per 32x32
2385/// block, when an intra block names a mode a key frame does not code, when a
2386/// coefficient sits outside its transform or is one the writer cannot code,
2387/// when a `NEWMV` block's motion vector needs eighth-pel precision.
2388pub fn sb_coeff_inter_frame_tile(
2389 mi_cols: u32,
2390 mi_rows: u32,
2391 base_q_idx: u8,
2392 blocks: &[Quadrant],
2393) -> Result<Vec<u8>> {
2394 sb_coeff_inter_frame_tile_tx(mi_cols, mi_rows, base_q_idx, blocks, false)
2395}
2396
2397/// [`sb_coeff_inter_frame_tile`] for a frame header carrying
2398/// `tx_mode == TxMode::Select`: every block then codes the transform syntax
2399/// [`write_tx_syntax_inter`] writes -- one `txfm_split` flag on an inter
2400/// block that carries a residual, a `tx_depth` symbol on an intra one -- and
2401/// an intra block whose depth is nonzero codes its luma as several transform
2402/// units. With `tx_select` false this writes exactly the stream it always did.
2403///
2404/// # Errors
2405/// As [`sb_coeff_inter_frame_tile`].
2406pub fn sb_coeff_inter_frame_tile_tx(
2407 mi_cols: u32,
2408 mi_rows: u32,
2409 base_q_idx: u8,
2410 blocks: &[Quadrant],
2411 tx_select: bool,
2412) -> Result<Vec<u8>> {
2413 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
2414 sb_coeff_inter_frame_tile_cdfs(
2415 mi_cols,
2416 mi_rows,
2417 base_q_idx,
2418 blocks,
2419 tx_select,
2420 &mut cdfs,
2421 TileRect::whole(mi_cols, mi_rows),
2422 &mut MiGrid::new(mi_cols as usize, mi_rows as usize),
2423 )
2424}
2425
2426/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
2427/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`].
2428///
2429/// # Errors
2430/// As [`sb_coeff_inter_frame_tile_tx`].
2431// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
2432#[allow(clippy::too_many_arguments)]
2433pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
2434 mi_cols: u32,
2435 mi_rows: u32,
2436 _base_q_idx: u8,
2437 blocks: &[Quadrant],
2438 tx_select: bool,
2439 cdfs: &mut Cdfs,
2440 // This tile's own span; see [`sb_coeff_key_frame_tile_cdfs`].
2441 tile: TileRect,
2442 // The frame's MV grid, carried across the frame's tiles by the caller
2443 // (see the comment at `set_tile_bounds` below).
2444 grid: &mut MiGrid,
2445) -> Result<Vec<u8>> {
2446 // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
2447 let _cdef_idx = CdefIdxGuard;
2448 check_blocks(mi_cols, mi_rows)?;
2449 // `block_grid`'s ceiling, not a plain division: a true frame size that is
2450 // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has
2451 // one more block/superblock whose own origin is inside the true frame,
2452 // same as `sb_coeff_key_frame_tile`.
2453 let (cols, rows) = block_grid(mi_cols, mi_rows);
2454 if blocks.len() != (cols * rows) as usize {
2455 return Err(Error::unsupported(
2456 "AV1 tile",
2457 "an inter frame needs one entry per 32x32 block inside the true frame",
2458 ));
2459 }
2460 let coded: Vec<&BlockCoeffs> = blocks.iter().flat_map(Quadrant::blocks).collect();
2461 if let Some(bad) = coded
2462 .into_iter()
2463 .find(|b| b.inter.is_none() && usize::from(b.mode) >= INTRA_MODES)
2464 {
2465 return Err(Error::unsupported(
2466 "AV1 tile",
2467 format!(
2468 "intra mode {} is not one of the thirteen this writer codes",
2469 bad.mode
2470 ),
2471 ));
2472 }
2473
2474 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only
2475 /// size this writer's inter branch codes.
2476 const SIZE_GROUP_32: usize = 3;
2477
2478 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
2479 let mut neighbours = Neighbours::new(
2480 cols as usize * 2,
2481 rows as usize * 2,
2482 mi_cols as usize,
2483 mi_rows as usize,
2484 );
2485 neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize);
2486 // The MV grid spans the FRAME and carries every tile written before this
2487 // one, exactly as a decoder's does (`decode_inter_frame_tile_with_cdfs`
2488 // keeps one grid for the whole frame and narrows its read window per
2489 // tile): the tile bounds below are what stops a candidate scan reaching
2490 // across the boundary, and a grid that was merely empty out there would
2491 // not read the same as the decoder's wherever a scan reads the array
2492 // without asking `MiGrid::get` first.
2493 let grid = &mut *grid;
2494 grid.set_tile_bounds(
2495 tile.mi_row0 as usize,
2496 tile.mi_col0 as usize,
2497 tile.mi_row1 as usize,
2498 tile.mi_col1 as usize,
2499 );
2500 grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get));
2501 let mut enc = SymbolEncoder::new();
2502 // An `is_inter` block's 32x32 luma transform reads a different
2503 // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see
2504 // `TxbSet::Luma32Inter`'s doc comment); chroma's transform type is
2505 // derived from luma's, not coded, so it never differs between the two.
2506 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
2507 let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16];
2508 // A 64x64 root's planes (lane-tx64): TX_64X64 luma -- DCT-only at this
2509 // size for an inter block too (spec `av1_get_ext_tx_set_type` returns
2510 // `TX_SET_DCTONLY` for `tx_size_sqr_up == TX_64X64`), so `Luma64` carries
2511 // no `tx_type` symbol and there is no `Luma64Inter` to write -- and one
2512 // TX_32X32 per chroma plane.
2513 let sb64_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
2514 let scan32 = default_scan(TX32);
2515 let scan16 = default_scan(TX16);
2516 let scan8 = default_scan(TX8);
2517 let scan4 = default_scan(TX4);
2518 // The same four tables again as one array, which is what the per-unit
2519 // luma writer indexes by transform side.
2520 let all_scans = [scan32.clone(), scan16.clone(), scan8.clone(), scan4.clone()];
2521 let zero_grids = [
2522 vec![0i32; TX32 * TX32],
2523 vec![0i32; TX16 * TX16],
2524 vec![0i32; TX16 * TX16],
2525 ];
2526
2527 let sb128 = sb128_armed();
2528 // lane-b128: set at a root whose own `PARTITION_NONE` 128x128 block was
2529 // just written, so the root's remaining 64x64 cells code nothing.
2530 let mut sb128_none = false;
2531 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
2532 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
2533 // and partition symbol first; at a 64 one this is plain raster and every
2534 // cell is its own superblock, i.e. byte-identical to the loop before.
2535 for (sb_r, sb_c, row_start, sb_start) in sb_write_order(
2536 tile.sb_row0,
2537 tile.sb_row1.min(sb_rows),
2538 tile.sb_col0,
2539 tile.sb_col1.min(sb_cols),
2540 sb128,
2541 ) {
2542 if row_start {
2543 neighbours.start_row();
2544 }
2545 if sb_start {
2546 sb128_none = false;
2547 }
2548 // lane-b128: the remaining three 64x64 cells of a root the search
2549 // left WHOLE carry no syntax at all -- the same skip the decoder's
2550 // own `sb128_none` runs.
2551 if sb128_none {
2552 continue;
2553 }
2554 if sb128 && sb_start {
2555 // The 128x128 block a `PARTITION_NONE` root carries, held by the
2556 // top-left 32x32 entry of the root's sixteen.
2557 let root_entry = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols)
2558 .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize]);
2559 let root_block = root_entry.and_then(|q| match q {
2560 Quadrant::Whole128(block) => Some(block),
2561 _ => None,
2562 });
2563 // lane-b128hv: the two rectangular halves a HORZ/VERT root carries.
2564 let root_rect = root_entry.and_then(|q| match q {
2565 Quadrant::Rect128(horz, halves) => Some((*horz, halves)),
2566 _ => None,
2567 });
2568 // lane-ab128: the three pieces an AB-shape root carries, and the
2569 // partition symbol it is coded under.
2570 let root_ab = root_entry.and_then(|q| match q {
2571 Quadrant::Ab128(symbol, pieces) => Some((*symbol as usize, pieces)),
2572 _ => None,
2573 });
2574 write_sb128_root(
2575 &mut enc,
2576 cdfs,
2577 &neighbours,
2578 sb_r,
2579 sb_c,
2580 mi_cols,
2581 mi_rows,
2582 match (root_block.is_some(), root_rect, root_ab) {
2583 (true, ..) => PARTITION_NONE,
2584 (_, Some((true, _)), _) => PARTITION_HORZ,
2585 (_, Some((false, _)), _) => PARTITION_VERT,
2586 (_, _, Some((symbol, _))) => symbol,
2587 _ => PARTITION_SPLIT,
2588 },
2589 );
2590 if let Some(block) = root_block {
2591 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
2592 write_inter_block_128(
2593 &mut enc,
2594 cdfs,
2595 &mut neighbours,
2596 grid,
2597 at128,
2598 block,
2599 mi_cols,
2600 mi_rows,
2601 tx_select,
2602 )?;
2603 sb128_none = true;
2604 continue;
2605 }
2606 if let Some((horz, halves)) = root_rect {
2607 // libaom `decode_partition` at BLOCK_128X128: `subsize` at
2608 // (mi_row, mi_col) and a second one at + hbs (16 mi) along the
2609 // cut axis, the second only when it is inside the frame -- the
2610 // search only offers a root wholly inside, so both are.
2611 let base_mi = (
2612 (sb_r & !1) as usize * SB_MI as usize,
2613 (sb_c & !1) as usize * SB_MI as usize,
2614 );
2615 let (w, h) = if horz { (128usize, 64usize) } else { (64, 128) };
2616 for (i, half) in halves.iter().enumerate() {
2617 let at_mi = if horz {
2618 (base_mi.0 + i * 16, base_mi.1)
2619 } else {
2620 (base_mi.0, base_mi.1 + i * 16)
2621 };
2622 write_inter_block_128_rect(
2623 &mut enc,
2624 cdfs,
2625 &mut neighbours,
2626 grid,
2627 at_mi,
2628 (w, h),
2629 half,
2630 mi_cols,
2631 mi_rows,
2632 tx_select,
2633 )?;
2634 }
2635 sb128_none = true;
2636 continue;
2637 }
2638 if let Some((symbol, pieces)) = root_ab {
2639 // libaom `decode_partition` at BLOCK_128X128, AB arm: two
2640 // 64x64 blocks and one 128x64 / 64x128 half, in the order
2641 // decode.rs' `sb128_ab` reads them
2642 // ([`crate::encode::ab128_pieces`]). An AB shape only comes
2643 // from the full alphabet symbol (both halves in frame), so
2644 // there is no edge break to mirror -- the search offers one
2645 // only at a root wholly inside.
2646 let base_mi = (
2647 (sb_r & !1) as usize * SB_MI as usize,
2648 (sb_c & !1) as usize * SB_MI as usize,
2649 );
2650 for (((mi_r, mi_c), (w, h)), piece) in crate::encode::ab128_pieces(symbol, base_mi)
2651 .iter()
2652 .zip(pieces)
2653 {
2654 write_inter_block_128_rect(
2655 &mut enc,
2656 cdfs,
2657 &mut neighbours,
2658 grid,
2659 (*mi_r, *mi_c),
2660 (*w, *h),
2661 piece,
2662 mi_cols,
2663 mi_rows,
2664 tx_select,
2665 )?;
2666 }
2667 SB128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2668 sb128_none = true;
2669 continue;
2670 }
2671 }
2672 {
2673 if !sb128 {
2674 write_lr(&mut enc, cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W);
2675 }
2676 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
2677 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
2678 // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock
2679 // whose bottom or right half falls outside the true frame cannot
2680 // be left whole, so the only question there is which of the three
2681 // partition symbols the split takes — same three-way signaling as
2682 // `sb_coeff_key_frame_tile`'s superblock level.
2683 let (has_cols, has_rows) = (
2684 sb_c * SB_MI + SB_MI / 2 < mi_cols,
2685 sb_r * SB_MI + SB_MI / 2 < mi_rows,
2686 );
2687 // lane-b64: a superblock the search left WHOLE — one 64x64 block
2688 // at `PARTITION_NONE`, carried by its top-left quadrant's entry
2689 // ([`Quadrant::Whole64`]). Single-reference; skipped, or with a
2690 // real residual through `TxbSet::Luma64` + two `Chroma32`
2691 // (lane-tx64).
2692 let sb64 = ((sb_r * 2) < rows && (sb_c * 2) < cols)
2693 .then(|| &blocks[((sb_r * 2) * cols + sb_c * 2) as usize])
2694 .and_then(|q| match q {
2695 Quadrant::Whole64(block) => Some(block),
2696 _ => None,
2697 });
2698 if let Some(block) = sb64 {
2699 if !has_cols || !has_rows {
2700 return Err(Error::unsupported(
2701 "AV1 tile",
2702 "a superblock that is half outside the true frame cannot be left whole",
2703 ));
2704 }
2705 let info = block.inter.ok_or_else(|| {
2706 Error::unsupported("AV1 tile", "a 64x64 root block is coded inter")
2707 })?;
2708 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[sb_ctx]);
2709 let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
2710 let has_above = neighbours.has_above(mi_r);
2711 let has_left = neighbours.has_left(mi_c);
2712 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
2713 + usize::from(neighbours.left_skip[mi_r]);
2714 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
2715 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
2716 write_delta_q(
2717 &mut enc,
2718 cdfs,
2719 (mi_r, mi_c),
2720 !sb128_armed(),
2721 block.skip,
2722 );
2723 let ii_ctx = intra_inter_ctx(
2724 has_above,
2725 has_left,
2726 neighbours.above_inter[mi_c],
2727 neighbours.left_inter[mi_r],
2728 );
2729 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
2730 write_comp_mode(
2731 &mut enc,
2732 cdfs,
2733 &neighbours,
2734 (mi_r, mi_c),
2735 (has_above, has_left),
2736 info.ref1.is_some(),
2737 );
2738 // lane-b64b: a COMPOUND 64x64 root takes the same mode chain
2739 // every other compound block does, at this superblock's own
2740 // 16x16-mi window.
2741 let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
2742 write_compound_block(
2743 &mut enc,
2744 cdfs,
2745 &neighbours,
2746 grid,
2747 (mi_r, mi_c),
2748 (SB_MI as usize, SB_MI as usize),
2749 (has_above, has_left),
2750 info,
2751 (mi_cols as usize, mi_rows as usize),
2752 )?
2753 } else {
2754 write_single_ref(
2755 &mut enc,
2756 cdfs,
2757 info.ref_frame,
2758 neighbours.above_ref[mi_c],
2759 neighbours.above_ref1[mi_c],
2760 neighbours.left_ref[mi_r],
2761 neighbours.left_ref1[mi_r],
2762 );
2763 let stack = find_mv_stack(
2764 grid,
2765 mi_r,
2766 mi_c,
2767 SB_MI as usize,
2768 SB_MI as usize,
2769 info.ref_frame,
2770 mi_cols as usize,
2771 mi_rows as usize,
2772 );
2773 let (mv, is_new_mv) = write_inter_mode(&mut enc, cdfs, info, &stack)?;
2774 if crate::msac::symtrace::dir().is_some() {
2775 crate::msac::symtrace::note(&format!(
2776 " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
2777 info.mode, info.ref_mv_idx, info.mv
2778 ));
2779 }
2780 (mv, (0, 0), is_new_mv)
2781 };
2782 for dr in 0..SB_MI as usize {
2783 for dc in 0..SB_MI as usize {
2784 grid.set(
2785 mi_r + dr,
2786 mi_c + dc,
2787 MiInfo {
2788 is_inter: true,
2789 ref_frame: info.ref_frame,
2790 ref_frame1: info.ref1.unwrap_or(NO_REF1),
2791 mv1: mv16(mv1),
2792 mv: mv16(mv),
2793 is_new_mv,
2794 size: SB_MI as u8,
2795 size_h: SB_MI as u8,
2796 is_global_mv0: false,
2797 is_global_mv1: false,
2798 },
2799 );
2800 }
2801 }
2802 if info.ref1.is_none() {
2803 // libaom's `motion_mode_allowed` fails on a compound
2804 // block, so the decoder reads no symbol for one.
2805 write_motion_mode(
2806 &mut enc,
2807 cdfs,
2808 grid,
2809 (mi_r, mi_c),
2810 (SB_MI as usize, SB_MI as usize),
2811 (SB, SB),
2812 (mi_cols as usize, mi_rows as usize),
2813 info.ref_frame,
2814 block.motion_mode,
2815 )?;
2816 }
2817 if tx_select {
2818 // A skipped inter block writes no `txfm_split` at all --
2819 // that call only publishes the max transform size the
2820 // reader infers for it; an unskipped one writes the
2821 // `txfm_split` flag: 0 when the root's luma is one whole
2822 // TX_64X64, 1 when it is the four TX_32X32 units
2823 // lane-b64b's var-tx arm chose.
2824 write_tx_syntax_inter(
2825 &mut enc,
2826 cdfs,
2827 &mut neighbours,
2828 (mi_r, mi_c),
2829 SB,
2830 true,
2831 block.skip,
2832 usize::from(block.tx_depth),
2833 );
2834 }
2835 if block.skip {
2836 neighbours.record(sb_at, SB, 0, &zero_grids);
2837 } else {
2838 // lane-tx64: the 64x64 root's real residual. Luma is one
2839 // TX_64X64 whose coded quarter is a 32x32 level grid
2840 // (`TxbSet::Luma64`, `TX32`'s own scan -- the same pair
2841 // `sb_coeff_key_frame_tile`'s `Superblock::Whole` writes),
2842 // chroma one whole TX_32X32 per plane, and `split` is
2843 // false because the luma transform covers the block.
2844 // lane-b64b: at `txfm_split = 1` the luma levels arrive in
2845 // 64x64 block coordinates and are written as the four
2846 // TX_32X32 units `write_luma_tus` slices out, each
2847 // publishing its own coefficient context before the next
2848 // one reads it; chroma is one TX_32X32 per plane either
2849 // way.
2850 let split = block.tx_depth == 1;
2851 let grids = [
2852 level_grid(&block.luma, if split { SB } else { TX32 })?,
2853 level_grid(&block.u, TX32)?,
2854 level_grid(&block.v, TX32)?,
2855 ];
2856 if split {
2857 write_luma_tus(
2858 &mut enc,
2859 cdfs,
2860 &mut neighbours,
2861 (mi_r, mi_c),
2862 SB,
2863 TX32,
2864 &grids[0],
2865 0,
2866 &all_scans,
2867 true,
2868 &block.luma_tx_types,
2869 )?;
2870 }
2871 write_block_planes(
2872 &mut enc,
2873 cdfs,
2874 &sb64_planes,
2875 &grids,
2876 &[&scan32, &scan32, &scan32],
2877 &neighbours.around(sb_at, SB),
2878 0,
2879 split,
2880 block_tx_type(block),
2881 true,
2882 );
2883 neighbours.record_planes(sb_at, SB, 0, &grids, !split);
2884 }
2885 neighbours.record_inter(sb_at, SB, block.skip, true, block_ref(block));
2886 record_block_compound(&mut neighbours, (mi_r, mi_c), SB, block);
2887 continue;
2888 }
2889 match (has_cols, has_rows) {
2890 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]),
2891 (true, false) => {
2892 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
2893 }
2894 (false, true) => {
2895 enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
2896 }
2897 (false, false) => {}
2898 }
2899
2900 for quadrant in 0..4 {
2901 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
2902 // Only a quadrant whose own mi origin is inside the true
2903 // frame is coded at all (spec `decode_partition`'s
2904 // `r >= MiRows || c >= MiCols` early return), same filter as
2905 // `sb_coeff_key_frame_tile`'s `quadrant_positions`.
2906 if r32 >= rows || c32 >= cols {
2907 continue;
2908 }
2909 let site = &blocks[(r32 * cols + c32) as usize];
2910 let at = (r32 as usize * 2, c32 as usize * 2);
2911 let ctx32 = neighbours.partition_ctx(at, BLOCK);
2912 // spec `decode_partition`'s hasRows/hasCols recomputed at this
2913 // quadrant's own half: a whole 32x32 block cannot be left
2914 // whole once its own half straddles the true edge, mirroring
2915 // `sb_coeff_key_frame_tile`'s "cannot be left whole" refusal.
2916 let (has_cols32, has_rows32) = (
2917 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
2918 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
2919 );
2920 let block = match site {
2921 // Already coded by the `Whole64` above -- but only inside
2922 // a superblock that really carried one.
2923 Quadrant::Whole64(_)
2924 | Quadrant::Whole128(_)
2925 | Quadrant::Rect128(..)
2926 | Quadrant::Ab128(..)
2927 | Quadrant::Covered => {
2928 return Err(Error::unsupported(
2929 "AV1 tile",
2930 "a `Whole64`/`Covered` quadrant needs its superblock's \
2931 top-left entry to be the `Whole64`",
2932 ));
2933 }
2934 Quadrant::Whole(block) => {
2935 if !has_cols32 || !has_rows32 {
2936 return Err(Error::unsupported(
2937 "AV1 tile",
2938 "a 32x32 block that is half outside the true frame \
2939 cannot be left whole",
2940 ));
2941 }
2942 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]);
2943 block
2944 }
2945 Quadrant::Split(sub_blocks) => {
2946 // Same filter as `sb_coeff_key_frame_tile`'s
2947 // `sub_positions`: only the 16x16 leaves whose own mi
2948 // origin is inside the true frame are coded.
2949 let sub_positions: Vec<(usize, usize)> = (0..4)
2950 .map(|i| (r32 as usize * 2 + i / 2, c32 as usize * 2 + i % 2))
2951 .filter(|&(sr, sc)| {
2952 (sr as u32) * SUB_MI < mi_rows && (sc as u32) * SUB_MI < mi_cols
2953 })
2954 .collect();
2955 if sub_blocks.len() != sub_positions.len() {
2956 return Err(Error::unsupported(
2957 "AV1 tile",
2958 "a split 32x32 inter-frame block needs one 16x16 entry \
2959 per sub-block inside the true frame",
2960 ));
2961 }
2962 // Same three-way spec signaling as the superblock
2963 // level above, recomputed at this quadrant's own half.
2964 match (has_cols32, has_rows32) {
2965 (true, true) => {
2966 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx32]);
2967 }
2968 (true, false) => {
2969 enc.symbol_fixed(
2970 1,
2971 &gather(&cdfs.partition_w32[ctx32], VERT_ALIKE),
2972 );
2973 }
2974 (false, true) => {
2975 enc.symbol_fixed(
2976 1,
2977 &gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE),
2978 );
2979 }
2980 (false, false) => {}
2981 }
2982 for (leaf, (sr, sc)) in sub_blocks.iter().zip(sub_positions) {
2983 // A 16x16 leaf whose own half straddles the true
2984 // frame edge splits into the 8x8 leaves that are
2985 // inside it (lane-av1inter8), same split the key
2986 // frame search takes at this geometry -- on both
2987 // axes too, where `decode_partition` infers the
2988 // split and reads no symbol at all
2989 // (lane-av1rect).
2990 let (has_cols16, has_rows16) = (
2991 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
2992 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
2993 );
2994 let at16 = (sr, sc);
2995 if has_cols16 && has_rows16 {
2996 let ctx16 = neighbours.partition_ctx(at16, SUB);
2997 // A 16x16 leaf wholly inside the frame that
2998 // carries `eight` split itself further, on
2999 // cost rather than on geometry (lane-av1rd2):
3000 // spec PARTITION_SPLIT at BLOCK_16X16, then
3001 // the same four 8x8 leaves the straddling
3002 // branch below writes -- all four inside, so
3003 // the partition symbol is a real one rather
3004 // than the edge's gathered flag.
3005 if let Some(leaves) = &leaf.eight {
3006 if leaves.len() != 4 {
3007 return Err(Error::unsupported(
3008 "AV1 tile",
3009 "a 16x16 inter-frame block inside the frame that splits needs all four 8x8 leaves",
3010 ));
3011 }
3012 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w16[ctx16]);
3013 let (mi_row0, mi_col0) =
3014 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
3015 for (i, leaf8) in leaves.iter().enumerate() {
3016 let leaf_mi = (
3017 (mi_row0 + (i as u32 / 2) * 2) as usize,
3018 (mi_col0 + (i as u32 % 2) * 2) as usize,
3019 );
3020 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
3021 enc.symbol(
3022 PARTITION_NONE,
3023 &mut cdfs.partition_w8[leaf_ctx],
3024 );
3025 let (skip, is_inter) = write_inter_frame_leaf8(
3026 &mut enc,
3027 cdfs,
3028 &mut neighbours,
3029 grid,
3030 mi_cols,
3031 mi_rows,
3032 leaf8,
3033 leaf_mi,
3034 &scan8,
3035 &scan4,
3036 tx_select,
3037 &all_scans,
3038 )?;
3039 let _ = (skip, is_inter);
3040 }
3041 continue;
3042 }
3043 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]);
3044 write_inter_frame_leaf(
3045 &mut enc,
3046 cdfs,
3047 &mut neighbours,
3048 grid,
3049 mi_cols,
3050 mi_rows,
3051 leaf,
3052 at16,
3053 &scan16,
3054 &scan8,
3055 tx_select,
3056 &all_scans,
3057 )?;
3058 } else {
3059 let ctx16 = neighbours.partition_ctx(at16, SUB);
3060 match (has_cols16, has_rows16) {
3061 (true, false) => enc.symbol_fixed(
3062 1,
3063 &gather(&cdfs.partition_w16[ctx16], VERT_ALIKE),
3064 ),
3065 (false, true) => enc.symbol_fixed(
3066 1,
3067 &gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE),
3068 ),
3069 // Both halves outside: SPLIT is inferred.
3070 _ => {}
3071 }
3072 let leaves = leaf.eight.as_ref().ok_or_else(|| {
3073 Error::unsupported(
3074 "AV1 tile",
3075 "a 16x16 inter-frame block the true frame edge cuts \
3076 through needs its `eight` leaves populated",
3077 )
3078 })?;
3079 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
3080 let leaf_positions: Vec<(u32, u32)> = (0..4)
3081 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
3082 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
3083 .collect();
3084 if leaves.len() != leaf_positions.len() {
3085 return Err(Error::unsupported(
3086 "AV1 tile",
3087 "a straddling 16x16 inter-frame block needs one \
3088 `eight` entry per 8x8 leaf inside the true frame",
3089 ));
3090 }
3091 for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) {
3092 let leaf_mi = (mr as usize, mc as usize);
3093 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
3094 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w8[leaf_ctx]);
3095 let (skip, is_inter) = write_inter_frame_leaf8(
3096 &mut enc,
3097 cdfs,
3098 &mut neighbours,
3099 grid,
3100 mi_cols,
3101 mi_rows,
3102 leaf8,
3103 leaf_mi,
3104 &scan8,
3105 &scan4,
3106 tx_select,
3107 &all_scans,
3108 )?;
3109 let _ = (skip, is_inter);
3110 }
3111 // Same write-back-once-from-the-last-leaf rule
3112 // as the key frame search's `write_leaf8`
3113 // caller (r15): the SUB-grid skip/inter arrays
3114 // are otherwise left stale for the next
3115 // 16x16 slot.
3116 }
3117 }
3118 continue;
3119 }
3120 };
3121
3122 let (r, c) = at;
3123 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3124 let has_above = neighbours.has_above(mi_r);
3125 let has_left = neighbours.has_left(mi_c);
3126 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
3127 + usize::from(neighbours.left_skip[mi_r]);
3128 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
3129 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
3130 write_delta_q(&mut enc, cdfs, (mi_r, mi_c), false, block.skip);
3131
3132 let is_inter = block.inter.is_some();
3133 let (above_inter, left_inter) =
3134 (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]);
3135 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
3136 enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
3137
3138 let mode_for_tx;
3139 if let Some(info) = block.inter {
3140 write_comp_mode(
3141 &mut enc,
3142 cdfs,
3143 &neighbours,
3144 (mi_r, mi_c),
3145 (has_above, has_left),
3146 info.ref1.is_some(),
3147 );
3148 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
3149 if info.ref1.is_some() {
3150 let (mv, mv1, is_new_mv) = write_compound_block(
3151 &mut enc,
3152 cdfs,
3153 &neighbours,
3154 grid,
3155 (mi_row, mi_col),
3156 (8, 8),
3157 (has_above, has_left),
3158 info,
3159 (mi_cols as usize, mi_rows as usize),
3160 )?;
3161 for dr in 0..8 {
3162 for dc in 0..8 {
3163 grid.set(
3164 mi_row + dr,
3165 mi_col + dc,
3166 MiInfo {
3167 is_inter: true,
3168 ref_frame: info.ref_frame,
3169 ref_frame1: info.ref1.unwrap_or(NO_REF1),
3170 mv1: mv16(mv1),
3171 mv: mv16(mv),
3172 is_new_mv,
3173 size: 8,
3174 size_h: 8,
3175 is_global_mv0: false,
3176 is_global_mv1: false,
3177 },
3178 );
3179 }
3180 }
3181 mode_for_tx = 0;
3182 } else {
3183 write_single_ref(
3184 &mut enc,
3185 cdfs,
3186 info.ref_frame,
3187 neighbours.above_ref[mi_c],
3188 neighbours.above_ref1[mi_c],
3189 neighbours.left_ref[mi_r],
3190 neighbours.left_ref1[mi_r],
3191 );
3192
3193 let stack = find_mv_stack(
3194 grid,
3195 mi_row,
3196 mi_col,
3197 8,
3198 8,
3199 info.ref_frame,
3200 mi_cols as usize,
3201 mi_rows as usize,
3202 );
3203
3204 let (mv, is_new_mv) = write_inter_mode(&mut enc, cdfs, info, &stack)?;
3205 if crate::msac::symtrace::dir().is_some() {
3206 crate::msac::symtrace::note(&format!(
3207 " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}",
3208 info.mode, info.ref_mv_idx, info.mv
3209 ));
3210 }
3211 grid.set(
3212 mi_row,
3213 mi_col,
3214 MiInfo {
3215 is_inter: true,
3216 ref_frame: info.ref_frame,
3217 ref_frame1: NO_REF1,
3218 mv1: (0, 0),
3219 mv: mv16(mv),
3220 is_new_mv,
3221 size: 8,
3222 size_h: 8,
3223 is_global_mv0: false,
3224 is_global_mv1: false,
3225 },
3226 );
3227 for dr in 0..8 {
3228 for dc in 0..8 {
3229 if dr == 0 && dc == 0 {
3230 continue;
3231 }
3232 grid.set(
3233 mi_row + dr,
3234 mi_col + dc,
3235 MiInfo {
3236 is_inter: true,
3237 ref_frame: info.ref_frame,
3238 ref_frame1: NO_REF1,
3239 mv1: (0, 0),
3240 mv: mv16(mv),
3241 is_new_mv,
3242 size: 8,
3243 size_h: 8,
3244 is_global_mv0: false,
3245 is_global_mv1: false,
3246 },
3247 );
3248 }
3249 }
3250 write_motion_mode(
3251 &mut enc,
3252 cdfs,
3253 grid,
3254 (mi_row, mi_col),
3255 (8, 8),
3256 (BLOCK, BLOCK),
3257 (mi_cols as usize, mi_rows as usize),
3258 info.ref_frame,
3259 block.motion_mode,
3260 )?;
3261 mode_for_tx = 0;
3262 }
3263 } else {
3264 let mode = usize::from(block.mode);
3265 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
3266 if (V_PRED..=D67_PRED).contains(&mode) {
3267 enc.symbol(
3268 (ANGLE_DELTA_ZERO as i32 + i32::from(block.angle_delta_y)) as usize,
3269 &mut cdfs.angle_delta[mode - V_PRED],
3270 );
3271 }
3272 let uv_mode = usize::from(block.uv_mode);
3273 enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]);
3274 if uv_mode == UV_CFL_PRED {
3275 write_cfl_alphas(&mut enc, cdfs, block.cfl_alphas.expect("cfl"));
3276 }
3277 if (V_PRED..=D67_PRED).contains(&uv_mode) {
3278 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
3279 }
3280 mode_for_tx = tx_row(mode, block.filter_intra);
3281 // Intra: no vote, but still a coded cell -- mvstack's
3282 // extended-scan coverage must see it (module doc).
3283 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
3284 write_palette_syntax(
3285 &mut enc,
3286 cdfs,
3287 &mut neighbours,
3288 block.palette.as_ref(),
3289 block.palette_uv.as_ref(),
3290 block.filter_intra,
3291 mode,
3292 uv_mode,
3293 (mi_row, mi_col),
3294 BLOCK,
3295 );
3296 for dr in 0..8 {
3297 for dc in 0..8 {
3298 grid.set(
3299 mi_row + dr,
3300 mi_col + dc,
3301 MiInfo {
3302 is_inter: false,
3303 ref_frame: -1,
3304 ref_frame1: NO_REF1,
3305 mv1: (0, 0),
3306 mv: (0, 0),
3307 is_new_mv: false,
3308 size: 8,
3309 size_h: 8,
3310 is_global_mv0: false,
3311 is_global_mv1: false,
3312 },
3313 );
3314 }
3315 }
3316 }
3317
3318 let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
3319 let tx = if tx_select {
3320 write_tx_syntax_inter(
3321 &mut enc,
3322 cdfs,
3323 &mut neighbours,
3324 at_mi,
3325 BLOCK,
3326 is_inter,
3327 block.skip,
3328 usize::from(block.tx_depth),
3329 )
3330 } else {
3331 BLOCK
3332 };
3333 let split = tx < BLOCK;
3334 if block.skip {
3335 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
3336 } else {
3337 let grids = [
3338 level_grid(&block.luma, TX32)?,
3339 level_grid(&block.u, TX16)?,
3340 level_grid(&block.v, TX16)?,
3341 ];
3342 if split {
3343 write_luma_tus(
3344 &mut enc,
3345 cdfs,
3346 &mut neighbours,
3347 at_mi,
3348 BLOCK,
3349 tx,
3350 &grids[0],
3351 mode_for_tx,
3352 &all_scans,
3353 is_inter,
3354 &block.luma_tx_types,
3355 )?;
3356 }
3357 write_block_planes(
3358 &mut enc,
3359 cdfs,
3360 if is_inter {
3361 &inter_planes
3362 } else {
3363 &intra_planes
3364 },
3365 &grids,
3366 &[&scan32, &scan16, &scan16],
3367 &neighbours.around(at, BLOCK),
3368 mode_for_tx,
3369 split,
3370 block_tx_type(block),
3371 is_inter,
3372 );
3373 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
3374 }
3375 neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));
3376 record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block);
3377 }
3378 }
3379 }
3380 Ok(enc.finish())
3381}