forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

coef.rs2445 lines, 107.1 KiBHistoryRawDownload
1use super::*;
2
3/// One plane of the picture being coded, and the reconstruction being built
4/// beside it.
5/// What one committed 4x4 cell left behind for the coefficient contexts of
6/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
7/// is the same state decode.rs records.
8#[derive(Clone, Copy, Default, PartialEq, Eq)]
9pub(super) struct CoefCtx {
10 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
11 pub(super) level: u8,
12 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
13 /// the DC itself was zero (tile.rs `dc_vote`).
14 pub(super) dc: i8,
15}
16
17/// One plane's coefficient contexts, committed in CODING ORDER: the search
18/// prices partition TREES, so the neighbour state a candidate reads has to be
19/// whatever the blocks coded before it left -- the parent's committed
20/// neighbours for a tree's first child, the just-committed sibling for the
21/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
22/// writer's two running bands is what makes that fall out: a trial commits
23/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
24/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
25/// to its left is exactly what the tile writer's `Neighbours` bands will hold
26/// when it gets there.
27///
28/// Before this map the pricer took both contexts as zero, which is exact for
29/// a luma transform covering its whole block and the largest remaining row of
30/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
31#[derive(Default)]
32pub(super) struct CoefCtxMap {
33 pub(super) cells: Vec<CoefCtx>,
34 pub(super) stride: usize,
35 /// Whether the transforms being priced right now are SMALLER than the
36 /// block they sit in -- a `TxMode::Select` depth split
37 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
38 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
39 /// trial cannot tell, and it is what decides whether luma reads context 0
40 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
41 pub(super) tu_split: bool,
42}
43
44/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
45/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
46/// padding-inclusive score the search used before lane-sse, which is how the
47/// before/after arms of the straddling gate rows are read off ONE binary.
48pub(super) fn edge_sse() -> bool {
49 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
50 crate::envflags::var("EC_AV1_EDGESSE")
51 .ok()
52 .map(|v| v != "0")
53 });
54 ENV.unwrap_or(true)
55}
56
57/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
58/// through and the share of their raw squared error that sat in the padding
59/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
60/// it, but the numbers are an instrument, not a decision (class
61/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
62/// without this census no gate row can say the clip fires at all).
63pub(super) fn edge_census() -> bool {
64 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
65 crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1")
66 });
67 *ENV
68}
69
70/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
71/// 128x128): how many scores clipped, the inside squared error they kept and
72/// the padding squared error they dropped.
73pub(super) static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
74 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
75
76/// One clipped score, for [`take_edge_census`].
77pub(super) fn record_edge_score(side: usize, inside: u64, padding: u64) {
78 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
79 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
80 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
81 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
82}
83
84/// The straddling-block census since the last call, and zero it: one
85/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
86#[must_use]
87pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
88 EDGE_SCORES
89 .iter()
90 .enumerate()
91 .filter_map(|(log2, row)| {
92 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
93 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
94 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
95 (n != 0).then_some((1usize << log2, n, inside, padding))
96 })
97 .collect()
98}
99
100pub(super) struct Plane<'a> {
101 pub(super) source: &'a [u8],
102 pub(super) reconstruction: Vec<u8>,
103 pub(super) width: usize,
104 pub(super) height: usize,
105 /// The frame's true, decodable extent in this plane's own units --
106 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
107 /// not `width`/`height` above, which is the padded coding-surface size.
108 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
109 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
110 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
111 /// this bound, even though the padded reconstruction buffer holds real
112 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
113 /// those instead of stopping here is what desyncs prediction at the true
114 /// edge.
115 pub(super) true_width: usize,
116 pub(super) true_height: usize,
117 /// This plane's own tile's pixel bounds, in this plane's units -- the
118 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
119 /// prediction never reaches across a tile edge even though the
120 /// neighbouring tile's real samples sit right there in the shared
121 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
122 /// leaves every edge exactly as it was before tiles existed.
123 pub(super) tile_x0: usize,
124 pub(super) tile_y0: usize,
125 pub(super) tile_x1: usize,
126 pub(super) tile_y1: usize,
127 /// [`CoefCtxMap`]: what the blocks already committed left for the
128 /// coefficient contexts of the ones still being priced. Sized on the
129 /// first commit, so a plane literal does not have to know its own extent
130 /// twice.
131 pub(super) ctx: CoefCtxMap,
132}
133
134impl Plane<'_> {
135 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
136 /// called at every superblock of the frame-raster search with the rect
137 /// of the tile that superblock belongs to.
138 pub(super) fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
139 self.tile_x0 = x0;
140 self.tile_y0 = y0;
141 self.tile_x1 = x1.min(self.width);
142 self.tile_y1 = y1.min(self.height);
143 }
144 /// The reconstructed samples a block at `(x, y)` predicts from: the row
145 /// above it, the column to its left and the sample between them, each
146 /// missing where the block sits against an edge of the frame.
147 ///
148 /// `reach` says whether the samples above the block's right and below its
149 /// left are decoded, which is what a directional mode reads into; where
150 /// they are not, or where the frame ends first, the edge is shorter and
151 /// the predictor repeats its last sample, exactly as the decoder's clamp
152 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
153 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
154 /// a free per mode per block, on the search's hottest path -- while an
155 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
156 /// samples, on the caller's stack.
157 pub(super) fn edges_into<'a>(
158 &self,
159 x: usize,
160 y: usize,
161 side: usize,
162 reach: Reach,
163 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
164 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
165 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
166 // Even a block's *own* edge is clamped to the true frame bound, not
167 // just a `reach` extension: libaom's `av1_predict_intra_block`
168 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
169 // this block's own right/bottom to the frame edge -- from
170 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
171 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
172 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
173 // samples the row/column above/left holds before the decoder starts
174 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
175 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
176 // extent straddles that edge legally (`has_half`) -- the transform
177 // still covers the whole block, but prediction does not get to read
178 // real reconstructed pixels past the true edge for its own row/column,
179 // only for the padded tail it invents.
180 let own_across = x + side.min(self.true_width.saturating_sub(x));
181 let across = if reach.above_right {
182 own_across + side.min(self.true_width.saturating_sub(own_across))
183 } else {
184 own_across
185 }
186 .min(self.width);
187 let own_down = y + side.min(self.true_height.saturating_sub(y));
188 let down = if reach.below_left {
189 own_down + side.min(self.true_height.saturating_sub(own_down))
190 } else {
191 own_down
192 }
193 .min(self.height);
194 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
195 // whose own origin already sits past the true edge -- only reachable
196 // through a partition trial priced for comparison on a split this
197 // frame's straddling quadrant will go on to refuse (see
198 // `a_picture_off_the_block_grid_is_refused`), never through a block
199 // this encoder actually commits. Such a block has no true-edge
200 // samples above or left of it at all, same as `y == 0`/`x == 0`.
201 let across = across.min(self.tile_x1);
202 let down = down.min(self.tile_y1);
203 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
204 if let Some(n) = above_n {
205 above_buf[..n].copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
206 }
207 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
208 if let Some(n) = left_n {
209 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
210 *d = self.reconstruction[row * self.width + x - 1];
211 }
212 }
213 let corner = (x > self.tile_x0 && y > self.tile_y0)
214 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
215 (
216 above_n.map(|n| &above_buf[..n]),
217 left_n.map(|n| &left_buf[..n]),
218 corner,
219 )
220 }
221
222 /// Codes one block under one mode without committing it: hands back the
223 /// levels, the block the decoder would reconstruct, the squared error
224 /// against the source and an estimate of what the levels cost in bits.
225 pub(super) fn trial(
226 &self,
227 at: At,
228 mode: u8,
229 angle_delta: i32,
230 base_q_idx: u8,
231 deadzone: f64,
232 fctx: &crate::decode::FrameCtx,
233 ) -> Trial {
234 self.trial_typed(
235 at,
236 mode,
237 angle_delta,
238 base_q_idx,
239 deadzone,
240 TxType::DctDct,
241 fctx,
242 )
243 }
244
245 /// [`Self::trial`] under a named transform type -- what an intra chroma
246 /// block gets, since chroma codes no `tx_type` symbol and the decoder
247 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
248 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
249 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
250 #[allow(clippy::too_many_arguments)]
251 /// Sum of absolute differences between the source block at `(x, y)` and a
252 /// `side x side` prediction, as the whole number it is.
253 ///
254 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
255 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
256 /// exactly, so no add here rounds and the order of the adds cannot change
257 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
258 /// integer division per sample -- is what lets the row walk vectorize.
259 pub(super) fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
260 let mut sad = 0u32;
261 for row in 0..side {
262 let source = &self.source[(y + row) * self.width + x..][..side];
263 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
264 sad += u32::from(s.abs_diff(p));
265 }
266 }
267 f64::from(sad)
268 }
269
270 /// Squared error between the source block at `(x, y)` and a reconstruction
271 /// of it, over the part of the block that is INSIDE the true frame.
272 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
273 /// `255^2 * 64 * 64`, under 2^28.
274 ///
275 /// A block the frame edge cuts through is still coded whole -- the
276 /// decoder reconstructs its outside samples too and the display crop
277 /// throws them away -- so scoring the padding would rank a mode, a
278 /// transform or a partition tree by how well it codes samples the source
279 /// does not have (libaom clips the same way: `av1_dist_block` measures
280 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
281 /// edge pixels, so predicting it is nearly free, but coding coefficients
282 /// for it spends real bits. Both gate films are superblock-aligned; this
283 /// only reaches arbitrary export sizes (lane-sse, generalising
284 /// lane-b64b's 64-root-only rescore of the 64 root).
285 pub(super) fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
286 let inside_rows = side.min(self.true_height.saturating_sub(y));
287 let inside_cols = side.min(self.true_width.saturating_sub(x));
288 let straddles = inside_rows < side || inside_cols < side;
289 // The knob is read only for a block the edge cuts, so the interior
290 // path -- the hot one -- carries no extra load at all.
291 let (rows, cols) = match straddles && !edge_sse() {
292 true => (side, side),
293 false => (inside_rows, inside_cols),
294 };
295 let mut sse = 0u64;
296 for row in 0..rows {
297 let source = &self.source[(y + row) * self.width + x..][..cols];
298 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
299 let d = u32::from(s.abs_diff(r));
300 sse += u64::from(d * d);
301 }
302 }
303 if straddles && edge_census() {
304 let (mut inside, mut whole) = (0u64, 0u64);
305 for row in 0..side {
306 let source = &self.source[(y + row) * self.width + x..][..side];
307 for (col, (&s, &r)) in source
308 .iter()
309 .zip(&reconstruction[row * side..][..side])
310 .enumerate()
311 {
312 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
313 whole += d;
314 if row < inside_rows && col < inside_cols {
315 inside += d;
316 }
317 }
318 }
319 record_edge_score(side, inside, whole - inside);
320 }
321 sse as f64
322 }
323
324 // Spec-shaped signature; bundling the operands would obscure the spec mapping.
325 #[allow(clippy::too_many_arguments)]
326 pub(super) fn trial_typed(
327 &self,
328 at: At,
329 mode: u8,
330 // This block's `angle_delta_y`/`angle_delta_uv` (spec
331 // `read_intra_angle_info`, -3..=3), zero for every non-directional
332 // mode -- the predictor's own `angle_delta` argument.
333 angle_delta: i32,
334 base_q_idx: u8,
335 deadzone: f64,
336 tx_type: TxType,
337 fctx: &crate::decode::FrameCtx,
338 ) -> Trial {
339 let At {
340 x, y, side, reach, ..
341 } = at;
342 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
343 let (above, left, corner) =
344 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
345 // Per-candidate scratch on the search's hottest path, so both buffers
346 // live on the stack -- `side` is at most `BLOCK` -- rather than
347 // costing a malloc/free pair per trial (`mc_trial` already does this).
348 let mut prediction = [0u8; BLOCK * BLOCK];
349 let prediction = &mut prediction[..side * side];
350 intra_predict_u8(
351 mode,
352 angle_delta,
353 above,
354 left,
355 corner,
356 side,
357 side,
358 false,
359 false,
360 prediction,
361 fctx,
362 );
363
364 let mut residual = [0i32; BLOCK * BLOCK];
365 let residual = &mut residual[..side * side];
366 for row in 0..side {
367 for col in 0..side {
368 residual[row * side + col] =
369 i32::from(self.source[(y + row) * self.width + x + col])
370 - i32::from(prediction[row * side + col]);
371 }
372 }
373 #[cfg(test)]
374 let t = stage_start();
375 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
376 // reconstruction below and the price further down are both of the
377 // grid this trial would really code.
378 let (levels, rdoq_bits) = if rdoq_on() {
379 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
380 residual,
381 side,
382 8,
383 i32::from(base_q_idx),
384 deadzone,
385 tx_type,
386 );
387 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
388 let bits = crate::tile::rdoq(
389 &mut levels,
390 &scaled,
391 side,
392 base_q_idx,
393 at.set,
394 skip_ctx,
395 sign_ctx,
396 rdoq_lambda(),
397 tx_type,
398 );
399 (levels, Some(bits))
400 } else {
401 (
402 forward_and_quantize_typed(
403 residual,
404 side,
405 8,
406 i32::from(base_q_idx),
407 deadzone,
408 tx_type,
409 ),
410 None,
411 )
412 };
413 // lane-av1speed2: 60% of the transform units of an inter stream carry
414 // no coefficient at all, and the square entry point re-inflates that
415 // case into `side * side` zeros (one allocate-and-memset per trial)
416 // only for the sum below to add them to the prediction. The `_wh`
417 // entry hands back the empty all-zero marker instead, and a zero
418 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
419 // `p` for a `u8`, so the bytes are the same.
420 let coded = dequant_and_inverse_typed_wh(
421 &levels,
422 side,
423 side,
424 8,
425 i32::from(base_q_idx),
426 0,
427 0,
428 tx_type,
429 None,
430 );
431 #[cfg(test)]
432 stage_since(2, t);
433
434 let reconstruction: Vec<u8> = if coded.is_empty() {
435 prediction.to_vec()
436 } else {
437 prediction
438 .iter()
439 .zip(&coded)
440 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
441 .collect()
442 };
443 let sse = self.block_sse(x, y, side, &reconstruction);
444 // What the levels cost is priced through the same CDFs the tile writer
445 // will code them with, so the search ranks modes -- and the partition
446 // trial ranks trees -- by the bits they actually spend.
447 #[cfg(test)]
448 let t = stage_start();
449 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
450 // What the search used before it could price a block exactly: a
451 // level costs its magnitude's width plus a sign and a run. Kept
452 // reachable from the sweep so the two rate terms can be compared
453 // on one build.
454 levels
455 .iter()
456 .filter(|&&level| level != 0)
457 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
458 .sum()
459 } else if let Some(bits) = rdoq_bits {
460 // Already priced, against the grid the pass settled on.
461 bits
462 } else {
463 {
464 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
465 crate::tile::coeff_bits_typed(
466 &levels,
467 at.set,
468 crate::decode::q_ctx_of(base_q_idx),
469 skip_ctx,
470 sign_ctx,
471 tx_type,
472 )
473 }
474 };
475 #[cfg(test)]
476 stage_since(3, t);
477 Trial {
478 levels,
479 reconstruction,
480 sse,
481 bits,
482 }
483 }
484
485 /// [`Self::trial`] with the prediction already built, so that an inter
486 /// block's motion-compensated prediction can go through the same
487 /// residual/quantize/reconstruct path an intra block's does. `skip`
488 /// takes the prediction as the reconstruction outright, coding no
489 /// residual at all — what a `NEARESTMV` block that names no coefficients
490 /// codes.
491 #[allow(clippy::too_many_arguments)]
492 pub(super) fn code_from_prediction(
493 &self,
494 x: usize,
495 y: usize,
496 side: usize,
497 prediction: &[u8],
498 skip: bool,
499 base_q_idx: u8,
500 deadzone: f64,
501 set: TxbSet,
502 ) -> Trial {
503 self.code_from_prediction_typed(
504 x,
505 y,
506 side,
507 prediction,
508 skip,
509 base_q_idx,
510 deadzone,
511 set,
512 TxType::DctDct,
513 )
514 }
515
516 /// [`Self::code_from_prediction`] coding the residual with a NAMED
517 /// transform type (lane-txset2): the inter luma sets carry a two-type
518 /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
519 /// a symbol for, and [`commit_inter_luma`] prices both through this.
520 #[allow(clippy::too_many_arguments)]
521 pub(super) fn code_from_prediction_typed(
522 &self,
523 x: usize,
524 y: usize,
525 side: usize,
526 prediction: &[u8],
527 skip: bool,
528 base_q_idx: u8,
529 deadzone: f64,
530 set: TxbSet,
531 tx_type: TxType,
532 ) -> Trial {
533 if skip {
534 let sse = self.block_sse(x, y, side, prediction);
535 return Trial {
536 levels: vec![0i32; side * side],
537 reconstruction: prediction.to_vec(),
538 sse,
539 bits: 0.0,
540 };
541 }
542 // A 64x64 root's residual is four times the scratch every other
543 // block coder here sizes for [`BLOCK`]; only that one case pays for
544 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
545 let mut small = [0i32; BLOCK * BLOCK];
546 let mut big = if side > BLOCK {
547 vec![0i32; side * side]
548 } else {
549 Vec::new()
550 };
551 let residual: &mut [i32] = if side > BLOCK {
552 &mut big
553 } else {
554 &mut small[..side * side]
555 };
556 for row in 0..side {
557 for col in 0..side {
558 residual[row * side + col] =
559 i32::from(self.source[(y + row) * self.width + x + col])
560 - i32::from(prediction[row * side + col]);
561 }
562 }
563 #[cfg(test)]
564 let t = stage_start();
565 // lane-rdoq, as in [`Self::trial_typed`].
566 let (levels, rdoq_bits) = if rdoq_on() {
567 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
568 residual,
569 side,
570 8,
571 i32::from(base_q_idx),
572 deadzone,
573 tx_type,
574 );
575 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
576 let bits = crate::tile::rdoq(
577 &mut levels,
578 &scaled,
579 side,
580 base_q_idx,
581 set,
582 skip_ctx,
583 sign_ctx,
584 rdoq_lambda(),
585 tx_type,
586 );
587 (levels, Some(bits))
588 } else {
589 (
590 forward_and_quantize_typed(
591 residual,
592 side,
593 8,
594 i32::from(base_q_idx),
595 deadzone,
596 tx_type,
597 ),
598 None,
599 )
600 };
601 // The same all-zero shortcut [`Self::trial_typed`] takes.
602 let coded = dequant_and_inverse_typed_wh(
603 &levels,
604 side,
605 side,
606 8,
607 i32::from(base_q_idx),
608 0,
609 0,
610 tx_type,
611 None,
612 );
613 #[cfg(test)]
614 stage_since(2, t);
615 let reconstruction: Vec<u8> = if coded.is_empty() {
616 prediction.to_vec()
617 } else {
618 prediction
619 .iter()
620 .zip(&coded)
621 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
622 .collect()
623 };
624 let sse = self.block_sse(x, y, side, &reconstruction);
625 // A 64-point transform codes only its top-left 32x32 corner (spec
626 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
627 // key frame writer takes a 32x32 level grid for one). The inverse
628 // above reads the whole 64x64 array, but the price below and the
629 // levels the writer takes are that corner.
630 let levels = if side > BLOCK {
631 coded_corner(&levels, side, BLOCK)
632 } else {
633 levels
634 };
635 #[cfg(test)]
636 let t = stage_start();
637 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
638 levels
639 .iter()
640 .filter(|&&level| level != 0)
641 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
642 .sum()
643 } else if let Some(bits) = rdoq_bits {
644 bits
645 } else {
646 {
647 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
648 crate::tile::coeff_bits_typed(
649 &levels,
650 set,
651 crate::decode::q_ctx_of(base_q_idx),
652 skip_ctx,
653 sign_ctx,
654 tx_type,
655 )
656 }
657 };
658 #[cfg(test)]
659 stage_since(3, t);
660 Trial {
661 levels,
662 reconstruction,
663 sse,
664 bits,
665 }
666 }
667
668 /// Codes this block's luma at transform depth `depth`: the
669 /// `(side >> depth)^2` transform units in raster order, each predicted
670 /// from the reconstruction the units before it left behind -- exactly
671 /// what the decoder's multi-transform-unit branch does (decode.rs
672 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
673 /// reconstructed on its own. Commits the result and hands back the
674 /// block-coordinate levels, the block's squared error and what its
675 /// coefficients cost.
676 #[allow(clippy::too_many_arguments)]
677 pub(super) fn code_tx_depth(
678 &mut self,
679 at: At,
680 mode: u8,
681 angle_delta: i32,
682 depth: usize,
683 // This block's `filter_intra_mode` when it is coded with one, in
684 // which case every transform unit predicts recursively off the
685 // reconstruction the units before it left -- what the decoder does
686 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
687 // `filter_intra`), not once over the whole block.
688 filter_intra: Option<u8>,
689 search: &Search,
690 fctx: &crate::decode::FrameCtx,
691 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
692 let At {
693 x, y, side, reach, ..
694 } = at;
695 let tx = side >> depth;
696 let n = 1usize << depth;
697 let set = luma_set_for(
698 match tx {
699 32 => TxbSet::Luma32,
700 16 => TxbSet::Luma16,
701 8 => TxbSet::Luma8,
702 _ => TxbSet::Luma4,
703 },
704 search.screen,
705 );
706 let mut levels = vec![0i32; side * side];
707 census_add(4, n * n);
708 // A unit smaller than its block reads the neighbour magnitude table
709 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
710 self.ctx.tu_split = n > 1;
711 let (mut sse, mut bits) = (0.0, 0.0);
712 // One entry per unit at its own `tu_row * n + tu_col`, which is how
713 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
714 // frame edge cuts away is never coded there, so a compacted list
715 // would slide every later unit's type onto the wrong transform.
716 let mut tx_types = vec![TxType::DctDct; n * n];
717 for tu_row in 0..n {
718 for tu_col in 0..n {
719 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
720 let tu = At {
721 x: x + col_off,
722 y: y + row_off,
723 side: tx,
724 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
725 set,
726 };
727 let trial = match filter_intra {
728 Some(fi) => {
729 let (mut above_buf, mut left_buf) =
730 ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
731 let (above, left, corner) = self.edges_into(
732 tu.x,
733 tu.y,
734 tx,
735 tu.reach,
736 &mut above_buf,
737 &mut left_buf,
738 );
739 let mut prediction = vec![0u8; tx * tx];
740 filter_intra_predict_u8(
741 usize::from(fi),
742 above,
743 left,
744 corner,
745 tx,
746 &mut prediction,
747 fctx,
748 );
749 self.code_from_prediction(
750 tu.x,
751 tu.y,
752 tx,
753 &prediction,
754 false,
755 search.base_q_idx,
756 search.deadzone,
757 set,
758 )
759 }
760 None => {
761 // lane-txset: the unit picks its own transform type
762 // out of the set the writer can name it in, priced
763 // through the same RDOQ'd trial path (its `bits`
764 // already carry the `tx_type` symbol itself).
765 let mut best: Option<(f64, TxType, Trial)> = None;
766 for &tx_type in tx_type_candidates(set, search.screen) {
767 let candidate = self.trial_typed(
768 tu,
769 mode,
770 angle_delta,
771 search.base_q_idx,
772 search.deadzone,
773 tx_type,
774 fctx,
775 );
776 // lane-txi: a non-`DCT_DCT` type is charged its
777 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
778 // search's weight (default 1 = unchanged). The
779 // film rows buy 0.04 dB for 1.2% more bytes at
780 // weight 1 on every frame and every PLANE, key
781 // frame included -- a rate term this decision
782 // under-charges (class
783 // `rd-rate-term-calibration`), not the
784 // propagation loss the leaves would have shown.
785 let cost = candidate.sse
786 + search.lambda * candidate.bits
787 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
788 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
789 best = Some((cost, tx_type, candidate));
790 }
791 }
792 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
793 tx_types[tu_row * n + tu_col] = tx_type;
794 TX_TYPE_HITS[tx_type as usize]
795 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
796 trial
797 }
798 };
799 sse += trial.sse;
800 bits += trial.bits;
801 self.commit(tu.x, tu.y, tx, &trial);
802 for row in 0..tx {
803 levels[(row_off + row) * side + col_off..][..tx]
804 .copy_from_slice(&trial.levels[row * tx..][..tx]);
805 }
806 }
807 }
808 self.ctx.tu_split = false;
809 (levels, sse, bits, tx_types)
810 }
811
812 /// Writes a trial's reconstruction back into the plane, and the
813 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
814 pub(super) fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
815 for row in 0..side {
816 self.reconstruction[(y + row) * self.width + x..][..side]
817 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
818 }
819 self.commit_ctx(x, y, side, &trial.levels);
820 }
821
822 /// Publishes one committed transform's own context over every 4x4 cell it
823 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
824 /// which is what the writer will read when it reaches the next block.
825 pub(super) fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
826 if self.ctx.cells.is_empty() {
827 self.ctx.stride = self.width.div_ceil(4);
828 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
829 }
830 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
831 let state = CoefCtx {
832 level: cul,
833 dc: match levels[0].signum() {
834 0 => 0,
835 -1 => -1,
836 _ => 1,
837 },
838 };
839 let n = (side / 4).max(1);
840 // Only up to the frame's TRUE extent: the writer's own
841 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
842 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
843 // and leaves the cells past it uncoded even mid-block, so a
844 // straddling block publishes context for its inside part only.
845 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
846 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
847 for row in 0..rows {
848 let start = (y / 4 + row) * self.ctx.stride + x / 4;
849 let end = (start + cols).min(self.ctx.cells.len());
850 if start < end {
851 self.ctx.cells[start..end].fill(state);
852 }
853 }
854 }
855
856 /// A block committed without any residual at all ([`ibc_commit`]): the
857 /// cells it covers coded nothing, and leaving an earlier trial's state
858 /// there would price its neighbours off a block that was never coded.
859 pub(super) fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
860 self.commit_ctx(x, y, side, &[0i32]);
861 }
862
863 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
864 /// plane reads, off what the blocks before it in coding order committed
865 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
866 /// the above/left neighbours coded anything (tile.rs
867 /// `write_block_planes`), luma reads context 0 when its transform covers
868 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
869 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
870 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
871 /// the same neighbours (tile.rs `dc_sign_ctx`).
872 ///
873 /// A neighbour outside this plane's own TILE does not exist, exactly as
874 /// the writer's per-tile `Neighbours` bands start blank.
875 ///
876 /// CLOSED (lane-av1straddle): the decisions this price changes used to
877 /// make `decode_stream_round_trips_an_odd_size_gop` and
878 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
879 /// fail at 216x96. Never this map: the writer coded the phantom
880 /// transform units of a right-edge-straddling 32x32 (tile.rs
881 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
882 /// like decode.rs and libaom), which libdav1d and libaom both refused
883 /// outright while a decision change was what first walked into it.
884 pub(super) fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
885 if self.ctx.cells.is_empty() {
886 return (0, 0);
887 }
888 let n = (side / 4).max(1);
889 let (cx, cy) = (x / 4, y / 4);
890 let (mut top, mut left) = (0u8, 0u8);
891 let mut vote = 0i32;
892 if y > self.tile_y0 && cy > 0 {
893 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
894 top |= cell.level;
895 vote += i32::from(cell.dc);
896 }
897 }
898 if x > self.tile_x0 && cx > 0 {
899 for row in 0..n {
900 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
901 left |= cell.level;
902 vote += i32::from(cell.dc);
903 }
904 }
905 let skip_ctx = if set.is_chroma() {
906 usize::from(top != 0) + usize::from(left != 0)
907 } else if self.ctx.tu_split {
908 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
909 } else {
910 0
911 };
912 let sign_ctx = match vote.signum() {
913 0 => 0,
914 -1 => 1,
915 _ => 2,
916 };
917 (skip_ctx, sign_ctx)
918 }
919
920 /// The source samples of one square, contiguous — what a motion search
921 /// compares its candidates' predictions against ([`motion::search`]'s
922 /// `source`), since [`Self::source`] itself is the whole plane, strided
923 /// by [`Self::width`].
924 pub(super) fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
925 rows_of(self.source, self.width, x, y, side)
926 }
927
928 /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
929 /// root's own HORZ/VERT motion search.
930 pub(super) fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
931 let mut out = vec![0u8; w * h];
932 for row in 0..h {
933 out[row * w..][..w].copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
934 }
935 out
936 }
937
938 /// The reconstructed samples of one square, so that a partition trial can
939 /// be undone.
940 /// The reconstructed samples of one square AND the coefficient contexts
941 /// its cells hold, so that a partition trial can be undone whole: a
942 /// losing trial that left its own nz/DC state behind would price the
943 /// blocks after it off a block the tile writer never codes.
944 pub(super) fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
945 (
946 rows_of(&self.reconstruction, self.width, x, y, side),
947 self.ctx_rows(x, y, side),
948 )
949 }
950
951 pub(super) fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
952 if self.ctx.cells.is_empty() {
953 return Vec::new();
954 }
955 let n = (side / 4).max(1);
956 (0..n)
957 .flat_map(|row| {
958 let start = (y / 4 + row) * self.ctx.stride + x / 4;
959 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
960 })
961 .collect()
962 }
963
964 /// Puts a snapshot back.
965 pub(super) fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
966 for row in 0..side {
967 self.reconstruction[(y + row) * self.width + x..][..side]
968 .copy_from_slice(&saved.0[row * side..][..side]);
969 }
970 if saved.1.is_empty() {
971 return;
972 }
973 let n = (side / 4).max(1);
974 for row in 0..n {
975 let start = (y / 4 + row) * self.ctx.stride + x / 4;
976 let end = (start + n).min(self.ctx.cells.len());
977 if start < end {
978 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
979 }
980 }
981 }
982
983 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
984 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
985 /// prescreen by the identical rule rather than a second one that could
986 /// drift from it.
987 pub(super) fn intra_scores(
988 &self,
989 at: At,
990 modes: &[u8],
991 mode_bits: &[f64; 13],
992 lambda: f64,
993 fctx: &crate::decode::FrameCtx,
994 ) -> Vec<(f64, u8)> {
995 let At {
996 x, y, side, reach, ..
997 } = at;
998 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
999 let (above, left, corner) =
1000 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
1001 modes
1002 .iter()
1003 .map(|&mode| {
1004 let mut prediction = vec![0u8; side * side];
1005 intra_predict_u8(
1006 mode,
1007 0,
1008 above,
1009 left,
1010 corner,
1011 side,
1012 side,
1013 false,
1014 false,
1015 &mut prediction,
1016 fctx,
1017 );
1018 let sad = self.block_sad(x, y, side, &prediction);
1019 (sad + lambda * mode_bits[usize::from(mode)], mode)
1020 })
1021 .collect()
1022 }
1023
1024 /// Codes one block under every mode the search offers (or, when
1025 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
1026 /// pre-pass plus DC) and commits the one whose squared error and
1027 /// estimated rate come out cheapest.
1028 ///
1029 /// The prediction is built once per mode regardless -- the full RD trial
1030 /// needs it too -- so ranking modes by SAD on that same prediction before
1031 /// running the expensive part (forward transform, quantize, reconstruct,
1032 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
1033 /// only to sum.
1034 pub(super) fn search_block(
1035 &mut self,
1036 at: At,
1037 search: &Search,
1038 mode_bits: &[f64; 13],
1039 fctx: &crate::decode::FrameCtx,
1040 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
1041 let At {
1042 x, y, side, reach, ..
1043 } = at;
1044 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
1045 let (above, left, corner) =
1046 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
1047 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
1048 // the census reports it), so summing it under the default unpruned
1049 // search is `side * side` absolute differences per mode spent on a
1050 // number no one reads.
1051 let want_sad = search.top_k.is_some() || census_on();
1052 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
1053 .modes
1054 .iter()
1055 .map(|&mode| {
1056 let mut prediction = vec![0u8; side * side];
1057 intra_predict_u8(
1058 mode,
1059 0,
1060 above,
1061 left,
1062 corner,
1063 side,
1064 side,
1065 false,
1066 false,
1067 &mut prediction,
1068 fctx,
1069 );
1070 let sad = if want_sad {
1071 self.block_sad(x, y, side, &prediction)
1072 } else {
1073 0.0
1074 };
1075 (
1076 sad + search.lambda * mode_bits[usize::from(mode)],
1077 mode,
1078 prediction,
1079 )
1080 })
1081 .collect();
1082 if let Some(k) = search.top_k
1083 && k < scored.len() {
1084 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
1085 let dc_entry = dc_pos.map(|i| scored.remove(i));
1086 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
1087 scored.truncate(if dc_entry.is_some() {
1088 k.saturating_sub(1)
1089 } else {
1090 k
1091 });
1092 if let Some(dc_entry) = dc_entry {
1093 scored.push(dc_entry);
1094 }
1095 }
1096 let ranking: Vec<(f64, u8)> = if census_on() {
1097 scored
1098 .iter()
1099 .map(|&(score, mode, _)| (score, mode))
1100 .collect()
1101 } else {
1102 Vec::new()
1103 };
1104 census_add(0, 1);
1105 census_add(1, scored.len());
1106 let mut best: Option<(f64, u8, Trial)> = None;
1107 for (_, mode, prediction) in scored {
1108 let trial = self.code_from_prediction(
1109 x,
1110 y,
1111 side,
1112 &prediction,
1113 false,
1114 search.base_q_idx,
1115 search.deadzone,
1116 at.set,
1117 );
1118 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
1119 if best
1120 .as_ref()
1121 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
1122 {
1123 best = Some((cost, mode, trial));
1124 }
1125 }
1126 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
1127 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
1128 // directional modes each carry a -3..=3 delta, three degrees a step,
1129 // which the writer has always coded as ZERO because nothing searched
1130 // it. Refined on the winning mode only -- libaom's own ordering, and
1131 // six extra trials on the directional blocks instead of on every
1132 // block times every mode. The edges are the ones the base angle
1133 // already read (`enable_intra_edge_filter` is off in this encoder's
1134 // sequence header, so no delta changes which samples exist), and the
1135 // predictor is the decoder's, `angle_delta` argument and all.
1136 let mut angle_delta = 0i32;
1137 // Not on a screen frame: measured on the 5-row native gate, the
1138 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
1139 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
1140 // synthetic edges land on the base angles, so every delta there buys
1141 // a symbol and no prediction. Same `search.screen` gate palette and
1142 // intrabc already stand behind.
1143 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
1144 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
1145 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
1146 let mut prediction = vec![0u8; side * side];
1147 for delta in [-3i32, -2, -1, 1, 2, 3] {
1148 intra_predict_u8(
1149 mode,
1150 delta,
1151 above,
1152 left,
1153 corner,
1154 side,
1155 side,
1156 false,
1157 false,
1158 &mut prediction,
1159 fctx,
1160 );
1161 let candidate = self.code_from_prediction(
1162 x,
1163 y,
1164 side,
1165 &prediction,
1166 false,
1167 search.base_q_idx,
1168 search.deadzone,
1169 at.set,
1170 );
1171 let bits =
1172 symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
1173 - zero_bits;
1174 let cost_d = candidate.sse
1175 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
1176 if cost_d < cost {
1177 cost = cost_d;
1178 angle_delta = delta;
1179 trial = candidate;
1180 }
1181 }
1182 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
1183 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1184 }
1185 // lane-txset: the block's own transform type, searched on the mode
1186 // and angle the trials above settled -- the same ordering the angle
1187 // refinement uses, and the same RD terms.
1188 let mut tx_type = TxType::DctDct;
1189 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
1190 let candidate = self.trial_typed(
1191 at,
1192 mode,
1193 angle_delta,
1194 search.base_q_idx,
1195 search.deadzone,
1196 candidate_type,
1197 fctx,
1198 );
1199 let cost_t =
1200 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
1201 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
1202 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
1203 // block's true one for the caller's own decision.
1204 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
1205 cost = cost_t;
1206 tx_type = candidate_type;
1207 trial = candidate;
1208 }
1209 }
1210 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1211 if census_on() {
1212 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
1213 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1214 }
1215 self.commit(x, y, side, &trial);
1216 // A 64-point transform codes only its top-left 32x32 corner, which is
1217 // the grid `code_from_prediction` hands back (lane-i64).
1218 (
1219 coeffs(&trial.levels, side.min(BLOCK)),
1220 mode,
1221 angle_delta,
1222 cost,
1223 tx_type,
1224 )
1225 }
1226}
1227
1228/// Where one block sits in its plane, and how far past its own edges its
1229/// prediction may read.
1230#[derive(Clone, Copy)]
1231pub(super) struct At {
1232 pub(super) x: usize,
1233 pub(super) y: usize,
1234 pub(super) side: usize,
1235 pub(super) reach: Reach,
1236 /// Which of the tile writer's coefficient tables this block's levels are
1237 /// coded with, and so which the search prices them through.
1238 pub(super) set: TxbSet,
1239}
1240
1241/// Which of the samples past a block's own edges the decoder has decoded by
1242/// the time it predicts the block, and so which a directional mode may read.
1243///
1244/// The decoder derives these from its `BlockDecoded` flags, which are cleared
1245/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
1246/// that map, this reads the answer the same way libaom and rav1e do: for a
1247/// block whose transform covers it whole, whether the samples above its right
1248/// (or below its left) are decoded depends only on where the block sits inside
1249/// its 64x64 superblock, which is a pinned table per block size.
1250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1251pub(crate) struct Reach {
1252 pub(crate) above_right: bool,
1253 pub(crate) below_left: bool,
1254}
1255
1256/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
1257/// libaom): for a block that is neither in the superblock's top row nor its
1258/// rightmost column, whether the block above and to its right is coded before
1259/// it. Indexed by the block's position in the superblock, in blocks of its own
1260/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
1261/// 128, not this crate's 64 superblock -- bit by bit from the low end.
1262pub(super) const HAS_TOP_RIGHT: [&[u8]; 4] = [
1263 &[255, 85, 119, 85, 127, 85, 119, 85],
1264 &[95, 87],
1265 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
1266 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
1267 &[
1268 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
1269 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
1270 ],
1271 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
1272 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
1273 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
1274 // with side 4 outside a TX4 split; without their own row they clamped
1275 // into the 8x8 table and read above-right samples the decoder has not
1276 // written yet (all-zero pixels in the bottom-right triangle of a
1277 // directional 4x4 leaf).
1278 &[
1279 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
1280 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
1281 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
1282 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
1283 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
1284 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
1285 119, 119, 119, 119, 85, 85, 85, 85,
1286 ],
1287];
1288
1289/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
1290/// left.
1291pub(super) const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
1292 &[84, 16, 84, 0, 84, 16, 84, 0],
1293 &[4, 4],
1294 // has_bl_8x8 (libaom av1/common/reconintra.c)
1295 &[
1296 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
1297 84, 85, 16, 17, 84, 85, 0, 0,
1298 ],
1299 // has_bl_4x4 (same source, same order).
1300 &[
1301 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
1302 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84,
1303 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
1304 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85,
1305 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
1306 85, 85, 0, 0, 0, 0,
1307 ],
1308];
1309
1310/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
1311/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
1312/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
1313/// rather than in raster order, so the bottom-left square's top-right
1314/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
1315/// libaom switches tables on the partition type (`get_has_tr_table`); the
1316/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
1317/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
1318/// lane-part32 r5 caught reading undecoded samples.
1319pub(super) const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
1320 // has_tr_vert_16x16
1321 &[255, 0, 119, 0, 127, 0, 119, 0],
1322 // has_tr_vert_32x32
1323 &[15, 7],
1324 // has_tr_vert_8x8
1325 &[
1326 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
1327 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
1328 ],
1329];
1330
1331/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
1332pub(super) const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
1333 // has_bl_vert_16x16
1334 &[254, 16, 254, 0, 254, 16, 254, 0],
1335 // has_bl_vert_32x32
1336 &[14, 14],
1337 // has_bl_vert_8x8
1338 &[
1339 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
1340 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
1341 ],
1342];
1343
1344thread_local! {
1345 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
1346 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
1347 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
1348 /// threading one bool through this crate's already twenty-argument
1349 /// `decode_block` would touch every call site instead of the two arms
1350 /// that need it.
1351 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1352}
1353
1354/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
1355pub(crate) struct VertAbGuard(bool);
1356
1357impl Drop for VertAbGuard {
1358 fn drop(&mut self) {
1359 VERT_AB_PARTITION.with(|c| c.set(self.0));
1360 }
1361}
1362
1363/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
1364/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
1365/// so no byte is retyped). Each is indexed by
1366/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
1367/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
1368/// superblock grid; on this crate's 64-pixel superblock the highest index a
1369/// shape can reach stays inside its own table, so no wrap is involved.
1370///
1371/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
1372/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
1373/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
1374/// 10 of the 21 reachable superblock positions for above-right and 7 for
1375/// below-left.
1376/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
1377pub(super) const HAS_TR_4X8: [u8; 64] = [
1378 255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255,
1379 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119,
1380 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127,
1381 127, 127, 127, 119, 119, 119, 119,
1382];
1383/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
1384pub(super) const HAS_BL_4X8: [u8; 64] = [
1385 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17,
1386 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1,
1387 1, 1, 16, 17, 17, 17, 0, 0, 0, 0,
1388];
1389/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
1390pub(super) const HAS_TR_8X4: [u8; 64] = [
1391 255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119,
1392 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127,
1393 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0,
1394];
1395/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
1396pub(super) const HAS_BL_8X4: [u8; 64] = [
1397 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254,
1398 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255,
1399 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0,
1400];
1401/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
1402pub(super) const HAS_TR_8X16: [u8; 16] = [
1403 255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119,
1404];
1405/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
1406pub(super) const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
1407/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
1408pub(super) const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
1409/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
1410pub(super) const HAS_BL_16X8: [u8; 16] = [
1411 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0,
1412];
1413/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
1414pub(super) const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
1415/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
1416pub(super) const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
1417/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
1418pub(super) const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
1419/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
1420pub(super) const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
1421/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
1422pub(super) const HAS_TR_32X64: [u8; 1] = [127];
1423/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
1424pub(super) const HAS_BL_32X64: [u8; 1] = [0];
1425/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
1426pub(super) const HAS_TR_64X32: [u8; 1] = [19];
1427/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
1428pub(super) const HAS_BL_64X32: [u8; 1] = [34];
1429/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
1430pub(super) const HAS_TR_4X16: [u8; 32] = [
1431 255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255,
1432 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127,
1433];
1434/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
1435pub(super) const HAS_BL_4X16: [u8; 32] = [
1436 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0,
1437];
1438/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
1439pub(super) const HAS_TR_16X4: [u8; 32] = [
1440 255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0,
1441 85, 0, 0, 0,
1442];
1443/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
1444pub(super) const HAS_BL_16X4: [u8; 32] = [
1445 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84,
1446 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0,
1447];
1448/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
1449pub(super) const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
1450/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
1451pub(super) const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
1452/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
1453pub(super) const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
1454/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
1455pub(super) const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
1456/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
1457pub(super) const HAS_TR_16X64: [u8; 2] = [255, 127];
1458/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
1459pub(super) const HAS_BL_16X64: [u8; 2] = [0, 0];
1460/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
1461pub(super) const HAS_TR_64X16: [u8; 2] = [3, 1];
1462/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
1463pub(super) const HAS_BL_64X16: [u8; 2] = [42, 42];
1464
1465/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
1466pub(super) fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
1467 match (bw, bh) {
1468 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
1469 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
1470 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
1471 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
1472 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
1473 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
1474 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
1475 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
1476 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
1477 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
1478 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
1479 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
1480 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
1481 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
1482 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
1483 }
1484}
1485
1486impl Reach {
1487 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
1488 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
1489 /// own answer is `block` -- a different rule from the standalone-block
1490 /// tables, because a unit's neighbours are mostly its own block's
1491 /// already-reconstructed units:
1492 /// * top-right: available while the unit to the right is still inside
1493 /// the block (`col_off + tx < bw`); otherwise only the block's top row
1494 /// of units reaches past it, through the block-level answer
1495 /// (libaom's `row_off > 0` branch returns exactly
1496 /// `col_off + txw < plane_bw`).
1497 /// * bottom-left: a unit outside the block's left column has none
1498 /// (libaom returns 0 for `col_off > 0`); inside the block
1499 /// (`row_off + tx < bh`) they are the left unit's, already
1500 /// reconstructed; the bottom row falls back to the block-level answer.
1501 pub(crate) fn of_tu(
1502 bw: usize,
1503 bh: usize,
1504 col_off: usize,
1505 row_off: usize,
1506 // The unit's own width and height in pixels; equal for a square
1507 // transform, different for the rect unit a 1:4 strip's first split
1508 // produces (lane-rectsplitx r1).
1509 tx_w: usize,
1510 tx_h: usize,
1511 block: Self,
1512 ) -> Self {
1513 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
1514 // order, so both libaom predicates special-case it (lane-sb128c r10);
1515 // without this the last unit column of every chunk of a 128x64 block
1516 // predicts from a chunk libaom has not decoded yet.
1517 let wide = bw > 64;
1518 Self {
1519 above_right: if row_off > 0 {
1520 // `has_top_right`'s `row_off > 0` branch: the offset is taken
1521 // modulo the 64-wide chunk, except for the one unit whose
1522 // top-right corner is the centre of a 128x128 block.
1523 if wide {
1524 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
1525 } else {
1526 col_off + tx_w < bw
1527 }
1528 } else if col_off + tx_w < bw {
1529 true
1530 } else {
1531 block.above_right
1532 },
1533 below_left: if wide && col_off > 0 && col_off.is_multiple_of(64) {
1534 // `has_bottom_left`: at the left edge of a right-hand chunk
1535 // the bottom-left pixels are in the already-coded left chunk,
1536 // provided they stay inside it.
1537 (row_off % 64) + tx_h < bh.min(64)
1538 } else if col_off > 0 {
1539 false
1540 } else if row_off + tx_h < bh {
1541 true
1542 } else {
1543 block.below_left
1544 },
1545 }
1546 }
1547
1548 /// libaom's own `has_top_right`/`has_bottom_left` for one transform unit
1549 /// of a CHROMA plane, at the plane granularity libaom uses there
1550 /// (`reconintra.c:203` / `reconintra.c:381`).
1551 ///
1552 /// Two things make a chroma unit's answer differ from the same unit's
1553 /// LUMA answer, and [`Self::of_tu`] has neither:
1554 ///
1555 /// 1. libaom runs a chroma plane through `scale_chroma_bsize(bsize,
1556 /// ss_x, ss_y)` (`reconintra.c:1823`, definition `:1649`) before
1557 /// either call, and that remap is not the identity. At 4:2:2
1558 /// (`ss (1,0)`) a BLOCK_4X4 luma leaf becomes BLOCK_8X4 -- TWO mi
1559 /// wide and one mi tall.
1560 /// 2. `has_bottom_left`'s "leftmost column of superblock" arm
1561 /// (`reconintra.c:429-435`) is then reached at `blk_col_in_sb == 0`,
1562 /// which the one-mi-wide luma BLOCK_4X4 reads as column 1 and the
1563 /// per-block table denies. [`Self::of_tu`] has no such arm at all: it
1564 /// ends at `block.below_left`, the BLOCK-level answer, which stands in
1565 /// for the table plus both superblock arms and so agrees with libaom
1566 /// only where neither superblock arm is the deciding step.
1567 ///
1568 /// `mi_bw`/`mi_bh` are the PLANE-scaled block's mi extent ([`Self`]'s
1569 /// caller supplies it from [`chroma_mi_shape`], never the luma block's),
1570 /// and `col_off`/`row_off`/`tx_w`/`tx_h` are LUMA pixels as at every other
1571 /// `Reach` call site -- libaom's plane units are one `tx_size_*_unit`
1572 /// (`1 << (2 + ss)` luma pixels) wide, and each comparison below is
1573 /// restated in luma pixels rather than rescaled twice. The
1574 /// 128-wide arm libaom guards on `block_size_wide[bsize] > 64` is not
1575 /// transcribed: every caller keeps such blocks on [`Self::of_tu`].
1576 ///
1577 /// `above_avail` is libaom's `top_available && right_available` and
1578 /// `below_avail` its `bottom_available && left_available` -- the early
1579 /// returns at `reconintra.c:204` / `:383`. The caller states them because
1580 /// libaom's two edge tests are TILE bounds over the TRANSFORM's plane
1581 /// extent (`mi_col + ((col_off + txw) << ss_x) < mi_col_end`,
1582 /// `mi_row + ((row_off + txh) << ss_y) < mi_row_end`,
1583 /// `reconintra.c:1815-1817`) while `top_available`/`left_available` are
1584 /// `y0 > 0` / `x0 > 0`.
1585 #[allow(clippy::too_many_arguments)]
1586 pub(crate) fn of_tu_chroma(
1587 mi_bw: usize,
1588 mi_bh: usize,
1589 mi_row: usize,
1590 mi_col: usize,
1591 sb_mi: usize,
1592 col_off: usize,
1593 row_off: usize,
1594 tx_w: usize,
1595 tx_h: usize,
1596 ss_x: usize,
1597 ss_y: usize,
1598 above_avail: bool,
1599 below_avail: bool,
1600 ) -> Self {
1601 if !above_avail && !below_avail {
1602 return Self::none();
1603 }
1604 let bw_log2 = mi_bw.trailing_zeros() as usize;
1605 let bh_log2 = mi_bh.trailing_zeros() as usize;
1606 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
1607 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
1608 // `plane_bw_unit`/`plane_bh_unit` (`reconintra.c:208` / `:414`) in
1609 // libaom's plane units, restated in the luma pixels of the offsets.
1610 let plane_bw = (mi_bw >> ss_x).max(1) << (2 + ss_x);
1611 let plane_bh = (mi_bh >> ss_y).max(1) << (2 + ss_y);
1612 let (tr, bl) = Self::plane_reach_tables(mi_bw, mi_bh);
1613 Self {
1614 above_right: above_avail
1615 && (if row_off > 0 {
1616 col_off + tx_w < plane_bw
1617 } else if col_off + tx_w < plane_bw {
1618 true
1619 } else if blk_row == 0 {
1620 // Top row of superblock: the top-right pixels are in the
1621 // superblock above.
1622 true
1623 } else if ((blk_col + 1) << bw_log2) >= sb_mi {
1624 // Rightmost column: they fall in the superblock to the
1625 // right, which is not decoded yet.
1626 false
1627 } else {
1628 Self::bit(tr, (blk_row << (5 - bw_log2)) + blk_col)
1629 }),
1630 below_left: below_avail
1631 && (if col_off > 0 {
1632 // Bottom-left pixels are in the bottom-left block.
1633 false
1634 } else if row_off + tx_h < plane_bh {
1635 true
1636 } else if blk_col == 0 {
1637 // `reconintra.c:429-435`: `blk_start_row_off + row_off +
1638 // count < sb_height_unit`, compared in plane units. Both
1639 // `>> ss_y` floors are lifted out of the comparison
1640 // instead of being evaluated, so the luma-pixel
1641 // restatement is exact.
1642 let from_block = (blk_row << bh_log2) >> ss_y;
1643 let sb_height = (sb_mi >> ss_y).saturating_sub(from_block);
1644 row_off + tx_h < sb_height << (2 + ss_y)
1645 } else if ((blk_row + 1) << bh_log2) >= sb_mi {
1646 // Bottom row (and not the leftmost column): the
1647 // superblock below is not decoded yet.
1648 false
1649 } else {
1650 Self::bit(bl, (blk_row << (5 - bw_log2)) + blk_col)
1651 }),
1652 }
1653 }
1654
1655 /// The `has_tr_*`/`has_bl_*` pair for a block of `mi_bw` x `mi_bh` mi --
1656 /// libaom's `get_has_tr_table`/`get_has_bl_table` indexed by the
1657 /// PLANE-scaled `BLOCK_SIZE`, so one shape can be a rectangle where
1658 /// [`Self::table`] would read a square's row (a 4:2:2 chroma BLOCK_8X4,
1659 /// which is [`Self::of_tu_chroma`]'s whole reason for existing).
1660 pub(super) fn plane_reach_tables(mi_bw: usize, mi_bh: usize) -> (&'static [u8], &'static [u8]) {
1661 if mi_bw != mi_bh {
1662 return rect_reach_tables(mi_bw * 4, mi_bh * 4);
1663 }
1664 let row = Self::table(mi_bw * 4);
1665 if VERT_AB_PARTITION.with(std::cell::Cell::get) && row < HAS_TOP_RIGHT_VERT.len() {
1666 (HAS_TOP_RIGHT_VERT[row], HAS_BOTTOM_LEFT_VERT[row])
1667 } else {
1668 (HAS_TOP_RIGHT[row], HAS_BOTTOM_LEFT[row])
1669 }
1670 }
1671
1672 /// What a block of `side` samples at `(x, y)` may read past its own edges,
1673 /// in a frame of `width` by `height`.
1674 pub(crate) fn of(
1675 side: usize,
1676 x: usize,
1677 y: usize,
1678 width: usize,
1679 height: usize,
1680 fctx: &crate::decode::FrameCtx,
1681 ) -> Self {
1682 Self {
1683 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
1684 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
1685 }
1686 }
1687
1688 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
1689 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
1690 /// block's own width for the row stride and by its own height for the
1691 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
1692 /// unlike the square [`Self::of`] which uses one `side` for everything.
1693 pub(crate) fn of_rect(
1694 bw: usize,
1695 bh: usize,
1696 x: usize,
1697 y: usize,
1698 width: usize,
1699 height: usize,
1700 fctx: &crate::decode::FrameCtx,
1701 ) -> Self {
1702 Self {
1703 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
1704 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
1705 }
1706 }
1707
1708 /// [`Self::of`] for one transform unit of a square block whose transform
1709 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
1710 /// non-zero `row_off`/`col_off`): interior units answer from the block's
1711 /// own geometry, and only a unit on the block's top row (resp. left
1712 /// column) reaches the table -- which is the BLOCK's table read at the
1713 /// BLOCK's position, never a table row for the transform's size. Letting
1714 /// the unit stand in for a block of its own size agrees with libaom for
1715 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
1716 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
1717 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
1718 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
1719 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
1720 /// the transform covering the whole block, luma): everything before the
1721 /// table lookup is that function's own early-exit ladder.
1722 pub(super) fn top_right_rect(
1723 bw: usize,
1724 bh: usize,
1725 x: usize,
1726 y: usize,
1727 fctx: &crate::decode::FrameCtx,
1728 ) -> bool {
1729 let sb_mi: usize = reach_sb_px(fctx) / 4;
1730 let (mi_row, mi_col) = (y / 4, x / 4);
1731 let bw_log2 = (bw / 4).trailing_zeros() as usize;
1732 let bh_log2 = (bh / 4).trailing_zeros() as usize;
1733 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
1734 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
1735 // Top row of the superblock: the top-right pixels are in the (already
1736 // decoded) superblock above.
1737 if blk_row == 0 {
1738 return true;
1739 }
1740 // Rightmost column: they fall in the superblock to the right.
1741 if ((blk_col + 1) << bw_log2) >= sb_mi {
1742 return false;
1743 }
1744 let table = rect_reach_tables(bw, bh).0;
1745 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
1746 }
1747
1748 /// libaom `has_top_right`'s own index arithmetic:
1749 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
1750 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
1751 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
1752 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
1753 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
1754 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
1755 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
1756 pub(super) fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
1757 (blk_row << (5 - bw_log2)) + blk_col
1758 }
1759
1760 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
1761 pub(super) fn bottom_left_rect(
1762 bw: usize,
1763 bh: usize,
1764 x: usize,
1765 y: usize,
1766 fctx: &crate::decode::FrameCtx,
1767 ) -> bool {
1768 let sb_mi: usize = reach_sb_px(fctx) / 4;
1769 let (mi_row, mi_col) = (y / 4, x / 4);
1770 let bw_log2 = (bw / 4).trailing_zeros() as usize;
1771 let bh_log2 = (bh / 4).trailing_zeros() as usize;
1772 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
1773 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
1774 // Leftmost column of the superblock: the bottom-left pixels are in
1775 // the left superblock iff they stay inside its height.
1776 if blk_col == 0 {
1777 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
1778 }
1779 // Bottom row (and not the leftmost column): they fall in the
1780 // superblock below, which is not decoded yet.
1781 if ((blk_row + 1) << bh_log2) >= sb_mi {
1782 return false;
1783 }
1784 let table = rect_reach_tables(bw, bh).1;
1785 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
1786 }
1787
1788 /// Marks every [`Reach::of`] made until the returned guard drops as being
1789 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
1790 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
1791 /// unaffected: libaom's own comment says vertical rectangles keep their
1792 /// non-vert table, which is what [`Reach::of_rect`] already reads.
1793 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
1794 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
1795 /// can count the sub-block work that partition creates (lane-ab16).
1796 pub(crate) fn in_vert_ab() -> bool {
1797 VERT_AB_PARTITION.with(std::cell::Cell::get)
1798 }
1799
1800 pub(crate) fn vert_ab_partition() -> VertAbGuard {
1801 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
1802 }
1803
1804 /// Neither, which is all a mode that reads no further than its own edges
1805 /// needs.
1806 pub(crate) fn none() -> Self {
1807 Self {
1808 above_right: false,
1809 below_left: false,
1810 }
1811 }
1812
1813 /// `has_top_right` for a block whose transform covers it whole: the top
1814 /// row of a superblock reads into the superblock above, which is decoded;
1815 /// the rightmost column would read into the superblock to the right, which
1816 /// is not; and everything between is the table's to answer.
1817 pub(super) fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1818 let (row, col, per_side) = Self::position(side, x, y, fctx);
1819 if row == 0 {
1820 return true;
1821 }
1822 if col + 1 == per_side {
1823 return false;
1824 }
1825 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
1826 // (the clamp corner-cut that used to live here is gone); sides
1827 // 16/32/64 share row 0 exactly as libaom's tables repeat.
1828 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
1829 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
1830 // -- a reach over-estimate (extra above-right reference pixels),
1831 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
1832 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
1833 // NB: named `table_row`, not `row` -- `row` above is the block's
1834 // position inside the superblock and is what the bit index below
1835 // steps by (a merge that shadowed it desynced every block size).
1836 let table_row = Self::table(side);
1837 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
1838 && table_row < HAS_TOP_RIGHT_VERT.len()
1839 {
1840 HAS_TOP_RIGHT_VERT[table_row]
1841 } else {
1842 HAS_TOP_RIGHT[table_row]
1843 };
1844 Self::bit(
1845 table,
1846 (row * Self::table_stride(side) + col) % (table.len() * 8),
1847 )
1848 }
1849
1850 /// `has_bottom_left` for such a block: the leftmost column of a superblock
1851 /// reads into the superblock to its left, which is decoded only as far
1852 /// down as its own bottom; the bottom row would read into the superblock
1853 /// below, which is not decoded at all; and the table answers the rest.
1854 pub(super) fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1855 let (row, col, per_side) = Self::position(side, x, y, fctx);
1856 if col == 0 {
1857 return row * side + side < reach_sb_px(fctx);
1858 }
1859 if row + 1 == per_side {
1860 return false;
1861 }
1862 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
1863 // (the clamp corner-cut that used to live here is gone); sides
1864 // 16/32/64 share row 0 exactly as libaom's tables repeat.
1865 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
1866 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
1867 // -- a reach over-estimate (extra above-right reference pixels),
1868 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
1869 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
1870 // NB: named `table_row`, not `row` -- `row` above is the block's
1871 // position inside the superblock and is what the bit index below
1872 // steps by (a merge that shadowed it desynced every block size).
1873 let table_row = Self::table(side);
1874 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get)
1875 && table_row < HAS_BOTTOM_LEFT_VERT.len()
1876 {
1877 HAS_BOTTOM_LEFT_VERT[table_row]
1878 } else {
1879 HAS_BOTTOM_LEFT[table_row]
1880 };
1881 Self::bit(
1882 table,
1883 (row * Self::table_stride(side) + col) % (table.len() * 8),
1884 )
1885 }
1886
1887 /// Where a block sits inside its superblock, in blocks of its own size,
1888 /// and how many of them a superblock is across.
1889 pub(super) fn position(
1890 side: usize,
1891 x: usize,
1892 y: usize,
1893 fctx: &crate::decode::FrameCtx,
1894 ) -> (usize, usize, usize) {
1895 let sb = reach_sb_px(fctx);
1896 ((y % sb) / side, (x % sb) / side, sb / side)
1897 }
1898
1899 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
1900 /// these tables to its compile-time maximum superblock (128, spec
1901 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
1902 /// size an encode actually uses, so a block's row in the bit index steps
1903 /// by 128 / `side` even though this crate only ever codes a 64
1904 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
1905 /// here instead indexes the wrong bit for every block size but the one
1906 /// where 64 and 128 give the same stride.
1907 pub(super) fn table_stride(side: usize) -> usize {
1908 128 / side
1909 }
1910
1911 /// Which of the three block sizes the encoder codes a table row is for.
1912 pub(super) fn table(side: usize) -> usize {
1913 if side == BLOCK {
1914 1
1915 } else if side == 8 {
1916 2
1917 } else if side == 4 {
1918 3
1919 } else {
1920 0
1921 }
1922 }
1923
1924 /// One bit of a table, counting from the low end of its first byte.
1925 pub(super) fn bit(table: &[u8], index: usize) -> bool {
1926 (table[index / 8] >> (index % 8)) & 1 != 0
1927 }
1928}
1929
1930/// What one symbol costs against a CDF, in bits.
1931/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
1932/// search, the frame header's `allow_warped_motion` and the sequence's
1933/// `enable_warped_motion`, all three together. ON by default since
1934/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
1935/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
1936/// bits -- back off for an A/B on one build.
1937pub(crate) fn warp_on() -> bool {
1938 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1939 crate::envflags::var("EC_AV1_WARP")
1940 .ok()
1941 .map(|v| !matches!(v.as_str(), "0" | "off"))
1942 });
1943 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
1944}
1945
1946/// The smallest LEAF an OBMC candidate is offered for, so the census can
1947/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
1948/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
1949/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
1950///
1951/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
1952/// (12 frames, four quantizers, the standing keep table):
1953///
1954/// | min side | film 1080p | film 2160p | screen |
1955/// |---|---|---|---|
1956/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
1957/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
1958/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
1959/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
1960///
1961/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
1962/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
1963/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
1964/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
1965/// that wins the local RD on five blocks in six and loses ladder bytes is
1966/// the `local-RD-on-references` class again, not a missing footprint.
1967///
1968/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
1969/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
1970/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
1971/// loss on the 1080p film became a 0.3-point win and the other two rows went
1972/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
1973/// of the "local win, ladder loss" it was charged with was the rate weight.
1974/// It still does not meet the keep rule (two down, one flat, both columns).
1975/// The tool stays OFF by default; the upgrade path is the price, not the size
1976/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
1977/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
1978/// 1080p film up, i.e. the same disagreement between the two gates).
1979///
1980/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
1981/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
1982/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
1983/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
1984/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
1985/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
1986/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
1987/// the margin's gain are the same bytes. It stays OFF.
1988///
1989/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
1990/// judgement above was taken when the gate's "film" rows were the `testsrc2`
1991/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
1992/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
1993/// the standing native keep table (`bd_rate_screen_native`):
1994///
1995/// | arm | film A | film B | screen | OBMC fire A/B |
1996/// |---|---|---|---|---|
1997/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
1998/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
1999/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
2000///
2001/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
2002/// only), where the anchors' non-skip area is the known gap:
2003///
2004/// | arm | film B long GOP | wall ours |
2005/// |---|---|---|
2006/// | off (control) | +89.8 / +9.1 | 477.5s |
2007/// | min side 8 | +89.6 / +9.0 | 514.1s |
2008///
2009/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
2010/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
2011/// only at min side 16, which is exactly where film B loses 0.7 on both
2012/// columns. Nothing here meets the keep rule (both films down on both
2013/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
2014/// costs +7.7% wall. OBMC stays OFF at every preset.
2015pub(super) fn obmc_min_side() -> usize {
2016 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2017 *N.get_or_init(|| {
2018 std::env::var("EC_AV1_OBMC_MIN")
2019 .ok()
2020 .and_then(|v| v.parse().ok())
2021 .unwrap_or(8)
2022 })
2023}
2024
2025/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
2026/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
2027/// same frame-CDF price the coefficients of a non-screen frame are estimated
2028/// with, not the static default table.
2029/// The same price for whichever alphabet the writer will really use for this
2030/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
2031/// (`allow_warped_motion` and at least one warp sample), otherwise the
2032/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
2033/// search pay it, so the alphabet cancels out of a comparison and only its
2034/// per-value spread decides.
2035pub(super) fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
2036 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
2037 return 0.0;
2038 };
2039 match warp_alphabet {
2040 true => crate::tile::motion_mode_symbol_bits(row, motion),
2041 false => crate::tile::obmc_symbol_bits(row, motion == 1),
2042 }
2043}
2044
2045/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
2046/// candidate, the header's `allow_warped_motion` and the sequence's
2047/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
2048/// native keep table, against the same build with the knob off:
2049///
2050/// | clip | warp on | off |
2051/// |---|---|---|
2052/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
2053/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
2054/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
2055///
2056/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
2057/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
2058/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
2059/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
2060/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
2061/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
2062/// this is a measured loss, not an inert knob. Same shape as the OBMC
2063/// candidate above it (`obmc_min_side`): a local RD win that does not convert
2064/// into ladder bytes.
2065///
2066/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
2067/// because a tool whose gain is local and whose cost is the rate it adds is
2068/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
2069///
2070/// | clip | warp on | off (both at lambda 0.05) |
2071/// |---|---|---|
2072/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
2073/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
2074/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
2075///
2076/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
2077/// column inside 0.1 everywhere -- which reads as a keep rather than the
2078/// 0.7/0.9 loss it was.
2079///
2080/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
2081/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
2082/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
2083/// ran the conformance shape the lambda lane deferred: every warp stream
2084/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
2085/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
2086/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
2087/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
2088/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
2089/// `allow_warped_motion` and `enable_warped_motion` back off together.
2090///
2091/// The WARPED_CAUSAL prediction of one square single-reference block: the
2092/// decoder's own warp-sample walk (`decode::find_samples` +
2093/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
2094/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
2095/// grid -- never a second implementation of any of the three. `None` when the
2096/// block would code no motion_mode symbol at all, when it has no warp sample
2097/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
2098/// or when the projection is not filter-representable (the decoder would then
2099/// predict translationally, so the mode is pure cost).
2100#[allow(clippy::too_many_arguments)]
2101pub(super) fn warp_prediction(
2102 grid: &MiGrid,
2103 (mi_row, mi_col): (usize, usize),
2104 (mi_rows, mi_cols): (usize, usize),
2105 (x, y): (usize, usize),
2106 side: usize,
2107 mv: (i32, i32),
2108 ref_frame: i8,
2109 ref_planes: [(&[u16], usize, usize, usize); 3],
2110 fctx: &crate::decode::FrameCtx,
2111) -> Option<[Vec<u8>; 3]> {
2112 let n4 = side / 4;
2113 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
2114 return None;
2115 }
2116 let mut samples = crate::decode::find_samples(
2117 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
2118 );
2119 if samples.is_empty() {
2120 return None;
2121 }
2122 if samples.len() > 1 {
2123 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
2124 }
2125 let params = crate::warp::find_projection(
2126 &samples,
2127 side as i32,
2128 side as i32,
2129 mv.1,
2130 mv.0,
2131 mi_row as i32,
2132 mi_col as i32,
2133 )?;
2134 let mut pred = [
2135 vec![0u16; side * side],
2136 vec![0u16; side * side / 4],
2137 vec![0u16; side * side / 4],
2138 ];
2139 // The translational prediction first, exactly as the decoder builds it,
2140 // then the affine one over the planes whose OWN block is at least 8x8
2141 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
2142 // 4x4 chroma stays translational).
2143 for (i, r) in ref_planes.into_iter().enumerate() {
2144 let luma_plane = i == 0;
2145 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
2146 let s = if luma_plane { side } else { side / 2 };
2147 mc::predict(
2148 r.0,
2149 r.1,
2150 r.2,
2151 r.3,
2152 mv_to_q4(px, mv.1, luma_plane),
2153 mv_to_q4(py, mv.0, luma_plane),
2154 s,
2155 s,
2156 &mut pred[i],
2157 fctx,
2158 );
2159 if crate::decode::warp_plane_allowed(s, s) {
2160 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
2161 crate::warp::warp_affine(
2162 &params,
2163 r.0,
2164 r.2 as i32,
2165 r.3 as i32,
2166 r.1 as i32,
2167 &mut pred[i],
2168 px as i32,
2169 py as i32,
2170 cside,
2171 cside,
2172 cside,
2173 sub,
2174 sub,
2175 fctx,
2176 );
2177 }
2178 }
2179 let [py_buf, pu_buf, pv_buf] = pred;
2180 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
2181 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
2182}
2183
2184/// What tile.rs' `write_compound_ref_frames` pays for the pair
2185/// `(ref0, ref1)`, symbol for symbol, each at the context its own
2186/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
2187/// derives from the block's above/left neighbours -- plus the `comp_mode`
2188/// symbol itself at `reference_mode_ctx`.
2189///
2190/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
2191/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
2192/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
2193/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
2194pub(crate) fn compound_ref_bits((ref0, ref1): (i8, i8), stack: &crate::mvstack::MvStack) -> f64 {
2195 use crate::mvstack::{
2196 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
2197 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
2198 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
2199 uni_comp_ref_p1_ctx,
2200 };
2201 let (a, a1) = stack.above_refs;
2202 let (l, l1) = stack.left_refs;
2203 let unidir = is_uni_comp_ref(ref0, ref1);
2204 let comp_mode = symbol_bits(
2205 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
2206 1,
2207 );
2208 let ref_type = symbol_bits(
2209 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
2210 usize::from(!unidir),
2211 );
2212 if unidir {
2213 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
2214 let p0 = symbol_bits(
2215 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
2216 usize::from(both_backward),
2217 );
2218 if both_backward {
2219 return comp_mode + ref_type + p0;
2220 }
2221 let past_last2 = ref1 != LAST2_FRAME;
2222 let p1 = symbol_bits(
2223 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
2224 usize::from(past_last2),
2225 );
2226 let p2 = if past_last2 {
2227 symbol_bits(
2228 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
2229 usize::from(ref1 == GOLDEN_FRAME),
2230 )
2231 } else {
2232 0.0
2233 };
2234 return comp_mode + ref_type + p0 + p1 + p2;
2235 }
2236 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
2237 let fwd = symbol_bits(
2238 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
2239 usize::from(far),
2240 ) + if far {
2241 symbol_bits(
2242 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
2243 usize::from(ref0 == GOLDEN_FRAME),
2244 )
2245 } else {
2246 symbol_bits(
2247 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
2248 usize::from(ref0 == LAST2_FRAME),
2249 )
2250 };
2251 let is_altref = ref1 == ALTREF_FRAME;
2252 let bwd = symbol_bits(
2253 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
2254 usize::from(is_altref),
2255 ) + if is_altref {
2256 0.0
2257 } else {
2258 symbol_bits(
2259 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
2260 usize::from(ref1 == ALTREF2_FRAME),
2261 )
2262 };
2263 comp_mode + ref_type + fwd + bwd
2264}
2265
2266/// What the `skip` symbol costs at the context tile.rs really codes it with
2267/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
2268/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
2269/// exactly the difference between this symbol's two values, so the row it is
2270/// read from moves that decision (class pricer-context-zero, lane-ctx).
2271pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
2272 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
2273 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
2274}
2275
2276/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
2277/// neighbours' intra/inter state, with an out-of-tile side contributing
2278/// nothing, off the same two cells (lane-ctx).
2279pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
2280 let ctx = crate::tile::intra_inter_ctx(
2281 stack.above_nbr.is_some(),
2282 stack.left_nbr.is_some(),
2283 stack.above_nbr.is_some_and(|n| n.is_inter),
2284 stack.left_nbr.is_some_and(|n| n.is_inter),
2285 );
2286 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
2287}
2288
2289/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
2290/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
2291/// context -- zero on a frame that carries no `reference_select` bit, where
2292/// the writer codes no symbol at all.
2293pub(super) fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
2294 if !reference_select() {
2295 return 0.0;
2296 }
2297 symbol_bits(
2298 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
2299 0,
2300 )
2301}
2302
2303/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
2304/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
2305/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
2306/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
2307/// LAST is p1=0,p3=0,p4=0,
2308/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
2309/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
2310/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
2311/// symbols off the wrong CDFs -- which is what made the search believe an
2312/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
2313/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
2314/// paid nothing at all, so compound was overcharged by the whole symbol.
2315pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
2316 use crate::mvstack::{
2317 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
2318 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
2319 single_ref_p5_ctx, single_ref_p6_ctx,
2320 };
2321 let (a, a1) = stack.above_refs;
2322 let (l, l1) = stack.left_refs;
2323 let comp_mode = comp_mode_single_bits(stack);
2324 let backward = ref_frame >= BWDREF_FRAME;
2325 let p1 = symbol_bits(
2326 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
2327 usize::from(backward),
2328 );
2329 if backward {
2330 let is_altref = ref_frame == ALTREF_FRAME;
2331 let p2 = symbol_bits(
2332 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
2333 usize::from(is_altref),
2334 );
2335 return comp_mode
2336 + p1
2337 + p2
2338 + if is_altref {
2339 0.0
2340 } else {
2341 symbol_bits(
2342 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
2343 usize::from(ref_frame == ALTREF2_FRAME),
2344 )
2345 };
2346 }
2347 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
2348 comp_mode
2349 + p1
2350 + symbol_bits(
2351 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
2352 usize::from(far),
2353 )
2354 + if far {
2355 symbol_bits(
2356 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
2357 usize::from(ref_frame == GOLDEN_FRAME),
2358 )
2359 } else {
2360 symbol_bits(
2361 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
2362 usize::from(ref_frame == LAST2_FRAME),
2363 )
2364 }
2365}
2366
2367pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
2368 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
2369 let width = cdf[symbol] - low;
2370 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
2371 // 32769 prices a symbol can carry; the `log2` behind each is computed
2372 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
2373 // profile -- this function is called for every symbol of every candidate
2374 // the RD search prices). Each entry is exactly the expression this used
2375 // to evaluate, so every price is bit-identical.
2376 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
2377 PRICES.get_or_init(|| {
2378 (0..=32768u32)
2379 .map(|w| -(f64::from(w) / 32768.0).log2())
2380 .collect()
2381 })[usize::from(width)]
2382}
2383
2384/// What the tile writer spends to say a block is coded in each of the thirteen
2385/// modes, given the modes of the blocks above it and to its left: the luma mode
2386/// symbol against the CDF those two neighbours pick, the angle delta a
2387/// directional mode carries, and the chroma mode symbol, whose CDF the luma
2388/// mode itself indexes.
2389///
2390/// Without this the search is blind to what a mode costs to name, which is not
2391/// a rounding error: a directional mode on a picture that does not run that way
2392/// is a rate loss the squared error never sees.
2393/// Codes one square of the picture as a single block: searches the luma mode,
2394/// codes both chroma planes DC, and hands back the block and what it cost --
2395/// squared error plus lambda times the bits its symbols spend.
2396/// How many halvings of a `side`-square block's transform the `tx_depth`
2397/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
2398/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
2399pub(super) fn max_tx_depth(side: usize) -> usize {
2400 match side {
2401 8 => 1,
2402 16 | 32 => 2,
2403 _ => 0,
2404 }
2405}
2406
2407/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
2408/// Priced at context row 0 -- the writer picks the real row from its
2409/// neighbours' transform sizes, which the search has no view of; the term is
2410/// the same for every depth of one block either way, so it only shifts the
2411/// depth-0-versus-split margin, never the ordering between two splits.
2412pub(super) fn tx_depth_bits(side: usize, depth: usize) -> f64 {
2413 match side {
2414 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
2415 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
2416 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
2417 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
2418 }
2419}
2420
2421/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
2422/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
2423/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
2424/// (the mode search's own weight); below 1 the split trial is charged less
2425/// for its bits and fires more often.
2426///
2427/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
2428/// `tx_depth` SYMBOL price correct and every film row got worse, because the
2429/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
2430/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
2431/// so what is mis-calibrated is the weight the split's rate is judged under,
2432/// not the price. `EC_AV1_SPLIT_LAMBDA`.
2433pub(crate) fn split_lambda_mult() -> f64 {
2434 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
2435 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
2436 .ok()
2437 .and_then(|v| v.parse().ok())
2438 .unwrap_or(SPLIT_LAMBDA)
2439 });
2440 *M
2441}
2442
2443/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
2444/// the sweep that chose it.
2445pub(super) const SPLIT_LAMBDA: f64 = 1.0;